@prisma/cli-engine 0.0.8 → 0.0.9

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.
@@ -1,8 +1,10 @@
1
- import { i as okVoid, n as notOk, t as CliStructuredError } from "./protocol-C1JQcGl9.js";
1
+ import { a as okVoid, r as notOk, t as CliStructuredError } from "./protocol-D1CRNkhv.js";
2
2
  import { createRequire } from "node:module";
3
3
  import { FlagNotFoundError, buildApplication, buildCommand, buildRouteMap, run, text_en } from "@stricli/core";
4
- import { existsSync, realpathSync } from "node:fs";
4
+ import { randomUUID } from "node:crypto";
5
+ import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from "node:fs";
5
6
  import { dirname, join, resolve } from "node:path";
7
+ import { detect } from "package-manager-detector/detect";
6
8
  import { createColors } from "colorette";
7
9
  import stringWidth from "string-width";
8
10
  import { Readable, Writable } from "node:stream";
@@ -155,6 +157,455 @@ function isChildStatusSettlement(value) {
155
157
  return typeof value === "object" && value !== null && value[CHILD_STATUS] === true;
156
158
  }
157
159
  //#endregion
160
+ //#region src/telemetry/endpoint.ts
161
+ /**
162
+ * Production endpoint pinned to the deployed Prisma Compute backend.
163
+ * Compiled as a build-time constant; not user-configurable.
164
+ */
165
+ const TELEMETRY_BACKEND_URL = "https://cmpbfbsdp09hr3jf7pojjs5qs.ewr.prisma.build";
166
+ /**
167
+ * Path within the backend that accepts telemetry POSTs.
168
+ */
169
+ const TELEMETRY_ENDPOINT_PATH = "/events";
170
+ /**
171
+ * Resolve the full POST URL the sender targets. The
172
+ * `PRISMA_TELEMETRY_ENDPOINT` env var is an integration-testing
173
+ * affordance only — it lets a test suite spin up a mock HTTP server on an
174
+ * ephemeral port and point the spawned sender at it. The override is
175
+ * intentionally undocumented in user-facing material.
176
+ *
177
+ * Fail-open: a malformed override (typo in a dev shell, bad CI config)
178
+ * silently falls back to the production backend rather than throwing,
179
+ * matching the telemetry layer's broader silent-on-failure contract.
180
+ */
181
+ function resolveTelemetryEndpoint(env) {
182
+ const override = env.PRISMA_TELEMETRY_ENDPOINT;
183
+ const base = override !== void 0 && override.length > 0 ? override : TELEMETRY_BACKEND_URL;
184
+ try {
185
+ return new URL(TELEMETRY_ENDPOINT_PATH, base).toString();
186
+ } catch {
187
+ return new URL(TELEMETRY_ENDPOINT_PATH, TELEMETRY_BACKEND_URL).toString();
188
+ }
189
+ }
190
+ //#endregion
191
+ //#region src/telemetry/gating.ts
192
+ /**
193
+ * A `PRISMA_DISABLE_TELEMETRY` value counts as an opt-out only if it
194
+ * parses as a truthy string. The set-but-falsy spellings (`''`, `'0'`,
195
+ * `'false'`) are intentionally treated as not-set so a parent shell that
196
+ * exports the variable to a benign value doesn't accidentally disable
197
+ * telemetry for child processes.
198
+ */
199
+ function isTruthyOptOut(raw) {
200
+ if (raw === void 0) return false;
201
+ const normalised = raw.trim().toLowerCase();
202
+ if (normalised === "") return false;
203
+ if (normalised === "0") return false;
204
+ if (normalised === "false") return false;
205
+ return true;
206
+ }
207
+ /**
208
+ * Pure-function resolution of the gating decision. Same input → same
209
+ * output; no I/O. The caller reads the env, the user config and the CI
210
+ * signal.
211
+ *
212
+ * Decision order:
213
+ * 1. CI (`inCI`) → disabled (`ci`). CI environments never emit,
214
+ * regardless of any stored consent.
215
+ * 2. Env-var override (`PRISMA_DISABLE_TELEMETRY` truthy, or
216
+ * `DO_NOT_TRACK=1`) → disabled (`env-opt-out`), winning over any
217
+ * stored or unset preference.
218
+ * 3. Stored `enableTelemetry === false` → disabled (`stored-opt-out`).
219
+ * 4. Stored `enableTelemetry === true` → enabled (`stored-opt-in`).
220
+ * 5. Stored `enableTelemetry === undefined` (file missing, or field
221
+ * not set) → ENABLED (`default-on`). This is the opt-out default:
222
+ * absence of an explicit choice means telemetry is on. This branch
223
+ * carries the whole opt-out model — do not "fix" it to default-off.
224
+ */
225
+ function resolveGating(inputs) {
226
+ if (inputs.inCI) return {
227
+ enabled: false,
228
+ reason: "ci"
229
+ };
230
+ if (isTruthyOptOut(inputs.env.PRISMA_DISABLE_TELEMETRY) || inputs.env.DO_NOT_TRACK === "1") return {
231
+ enabled: false,
232
+ reason: "env-opt-out"
233
+ };
234
+ if (inputs.config.enableTelemetry === false) return {
235
+ enabled: false,
236
+ reason: "stored-opt-out"
237
+ };
238
+ if (inputs.config.enableTelemetry === true) return {
239
+ enabled: true,
240
+ reason: "stored-opt-in"
241
+ };
242
+ return {
243
+ enabled: true,
244
+ reason: "default-on"
245
+ };
246
+ }
247
+ //#endregion
248
+ //#region src/telemetry/payload.ts
249
+ /**
250
+ * Project the parse-time snapshot into the wire-shape command and flag
251
+ * names. Pure; the snapshot's fields are the only inputs.
252
+ *
253
+ * No flag values, no positionals, no raw argv:
254
+ * - The wire ships `telemetry status`, never the binary name (the
255
+ * snapshot's commandPath already excludes it).
256
+ * - Only flags whose source is `cli` survive — defaulted and
257
+ * env-sourced flags say nothing about what the user typed.
258
+ * - Flag names ship in the user-facing kebab-case spelling the engine
259
+ * recorded; nothing is renamed or filtered per command.
260
+ * - `positionalCount` is accepted and never read.
261
+ */
262
+ function sanitizeCommandSnapshot(snapshot) {
263
+ return {
264
+ command: snapshot.commandPath.join(" "),
265
+ flags: snapshot.flags.flatMap((flag) => flag.source === "cli" ? [flag.name] : [])
266
+ };
267
+ }
268
+ /**
269
+ * The whole payload, from the run's identity plus its snapshot. The
270
+ * snapshot reaches the payload only through
271
+ * {@link sanitizeCommandSnapshot}, so no field of it can arrive by
272
+ * another route. `databaseTarget` is left unset — see its doc-block.
273
+ */
274
+ function composeTelemetryPayload(inputs) {
275
+ return {
276
+ installationId: inputs.installationId,
277
+ version: inputs.version,
278
+ projectRoot: inputs.projectRoot,
279
+ endpoint: inputs.endpoint,
280
+ ...sanitizeCommandSnapshot(inputs.snapshot)
281
+ };
282
+ }
283
+ //#endregion
284
+ //#region src/telemetry/user-config.ts
285
+ const APP_DIR = "prisma";
286
+ const FILE_NAME = "config.json";
287
+ function set(raw) {
288
+ return raw !== void 0 && raw.length > 0 ? raw : void 0;
289
+ }
290
+ /**
291
+ * Resolves the user-level config directory:
292
+ * - Windows: `%APPDATA%\prisma\` (fallback: `%USERPROFILE%\AppData\Roaming\prisma\`).
293
+ * - Unix (incl. macOS): `$XDG_CONFIG_HOME/prisma/` if set, else
294
+ * `$HOME/.config/prisma/` per the XDG Base Directory Specification.
295
+ *
296
+ * XDG is chosen over the macOS-native `~/Library/Preferences/`
297
+ * convention so the path resolution follows an environment variable and
298
+ * matches the documented behaviour on all *nix platforms. The directory
299
+ * is `prisma`, after the binary: the `prisma-next` name it carried is
300
+ * retired with that binary, and nothing reads the old location — no
301
+ * fallback, no migration.
302
+ *
303
+ * EVERY variable comes from the invocation's env — the engine reads no
304
+ * process globals, and `os.homedir()` is one: it answers from the
305
+ * process's own `$HOME`, not the invocation's. An env that names none of
306
+ * them resolves to `undefined`: the preference store is unavailable, and
307
+ * the engine then reads nothing, writes nothing and reports nothing.
308
+ * Failing closed is the only safe direction for a privacy feature —
309
+ * `runtime.env` is `process.env` in production, where `HOME` (or
310
+ * `USERPROFILE`) is always set, so this is a test-shaped state.
311
+ *
312
+ * `process.platform` stays: it does not vary with an invocation and is
313
+ * not modelled on the Runtime.
314
+ */
315
+ function configDir(env) {
316
+ if (process.platform === "win32") {
317
+ const appData = set(env.APPDATA);
318
+ if (appData !== void 0) return join(appData, APP_DIR);
319
+ const userProfile = set(env.USERPROFILE);
320
+ return userProfile === void 0 ? void 0 : join(userProfile, "AppData", "Roaming", APP_DIR);
321
+ }
322
+ const xdg = set(env.XDG_CONFIG_HOME);
323
+ if (xdg !== void 0) return join(xdg, APP_DIR);
324
+ const home = set(env.HOME);
325
+ return home === void 0 ? void 0 : join(home, ".config", APP_DIR);
326
+ }
327
+ /**
328
+ * Path to the user-level config file for this invocation, or `undefined`
329
+ * when the environment says nothing about where the user's config
330
+ * directory is. Callers treat `undefined` as "the preference store is
331
+ * unavailable".
332
+ */
333
+ function userConfigPath(env) {
334
+ const dir = configDir(env);
335
+ return dir === void 0 ? void 0 : join(dir, FILE_NAME);
336
+ }
337
+ /**
338
+ * Reads the user-level config. File-missing, unreadable, or malformed →
339
+ * `{}` (the absence of consent is the same answer in every error mode).
340
+ * Unknown fields from a future client are passed through verbatim.
341
+ */
342
+ function readUserConfig(env) {
343
+ const path = userConfigPath(env);
344
+ if (path === void 0 || !existsSync(path)) return {};
345
+ try {
346
+ const raw = readFileSync(path, "utf-8");
347
+ const parsed = JSON.parse(raw);
348
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
349
+ return {};
350
+ } catch {
351
+ return {};
352
+ }
353
+ }
354
+ /**
355
+ * Merges `partial` into the current config and writes the result
356
+ * atomically (temp file + rename) so a crash mid-write never leaves a
357
+ * half-baked file readable on disk. Unknown fields already on disk are
358
+ * preserved.
359
+ *
360
+ * When `partial.enableTelemetry === true` and no `installationId` is
361
+ * stored yet, generates a v4 random UUID and persists both fields in the
362
+ * same write. An existing `installationId` is never rotated. This is the
363
+ * *explicit-consent* mint path: a `false` answer
364
+ * (`writeUserConfig({ enableTelemetry: false })`) writes no id, and a
365
+ * bare `writeUserConfig({ installationId })` mints nothing extra. The
366
+ * default-on first-send path mints its id separately via
367
+ * {@link ensureInstallationId}, which records no consent answer.
368
+ */
369
+ function writeUserConfig(env, partial) {
370
+ const merged = {
371
+ ...readUserConfig(env),
372
+ ...partial
373
+ };
374
+ if (partial.enableTelemetry === true && merged.installationId === void 0) merged.installationId = randomUUID();
375
+ const path = userConfigPath(env);
376
+ if (path === void 0) throw new Error("@prisma/cli-engine: cannot resolve the user config directory — the environment sets none of XDG_CONFIG_HOME, HOME, APPDATA or USERPROFILE");
377
+ const dir = dirname(path);
378
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
379
+ const tmpPath = `${path}.${process.pid}.tmp`;
380
+ writeFileSync(tmpPath, `${JSON.stringify(merged, null, 2)}\n`, "utf-8");
381
+ renameSync(tmpPath, path);
382
+ }
383
+ /**
384
+ * Returns the stored `installationId`, minting and persisting a fresh v4
385
+ * UUID when none exists yet. Crucially, this persists *only* the id —
386
+ * `enableTelemetry` is left untouched (stays `undefined` on a default-on
387
+ * first run), so no explicit consent the user never gave is recorded.
388
+ *
389
+ * Used by the default-on first-run fire path: the gating resolution has
390
+ * already come back enabled, so this only ever runs when telemetry is on.
391
+ */
392
+ function ensureInstallationId(env) {
393
+ const existing = readUserConfig(env).installationId;
394
+ if (typeof existing === "string" && existing.length > 0) return existing;
395
+ const installationId = randomUUID();
396
+ writeUserConfig(env, { installationId });
397
+ return installationId;
398
+ }
399
+ //#endregion
400
+ //#region src/telemetry/report.ts
401
+ /**
402
+ * The command path the whole telemetry surface is exempt from. Running
403
+ * `telemetry disable` must not report a usage event on its way to
404
+ * disabling, and `telemetry status` must not mint an id while merely
405
+ * reporting state.
406
+ */
407
+ const EXEMPT_COMMAND = "telemetry";
408
+ /**
409
+ * The one-time first-run disclosure. `<name> telemetry disable` is named
410
+ * as the primary, friendliest opt-out, alongside the environment
411
+ * variables. The config file is not named and hand-editing it is not
412
+ * suggested: the preference is machine-edited, which is what the
413
+ * telemetry commands are for, and `telemetry status` reports the path
414
+ * for anyone who wants it.
415
+ */
416
+ function firstRunNotice(cliName, docsUrl) {
417
+ return [
418
+ "Prisma collects anonymous CLI usage data, enabled by default.",
419
+ `What's collected and why: ${docsUrl}.`,
420
+ `Opt out: run "${cliName} telemetry disable", set DO_NOT_TRACK=1 or`,
421
+ "PRISMA_DISABLE_TELEMETRY=1."
422
+ ].join(" ");
423
+ }
424
+ /**
425
+ * The first enabled run on this machine: disclose, then mint. Both are
426
+ * best-effort. A failed write returns no id, which skips the event
427
+ * rather than sending a junk one, and leaves the notice to print again
428
+ * next run — the stored id is what makes it print exactly once.
429
+ */
430
+ function discloseAndMint(inputs) {
431
+ const { host } = inputs;
432
+ try {
433
+ host.stderr.write(`${firstRunNotice(inputs.name, inputs.telemetry.docsUrl)}\n`);
434
+ } catch {}
435
+ try {
436
+ return ensureInstallationId(host.env);
437
+ } catch {
438
+ return;
439
+ }
440
+ }
441
+ /**
442
+ * Report one run, at command start — before the handler, from the
443
+ * parse-time snapshot. Exempt the telemetry command, resolve gating,
444
+ * disclose and mint on a first enabled run, compose, hand the payload to
445
+ * the host's seam. The engine composes; the host spawns.
446
+ *
447
+ * A host with no seam is turned away first, before the config is even
448
+ * read: a CLI that cannot deliver an event must not tell the user it
449
+ * collects data, and must not mint an installation id it has no use
450
+ * for. Declaring telemetry and wiring the seam are two halves of one
451
+ * decision; either one missing means the run reports nothing. An
452
+ * environment that says nothing about where the user's config lives is
453
+ * turned away at the same point and for the same reason.
454
+ *
455
+ * Every failure is swallowed: a malformed stored config, an unwritable
456
+ * config directory and a throwing seam all leave the run's exit code,
457
+ * stdout and stderr exactly as they would have been.
458
+ */
459
+ function reportCommandStart(inputs) {
460
+ try {
461
+ const { host, snapshot } = inputs;
462
+ const deliver = host.spawnTelemetry;
463
+ const configPath = userConfigPath(host.env);
464
+ if (deliver === void 0 || configPath === void 0 || snapshot.commandPath[0] === EXEMPT_COMMAND) return;
465
+ const config = readUserConfig(host.env);
466
+ if (!resolveGating({
467
+ env: host.env,
468
+ config,
469
+ inCI: host.isCI
470
+ }).enabled) return;
471
+ const stored = config.installationId;
472
+ const installationId = typeof stored === "string" && stored.length > 0 ? stored : discloseAndMint(inputs);
473
+ if (installationId === void 0) return;
474
+ deliver(composeTelemetryPayload({
475
+ installationId,
476
+ version: inputs.version,
477
+ projectRoot: host.cwd,
478
+ endpoint: resolveTelemetryEndpoint(host.env),
479
+ snapshot
480
+ }));
481
+ } catch {}
482
+ }
483
+ //#endregion
484
+ //#region src/package-manager.ts
485
+ const MANAGERS = new Set([
486
+ "npm",
487
+ "pnpm",
488
+ "yarn",
489
+ "bun",
490
+ "deno"
491
+ ]);
492
+ function isManager(name) {
493
+ return MANAGERS.has(name);
494
+ }
495
+ /**
496
+ * The manager that invoked this process, read from the environment the
497
+ * host handed the engine. package-manager-detector's own getUserAgent
498
+ * reads process.env directly, which the engine may not do; this is the
499
+ * same parse over Runtime.env.
500
+ */
501
+ function invokingManager(env) {
502
+ const name = env.npm_config_user_agent?.split("/")[0];
503
+ return name !== void 0 && isManager(name) ? name : void 0;
504
+ }
505
+ /**
506
+ * Resolves the manager to drive at `cwd`. In order: the caller's
507
+ * choice, the host's, the project the library detects by walking up
508
+ * from `cwd`, the manager that invoked this process, then npm. Always
509
+ * resolves — "we could not tell" is not an outcome.
510
+ *
511
+ * Two inherited behaviors of package-manager-detector, deliberate and
512
+ * documented so they are not rediscovered as bugs: the walk goes to the
513
+ * filesystem root with no project boundary, so a lockfile above the
514
+ * project counts; and within one directory a package.json
515
+ * `packageManager` field beats a lockfile.
516
+ */
517
+ async function resolvePackageManager(request) {
518
+ const chosen = request.override ?? request.host;
519
+ if (chosen !== void 0) return chosen;
520
+ const detected = await detect({ cwd: request.cwd });
521
+ if (detected !== null && isManager(detected.name)) return detected.name;
522
+ return invokingManager(request.env) ?? "npm";
523
+ }
524
+ /**
525
+ * The characters a POSIX shell hands to a command unchanged. Everything
526
+ * else — whitespace, `|`, `>`, `$`, `*`, quotes — either moves an
527
+ * argument boundary or is syntax the shell acts on, and the line is
528
+ * offered to the user as the command to run by hand: it has to reach
529
+ * their package manager as the argv the engine composed.
530
+ */
531
+ const SHELL_SAFE = /^[A-Za-z0-9_@%+=:,./-]+$/;
532
+ /**
533
+ * Single quotes, because a POSIX shell expands nothing inside them; a
534
+ * single quote in the entry itself has to leave and re-enter them.
535
+ * Known limitation: this is not a Windows rule — cmd.exe treats `'` as
536
+ * an ordinary character and reads `%` and `^` — so a line pasted into
537
+ * cmd.exe or PowerShell is not quoted for those shells.
538
+ */
539
+ function shellQuote(entry) {
540
+ if (SHELL_SAFE.test(entry)) return entry;
541
+ return `'${entry.replaceAll("'", String.raw`'\''`)}'`;
542
+ }
543
+ function spell$1(file, args) {
544
+ return {
545
+ file,
546
+ args,
547
+ line: [file, ...args].map(shellQuote).join(" ")
548
+ };
549
+ }
550
+ function addSpelling(file) {
551
+ return (packages, dev) => spell$1(file, [
552
+ "add",
553
+ ...dev ? ["-D"] : [],
554
+ ...packages
555
+ ]);
556
+ }
557
+ /**
558
+ * Every command line the engine will run, for every manager and both
559
+ * forms. Nothing else in the engine spells a manager command.
560
+ */
561
+ const SPELLINGS = {
562
+ npm: {
563
+ install: addSpelling("npm"),
564
+ run: (packageName, args) => spell$1("npx", [packageName, ...args])
565
+ },
566
+ pnpm: {
567
+ install: addSpelling("pnpm"),
568
+ run: (packageName, args) => spell$1("pnpm", [
569
+ "dlx",
570
+ packageName,
571
+ ...args
572
+ ])
573
+ },
574
+ yarn: {
575
+ install: addSpelling("yarn"),
576
+ run: (packageName, args) => spell$1("yarn", [
577
+ "dlx",
578
+ packageName,
579
+ ...args
580
+ ])
581
+ },
582
+ bun: {
583
+ install: addSpelling("bun"),
584
+ run: (packageName, args) => spell$1("bunx", [packageName, ...args])
585
+ },
586
+ deno: {
587
+ install: (packages, dev) => spell$1("deno", [
588
+ "add",
589
+ ...dev ? ["--dev"] : [],
590
+ ...packages.map((specifier) => `npm:${specifier}`)
591
+ ]),
592
+ run: (packageName, args) => spell$1("deno", [
593
+ "run",
594
+ "-A",
595
+ `npm:${packageName}`,
596
+ ...args
597
+ ])
598
+ }
599
+ };
600
+ /** Adds dependencies to the project. */
601
+ function installCommand(manager, request) {
602
+ return SPELLINGS[manager].install(request.packages, request.dev ?? false);
603
+ }
604
+ /** Runs a package's bin once, without adding a dependency. */
605
+ function runCommand(manager, request) {
606
+ return SPELLINGS[manager].run(request.package, request.args ?? []);
607
+ }
608
+ //#endregion
158
609
  //#region src/presentation.ts
159
610
  const PRESENTED = Symbol.for("prisma.cli-engine.presented");
160
611
  //#endregion
@@ -283,9 +734,9 @@ const SERVICE_TOKEN_ENV_VAR = "PRISMA_SERVICE_TOKEN";
283
734
  const WORKSPACE_ID_ENV_VAR = "PRISMA_WORKSPACE_ID";
284
735
  //#endregion
285
736
  //#region src/execution/debug.ts
286
- const DEBUG_ENV_VAR = "PRISMA_NEXT_DEBUG";
737
+ const DEBUG_ENV_VAR = "PRISMA_DEBUG";
287
738
  /**
288
- * The engine's debug valve: silent unless PRISMA_NEXT_DEBUG=1 in the
739
+ * The engine's debug valve: silent unless PRISMA_DEBUG=1 in the
289
740
  * injected env (never process.env), writing to the injected stderr.
290
741
  * Token material never reaches it.
291
742
  */
@@ -1468,7 +1919,7 @@ function structuredErrorFromDiagnostic(diagnostic) {
1468
1919
  * success it carries the validated section value for ctx.config. */
1469
1920
  async function checkNeeds(def, invocation) {
1470
1921
  const needs = def.needs;
1471
- const failure = checkInteraction(needs, invocation) ?? checkDependencies(needs, invocation);
1922
+ const failure = checkInteraction(needs, invocation) ?? await checkDependencies(needs, invocation);
1472
1923
  if (failure !== void 0) return failure;
1473
1924
  const credentials = await checkCredentials(needs, invocation);
1474
1925
  if (credentials.failure !== void 0) return credentials.failure;
@@ -1495,8 +1946,15 @@ function checkInteraction(needs, invocation) {
1495
1946
  }]
1496
1947
  }));
1497
1948
  }
1498
- function checkDependencies(needs, invocation) {
1499
- for (const specifier of needs.dependencies) if (!dependencyResolvable(specifier, invocation.runtime.cwd)) return needsErrored(missingDependencyError(specifier, invocation.runtime.packageManager));
1949
+ async function checkDependencies(needs, invocation) {
1950
+ const runtime = invocation.runtime;
1951
+ const missing = needs.dependencies.find((specifier) => !dependencyResolvable(specifier, runtime.cwd));
1952
+ if (missing === void 0) return;
1953
+ return needsErrored(missingDependencyError(missing, await resolvePackageManager({
1954
+ cwd: runtime.cwd,
1955
+ env: runtime.env,
1956
+ host: runtime.packageManager
1957
+ })));
1500
1958
  }
1501
1959
  /**
1502
1960
  * The credentials need, single-sourced from the credential manager:
@@ -1618,30 +2076,18 @@ function dependencyResolvable(specifier, cwd) {
1618
2076
  return false;
1619
2077
  }
1620
2078
  }
1621
- function installCommand(packageManager, specifier) {
1622
- switch (packageManager) {
1623
- case "npm": return `npm install ${specifier}`;
1624
- case "pnpm": return `pnpm add ${specifier}`;
1625
- case "yarn": return `yarn add ${specifier}`;
1626
- case "bun": return `bun add ${specifier}`;
1627
- case "unknown": return;
1628
- }
1629
- }
1630
2079
  /** Optional peer dependencies: the engine probes and phrases. */
1631
- function missingDependencyError(specifier, packageManager) {
1632
- const install = installCommand(packageManager, specifier);
2080
+ function missingDependencyError(specifier, manager) {
2081
+ const install = installCommand(manager, { packages: [specifier] }).line;
1633
2082
  return new CliStructuredError("CLI.MISSING_DEPENDENCY", `This command requires the optional dependency '${specifier}', which is not installed in this project.`, {
1634
- nextActions: [install === void 0 ? {
1635
- kind: "user-choice",
1636
- label: `Install '${specifier}' with your package manager, then run the command again.`
1637
- } : {
2083
+ nextActions: [{
1638
2084
  kind: "run-command",
1639
2085
  label: `Install '${specifier}'`,
1640
2086
  command: install
1641
2087
  }],
1642
2088
  meta: {
1643
2089
  specifier,
1644
- ...install === void 0 ? {} : { installCommand: install }
2090
+ installCommand: install
1645
2091
  }
1646
2092
  });
1647
2093
  }
@@ -1663,6 +2109,252 @@ async function announceUrl(invocation, request) {
1663
2109
  }
1664
2110
  }
1665
2111
  //#endregion
2112
+ //#region src/package-manager-errors.ts
2113
+ function why(failure) {
2114
+ if (failure.reason === "runner-unavailable") return "This host wires no package-manager runner, so nothing was run.";
2115
+ return `${failure.manager} exited with code ${failure.exitCode}.`;
2116
+ }
2117
+ /**
2118
+ * The single constructor of CLI.PACKAGE_MANAGER_FAILED — both forms of
2119
+ * ctx.packages, and the host that can run neither.
2120
+ */
2121
+ function packageManagerFailedError(failure) {
2122
+ const installing = failure.form === "install";
2123
+ return new CliStructuredError("CLI.PACKAGE_MANAGER_FAILED", installing ? `Installing packages with ${failure.manager} failed.` : `Running ${failure.package} with ${failure.manager} failed.`, {
2124
+ why: why(failure),
2125
+ nextActions: [{
2126
+ kind: "run-command",
2127
+ label: installing ? "Run the install yourself" : "Run the command yourself",
2128
+ command: failure.command
2129
+ }],
2130
+ meta: {
2131
+ form: failure.form,
2132
+ manager: failure.manager,
2133
+ command: failure.command,
2134
+ exitCode: failure.exitCode,
2135
+ stderrTail: failure.stderrTail,
2136
+ ...failure.reason === void 0 ? {} : { reason: failure.reason }
2137
+ }
2138
+ });
2139
+ }
2140
+ //#endregion
2141
+ //#region src/execution/redaction.ts
2142
+ const REDACTED = "…";
2143
+ /** A candidate runs from a scheme to the end of the authority, which is
2144
+ * the only part of a URL userinfo can be in. Delimiting it is all this
2145
+ * does; `URL` below decides whether the candidate is a URL at all. What
2146
+ * follows the authority is never matched, so a path holding an `@`, and
2147
+ * the punctuation a URL ending a sentence carries, are untouched. */
2148
+ const URL_AUTHORITY = /[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s/?#<>]+/g;
2149
+ const AUTHORITY_MARK = "://";
2150
+ /** `new URL` throws for everything that is not a URL, which is how a
2151
+ * candidate is rejected. */
2152
+ function asUrl(candidate) {
2153
+ try {
2154
+ return new URL(candidate);
2155
+ } catch {
2156
+ return;
2157
+ }
2158
+ }
2159
+ /** `URL` reports whether there is userinfo at all, and the `@` that ends
2160
+ * it is the last one in the authority. Only that span of the original
2161
+ * text is replaced: serialising the parsed URL back out would return a
2162
+ * normalised one — default port dropped, path resolved, password
2163
+ * percent-encoded — and the surrounding output has to survive verbatim. */
2164
+ function redactUserinfo(candidate) {
2165
+ const url = asUrl(candidate);
2166
+ if (url === void 0 || url.username === "" && url.password === "") return candidate;
2167
+ const start = candidate.indexOf(AUTHORITY_MARK) + 3;
2168
+ const end = candidate.lastIndexOf("@");
2169
+ return `${candidate.slice(0, start)}${REDACTED}${candidate.slice(end)}`;
2170
+ }
2171
+ const VALUE = String.raw`"[^"]*"|'[^']*'|\S+`;
2172
+ const ASSIGNMENT = new RegExp(String.raw`\b([A-Za-z_][A-Za-z0-9_]*)=(${VALUE})`, "g");
2173
+ /** A header's value runs to the end of its line, because an auth scheme
2174
+ * and its credential are one value: `Authorization: Bearer eyJ…`. */
2175
+ const HEADER = /\b([A-Za-z][A-Za-z0-9_-]*):[ \t]+[^\n]+/g;
2176
+ /** A flag's value is the word after it. A word starting with a dash is
2177
+ * the next flag rather than this one's value. */
2178
+ const FLAG = new RegExp(String.raw`(--?[A-Za-z][A-Za-z0-9_-]*)[ \t]+(?!-)(?:${VALUE})`, "g");
2179
+ const SECRET_WORDS = new Set([
2180
+ "TOKEN",
2181
+ "KEY",
2182
+ "SECRET",
2183
+ "PASSWORD",
2184
+ "AUTHORIZATION"
2185
+ ]);
2186
+ /** Underscores, hyphens and camelCase humps: `MY_API_TOKEN`,
2187
+ * `--auth-token` and `_authToken` name a secret; `monkey`,
2188
+ * `--keyring` and `tokenizer` do not. */
2189
+ const NAME_WORDS = /[_-]+|(?<=[a-z0-9])(?=[A-Z])/;
2190
+ function namesSecret(name) {
2191
+ return name.split(NAME_WORDS).some((word) => SECRET_WORDS.has(word.toUpperCase()));
2192
+ }
2193
+ /**
2194
+ * Removes the shapes a package manager's output leaks credentials in:
2195
+ * the userinfo of a URL, and the value carried by a name that says it
2196
+ * holds a secret — after an `=`, after a header's colon, or after a
2197
+ * flag. Everything else survives verbatim, so a caller matching an
2198
+ * error code out of stderr still finds it.
2199
+ */
2200
+ function redactSecrets(text) {
2201
+ return text.replace(URL_AUTHORITY, redactUserinfo).replace(ASSIGNMENT, (assignment, name) => namesSecret(name) ? `${name}=${REDACTED}` : assignment).replace(HEADER, (header, name) => namesSecret(name) ? `${name}: ${REDACTED}` : header).replace(FLAG, (flag, name) => namesSecret(name) ? `${name} ${REDACTED}` : flag);
2202
+ }
2203
+ //#endregion
2204
+ //#region src/execution/package-operations.ts
2205
+ /** What the seam reports for a child that never ran, and what a host
2206
+ * with no runner at all reports for the same reason. */
2207
+ const NO_CHILD_EXIT_CODE = 1;
2208
+ function spell(operation, manager) {
2209
+ return operation.form === "install" ? installCommand(manager, {
2210
+ packages: operation.packages,
2211
+ dev: operation.dev
2212
+ }) : runCommand(manager, {
2213
+ package: operation.package,
2214
+ args: operation.args
2215
+ });
2216
+ }
2217
+ function failed(operation, command, outcome) {
2218
+ const spelling = redactSecrets(command.line);
2219
+ return packageManagerFailedError(operation.form === "install" ? {
2220
+ ...outcome,
2221
+ command: spelling,
2222
+ form: "install"
2223
+ } : {
2224
+ ...outcome,
2225
+ command: spelling,
2226
+ form: "run",
2227
+ package: operation.package
2228
+ });
2229
+ }
2230
+ /** Cancellation throws rather than resolving a failure, so an aborted
2231
+ * operation settles the way Ctrl-C settles everywhere else. Asked again
2232
+ * after detection: that await is long enough for the signal to fire,
2233
+ * and an operation nothing spawned must announce nothing. */
2234
+ function stopIfCancelled(signal) {
2235
+ if (signal.aborted) throw signal.reason;
2236
+ }
2237
+ /** The seam hands over chunks as the child writes them; an `output`
2238
+ * event carries one line, so a line split across two chunks waits for
2239
+ * its second half. */
2240
+ function lineAssembler(emit) {
2241
+ let pending = "";
2242
+ const emitLine = (line) => {
2243
+ emit(redactSecrets(line.endsWith("\r") ? line.slice(0, -1) : line));
2244
+ };
2245
+ return {
2246
+ push: (chunk) => {
2247
+ const lines = (pending + chunk).split("\n");
2248
+ pending = lines.pop() ?? "";
2249
+ for (const line of lines) emitLine(line);
2250
+ },
2251
+ flush: () => {
2252
+ if (pending !== "") {
2253
+ emitLine(pending);
2254
+ pending = "";
2255
+ }
2256
+ }
2257
+ };
2258
+ }
2259
+ function outputChannels(invocation, manager) {
2260
+ const assemble = (channel) => lineAssembler((line) => {
2261
+ reportEvent(invocation, {
2262
+ kind: "output",
2263
+ source: manager,
2264
+ channel,
2265
+ line
2266
+ });
2267
+ });
2268
+ const channels = {
2269
+ data: assemble("data"),
2270
+ diagnostic: assemble("diagnostic")
2271
+ };
2272
+ return {
2273
+ push: (channel, chunk) => {
2274
+ channels[channel].push(chunk);
2275
+ },
2276
+ flush: () => {
2277
+ channels.data.flush();
2278
+ channels.diagnostic.flush();
2279
+ }
2280
+ };
2281
+ }
2282
+ async function execute(invocation, operation, placement) {
2283
+ const { runtime, signal } = invocation;
2284
+ stopIfCancelled(signal);
2285
+ const cwd = placement.cwd ?? runtime.cwd;
2286
+ const manager = await resolvePackageManager({
2287
+ cwd,
2288
+ env: runtime.env,
2289
+ override: placement.manager,
2290
+ host: runtime.packageManager
2291
+ });
2292
+ stopIfCancelled(signal);
2293
+ const command = spell(operation, manager);
2294
+ const runner = runtime.runPackageManager;
2295
+ if (runner === void 0) return notOk(failed(operation, command, {
2296
+ manager,
2297
+ exitCode: NO_CHILD_EXIT_CODE,
2298
+ stderrTail: "",
2299
+ reason: "runner-unavailable"
2300
+ }));
2301
+ const output = outputChannels(invocation, manager);
2302
+ const step = redactSecrets(command.line);
2303
+ reportEvent(invocation, {
2304
+ kind: "step-started",
2305
+ step
2306
+ });
2307
+ let result;
2308
+ try {
2309
+ result = await runner({
2310
+ file: command.file,
2311
+ args: command.args,
2312
+ cwd,
2313
+ signal,
2314
+ onOutput: output.push
2315
+ });
2316
+ } finally {
2317
+ output.flush();
2318
+ }
2319
+ reportEvent(invocation, {
2320
+ kind: "step-finished",
2321
+ step,
2322
+ outcome: signal.aborted || result.exitCode !== 0 ? "failed" : "ok"
2323
+ });
2324
+ stopIfCancelled(signal);
2325
+ if (result.exitCode === 0) return okVoid();
2326
+ return notOk(failed(operation, command, {
2327
+ manager,
2328
+ exitCode: result.exitCode,
2329
+ stderrTail: redactSecrets(result.stderr)
2330
+ }));
2331
+ }
2332
+ function makePackageOperations(invocation) {
2333
+ const state = invocation.state;
2334
+ const perform = async (operation, placement) => {
2335
+ if (state.delegatedTerminal !== void 0) throw constructionError(`command '${state.commandId}' called ctx.packages while a child owned the terminal`);
2336
+ if (state.packageOperationRunning) throw constructionError("ctx.packages runs one operation at a time, so two package managers can never write one project at once");
2337
+ state.packageOperationRunning = true;
2338
+ try {
2339
+ return await execute(invocation, operation, placement);
2340
+ } finally {
2341
+ state.packageOperationRunning = false;
2342
+ }
2343
+ };
2344
+ return {
2345
+ install: (request) => perform({
2346
+ form: "install",
2347
+ packages: request.packages,
2348
+ dev: request.dev ?? false
2349
+ }, request),
2350
+ run: (request) => perform({
2351
+ form: "run",
2352
+ package: request.package,
2353
+ args: request.args
2354
+ }, request)
2355
+ };
2356
+ }
2357
+ //#endregion
1666
2358
  //#region src/execution/clack-renderer.ts
1667
2359
  /**
1668
2360
  * Interactive prompt rendering backed by @clack/prompts, driven
@@ -1760,22 +2452,24 @@ function makeLineReader(stdin, invocation) {
1760
2452
  const decoder = new TextDecoder();
1761
2453
  let buffer = "";
1762
2454
  let done = false;
2455
+ const takeBufferedLine = () => {
2456
+ const newline = buffer.indexOf("\n");
2457
+ if (newline === -1) return;
2458
+ const line = buffer.slice(0, newline);
2459
+ buffer = buffer.slice(newline + 1);
2460
+ return line.endsWith("\r") ? line.slice(0, -1) : line;
2461
+ };
2462
+ const takeFinalLine = () => {
2463
+ if (buffer.length === 0) return;
2464
+ const line = buffer;
2465
+ buffer = "";
2466
+ return line;
2467
+ };
1763
2468
  return async () => {
1764
2469
  for (;;) {
1765
- const newline = buffer.indexOf("\n");
1766
- if (newline !== -1) {
1767
- const line = buffer.slice(0, newline);
1768
- buffer = buffer.slice(newline + 1);
1769
- return line.endsWith("\r") ? line.slice(0, -1) : line;
1770
- }
1771
- if (done) {
1772
- if (buffer.length > 0) {
1773
- const line = buffer;
1774
- buffer = "";
1775
- return line;
1776
- }
1777
- return;
1778
- }
2470
+ const buffered = takeBufferedLine();
2471
+ if (buffered !== void 0) return buffered;
2472
+ if (done) return takeFinalLine();
1779
2473
  const next = await iterator.next();
1780
2474
  if (next.done === true) {
1781
2475
  done = true;
@@ -1794,6 +2488,12 @@ function promptUnanswerable(question, state) {
1794
2488
  label: "Run the command from an interactive terminal, or pass a flag that answers the prompt."
1795
2489
  }] });
1796
2490
  }
2491
+ /** What a prompt resolves to when it cannot be shown: its declared
2492
+ * default, or a halt when it has none. */
2493
+ function answerWithoutAsking(question, fallback, state) {
2494
+ if (fallback === void 0) throw promptUnanswerable(question, state);
2495
+ return fallback;
2496
+ }
1797
2497
  function consentUnavailable(question, state, token) {
1798
2498
  const situation = state.yes ? `"${question}" requires explicit consent, which --yes cannot grant.` : `"${question}" requires explicit consent, and the session is not interactive.`;
1799
2499
  if (token === void 0) return new CliStructuredError("CLI.CONSENT_REQUIRED", situation, { nextActions: [{
@@ -1911,6 +2611,28 @@ function makePromptSurface(invocation) {
1911
2611
  if (typeof typed !== "string" || typed.trim() !== token) throw consentTokenMismatch(question, token, String(typed));
1912
2612
  return true;
1913
2613
  };
2614
+ const askSelect = async (question, options, fallback) => {
2615
+ const raw = await ask(question, [
2616
+ `? ${question}`,
2617
+ ...options.map((option) => ` ${option.value === fallback ? "▸" : " "} ${option.value}: ${option.label}`),
2618
+ "> "
2619
+ ].join("\n"));
2620
+ if (typeof raw !== "string") throw promptInvalid(question, String(raw));
2621
+ const answer = raw.trim();
2622
+ if (answer === "") {
2623
+ if (fallback === void 0) throw promptInvalid(question, raw);
2624
+ return fallback;
2625
+ }
2626
+ const match = options.find((option) => option.value === answer);
2627
+ if (match === void 0) throw promptInvalid(question, raw);
2628
+ return match.value;
2629
+ };
2630
+ const askText = async (question, fallback) => {
2631
+ const raw = await ask(question, `? ${question}${fallback === void 0 ? "" : ` (${fallback})`} `);
2632
+ if (typeof raw !== "string") throw promptInvalid(question, String(raw));
2633
+ if (raw === "") return fallback ?? "";
2634
+ return raw;
2635
+ };
1914
2636
  /** A prompt writes to stderr and reads the engine's stdin — the same
1915
2637
  * terminal a live child inherited. Like ctx.present, prompting while
1916
2638
  * a child owns the terminal is a construction error. */
@@ -1920,10 +2642,7 @@ function makePromptSurface(invocation) {
1920
2642
  const surface = {
1921
2643
  confirm: async (question, opts) => {
1922
2644
  const fallback = opts?.default;
1923
- if (state.yes || !state.interactive) {
1924
- if (fallback === void 0) throw promptUnanswerable(question, state);
1925
- return fallback;
1926
- }
2645
+ if (state.yes || !state.interactive) return answerWithoutAsking(question, fallback, state);
1927
2646
  if (useClack()) return renderWithClack(question, (r) => r.confirm(question, fallback));
1928
2647
  let hint = "(y/n)";
1929
2648
  if (fallback === true) hint = "(Y/n)";
@@ -1942,40 +2661,16 @@ function makePromptSurface(invocation) {
1942
2661
  },
1943
2662
  select: async (question, options, opts) => {
1944
2663
  const fallback = opts?.default;
1945
- if (state.yes || !state.interactive) {
1946
- if (fallback === void 0) throw promptUnanswerable(question, state);
1947
- return fallback;
1948
- }
2664
+ if (state.yes || !state.interactive) return answerWithoutAsking(question, fallback, state);
1949
2665
  if (useClack()) return renderWithClack(question, (r) => r.select(question, options, fallback));
1950
- const raw = await ask(question, [
1951
- `? ${question}`,
1952
- ...options.map((option) => ` ${option.value === fallback ? "▸" : " "} ${option.value}: ${option.label}`),
1953
- "> "
1954
- ].join("\n"));
1955
- if (typeof raw !== "string") throw promptInvalid(question, String(raw));
1956
- const answer = raw.trim();
1957
- if (answer === "") {
1958
- if (fallback === void 0) throw promptInvalid(question, raw);
1959
- return fallback;
1960
- }
1961
- const match = options.find((option) => option.value === answer);
1962
- if (match === void 0) throw promptInvalid(question, raw);
1963
- return match.value;
2666
+ return askSelect(question, options, fallback);
1964
2667
  },
1965
2668
  text: async (question, opts) => {
1966
2669
  const fallback = opts?.default;
1967
- if (state.yes || !state.interactive) {
1968
- if (fallback === void 0) throw promptUnanswerable(question, state);
1969
- return fallback;
1970
- }
1971
- if (useClack()) {
1972
- const value = await renderWithClack(question, (r) => r.text(question, opts?.placeholder, fallback));
1973
- return value === "" ? fallback ?? "" : value;
1974
- }
1975
- const raw = await ask(question, `? ${question}${fallback === void 0 ? "" : ` (${fallback})`} `);
1976
- if (typeof raw !== "string") throw promptInvalid(question, String(raw));
1977
- if (raw === "") return fallback ?? "";
1978
- return raw;
2670
+ if (state.yes || !state.interactive) return answerWithoutAsking(question, fallback, state);
2671
+ if (!useClack()) return askText(question, fallback);
2672
+ const value = await renderWithClack(question, (r) => r.text(question, opts?.placeholder, fallback));
2673
+ return value === "" ? fallback ?? "" : value;
1979
2674
  },
1980
2675
  browserWait: async ({ url, message, poll, timeout, interval }) => {
1981
2676
  if (!state.interactive) throw browserWaitUnavailable(message, url);
@@ -2038,6 +2733,7 @@ function makeSpawn(invocation, def) {
2038
2733
  if (!def.maySpawn) throw constructionError(`command '${state.commandId}' called ctx.spawn without declaring maySpawn`);
2039
2734
  if (state.delegatedTerminal !== void 0) throw constructionError(`command '${state.commandId}' called ctx.spawn while a child was still live (one live child per run)`);
2040
2735
  if (state.activePrompts > 0) throw constructionError(`command '${state.commandId}' called ctx.spawn while a prompt owned the terminal`);
2736
+ if (state.packageOperationRunning) throw constructionError(`command '${state.commandId}' called ctx.spawn while a package operation was still running`);
2041
2737
  const spawnChild = invocation.runtime.spawn;
2042
2738
  if (spawnChild === void 0) throw new Error("@prisma/cli-engine: the command declares maySpawn but the Runtime supplies no spawn adapter");
2043
2739
  const terminal = {
@@ -2233,7 +2929,7 @@ function materializePresentation(state, ui, presentations) {
2233
2929
  next: presentations.next?.() ?? []
2234
2930
  };
2235
2931
  }
2236
- function makeContext(invocation, def, config, managesCredentials) {
2932
+ function makeContext(invocation, def, config, capabilities) {
2237
2933
  const state = invocation.state;
2238
2934
  const ui = makeUi(state.colorEnabled, invocation.runtime.stderr);
2239
2935
  const present = (outcome, presentations) => {
@@ -2266,9 +2962,17 @@ function makeContext(invocation, def, config, managesCredentials) {
2266
2962
  signal: invocation.signal,
2267
2963
  cwd: invocation.runtime.cwd,
2268
2964
  env: invocation.runtime.env,
2269
- requireDependency: async (specifier) => dependencyResolvable(specifier, invocation.runtime.cwd) ? okVoid() : notOk(missingDependencyError(specifier, invocation.runtime.packageManager))
2965
+ isCI: invocation.runtime.isCI,
2966
+ requireDependency: async (specifier) => {
2967
+ if (dependencyResolvable(specifier, invocation.runtime.cwd)) return okVoid();
2968
+ return notOk(missingDependencyError(specifier, await resolvePackageManager({
2969
+ cwd: invocation.runtime.cwd,
2970
+ env: invocation.runtime.env,
2971
+ host: invocation.runtime.packageManager
2972
+ })));
2973
+ }
2270
2974
  };
2271
- if (managesCredentials) Object.defineProperty(context, "credentialManager", {
2975
+ if (capabilities.managesCredentials) Object.defineProperty(context, "credentialManager", {
2272
2976
  enumerable: true,
2273
2977
  get() {
2274
2978
  const manager = invocation.runtime.credentialManager;
@@ -2276,6 +2980,10 @@ function makeContext(invocation, def, config, managesCredentials) {
2276
2980
  return manager;
2277
2981
  }
2278
2982
  });
2983
+ if (capabilities.installsPackages) Object.defineProperty(context, "packages", {
2984
+ enumerable: true,
2985
+ value: makePackageOperations(invocation)
2986
+ });
2279
2987
  return context;
2280
2988
  }
2281
2989
  //#endregion
@@ -2303,13 +3011,40 @@ function aliasMap(def) {
2303
3011
  return aliases;
2304
3012
  }
2305
3013
  /**
3014
+ * The key a long token marks. Long tokens match in both the kebab and
3015
+ * camel spellings (the scanner allows kebab-for-camel), and a
3016
+ * `--no-<flag>` token marks its base flag. Values are irrelevant here:
3017
+ * `--name=value` is cut at the `=` before matching.
3018
+ */
3019
+ function longFlagKey(token, declared) {
3020
+ const equals = token.indexOf("=");
3021
+ const raw = token.slice(2, equals === -1 ? void 0 : equals);
3022
+ const exact = camelCase(raw);
3023
+ if (declared.has(exact)) return exact;
3024
+ if (!raw.startsWith("no-")) return;
3025
+ const negated = camelCase(raw.slice(3));
3026
+ return declared.has(negated) ? negated : void 0;
3027
+ }
3028
+ function shortFlagKeys(token, declared, aliases) {
3029
+ const keys = [];
3030
+ for (const char of token.slice(1)) {
3031
+ const key = aliases.get(char);
3032
+ if (key !== void 0 && declared.has(key)) keys.push(key);
3033
+ }
3034
+ return keys;
3035
+ }
3036
+ function tokenFlagKeys(token, declared, aliases) {
3037
+ if (token.startsWith("--")) {
3038
+ const key = longFlagKey(token, declared);
3039
+ return key === void 0 ? [] : [key];
3040
+ }
3041
+ if (token.startsWith("-") && token.length > 1) return shortFlagKeys(token, declared, aliases);
3042
+ return [];
3043
+ }
3044
+ /**
2306
3045
  * The flag keys explicitly present on argv, resolved against the
2307
- * command's declared keys and aliases. Long tokens match in both the
2308
- * kebab and camel spellings (the scanner allows kebab-for-camel), a
2309
- * `--no-<flag>` token marks its base flag, and single-dash tokens are
2310
- * resolved character-by-character through the alias map. Everything
2311
- * after a bare `--` is positional and never consulted. Values are
2312
- * irrelevant here: `--name=value` is cut at the `=` before matching.
3046
+ * command's declared keys and aliases. Everything after a bare `--` is
3047
+ * positional and never consulted.
2313
3048
  */
2314
3049
  function explicitFlagKeys(def, declared, argv) {
2315
3050
  const declaredSet = new Set(declared);
@@ -2317,24 +3052,7 @@ function explicitFlagKeys(def, declared, argv) {
2317
3052
  const explicit = /* @__PURE__ */ new Set();
2318
3053
  for (const token of argv) {
2319
3054
  if (token === "--") break;
2320
- if (token.startsWith("--")) {
2321
- const equals = token.indexOf("=");
2322
- const raw = token.slice(2, equals === -1 ? void 0 : equals);
2323
- const exact = camelCase(raw);
2324
- if (declaredSet.has(exact)) {
2325
- explicit.add(exact);
2326
- continue;
2327
- }
2328
- if (raw.startsWith("no-")) {
2329
- const negated = camelCase(raw.slice(3));
2330
- if (declaredSet.has(negated)) explicit.add(negated);
2331
- }
2332
- continue;
2333
- }
2334
- if (token.startsWith("-") && token.length > 1) for (const char of token.slice(1)) {
2335
- const key = aliases.get(char);
2336
- if (key !== void 0 && declaredSet.has(key)) explicit.add(key);
2337
- }
3055
+ for (const key of tokenFlagKeys(token, declaredSet, aliases)) explicit.add(key);
2338
3056
  }
2339
3057
  return explicit;
2340
3058
  }
@@ -2580,6 +3298,15 @@ function diagnosticOf(error) {
2580
3298
  const { ok: _ok, ...diagnostic } = error.toEnvelope();
2581
3299
  return diagnostic;
2582
3300
  }
3301
+ /** The list is typed, but nothing at runtime has checked it: an error
3302
+ * built by another copy of the engine passes `CliStructuredError.is`
3303
+ * on its name, its code and its `toEnvelope` alone, and a handler's
3304
+ * `notOk` failure is checked by nothing at all. A value that is not a
3305
+ * list settles as no accompanying findings rather than reaching the
3306
+ * human renderer and the json envelope as garbage. */
3307
+ function accompanyingFindings(diagnostics) {
3308
+ return Array.isArray(diagnostics) ? diagnostics : [];
3309
+ }
2583
3310
  function settleErrored(invocation, error, diagnostics = []) {
2584
3311
  const state = invocation.state;
2585
3312
  state.settledExitCode = error.code === "CLI.PROMPT_CANCELLED" ? 3 : 2;
@@ -2587,7 +3314,7 @@ function settleErrored(invocation, error, diagnostics = []) {
2587
3314
  ok: false,
2588
3315
  commandId: state.commandId,
2589
3316
  error: diagnosticOf(error),
2590
- diagnostics,
3317
+ diagnostics: accompanyingFindings(diagnostics),
2591
3318
  nextActions: error.nextActions
2592
3319
  });
2593
3320
  }
@@ -2619,7 +3346,7 @@ function isAbortCause(cause, signal) {
2619
3346
  }
2620
3347
  function settleThrown(invocation, cause) {
2621
3348
  if (isAbortCause(cause, invocation.signal)) settleAborted(invocation);
2622
- else if (CliStructuredError.is(cause)) settleErrored(invocation, cause);
3349
+ else if (CliStructuredError.is(cause)) settleErrored(invocation, cause, cause.diagnostics);
2623
3350
  else settleBug(invocation, cause);
2624
3351
  }
2625
3352
  function settleAborted(invocation) {
@@ -2881,6 +3608,7 @@ var EngineImpl = class {
2881
3608
  delegatedTerminal: void 0,
2882
3609
  lastChild: void 0,
2883
3610
  activePrompts: 0,
3611
+ packageOperationRunning: false,
2884
3612
  deliveredSignal: void 0,
2885
3613
  pendingForceExit: void 0,
2886
3614
  spawnCredential: void 0
@@ -3005,25 +3733,71 @@ var EngineImpl = class {
3005
3733
  hooks.onSettled(summary);
3006
3734
  } catch {}
3007
3735
  }
3736
+ /** The refusals a maySpawn command can hit before anything runs: a
3737
+ * child's terminal output cannot be framed as a json stream, and a
3738
+ * host that mounts the command without a spawn adapter is
3739
+ * misconfigured. Returns whether the run was settled here. */
3740
+ refuseUnspawnable(invocation, entry) {
3741
+ const state = invocation.state;
3742
+ if (!entry.def.maySpawn) return false;
3743
+ if (formatFlagGiven(state.argv) === "json") {
3744
+ state.format = "human";
3745
+ settleErrored(invocation, jsonUnsupportedError(entry.id));
3746
+ return true;
3747
+ }
3748
+ if (invocation.runtime.spawn === void 0) {
3749
+ state.format = "human";
3750
+ settleBug(invocation, /* @__PURE__ */ new Error(`@prisma/cli-engine: command '${entry.id}' declares maySpawn but the Runtime supplies no spawn adapter`));
3751
+ return true;
3752
+ }
3753
+ return false;
3754
+ }
3755
+ /** Every mounted handler settles the same way: an abandoned child
3756
+ * wins over the handler's own outcome, a failure settles errored, a
3757
+ * child-status value settles as that child's exit, and any other
3758
+ * value is the command's own completion. */
3759
+ async settleHandlerOutcome(invocation, entry, runHandler, settleCompletion) {
3760
+ const state = invocation.state;
3761
+ try {
3762
+ const result = await runHandler();
3763
+ if (await this.settleAbandonedChild(invocation, false)) return;
3764
+ state.resolved = true;
3765
+ if (!result.ok) settleErrored(invocation, result.failure, result.failure.diagnostics);
3766
+ else if (isChildStatusSettlement(result.value)) settleChildStatus(invocation, entry.def, result.value);
3767
+ else settleCompletion(result.value);
3768
+ } catch (cause) {
3769
+ if (await this.settleAbandonedChild(invocation, true, cause)) return;
3770
+ state.resolved = true;
3771
+ settleThrown(invocation, cause);
3772
+ }
3773
+ }
3774
+ /** The telemetry fire, at command start: once per run, from the
3775
+ * parse-time snapshot, before the handler and before any command
3776
+ * output. A CLI that declared no telemetry block reports nothing —
3777
+ * no config read, no disclosure, no mint, no seam call. Runs that
3778
+ * never mount a command never reach here and so never report. */
3779
+ fireTelemetry(invocation) {
3780
+ const { snapshot } = invocation.state;
3781
+ if (this.spec.telemetry === void 0 || snapshot === void 0) return;
3782
+ reportCommandStart({
3783
+ host: invocation.runtime,
3784
+ telemetry: this.spec.telemetry,
3785
+ name: this.spec.name,
3786
+ version: this.spec.version,
3787
+ snapshot
3788
+ });
3789
+ }
3008
3790
  async executeMounted(invocation, entry, rawFlags, values) {
3009
3791
  const state = invocation.state;
3010
3792
  state.commandId = entry.id;
3011
3793
  state.docsBaseUrl = entry.docsBaseUrl;
3012
3794
  state.snapshot = buildCommandSnapshot(entry.id, entry.def, state.argv, values);
3795
+ this.fireTelemetry(invocation);
3013
3796
  if (entry.def.kind === "server-command") {
3014
3797
  await this.executeServer(invocation, entry, rawFlags);
3015
3798
  return;
3016
3799
  }
3017
- if (entry.def.maySpawn && formatFlagGiven(state.argv) === "json") {
3018
- state.format = "human";
3019
- settleErrored(invocation, jsonUnsupportedError(entry.id));
3020
- return;
3021
- }
3022
- if (entry.def.maySpawn && invocation.runtime.spawn === void 0) {
3023
- state.format = "human";
3024
- settleBug(invocation, /* @__PURE__ */ new Error(`@prisma/cli-engine: command '${entry.id}' declares maySpawn but the Runtime supplies no spawn adapter`));
3025
- return;
3026
- }
3800
+ if (this.refuseUnspawnable(invocation, entry)) return;
3027
3801
  let needsOutcome;
3028
3802
  try {
3029
3803
  applySharedFlags(state, rawFlags, invocation.runtime);
@@ -3047,34 +3821,12 @@ var EngineImpl = class {
3047
3821
  flags: declaredFlags(entry.def, rawFlags),
3048
3822
  positionals: distributePositionals(entry.def, values)
3049
3823
  };
3050
- const ctx = makeContext(invocation, entry.def, needsOutcome.config, entry.def.kind === "result-command" && entry.def.managesCredentials);
3824
+ const ctx = makeContext(invocation, entry.def, needsOutcome.config, declaredCapabilities(entry.def));
3051
3825
  if (entry.def.kind === "session-command") {
3052
- try {
3053
- const result = await handler(args, ctx);
3054
- if (await this.settleAbandonedChild(invocation, false)) return;
3055
- state.resolved = true;
3056
- if (!result.ok) settleErrored(invocation, result.failure);
3057
- else if (isChildStatusSettlement(result.value)) settleChildStatus(invocation, entry.def, result.value);
3058
- else settleSessionCompleted(invocation);
3059
- } catch (cause) {
3060
- if (await this.settleAbandonedChild(invocation, true, cause)) return;
3061
- state.resolved = true;
3062
- settleThrown(invocation, cause);
3063
- }
3826
+ await this.settleHandlerOutcome(invocation, entry, () => handler(args, ctx), () => settleSessionCompleted(invocation));
3064
3827
  return;
3065
3828
  }
3066
- try {
3067
- const result = await handler(args, ctx);
3068
- if (await this.settleAbandonedChild(invocation, false)) return;
3069
- state.resolved = true;
3070
- if (!result.ok) settleErrored(invocation, result.failure);
3071
- else if (isChildStatusSettlement(result.value)) settleChildStatus(invocation, entry.def, result.value);
3072
- else settleCompleted(invocation, entry.def, result.value);
3073
- } catch (cause) {
3074
- if (await this.settleAbandonedChild(invocation, true, cause)) return;
3075
- state.resolved = true;
3076
- settleThrown(invocation, cause);
3077
- }
3829
+ await this.settleHandlerOutcome(invocation, entry, () => handler(args, ctx), (presented) => settleCompleted(invocation, entry.def, presented));
3078
3830
  }
3079
3831
  /** The handler resolved or threw with its child still live. The
3080
3832
  * engine ends that child — SIGTERM, the ruled grace period, then
@@ -3168,6 +3920,16 @@ function jsonUnsupportedError(commandId) {
3168
3920
  }]
3169
3921
  });
3170
3922
  }
3923
+ function declaredCapabilities(def) {
3924
+ if (def.kind !== "result-command") return {
3925
+ managesCredentials: false,
3926
+ installsPackages: false
3927
+ };
3928
+ return {
3929
+ managesCredentials: def.managesCredentials,
3930
+ installsPackages: def.installsPackages
3931
+ };
3932
+ }
3171
3933
  function declaredFlags(def, rawFlags) {
3172
3934
  const flags = {};
3173
3935
  for (const key of Object.keys(def.args.flags)) flags[key] = rawFlags[key];
@@ -3252,4 +4014,4 @@ function claimedIdentity(token) {
3252
4014
  };
3253
4015
  }
3254
4016
  //#endregion
3255
- export { PRESENTED as _, CONFIG_FILE_NAME as a, positional as b, PRISMA_CONFIG_VERSION as c, authServiceError as d, credentialRejectedError as f, noSessionForWorkspaceError as g, emptyServiceTokenError as h, buildEngine as i, SERVICE_TOKEN_ENV_VAR as l, credentialsRequiredError as m, claimedIdentity as n, defineConfig as o, credentialWorkspaceMismatchError as p, credentialWorkspaceId as r, loadConfig as s, claimedExpiresAt as t, WORKSPACE_ID_ENV_VAR as u, exitWithChildStatus as v, flag as y };
4017
+ export { flag as C, exitWithChildStatus as S, PRESENTED as _, CONFIG_FILE_NAME as a, writeUserConfig as b, PRISMA_CONFIG_VERSION as c, authServiceError as d, credentialRejectedError as f, noSessionForWorkspaceError as g, emptyServiceTokenError as h, buildEngine as i, SERVICE_TOKEN_ENV_VAR as l, credentialsRequiredError as m, claimedIdentity as n, defineConfig as o, credentialWorkspaceMismatchError as p, credentialWorkspaceId as r, loadConfig as s, claimedExpiresAt as t, WORKSPACE_ID_ENV_VAR as u, readUserConfig as v, positional as w, resolveGating as x, userConfigPath as y };