@prisma/cli-engine 0.0.8 → 0.1.0
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/dist/index.d.ts +66 -6
- package/dist/index.js +167 -3
- package/dist/{protocol-C1JQcGl9.js → protocol-D1CRNkhv.js} +25 -4
- package/dist/{protocol-CpZLdxML.d.ts → protocol-YjqPCCOG.d.ts} +23 -3
- package/dist/protocol.d.ts +2 -2
- package/dist/protocol.js +2 -2
- package/dist/{run-summary-CVHIRjTS.d.ts → report-DID_e0si.d.ts} +412 -222
- package/dist/testing.d.ts +32 -2
- package/dist/testing.js +54 -23
- package/dist/{token-claims-_AF7BYbq.js → token-claims-CJNNCGkL.js} +1486 -180
- package/package.json +11 -9
|
@@ -1,8 +1,11 @@
|
|
|
1
|
-
import {
|
|
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
|
|
4
|
+
import vendors from "ci-info/vendors.json" with { type: "json" };
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
6
|
+
import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from "node:fs";
|
|
5
7
|
import { dirname, join, resolve } from "node:path";
|
|
8
|
+
import { detect } from "package-manager-detector/detect";
|
|
6
9
|
import { createColors } from "colorette";
|
|
7
10
|
import stringWidth from "string-width";
|
|
8
11
|
import { Readable, Writable } from "node:stream";
|
|
@@ -54,6 +57,17 @@ const flag = {
|
|
|
54
57
|
...spec
|
|
55
58
|
});
|
|
56
59
|
},
|
|
60
|
+
/**
|
|
61
|
+
* A boolean the user can leave unsaid: `--flag`, `--no-flag`, or
|
|
62
|
+
* neither, which arrives as undefined. Use it when absence means
|
|
63
|
+
* something of its own — "ask me" rather than "no".
|
|
64
|
+
*/
|
|
65
|
+
optionalBoolean(spec) {
|
|
66
|
+
return brandFlag({
|
|
67
|
+
type: "optionalBoolean",
|
|
68
|
+
...spec
|
|
69
|
+
});
|
|
70
|
+
},
|
|
57
71
|
enum(spec) {
|
|
58
72
|
return brandFlag({
|
|
59
73
|
type: "enum",
|
|
@@ -155,6 +169,516 @@ function isChildStatusSettlement(value) {
|
|
|
155
169
|
return typeof value === "object" && value !== null && value[CHILD_STATUS] === true;
|
|
156
170
|
}
|
|
157
171
|
//#endregion
|
|
172
|
+
//#region src/ci.ts
|
|
173
|
+
/**
|
|
174
|
+
* ci-info's own list of CI providers, read from the installed package
|
|
175
|
+
* rather than copied here, so upgrading ci-info is what teaches the
|
|
176
|
+
* engine a new provider. Its `isCI` export cannot be used instead: that
|
|
177
|
+
* module evaluates against the real `process.env` the moment it is
|
|
178
|
+
* imported, and the engine may only read the environment its host
|
|
179
|
+
* injected.
|
|
180
|
+
*/
|
|
181
|
+
const VENDORS = vendors;
|
|
182
|
+
/**
|
|
183
|
+
* The variables ci-info checks outside the vendor table, catching CI
|
|
184
|
+
* systems that set a conventional variable but have no table entry.
|
|
185
|
+
* These are cross-vendor conventions rather than per-vendor facts,
|
|
186
|
+
* which is why this list holds still while the table grows.
|
|
187
|
+
*/
|
|
188
|
+
const CONVENTIONAL_CI_VARS = [
|
|
189
|
+
"BUILD_ID",
|
|
190
|
+
"BUILD_NUMBER",
|
|
191
|
+
"CI",
|
|
192
|
+
"CI_APP_ID",
|
|
193
|
+
"CI_BUILD_ID",
|
|
194
|
+
"CI_BUILD_NUMBER",
|
|
195
|
+
"CI_NAME",
|
|
196
|
+
"CONTINUOUS_INTEGRATION",
|
|
197
|
+
"RUN_ID"
|
|
198
|
+
];
|
|
199
|
+
function isSet(value) {
|
|
200
|
+
return value !== void 0 && value !== "";
|
|
201
|
+
}
|
|
202
|
+
function checkMatches(check, env) {
|
|
203
|
+
if (typeof check === "string") return isSet(env[check]);
|
|
204
|
+
const { env: variable, includes, any } = check;
|
|
205
|
+
if (typeof variable === "string" && typeof includes === "string") return env[variable]?.includes(includes) === true;
|
|
206
|
+
if (Array.isArray(any)) return any.some((name) => isSet(env[String(name)]));
|
|
207
|
+
return Object.entries(check).every(([name, value]) => env[name] === value);
|
|
208
|
+
}
|
|
209
|
+
function vendorMatches(vendor, env) {
|
|
210
|
+
return (Array.isArray(vendor.env) ? vendor.env : [vendor.env]).every((check) => checkMatches(check, env));
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Whether this environment is a CI environment, by ci-info's rules
|
|
214
|
+
* applied to the environment the host injected rather than to
|
|
215
|
+
* `process.env`. `CI=false` is an explicit denial that stops every
|
|
216
|
+
* other check, exactly as ci-info treats it.
|
|
217
|
+
*/
|
|
218
|
+
function detectCI(env) {
|
|
219
|
+
if (env.CI === "false") return false;
|
|
220
|
+
if (CONVENTIONAL_CI_VARS.some((name) => isSet(env[name]))) return true;
|
|
221
|
+
return VENDORS.some((vendor) => vendorMatches(vendor, env));
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* The engine's one answer to "is this run in CI", read by telemetry
|
|
225
|
+
* gating, `ctx.isCI` and the default interactivity decision. A host
|
|
226
|
+
* that says nothing gets detection, so forgetting to answer cannot turn
|
|
227
|
+
* a CI run into a reporting one.
|
|
228
|
+
*/
|
|
229
|
+
function resolveIsCI(host) {
|
|
230
|
+
return host.isCIOverride ?? detectCI(host.env);
|
|
231
|
+
}
|
|
232
|
+
//#endregion
|
|
233
|
+
//#region src/telemetry/endpoint.ts
|
|
234
|
+
/**
|
|
235
|
+
* Production endpoint pinned to the deployed Prisma Compute backend.
|
|
236
|
+
* Compiled as a build-time constant; not user-configurable.
|
|
237
|
+
*/
|
|
238
|
+
const TELEMETRY_BACKEND_URL = "https://cmpbfbsdp09hr3jf7pojjs5qs.ewr.prisma.build";
|
|
239
|
+
/**
|
|
240
|
+
* Path within the backend that accepts telemetry POSTs.
|
|
241
|
+
*/
|
|
242
|
+
const TELEMETRY_ENDPOINT_PATH = "/events";
|
|
243
|
+
/**
|
|
244
|
+
* Resolve the full POST URL the sender targets. The
|
|
245
|
+
* `PRISMA_TELEMETRY_ENDPOINT` env var is an integration-testing
|
|
246
|
+
* affordance only — it lets a test suite spin up a mock HTTP server on an
|
|
247
|
+
* ephemeral port and point the spawned sender at it. The override is
|
|
248
|
+
* intentionally undocumented in user-facing material.
|
|
249
|
+
*
|
|
250
|
+
* Fail-open: a malformed override (typo in a dev shell, bad CI config)
|
|
251
|
+
* silently falls back to the production backend rather than throwing,
|
|
252
|
+
* matching the telemetry layer's broader silent-on-failure contract.
|
|
253
|
+
*/
|
|
254
|
+
function resolveTelemetryEndpoint(env) {
|
|
255
|
+
const override = env.PRISMA_TELEMETRY_ENDPOINT;
|
|
256
|
+
const base = override !== void 0 && override.length > 0 ? override : TELEMETRY_BACKEND_URL;
|
|
257
|
+
try {
|
|
258
|
+
return new URL(TELEMETRY_ENDPOINT_PATH, base).toString();
|
|
259
|
+
} catch {
|
|
260
|
+
return new URL(TELEMETRY_ENDPOINT_PATH, TELEMETRY_BACKEND_URL).toString();
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
//#endregion
|
|
264
|
+
//#region src/telemetry/gating.ts
|
|
265
|
+
/**
|
|
266
|
+
* A `PRISMA_DISABLE_TELEMETRY` value counts as an opt-out only if it
|
|
267
|
+
* parses as a truthy string. The set-but-falsy spellings (`''`, `'0'`,
|
|
268
|
+
* `'false'`) are intentionally treated as not-set so a parent shell that
|
|
269
|
+
* exports the variable to a benign value doesn't accidentally disable
|
|
270
|
+
* telemetry for child processes.
|
|
271
|
+
*/
|
|
272
|
+
function isTruthyOptOut(raw) {
|
|
273
|
+
if (raw === void 0) return false;
|
|
274
|
+
const normalised = raw.trim().toLowerCase();
|
|
275
|
+
if (normalised === "") return false;
|
|
276
|
+
if (normalised === "0") return false;
|
|
277
|
+
if (normalised === "false") return false;
|
|
278
|
+
return true;
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* Pure-function resolution of the gating decision. Same input → same
|
|
282
|
+
* output; no I/O. The caller reads the env, the user config and the CI
|
|
283
|
+
* signal.
|
|
284
|
+
*
|
|
285
|
+
* Decision order:
|
|
286
|
+
* 1. CI (`inCI`) → disabled (`ci`). CI environments never emit,
|
|
287
|
+
* regardless of any stored consent.
|
|
288
|
+
* 2. Env-var override (`PRISMA_DISABLE_TELEMETRY` truthy, or
|
|
289
|
+
* `DO_NOT_TRACK=1`) → disabled (`env-opt-out`), winning over any
|
|
290
|
+
* stored or unset preference.
|
|
291
|
+
* 3. Stored `enableTelemetry === false` → disabled (`stored-opt-out`).
|
|
292
|
+
* 4. Stored `enableTelemetry === true` → enabled (`stored-opt-in`).
|
|
293
|
+
* 5. Stored `enableTelemetry === undefined` (file missing, or field
|
|
294
|
+
* not set) → ENABLED (`default-on`). This is the opt-out default:
|
|
295
|
+
* absence of an explicit choice means telemetry is on. This branch
|
|
296
|
+
* carries the whole opt-out model — do not "fix" it to default-off.
|
|
297
|
+
*/
|
|
298
|
+
function resolveGating(inputs) {
|
|
299
|
+
if (inputs.inCI) return {
|
|
300
|
+
enabled: false,
|
|
301
|
+
reason: "ci"
|
|
302
|
+
};
|
|
303
|
+
if (isTruthyOptOut(inputs.env.PRISMA_DISABLE_TELEMETRY) || inputs.env.DO_NOT_TRACK === "1") return {
|
|
304
|
+
enabled: false,
|
|
305
|
+
reason: "env-opt-out"
|
|
306
|
+
};
|
|
307
|
+
if (inputs.config.enableTelemetry === false) return {
|
|
308
|
+
enabled: false,
|
|
309
|
+
reason: "stored-opt-out"
|
|
310
|
+
};
|
|
311
|
+
if (inputs.config.enableTelemetry === true) return {
|
|
312
|
+
enabled: true,
|
|
313
|
+
reason: "stored-opt-in"
|
|
314
|
+
};
|
|
315
|
+
return {
|
|
316
|
+
enabled: true,
|
|
317
|
+
reason: "default-on"
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
//#endregion
|
|
321
|
+
//#region src/telemetry/payload.ts
|
|
322
|
+
/**
|
|
323
|
+
* Project the parse-time snapshot into the wire-shape command and flag
|
|
324
|
+
* names. Pure; the snapshot's fields are the only inputs.
|
|
325
|
+
*
|
|
326
|
+
* No flag values, no positionals, no raw argv:
|
|
327
|
+
* - The wire ships `telemetry status`, never the binary name (the
|
|
328
|
+
* snapshot's commandPath already excludes it).
|
|
329
|
+
* - Only flags whose source is `cli` survive — defaulted and
|
|
330
|
+
* env-sourced flags say nothing about what the user typed.
|
|
331
|
+
* - Flag names ship in the user-facing kebab-case spelling the engine
|
|
332
|
+
* recorded; nothing is renamed or filtered per command.
|
|
333
|
+
* - `positionalCount` is accepted and never read.
|
|
334
|
+
*/
|
|
335
|
+
function sanitizeCommandSnapshot(snapshot) {
|
|
336
|
+
return {
|
|
337
|
+
command: snapshot.commandPath.join(" "),
|
|
338
|
+
flags: snapshot.flags.flatMap((flag) => flag.source === "cli" ? [flag.name] : [])
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* The whole payload, from the run's identity plus its snapshot. The
|
|
343
|
+
* snapshot reaches the payload only through
|
|
344
|
+
* {@link sanitizeCommandSnapshot}, so no field of it can arrive by
|
|
345
|
+
* another route. `databaseTarget` is left unset — see its doc-block.
|
|
346
|
+
*/
|
|
347
|
+
function composeTelemetryPayload(inputs) {
|
|
348
|
+
return {
|
|
349
|
+
installationId: inputs.installationId,
|
|
350
|
+
version: inputs.version,
|
|
351
|
+
projectRoot: inputs.projectRoot,
|
|
352
|
+
endpoint: inputs.endpoint,
|
|
353
|
+
...sanitizeCommandSnapshot(inputs.snapshot)
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
//#endregion
|
|
357
|
+
//#region src/telemetry/user-config.ts
|
|
358
|
+
const APP_DIR = "prisma";
|
|
359
|
+
const FILE_NAME = "config.json";
|
|
360
|
+
function set(raw) {
|
|
361
|
+
return raw !== void 0 && raw.length > 0 ? raw : void 0;
|
|
362
|
+
}
|
|
363
|
+
/**
|
|
364
|
+
* Resolves the user-level config directory:
|
|
365
|
+
* - Windows: `%APPDATA%\prisma\` (fallback: `%USERPROFILE%\AppData\Roaming\prisma\`).
|
|
366
|
+
* - Unix (incl. macOS): `$XDG_CONFIG_HOME/prisma/` if set, else
|
|
367
|
+
* `$HOME/.config/prisma/` per the XDG Base Directory Specification.
|
|
368
|
+
*
|
|
369
|
+
* XDG is chosen over the macOS-native `~/Library/Preferences/`
|
|
370
|
+
* convention so the path resolution follows an environment variable and
|
|
371
|
+
* matches the documented behaviour on all *nix platforms. The directory
|
|
372
|
+
* is `prisma`, after the binary: the `prisma-next` name it carried is
|
|
373
|
+
* retired with that binary, and nothing reads the old location — no
|
|
374
|
+
* fallback, no migration.
|
|
375
|
+
*
|
|
376
|
+
* EVERY variable comes from the invocation's env — the engine reads no
|
|
377
|
+
* process globals, and `os.homedir()` is one: it answers from the
|
|
378
|
+
* process's own `$HOME`, not the invocation's. An env that names none of
|
|
379
|
+
* them resolves to `undefined`: the preference store is unavailable, and
|
|
380
|
+
* the engine then reads nothing, writes nothing and reports nothing.
|
|
381
|
+
* Failing closed is the only safe direction for a privacy feature —
|
|
382
|
+
* `runtime.env` is `process.env` in production, where `HOME` (or
|
|
383
|
+
* `USERPROFILE`) is always set, so this is a test-shaped state.
|
|
384
|
+
*
|
|
385
|
+
* `process.platform` stays: it does not vary with an invocation and is
|
|
386
|
+
* not modelled on the Runtime.
|
|
387
|
+
*/
|
|
388
|
+
function configDir(env) {
|
|
389
|
+
if (process.platform === "win32") {
|
|
390
|
+
const appData = set(env.APPDATA);
|
|
391
|
+
if (appData !== void 0) return join(appData, APP_DIR);
|
|
392
|
+
const userProfile = set(env.USERPROFILE);
|
|
393
|
+
return userProfile === void 0 ? void 0 : join(userProfile, "AppData", "Roaming", APP_DIR);
|
|
394
|
+
}
|
|
395
|
+
const xdg = set(env.XDG_CONFIG_HOME);
|
|
396
|
+
if (xdg !== void 0) return join(xdg, APP_DIR);
|
|
397
|
+
const home = set(env.HOME);
|
|
398
|
+
return home === void 0 ? void 0 : join(home, ".config", APP_DIR);
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* Path to the user-level config file for this invocation, or `undefined`
|
|
402
|
+
* when the environment says nothing about where the user's config
|
|
403
|
+
* directory is. Callers treat `undefined` as "the preference store is
|
|
404
|
+
* unavailable".
|
|
405
|
+
*/
|
|
406
|
+
function userConfigPath(env) {
|
|
407
|
+
const dir = configDir(env);
|
|
408
|
+
return dir === void 0 ? void 0 : join(dir, FILE_NAME);
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Reads the user-level config. File-missing, unreadable, or malformed →
|
|
412
|
+
* `{}` (the absence of consent is the same answer in every error mode).
|
|
413
|
+
* Unknown fields from a future client are passed through verbatim.
|
|
414
|
+
*/
|
|
415
|
+
function readUserConfig(env) {
|
|
416
|
+
const path = userConfigPath(env);
|
|
417
|
+
if (path === void 0 || !existsSync(path)) return {};
|
|
418
|
+
try {
|
|
419
|
+
const raw = readFileSync(path, "utf-8");
|
|
420
|
+
const parsed = JSON.parse(raw);
|
|
421
|
+
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
|
|
422
|
+
return {};
|
|
423
|
+
} catch {
|
|
424
|
+
return {};
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
428
|
+
* Merges `partial` into the current config and writes the result
|
|
429
|
+
* atomically (temp file + rename) so a crash mid-write never leaves a
|
|
430
|
+
* half-baked file readable on disk. Unknown fields already on disk are
|
|
431
|
+
* preserved.
|
|
432
|
+
*
|
|
433
|
+
* When `partial.enableTelemetry === true` and no `installationId` is
|
|
434
|
+
* stored yet, generates a v4 random UUID and persists both fields in the
|
|
435
|
+
* same write. An existing `installationId` is never rotated. This is the
|
|
436
|
+
* *explicit-consent* mint path: a `false` answer
|
|
437
|
+
* (`writeUserConfig({ enableTelemetry: false })`) writes no id, and a
|
|
438
|
+
* bare `writeUserConfig({ installationId })` mints nothing extra. The
|
|
439
|
+
* default-on first-send path mints its id separately via
|
|
440
|
+
* {@link ensureInstallationId}, which records no consent answer.
|
|
441
|
+
*/
|
|
442
|
+
function writeUserConfig(env, partial) {
|
|
443
|
+
const merged = {
|
|
444
|
+
...readUserConfig(env),
|
|
445
|
+
...partial
|
|
446
|
+
};
|
|
447
|
+
if (partial.enableTelemetry === true && merged.installationId === void 0) merged.installationId = randomUUID();
|
|
448
|
+
const path = userConfigPath(env);
|
|
449
|
+
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");
|
|
450
|
+
const dir = dirname(path);
|
|
451
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
452
|
+
const tmpPath = `${path}.${process.pid}.tmp`;
|
|
453
|
+
writeFileSync(tmpPath, `${JSON.stringify(merged, null, 2)}\n`, "utf-8");
|
|
454
|
+
renameSync(tmpPath, path);
|
|
455
|
+
}
|
|
456
|
+
/**
|
|
457
|
+
* Returns the stored `installationId`, minting and persisting a fresh v4
|
|
458
|
+
* UUID when none exists yet. Crucially, this persists *only* the id —
|
|
459
|
+
* `enableTelemetry` is left untouched (stays `undefined` on a default-on
|
|
460
|
+
* first run), so no explicit consent the user never gave is recorded.
|
|
461
|
+
*
|
|
462
|
+
* Used by the default-on first-run fire path: the gating resolution has
|
|
463
|
+
* already come back enabled, so this only ever runs when telemetry is on.
|
|
464
|
+
*/
|
|
465
|
+
function ensureInstallationId(env) {
|
|
466
|
+
const existing = readUserConfig(env).installationId;
|
|
467
|
+
if (typeof existing === "string" && existing.length > 0) return existing;
|
|
468
|
+
const installationId = randomUUID();
|
|
469
|
+
writeUserConfig(env, { installationId });
|
|
470
|
+
return installationId;
|
|
471
|
+
}
|
|
472
|
+
//#endregion
|
|
473
|
+
//#region src/telemetry/report.ts
|
|
474
|
+
/**
|
|
475
|
+
* The command path the whole telemetry surface is exempt from. Running
|
|
476
|
+
* `telemetry disable` must not report a usage event on its way to
|
|
477
|
+
* disabling, and `telemetry status` must not mint an id while merely
|
|
478
|
+
* reporting state.
|
|
479
|
+
*/
|
|
480
|
+
const EXEMPT_COMMAND = "telemetry";
|
|
481
|
+
/**
|
|
482
|
+
* The one-time first-run disclosure. `<name> telemetry disable` is named
|
|
483
|
+
* as the primary, friendliest opt-out, alongside the environment
|
|
484
|
+
* variables. The config file is not named and hand-editing it is not
|
|
485
|
+
* suggested: the preference is machine-edited, which is what the
|
|
486
|
+
* telemetry commands are for, and `telemetry status` reports the path
|
|
487
|
+
* for anyone who wants it.
|
|
488
|
+
*/
|
|
489
|
+
function firstRunNotice(cliName, docsUrl) {
|
|
490
|
+
return [
|
|
491
|
+
"Prisma collects anonymous CLI usage data, enabled by default.",
|
|
492
|
+
`What's collected and why: ${docsUrl}.`,
|
|
493
|
+
`Opt out: run "${cliName} telemetry disable", set DO_NOT_TRACK=1 or`,
|
|
494
|
+
"PRISMA_DISABLE_TELEMETRY=1."
|
|
495
|
+
].join(" ");
|
|
496
|
+
}
|
|
497
|
+
/**
|
|
498
|
+
* The first enabled run on this machine: disclose, then mint. Both are
|
|
499
|
+
* best-effort. A failed write returns no id, which skips the event
|
|
500
|
+
* rather than sending a junk one, and leaves the notice to print again
|
|
501
|
+
* next run — the stored id is what makes it print exactly once.
|
|
502
|
+
*/
|
|
503
|
+
function discloseAndMint(inputs) {
|
|
504
|
+
const { host } = inputs;
|
|
505
|
+
try {
|
|
506
|
+
host.stderr.write(`${firstRunNotice(inputs.name, inputs.telemetry.docsUrl)}\n`);
|
|
507
|
+
} catch {}
|
|
508
|
+
try {
|
|
509
|
+
return ensureInstallationId(host.env);
|
|
510
|
+
} catch {
|
|
511
|
+
return;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* Report one run, at command start — before the handler, from the
|
|
516
|
+
* parse-time snapshot. Exempt the telemetry command, resolve gating,
|
|
517
|
+
* disclose and mint on a first enabled run, compose, hand the payload to
|
|
518
|
+
* the host's seam. The engine composes; the host spawns.
|
|
519
|
+
*
|
|
520
|
+
* A host with no seam is turned away first, before the config is even
|
|
521
|
+
* read: a CLI that cannot deliver an event must not tell the user it
|
|
522
|
+
* collects data, and must not mint an installation id it has no use
|
|
523
|
+
* for. Declaring telemetry and wiring the seam are two halves of one
|
|
524
|
+
* decision; either one missing means the run reports nothing. An
|
|
525
|
+
* environment that says nothing about where the user's config lives is
|
|
526
|
+
* turned away at the same point and for the same reason.
|
|
527
|
+
*
|
|
528
|
+
* Every failure is swallowed: a malformed stored config, an unwritable
|
|
529
|
+
* config directory and a throwing seam all leave the run's exit code,
|
|
530
|
+
* stdout and stderr exactly as they would have been.
|
|
531
|
+
*/
|
|
532
|
+
function reportCommandStart(inputs) {
|
|
533
|
+
try {
|
|
534
|
+
const { host, snapshot } = inputs;
|
|
535
|
+
const deliver = host.spawnTelemetry;
|
|
536
|
+
const configPath = userConfigPath(host.env);
|
|
537
|
+
if (deliver === void 0 || configPath === void 0 || snapshot.commandPath[0] === EXEMPT_COMMAND) return;
|
|
538
|
+
const config = readUserConfig(host.env);
|
|
539
|
+
if (!resolveGating({
|
|
540
|
+
env: host.env,
|
|
541
|
+
config,
|
|
542
|
+
inCI: resolveIsCI(host)
|
|
543
|
+
}).enabled) return;
|
|
544
|
+
const stored = config.installationId;
|
|
545
|
+
const installationId = typeof stored === "string" && stored.length > 0 ? stored : discloseAndMint(inputs);
|
|
546
|
+
if (installationId === void 0) return;
|
|
547
|
+
deliver(composeTelemetryPayload({
|
|
548
|
+
installationId,
|
|
549
|
+
version: inputs.version,
|
|
550
|
+
projectRoot: host.cwd,
|
|
551
|
+
endpoint: resolveTelemetryEndpoint(host.env),
|
|
552
|
+
snapshot
|
|
553
|
+
}));
|
|
554
|
+
} catch {}
|
|
555
|
+
}
|
|
556
|
+
//#endregion
|
|
557
|
+
//#region src/package-manager.ts
|
|
558
|
+
const MANAGERS = new Set([
|
|
559
|
+
"npm",
|
|
560
|
+
"pnpm",
|
|
561
|
+
"yarn",
|
|
562
|
+
"bun",
|
|
563
|
+
"deno"
|
|
564
|
+
]);
|
|
565
|
+
function isManager(name) {
|
|
566
|
+
return MANAGERS.has(name);
|
|
567
|
+
}
|
|
568
|
+
/**
|
|
569
|
+
* The manager that invoked this process, read from the environment the
|
|
570
|
+
* host handed the engine. package-manager-detector's own getUserAgent
|
|
571
|
+
* reads process.env directly, which the engine may not do; this is the
|
|
572
|
+
* same parse over Runtime.env.
|
|
573
|
+
*/
|
|
574
|
+
function invokingManager(env) {
|
|
575
|
+
const name = env.npm_config_user_agent?.split("/")[0];
|
|
576
|
+
return name !== void 0 && isManager(name) ? name : void 0;
|
|
577
|
+
}
|
|
578
|
+
/**
|
|
579
|
+
* Resolves the manager to drive at `cwd`. In order: the caller's
|
|
580
|
+
* choice, the host's, the project the library detects by walking up
|
|
581
|
+
* from `cwd`, the manager that invoked this process, then npm. Always
|
|
582
|
+
* resolves — "we could not tell" is not an outcome.
|
|
583
|
+
*
|
|
584
|
+
* Two inherited behaviors of package-manager-detector, deliberate and
|
|
585
|
+
* documented so they are not rediscovered as bugs: the walk goes to the
|
|
586
|
+
* filesystem root with no project boundary, so a lockfile above the
|
|
587
|
+
* project counts; and within one directory a package.json
|
|
588
|
+
* `packageManager` field beats a lockfile.
|
|
589
|
+
*/
|
|
590
|
+
async function resolvePackageManager(request) {
|
|
591
|
+
const chosen = request.override ?? request.host;
|
|
592
|
+
if (chosen !== void 0) return chosen;
|
|
593
|
+
const detected = await detect({ cwd: request.cwd });
|
|
594
|
+
if (detected !== null && isManager(detected.name)) return detected.name;
|
|
595
|
+
return invokingManager(request.env) ?? "npm";
|
|
596
|
+
}
|
|
597
|
+
/**
|
|
598
|
+
* The characters a POSIX shell hands to a command unchanged. Everything
|
|
599
|
+
* else — whitespace, `|`, `>`, `$`, `*`, quotes — either moves an
|
|
600
|
+
* argument boundary or is syntax the shell acts on, and the line is
|
|
601
|
+
* offered to the user as the command to run by hand: it has to reach
|
|
602
|
+
* their package manager as the argv the engine composed.
|
|
603
|
+
*/
|
|
604
|
+
const SHELL_SAFE = /^[A-Za-z0-9_@%+=:,./-]+$/;
|
|
605
|
+
/**
|
|
606
|
+
* Single quotes, because a POSIX shell expands nothing inside them; a
|
|
607
|
+
* single quote in the entry itself has to leave and re-enter them.
|
|
608
|
+
* Known limitation: this is not a Windows rule — cmd.exe treats `'` as
|
|
609
|
+
* an ordinary character and reads `%` and `^` — so a line pasted into
|
|
610
|
+
* cmd.exe or PowerShell is not quoted for those shells.
|
|
611
|
+
*/
|
|
612
|
+
function shellQuote(entry) {
|
|
613
|
+
if (SHELL_SAFE.test(entry)) return entry;
|
|
614
|
+
return `'${entry.replaceAll("'", String.raw`'\''`)}'`;
|
|
615
|
+
}
|
|
616
|
+
function spell$1(file, args) {
|
|
617
|
+
return {
|
|
618
|
+
file,
|
|
619
|
+
args,
|
|
620
|
+
line: [file, ...args].map(shellQuote).join(" ")
|
|
621
|
+
};
|
|
622
|
+
}
|
|
623
|
+
function addSpelling(file) {
|
|
624
|
+
return (packages, dev) => spell$1(file, [
|
|
625
|
+
"add",
|
|
626
|
+
...dev ? ["-D"] : [],
|
|
627
|
+
...packages
|
|
628
|
+
]);
|
|
629
|
+
}
|
|
630
|
+
/**
|
|
631
|
+
* Every command line the engine will run, for every manager and both
|
|
632
|
+
* forms. Nothing else in the engine spells a manager command.
|
|
633
|
+
*/
|
|
634
|
+
const SPELLINGS = {
|
|
635
|
+
npm: {
|
|
636
|
+
install: addSpelling("npm"),
|
|
637
|
+
run: (packageName, args) => spell$1("npx", [packageName, ...args])
|
|
638
|
+
},
|
|
639
|
+
pnpm: {
|
|
640
|
+
install: addSpelling("pnpm"),
|
|
641
|
+
run: (packageName, args) => spell$1("pnpm", [
|
|
642
|
+
"dlx",
|
|
643
|
+
packageName,
|
|
644
|
+
...args
|
|
645
|
+
])
|
|
646
|
+
},
|
|
647
|
+
yarn: {
|
|
648
|
+
install: addSpelling("yarn"),
|
|
649
|
+
run: (packageName, args) => spell$1("yarn", [
|
|
650
|
+
"dlx",
|
|
651
|
+
packageName,
|
|
652
|
+
...args
|
|
653
|
+
])
|
|
654
|
+
},
|
|
655
|
+
bun: {
|
|
656
|
+
install: addSpelling("bun"),
|
|
657
|
+
run: (packageName, args) => spell$1("bunx", [packageName, ...args])
|
|
658
|
+
},
|
|
659
|
+
deno: {
|
|
660
|
+
install: (packages, dev) => spell$1("deno", [
|
|
661
|
+
"add",
|
|
662
|
+
...dev ? ["--dev"] : [],
|
|
663
|
+
...packages.map((specifier) => `npm:${specifier}`)
|
|
664
|
+
]),
|
|
665
|
+
run: (packageName, args) => spell$1("deno", [
|
|
666
|
+
"run",
|
|
667
|
+
"-A",
|
|
668
|
+
`npm:${packageName}`,
|
|
669
|
+
...args
|
|
670
|
+
])
|
|
671
|
+
}
|
|
672
|
+
};
|
|
673
|
+
/** Adds dependencies to the project. */
|
|
674
|
+
function installCommand(manager, request) {
|
|
675
|
+
return SPELLINGS[manager].install(request.packages, request.dev ?? false);
|
|
676
|
+
}
|
|
677
|
+
/** Runs a package's bin once, without adding a dependency. */
|
|
678
|
+
function runCommand(manager, request) {
|
|
679
|
+
return SPELLINGS[manager].run(request.package, request.args ?? []);
|
|
680
|
+
}
|
|
681
|
+
//#endregion
|
|
158
682
|
//#region src/presentation.ts
|
|
159
683
|
const PRESENTED = Symbol.for("prisma.cli-engine.presented");
|
|
160
684
|
//#endregion
|
|
@@ -283,9 +807,9 @@ const SERVICE_TOKEN_ENV_VAR = "PRISMA_SERVICE_TOKEN";
|
|
|
283
807
|
const WORKSPACE_ID_ENV_VAR = "PRISMA_WORKSPACE_ID";
|
|
284
808
|
//#endregion
|
|
285
809
|
//#region src/execution/debug.ts
|
|
286
|
-
const DEBUG_ENV_VAR = "
|
|
810
|
+
const DEBUG_ENV_VAR = "PRISMA_DEBUG";
|
|
287
811
|
/**
|
|
288
|
-
* The engine's debug valve: silent unless
|
|
812
|
+
* The engine's debug valve: silent unless PRISMA_DEBUG=1 in the
|
|
289
813
|
* injected env (never process.env), writing to the injected stderr.
|
|
290
814
|
* Token material never reaches it.
|
|
291
815
|
*/
|
|
@@ -336,6 +860,26 @@ function buildManagementApiClient(invocation) {
|
|
|
336
860
|
};
|
|
337
861
|
} });
|
|
338
862
|
}
|
|
863
|
+
/**
|
|
864
|
+
* Loads the SDK, surviving a Node ESM resolver fault observed in the
|
|
865
|
+
* wild: the resolver can return the package's un-realpathed pnpm
|
|
866
|
+
* symlink URL (instead of the .pnpm real path), from which the SDK's
|
|
867
|
+
* own 'openapi-fetch' import cannot resolve. The fault is
|
|
868
|
+
* state-dependent — two fstatSync calls at process start reliably
|
|
869
|
+
* provoke it, and a module-loader hook masks it — so nothing here can
|
|
870
|
+
* rule it out. The fallback resolves through CJS require, which
|
|
871
|
+
* realpaths, and imports the real location directly; it never fires
|
|
872
|
+
* when the normal import works.
|
|
873
|
+
*/
|
|
874
|
+
async function importManagementApiSdk() {
|
|
875
|
+
try {
|
|
876
|
+
return await import("@prisma/management-api-sdk");
|
|
877
|
+
} catch {
|
|
878
|
+
const { createRequire } = await import("node:module");
|
|
879
|
+
const { pathToFileURL } = await import("node:url");
|
|
880
|
+
return await import(pathToFileURL(createRequire(import.meta.url).resolve("@prisma/management-api-sdk")).href);
|
|
881
|
+
}
|
|
882
|
+
}
|
|
339
883
|
async function constructClient(invocation, debug, probe) {
|
|
340
884
|
const manager = invocation.runtime.credentialManager;
|
|
341
885
|
if (manager === void 0) throw credentialsRequiredError();
|
|
@@ -344,7 +888,7 @@ async function constructClient(invocation, debug, probe) {
|
|
|
344
888
|
const config = invocation.runtime.managementApiClientConfig;
|
|
345
889
|
if (config === void 0) throw new Error("@prisma/cli-engine: ctx.api requires Runtime.managementApiClientConfig when a credentialManager is wired");
|
|
346
890
|
const storage = observedTokenStorage(await manager.activeCredentialStorage(), active, debug, probe);
|
|
347
|
-
const { createManagementApiSdk } = await
|
|
891
|
+
const { createManagementApiSdk } = await importManagementApiSdk();
|
|
348
892
|
return {
|
|
349
893
|
client: createManagementApiSdk({
|
|
350
894
|
clientId: config.clientId,
|
|
@@ -562,14 +1106,17 @@ function reservedConfigSectionName(name) {
|
|
|
562
1106
|
* top-level key names a config section, and the recognised section
|
|
563
1107
|
* names are exactly the ones the CLI's command families declare. Never
|
|
564
1108
|
* throws — bad section values are the section validator's problem, not
|
|
565
|
-
*
|
|
1109
|
+
* definePrismaConfig's.
|
|
566
1110
|
*/
|
|
567
|
-
function
|
|
1111
|
+
function definePrismaConfig(config) {
|
|
568
1112
|
return Object.freeze({
|
|
569
1113
|
...config,
|
|
570
1114
|
$prismaConfig: 1
|
|
571
1115
|
});
|
|
572
1116
|
}
|
|
1117
|
+
/** @deprecated Renamed to {@link definePrismaConfig}: every family's
|
|
1118
|
+
* config helper carries a unique name, so none needs an import alias. */
|
|
1119
|
+
const defineConfig = definePrismaConfig;
|
|
573
1120
|
function hasVersionMarker(value) {
|
|
574
1121
|
return typeof value === "object" && value !== null && typeof value[MARKER_KEY] === "number";
|
|
575
1122
|
}
|
|
@@ -588,10 +1135,10 @@ function missingMarkerDiagnostic(path) {
|
|
|
588
1135
|
code: "CLI.CONFIG_MISSING_MARKER",
|
|
589
1136
|
severity: "error",
|
|
590
1137
|
summary: `${path} was not written for this version of the Prisma CLI, so it cannot be used.`,
|
|
591
|
-
why: "Configs for this CLI are created with
|
|
1138
|
+
why: "Configs for this CLI are created with definePrismaConfig, which records a version marker on the exported object. This file's default export has no marker — it is most likely a Prisma 7 config, which uses the same filename — and the CLI stops rather than misread it.",
|
|
592
1139
|
nextActions: [{
|
|
593
1140
|
kind: "user-choice",
|
|
594
|
-
label: "Migrate the file: wrap the exported object in
|
|
1141
|
+
label: "Migrate the file: wrap the exported object in definePrismaConfig from @prisma/cli-engine and export the result as the default export."
|
|
595
1142
|
}],
|
|
596
1143
|
where: { path }
|
|
597
1144
|
};
|
|
@@ -607,7 +1154,7 @@ function unsupportedVersionDiagnostic(path, found) {
|
|
|
607
1154
|
summary: `${path} declares config version ${found}, but this CLI supports only version 1.`,
|
|
608
1155
|
nextActions: [{
|
|
609
1156
|
kind: "user-choice",
|
|
610
|
-
label: "Regenerate the config with a
|
|
1157
|
+
label: "Regenerate the config with a definePrismaConfig matching this CLI, or update the CLI to a version that supports the declared config version."
|
|
611
1158
|
}],
|
|
612
1159
|
where: { path }
|
|
613
1160
|
};
|
|
@@ -730,12 +1277,12 @@ async function loadConfig(cwd, configPath) {
|
|
|
730
1277
|
}
|
|
731
1278
|
//#endregion
|
|
732
1279
|
//#region src/execution/pre-parse-argv.ts
|
|
733
|
-
function flagTokens(argv) {
|
|
1280
|
+
function flagTokens$1(argv) {
|
|
734
1281
|
const terminator = argv.indexOf("--");
|
|
735
1282
|
return terminator === -1 ? argv : argv.slice(0, terminator);
|
|
736
1283
|
}
|
|
737
1284
|
function versionFlagGiven(argv) {
|
|
738
|
-
return flagTokens(argv).includes("--version");
|
|
1285
|
+
return flagTokens$1(argv).includes("--version");
|
|
739
1286
|
}
|
|
740
1287
|
/**
|
|
741
1288
|
* The one malformed `--config` shape the parser cannot see. stricli
|
|
@@ -753,12 +1300,12 @@ function versionFlagGiven(argv) {
|
|
|
753
1300
|
* data, and `--` remains the way to pass it.
|
|
754
1301
|
*/
|
|
755
1302
|
function configFlagGivenNoValue(argv) {
|
|
756
|
-
return flagTokens(argv).includes("--config=");
|
|
1303
|
+
return flagTokens$1(argv).includes("--config=");
|
|
757
1304
|
}
|
|
758
1305
|
/** The format requested by --json / --format / --format=<value>, if
|
|
759
1306
|
* any. */
|
|
760
1307
|
function formatFlagGiven(argv) {
|
|
761
|
-
const tokens = flagTokens(argv);
|
|
1308
|
+
const tokens = flagTokens$1(argv);
|
|
762
1309
|
for (const [index, token] of tokens.entries()) {
|
|
763
1310
|
if (token === "--json" || token === "--format=json") return "json";
|
|
764
1311
|
if (token === "--format=human") return "human";
|
|
@@ -912,9 +1459,13 @@ function resolveColorEnabled(shared, runtime) {
|
|
|
912
1459
|
* --no-interactive override in either direction. Format never decides
|
|
913
1460
|
* interactivity (operator ruling, 2026-08-09): an interactive json run
|
|
914
1461
|
* may prompt — the prompt UI writes to stderr, so stdout stays a clean
|
|
915
|
-
* frame stream.
|
|
1462
|
+
* frame stream.
|
|
1463
|
+
*
|
|
1464
|
+
* This asks the engine's CI detection rather than testing `CI` for
|
|
1465
|
+
* being set at all: a Jenkins, TeamCity or Azure Pipelines job sets no
|
|
1466
|
+
* `CI` variable, and used to be offered a prompt no one could answer. */
|
|
916
1467
|
function defaultInteractive(runtime) {
|
|
917
|
-
return runtime.isTty.stdin && runtime
|
|
1468
|
+
return runtime.isTty.stdin && !resolveIsCI(runtime);
|
|
918
1469
|
}
|
|
919
1470
|
function resolveAutoFormat(shared, runtime) {
|
|
920
1471
|
if (shared.json === true) return "json";
|
|
@@ -1152,9 +1703,9 @@ const TONE_VERB = {
|
|
|
1152
1703
|
"color-6": "green"
|
|
1153
1704
|
};
|
|
1154
1705
|
const COLORED = createColors({ useColor: true });
|
|
1155
|
-
const PLAIN = createColors({ useColor: false });
|
|
1706
|
+
const PLAIN$1 = createColors({ useColor: false });
|
|
1156
1707
|
function makePaint(colorEnabled) {
|
|
1157
|
-
const colors = colorEnabled ? COLORED : PLAIN;
|
|
1708
|
+
const colors = colorEnabled ? COLORED : PLAIN$1;
|
|
1158
1709
|
return (tone, text) => colors[TONE_VERB[tone]](text);
|
|
1159
1710
|
}
|
|
1160
1711
|
function renderText(text, paint) {
|
|
@@ -1238,7 +1789,7 @@ const STATUS_SYMBOL = {
|
|
|
1238
1789
|
};
|
|
1239
1790
|
const MASK = "********";
|
|
1240
1791
|
const COLUMN_GAP = " ";
|
|
1241
|
-
const RAIL = "│";
|
|
1792
|
+
const RAIL$1 = "│";
|
|
1242
1793
|
const BRANCH = "├─";
|
|
1243
1794
|
const LAST_BRANCH = "└─";
|
|
1244
1795
|
const TRAILING_SPACES = / +$/;
|
|
@@ -1308,10 +1859,10 @@ function toned(text, tone) {
|
|
|
1308
1859
|
function writeFields(rows, rail, paint, write) {
|
|
1309
1860
|
const cells = rows.map((row) => ({
|
|
1310
1861
|
label: toned(extend(row.label, ":"), "heading"),
|
|
1311
|
-
value: row.sensitive === true ? MASK : row.value
|
|
1862
|
+
value: row.sensitive === true ? MASK : orPlaceholder(row.value)
|
|
1312
1863
|
}));
|
|
1313
1864
|
const width = Math.max(0, ...cells.map((cell) => textWidth(cell.label)));
|
|
1314
|
-
const prefix = rail ? `${paint("structure", RAIL)}${COLUMN_GAP}` : "";
|
|
1865
|
+
const prefix = rail ? `${paint("structure", RAIL$1)}${COLUMN_GAP}` : "";
|
|
1315
1866
|
for (const cell of cells) write(`${prefix}${renderText(padTo(cell.label, width), paint)}${COLUMN_GAP}${renderText(cell.value, paint)}`);
|
|
1316
1867
|
}
|
|
1317
1868
|
/**
|
|
@@ -1319,8 +1870,23 @@ function writeFields(rows, rail, paint, write) {
|
|
|
1319
1870
|
* than the bytes so colour cannot shift a column. The last column is
|
|
1320
1871
|
* never padded, so no line carries trailing whitespace.
|
|
1321
1872
|
*/
|
|
1873
|
+
/** One header convention for every table: plain-string headers are
|
|
1874
|
+
* normalized to sentence case, so casing is not a per-command choice. */
|
|
1875
|
+
function sentenceCase(text) {
|
|
1876
|
+
if (typeof text !== "string" || text === "") return text;
|
|
1877
|
+
return `${text[0].toUpperCase()}${text.slice(1)}`;
|
|
1878
|
+
}
|
|
1879
|
+
const PLACEHOLDER = "—";
|
|
1880
|
+
/** An absent value renders as a dim em dash rather than invented prose
|
|
1881
|
+
* ("none", "n/a") in data tone. */
|
|
1882
|
+
function orPlaceholder(cell) {
|
|
1883
|
+
return cell === "" || typeof cell !== "string" && textWidth(cell) === 0 ? [{
|
|
1884
|
+
text: PLACEHOLDER,
|
|
1885
|
+
tone: "placeholder"
|
|
1886
|
+
}] : cell;
|
|
1887
|
+
}
|
|
1322
1888
|
function writeTable(columns, rows, paint, write) {
|
|
1323
|
-
const all = [columns.map((column) => toned(column, "heading")), ...rows];
|
|
1889
|
+
const all = [columns.map((column) => toned(sentenceCase(column), "heading")), ...rows.map((row) => row.map(orPlaceholder))];
|
|
1324
1890
|
const widths = [];
|
|
1325
1891
|
for (const row of all) for (const [index, cell] of row.entries()) widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
|
|
1326
1892
|
for (const row of all) write(row.map((cell, index) => renderText(index === row.length - 1 ? cell : padTo(cell, widths[index]), paint)).join(COLUMN_GAP).replace(TRAILING_SPACES, ""));
|
|
@@ -1331,7 +1897,7 @@ function writeBranches(nodes, prefix, paint, write) {
|
|
|
1331
1897
|
for (const [index, node] of nodes.entries()) {
|
|
1332
1898
|
const last = index === nodes.length - 1;
|
|
1333
1899
|
write(`${prefix}${paint("structure", last ? LAST_BRANCH : BRANCH)} ${treeLabel(node, paint)}`);
|
|
1334
|
-
const continuation = last ? " " : `${paint("structure", RAIL)}${COLUMN_GAP}`;
|
|
1900
|
+
const continuation = last ? " " : `${paint("structure", RAIL$1)}${COLUMN_GAP}`;
|
|
1335
1901
|
writeBranches(node.children ?? [], `${prefix}${continuation}`, paint, write);
|
|
1336
1902
|
}
|
|
1337
1903
|
}
|
|
@@ -1346,21 +1912,27 @@ const DIAGNOSTIC_SYMBOL = {
|
|
|
1346
1912
|
warn: "⚠",
|
|
1347
1913
|
info: "ℹ"
|
|
1348
1914
|
};
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1915
|
+
const PLAIN = makePaint(false);
|
|
1916
|
+
function writeDiagnostic(stream, diagnostic, paint = PLAIN) {
|
|
1917
|
+
const glyph = paint(diagnostic.severity, DIAGNOSTIC_SYMBOL[diagnostic.severity]);
|
|
1918
|
+
const code = paint("muted", `[${diagnostic.code}]`);
|
|
1919
|
+
stream.write(`${glyph} ${code} ${diagnostic.summary}\n`);
|
|
1920
|
+
if (diagnostic.why !== void 0) stream.write(` ${paint("muted", `why: ${diagnostic.why}`)}\n`);
|
|
1921
|
+
for (const action of diagnostic.nextActions) stream.write(`${renderNextAction(action, paint)}\n`);
|
|
1922
|
+
if (diagnostic.docsUrl !== void 0) stream.write(` ${paint("muted", "docs:")} ${paint("link", diagnostic.docsUrl)}\n`);
|
|
1354
1923
|
}
|
|
1355
1924
|
/** `label` is required, so a mapper building an action out of a bare
|
|
1356
1925
|
* command string — a legacy error's follow-up step, with no prose
|
|
1357
1926
|
* beside it — has nothing to put in the label but the command itself.
|
|
1358
1927
|
* Only the renderer sees both fields, so only it can tell they are the
|
|
1359
1928
|
* same string and print it once. */
|
|
1360
|
-
function renderNextAction(action) {
|
|
1929
|
+
function renderNextAction(action, paint = PLAIN) {
|
|
1361
1930
|
const target = action.command ?? action.url;
|
|
1362
1931
|
const repeatsTheLabel = target === void 0 || target === action.label;
|
|
1363
|
-
|
|
1932
|
+
const arrow = paint("heading", "→");
|
|
1933
|
+
if (repeatsTheLabel) return `${arrow} ${action.command !== void 0 ? paint("identifier", action.label) : action.label}`;
|
|
1934
|
+
const painted = action.command !== void 0 ? paint("identifier", target) : paint("link", target);
|
|
1935
|
+
return `${arrow} ${action.label}: ${painted}`;
|
|
1364
1936
|
}
|
|
1365
1937
|
/** Populates docsUrl from the owning family's docsBaseUrl (base + code)
|
|
1366
1938
|
* when the diagnostic does not carry its own — a per-raise docsUrl wins. */
|
|
@@ -1372,6 +1944,27 @@ function withDocsUrl(state, diagnostic) {
|
|
|
1372
1944
|
docsUrl: `${base}${diagnostic.code}`
|
|
1373
1945
|
};
|
|
1374
1946
|
}
|
|
1947
|
+
const TRAILING_NEWLINE = /\n$/;
|
|
1948
|
+
function diagnosticSection(diagnostic, paint) {
|
|
1949
|
+
const lines = [];
|
|
1950
|
+
writeDiagnostic({ write: (text) => lines.push(...text.replace(TRAILING_NEWLINE, "").split("\n")) }, diagnostic, paint);
|
|
1951
|
+
return {
|
|
1952
|
+
lines,
|
|
1953
|
+
compact: lines.length === 1
|
|
1954
|
+
};
|
|
1955
|
+
}
|
|
1956
|
+
/** A blank line between sections wherever a multi-line one is involved,
|
|
1957
|
+
* so a card, a table and the next actions each read as their own
|
|
1958
|
+
* paragraph; adjacent compact sections keep hugging. */
|
|
1959
|
+
function writeSections(sections, stream) {
|
|
1960
|
+
let previous;
|
|
1961
|
+
for (const section of sections) {
|
|
1962
|
+
if (section.lines.length === 0) continue;
|
|
1963
|
+
if (previous !== void 0 && !(previous.compact && section.compact)) stream.write("\n");
|
|
1964
|
+
for (const line of section.lines) stream.write(`${line}\n`);
|
|
1965
|
+
previous = section;
|
|
1966
|
+
}
|
|
1967
|
+
}
|
|
1375
1968
|
/** Channel discipline (operator ruling, 2026-08-09): human Blocks,
|
|
1376
1969
|
* next-action lines, and diagnostics are presentation prose on stderr;
|
|
1377
1970
|
* the materialized `stdout` presentation lines are the machine-usable
|
|
@@ -1379,10 +1972,21 @@ function withDocsUrl(state, diagnostic) {
|
|
|
1379
1972
|
function renderCompletedHuman(invocation, presented) {
|
|
1380
1973
|
const { runtime, state } = invocation;
|
|
1381
1974
|
const paint = makePaint(state.colorEnabled);
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1975
|
+
const sections = presented.presentation.human.map((block) => {
|
|
1976
|
+
const lines = [];
|
|
1977
|
+
renderBlock(block, paint, (line) => lines.push(line));
|
|
1978
|
+
return {
|
|
1979
|
+
lines,
|
|
1980
|
+
compact: block.kind === "summary"
|
|
1981
|
+
};
|
|
1982
|
+
});
|
|
1983
|
+
if (presented.presentation.next.length > 0) sections.push({
|
|
1984
|
+
lines: presented.presentation.next.map((action) => renderNextAction(action, paint)),
|
|
1985
|
+
compact: true
|
|
1986
|
+
});
|
|
1987
|
+
for (const diagnostic of presented.diagnostics) sections.push(diagnosticSection(withDocsUrl(state, diagnostic), paint));
|
|
1988
|
+
writeSections(sections, runtime.stderr);
|
|
1989
|
+
if (!(runtime.isTty.stdout && runtime.isTty.stderr && runtime.outputStreamsShareDevice !== false)) for (const line of presented.presentation.stdout) runtime.stdout.write(`${line}\n`);
|
|
1386
1990
|
}
|
|
1387
1991
|
const SEVERITY_RANK = {
|
|
1388
1992
|
error: 0,
|
|
@@ -1468,7 +2072,7 @@ function structuredErrorFromDiagnostic(diagnostic) {
|
|
|
1468
2072
|
* success it carries the validated section value for ctx.config. */
|
|
1469
2073
|
async function checkNeeds(def, invocation) {
|
|
1470
2074
|
const needs = def.needs;
|
|
1471
|
-
const failure = checkInteraction(needs, invocation) ?? checkDependencies(needs, invocation);
|
|
2075
|
+
const failure = checkInteraction(needs, invocation) ?? await checkDependencies(needs, invocation);
|
|
1472
2076
|
if (failure !== void 0) return failure;
|
|
1473
2077
|
const credentials = await checkCredentials(needs, invocation);
|
|
1474
2078
|
if (credentials.failure !== void 0) return credentials.failure;
|
|
@@ -1495,8 +2099,15 @@ function checkInteraction(needs, invocation) {
|
|
|
1495
2099
|
}]
|
|
1496
2100
|
}));
|
|
1497
2101
|
}
|
|
1498
|
-
function checkDependencies(needs, invocation) {
|
|
1499
|
-
|
|
2102
|
+
async function checkDependencies(needs, invocation) {
|
|
2103
|
+
const runtime = invocation.runtime;
|
|
2104
|
+
const missing = needs.dependencies.find((specifier) => !dependencyResolvable(specifier, runtime.cwd));
|
|
2105
|
+
if (missing === void 0) return;
|
|
2106
|
+
return needsErrored(missingDependencyError(missing, await resolvePackageManager({
|
|
2107
|
+
cwd: runtime.cwd,
|
|
2108
|
+
env: runtime.env,
|
|
2109
|
+
host: runtime.packageManager
|
|
2110
|
+
})));
|
|
1500
2111
|
}
|
|
1501
2112
|
/**
|
|
1502
2113
|
* The credentials need, single-sourced from the credential manager:
|
|
@@ -1607,7 +2218,7 @@ function writeSectionWarnings(invocation, diagnostics) {
|
|
|
1607
2218
|
const state = invocation.state;
|
|
1608
2219
|
for (const diagnostic of diagnostics) {
|
|
1609
2220
|
if (SEVERITY_RANK[diagnostic.severity] > SEVERITY_RANK[state.logLevel]) continue;
|
|
1610
|
-
writeDiagnostic(invocation.runtime.stderr, withDocsUrl(state, diagnostic));
|
|
2221
|
+
writeDiagnostic(invocation.runtime.stderr, withDocsUrl(state, diagnostic), makePaint(state.colorEnabled));
|
|
1611
2222
|
}
|
|
1612
2223
|
}
|
|
1613
2224
|
function dependencyResolvable(specifier, cwd) {
|
|
@@ -1618,30 +2229,18 @@ function dependencyResolvable(specifier, cwd) {
|
|
|
1618
2229
|
return false;
|
|
1619
2230
|
}
|
|
1620
2231
|
}
|
|
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
2232
|
/** Optional peer dependencies: the engine probes and phrases. */
|
|
1631
|
-
function missingDependencyError(specifier,
|
|
1632
|
-
const install = installCommand(
|
|
2233
|
+
function missingDependencyError(specifier, manager) {
|
|
2234
|
+
const install = installCommand(manager, { packages: [specifier] }).line;
|
|
1633
2235
|
return new CliStructuredError("CLI.MISSING_DEPENDENCY", `This command requires the optional dependency '${specifier}', which is not installed in this project.`, {
|
|
1634
|
-
nextActions: [
|
|
1635
|
-
kind: "user-choice",
|
|
1636
|
-
label: `Install '${specifier}' with your package manager, then run the command again.`
|
|
1637
|
-
} : {
|
|
2236
|
+
nextActions: [{
|
|
1638
2237
|
kind: "run-command",
|
|
1639
2238
|
label: `Install '${specifier}'`,
|
|
1640
2239
|
command: install
|
|
1641
2240
|
}],
|
|
1642
2241
|
meta: {
|
|
1643
2242
|
specifier,
|
|
1644
|
-
|
|
2243
|
+
installCommand: install
|
|
1645
2244
|
}
|
|
1646
2245
|
});
|
|
1647
2246
|
}
|
|
@@ -1663,6 +2262,252 @@ async function announceUrl(invocation, request) {
|
|
|
1663
2262
|
}
|
|
1664
2263
|
}
|
|
1665
2264
|
//#endregion
|
|
2265
|
+
//#region src/package-manager-errors.ts
|
|
2266
|
+
function why(failure) {
|
|
2267
|
+
if (failure.reason === "runner-unavailable") return "This host wires no package-manager runner, so nothing was run.";
|
|
2268
|
+
return `${failure.manager} exited with code ${failure.exitCode}.`;
|
|
2269
|
+
}
|
|
2270
|
+
/**
|
|
2271
|
+
* The single constructor of CLI.PACKAGE_MANAGER_FAILED — both forms of
|
|
2272
|
+
* ctx.packages, and the host that can run neither.
|
|
2273
|
+
*/
|
|
2274
|
+
function packageManagerFailedError(failure) {
|
|
2275
|
+
const installing = failure.form === "install";
|
|
2276
|
+
return new CliStructuredError("CLI.PACKAGE_MANAGER_FAILED", installing ? `Installing packages with ${failure.manager} failed.` : `Running ${failure.package} with ${failure.manager} failed.`, {
|
|
2277
|
+
why: why(failure),
|
|
2278
|
+
nextActions: [{
|
|
2279
|
+
kind: "run-command",
|
|
2280
|
+
label: installing ? "Run the install yourself" : "Run the command yourself",
|
|
2281
|
+
command: failure.command
|
|
2282
|
+
}],
|
|
2283
|
+
meta: {
|
|
2284
|
+
form: failure.form,
|
|
2285
|
+
manager: failure.manager,
|
|
2286
|
+
command: failure.command,
|
|
2287
|
+
exitCode: failure.exitCode,
|
|
2288
|
+
stderrTail: failure.stderrTail,
|
|
2289
|
+
...failure.reason === void 0 ? {} : { reason: failure.reason }
|
|
2290
|
+
}
|
|
2291
|
+
});
|
|
2292
|
+
}
|
|
2293
|
+
//#endregion
|
|
2294
|
+
//#region src/execution/redaction.ts
|
|
2295
|
+
const REDACTED = "…";
|
|
2296
|
+
/** A candidate runs from a scheme to the end of the authority, which is
|
|
2297
|
+
* the only part of a URL userinfo can be in. Delimiting it is all this
|
|
2298
|
+
* does; `URL` below decides whether the candidate is a URL at all. What
|
|
2299
|
+
* follows the authority is never matched, so a path holding an `@`, and
|
|
2300
|
+
* the punctuation a URL ending a sentence carries, are untouched. */
|
|
2301
|
+
const URL_AUTHORITY = /[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s/?#<>]+/g;
|
|
2302
|
+
const AUTHORITY_MARK = "://";
|
|
2303
|
+
/** `new URL` throws for everything that is not a URL, which is how a
|
|
2304
|
+
* candidate is rejected. */
|
|
2305
|
+
function asUrl(candidate) {
|
|
2306
|
+
try {
|
|
2307
|
+
return new URL(candidate);
|
|
2308
|
+
} catch {
|
|
2309
|
+
return;
|
|
2310
|
+
}
|
|
2311
|
+
}
|
|
2312
|
+
/** `URL` reports whether there is userinfo at all, and the `@` that ends
|
|
2313
|
+
* it is the last one in the authority. Only that span of the original
|
|
2314
|
+
* text is replaced: serialising the parsed URL back out would return a
|
|
2315
|
+
* normalised one — default port dropped, path resolved, password
|
|
2316
|
+
* percent-encoded — and the surrounding output has to survive verbatim. */
|
|
2317
|
+
function redactUserinfo(candidate) {
|
|
2318
|
+
const url = asUrl(candidate);
|
|
2319
|
+
if (url === void 0 || url.username === "" && url.password === "") return candidate;
|
|
2320
|
+
const start = candidate.indexOf(AUTHORITY_MARK) + 3;
|
|
2321
|
+
const end = candidate.lastIndexOf("@");
|
|
2322
|
+
return `${candidate.slice(0, start)}${REDACTED}${candidate.slice(end)}`;
|
|
2323
|
+
}
|
|
2324
|
+
const VALUE = String.raw`"[^"]*"|'[^']*'|\S+`;
|
|
2325
|
+
const ASSIGNMENT = new RegExp(String.raw`\b([A-Za-z_][A-Za-z0-9_]*)=(${VALUE})`, "g");
|
|
2326
|
+
/** A header's value runs to the end of its line, because an auth scheme
|
|
2327
|
+
* and its credential are one value: `Authorization: Bearer eyJ…`. */
|
|
2328
|
+
const HEADER = /\b([A-Za-z][A-Za-z0-9_-]*):[ \t]+[^\n]+/g;
|
|
2329
|
+
/** A flag's value is the word after it. A word starting with a dash is
|
|
2330
|
+
* the next flag rather than this one's value. */
|
|
2331
|
+
const FLAG = new RegExp(String.raw`(--?[A-Za-z][A-Za-z0-9_-]*)[ \t]+(?!-)(?:${VALUE})`, "g");
|
|
2332
|
+
const SECRET_WORDS = new Set([
|
|
2333
|
+
"TOKEN",
|
|
2334
|
+
"KEY",
|
|
2335
|
+
"SECRET",
|
|
2336
|
+
"PASSWORD",
|
|
2337
|
+
"AUTHORIZATION"
|
|
2338
|
+
]);
|
|
2339
|
+
/** Underscores, hyphens and camelCase humps: `MY_API_TOKEN`,
|
|
2340
|
+
* `--auth-token` and `_authToken` name a secret; `monkey`,
|
|
2341
|
+
* `--keyring` and `tokenizer` do not. */
|
|
2342
|
+
const NAME_WORDS = /[_-]+|(?<=[a-z0-9])(?=[A-Z])/;
|
|
2343
|
+
function namesSecret(name) {
|
|
2344
|
+
return name.split(NAME_WORDS).some((word) => SECRET_WORDS.has(word.toUpperCase()));
|
|
2345
|
+
}
|
|
2346
|
+
/**
|
|
2347
|
+
* Removes the shapes a package manager's output leaks credentials in:
|
|
2348
|
+
* the userinfo of a URL, and the value carried by a name that says it
|
|
2349
|
+
* holds a secret — after an `=`, after a header's colon, or after a
|
|
2350
|
+
* flag. Everything else survives verbatim, so a caller matching an
|
|
2351
|
+
* error code out of stderr still finds it.
|
|
2352
|
+
*/
|
|
2353
|
+
function redactSecrets(text) {
|
|
2354
|
+
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);
|
|
2355
|
+
}
|
|
2356
|
+
//#endregion
|
|
2357
|
+
//#region src/execution/package-operations.ts
|
|
2358
|
+
/** What the seam reports for a child that never ran, and what a host
|
|
2359
|
+
* with no runner at all reports for the same reason. */
|
|
2360
|
+
const NO_CHILD_EXIT_CODE = 1;
|
|
2361
|
+
function spell(operation, manager) {
|
|
2362
|
+
return operation.form === "install" ? installCommand(manager, {
|
|
2363
|
+
packages: operation.packages,
|
|
2364
|
+
dev: operation.dev
|
|
2365
|
+
}) : runCommand(manager, {
|
|
2366
|
+
package: operation.package,
|
|
2367
|
+
args: operation.args
|
|
2368
|
+
});
|
|
2369
|
+
}
|
|
2370
|
+
function failed(operation, command, outcome) {
|
|
2371
|
+
const spelling = redactSecrets(command.line);
|
|
2372
|
+
return packageManagerFailedError(operation.form === "install" ? {
|
|
2373
|
+
...outcome,
|
|
2374
|
+
command: spelling,
|
|
2375
|
+
form: "install"
|
|
2376
|
+
} : {
|
|
2377
|
+
...outcome,
|
|
2378
|
+
command: spelling,
|
|
2379
|
+
form: "run",
|
|
2380
|
+
package: operation.package
|
|
2381
|
+
});
|
|
2382
|
+
}
|
|
2383
|
+
/** Cancellation throws rather than resolving a failure, so an aborted
|
|
2384
|
+
* operation settles the way Ctrl-C settles everywhere else. Asked again
|
|
2385
|
+
* after detection: that await is long enough for the signal to fire,
|
|
2386
|
+
* and an operation nothing spawned must announce nothing. */
|
|
2387
|
+
function stopIfCancelled(signal) {
|
|
2388
|
+
if (signal.aborted) throw signal.reason;
|
|
2389
|
+
}
|
|
2390
|
+
/** The seam hands over chunks as the child writes them; an `output`
|
|
2391
|
+
* event carries one line, so a line split across two chunks waits for
|
|
2392
|
+
* its second half. */
|
|
2393
|
+
function lineAssembler(emit) {
|
|
2394
|
+
let pending = "";
|
|
2395
|
+
const emitLine = (line) => {
|
|
2396
|
+
emit(redactSecrets(line.endsWith("\r") ? line.slice(0, -1) : line));
|
|
2397
|
+
};
|
|
2398
|
+
return {
|
|
2399
|
+
push: (chunk) => {
|
|
2400
|
+
const lines = (pending + chunk).split("\n");
|
|
2401
|
+
pending = lines.pop() ?? "";
|
|
2402
|
+
for (const line of lines) emitLine(line);
|
|
2403
|
+
},
|
|
2404
|
+
flush: () => {
|
|
2405
|
+
if (pending !== "") {
|
|
2406
|
+
emitLine(pending);
|
|
2407
|
+
pending = "";
|
|
2408
|
+
}
|
|
2409
|
+
}
|
|
2410
|
+
};
|
|
2411
|
+
}
|
|
2412
|
+
function outputChannels(invocation, manager) {
|
|
2413
|
+
const assemble = (channel) => lineAssembler((line) => {
|
|
2414
|
+
reportEvent(invocation, {
|
|
2415
|
+
kind: "output",
|
|
2416
|
+
source: manager,
|
|
2417
|
+
channel,
|
|
2418
|
+
line
|
|
2419
|
+
});
|
|
2420
|
+
});
|
|
2421
|
+
const channels = {
|
|
2422
|
+
data: assemble("data"),
|
|
2423
|
+
diagnostic: assemble("diagnostic")
|
|
2424
|
+
};
|
|
2425
|
+
return {
|
|
2426
|
+
push: (channel, chunk) => {
|
|
2427
|
+
channels[channel].push(chunk);
|
|
2428
|
+
},
|
|
2429
|
+
flush: () => {
|
|
2430
|
+
channels.data.flush();
|
|
2431
|
+
channels.diagnostic.flush();
|
|
2432
|
+
}
|
|
2433
|
+
};
|
|
2434
|
+
}
|
|
2435
|
+
async function execute(invocation, operation, placement) {
|
|
2436
|
+
const { runtime, signal } = invocation;
|
|
2437
|
+
stopIfCancelled(signal);
|
|
2438
|
+
const cwd = placement.cwd ?? runtime.cwd;
|
|
2439
|
+
const manager = await resolvePackageManager({
|
|
2440
|
+
cwd,
|
|
2441
|
+
env: runtime.env,
|
|
2442
|
+
override: placement.manager,
|
|
2443
|
+
host: runtime.packageManager
|
|
2444
|
+
});
|
|
2445
|
+
stopIfCancelled(signal);
|
|
2446
|
+
const command = spell(operation, manager);
|
|
2447
|
+
const runner = runtime.runPackageManager;
|
|
2448
|
+
if (runner === void 0) return notOk(failed(operation, command, {
|
|
2449
|
+
manager,
|
|
2450
|
+
exitCode: NO_CHILD_EXIT_CODE,
|
|
2451
|
+
stderrTail: "",
|
|
2452
|
+
reason: "runner-unavailable"
|
|
2453
|
+
}));
|
|
2454
|
+
const output = outputChannels(invocation, manager);
|
|
2455
|
+
const step = redactSecrets(command.line);
|
|
2456
|
+
reportEvent(invocation, {
|
|
2457
|
+
kind: "step-started",
|
|
2458
|
+
step
|
|
2459
|
+
});
|
|
2460
|
+
let result;
|
|
2461
|
+
try {
|
|
2462
|
+
result = await runner({
|
|
2463
|
+
file: command.file,
|
|
2464
|
+
args: command.args,
|
|
2465
|
+
cwd,
|
|
2466
|
+
signal,
|
|
2467
|
+
onOutput: output.push
|
|
2468
|
+
});
|
|
2469
|
+
} finally {
|
|
2470
|
+
output.flush();
|
|
2471
|
+
}
|
|
2472
|
+
reportEvent(invocation, {
|
|
2473
|
+
kind: "step-finished",
|
|
2474
|
+
step,
|
|
2475
|
+
outcome: signal.aborted || result.exitCode !== 0 ? "failed" : "ok"
|
|
2476
|
+
});
|
|
2477
|
+
stopIfCancelled(signal);
|
|
2478
|
+
if (result.exitCode === 0) return okVoid();
|
|
2479
|
+
return notOk(failed(operation, command, {
|
|
2480
|
+
manager,
|
|
2481
|
+
exitCode: result.exitCode,
|
|
2482
|
+
stderrTail: redactSecrets(result.stderr)
|
|
2483
|
+
}));
|
|
2484
|
+
}
|
|
2485
|
+
function makePackageOperations(invocation) {
|
|
2486
|
+
const state = invocation.state;
|
|
2487
|
+
const perform = async (operation, placement) => {
|
|
2488
|
+
if (state.delegatedTerminal !== void 0) throw constructionError(`command '${state.commandId}' called ctx.packages while a child owned the terminal`);
|
|
2489
|
+
if (state.packageOperationRunning) throw constructionError("ctx.packages runs one operation at a time, so two package managers can never write one project at once");
|
|
2490
|
+
state.packageOperationRunning = true;
|
|
2491
|
+
try {
|
|
2492
|
+
return await execute(invocation, operation, placement);
|
|
2493
|
+
} finally {
|
|
2494
|
+
state.packageOperationRunning = false;
|
|
2495
|
+
}
|
|
2496
|
+
};
|
|
2497
|
+
return {
|
|
2498
|
+
install: (request) => perform({
|
|
2499
|
+
form: "install",
|
|
2500
|
+
packages: request.packages,
|
|
2501
|
+
dev: request.dev ?? false
|
|
2502
|
+
}, request),
|
|
2503
|
+
run: (request) => perform({
|
|
2504
|
+
form: "run",
|
|
2505
|
+
package: request.package,
|
|
2506
|
+
args: request.args
|
|
2507
|
+
}, request)
|
|
2508
|
+
};
|
|
2509
|
+
}
|
|
2510
|
+
//#endregion
|
|
1666
2511
|
//#region src/execution/clack-renderer.ts
|
|
1667
2512
|
/**
|
|
1668
2513
|
* Interactive prompt rendering backed by @clack/prompts, driven
|
|
@@ -1760,22 +2605,24 @@ function makeLineReader(stdin, invocation) {
|
|
|
1760
2605
|
const decoder = new TextDecoder();
|
|
1761
2606
|
let buffer = "";
|
|
1762
2607
|
let done = false;
|
|
2608
|
+
const takeBufferedLine = () => {
|
|
2609
|
+
const newline = buffer.indexOf("\n");
|
|
2610
|
+
if (newline === -1) return;
|
|
2611
|
+
const line = buffer.slice(0, newline);
|
|
2612
|
+
buffer = buffer.slice(newline + 1);
|
|
2613
|
+
return line.endsWith("\r") ? line.slice(0, -1) : line;
|
|
2614
|
+
};
|
|
2615
|
+
const takeFinalLine = () => {
|
|
2616
|
+
if (buffer.length === 0) return;
|
|
2617
|
+
const line = buffer;
|
|
2618
|
+
buffer = "";
|
|
2619
|
+
return line;
|
|
2620
|
+
};
|
|
1763
2621
|
return async () => {
|
|
1764
2622
|
for (;;) {
|
|
1765
|
-
const
|
|
1766
|
-
if (
|
|
1767
|
-
|
|
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
|
-
}
|
|
2623
|
+
const buffered = takeBufferedLine();
|
|
2624
|
+
if (buffered !== void 0) return buffered;
|
|
2625
|
+
if (done) return takeFinalLine();
|
|
1779
2626
|
const next = await iterator.next();
|
|
1780
2627
|
if (next.done === true) {
|
|
1781
2628
|
done = true;
|
|
@@ -1794,6 +2641,12 @@ function promptUnanswerable(question, state) {
|
|
|
1794
2641
|
label: "Run the command from an interactive terminal, or pass a flag that answers the prompt."
|
|
1795
2642
|
}] });
|
|
1796
2643
|
}
|
|
2644
|
+
/** What a prompt resolves to when it cannot be shown: its declared
|
|
2645
|
+
* default, or a halt when it has none. */
|
|
2646
|
+
function answerWithoutAsking(question, fallback, state) {
|
|
2647
|
+
if (fallback === void 0) throw promptUnanswerable(question, state);
|
|
2648
|
+
return fallback;
|
|
2649
|
+
}
|
|
1797
2650
|
function consentUnavailable(question, state, token) {
|
|
1798
2651
|
const situation = state.yes ? `"${question}" requires explicit consent, which --yes cannot grant.` : `"${question}" requires explicit consent, and the session is not interactive.`;
|
|
1799
2652
|
if (token === void 0) return new CliStructuredError("CLI.CONSENT_REQUIRED", situation, { nextActions: [{
|
|
@@ -1911,6 +2764,28 @@ function makePromptSurface(invocation) {
|
|
|
1911
2764
|
if (typeof typed !== "string" || typed.trim() !== token) throw consentTokenMismatch(question, token, String(typed));
|
|
1912
2765
|
return true;
|
|
1913
2766
|
};
|
|
2767
|
+
const askSelect = async (question, options, fallback) => {
|
|
2768
|
+
const raw = await ask(question, [
|
|
2769
|
+
`? ${question}`,
|
|
2770
|
+
...options.map((option) => ` ${option.value === fallback ? "▸" : " "} ${option.value}: ${option.label}`),
|
|
2771
|
+
"> "
|
|
2772
|
+
].join("\n"));
|
|
2773
|
+
if (typeof raw !== "string") throw promptInvalid(question, String(raw));
|
|
2774
|
+
const answer = raw.trim();
|
|
2775
|
+
if (answer === "") {
|
|
2776
|
+
if (fallback === void 0) throw promptInvalid(question, raw);
|
|
2777
|
+
return fallback;
|
|
2778
|
+
}
|
|
2779
|
+
const match = options.find((option) => option.value === answer);
|
|
2780
|
+
if (match === void 0) throw promptInvalid(question, raw);
|
|
2781
|
+
return match.value;
|
|
2782
|
+
};
|
|
2783
|
+
const askText = async (question, fallback) => {
|
|
2784
|
+
const raw = await ask(question, `? ${question}${fallback === void 0 ? "" : ` (${fallback})`} `);
|
|
2785
|
+
if (typeof raw !== "string") throw promptInvalid(question, String(raw));
|
|
2786
|
+
if (raw === "") return fallback ?? "";
|
|
2787
|
+
return raw;
|
|
2788
|
+
};
|
|
1914
2789
|
/** A prompt writes to stderr and reads the engine's stdin — the same
|
|
1915
2790
|
* terminal a live child inherited. Like ctx.present, prompting while
|
|
1916
2791
|
* a child owns the terminal is a construction error. */
|
|
@@ -1920,10 +2795,7 @@ function makePromptSurface(invocation) {
|
|
|
1920
2795
|
const surface = {
|
|
1921
2796
|
confirm: async (question, opts) => {
|
|
1922
2797
|
const fallback = opts?.default;
|
|
1923
|
-
if (state.yes || !state.interactive)
|
|
1924
|
-
if (fallback === void 0) throw promptUnanswerable(question, state);
|
|
1925
|
-
return fallback;
|
|
1926
|
-
}
|
|
2798
|
+
if (state.yes || !state.interactive) return answerWithoutAsking(question, fallback, state);
|
|
1927
2799
|
if (useClack()) return renderWithClack(question, (r) => r.confirm(question, fallback));
|
|
1928
2800
|
let hint = "(y/n)";
|
|
1929
2801
|
if (fallback === true) hint = "(Y/n)";
|
|
@@ -1942,40 +2814,16 @@ function makePromptSurface(invocation) {
|
|
|
1942
2814
|
},
|
|
1943
2815
|
select: async (question, options, opts) => {
|
|
1944
2816
|
const fallback = opts?.default;
|
|
1945
|
-
if (state.yes || !state.interactive)
|
|
1946
|
-
if (fallback === void 0) throw promptUnanswerable(question, state);
|
|
1947
|
-
return fallback;
|
|
1948
|
-
}
|
|
2817
|
+
if (state.yes || !state.interactive) return answerWithoutAsking(question, fallback, state);
|
|
1949
2818
|
if (useClack()) return renderWithClack(question, (r) => r.select(question, options, fallback));
|
|
1950
|
-
|
|
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;
|
|
2819
|
+
return askSelect(question, options, fallback);
|
|
1964
2820
|
},
|
|
1965
2821
|
text: async (question, opts) => {
|
|
1966
2822
|
const fallback = opts?.default;
|
|
1967
|
-
if (state.yes || !state.interactive)
|
|
1968
|
-
|
|
1969
|
-
|
|
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;
|
|
2823
|
+
if (state.yes || !state.interactive) return answerWithoutAsking(question, fallback, state);
|
|
2824
|
+
if (!useClack()) return askText(question, fallback);
|
|
2825
|
+
const value = await renderWithClack(question, (r) => r.text(question, opts?.placeholder, fallback));
|
|
2826
|
+
return value === "" ? fallback ?? "" : value;
|
|
1979
2827
|
},
|
|
1980
2828
|
browserWait: async ({ url, message, poll, timeout, interval }) => {
|
|
1981
2829
|
if (!state.interactive) throw browserWaitUnavailable(message, url);
|
|
@@ -2038,6 +2886,7 @@ function makeSpawn(invocation, def) {
|
|
|
2038
2886
|
if (!def.maySpawn) throw constructionError(`command '${state.commandId}' called ctx.spawn without declaring maySpawn`);
|
|
2039
2887
|
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
2888
|
if (state.activePrompts > 0) throw constructionError(`command '${state.commandId}' called ctx.spawn while a prompt owned the terminal`);
|
|
2889
|
+
if (state.packageOperationRunning) throw constructionError(`command '${state.commandId}' called ctx.spawn while a package operation was still running`);
|
|
2041
2890
|
const spawnChild = invocation.runtime.spawn;
|
|
2042
2891
|
if (spawnChild === void 0) throw new Error("@prisma/cli-engine: the command declares maySpawn but the Runtime supplies no spawn adapter");
|
|
2043
2892
|
const terminal = {
|
|
@@ -2218,12 +3067,31 @@ function makeUi(colorEnabled, stderr) {
|
|
|
2218
3067
|
};
|
|
2219
3068
|
}
|
|
2220
3069
|
/** Materializes ONLY the active format's presentation functions, at the
|
|
2221
|
-
* return site: human → human + stdout + next; json → json + next.
|
|
3070
|
+
* return site: human → human + stdout + next; json → json + next.
|
|
3071
|
+
*
|
|
3072
|
+
* `stdout` and `next` may be absent at runtime, so both are called with
|
|
3073
|
+
* `?.()`. `Presentations` requires all four, so no command compiled
|
|
3074
|
+
* against this engine can omit one — but `@prisma/orm-toolchain` is
|
|
3075
|
+
* built against engine `0.0.9`, where three of the four were optional,
|
|
3076
|
+
* and its published commands took that up: `migration list` declares
|
|
3077
|
+
* `human` and `json` and neither of the others. Calling them
|
|
3078
|
+
* unconditionally makes it exit 2 — `stdout` in human mode, `next` in
|
|
3079
|
+
* both.
|
|
3080
|
+
*
|
|
3081
|
+
* `json` is called unconditionally, and stays that way: a missing json
|
|
3082
|
+
* presentation is the defect this change removes, and every ORM command
|
|
3083
|
+
* already declares one.
|
|
3084
|
+
*
|
|
3085
|
+
* This is version skew in our own code, not a foreign contract. The fix
|
|
3086
|
+
* is in prisma/prisma: declare the missing presentations in the ORM
|
|
3087
|
+
* commands and build orm-toolchain against this engine, where the type
|
|
3088
|
+
* refuses to compile without them. Delete both `?.()` when that
|
|
3089
|
+
* version is pinned here. */
|
|
2222
3090
|
function materializePresentation(state, ui, presentations) {
|
|
2223
3091
|
if (state.format === "json") return {
|
|
2224
3092
|
human: [],
|
|
2225
3093
|
stdout: [],
|
|
2226
|
-
json: presentations.json
|
|
3094
|
+
json: presentations.json(),
|
|
2227
3095
|
next: presentations.next?.() ?? []
|
|
2228
3096
|
};
|
|
2229
3097
|
return {
|
|
@@ -2233,7 +3101,7 @@ function materializePresentation(state, ui, presentations) {
|
|
|
2233
3101
|
next: presentations.next?.() ?? []
|
|
2234
3102
|
};
|
|
2235
3103
|
}
|
|
2236
|
-
function makeContext(invocation, def, config,
|
|
3104
|
+
function makeContext(invocation, def, config, capabilities) {
|
|
2237
3105
|
const state = invocation.state;
|
|
2238
3106
|
const ui = makeUi(state.colorEnabled, invocation.runtime.stderr);
|
|
2239
3107
|
const present = (outcome, presentations) => {
|
|
@@ -2266,9 +3134,18 @@ function makeContext(invocation, def, config, managesCredentials) {
|
|
|
2266
3134
|
signal: invocation.signal,
|
|
2267
3135
|
cwd: invocation.runtime.cwd,
|
|
2268
3136
|
env: invocation.runtime.env,
|
|
2269
|
-
|
|
3137
|
+
host: invocation.runtime.host,
|
|
3138
|
+
isCI: resolveIsCI(invocation.runtime),
|
|
3139
|
+
requireDependency: async (specifier) => {
|
|
3140
|
+
if (dependencyResolvable(specifier, invocation.runtime.cwd)) return okVoid();
|
|
3141
|
+
return notOk(missingDependencyError(specifier, await resolvePackageManager({
|
|
3142
|
+
cwd: invocation.runtime.cwd,
|
|
3143
|
+
env: invocation.runtime.env,
|
|
3144
|
+
host: invocation.runtime.packageManager
|
|
3145
|
+
})));
|
|
3146
|
+
}
|
|
2270
3147
|
};
|
|
2271
|
-
if (managesCredentials) Object.defineProperty(context, "credentialManager", {
|
|
3148
|
+
if (capabilities.managesCredentials) Object.defineProperty(context, "credentialManager", {
|
|
2272
3149
|
enumerable: true,
|
|
2273
3150
|
get() {
|
|
2274
3151
|
const manager = invocation.runtime.credentialManager;
|
|
@@ -2276,6 +3153,10 @@ function makeContext(invocation, def, config, managesCredentials) {
|
|
|
2276
3153
|
return manager;
|
|
2277
3154
|
}
|
|
2278
3155
|
});
|
|
3156
|
+
if (capabilities.installsPackages) Object.defineProperty(context, "packages", {
|
|
3157
|
+
enumerable: true,
|
|
3158
|
+
value: makePackageOperations(invocation)
|
|
3159
|
+
});
|
|
2279
3160
|
return context;
|
|
2280
3161
|
}
|
|
2281
3162
|
//#endregion
|
|
@@ -2303,13 +3184,40 @@ function aliasMap(def) {
|
|
|
2303
3184
|
return aliases;
|
|
2304
3185
|
}
|
|
2305
3186
|
/**
|
|
3187
|
+
* The key a long token marks. Long tokens match in both the kebab and
|
|
3188
|
+
* camel spellings (the scanner allows kebab-for-camel), and a
|
|
3189
|
+
* `--no-<flag>` token marks its base flag. Values are irrelevant here:
|
|
3190
|
+
* `--name=value` is cut at the `=` before matching.
|
|
3191
|
+
*/
|
|
3192
|
+
function longFlagKey(token, declared) {
|
|
3193
|
+
const equals = token.indexOf("=");
|
|
3194
|
+
const raw = token.slice(2, equals === -1 ? void 0 : equals);
|
|
3195
|
+
const exact = camelCase(raw);
|
|
3196
|
+
if (declared.has(exact)) return exact;
|
|
3197
|
+
if (!raw.startsWith("no-")) return;
|
|
3198
|
+
const negated = camelCase(raw.slice(3));
|
|
3199
|
+
return declared.has(negated) ? negated : void 0;
|
|
3200
|
+
}
|
|
3201
|
+
function shortFlagKeys(token, declared, aliases) {
|
|
3202
|
+
const keys = [];
|
|
3203
|
+
for (const char of token.slice(1)) {
|
|
3204
|
+
const key = aliases.get(char);
|
|
3205
|
+
if (key !== void 0 && declared.has(key)) keys.push(key);
|
|
3206
|
+
}
|
|
3207
|
+
return keys;
|
|
3208
|
+
}
|
|
3209
|
+
function tokenFlagKeys(token, declared, aliases) {
|
|
3210
|
+
if (token.startsWith("--")) {
|
|
3211
|
+
const key = longFlagKey(token, declared);
|
|
3212
|
+
return key === void 0 ? [] : [key];
|
|
3213
|
+
}
|
|
3214
|
+
if (token.startsWith("-") && token.length > 1) return shortFlagKeys(token, declared, aliases);
|
|
3215
|
+
return [];
|
|
3216
|
+
}
|
|
3217
|
+
/**
|
|
2306
3218
|
* The flag keys explicitly present on argv, resolved against the
|
|
2307
|
-
* command's declared keys and aliases.
|
|
2308
|
-
*
|
|
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.
|
|
3219
|
+
* command's declared keys and aliases. Everything after a bare `--` is
|
|
3220
|
+
* positional and never consulted.
|
|
2313
3221
|
*/
|
|
2314
3222
|
function explicitFlagKeys(def, declared, argv) {
|
|
2315
3223
|
const declaredSet = new Set(declared);
|
|
@@ -2317,24 +3225,7 @@ function explicitFlagKeys(def, declared, argv) {
|
|
|
2317
3225
|
const explicit = /* @__PURE__ */ new Set();
|
|
2318
3226
|
for (const token of argv) {
|
|
2319
3227
|
if (token === "--") break;
|
|
2320
|
-
|
|
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
|
-
}
|
|
3228
|
+
for (const key of tokenFlagKeys(token, declaredSet, aliases)) explicit.add(key);
|
|
2338
3229
|
}
|
|
2339
3230
|
return explicit;
|
|
2340
3231
|
}
|
|
@@ -2374,6 +3265,12 @@ function stricliFlagParameter(spec) {
|
|
|
2374
3265
|
brief: spec.brief,
|
|
2375
3266
|
default: false
|
|
2376
3267
|
};
|
|
3268
|
+
case "optionalBoolean": return {
|
|
3269
|
+
kind: "boolean",
|
|
3270
|
+
brief: spec.brief,
|
|
3271
|
+
optional: true,
|
|
3272
|
+
withNegated: true
|
|
3273
|
+
};
|
|
2377
3274
|
case "enum": return {
|
|
2378
3275
|
kind: "enum",
|
|
2379
3276
|
brief: spec.brief,
|
|
@@ -2538,6 +3435,315 @@ function usageErrorCode(stricliExitCode) {
|
|
|
2538
3435
|
if (stricliExitCode === -4) return "CLI.INVALID_ARGUMENTS";
|
|
2539
3436
|
}
|
|
2540
3437
|
//#endregion
|
|
3438
|
+
//#region src/execution/help.ts
|
|
3439
|
+
/**
|
|
3440
|
+
* Engine-rendered help: the command tree drawn with the same tones the
|
|
3441
|
+
* block renderer uses, so help is themed like every other surface.
|
|
3442
|
+
* stricli's text_en renderer is never consulted — root and group help
|
|
3443
|
+
* list `name brief` rows, and full signatures appear only on the leaf
|
|
3444
|
+
* that owns them.
|
|
3445
|
+
*/
|
|
3446
|
+
const RAIL = "│";
|
|
3447
|
+
const GAP = " ";
|
|
3448
|
+
const WRAP_WIDTH = 76;
|
|
3449
|
+
function flagTokens(argv) {
|
|
3450
|
+
const terminator = argv.indexOf("--");
|
|
3451
|
+
return terminator === -1 ? argv : argv.slice(0, terminator);
|
|
3452
|
+
}
|
|
3453
|
+
function helpFlagGiven(argv) {
|
|
3454
|
+
return flagTokens(argv).some((token) => token === "-h" || token === "--help" || token === "--help-all");
|
|
3455
|
+
}
|
|
3456
|
+
/** The colour decision available before the shared flags are parsed,
|
|
3457
|
+
* read from raw argv: explicit flag, then NO_COLOR, then the TTY of
|
|
3458
|
+
* the stream about to be written. Help and pre-mount failures both
|
|
3459
|
+
* render through this; applySharedFlags re-resolves once a command
|
|
3460
|
+
* actually parses. */
|
|
3461
|
+
function preParseColorEnabled(argv, runtime, stream) {
|
|
3462
|
+
const tokens = flagTokens(argv);
|
|
3463
|
+
if (tokens.includes("--no-color")) return false;
|
|
3464
|
+
if (tokens.includes("--color")) return true;
|
|
3465
|
+
if (runtime.env.NO_COLOR !== void 0) return false;
|
|
3466
|
+
return runtime.isTty[stream];
|
|
3467
|
+
}
|
|
3468
|
+
/** The command path the user asked help for: the leading non-flag
|
|
3469
|
+
* tokens, resolved as far as the tree recognizes them. */
|
|
3470
|
+
function helpPath(argv) {
|
|
3471
|
+
const segments = [];
|
|
3472
|
+
for (const token of argv) {
|
|
3473
|
+
if (token.startsWith("-")) break;
|
|
3474
|
+
segments.push(token);
|
|
3475
|
+
}
|
|
3476
|
+
return segments;
|
|
3477
|
+
}
|
|
3478
|
+
/** Walks as far as the segments stay recognized; help for `project
|
|
3479
|
+
* frobnicate` is project's help, not a dead end. */
|
|
3480
|
+
function resolveTarget(root, segments) {
|
|
3481
|
+
let node = root;
|
|
3482
|
+
const path = [];
|
|
3483
|
+
for (const segment of segments) {
|
|
3484
|
+
const entry = node.commands.get(segment);
|
|
3485
|
+
if (entry !== void 0) return {
|
|
3486
|
+
target: {
|
|
3487
|
+
kind: "leaf",
|
|
3488
|
+
entry
|
|
3489
|
+
},
|
|
3490
|
+
path: [...path, segment]
|
|
3491
|
+
};
|
|
3492
|
+
const child = node.children.get(segment);
|
|
3493
|
+
if (child === void 0) break;
|
|
3494
|
+
node = child;
|
|
3495
|
+
path.push(segment);
|
|
3496
|
+
}
|
|
3497
|
+
return {
|
|
3498
|
+
target: {
|
|
3499
|
+
kind: "node",
|
|
3500
|
+
node
|
|
3501
|
+
},
|
|
3502
|
+
path
|
|
3503
|
+
};
|
|
3504
|
+
}
|
|
3505
|
+
/** A BARE group invocation (`prisma-cli project`, or no argv at all)
|
|
3506
|
+
* is a help request; anything carrying flags or extra tokens is not —
|
|
3507
|
+
* `cli --unknown` and `cli project --frobnicate` must reach routing
|
|
3508
|
+
* and usage validation, not exit 0 with a help card. A bare leaf is a
|
|
3509
|
+
* command run and is left alone. */
|
|
3510
|
+
function bareGroupInvocation(root, argv) {
|
|
3511
|
+
const segments = helpPath(argv);
|
|
3512
|
+
if (segments.length !== argv.length) return false;
|
|
3513
|
+
if (segments.length === 0) return true;
|
|
3514
|
+
const { target, path } = resolveTarget(root, segments);
|
|
3515
|
+
return target.kind === "node" && path.length === segments.length;
|
|
3516
|
+
}
|
|
3517
|
+
function renderHelp(spec, root, argv, colorEnabled, out) {
|
|
3518
|
+
const paint = makePaint(colorEnabled);
|
|
3519
|
+
const { target, path } = resolveTarget(root, helpPath(argv));
|
|
3520
|
+
const lines = [];
|
|
3521
|
+
if (target.kind === "leaf") renderLeafHelp(spec, target.entry, path, paint, lines);
|
|
3522
|
+
else renderNodeHelp(spec, target.node, path, paint, lines);
|
|
3523
|
+
out.write(`${lines.join("\n")}\n`);
|
|
3524
|
+
}
|
|
3525
|
+
/** `prisma-cli project → Manage and inspect your Prisma projects` */
|
|
3526
|
+
function header(spec, path, tagline, paint) {
|
|
3527
|
+
const name = paint("emphasis", [spec.name, ...path].join(" "));
|
|
3528
|
+
if (tagline === void 0 || tagline === "") return name;
|
|
3529
|
+
return `${name} ${paint("muted", `→ ${tagline}`)}`;
|
|
3530
|
+
}
|
|
3531
|
+
function rail(paint, rest = "") {
|
|
3532
|
+
return rest === "" ? paint("structure", RAIL) : `${paint("structure", RAIL)}${GAP}${rest}`;
|
|
3533
|
+
}
|
|
3534
|
+
function sectionLabel(paint, label) {
|
|
3535
|
+
return rail(paint, paint("muted", label));
|
|
3536
|
+
}
|
|
3537
|
+
/** Two-column rows under the rail: name in the accent, brief plain. */
|
|
3538
|
+
function railRows(rows, paint, lines) {
|
|
3539
|
+
const width = Math.max(0, ...rows.map((row) => textWidth(row.name)));
|
|
3540
|
+
for (const row of rows) {
|
|
3541
|
+
const pad = " ".repeat(width - textWidth(row.name));
|
|
3542
|
+
const suffix = row.suffix === void 0 || row.suffix === "" ? "" : ` ${paint("muted", row.suffix)}`;
|
|
3543
|
+
lines.push(rail(paint, `${paint("identifier", row.name)}${pad}${GAP}${row.brief}${suffix}`));
|
|
3544
|
+
}
|
|
3545
|
+
}
|
|
3546
|
+
function wrap(text, width) {
|
|
3547
|
+
const lines = [];
|
|
3548
|
+
for (const paragraph of text.split("\n")) {
|
|
3549
|
+
if (paragraph === "") {
|
|
3550
|
+
lines.push("");
|
|
3551
|
+
continue;
|
|
3552
|
+
}
|
|
3553
|
+
let line = "";
|
|
3554
|
+
for (const word of paragraph.split(" ")) if (line !== "" && line.length + 1 + word.length > width) {
|
|
3555
|
+
lines.push(line);
|
|
3556
|
+
line = word;
|
|
3557
|
+
} else line = line === "" ? word : `${line} ${word}`;
|
|
3558
|
+
if (line !== "") lines.push(line);
|
|
3559
|
+
}
|
|
3560
|
+
return lines;
|
|
3561
|
+
}
|
|
3562
|
+
function proseLines(text, paint, lines, tone = "plain") {
|
|
3563
|
+
for (const line of wrap(text, WRAP_WIDTH)) lines.push(rail(paint, tone === "muted" ? paint("muted", line) : line));
|
|
3564
|
+
}
|
|
3565
|
+
function exampleLines(examples, cliName, paint, lines) {
|
|
3566
|
+
if (examples.length === 0) return;
|
|
3567
|
+
lines.push(rail(paint));
|
|
3568
|
+
lines.push(sectionLabel(paint, "Examples"));
|
|
3569
|
+
for (const example of examples) lines.push(rail(paint, `${GAP}${paint("muted", "$")} ${resolveExample(example, cliName)}`));
|
|
3570
|
+
}
|
|
3571
|
+
function docsLine(url, paint, lines) {
|
|
3572
|
+
if (url === void 0) return;
|
|
3573
|
+
lines.push(rail(paint));
|
|
3574
|
+
lines.push(rail(paint, `${paint("muted", "Docs")}${GAP}${paint("link", url)}`));
|
|
3575
|
+
}
|
|
3576
|
+
/** `--interactive/--no-interactive`, `-q, --quiet`, `--config <path>` —
|
|
3577
|
+
* one spelling rule for shared and declared flags alike. */
|
|
3578
|
+
function flagLabel(key, spec) {
|
|
3579
|
+
const kebab = kebabCase(key);
|
|
3580
|
+
return `${spec.alias === void 0 ? " " : `-${spec.alias},`} --${kebab}${spec.withNegated === true ? `/--no-${kebab}` : ""}${spec.placeholder === void 0 ? "" : ` <${spec.placeholder}>`}${spec.variadic === true ? "..." : ""}`;
|
|
3581
|
+
}
|
|
3582
|
+
function sharedFlagRows() {
|
|
3583
|
+
const aliasByKey = new Map(Object.entries(SHARED_ALIASES).map(([alias, key]) => [key, alias]));
|
|
3584
|
+
return [
|
|
3585
|
+
...Object.entries(SHARED_FLAG_PARAMETERS).map(([key, spec]) => {
|
|
3586
|
+
const record = spec;
|
|
3587
|
+
return {
|
|
3588
|
+
name: flagLabel(key, {
|
|
3589
|
+
...record,
|
|
3590
|
+
alias: aliasByKey.get(key)
|
|
3591
|
+
}),
|
|
3592
|
+
brief: record.brief,
|
|
3593
|
+
suffix: record.values === void 0 ? void 0 : record.values.join("|")
|
|
3594
|
+
};
|
|
3595
|
+
}),
|
|
3596
|
+
{
|
|
3597
|
+
name: `-h, --help`,
|
|
3598
|
+
brief: "Print help for a command"
|
|
3599
|
+
},
|
|
3600
|
+
{
|
|
3601
|
+
name: ` --version`,
|
|
3602
|
+
brief: "Print the CLI version and exit"
|
|
3603
|
+
}
|
|
3604
|
+
];
|
|
3605
|
+
}
|
|
3606
|
+
function declaredFlagRows(def) {
|
|
3607
|
+
return Object.entries(def.args.flags).map(([key, spec]) => {
|
|
3608
|
+
const runtime = flagRuntime(spec);
|
|
3609
|
+
return {
|
|
3610
|
+
name: flagLabel(key, {
|
|
3611
|
+
alias: runtime.alias,
|
|
3612
|
+
placeholder: runtime.type === "boolean" || runtime.type === "optionalBoolean" ? void 0 : runtime.placeholder ?? "value",
|
|
3613
|
+
withNegated: runtime.type === "optionalBoolean",
|
|
3614
|
+
variadic: runtime.type === "repeated"
|
|
3615
|
+
}),
|
|
3616
|
+
brief: runtime.brief,
|
|
3617
|
+
suffix: flagSuffix(runtime)
|
|
3618
|
+
};
|
|
3619
|
+
});
|
|
3620
|
+
}
|
|
3621
|
+
function flagSuffix(runtime) {
|
|
3622
|
+
const parts = [];
|
|
3623
|
+
if (runtime.values !== void 0 && runtime.values.length > 0) parts.push(runtime.values.join("|"));
|
|
3624
|
+
if (runtime.type === "requiredString") parts.push("required");
|
|
3625
|
+
if (runtime.default !== void 0) parts.push(`default: ${String(runtime.default)}`);
|
|
3626
|
+
return parts.length === 0 ? void 0 : `(${parts.join("; ")})`;
|
|
3627
|
+
}
|
|
3628
|
+
function positionalUsage(def) {
|
|
3629
|
+
return Object.values(def.args.positionals).map((spec) => {
|
|
3630
|
+
const runtime = positionalRuntime(spec);
|
|
3631
|
+
if (runtime.type === "optionalString") return `[${runtime.placeholder}]`;
|
|
3632
|
+
if (runtime.type === "variadic") return `[${runtime.placeholder}...]`;
|
|
3633
|
+
return `<${runtime.placeholder}>`;
|
|
3634
|
+
}).join(" ");
|
|
3635
|
+
}
|
|
3636
|
+
function requiredFlagUsage(def) {
|
|
3637
|
+
return Object.entries(def.args.flags).flatMap(([key, spec]) => {
|
|
3638
|
+
const runtime = flagRuntime(spec);
|
|
3639
|
+
return runtime.type === "requiredString" ? [`--${kebabCase(key)} <${runtime.placeholder ?? "value"}>`] : [];
|
|
3640
|
+
}).join(" ");
|
|
3641
|
+
}
|
|
3642
|
+
/** Mount order, not map-partition order: a leaf and a group list in
|
|
3643
|
+
* the order their first command was mounted. */
|
|
3644
|
+
function nodeRows(spec, node, path) {
|
|
3645
|
+
const groupPath = path.join(" ");
|
|
3646
|
+
const depth = path.length;
|
|
3647
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3648
|
+
const rows = [];
|
|
3649
|
+
for (const mounted of Object.keys(spec.commands)) {
|
|
3650
|
+
const segments = mounted.split(" ");
|
|
3651
|
+
if (segments.length <= depth || segments.slice(0, depth).join(" ") !== groupPath) continue;
|
|
3652
|
+
const name = segments[depth];
|
|
3653
|
+
if (seen.has(name)) continue;
|
|
3654
|
+
seen.add(name);
|
|
3655
|
+
const entry = node.commands.get(name);
|
|
3656
|
+
if (entry !== void 0) rows.push({
|
|
3657
|
+
name: usageName(name, entry.def),
|
|
3658
|
+
brief: entry.def.help.summary
|
|
3659
|
+
});
|
|
3660
|
+
else if (node.children.has(name)) {
|
|
3661
|
+
const childPath = depth === 0 ? name : `${groupPath} ${name}`;
|
|
3662
|
+
rows.push({
|
|
3663
|
+
name,
|
|
3664
|
+
brief: spec.groups[childPath]?.brief ?? ""
|
|
3665
|
+
});
|
|
3666
|
+
}
|
|
3667
|
+
}
|
|
3668
|
+
return rows;
|
|
3669
|
+
}
|
|
3670
|
+
function renderNodeHelp(spec, node, path, paint, lines) {
|
|
3671
|
+
const atRoot = path.length === 0;
|
|
3672
|
+
const groupPath = path.join(" ");
|
|
3673
|
+
const tagline = atRoot ? spec.help?.tagline : spec.groups[groupPath]?.brief;
|
|
3674
|
+
lines.push(header(spec, path, tagline, paint));
|
|
3675
|
+
lines.push("");
|
|
3676
|
+
railRows(nodeRows(spec, node, path), paint, lines);
|
|
3677
|
+
const description = atRoot ? spec.help?.description : spec.groups[groupPath]?.description;
|
|
3678
|
+
if (description !== void 0) {
|
|
3679
|
+
lines.push(rail(paint));
|
|
3680
|
+
proseLines(description, paint, lines);
|
|
3681
|
+
}
|
|
3682
|
+
if (atRoot) {
|
|
3683
|
+
lines.push(rail(paint));
|
|
3684
|
+
lines.push(sectionLabel(paint, "Global options"));
|
|
3685
|
+
railRows(sharedFlagRows(), paint, lines);
|
|
3686
|
+
exampleLines(spec.help?.examples ?? [], spec.name, paint, lines);
|
|
3687
|
+
docsLine(spec.help?.docsUrl, paint, lines);
|
|
3688
|
+
} else {
|
|
3689
|
+
lines.push(rail(paint));
|
|
3690
|
+
lines.push(rail(paint, paint("muted", `Run '${spec.name} ${groupPath} <command> --help' for details on a command.`)));
|
|
3691
|
+
}
|
|
3692
|
+
lines.push("");
|
|
3693
|
+
}
|
|
3694
|
+
/** `link [id-or-name]` — the row a group lists for a leaf: name plus
|
|
3695
|
+
* positional shape, briefs carry the rest. */
|
|
3696
|
+
function usageName(name, def) {
|
|
3697
|
+
const positionals = positionalUsage(def);
|
|
3698
|
+
return positionals === "" ? name : `${name} ${positionals}`;
|
|
3699
|
+
}
|
|
3700
|
+
function renderLeafHelp(spec, entry, path, paint, lines) {
|
|
3701
|
+
const def = entry.def;
|
|
3702
|
+
lines.push(header(spec, path, def.help.summary, paint));
|
|
3703
|
+
lines.push("");
|
|
3704
|
+
const usageParts = [
|
|
3705
|
+
spec.name,
|
|
3706
|
+
...path,
|
|
3707
|
+
requiredFlagUsage(def),
|
|
3708
|
+
"[options]",
|
|
3709
|
+
positionalUsage(def)
|
|
3710
|
+
].filter((part) => part !== "");
|
|
3711
|
+
lines.push(sectionLabel(paint, "Usage"));
|
|
3712
|
+
lines.push(rail(paint, `${GAP}${paint("muted", "$")} ${paint("emphasis", usageParts.join(" "))}`));
|
|
3713
|
+
if (def.help.description !== void 0) {
|
|
3714
|
+
lines.push(rail(paint));
|
|
3715
|
+
proseLines(def.help.description, paint, lines);
|
|
3716
|
+
}
|
|
3717
|
+
if (def.maySpawn) {
|
|
3718
|
+
lines.push(rail(paint));
|
|
3719
|
+
lines.push(rail(paint, paint("muted", NO_JSON_NOTE)));
|
|
3720
|
+
}
|
|
3721
|
+
const positionalEntries = Object.values(def.args.positionals).map((spec) => positionalRuntime(spec));
|
|
3722
|
+
if (positionalEntries.length > 0) {
|
|
3723
|
+
lines.push(rail(paint));
|
|
3724
|
+
lines.push(sectionLabel(paint, "Arguments"));
|
|
3725
|
+
railRows(positionalEntries.map((runtime) => ({
|
|
3726
|
+
name: runtime.placeholder,
|
|
3727
|
+
brief: runtime.brief,
|
|
3728
|
+
suffix: runtime.type === "optionalString" ? "(optional)" : void 0
|
|
3729
|
+
})), paint, lines);
|
|
3730
|
+
}
|
|
3731
|
+
const flagRows = declaredFlagRows(def);
|
|
3732
|
+
if (flagRows.length > 0) {
|
|
3733
|
+
lines.push(rail(paint));
|
|
3734
|
+
lines.push(sectionLabel(paint, "Options"));
|
|
3735
|
+
railRows(flagRows, paint, lines);
|
|
3736
|
+
}
|
|
3737
|
+
if (def.kind !== "server-command") {
|
|
3738
|
+
const sharedNames = [...Object.keys(SHARED_FLAG_PARAMETERS).map((key) => `--${kebabCase(key)}`)].join(", ");
|
|
3739
|
+
lines.push(rail(paint));
|
|
3740
|
+
proseLines(`Global options also apply: ${sharedNames}. Run '${spec.name} --help' for details.`, paint, lines, "muted");
|
|
3741
|
+
}
|
|
3742
|
+
exampleLines(def.help.examples, spec.name, paint, lines);
|
|
3743
|
+
docsLine(entry.docsBaseUrl, paint, lines);
|
|
3744
|
+
lines.push("");
|
|
3745
|
+
}
|
|
3746
|
+
//#endregion
|
|
2541
3747
|
//#region src/execution/settlement.ts
|
|
2542
3748
|
function undocumentedExitCode(def, exitCode) {
|
|
2543
3749
|
if (exitCode === 0) return;
|
|
@@ -2564,7 +3770,7 @@ function settleCompleted(invocation, def, presented) {
|
|
|
2564
3770
|
envelope: {
|
|
2565
3771
|
ok: true,
|
|
2566
3772
|
commandId: state.commandId,
|
|
2567
|
-
result: presented.presentation.json
|
|
3773
|
+
result: presented.presentation.json,
|
|
2568
3774
|
exitCode,
|
|
2569
3775
|
diagnostics: presented.diagnostics.map((diagnostic) => withDocsUrl(state, diagnostic)),
|
|
2570
3776
|
nextActions: presented.presentation.next
|
|
@@ -2580,6 +3786,15 @@ function diagnosticOf(error) {
|
|
|
2580
3786
|
const { ok: _ok, ...diagnostic } = error.toEnvelope();
|
|
2581
3787
|
return diagnostic;
|
|
2582
3788
|
}
|
|
3789
|
+
/** The list is typed, but nothing at runtime has checked it: an error
|
|
3790
|
+
* built by another copy of the engine passes `CliStructuredError.is`
|
|
3791
|
+
* on its name, its code and its `toEnvelope` alone, and a handler's
|
|
3792
|
+
* `notOk` failure is checked by nothing at all. A value that is not a
|
|
3793
|
+
* list settles as no accompanying findings rather than reaching the
|
|
3794
|
+
* human renderer and the json envelope as garbage. */
|
|
3795
|
+
function accompanyingFindings(diagnostics) {
|
|
3796
|
+
return Array.isArray(diagnostics) ? diagnostics : [];
|
|
3797
|
+
}
|
|
2583
3798
|
function settleErrored(invocation, error, diagnostics = []) {
|
|
2584
3799
|
const state = invocation.state;
|
|
2585
3800
|
state.settledExitCode = error.code === "CLI.PROMPT_CANCELLED" ? 3 : 2;
|
|
@@ -2587,7 +3802,7 @@ function settleErrored(invocation, error, diagnostics = []) {
|
|
|
2587
3802
|
ok: false,
|
|
2588
3803
|
commandId: state.commandId,
|
|
2589
3804
|
error: diagnosticOf(error),
|
|
2590
|
-
diagnostics,
|
|
3805
|
+
diagnostics: accompanyingFindings(diagnostics),
|
|
2591
3806
|
nextActions: error.nextActions
|
|
2592
3807
|
});
|
|
2593
3808
|
}
|
|
@@ -2619,7 +3834,7 @@ function isAbortCause(cause, signal) {
|
|
|
2619
3834
|
}
|
|
2620
3835
|
function settleThrown(invocation, cause) {
|
|
2621
3836
|
if (isAbortCause(cause, invocation.signal)) settleAborted(invocation);
|
|
2622
|
-
else if (CliStructuredError.is(cause)) settleErrored(invocation, cause);
|
|
3837
|
+
else if (CliStructuredError.is(cause)) settleErrored(invocation, cause, cause.diagnostics);
|
|
2623
3838
|
else settleBug(invocation, cause);
|
|
2624
3839
|
}
|
|
2625
3840
|
function settleAborted(invocation) {
|
|
@@ -2670,7 +3885,7 @@ function settleChildStatus(invocation, def, settlement) {
|
|
|
2670
3885
|
if (!def.maySpawn) throw new Error(`@prisma/cli-engine: command '${invocation.state.commandId}' returned exitWithChildStatus without declaring maySpawn — only a command that hands the terminal to another program may settle with that program's status`);
|
|
2671
3886
|
const child = invocation.state.lastChild;
|
|
2672
3887
|
if (child === void 0) throw new Error(`@prisma/cli-engine: command '${invocation.state.commandId}' returned exitWithChildStatus without a child having run — that settlement reports the status of a child ctx.spawn started, and this run started none`);
|
|
2673
|
-
if (child.signal === null) for (const action of settlement.nextActions) invocation.runtime.stderr.write(`${renderNextAction(action)}\n`);
|
|
3888
|
+
if (child.signal === null) for (const action of settlement.nextActions) invocation.runtime.stderr.write(`${renderNextAction(action, makePaint(invocation.state.colorEnabled))}\n`);
|
|
2674
3889
|
settleVerbatimExitCode(invocation, childExitCode(child));
|
|
2675
3890
|
}
|
|
2676
3891
|
/** A session command that returned ok shut down cleanly: no
|
|
@@ -2729,9 +3944,8 @@ function emitErrored(invocation, raw) {
|
|
|
2729
3944
|
});
|
|
2730
3945
|
return;
|
|
2731
3946
|
}
|
|
2732
|
-
const
|
|
2733
|
-
|
|
2734
|
-
for (const diagnostic of envelope.diagnostics) writeDiagnostic(stderr, diagnostic);
|
|
3947
|
+
const paint = makePaint(invocation.state.colorEnabled);
|
|
3948
|
+
writeSections([envelope.error, ...envelope.diagnostics].map((diagnostic) => diagnosticSection(diagnostic, paint)), invocation.runtime.stderr);
|
|
2735
3949
|
}
|
|
2736
3950
|
/** `--version` prints createCli's version and exits 0. In json mode the
|
|
2737
3951
|
* version travels as the run's single result frame. */
|
|
@@ -2808,21 +4022,63 @@ function settleUnhandled(spec, invocation, stricliExitCode) {
|
|
|
2808
4022
|
const full = captured.length > 0 ? captured : "The command failed unexpectedly";
|
|
2809
4023
|
const summary = firstLine(full);
|
|
2810
4024
|
const remainder = full.slice(full.indexOf("\n") + 1).trim();
|
|
4025
|
+
const code = usageErrorCode(raw) ?? "CLI.INTERNAL_ERROR";
|
|
4026
|
+
const nextActions = code === "CLI.UNKNOWN_COMMAND" ? unknownCommandActions(spec, state) : [];
|
|
2811
4027
|
emitErrored(invocation, {
|
|
2812
4028
|
ok: false,
|
|
2813
4029
|
commandId: segments.join("."),
|
|
2814
4030
|
error: {
|
|
2815
|
-
code
|
|
4031
|
+
code,
|
|
2816
4032
|
severity: "error",
|
|
2817
4033
|
summary,
|
|
2818
4034
|
...usage && full.includes("\n") && remainder.length > 0 ? { why: remainder } : {},
|
|
2819
|
-
nextActions
|
|
4035
|
+
nextActions
|
|
2820
4036
|
},
|
|
2821
4037
|
diagnostics: [],
|
|
2822
|
-
nextActions
|
|
4038
|
+
nextActions
|
|
2823
4039
|
});
|
|
2824
4040
|
return usage ? 2 : 1;
|
|
2825
4041
|
}
|
|
4042
|
+
function editDistance(a, b) {
|
|
4043
|
+
const rows = a.length + 1;
|
|
4044
|
+
const cols = b.length + 1;
|
|
4045
|
+
const d = Array.from({ length: rows * cols }, () => 0);
|
|
4046
|
+
for (let i = 0; i < rows; i += 1) d[i * cols] = i;
|
|
4047
|
+
for (let j = 0; j < cols; j += 1) d[j] = j;
|
|
4048
|
+
for (let i = 1; i < rows; i += 1) for (let j = 1; j < cols; j += 1) {
|
|
4049
|
+
const substitution = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
4050
|
+
d[i * cols + j] = Math.min(d[(i - 1) * cols + j] + 1, d[i * cols + j - 1] + 1, d[(i - 1) * cols + j - 1] + substitution);
|
|
4051
|
+
}
|
|
4052
|
+
return d[rows * cols - 1];
|
|
4053
|
+
}
|
|
4054
|
+
/** A misspelling is close (edit distance ≤ 2, and short paths tighter);
|
|
4055
|
+
* anything further is not a suggestion worth making. Every unknown
|
|
4056
|
+
* command at least learns where the command list is. */
|
|
4057
|
+
function unknownCommandActions(spec, state) {
|
|
4058
|
+
const attempted = [];
|
|
4059
|
+
for (const token of state.argv) {
|
|
4060
|
+
if (token.startsWith("-")) break;
|
|
4061
|
+
attempted.push(token);
|
|
4062
|
+
}
|
|
4063
|
+
const typed = attempted.join(" ");
|
|
4064
|
+
const candidates = new Set(Object.keys(spec.commands));
|
|
4065
|
+
for (const path of Object.keys(spec.commands)) {
|
|
4066
|
+
const segments = path.split(" ");
|
|
4067
|
+
for (let depth = 1; depth < segments.length; depth += 1) candidates.add(segments.slice(0, depth).join(" "));
|
|
4068
|
+
}
|
|
4069
|
+
return [...[...candidates].map((path) => ({
|
|
4070
|
+
path,
|
|
4071
|
+
distance: editDistance(typed, path)
|
|
4072
|
+
})).filter(({ path, distance }) => distance <= Math.max(path.length >= 8 ? 3 : 1, Math.min(2, path.length - 1))).sort((a, b) => a.distance - b.distance).slice(0, 3).map(({ path }) => ({
|
|
4073
|
+
kind: "run-command",
|
|
4074
|
+
label: "Did you mean",
|
|
4075
|
+
command: `${spec.name} ${path}`
|
|
4076
|
+
})), {
|
|
4077
|
+
kind: "run-command",
|
|
4078
|
+
label: "List every command",
|
|
4079
|
+
command: `${spec.name} --help`
|
|
4080
|
+
}];
|
|
4081
|
+
}
|
|
2826
4082
|
//#endregion
|
|
2827
4083
|
//#region src/execution/engine.ts
|
|
2828
4084
|
function buildEngine(spec, options) {
|
|
@@ -2844,6 +4100,7 @@ function waitFor(ms, signal) {
|
|
|
2844
4100
|
}
|
|
2845
4101
|
var EngineImpl = class {
|
|
2846
4102
|
spec;
|
|
4103
|
+
tree;
|
|
2847
4104
|
root;
|
|
2848
4105
|
redirects;
|
|
2849
4106
|
now;
|
|
@@ -2854,20 +4111,25 @@ var EngineImpl = class {
|
|
|
2854
4111
|
this.now = now;
|
|
2855
4112
|
this.delay = delay;
|
|
2856
4113
|
this.configSections = declaredConfigSections(spec);
|
|
2857
|
-
this.
|
|
4114
|
+
this.tree = buildCommandTree(spec);
|
|
4115
|
+
this.root = buildRoutes(spec, this.tree, "", (invocation, entry, flags, values) => this.executeMounted(invocation, entry, flags, values));
|
|
2858
4116
|
this.redirects = buildRedirectTable(spec);
|
|
2859
4117
|
}
|
|
2860
4118
|
async execute(argv, runtime, hooks) {
|
|
4119
|
+
const format = sniffFormat(argv, runtime);
|
|
2861
4120
|
const state = {
|
|
2862
4121
|
commandId: "",
|
|
2863
4122
|
docsBaseUrl: void 0,
|
|
2864
4123
|
prefix: [],
|
|
2865
|
-
format
|
|
4124
|
+
format,
|
|
2866
4125
|
logLevel: "info",
|
|
2867
4126
|
yes: false,
|
|
2868
4127
|
confirmValues: [],
|
|
2869
4128
|
interactive: defaultInteractive(runtime),
|
|
2870
|
-
|
|
4129
|
+
/** Pre-parse resolution so a run that never mounts a command — an
|
|
4130
|
+
* unknown command, a parse failure — still colours its
|
|
4131
|
+
* diagnostics; applySharedFlags re-resolves after parsing. */
|
|
4132
|
+
colorEnabled: preParseColorEnabled(argv, runtime, "stderr"),
|
|
2871
4133
|
configPath: void 0,
|
|
2872
4134
|
resolved: false,
|
|
2873
4135
|
settledExitCode: void 0,
|
|
@@ -2881,6 +4143,7 @@ var EngineImpl = class {
|
|
|
2881
4143
|
delegatedTerminal: void 0,
|
|
2882
4144
|
lastChild: void 0,
|
|
2883
4145
|
activePrompts: 0,
|
|
4146
|
+
packageOperationRunning: false,
|
|
2884
4147
|
deliveredSignal: void 0,
|
|
2885
4148
|
pendingForceExit: void 0,
|
|
2886
4149
|
spawnCredential: void 0
|
|
@@ -2922,6 +4185,15 @@ var EngineImpl = class {
|
|
|
2922
4185
|
settleErrored(invocation, configFlagGivenNoValueError());
|
|
2923
4186
|
return 2;
|
|
2924
4187
|
}
|
|
4188
|
+
if (helpFlagGiven(argv) || bareGroupInvocation(this.tree, argv)) {
|
|
4189
|
+
unsubscribe();
|
|
4190
|
+
/** Help prose follows stricli's channel rule: stdout in human
|
|
4191
|
+
* mode, stderr in json mode so stdout stays a clean frame
|
|
4192
|
+
* stream. Never fires telemetry, like --version. */
|
|
4193
|
+
const stream = format === "human" ? runtime.stdout : runtime.stderr;
|
|
4194
|
+
renderHelp(this.spec, this.tree, argv, preParseColorEnabled(argv, runtime, format === "human" ? "stdout" : "stderr"), stream);
|
|
4195
|
+
return 0;
|
|
4196
|
+
}
|
|
2925
4197
|
const stricliProcess = {
|
|
2926
4198
|
/** stricli writes only help text here. In json mode stdout carries
|
|
2927
4199
|
* exactly the frame stream, so help prose goes to stderr instead. */
|
|
@@ -3005,25 +4277,71 @@ var EngineImpl = class {
|
|
|
3005
4277
|
hooks.onSettled(summary);
|
|
3006
4278
|
} catch {}
|
|
3007
4279
|
}
|
|
4280
|
+
/** The refusals a maySpawn command can hit before anything runs: a
|
|
4281
|
+
* child's terminal output cannot be framed as a json stream, and a
|
|
4282
|
+
* host that mounts the command without a spawn adapter is
|
|
4283
|
+
* misconfigured. Returns whether the run was settled here. */
|
|
4284
|
+
refuseUnspawnable(invocation, entry) {
|
|
4285
|
+
const state = invocation.state;
|
|
4286
|
+
if (!entry.def.maySpawn) return false;
|
|
4287
|
+
if (formatFlagGiven(state.argv) === "json") {
|
|
4288
|
+
state.format = "human";
|
|
4289
|
+
settleErrored(invocation, jsonUnsupportedError(entry.id));
|
|
4290
|
+
return true;
|
|
4291
|
+
}
|
|
4292
|
+
if (invocation.runtime.spawn === void 0) {
|
|
4293
|
+
state.format = "human";
|
|
4294
|
+
settleBug(invocation, /* @__PURE__ */ new Error(`@prisma/cli-engine: command '${entry.id}' declares maySpawn but the Runtime supplies no spawn adapter`));
|
|
4295
|
+
return true;
|
|
4296
|
+
}
|
|
4297
|
+
return false;
|
|
4298
|
+
}
|
|
4299
|
+
/** Every mounted handler settles the same way: an abandoned child
|
|
4300
|
+
* wins over the handler's own outcome, a failure settles errored, a
|
|
4301
|
+
* child-status value settles as that child's exit, and any other
|
|
4302
|
+
* value is the command's own completion. */
|
|
4303
|
+
async settleHandlerOutcome(invocation, entry, runHandler, settleCompletion) {
|
|
4304
|
+
const state = invocation.state;
|
|
4305
|
+
try {
|
|
4306
|
+
const result = await runHandler();
|
|
4307
|
+
if (await this.settleAbandonedChild(invocation, false)) return;
|
|
4308
|
+
state.resolved = true;
|
|
4309
|
+
if (!result.ok) settleErrored(invocation, result.failure, result.failure.diagnostics);
|
|
4310
|
+
else if (isChildStatusSettlement(result.value)) settleChildStatus(invocation, entry.def, result.value);
|
|
4311
|
+
else settleCompletion(result.value);
|
|
4312
|
+
} catch (cause) {
|
|
4313
|
+
if (await this.settleAbandonedChild(invocation, true, cause)) return;
|
|
4314
|
+
state.resolved = true;
|
|
4315
|
+
settleThrown(invocation, cause);
|
|
4316
|
+
}
|
|
4317
|
+
}
|
|
4318
|
+
/** The telemetry fire, at command start: once per run, from the
|
|
4319
|
+
* parse-time snapshot, before the handler and before any command
|
|
4320
|
+
* output. A CLI that declared no telemetry block reports nothing —
|
|
4321
|
+
* no config read, no disclosure, no mint, no seam call. Runs that
|
|
4322
|
+
* never mount a command never reach here and so never report. */
|
|
4323
|
+
fireTelemetry(invocation) {
|
|
4324
|
+
const { snapshot } = invocation.state;
|
|
4325
|
+
if (this.spec.telemetry === void 0 || snapshot === void 0) return;
|
|
4326
|
+
reportCommandStart({
|
|
4327
|
+
host: invocation.runtime,
|
|
4328
|
+
telemetry: this.spec.telemetry,
|
|
4329
|
+
name: this.spec.name,
|
|
4330
|
+
version: this.spec.version,
|
|
4331
|
+
snapshot
|
|
4332
|
+
});
|
|
4333
|
+
}
|
|
3008
4334
|
async executeMounted(invocation, entry, rawFlags, values) {
|
|
3009
4335
|
const state = invocation.state;
|
|
3010
4336
|
state.commandId = entry.id;
|
|
3011
4337
|
state.docsBaseUrl = entry.docsBaseUrl;
|
|
3012
4338
|
state.snapshot = buildCommandSnapshot(entry.id, entry.def, state.argv, values);
|
|
4339
|
+
this.fireTelemetry(invocation);
|
|
3013
4340
|
if (entry.def.kind === "server-command") {
|
|
3014
4341
|
await this.executeServer(invocation, entry, rawFlags);
|
|
3015
4342
|
return;
|
|
3016
4343
|
}
|
|
3017
|
-
if (
|
|
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
|
-
}
|
|
4344
|
+
if (this.refuseUnspawnable(invocation, entry)) return;
|
|
3027
4345
|
let needsOutcome;
|
|
3028
4346
|
try {
|
|
3029
4347
|
applySharedFlags(state, rawFlags, invocation.runtime);
|
|
@@ -3047,34 +4365,12 @@ var EngineImpl = class {
|
|
|
3047
4365
|
flags: declaredFlags(entry.def, rawFlags),
|
|
3048
4366
|
positionals: distributePositionals(entry.def, values)
|
|
3049
4367
|
};
|
|
3050
|
-
const ctx = makeContext(invocation, entry.def, needsOutcome.config, entry.def
|
|
4368
|
+
const ctx = makeContext(invocation, entry.def, needsOutcome.config, declaredCapabilities(entry.def));
|
|
3051
4369
|
if (entry.def.kind === "session-command") {
|
|
3052
|
-
|
|
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
|
-
}
|
|
4370
|
+
await this.settleHandlerOutcome(invocation, entry, () => handler(args, ctx), () => settleSessionCompleted(invocation));
|
|
3064
4371
|
return;
|
|
3065
4372
|
}
|
|
3066
|
-
|
|
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
|
-
}
|
|
4373
|
+
await this.settleHandlerOutcome(invocation, entry, () => handler(args, ctx), (presented) => settleCompleted(invocation, entry.def, presented));
|
|
3078
4374
|
}
|
|
3079
4375
|
/** The handler resolved or threw with its child still live. The
|
|
3080
4376
|
* engine ends that child — SIGTERM, the ruled grace period, then
|
|
@@ -3168,6 +4464,16 @@ function jsonUnsupportedError(commandId) {
|
|
|
3168
4464
|
}]
|
|
3169
4465
|
});
|
|
3170
4466
|
}
|
|
4467
|
+
function declaredCapabilities(def) {
|
|
4468
|
+
if (def.kind !== "result-command") return {
|
|
4469
|
+
managesCredentials: false,
|
|
4470
|
+
installsPackages: false
|
|
4471
|
+
};
|
|
4472
|
+
return {
|
|
4473
|
+
managesCredentials: def.managesCredentials,
|
|
4474
|
+
installsPackages: def.installsPackages
|
|
4475
|
+
};
|
|
4476
|
+
}
|
|
3171
4477
|
function declaredFlags(def, rawFlags) {
|
|
3172
4478
|
const flags = {};
|
|
3173
4479
|
for (const key of Object.keys(def.args.flags)) flags[key] = rawFlags[key];
|
|
@@ -3252,4 +4558,4 @@ function claimedIdentity(token) {
|
|
|
3252
4558
|
};
|
|
3253
4559
|
}
|
|
3254
4560
|
//#endregion
|
|
3255
|
-
export {
|
|
4561
|
+
export { exitWithChildStatus as C, resolveGating as S, positional as T, noSessionForWorkspaceError as _, CONFIG_FILE_NAME as a, userConfigPath as b, loadConfig as c, WORKSPACE_ID_ENV_VAR as d, authServiceError as f, emptyServiceTokenError as g, credentialsRequiredError as h, buildEngine as i, PRISMA_CONFIG_VERSION as l, credentialWorkspaceMismatchError as m, claimedIdentity as n, defineConfig as o, credentialRejectedError as p, credentialWorkspaceId as r, definePrismaConfig as s, claimedExpiresAt as t, SERVICE_TOKEN_ENV_VAR as u, PRESENTED as v, flag as w, writeUserConfig as x, readUserConfig as y };
|