shiplane 0.0.0 → 0.2.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.
@@ -0,0 +1,3789 @@
1
+ import { a as releaseFlow, i as backendService, n as publishedPackage, r as mobileApp, t as webApp } from "./web-app.module-6KrXIU7j.js";
2
+ import { C as changelogSection, D as tagName, E as releaseTags, O as expandPatterns, S as cameWithRelease, a as CommandFailed, c as onlyVersionFiles, d as appBumps, f as changesetApps, g as unreleasedChangesets, h as unreleasedApps, i as minutesBudget, k as workspacePatterns, l as shipsFrom, m as splitChangesets, o as deployRunTitle, p as packageBumps, r as deployEstimate, u as webShip, w as firstRelease, x as DEFAULT_TAG_FORMAT, y as releaseSource } from "./budget-BqtW-Ekk.js";
3
+ import { z } from "zod";
4
+ import { styleText } from "node:util";
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import { Document, LineCounter, isMap, isScalar, isSeq, parseDocument } from "yaml";
8
+ import { fileURLToPath } from "node:url";
9
+ import { createJiti } from "jiti";
10
+ import { execFile, spawn } from "node:child_process";
11
+ import ora from "ora";
12
+ //#region src/adapters/files/node-files.adapter.ts
13
+ /** The repository on disk, under `root`. */
14
+ const nodeFiles = (root) => {
15
+ const at = (file) => path.join(root, file);
16
+ return {
17
+ exists: (file) => fs.existsSync(at(file)),
18
+ read: (file) => fs.existsSync(at(file)) ? fs.readFileSync(at(file), "utf8") : null,
19
+ write: (file, text) => {
20
+ fs.mkdirSync(path.dirname(at(file)), { recursive: true });
21
+ fs.writeFileSync(at(file), text);
22
+ },
23
+ remove: (file) => fs.rmSync(at(file), { force: true }),
24
+ list: (dir) => fs.existsSync(at(dir)) ? fs.readdirSync(at(dir)) : [],
25
+ folders: (dir) => fs.existsSync(at(dir)) ? fs.readdirSync(at(dir), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name) : []
26
+ };
27
+ };
28
+ //#endregion
29
+ //#region src/modules/suggest.ts
30
+ const SUGGESTED = {
31
+ "server-hosting": {
32
+ kind: "backend-service",
33
+ factory: "backendService",
34
+ port: "serverHosting"
35
+ },
36
+ "static-hosting": {
37
+ kind: "web-app",
38
+ factory: "webApp",
39
+ port: "staticHosting"
40
+ },
41
+ "mobile-distribution": {
42
+ kind: "mobile-app",
43
+ factory: "mobileApp",
44
+ port: "mobileDistribution"
45
+ },
46
+ "package-registry": {
47
+ kind: "published-package",
48
+ factory: "publishedPackage",
49
+ port: "packageRegistry"
50
+ }
51
+ };
52
+ const suggestedModule = (adapter) => SUGGESTED[adapter.capability];
53
+ /** The module a provider makes under a name, as `init` composes it before the config exists. */
54
+ const moduleFor = (adapter, name) => {
55
+ switch (adapter.capability) {
56
+ case "server-hosting": return backendService({
57
+ name,
58
+ serverHosting: adapter
59
+ });
60
+ case "static-hosting": return webApp({
61
+ name,
62
+ staticHosting: adapter
63
+ });
64
+ case "mobile-distribution": return mobileApp({
65
+ name,
66
+ mobileDistribution: adapter
67
+ });
68
+ case "package-registry": return publishedPackage({
69
+ name,
70
+ packageRegistry: adapter
71
+ });
72
+ }
73
+ };
74
+ //#endregion
75
+ //#region src/application/config/problem.ts
76
+ const distance = (left, right) => {
77
+ const previous = Array.from({ length: right.length + 1 }, (_, index) => index);
78
+ for (let row = 1; row <= left.length; row += 1) {
79
+ let diagonal = previous[0] ?? 0;
80
+ previous[0] = row;
81
+ for (let column = 1; column <= right.length; column += 1) {
82
+ const above = previous[column] ?? 0;
83
+ const cost = left[row - 1] === right[column - 1] ? 0 : 1;
84
+ previous[column] = Math.min(above + 1, (previous[column - 1] ?? 0) + 1, diagonal + cost);
85
+ diagonal = above;
86
+ }
87
+ }
88
+ return previous[right.length] ?? 0;
89
+ };
90
+ /** The candidate a typo most likely meant, when one is close enough to be worth naming. */
91
+ const didYouMean = (word, candidates) => {
92
+ const [best] = candidates.map((candidate) => ({
93
+ candidate,
94
+ cost: distance(word.toLowerCase(), candidate.toLowerCase())
95
+ })).sort((left, right) => left.cost - right.cost);
96
+ return best && best.cost <= Math.max(2, Math.floor(word.length / 3)) ? `did you mean "${best.candidate}"?` : void 0;
97
+ };
98
+ /** Top to bottom per file, problems without a line last. */
99
+ const sortProblems = (problems) => [...problems].sort((left, right) => left.file.localeCompare(right.file) || (left.line ?? Number.MAX_SAFE_INTEGER) - (right.line ?? Number.MAX_SAFE_INTEGER));
100
+ //#endregion
101
+ //#region src/application/config/unitSchema.ts
102
+ const definition = (schema) => schema.def;
103
+ const mapShape = (shape, map) => Object.fromEntries(Object.entries(shape).map(([key, value]) => [key, map(value)]));
104
+ /**
105
+ * The same schema, refusing unknown keys at every depth. Read through `def.type` rather than
106
+ * `instanceof`: a config loads its own copy of zod.
107
+ */
108
+ const deepStrict = (schema) => {
109
+ const def = definition(schema);
110
+ const strict = () => {
111
+ switch (def.type) {
112
+ case "object": return z.strictObject(mapShape(def.shape ?? {}, deepStrict));
113
+ case "optional": return def.innerType ? deepStrict(def.innerType).optional() : schema;
114
+ case "nullable": return def.innerType ? deepStrict(def.innerType).nullable() : schema;
115
+ case "default": return def.innerType ? deepStrict(def.innerType).default(def.defaultValue) : schema;
116
+ case "union": return z.union((def.options ?? []).map(deepStrict));
117
+ case "record": return def.keyType && def.valueType ? z.record(def.keyType, deepStrict(def.valueType)) : schema;
118
+ case "array": return def.element ? z.array(deepStrict(def.element)) : schema;
119
+ default: return schema;
120
+ }
121
+ };
122
+ const result = strict();
123
+ const { description } = schema;
124
+ return description && result !== schema ? result.describe(description) : result;
125
+ };
126
+ /** The keys an object schema allows at a path, best effort, for "did you mean". */
127
+ const keysAt = (schema, at) => {
128
+ const def = definition(schema);
129
+ if (def.type === "optional" || def.type === "nullable" || def.type === "default") return def.innerType ? keysAt(def.innerType, at) : [];
130
+ if (def.type === "union") return (def.options ?? []).flatMap((option) => keysAt(option, at));
131
+ if (def.type === "record" && at.length > 0 && def.valueType) return keysAt(def.valueType, at.slice(1));
132
+ if (def.type !== "object") return [];
133
+ const [first, ...rest] = at;
134
+ if (first === void 0) return Object.keys(def.shape ?? {});
135
+ const child = def.shape?.[String(first)];
136
+ return child ? keysAt(child, rest) : [];
137
+ };
138
+ /** What a unit file naming this module may hold: `module`, then its adapter's settings. */
139
+ const unitSchema = (module) => z.strictObject({
140
+ module: z.literal(module.name).describe(`The module that ships this app, with ${module.provider}`),
141
+ buildCommand: z.string().optional().describe("How to build this app, when its package.json has no \"build\" script"),
142
+ ...mapShape(module.settings.shape, deepStrict)
143
+ });
144
+ /** The JSON Schema editors read for `shiplane.unit.yml`: the module an app names picks its keys. */
145
+ const unitJsonSchema = (modules) => z.toJSONSchema(z.union(modules.map(unitSchema)), {
146
+ io: "input",
147
+ unrepresentable: "any"
148
+ });
149
+ //#endregion
150
+ //#region src/domain/environment.ts
151
+ /** Where a unit runs, in promotion order: production ships what preview validated. */
152
+ const ENVIRONMENTS = ["preview", "production"];
153
+ //#endregion
154
+ //#region src/application/config/values.ts
155
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
156
+ /** A map keyed by exactly the environments: one of its values is picked per environment. */
157
+ const isPerEnvValue = (value) => isRecord(value) && Object.keys(value).length === ENVIRONMENTS.length && ENVIRONMENTS.every((environment) => environment in value);
158
+ /** `${units.<name>.<key>}`, where key may be dotted. */
159
+ const REFERENCE = /\$\{units\.([\w-]+)\.([\w.-]+)\}/g;
160
+ const referencesIn = (value, at = []) => {
161
+ if (typeof value === "string") return [...value.matchAll(REFERENCE)].map(([, unit = "", key = ""]) => ({
162
+ unit,
163
+ key,
164
+ at
165
+ }));
166
+ if (Array.isArray(value)) return value.flatMap((item, index) => referencesIn(item, [...at, String(index)]));
167
+ if (isRecord(value)) return Object.entries(value).flatMap(([key, item]) => referencesIn(item, [...at, key]));
168
+ return [];
169
+ };
170
+ const valueAt = (value, at) => at.reduce((current, key) => isRecord(current) ? current[key] : void 0, value);
171
+ //#endregion
172
+ //#region src/application/config/readUnitFile.ts
173
+ const UNIT_FILE = "shiplane.unit.yml";
174
+ const UNIT_FILES = [UNIT_FILE, "release.unit.yml"];
175
+ const locate = (doc, counter) => (at, key) => {
176
+ let node = doc.contents;
177
+ for (const segment of at) {
178
+ if (!isMap(node) && !isSeq(node)) return void 0;
179
+ node = node.get(segment, true);
180
+ }
181
+ if (key !== void 0 && isMap(node)) node = node.items.find((pair) => isScalar(pair.key) && pair.key.value === key)?.key;
182
+ const offset = node?.range?.[0];
183
+ return offset === void 0 ? void 0 : counter.linePos(offset).line;
184
+ };
185
+ const describeIssue = (issue, file, module, lineAt) => {
186
+ const at = issue.path;
187
+ if (issue.code === "unrecognized_keys") return issue.keys.map((key) => ({
188
+ file,
189
+ line: lineAt(at, key),
190
+ message: `unknown key "${[...at, key].join(".")}" for ${module.name}`,
191
+ hint: didYouMean(key, keysAt(module.settings, at))
192
+ }));
193
+ const name = at.join(".");
194
+ if (issue.code === "invalid_type" && issue.message.endsWith("received undefined")) return [{
195
+ file,
196
+ line: at.length > 1 ? lineAt(at.slice(0, -1)) : void 0,
197
+ message: `"${name}" is required`
198
+ }];
199
+ return [{
200
+ file,
201
+ line: lineAt(at),
202
+ message: `"${name}": ${issue.message}`
203
+ }];
204
+ };
205
+ const problem = (file, line, message, hint) => ({ problems: [{
206
+ file,
207
+ line,
208
+ message,
209
+ hint
210
+ }] });
211
+ /** A unit file checked against the adapter of the module it names, every problem with its line. */
212
+ const readUnitFile = (file, text, modules, features = []) => {
213
+ const counter = new LineCounter();
214
+ const doc = parseDocument(text, {
215
+ lineCounter: counter,
216
+ uniqueKeys: true,
217
+ prettyErrors: false
218
+ });
219
+ if (doc.errors.length > 0) return { problems: doc.errors.map((error) => ({
220
+ file,
221
+ line: counter.linePos(error.pos[0]).line,
222
+ message: error.message.split("\n")[0] ?? error.message
223
+ })) };
224
+ const lineAt = locate(doc, counter);
225
+ const data = doc.toJS();
226
+ const names = modules.map(({ name }) => name);
227
+ const oneOf = `one of: ${names.join(", ")}`;
228
+ if (isRecord(data) && "target" in data && !("module" in data)) return problem(file, lineAt(["target"]), "target: is now module: the module in shiplane.config.ts that ships this app", oneOf);
229
+ if (!isRecord(data) || typeof data.module !== "string") return problem(file, 1, "a unit file starts with module: the module that ships it", oneOf);
230
+ const named = data.module;
231
+ const module = modules.find(({ name }) => name === named);
232
+ if (features.includes(named)) return problem(file, lineAt(["module"]), `"${named}" ships no app: it runs on every ship`, oneOf);
233
+ if (!module) return problem(file, lineAt(["module"]), `no module named "${named}" in shiplane.config.ts`, didYouMean(named, names) ?? oneOf);
234
+ const parsed = unitSchema(module).safeParse(data);
235
+ if (!parsed.success) return { problems: parsed.error.issues.flatMap((issue) => describeIssue(issue, file, module, lineAt)) };
236
+ const options = Object.fromEntries(Object.entries(data).filter(([key]) => key !== "module" && key !== "buildCommand"));
237
+ const buildCommand = typeof data.buildCommand === "string" ? data.buildCommand : void 0;
238
+ return {
239
+ unit: {
240
+ module: named,
241
+ ...buildCommand ? { buildCommand } : {},
242
+ options,
243
+ lineOf: (at) => lineAt(at)
244
+ },
245
+ problems: []
246
+ };
247
+ };
248
+ //#endregion
249
+ //#region src/application/releaseOrder.ts
250
+ /** `admin (reads api.url)`: an app, with the values of other apps it reads. */
251
+ const withReads = ({ name, options }) => {
252
+ const reads = [...new Set(referencesIn(options).filter(({ unit }) => unit !== name).map(({ unit, key }) => `${unit}.${key}`))];
253
+ return reads.length > 0 ? `${name} (reads ${reads.join(", ")})` : name;
254
+ };
255
+ /** `1 expo · Latest → 2 api → 3 admin (reads api.url)`: the apps numbered in release order. */
256
+ const releaseOrder = (units) => units.map((unit, index) => `${index + 1} ${withReads(unit)}${index === 0 ? " · Latest" : ""}`).join(" → ");
257
+ //#endregion
258
+ //#region src/application/say.ts
259
+ const paint = (style, text) => styleText(style, text);
260
+ /** A failure, said with what to run next; the caller returns false so nothing else runs. */
261
+ const fail = ({ output, progress }, title, detail, commands = []) => {
262
+ progress.say("worried", `${paint(["bold", "red"], `✗ ${title}:`)} ${detail}`);
263
+ commands.forEach((command) => output.line(` ${paint("cyan", command)}`));
264
+ };
265
+ /** Yes without asking under --yes; without a terminal, no. */
266
+ const confirm = async ({ prompter, options, output }, question, initial = false) => {
267
+ if (options.yes) return true;
268
+ if (!prompter.interactive) {
269
+ output.line(paint("yellow", "Not a terminal: pass --yes to run it."));
270
+ return false;
271
+ }
272
+ return prompter.confirm(question, initial);
273
+ };
274
+ /** `api`, `api and admin`, `api, admin and landing`. */
275
+ const listed = (names) => names.length < 2 ? names.join("") : `${names.slice(0, -1).join(", ")} and ${names.slice(-1).join("")}`;
276
+ /** The keys a screen offers, each the same way: `d see the diff o open it on GitHub`. */
277
+ const keyHints = (hints) => hints.map(({ key, label }) => `${paint("cyan", key)} ${paint("dim", label)}`).join(" ");
278
+ //#endregion
279
+ //#region src/domain/codeScope.ts
280
+ const NOT_SHIPPED = [
281
+ /(^|\/)(shiplane|release)\.unit\.yml$/,
282
+ /^\.changeset\//,
283
+ /^\.planning\//,
284
+ /^\.github\//,
285
+ /^\.claude\//,
286
+ /^docs\//,
287
+ /\.md$/
288
+ ];
289
+ /** A package's folder and the folders of every workspace package it uses, however deep. */
290
+ const codeFolders = (packageName, dependencies, folders) => {
291
+ const seen = new Set([packageName]);
292
+ const queue = [packageName];
293
+ for (const name of queue) for (const dependency of dependencies[name] ?? []) {
294
+ if (seen.has(dependency)) continue;
295
+ seen.add(dependency);
296
+ queue.push(dependency);
297
+ }
298
+ return [...seen].flatMap((name) => folders[name] ?? []);
299
+ };
300
+ /**
301
+ * The changed files that can reach what a unit ships: in its own code folders, or at the root
302
+ * outside every workspace folder, such as the lockfile. Another app's folder never does.
303
+ */
304
+ const changesReaching = (files, scope) => files.filter((file) => {
305
+ if (scope.versionFiles.has(file) || NOT_SHIPPED.some((pattern) => pattern.test(file))) return false;
306
+ const inside = (folder) => file.startsWith(`${folder}/`);
307
+ return scope.own.some(inside) || !scope.workspace.some(inside);
308
+ });
309
+ //#endregion
310
+ //#region src/application/config/optionsFor.ts
311
+ const resolve = (value, env, units) => {
312
+ const picked = isPerEnvValue(value) ? value[env] : value;
313
+ if (typeof picked === "string") return picked.replace(REFERENCE, (_match, name, key) => {
314
+ const other = units.find((unit) => unit.name === name);
315
+ const resolved = other ? resolve(valueAt(other.options, key.split(".")), env, units) : "";
316
+ return typeof resolved === "string" ? resolved : "";
317
+ });
318
+ if (Array.isArray(picked)) return picked.map((item) => resolve(item, env, units));
319
+ if (isRecord(picked)) return Object.fromEntries(Object.entries(picked).map(([key, item]) => [key, resolve(item, env, units)]));
320
+ return picked;
321
+ };
322
+ /** A unit's options for one environment: per-environment values picked, references filled in. */
323
+ const optionsFor = (unit, env, units) => {
324
+ const resolved = resolve(unit.options, env, units);
325
+ return isRecord(resolved) ? resolved : {};
326
+ };
327
+ //#endregion
328
+ //#region src/application/targets.ts
329
+ /** The module that ships an app: the one its unit file names. */
330
+ const moduleOf = ({ release }, unit) => release.modules.find(({ name }) => name === unit.module);
331
+ /** An app's settings for an environment, its module's defaults applied first. */
332
+ const resolvedOptions = (module, unit, environment, units) => {
333
+ const withDefaults = module.settings.parse(unit.options);
334
+ return optionsFor({
335
+ ...unit,
336
+ options: withDefaults
337
+ }, environment, units);
338
+ };
339
+ /** What a module's stages are told about one app's tag. */
340
+ const jobInput = (context, module, unit, { tag, environment, commit }) => ({
341
+ unit,
342
+ tag,
343
+ environment,
344
+ commit,
345
+ options: resolvedOptions(module, unit, environment, context.release.units)
346
+ });
347
+ /** Where a tag lands and the jobs that ship it, as its module says. */
348
+ const shipPlanOf = (context, module, input) => module.ship(decideContext(context), input);
349
+ /** Every file a release may move after a tag without changing what ships. */
350
+ const versionFiles = (context) => new Set(context.release.units.flatMap((unit) => moduleOf(context, unit)?.versionFiles?.(unit, context.release.units, context.open) ?? []));
351
+ /** A command as a person would type it, variables first, secrets by name only. */
352
+ const commandLine = ({ command, args, env, secrets }) => [
353
+ ...Object.entries(env ?? {}).map(([key, value]) => `${key}=${value}`),
354
+ command,
355
+ ...args,
356
+ ...(secrets ?? []).flatMap(({ flag, name }) => [flag, `${name}=$${name}`])
357
+ ].join(" ");
358
+ /** Runs a job's commands here in order, then records the deploy. Throws on the first failure. */
359
+ const runHere = async ({ shell, services, release, output }, job, { tag, environment }) => {
360
+ const secretArgs = (step) => (step.secrets ?? []).flatMap(({ flag, name }) => {
361
+ const value = shell.env(name);
362
+ if (value) return [flag, `${name}=${value}`];
363
+ output.line(` ! ${name} is not set: ${flag} left out`);
364
+ return [];
365
+ });
366
+ const run = (step) => shell.attach(step.command, [...step.args, ...secretArgs(step)], {
367
+ cwd: path.join(release.root, step.cwd ?? ""),
368
+ env: step.env
369
+ });
370
+ try {
371
+ for (const step of job.local) {
372
+ const status = await run(step);
373
+ if (status !== 0) throw new Error(`${step.command} exited with ${status}`);
374
+ }
375
+ } finally {
376
+ for (const step of job.cleanup ?? []) await run(step);
377
+ }
378
+ if (job.record) await services.codeHost.recordDeployment(tag, environment);
379
+ };
380
+ /** Dispatches the ship workflow on a ref for its units and returns at once: the runner ships them. */
381
+ const dispatchShip = async ({ services }, { ref, units }, environment) => services.ciPipeline.dispatch(services.ciPipeline.shipWorkflow, ref, {
382
+ units: units.join(" "),
383
+ environment
384
+ });
385
+ /** Which changed files can reach what a unit ships. */
386
+ const reaching = async (context, unit) => {
387
+ const { versioning } = context.services;
388
+ const [dependencies, folders] = await Promise.all([versioning.dependencies(), versioning.folders()]);
389
+ const scope = {
390
+ own: [unit.dir, ...codeFolders(unit.packageName, dependencies, folders)],
391
+ workspace: Object.values(folders),
392
+ versionFiles: versionFiles(context)
393
+ };
394
+ return (files) => changesReaching(files, scope);
395
+ };
396
+ /** What a module's per-app stages may read and run. */
397
+ const decideContext = (context) => ({
398
+ root: context.release.root,
399
+ shell: context.shell,
400
+ sourceControl: context.services.sourceControl,
401
+ codeHost: context.services.codeHost,
402
+ ciPipeline: context.services.ciPipeline,
403
+ units: context.release.units,
404
+ tagFormat: context.release.tagFormat,
405
+ versionFiles: versionFiles(context),
406
+ now: () => context.clock.now(),
407
+ open: context.open,
408
+ changedCode: async (unit, from, to) => {
409
+ const [files, filter] = await Promise.all([context.services.sourceControl.diffNames(from, to), reaching(context, unit)]);
410
+ return filter(files);
411
+ }
412
+ });
413
+ /** What a module may read once apps ship. */
414
+ const afterShipContext = (context) => ({
415
+ open: context.open,
416
+ tagFormat: context.release.tagFormat,
417
+ subjectsReaching: async (unit, from, to) => {
418
+ const [commits, filter] = await Promise.all([context.services.sourceControl.commitsBetween(from, to), reaching(context, unit)]);
419
+ return commits.filter(({ files }) => filter(files).length > 0).map(({ subject }) => subject);
420
+ }
421
+ });
422
+ /**
423
+ * What the person reads for an environment: a package registry has no staging, so when every unit
424
+ * is a published package, preview is where users install it — it reads "live".
425
+ */
426
+ const environmentLabel = (context, units, environment) => {
427
+ if (environment !== "preview") return environment;
428
+ const names = [...units];
429
+ return names.length > 0 && names.every((name) => {
430
+ const unit = context.release.units.find((candidate) => candidate.name === name);
431
+ return unit !== void 0 && moduleOf(context, unit)?.kind === "published-package";
432
+ }) ? "live" : environment;
433
+ };
434
+ //#endregion
435
+ //#region src/application/requirements.ts
436
+ /**
437
+ * Every tool and sign-in the flow, the features and the modules need, once each. With `apps`, only
438
+ * the modules shipping one of those apps count.
439
+ */
440
+ const requirementsOf = (release, apps) => {
441
+ const appsOf = (name) => release.units.filter(({ module, name: app }) => module === name && (!apps || apps.has(app)));
442
+ const required = [
443
+ ...[
444
+ release.flow.sourceControl,
445
+ release.flow.codeHost,
446
+ release.flow.ciPipeline,
447
+ release.flow.versioning
448
+ ].flatMap((adapter) => adapter.requirements?.() ?? []),
449
+ ...release.modules.flatMap((module) => {
450
+ const shipped = appsOf(module.name);
451
+ return apps && shipped.length === 0 ? [] : module.requirements?.(shipped) ?? [];
452
+ }),
453
+ ...release.features.flatMap((feature) => feature.requirements?.() ?? [])
454
+ ];
455
+ return required.filter((requirement, index) => required.findIndex(({ label }) => label === requirement.label) === index);
456
+ };
457
+ /** A requirement's check run from the root: its exit status, 127 when the tool is missing. */
458
+ const checkStatus = async (shell, root, { check }) => (await shell.capture(check.command, check.args, {
459
+ cwd: path.join(root, check.cwd ?? ""),
460
+ env: check.env
461
+ })).status;
462
+ /**
463
+ * Before a release writes anything: each sign-in its picked units need. A failing one offers its
464
+ * fix, then is checked again. False, with the commands to run, when one still fails.
465
+ */
466
+ const preflight = async (context, apps) => {
467
+ const { shell, prompter, options, release } = context;
468
+ const failing = [];
469
+ for (const requirement of requirementsOf(release, apps)) {
470
+ const status = await checkStatus(shell, release.root, requirement);
471
+ if (status === 0) continue;
472
+ const { fix } = requirement;
473
+ if ((fix !== void 0 && status !== 127 && prompter.interactive && !options.yes ? await prompter.confirm(`Run ${commandLine(fix)} now?`, true) : false) && fix) {
474
+ await shell.attach(fix.command, fix.args, {
475
+ cwd: path.join(release.root, fix.cwd ?? ""),
476
+ env: fix.env
477
+ });
478
+ if (await checkStatus(shell, release.root, requirement) === 0) continue;
479
+ }
480
+ failing.push(requirement);
481
+ }
482
+ if (failing.length === 0) return true;
483
+ fail(context, `Not signed in: ${failing.map(({ label }) => label).join(", ")}`, "nothing was written. Sign in, then run the release again.", [...failing.flatMap(({ fix }) => fix ? [commandLine(fix)] : []), "shiplane"]);
484
+ return false;
485
+ };
486
+ //#endregion
487
+ //#region src/application/setupFiles.ts
488
+ const CONFIG_FILE = "shiplane.config.ts";
489
+ const SCHEMA_FILE = "node_modules/.cache/shiplane/schema.json";
490
+ const VSCODE_SETTINGS = ".vscode/settings.json";
491
+ /** `cloudflare-pages` → `cloudflarePages`. */
492
+ const factoryName = (name) => name.replace(/-([a-z])/g, (_match, letter) => letter.toUpperCase());
493
+ /** `fly` serving servers → `flyServerHosting`, the factory an official adapter is imported by. */
494
+ const adapterFactory = ({ name, capability }) => `${factoryName(name)}${factoryName(`-${capability}`)}`;
495
+ const moduleCall = ({ factory, port, adapter, name }) => `${factory}({ ${name ? `name: "${name}", ` : ""}${port}: ${adapter}() })`;
496
+ /**
497
+ * The module an app ships with, given what the release already composes: the one holding this
498
+ * provider for that kind, else a new one under the kind's name, or the provider's when that is taken.
499
+ */
500
+ const placeModule = (adapter, modules, pkg = INSTALLED) => {
501
+ const from = adapter.name === "shell" ? pkg : pluginPackage(adapter.name);
502
+ const { kind, factory, port } = suggestedModule(adapter);
503
+ const held = modules.find((module) => module.kind === kind && module.provider === adapter.name);
504
+ if (held) return { name: held.name };
505
+ const taken = modules.some((module) => module.name === kind);
506
+ const name = taken ? `${kind}-${adapter.name}` : kind;
507
+ return {
508
+ name,
509
+ entry: {
510
+ factory,
511
+ port,
512
+ adapter: adapterFactory(adapter),
513
+ from,
514
+ ...taken ? { name } : {}
515
+ }
516
+ };
517
+ };
518
+ /** The name other repositories install the CLI under. */
519
+ const INSTALLED = "shiplane";
520
+ const NAMES$1 = /shiplane/;
521
+ /** Where a plugin is installed from. */
522
+ const pluginPackage = (plugin) => `@shiplane/${plugin}`;
523
+ /** What a written config imports the CLI as. */
524
+ const releasePackage = (files) => {
525
+ const manifest = JSON.parse(files.read("package.json") ?? "{}");
526
+ return "shiplane" in {
527
+ ...manifest.dependencies,
528
+ ...manifest.devDependencies
529
+ } ? "shiplane" : INSTALLED;
530
+ };
531
+ const importLine = (names, from) => `import { ${[...new Set(names)].sort().join(", ")} } from "${from}";`;
532
+ const FLOW_PORTS = [
533
+ "sourceControl",
534
+ "codeHost",
535
+ "ciPipeline",
536
+ "versioning"
537
+ ];
538
+ /** The flow init writes when nothing else is chosen: git, GitHub, GitHub Actions, changesets. */
539
+ const DEFAULT_FLOW = {
540
+ sourceControl: {
541
+ factory: "gitSourceControl",
542
+ from: pluginPackage("git")
543
+ },
544
+ codeHost: {
545
+ factory: "gitHubCodeHost",
546
+ from: pluginPackage("github")
547
+ },
548
+ ciPipeline: {
549
+ factory: "gitHubActionsCiPipeline",
550
+ from: pluginPackage("github")
551
+ },
552
+ versioning: {
553
+ factory: "changesetsVersioning",
554
+ from: pluginPackage("changesets")
555
+ }
556
+ };
557
+ /** A root config with this flow (today's by default) and these modules, in the order given. */
558
+ const renderConfig = (entries, pkg = INSTALLED, flow = DEFAULT_FLOW, units) => {
559
+ const byPlugin = /* @__PURE__ */ new Map();
560
+ const add = (from, name) => byPlugin.set(from, [...byPlugin.get(from) ?? [], name]);
561
+ FLOW_PORTS.forEach((port) => add(flow[port].from, flow[port].factory));
562
+ const own = [
563
+ "defineRelease",
564
+ "releaseFlow",
565
+ ...entries.map(({ factory }) => factory)
566
+ ];
567
+ entries.forEach(({ adapter, from }) => {
568
+ if (from === pkg) own.push(adapter);
569
+ else add(from, adapter);
570
+ });
571
+ const local = (from) => from.startsWith(".");
572
+ return [
573
+ importLine(own, pkg),
574
+ ...[...byPlugin].filter(([from]) => !local(from)).sort(([a], [b]) => a.localeCompare(b)).map(([from, names]) => importLine(names, from)),
575
+ ...[...byPlugin].filter(([from]) => local(from)).sort(([a], [b]) => a.localeCompare(b)).map(([from, names]) => importLine(names, from)),
576
+ "",
577
+ "export default defineRelease({",
578
+ " flow: releaseFlow({",
579
+ ...FLOW_PORTS.map((port) => ` ${port}: ${flow[port].factory}(),`),
580
+ " }),",
581
+ ...units ? [` units: [${units.map((unit) => JSON.stringify(unit)).join(", ")}],`] : [],
582
+ " // What gets released, in this order. The first app is the repository's Latest release.",
583
+ " modules: [",
584
+ ...entries.map((entry) => ` ${moduleCall(entry)},`),
585
+ " ],",
586
+ "});",
587
+ ""
588
+ ].join("\n");
589
+ };
590
+ /** The index of the bracket closing the one at `open`, or -1. */
591
+ const closing = (text, open) => {
592
+ let depth = 0;
593
+ for (let index = open; index < text.length; index += 1) {
594
+ if (text[index] === "[") depth += 1;
595
+ if (text[index] === "]") depth -= 1;
596
+ if (depth === 0) return index;
597
+ }
598
+ return -1;
599
+ };
600
+ /** Adds a name to the CLI's import, under whichever name it has, or a new import when there is none. */
601
+ const withNamedImport = (config, name, pkg) => {
602
+ const match = new RegExp(`import \\{([^}]*)\\} from "(${NAMES$1.source})";`).exec(config);
603
+ if (!match) return `import { ${name} } from "${pkg}";\n${config}`;
604
+ const names = match[1]?.split(",").map((part) => part.trim()).filter(Boolean) ?? [];
605
+ if (names.includes(name)) return config;
606
+ const line = `import { ${[...names, name].sort().join(", ")} } from "${match[2] ?? pkg}";`;
607
+ return config.replace(match[0], line);
608
+ };
609
+ /** Adds a module and its imports to an existing config, or null when its shape is not ours. */
610
+ const addToConfig = (config, entry, pkg = INSTALLED) => {
611
+ const start = config.search(/modules:\s*\[/);
612
+ if (start < 0) return null;
613
+ const open = config.indexOf("[", start);
614
+ const close = closing(config, open);
615
+ if (close < 0) return null;
616
+ const call = moduleCall(entry);
617
+ const inner = config.slice(open + 1, close);
618
+ const trimmed = inner.trimEnd();
619
+ const tail = inner.slice(trimmed.length);
620
+ const comma = trimmed === "" || trimmed.endsWith(",") ? "" : ",";
621
+ const added = inner.includes("\n") ? `${trimmed}${comma}\n ${call},${tail}` : `${trimmed}${comma}${trimmed === "" ? "" : " "}${call}${tail}`;
622
+ const withCall = withNamedImport(`${config.slice(0, open + 1)}${added}${config.slice(close)}`, entry.factory, pkg);
623
+ if (entry.from === pkg) return withNamedImport(withCall, entry.adapter, pkg);
624
+ const importLine = `import { ${entry.adapter} } from "${entry.from}";`;
625
+ if (withCall.includes(importLine)) return withCall;
626
+ const last = [...withCall.matchAll(/^import [^;]*;$/gm)].at(-1);
627
+ const at = last?.index === void 0 ? 0 : last.index + last[0].length;
628
+ return `${withCall.slice(0, at)}${at === 0 ? "" : "\n"}${importLine}${at === 0 ? "\n" : ""}${withCall.slice(at)}`;
629
+ };
630
+ /** A unit file naming its module, with the settings init found, and where it found them. */
631
+ const renderUnit = (module, options, { reason, schemaLine }) => {
632
+ const doc = new Document({
633
+ module,
634
+ ...options
635
+ });
636
+ doc.commentBefore = [
637
+ ...schemaLine ? [` yaml-language-server: $schema=${schemaLine}`] : [],
638
+ ` Written by shiplane init. Every key: shiplane docs ${module}`,
639
+ ...reason ? [` Read from ${reason}`] : []
640
+ ].join("\n");
641
+ return doc.toString();
642
+ };
643
+ /** A schema's keys as dotted paths: a nested object lists each of its own keys, not itself. */
644
+ const flatten = (properties, required, prefix = "") => Object.entries(properties).flatMap(([name, property]) => property.properties ? flatten(property.properties, property.required ?? [], `${prefix}${name}.`) : [{
645
+ key: `${prefix}${name}`,
646
+ description: property.description ?? "",
647
+ default: property.default,
648
+ required: required.includes(name)
649
+ }]);
650
+ /** Every key a unit file takes, nested ones as `build.command`, for `shiplane docs`. */
651
+ const documentedKeys = (settings) => {
652
+ const schema = z.toJSONSchema(settings, {
653
+ io: "input",
654
+ unrepresentable: "any"
655
+ });
656
+ return flatten(schema.properties ?? {}, schema.required ?? []);
657
+ };
658
+ /** Each key a schema takes, with its description and default, from its JSON Schema. */
659
+ const settingsKeys = (settings) => {
660
+ const schema = z.toJSONSchema(settings, {
661
+ io: "input",
662
+ unrepresentable: "any"
663
+ });
664
+ return Object.entries(schema.properties ?? {}).map(([key, property]) => ({
665
+ key,
666
+ description: property.description ?? "",
667
+ default: property.default,
668
+ required: schema.required?.includes(key) ?? false
669
+ }));
670
+ };
671
+ /** A unit file with only its module set and every other key commented, described. */
672
+ const renderBlankUnit = (module, settings, schemaLine) => [
673
+ ...schemaLine ? [`# yaml-language-server: $schema=${schemaLine}`] : [],
674
+ `# Written by shiplane init --blank. Uncomment and fill what applies.`,
675
+ `module: ${module}`,
676
+ ...settingsKeys(settings).flatMap(({ key, description, default: fallback, required }) => [
677
+ "",
678
+ `# ${description}${required ? " (required)" : ""}`,
679
+ `# ${key}:${fallback === void 0 ? "" : ` ${JSON.stringify(fallback)}`}`
680
+ ]),
681
+ ""
682
+ ].join("\n");
683
+ /** The schema a unit file's editor reads, relative to that unit file. */
684
+ const schemaLineFor = (dir) => path.posix.relative(dir, "node_modules/.cache/shiplane/schema.json") || "node_modules/.cache/shiplane/schema.json";
685
+ /** The JSON Schema for every unit file: the module an app names picks the keys it takes. */
686
+ const schemaText = (modules) => `${JSON.stringify(unitJsonSchema(modules), null, 2)}\n`;
687
+ /**
688
+ * Writes the editor schema when it no longer matches the composed modules. It is generated, never
689
+ * committed: every command keeps it current. True when it wrote.
690
+ */
691
+ const refreshEditorSchema = (files, release) => {
692
+ const text = schemaText(release.modules);
693
+ if (files.read("node_modules/.cache/shiplane/schema.json") === text) return false;
694
+ files.write(SCHEMA_FILE, text);
695
+ return true;
696
+ };
697
+ /** Maps every unit file to the schema once, keeping a settings file's comments as they are. */
698
+ const withEditorSchema = (settings) => {
699
+ const entry = `"yaml.schemas": { "./${SCHEMA_FILE}": "**/${UNIT_FILE}" }`;
700
+ if (settings === null) return `{\n ${entry}\n}\n`;
701
+ if (settings.includes("\"yaml.schemas\"")) return null;
702
+ const open = settings.indexOf("{");
703
+ if (open < 0) return null;
704
+ return `${settings.slice(0, open + 1)}\n ${entry},${settings.slice(open + 1)}`;
705
+ };
706
+ const editorSettingsFile = VSCODE_SETTINGS;
707
+ /** A folder as adapters see it when recognising what ships from it. */
708
+ const folderView = (files, dir) => ({
709
+ dir,
710
+ name: path.posix.basename(dir),
711
+ files: files.list(dir),
712
+ has: (file) => files.exists(path.posix.join(dir, file)),
713
+ read: (file) => files.read(path.posix.join(dir, file))
714
+ });
715
+ /** The repository's short name: its package name without scope, else its folder's. */
716
+ const repositoryName = (files, root) => {
717
+ const parsed = z.object({ name: z.string() }).safeParse(JSON.parse(files.read("package.json") ?? "{}"));
718
+ return parsed.success ? parsed.data.name.replace(/^@[^/]+\//, "") : path.basename(root);
719
+ };
720
+ //#endregion
721
+ //#region src/application/doctor.ts
722
+ /**
723
+ * `shiplane doctor`: the config as written, the editor schema refreshed, the release order, a warning
724
+ * for each module no app names, then every tool and sign-in the flow, modules and features need, each
725
+ * failure with the command that fixes it, offered to run.
726
+ */
727
+ const doctor = async (context) => {
728
+ const { output, files, shell, prompter, root } = context;
729
+ output.line();
730
+ output.line(`${paint("cyan", "◆")} ${paint("bold", "shiplane doctor")}`);
731
+ const release = await context.load();
732
+ if (release.problems.length > 0) {
733
+ release.problems.forEach(({ file, line, message, hint }) => {
734
+ output.line(`${paint("red", "✗")} ${paint("bold", line === void 0 ? file : `${file}:${line}`)} ${message}`);
735
+ if (hint) output.line(` ${paint("dim", hint)}`);
736
+ });
737
+ return false;
738
+ }
739
+ refreshEditorSchema(files, release);
740
+ const appsOf = (name) => release.units.filter(({ module }) => module === name);
741
+ if (release.units.length > 0) output.line(`${paint("dim", "│")} Order ${paint("dim", releaseOrder(release.units))}`);
742
+ release.modules.filter((module) => appsOf(module.name).length === 0).forEach(({ name }) => output.line(`${paint("dim", "│")} ${paint("yellow", "!")} ${name} ${paint("dim", `no app names it: module: ${name} in a ${UNIT_FILE}`)}`));
743
+ (release.renames ?? []).forEach(({ from, to }) => output.line(`${paint("dim", "│")} ${paint("yellow", "!")} ${paint("dim", `rename ${from} to ${to}: the old name still works for now`)}`));
744
+ const unique = requirementsOf(release);
745
+ const failing = [];
746
+ const missing = /* @__PURE__ */ new Set();
747
+ for (const requirement of unique) {
748
+ const { check } = requirement;
749
+ const status = await checkStatus(shell, root, requirement);
750
+ if (status === 0) output.line(`${paint("dim", "│")} ${paint("green", "✓")} ${requirement.label}`);
751
+ else {
752
+ failing.push(requirement);
753
+ if (status === 127) missing.add(check.command);
754
+ const fix = status === 127 ? `not installed: ${check.command}` : requirement.fix ? `fix: ${commandLine(requirement.fix)}` : "not available here";
755
+ output.line(`${paint("dim", "│")} ${paint("red", "✗")} ${requirement.label} ${paint("dim", fix)}`);
756
+ }
757
+ }
758
+ for (const { fix } of failing) {
759
+ if (!fix || !prompter.interactive || missing.has(fix.command)) continue;
760
+ if (await prompter.confirm(`Run ${commandLine(fix)} now?`)) await shell.attach(fix.command, fix.args, {
761
+ cwd: path.join(root, fix.cwd ?? ""),
762
+ env: fix.env
763
+ });
764
+ }
765
+ output.line(`${paint("dim", "└")} Next: ${paint("cyan", failing.length > 0 ? "shiplane doctor" : "shiplane status")}`);
766
+ return failing.length === 0;
767
+ };
768
+ //#endregion
769
+ //#region src/application/initRelease.ts
770
+ const bar = paint("dim", "│");
771
+ /** Sets `key`, dotted, in a nested object. */
772
+ const setAt = (target, key, value) => {
773
+ const [head = "", ...rest] = key.split(".");
774
+ if (rest.length === 0) {
775
+ target[head] = value;
776
+ return;
777
+ }
778
+ const child = isRecord(target[head]) ? target[head] : {};
779
+ target[head] = child;
780
+ setAt(child, rest.join("."), value);
781
+ };
782
+ /** Each workspace folder with a manifest and no unit file yet, with what adapters recognise in it. */
783
+ const scanFolders = (context, adapters) => expandPatterns(context.root, workspacePatterns(context.root)).filter((dir) => dir !== "." && context.files.exists(path.posix.join(dir, "package.json"))).filter((dir) => !UNIT_FILES.some((name) => context.files.exists(path.posix.join(dir, name)))).map((dir) => {
784
+ const folder = folderView(context.files, dir);
785
+ const detections = adapters.flatMap((adapter) => {
786
+ const detection = adapter.detect?.(folder);
787
+ return detection ? [{
788
+ adapter,
789
+ detection
790
+ }] : [];
791
+ });
792
+ return {
793
+ folder,
794
+ guess: [
795
+ "found",
796
+ "likely",
797
+ "possible"
798
+ ].map((certainty) => detections.find(({ detection }) => detection.certainty === certainty)).find(Boolean) ?? null
799
+ };
800
+ });
801
+ /** The options a placed folder needs that its folder did not say, asked or taken as suggested. */
802
+ const askOptions = async (context, folder, adapter, found, yes) => {
803
+ const options = structuredClone(found);
804
+ const repository = repositoryName(context.files, context.root);
805
+ for (const question of adapter.questions?.(folder, options, repository) ?? []) {
806
+ const answer = yes ? question.initial ?? null : await context.prompter.text(`${folder.dir} · ${question.message}`, question.initial);
807
+ if (answer !== null && answer !== "") setAt(options, question.key, answer);
808
+ }
809
+ return options;
810
+ };
811
+ const candidateLine = ({ folder, guess }, width) => {
812
+ const target = guess?.detection.certainty === "found" ? paint("green", guess.adapter.name) : paint("yellow", "?");
813
+ return `${folder.dir.padEnd(width)}${target.padEnd(18)}${paint("dim", guess?.detection.reason ?? "")}`;
814
+ };
815
+ /** Whether the person writes, after seeing the list, the diff if asked. */
816
+ const review = async (context, writes, yes) => {
817
+ const { output, prompter } = context;
818
+ output.line(`${paint("cyan", "◆")} ${paint("bold", "Write these files?")}`);
819
+ writes.forEach(({ file, created }) => output.line(`${bar} ${created ? paint("green", "+") : paint("yellow", "~")} ${file}`));
820
+ if (yes) return true;
821
+ for (;;) {
822
+ const answer = await prompter.select("Write these files?", [
823
+ {
824
+ value: "write",
825
+ label: "Write"
826
+ },
827
+ {
828
+ value: "diff",
829
+ label: "Show the files"
830
+ },
831
+ {
832
+ value: "cancel",
833
+ label: "Cancel, write nothing"
834
+ }
835
+ ], "write");
836
+ if (answer !== "diff") return answer === "write";
837
+ writes.forEach(({ file, text }) => {
838
+ output.line();
839
+ output.line(paint("bold", file));
840
+ text.split("\n").forEach((line) => output.line(` ${line}`));
841
+ });
842
+ }
843
+ };
844
+ /**
845
+ * `shiplane init`: finds every workspace folder, guesses how each ships from what it holds, asks only
846
+ * what it cannot tell, shows every file, writes them, then runs doctor. Run again, it offers the
847
+ * folders added since and never rewrites a unit file. `--yes` takes every guess, `--blank` writes
848
+ * commented templates.
849
+ */
850
+ const initRelease = async (context, { yes, blank }) => {
851
+ const { output, prompter, files } = context;
852
+ const existing = files.exists("shiplane.config.ts") ? await context.load() : null;
853
+ const adapters = context.adapters;
854
+ const candidates = scanFolders(context, adapters);
855
+ output.line(`${paint("dim", "┌")} ${paint("bold", "shiplane init")}`);
856
+ output.line(bar);
857
+ output.line(`${paint("green", "◇")} Workspace ${paint("dim", workspacePatterns(context.root).join(", "))}`);
858
+ output.line(bar);
859
+ if (existing) {
860
+ output.line(`${paint("cyan", "◆")} ${paint("bold", "Since the last init")}`);
861
+ candidates.filter(({ guess }) => guess).forEach(({ folder, guess }) => output.line(`${bar} ${paint("green", "+")} ${folder.dir.padEnd(14)}${paint("dim", `new folder, ${guess?.detection.reason ?? ""}`)}`));
862
+ output.line(`${bar} ${paint("dim", "=")} ${`${existing.units.length} folders`.padEnd(14)}${paint("dim", "unchanged, your edits kept")}`);
863
+ output.line(bar);
864
+ }
865
+ const placeable = candidates.filter(({ guess }) => guess !== null);
866
+ const width = Math.max(14, ...placeable.map(({ folder }) => folder.dir.length)) + 2;
867
+ placeable.forEach((candidate) => output.line(`${bar} ${candidateLine(candidate, width)}`));
868
+ const unplaced = candidates.length - placeable.length;
869
+ if (unplaced > 0) {
870
+ const folders = `${unplaced} folder${unplaced === 1 ? "" : "s"}`;
871
+ output.line(`${bar} ${paint("dim", `◻ ${folders} with nothing to ship them, versioned only (shiplane add <folder> ships one)`)}`);
872
+ }
873
+ output.line(bar);
874
+ const offered = placeable;
875
+ const pickedDirs = yes ? offered.map(({ folder }) => folder.dir) : await prompter.multiselect("Which folders ship somewhere?", offered.map(({ folder, guess }) => ({
876
+ value: folder.dir,
877
+ label: folder.dir,
878
+ hint: guess ? `${guess.adapter.name} · ${guess.detection.reason}` : ""
879
+ })), offered.map(({ folder }) => folder.dir));
880
+ if (pickedDirs === null) {
881
+ output.line(paint("dim", "Nothing written."));
882
+ return true;
883
+ }
884
+ const placed = [];
885
+ for (const candidate of candidates.filter(({ folder }) => pickedDirs.includes(folder.dir))) {
886
+ const { folder, guess } = candidate;
887
+ const name = guess?.detection.certainty === "found" || yes ? guess?.adapter.name ?? "skip" : await prompter.select(`How does ${folder.dir} ship?`, [...adapters.map((adapter) => ({
888
+ value: adapter.name,
889
+ label: adapter.name,
890
+ hint: adapter.name === guess?.adapter.name ? `${guess.detection.reason} (recommended)` : ""
891
+ })), {
892
+ value: "skip",
893
+ label: "skip",
894
+ hint: "versioned, never shipped"
895
+ }], guess?.adapter.name);
896
+ const adapter = adapters.find((candidateAdapter) => candidateAdapter.name === name);
897
+ if (!adapter) continue;
898
+ const found = guess?.adapter === adapter ? guess.detection.options : {};
899
+ const options = blank ? {} : await askOptions(context, folder, adapter, found, yes);
900
+ placed.push({
901
+ folder,
902
+ adapter,
903
+ options,
904
+ reason: guess?.adapter === adapter ? guess.detection.reason : void 0
905
+ });
906
+ }
907
+ const extras = [...files.exists(".vscode") ? [{
908
+ value: "editor",
909
+ label: "editor autocompletion",
910
+ hint: editorSettingsFile
911
+ }] : []];
912
+ const editor = ((yes ? extras.map(({ value }) => value) : extras.length === 0 ? [] : await prompter.multiselect("Also set up", extras, extras.map(({ value }) => value))) ?? []).includes("editor");
913
+ const modules = [...existing?.modules ?? []];
914
+ const entries = [];
915
+ const pkg = releasePackage(files);
916
+ const named = placed.map((entry) => {
917
+ const { name, entry: added } = placeModule(entry.adapter, modules, pkg);
918
+ if (added) {
919
+ entries.push(added);
920
+ modules.push(moduleFor(entry.adapter, name));
921
+ }
922
+ return {
923
+ ...entry,
924
+ module: name
925
+ };
926
+ });
927
+ const writes = [];
928
+ if (!existing) writes.push({
929
+ file: CONFIG_FILE,
930
+ text: renderConfig(entries, pkg),
931
+ created: true
932
+ });
933
+ else {
934
+ let config = files.read("shiplane.config.ts") ?? "";
935
+ for (const entry of entries) config = addToConfig(config, entry, pkg) ?? config;
936
+ if (config !== files.read("shiplane.config.ts")) writes.push({
937
+ file: CONFIG_FILE,
938
+ text: config,
939
+ created: false
940
+ });
941
+ }
942
+ named.forEach(({ folder, adapter, module, options, reason }) => {
943
+ const schemaLine = editor ? void 0 : schemaLineFor(folder.dir);
944
+ writes.push({
945
+ file: path.posix.join(folder.dir, UNIT_FILE),
946
+ text: blank ? renderBlankUnit(module, adapter.settings, schemaLine) : renderUnit(module, options, {
947
+ reason,
948
+ schemaLine
949
+ }),
950
+ created: true
951
+ });
952
+ });
953
+ writes.push({
954
+ file: SCHEMA_FILE,
955
+ text: schemaText(modules),
956
+ created: !files.exists(SCHEMA_FILE)
957
+ });
958
+ if (editor) {
959
+ const current = files.read(editorSettingsFile);
960
+ const settings = withEditorSchema(current);
961
+ if (current?.includes(`./node_modules/.cache/shiplane/schema.json`)) {} else if (settings) writes.push({
962
+ file: editorSettingsFile,
963
+ text: settings,
964
+ created: !files.exists(editorSettingsFile)
965
+ });
966
+ else output.line(`${bar} ${paint("dim", `${editorSettingsFile} already maps yaml.schemas: add ./${SCHEMA_FILE} for **/${UNIT_FILE}`)}`);
967
+ }
968
+ if (!await review(context, writes, yes)) {
969
+ output.line(paint("dim", "Nothing written."));
970
+ return true;
971
+ }
972
+ writes.forEach(({ file, text }) => files.write(file, text));
973
+ output.line(`${paint("green", "◇")} Wrote ${writes.length} file${writes.length === 1 ? "" : "s"}`);
974
+ return doctor(context);
975
+ };
976
+ //#endregion
977
+ //#region src/application/addUnit.ts
978
+ /** `shiplane add <folder>`: init's questions for one folder, its unit file written. */
979
+ const addUnit = async (context, dir) => {
980
+ const { output, prompter, files } = context;
981
+ const folderDir = path.posix.normalize(dir).replace(/\/$/, "");
982
+ const candidate = scanFolders(context, context.adapters).find(({ folder }) => folder.dir === folderDir);
983
+ if (!candidate) {
984
+ output.line(`${paint("red", "✗")} ${folderDir} is not a workspace folder without a ${UNIT_FILE}`);
985
+ return false;
986
+ }
987
+ const { folder, guess } = candidate;
988
+ const name = guess?.detection.certainty === "found" ? guess.adapter.name : await prompter.select(`How does ${folder.dir} ship?`, context.adapters.map((adapter) => ({
989
+ value: adapter.name,
990
+ label: adapter.name,
991
+ hint: adapter.name === guess?.adapter.name ? `${guess.detection.reason} (recommended)` : ""
992
+ })), guess?.adapter.name);
993
+ const adapter = context.adapters.find((offered) => offered.name === name);
994
+ if (!adapter) return false;
995
+ const options = await askOptions(context, folder, adapter, guess?.adapter === adapter ? guess.detection.options : {}, false);
996
+ const file = path.posix.join(folder.dir, UNIT_FILE);
997
+ if (!await prompter.confirm(`Write ${file}?`)) {
998
+ output.line(paint("dim", "Nothing written."));
999
+ return true;
1000
+ }
1001
+ const release = await context.load();
1002
+ const pkg = releasePackage(files);
1003
+ const placed = placeModule(adapter, release.modules, pkg);
1004
+ files.write(file, renderUnit(placed.name, options, { reason: guess?.detection.reason }));
1005
+ if (placed.entry) {
1006
+ const config = addToConfig(files.read("shiplane.config.ts") ?? "", placed.entry, pkg);
1007
+ if (config) files.write(CONFIG_FILE, config);
1008
+ else output.line(`${paint("yellow", "!")} add ${moduleCall(placed.entry)} to the modules in ${CONFIG_FILE}`);
1009
+ }
1010
+ const modules = placed.entry ? [...release.modules, moduleFor(adapter, placed.name)] : release.modules;
1011
+ files.write(SCHEMA_FILE, schemaText(modules));
1012
+ output.line(`${paint("green", "◇")} Wrote ${file}`);
1013
+ return true;
1014
+ };
1015
+ /** `shiplane remove <unit>`: its unit file goes; changesets still version it. */
1016
+ const removeUnit = async (context, name) => {
1017
+ const { output, prompter, files } = context;
1018
+ const unit = (await context.load()).units.find((candidate) => candidate.name === name);
1019
+ if (!unit) {
1020
+ output.line(`${paint("red", "✗")} no unit named "${name}"`);
1021
+ return false;
1022
+ }
1023
+ if (!await prompter.confirm(`Stop shipping ${name}? It stays versioned.`)) return true;
1024
+ files.remove(unit.file);
1025
+ output.line(`${paint("green", "◇")} Removed ${unit.file}`);
1026
+ return true;
1027
+ };
1028
+ //#endregion
1029
+ //#region src/adapters/manifest/package-json-manifest.adapter.ts
1030
+ const PackageSchema = z.object({
1031
+ name: z.string(),
1032
+ version: z.string()
1033
+ });
1034
+ const packageJsonManifest = { read: (root, dir) => {
1035
+ const file = path.join(root, dir, "package.json");
1036
+ if (!fs.existsSync(file)) return null;
1037
+ const parsed = PackageSchema.safeParse(JSON.parse(fs.readFileSync(file, "utf8")));
1038
+ return parsed.success ? parsed.data : null;
1039
+ } };
1040
+ //#endregion
1041
+ //#region src/application/config/loadRelease.ts
1042
+ const EXTENSIONS = [
1043
+ "ts",
1044
+ "mts",
1045
+ "js",
1046
+ "mjs"
1047
+ ];
1048
+ /** The config's names, the one from before shiplane last: still read, listed to rename. */
1049
+ const CONFIG_FILES = [...EXTENSIONS.map((extension) => `shiplane.config.${extension}`), ...EXTENSIONS.map((extension) => `release.config.${extension}`)];
1050
+ const renameOf = (file) => /(^|\/)release\.(config|unit)\./.test(file) ? {
1051
+ from: file,
1052
+ to: file.replace(/(^|\/)release\./, "$1shiplane.")
1053
+ } : null;
1054
+ const findConfig = (root) => CONFIG_FILES.map((file) => path.join(root, file)).find((file) => fs.existsSync(file));
1055
+ const NAMES = ["shiplane"];
1056
+ const resolves = (specifier) => {
1057
+ try {
1058
+ return fileURLToPath(import.meta.resolve(specifier));
1059
+ } catch {
1060
+ return null;
1061
+ }
1062
+ };
1063
+ const selfAliases = () => {
1064
+ const own = NAMES.find((name) => resolves(name) !== null);
1065
+ if (!own) return {};
1066
+ return Object.fromEntries([
1067
+ "",
1068
+ "/plugin",
1069
+ "/testing"
1070
+ ].flatMap((sub) => {
1071
+ const target = resolves(`${own}${sub}`);
1072
+ return target ? NAMES.map((name) => [`${name}${sub}`, target]) : [];
1073
+ }));
1074
+ };
1075
+ /** A port no flow fills yet: a release that never loaded has nothing to run on. */
1076
+ const unset = (port) => ({
1077
+ name: "unset",
1078
+ create: () => {
1079
+ throw new Error(`no ${port} adapter: shiplane.config.ts sets none`);
1080
+ }
1081
+ });
1082
+ /** The flow of a release that did not load: every port unset. */
1083
+ const unsetFlow = () => releaseFlow({
1084
+ sourceControl: unset("sourceControl"),
1085
+ codeHost: unset("codeHost"),
1086
+ ciPipeline: unset("ciPipeline"),
1087
+ versioning: unset("versioning")
1088
+ });
1089
+ const FLOW_MISSING = [
1090
+ "flow is missing: give it one, such as",
1091
+ "flow: releaseFlow({ sourceControl: gitSourceControl(), codeHost: gitHubCodeHost(),",
1092
+ "ciPipeline: gitHubActionsCiPipeline(), versioning: changesetsVersioning() }),",
1093
+ "from the shiplane-git, shiplane-github and shiplane-changesets plugins"
1094
+ ].join(" ");
1095
+ const typed = (value, type) => isRecord(value) && value.type === type && typeof value.name === "string";
1096
+ const isFlow = (value) => isRecord(value) && value.type === "flow";
1097
+ const isModule = (value) => typed(value, "module");
1098
+ const isFeature = (value) => typed(value, "feature");
1099
+ const listOf = (value, key, is, example) => {
1100
+ if (value === void 0) return [];
1101
+ if (!Array.isArray(value)) throw new Error(`${key} is not a list, such as ${key}: [${example}]`);
1102
+ return value.map((item, index) => {
1103
+ if (!is(item)) throw new Error(`${key}[${index}] is not one of its ${key}, such as ${example}`);
1104
+ return item;
1105
+ });
1106
+ };
1107
+ const LEFTOVERS = {
1108
+ plugins: "plugins is gone: defineRelease takes flow, modules and features, such as modules: [backendService({ serverHosting: flyServerHosting() })]",
1109
+ latest: "latest is gone: the first app of the first module is the Latest release"
1110
+ };
1111
+ /** The modules, their names unique and their adapters' settings free of `module`. */
1112
+ const checkModules = (modules, features) => {
1113
+ const names = [...modules, ...features].map(({ name }) => name);
1114
+ names.forEach((name, index) => {
1115
+ if (names.indexOf(name) !== index) throw new Error(`two modules are named "${name}": give one its own, such as { name: "${name}-2", ... }`);
1116
+ });
1117
+ const clash = modules.find(({ settings }) => "module" in settings.shape);
1118
+ if (clash) throw new Error(`"module" is reserved for the unit file's module, yet ${clash.name}'s adapter takes it`);
1119
+ };
1120
+ const tagFormatOf = (tag) => {
1121
+ if (tag === void 0) return DEFAULT_TAG_FORMAT;
1122
+ if (typeof tag !== "string" || !tag.includes("{version}")) throw new Error("tag must name the version, such as tag: \"v{version}\"");
1123
+ return tag;
1124
+ };
1125
+ const releasesCommitsOf = (choice) => {
1126
+ if (choice === void 0 || choice === "ignore") return false;
1127
+ if (choice === "release") return true;
1128
+ throw new Error("commitsWithoutChangeset is \"release\" or \"ignore\"");
1129
+ };
1130
+ const readConfig = async (file, aliases) => {
1131
+ const loaded = await createJiti(import.meta.url, {
1132
+ alias: aliases,
1133
+ moduleCache: false,
1134
+ fsCache: false
1135
+ }).import(file, { default: true });
1136
+ if (!isRecord(loaded)) throw new Error("its default export is not defineRelease({ modules })");
1137
+ for (const [key, message] of Object.entries(LEFTOVERS)) if (key in loaded) throw new Error(message);
1138
+ if (loaded.flow === void 0) throw new Error(FLOW_MISSING);
1139
+ if (!isFlow(loaded.flow)) throw new Error("flow is not a release flow, such as flow: releaseFlow({ ... })");
1140
+ const modules = listOf(loaded.modules, "modules", isModule, "webApp({ ... })");
1141
+ const features = listOf(loaded.features, "features", isFeature, "releaseComments({ ... })");
1142
+ checkModules(modules, features);
1143
+ const units = Array.isArray(loaded.units) ? loaded.units.filter((unit) => typeof unit === "string") : void 0;
1144
+ const display = isRecord(loaded.display) ? loaded.display : {};
1145
+ const flag = (value) => typeof value === "boolean" ? value : void 0;
1146
+ return {
1147
+ flow: loaded.flow,
1148
+ modules,
1149
+ features,
1150
+ units,
1151
+ display: {
1152
+ verbose: flag(display.verbose),
1153
+ mascot: mascotOf(display.mascot)
1154
+ },
1155
+ tagFormat: tagFormatOf(loaded.tag),
1156
+ releasesCommits: releasesCommitsOf(loaded.commitsWithoutChangeset)
1157
+ };
1158
+ };
1159
+ /** A config's mascot: true, false, frames per mood, or a function; anything else is ignored. */
1160
+ const mascotOf = (value) => {
1161
+ if (typeof value === "boolean" || typeof value === "function") return value;
1162
+ if (!isRecord(value)) return void 0;
1163
+ const frames = Object.entries(value).filter(([, list]) => Array.isArray(list) && list.every((frame) => typeof frame === "string"));
1164
+ return frames.length > 0 ? Object.fromEntries(frames) : void 0;
1165
+ };
1166
+ /** Apps in release order: by module as the config lists them, then by name. */
1167
+ const inReleaseOrder = (read, modules) => {
1168
+ const rank = (unit) => modules.findIndex(({ name }) => name === unit.module);
1169
+ return [...read].sort((left, right) => rank(left.unit) - rank(right.unit) || left.unit.name.localeCompare(right.unit.name));
1170
+ };
1171
+ const referenceProblems = ({ unit, file }, ordered) => referencesIn(unit.options).flatMap(({ unit: name, key, at }) => {
1172
+ const other = ordered.find((candidate) => candidate.unit.name === name)?.unit;
1173
+ const line = file.lineOf(at);
1174
+ if (!other) return [{
1175
+ file: unit.file,
1176
+ line,
1177
+ message: `"${name}" has no ${UNIT_FILE} to read from`
1178
+ }];
1179
+ if (valueAt(other.options, key.split(".")) === void 0) return [{
1180
+ file: unit.file,
1181
+ line,
1182
+ message: `"${name}" has no "${key}" in ${other.file}`
1183
+ }];
1184
+ const position = (target) => ordered.findIndex((candidate) => candidate.unit === target);
1185
+ if (other !== unit && position(other) > position(unit)) return [{
1186
+ file: unit.file,
1187
+ line,
1188
+ message: `"${unit.name}" reads ${name}.${key}, which is released after it`,
1189
+ hint: other.module === unit.module ? `${unit.name} and ${name} share ${unit.module}: give ${name} a module of its own, listed first` : `move ${other.module} before ${unit.module} in the modules of shiplane.config.ts`
1190
+ }];
1191
+ return [];
1192
+ });
1193
+ /**
1194
+ * The release as written: what `shiplane.config.ts` composes, and one app per folder that holds a
1195
+ * `shiplane.unit.yml`, in release order. Every problem is collected, never thrown.
1196
+ */
1197
+ const loadRelease = async (root, options = {}) => {
1198
+ const empty = (problems) => ({
1199
+ root,
1200
+ flow: unsetFlow(),
1201
+ tagFormat: DEFAULT_TAG_FORMAT,
1202
+ modules: [],
1203
+ features: [],
1204
+ units: [],
1205
+ problems
1206
+ });
1207
+ const configFile = findConfig(root);
1208
+ if (!configFile) return empty([{
1209
+ file: "shiplane.config.ts",
1210
+ message: "No shiplane.config.ts in this repository",
1211
+ hint: "shiplane init writes it, with a shiplane.unit.yml next to each app"
1212
+ }]);
1213
+ let config;
1214
+ try {
1215
+ config = await readConfig(configFile, options.aliases ?? selfAliases());
1216
+ } catch (error) {
1217
+ const reason = error instanceof Error ? error.message : String(error);
1218
+ return empty([{
1219
+ file: path.basename(configFile),
1220
+ message: `it did not load: ${reason.split("\n")[0]}`
1221
+ }]);
1222
+ }
1223
+ const manifests = options.manifests ?? packageJsonManifest;
1224
+ const problems = [];
1225
+ const features = config.features.map(({ name }) => name);
1226
+ const ordered = inReleaseOrder(expandPatterns(root, config.units ?? workspacePatterns(root)).flatMap((dir) => {
1227
+ const relative = UNIT_FILES.map((name) => path.posix.join(dir, name)).find((file) => fs.existsSync(path.join(root, file)));
1228
+ if (!relative) return [];
1229
+ const result = readUnitFile(relative, fs.readFileSync(path.join(root, relative), "utf8"), config.modules, features);
1230
+ problems.push(...result.problems);
1231
+ const manifest = manifests.read(root, dir);
1232
+ if (!manifest) problems.push({
1233
+ file: relative,
1234
+ message: "no package.json next to it to read its name and version"
1235
+ });
1236
+ if (!result.unit || !manifest) return [];
1237
+ return [{
1238
+ unit: {
1239
+ name: dir === "." ? manifest.name.replace(/^@[^/]+\//, "") : path.posix.basename(dir),
1240
+ dir,
1241
+ file: relative,
1242
+ packageName: manifest.name,
1243
+ version: manifest.version,
1244
+ module: result.unit.module,
1245
+ ...result.unit.buildCommand ? { buildCommand: result.unit.buildCommand } : {},
1246
+ options: result.unit.options,
1247
+ after: []
1248
+ },
1249
+ file: result.unit
1250
+ }];
1251
+ }), config.modules);
1252
+ ordered.forEach((entry, index) => {
1253
+ const twin = ordered.findIndex(({ unit }) => unit.name === entry.unit.name);
1254
+ if (twin !== index) problems.push({
1255
+ file: entry.unit.file,
1256
+ message: `two folders are both named "${entry.unit.name}"`,
1257
+ hint: `rename one of ${ordered[twin]?.unit.dir} and ${entry.unit.dir}`
1258
+ });
1259
+ problems.push(...referenceProblems(entry, ordered));
1260
+ entry.unit.after = [...new Set(referencesIn(entry.unit.options).map(({ unit }) => unit))].filter((name) => name !== entry.unit.name && ordered.some(({ unit }) => unit.name === name));
1261
+ });
1262
+ return {
1263
+ root,
1264
+ flow: config.flow,
1265
+ modules: config.modules,
1266
+ features: config.features,
1267
+ units: ordered.map(({ unit }) => unit),
1268
+ problems: sortProblems(problems),
1269
+ display: config.display,
1270
+ renames: [path.basename(configFile), ...ordered.map(({ unit }) => unit.file)].flatMap((file) => renameOf(file) ?? []),
1271
+ tagFormat: config.tagFormat,
1272
+ releasesCommits: config.releasesCommits
1273
+ };
1274
+ };
1275
+ //#endregion
1276
+ //#region src/application/docsFor.ts
1277
+ /**
1278
+ * `shiplane docs <module or adapter>`: every key a unit file takes, described, with its default. A
1279
+ * module name reads the release config; an adapter name, the official adapters and those composed.
1280
+ */
1281
+ const docsFor = async (context, name) => {
1282
+ const { output } = context;
1283
+ const release = await context.load();
1284
+ const module = release.modules.find((candidate) => candidate.name === name);
1285
+ const adapters = [...context.adapters, ...release.modules.map(({ provider, settings }) => ({
1286
+ name: provider,
1287
+ settings
1288
+ }))];
1289
+ const adapter = adapters.find((candidate) => candidate.name === name);
1290
+ const found = module ? {
1291
+ title: `module: ${module.name} ${paint("dim", `with ${module.provider}`)}`,
1292
+ settings: module.settings
1293
+ } : adapter && {
1294
+ title: `${adapter.name} ${paint("dim", "adapter")}`,
1295
+ settings: adapter.settings
1296
+ };
1297
+ if (!found) {
1298
+ const known = [...new Set([...release.modules.map((candidate) => candidate.name), ...adapters.map((candidate) => candidate.name)])];
1299
+ output.line(`${paint("red", "✗")} no module or adapter "${name}": ${known.join(", ")}`);
1300
+ return false;
1301
+ }
1302
+ const keys = documentedKeys(found.settings);
1303
+ const width = Math.max(8, ...keys.map(({ key }) => key.length)) + 2;
1304
+ output.line();
1305
+ output.line(` ${paint("bold", found.title)}`);
1306
+ output.line();
1307
+ keys.forEach(({ key, description, default: fallback, required }) => {
1308
+ const note = required ? paint("yellow", "required") : fallback === void 0 ? "optional" : `default: ${typeof fallback === "string" ? fallback : JSON.stringify(fallback)}`;
1309
+ output.line(` ${key.padEnd(width)}${description}`);
1310
+ output.line(` ${" ".repeat(width)}${paint("dim", note)}`);
1311
+ });
1312
+ output.line();
1313
+ return true;
1314
+ };
1315
+ //#endregion
1316
+ //#region src/application/newAdapter.ts
1317
+ const adapterFile = (name, factory, pkg) => `import { defineServerHosting, z } from "${pkg}";
1318
+
1319
+ /** Hosts a server on ${name}. Replace the command with the one that deploys it. */
1320
+ export const ${factory} = () =>
1321
+ defineServerHosting({
1322
+ name: "${name}",
1323
+ settings: z.object({
1324
+ service: z.string().describe("What to deploy"),
1325
+ }),
1326
+ describe: ({ options }) => \`\${options.service} on ${name}\`,
1327
+ jobs: ({ tag, options }) => [
1328
+ {
1329
+ label: \`deploy \${tag} to \${options.service}\`,
1330
+ local: [{ command: "echo", args: ["deploy", options.service] }],
1331
+ },
1332
+ ],
1333
+ });
1334
+ `;
1335
+ const testFile = (name, factory, pkg) => `import { serverHostingContract, serverHostingFake } from "${pkg}/testing";
1336
+
1337
+ import { ${factory} } from "./${name}";
1338
+
1339
+ // The contract every server host passes, run on this adapter and on the Fake tests use in its place.
1340
+ serverHostingContract([
1341
+ { adapter: ${factory}(), settings: { service: "web-preview" } },
1342
+ { adapter: serverHostingFake(), settings: { service: "web-preview" } },
1343
+ ]);
1344
+ `;
1345
+ /**
1346
+ * `shiplane adapter new <name>`: a server hosting adapter, the port's contract suite run on it and on
1347
+ * its Fake, and a module for it in the root config.
1348
+ */
1349
+ const newAdapter = async (context, name) => {
1350
+ const { output, files } = context;
1351
+ if (!/^[a-z][a-z0-9-]*$/.test(name)) {
1352
+ output.line(`${paint("red", "✗")} an adapter name is lowercase words joined by dashes, like my-host`);
1353
+ return false;
1354
+ }
1355
+ const factory = `${factoryName(name)}ServerHosting`;
1356
+ const pkg = releasePackage(files);
1357
+ const file = `release/adapters/${name}.ts`;
1358
+ if (files.exists(file)) {
1359
+ output.line(`${paint("red", "✗")} ${file} already exists`);
1360
+ return false;
1361
+ }
1362
+ const config = addToConfig(files.read("shiplane.config.ts") ?? "", {
1363
+ factory: "backendService",
1364
+ port: "serverHosting",
1365
+ adapter: factory,
1366
+ name,
1367
+ from: `./release/adapters/${name}`
1368
+ }, pkg);
1369
+ if (!config) {
1370
+ output.line(`${paint("red", "✗")} ${CONFIG_FILE} has no modules list to add it to: run shiplane init first`);
1371
+ return false;
1372
+ }
1373
+ files.write(file, adapterFile(name, factory, pkg));
1374
+ files.write(`release/adapters/${name}.test.ts`, testFile(name, factory, pkg));
1375
+ files.write(CONFIG_FILE, config);
1376
+ output.line(`${paint("green", "◇")} Wrote ${file}, its contract test, and a ${name} module in ${CONFIG_FILE}`);
1377
+ output.line(`${paint("dim", "└")} Next: point an app at it with ${paint("cyan", `module: ${name}`)}`);
1378
+ return Promise.resolve(true);
1379
+ };
1380
+ //#endregion
1381
+ //#region src/domain/releasePr.ts
1382
+ /**
1383
+ * Where `pnpm shiplane` picks up, from what main and GitHub hold right now. A merged release is
1384
+ * tagged and shipped before the next one is opened.
1385
+ */
1386
+ const nextStep = ({ pending, releasePrs, untagged, unreleased }) => {
1387
+ if (releasePrs.length > 0) return {
1388
+ step: "wait-merge",
1389
+ prs: releasePrs
1390
+ };
1391
+ if ((pending > 0 || unreleased > 0) && untagged === 0) return { step: "release-pr" };
1392
+ return { step: "ship" };
1393
+ };
1394
+ const RELEASE_BRANCH_PREFIX = "shiplane/release-";
1395
+ const twoDigits = (value) => String(value).padStart(2, "0");
1396
+ const releaseBranchName = (now) => `${RELEASE_BRANCH_PREFIX}${now.getFullYear()}-${twoDigits(now.getMonth() + 1)}-${twoDigits(now.getDate())}-${twoDigits(now.getHours())}${twoDigits(now.getMinutes())}`;
1397
+ const sentence = (items) => items.length < 2 ? items.join("") : `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`;
1398
+ const MAX_LINE = 100;
1399
+ /** One app's release commit: `chore(api): release v0.0.4`. */
1400
+ const releaseCommitTitle = ({ app, to }) => `chore(${app}): release v${to}`;
1401
+ MAX_LINE - 9;
1402
+ const counted = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
1403
+ /** What a title calls a unit of each module kind; several kinds at once are apps. */
1404
+ const NOUN = {
1405
+ "published-package": "package",
1406
+ "backend-service": "service",
1407
+ "web-app": "web app",
1408
+ "mobile-app": "mobile app",
1409
+ "internal-tool": "tool"
1410
+ };
1411
+ /**
1412
+ * The apps, gathered into families in their own order: a root moving with its `root-*` apps
1413
+ * (`shiplane`, `shiplane-npm`) is one family; any other app is a family of one.
1414
+ */
1415
+ const releaseFamilies = (bumps) => {
1416
+ return bumps.filter(({ app }) => !bumps.some((other) => other.app !== app && app.startsWith(`${other.app}-`))).map((root) => bumps.filter(({ app }) => app === root.app || app.startsWith(`${root.app}-`)));
1417
+ };
1418
+ /** One family as a title names it: `api v0.0.4`, `shiplane and 7 plugins v0.1.0`, `api v0.3.0 and 2 more services`. */
1419
+ const familyLabel = ([root, ...members], kindOf) => {
1420
+ if (!root) return "";
1421
+ if (members.length < 2) return [root, ...members].map(({ app, to }) => `${app} v${to}`).join(", ");
1422
+ const kinds = new Set([root, ...members].map(({ app }) => kindOf(app)));
1423
+ const [kind] = kinds;
1424
+ const noun = kinds.size === 1 && kind && NOUN[kind] || "app";
1425
+ const rest = noun === "package" ? counted(members.length, "plugin") : `${members.length} more ${counted(members.length, noun).replace(/^\d+ /, "")}`;
1426
+ return members.every(({ to }) => to === root.to) ? `${root.app} and ${rest} v${root.to}` : `${root.app} v${root.to} and ${rest}`;
1427
+ };
1428
+ /**
1429
+ * The release PRs a release opens, all from main at once: one per app, a family counting as one.
1430
+ * Apps `linked` (one changeset naming both, or one moving with the other) share a PR, so no two
1431
+ * PRs ever touch the same file.
1432
+ */
1433
+ const releasePrGroups = (bumps, linked) => {
1434
+ const groups = releaseFamilies(bumps).map((family) => new Set(family.map(({ app }) => app)));
1435
+ const merged = linked.reduce((current, apps) => {
1436
+ const touched = current.filter((group) => apps.some((app) => group.has(app)));
1437
+ if (touched.length < 2) return current;
1438
+ const union = new Set(touched.flatMap((group) => [...group]));
1439
+ return [...current.filter((group) => !touched.includes(group)), union];
1440
+ }, groups);
1441
+ const order = (group) => bumps.findIndex(({ app }) => group.has(app));
1442
+ return merged.sort((left, right) => order(left) - order(right)).map((group) => bumps.filter(({ app }) => group.has(app)));
1443
+ };
1444
+ /** Whether a title still fits once a squash merge appends its PR number. */
1445
+ const titleFits = (title) => title.length <= 91;
1446
+ /**
1447
+ * Conventional, and naming every app it brings, never a bare count: `chore(api): release v0.0.4`,
1448
+ * `chore(release): api v0.0.2 and admin v0.1.0`, or, when listing each one is too long, families
1449
+ * by their root: `chore(release): shiplane and 7 plugins v0.1.0, landing v1.2.0 and expo v2.1.0`.
1450
+ * One release is one PR: a title too long even then stays whole, see `titleFits`.
1451
+ */
1452
+ const releaseTitle = (bumps, kindOf = () => void 0) => {
1453
+ const [first, ...others] = bumps;
1454
+ if (!first) return "chore(release): package changelogs";
1455
+ if (others.length === 0) return releaseCommitTitle(first);
1456
+ const families = releaseFamilies(bumps);
1457
+ const [only] = families;
1458
+ if (families.length === 1 && only?.[0]) return releaseCommitTitle(only[0]);
1459
+ const every = `chore(release): ${sentence(bumps.map(({ app, to }) => `${app} v${to}`))}`;
1460
+ if (titleFits(every)) return every;
1461
+ families.sort((left, right) => Number(right.length > 1) - Number(left.length > 1));
1462
+ const labels = families.map((family) => familyLabel(family, kindOf));
1463
+ return `chore(release): ${labels.at(-1)?.includes(" and ") ? labels.join(", ") : sentence(labels)}`;
1464
+ };
1465
+ /** A bullet wrapped to commitlint's 100-character body lines, continued under its text. */
1466
+ const bullet = (text) => text.split(" ").reduce((lines, word) => {
1467
+ const last = lines.at(-1);
1468
+ if (last !== void 0 && `${last} ${word}`.length <= MAX_LINE) return [...lines.slice(0, -1), `${last} ${word}`];
1469
+ return [...lines, `${last === void 0 ? "-" : " "} ${word}`];
1470
+ }, []).join("\n");
1471
+ /** The release commit's body: each app's version, then what its users get. */
1472
+ const releaseCommitBody = (bumps) => bumps.map(({ app, to, notes, movedWith }) => {
1473
+ const lines = notes.length > 0 ? notes : movedWith.length > 0 ? [`Moves with ${movedWith.join(", ")}.`] : [];
1474
+ return [`${app} ${to}`, ...lines.map(bullet)].join("\n");
1475
+ }).join("\n\n");
1476
+ /** The release PR's body; `onMerge` says what happens to each unit once it is merged. */
1477
+ const releasePrBody = (bumps, onMerge) => {
1478
+ const appWidth = Math.max(3, ...bumps.map(({ app }) => app.length));
1479
+ const versionWidth = Math.max(7, ...bumps.map(({ from, to }) => `${from} → ${to}`.length));
1480
+ const row = (cells) => `| ${cells.join(" | ")} |`;
1481
+ const table = [
1482
+ row([
1483
+ "App".padEnd(appWidth),
1484
+ "Version".padEnd(versionWidth),
1485
+ "On merge"
1486
+ ]),
1487
+ row([
1488
+ "-".repeat(appWidth),
1489
+ "-".repeat(versionWidth),
1490
+ "--------"
1491
+ ]),
1492
+ ...bumps.map((bump) => row([
1493
+ bump.app.padEnd(appWidth),
1494
+ `${bump.from} → ${bump.to}`.padEnd(versionWidth),
1495
+ onMerge(bump)
1496
+ ]))
1497
+ ];
1498
+ const notes = bumps.flatMap(({ app, to, notes: lines }) => lines.length > 0 ? [
1499
+ "",
1500
+ `### ${app} ${to}`,
1501
+ "",
1502
+ ...lines.map((line) => `- ${line}`)
1503
+ ] : []);
1504
+ return [
1505
+ "## 🎯 What & why",
1506
+ "",
1507
+ "Versions the changesets merged since the last release. Squash and merge it by hand: `pnpm shiplane`, still running or run again, tags and ships to preview once it is merged.",
1508
+ "",
1509
+ ...bumps.length > 0 ? table : ["Internal packages only: changelogs, nothing ships."],
1510
+ ...notes,
1511
+ "",
1512
+ "## ✅ Testing",
1513
+ "",
1514
+ "Versions, changelogs and version files only. No UI change."
1515
+ ].join("\n");
1516
+ };
1517
+ const MERGE_BUTTON = [
1518
+ {
1519
+ value: "--merge",
1520
+ label: "Create a merge commit",
1521
+ hint: "every commit, joined by a merge commit"
1522
+ },
1523
+ {
1524
+ value: "--squash",
1525
+ label: "Squash and merge",
1526
+ hint: "the commits combined into one"
1527
+ },
1528
+ {
1529
+ value: "--rebase",
1530
+ label: "Rebase and merge",
1531
+ hint: "every commit, rebased onto main"
1532
+ }
1533
+ ];
1534
+ /** The methods as GitHub's merge button lists them, preselected as the pull request page does. */
1535
+ const mergeChoices = ({ allowed, preselected }) => {
1536
+ const choices = MERGE_BUTTON.filter(({ value }) => allowed.includes(value));
1537
+ return {
1538
+ choices,
1539
+ initial: preselected && allowed.includes(preselected) ? preselected : choices[0]?.value
1540
+ };
1541
+ };
1542
+ const WAIT_KEYS = {
1543
+ d: "diff",
1544
+ m: "merge",
1545
+ o: "open"
1546
+ };
1547
+ /** What a key does while the release waits for its pull request to merge. */
1548
+ const waitKey = (name) => name && WAIT_KEYS[name] || null;
1549
+ //#endregion
1550
+ //#region src/domain/companions.ts
1551
+ /** The shortest chain of moving packages from `from` to one a changeset names, breadth first. */
1552
+ const chainTo = (from, dependencies, moving, named) => {
1553
+ const seen = /* @__PURE__ */ new Set();
1554
+ let paths = [[from]];
1555
+ while (paths.length > 0) {
1556
+ const next = [];
1557
+ for (const path of paths) {
1558
+ const last = path[path.length - 1] ?? from;
1559
+ for (const dependency of dependencies[last] ?? []) {
1560
+ if (!moving.has(dependency) || seen.has(dependency)) continue;
1561
+ seen.add(dependency);
1562
+ const chain = [...path, dependency];
1563
+ if (named.has(dependency)) return chain.slice(1);
1564
+ next.push(chain);
1565
+ }
1566
+ }
1567
+ paths = next;
1568
+ }
1569
+ return [];
1570
+ };
1571
+ /**
1572
+ * Preview: the units a release moves that the person did not pick. changesets moves a unit whenever
1573
+ * a workspace package it uses moves, so it cannot stay behind; this says through which package.
1574
+ */
1575
+ const draggedUnits = (plan, dependencies, units, scope) => {
1576
+ const moving = new Set(plan.releases.map(({ name }) => name));
1577
+ const named = new Set(plan.releases.filter(({ changesets }) => changesets.length > 0).map(({ name }) => name));
1578
+ const picked = units.filter(({ name }) => scope.has(name));
1579
+ return units.flatMap(({ name: app, packageName }) => {
1580
+ const release = plan.releases.find(({ name }) => name === packageName);
1581
+ if (scope.has(app) || !release) return [];
1582
+ const chain = chainTo(packageName, dependencies, moving, named);
1583
+ const source = chain[chain.length - 1];
1584
+ const movers = picked.filter((unit) => plan.changesets.some(({ releases }) => releases.some(({ name }) => name === source) && releases.some(({ name }) => name === unit.packageName))).map(({ name }) => name);
1585
+ const whose = movers.length > 0 ? `${movers.join(", ")}'s changes move` : "this release moves";
1586
+ return [{
1587
+ app,
1588
+ version: release.newVersion,
1589
+ with: movers,
1590
+ why: chain.length > 0 ? `uses ${chain.join(" → ")}, which ${whose}` : "moves with this release"
1591
+ }];
1592
+ });
1593
+ };
1594
+ const OWN_CHANGE = /^- ([0-9a-f]{7,40}): /gm;
1595
+ const DEPENDENCY_CHANGES = /^- Updated dependencies \[([^\]]+)\]/gm;
1596
+ /** The changes a version carries: its own, and those a package it uses moved for. */
1597
+ const changeIds = (notes) => new Set([...[...notes.matchAll(OWN_CHANGE)].flatMap(([, id]) => id ? [id] : []), ...[...notes.matchAll(DEPENDENCY_CHANGES)].flatMap(([, ids]) => (ids ?? "").split(",").map((id) => id.trim()))]);
1598
+ /** A change's first line in these notes, with an ellipsis when it goes on. */
1599
+ const summaryOf = (notes, id) => {
1600
+ const lines = notes.split("\n");
1601
+ const index = lines.findIndex((line) => line.startsWith(`- ${id}: `));
1602
+ const first = lines[index]?.slice(`- ${id}: `.length).trim();
1603
+ if (index < 0 || !first) return null;
1604
+ return /^ {2}\S/.test(lines[index + 1] ?? "") ? `${first}…` : first;
1605
+ };
1606
+ /** The packages listed under the `Updated dependencies` line that names this change. */
1607
+ const packagesMovedFor = (notes, id) => {
1608
+ const lines = notes.split("\n");
1609
+ const start = lines.findIndex((line) => line.startsWith("- Updated dependencies [") && line.includes(id));
1610
+ if (start < 0) return [];
1611
+ const listed = lines.slice(start + 1);
1612
+ const end = listed.findIndex((line) => !/^ {2}- \S+@/.test(line));
1613
+ return (end < 0 ? listed : listed.slice(0, end)).map((line) => line.trim().slice(2).replace(/@[^@]*$/, ""));
1614
+ };
1615
+ /** Why two versions went out together: the change they share, or the package both moved for. */
1616
+ const sharedReason = (partner, other, id) => {
1617
+ const summary = summaryOf(partner.notes, id) ?? summaryOf(other.notes, id);
1618
+ if (summary) return ` for: ${summary}`;
1619
+ const theirs = new Set(packagesMovedFor(partner.notes, id));
1620
+ const both = packagesMovedFor(other.notes, id).filter((name) => theirs.has(name));
1621
+ return both.length > 0 ? `: both use ${both.join(", ")}, which moved` : "";
1622
+ };
1623
+ /**
1624
+ * Production: the units preview runs with the picked ones that are not picked. Two versions went to
1625
+ * preview together when their notes share a change, their own or one a package they use moved for.
1626
+ */
1627
+ const releasedTogether = (picked, others) => others.flatMap((other) => {
1628
+ const ids = changeIds(other.notes);
1629
+ const partners = picked.flatMap((partner) => {
1630
+ const shared = [...changeIds(partner.notes)].find((id) => ids.has(id));
1631
+ return shared ? [{
1632
+ partner,
1633
+ shared
1634
+ }] : [];
1635
+ });
1636
+ const [first] = partners;
1637
+ if (!first) return [];
1638
+ const names = partners.map(({ partner }) => `${partner.app} ${partner.version}`).join(", ");
1639
+ return [{
1640
+ app: other.app,
1641
+ version: other.version,
1642
+ with: partners.map(({ partner }) => partner.app),
1643
+ why: `went to preview with ${names}${sharedReason(first.partner, other, first.shared)}`
1644
+ }];
1645
+ });
1646
+ //#endregion
1647
+ //#region src/application/readScope.ts
1648
+ const MANIFEST = "package.json";
1649
+ const unitRefs = (units) => units.map(({ name, packageName }) => ({
1650
+ name,
1651
+ packageName
1652
+ }));
1653
+ /** The units the pending changesets name. */
1654
+ const namedUnits = async ({ release, services }) => new Set((await services.versioning.pending()).flatMap(({ text }) => changesetApps(text, unitRefs(release.units))));
1655
+ /** Units whose folder moved since their current version, that no changeset or bump ships. */
1656
+ const findUnreleased = async ({ release, services: { sourceControl: source } }, named) => {
1657
+ if (!release.releasesCommits) return [];
1658
+ return unreleasedApps((await Promise.all(release.units.map(async ({ name, dir, version }) => {
1659
+ const since = await source.tagCommit(tagName(name, version, release.tagFormat)) ?? (await source.versionCommit(dir, "package.json", version))?.sha;
1660
+ if (!since) return [];
1661
+ return [{
1662
+ app: name,
1663
+ version,
1664
+ commits: await source.subjectsSince(since, dir, UNIT_FILES)
1665
+ }];
1666
+ }))).flat(), named);
1667
+ };
1668
+ /** A tag's deploy on an environment, from every record the host keeps. */
1669
+ const deployedOn = (history, tag, environment) => {
1670
+ const states = history.filter(({ title }) => title === deployRunTitle(tag, environment)).map(({ state }) => state);
1671
+ if (states.includes("done")) return "done";
1672
+ return states.includes("running") ? "running" : "none";
1673
+ };
1674
+ /**
1675
+ * Each unit as the first question sees it: git for what is new, the host's deploy records for what
1676
+ * each environment runs (offline, nothing counts as deployed).
1677
+ */
1678
+ const readScope = async (context, environment) => {
1679
+ const { release, services } = context;
1680
+ const pending = await services.versioning.pending();
1681
+ const refs = unitRefs(release.units);
1682
+ const named = pending.map(({ text }) => changesetApps(text, refs));
1683
+ const unreleased = await findUnreleased(context, new Set(named.flat()));
1684
+ const [deployed, tags] = await Promise.all([services.codeHost.deployments().catch(() => []), services.sourceControl.tags()]);
1685
+ return Promise.all(release.units.map(async (unit) => {
1686
+ const tag = tagName(unit.name, unit.version, context.release.tagFormat);
1687
+ const target = moduleOf(context, unit);
1688
+ const decidedBy = target?.decidedBy;
1689
+ const commit = await services.sourceControl.versionCommit(unit.dir, MANIFEST, unit.version);
1690
+ const tagged = await services.sourceControl.tagCommit(tag) !== null;
1691
+ const live = async (on) => {
1692
+ if (!target?.live || !tagged) return deployedOn(deployed, tag, on) === "done";
1693
+ const { head } = await services.sourceControl.position();
1694
+ const input = jobInput(context, target, unit, {
1695
+ tag,
1696
+ environment: on,
1697
+ commit: head
1698
+ });
1699
+ return target.live(decideContext(context), input).catch(() => false);
1700
+ };
1701
+ return {
1702
+ app: unit.name,
1703
+ version: unit.version,
1704
+ changesets: named.filter((apps) => apps.includes(unit.name)).length,
1705
+ commits: unreleased.find((entry) => entry.app === unit.name)?.commits.length ?? 0,
1706
+ tagged,
1707
+ versioned: commit !== null && cameWithRelease({
1708
+ app: unit.name,
1709
+ version: unit.version,
1710
+ commit
1711
+ }),
1712
+ firstRelease: !tagged && commit !== null && firstRelease(unit.name, unit.version, tags, context.release.tagFormat),
1713
+ onChannel: await live(environment),
1714
+ onPreview: await live("preview"),
1715
+ ...decidedBy ? { decidedBy } : {},
1716
+ ...target?.releaseOnly ? { releaseOnly: true } : {}
1717
+ };
1718
+ }));
1719
+ };
1720
+ //#endregion
1721
+ //#region src/application/prepareRelease.ts
1722
+ const NOTHING_HELD = {
1723
+ ships: [],
1724
+ waits: []
1725
+ };
1726
+ /** The person's answer to a plugin's choice; the suggestion without a terminal or with --yes. */
1727
+ const choose = async ({ prompter, options }, choice) => {
1728
+ if (!choice) return null;
1729
+ if (options.yes || !prompter.interactive) return choice.suggested;
1730
+ return prompter.select(choice.question, choice.options, choice.suggested);
1731
+ };
1732
+ /** What each picked unit's plugin adds, given the unit's bump so far. One at a time: it may ask. */
1733
+ const contributionsOf = async (context, scope, bumps, known = {}) => {
1734
+ const { head } = await context.services.sourceControl.position();
1735
+ const contributions = {};
1736
+ for (const unit of context.release.units.filter(({ name }) => scope.has(name))) {
1737
+ const answered = known[unit.name];
1738
+ if (answered) {
1739
+ contributions[unit.name] = answered;
1740
+ continue;
1741
+ }
1742
+ const module = moduleOf(context, unit);
1743
+ const version = module?.version?.bind(module);
1744
+ if (!module || !version) continue;
1745
+ const input = jobInput(context, module, unit, {
1746
+ tag: tagName(unit.name, unit.version, context.release.tagFormat),
1747
+ environment: "preview",
1748
+ commit: head
1749
+ });
1750
+ const bump = bumps.find(({ app }) => app === unit.name);
1751
+ const contribute = (chosen) => version(decideContext(context), {
1752
+ ...input,
1753
+ bump,
1754
+ chosen
1755
+ });
1756
+ const suggested = await contribute();
1757
+ const chosen = await choose(context, suggested.choice);
1758
+ contributions[unit.name] = chosen && chosen !== suggested.choice?.suggested ? await contribute(chosen) : suggested;
1759
+ }
1760
+ return contributions;
1761
+ };
1762
+ /** What a release PR covering `scope` would version, computed without writing anything. */
1763
+ const prepareRelease = async (context, scope, known = {}) => {
1764
+ const { release, services } = context;
1765
+ const refs = unitRefs(release.units);
1766
+ const [dependencies, named, base, pendingFiles] = await Promise.all([
1767
+ services.versioning.dependencies(),
1768
+ namedUnits(context),
1769
+ services.versioning.plan([], []),
1770
+ services.versioning.pending()
1771
+ ]);
1772
+ const baseBumps = appBumps(base, dependencies, refs);
1773
+ const unreleased = await findUnreleased(context, new Set([...named, ...baseBumps.map(({ app }) => app)]));
1774
+ const held = [...named].filter((app) => !scope.has(app));
1775
+ const adopted = unreleased.filter(({ app }) => scope.has(app)).flatMap(({ app, version, commits }) => {
1776
+ const ref = refs.find(({ name }) => name === app);
1777
+ return ref ? unreleasedChangesets(ref, version, commits) : [];
1778
+ });
1779
+ const split = held.length > 0 ? splitChangesets(base.changesets, held, refs) : NOTHING_HELD;
1780
+ const picked = held.length > 0 || adopted.length > 0 ? await services.versioning.plan(adopted, split.waits) : base;
1781
+ const contributions = await contributionsOf(context, scope, appBumps(picked, dependencies, refs), known);
1782
+ const contributed = Object.values(contributions).flatMap(({ added }) => added);
1783
+ const added = [...adopted, ...contributed];
1784
+ const plan = contributed.length > 0 ? await services.versioning.plan(added, split.waits) : picked;
1785
+ return {
1786
+ pending: (held.length > 0 ? split.ships.length : pendingFiles.length) + added.length,
1787
+ held,
1788
+ unreleased: unreleased.filter(({ app }) => !scope.has(app)),
1789
+ split,
1790
+ bumps: appBumps(plan, dependencies, refs),
1791
+ companions: draggedUnits(plan, dependencies, refs, scope),
1792
+ packages: packageBumps(plan, refs),
1793
+ added,
1794
+ shipped: plan.changesets,
1795
+ contributions
1796
+ };
1797
+ };
1798
+ //#endregion
1799
+ //#region src/application/steps.ts
1800
+ const MAX_OUTPUT_LINES = 40;
1801
+ const reasonOf$1 = (error) => error instanceof Error ? error.message : String(error);
1802
+ /** What the failed command printed, so the person reads why without running it again. */
1803
+ const printOutput = ({ output }, error) => {
1804
+ if (!(error instanceof CommandFailed) || !error.output) return;
1805
+ const lines = error.output.split("\n");
1806
+ const shown = lines.slice(-MAX_OUTPUT_LINES);
1807
+ if (shown.length < lines.length) output.line(paint("dim", ` … ${lines.length - shown.length} earlier lines`));
1808
+ shown.forEach((line) => output.line(paint("dim", ` │ ${line}`)));
1809
+ };
1810
+ /** Takes back the steps that ran, newest first; one that cannot be undone never stops the rest. */
1811
+ const cancel = async (context, ran) => {
1812
+ const undos = ran.flatMap(({ undo }) => undo ? [undo] : []).reverse();
1813
+ const kept = ran.flatMap((step) => step.kept ? [step.kept] : []);
1814
+ if (undos.length === 0 && kept.length === 0) return;
1815
+ const left = [];
1816
+ for (const undo of undos) try {
1817
+ await context.progress.during(`undo: ${undo.label}`, "working", undo.run);
1818
+ } catch (error) {
1819
+ left.push(undo);
1820
+ context.progress.say("worried", `${paint("red", "✗")} undo ${undo.label}: ${reasonOf$1(error)}`);
1821
+ }
1822
+ if (left.length === 0 && kept.length === 0) {
1823
+ context.progress.say("resting", paint("dim", "Cancelled: everything this run did is undone."));
1824
+ return;
1825
+ }
1826
+ const commands = [...new Set([...left, ...kept].flatMap(({ byHand }) => byHand()))];
1827
+ const these = commands.length > 1 ? "these" : "this";
1828
+ const ask = kept.length === 0 ? "run these to finish the cleanup:" : `run ${these} to finish:`;
1829
+ fail(context, "Cancelled, not all of it", [...kept.map(({ label }) => label), ask].join("; "), commands);
1830
+ };
1831
+ /**
1832
+ * Runs steps in order, each shown with its place in the run. At the first failure it says why,
1833
+ * with the command's own output, and undoes the steps that ran.
1834
+ */
1835
+ const runSteps = async (context, steps) => {
1836
+ for (const [index, step] of steps.entries()) try {
1837
+ await context.progress.during(step.label, "working", step.run, {
1838
+ index,
1839
+ total: steps.length
1840
+ });
1841
+ } catch (error) {
1842
+ fail(context, `${step.label} failed`, `${reasonOf$1(error)}, the steps after it did not run.`);
1843
+ printOutput(context, error);
1844
+ await cancel(context, steps.slice(0, index));
1845
+ return false;
1846
+ }
1847
+ return true;
1848
+ };
1849
+ /** A branch from main; undone by dropping the changes made on it and the branch itself. */
1850
+ const branchStep = ({ services: { sourceControl: source } }, branch) => {
1851
+ let untracked = /* @__PURE__ */ new Set();
1852
+ return {
1853
+ label: `branch ${branch} from main`,
1854
+ run: async () => {
1855
+ untracked = new Set(await source.changedFiles());
1856
+ await source.createBranch(branch);
1857
+ },
1858
+ undo: {
1859
+ label: `delete ${branch}`,
1860
+ run: async () => {
1861
+ const created = (await source.changedFiles()).filter((file) => !untracked.has(file));
1862
+ await source.discard(created);
1863
+ await source.switchTo("main");
1864
+ await source.deleteBranch(branch);
1865
+ },
1866
+ byHand: () => [
1867
+ "git reset --hard",
1868
+ "git switch main",
1869
+ `git branch -D ${branch}`
1870
+ ]
1871
+ }
1872
+ };
1873
+ };
1874
+ const pushStep = ({ services: { sourceControl: source } }, branch) => ({
1875
+ label: `push ${branch}`,
1876
+ run: () => source.push(branch),
1877
+ undo: {
1878
+ label: `delete ${branch} on origin`,
1879
+ run: () => source.deleteRemoteBranch(branch),
1880
+ byHand: () => [`git push origin --delete ${branch}`]
1881
+ }
1882
+ });
1883
+ /** Opens a pull request; undone by closing it, with a comment saying why. */
1884
+ const openPrStep = ({ services: { codeHost: host } }, label, open) => {
1885
+ let opened = null;
1886
+ return {
1887
+ label,
1888
+ run: async () => {
1889
+ opened = await open();
1890
+ },
1891
+ undo: {
1892
+ label: "close the pull request",
1893
+ run: async () => {
1894
+ if (opened) await host.closePr(opened, "The release stopped part way, so it closed this.");
1895
+ },
1896
+ byHand: () => opened ? [`gh pr close ${opened.number}`] : []
1897
+ }
1898
+ };
1899
+ };
1900
+ //#endregion
1901
+ //#region src/application/openReleasePr.ts
1902
+ const plural$2 = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
1903
+ /** What happens to a unit once the release PR merges: its module ships the version to preview. */
1904
+ const shipsOnMerge = (context, { contributions, companions }) => (bump) => {
1905
+ const contributed = contributions[bump.app]?.onMerge;
1906
+ if (contributed) return contributed;
1907
+ const unit = context.release.units.find(({ name }) => name === bump.app);
1908
+ const along = companions.find(({ app }) => app === bump.app);
1909
+ const reason = along ? ` (not picked: ${along.why})` : bump.movedWith.length > 0 ? ` (moved with ${bump.movedWith.join(", ")})` : "";
1910
+ return `${environmentLabel(context, [bump.app], "preview") === "live" ? "Ship live" : "Ship to preview"} with ${(unit && moduleOf(context, unit)?.provider) ?? "its target"}${reason}`;
1911
+ };
1912
+ /** Units going out unpicked, each with the package that takes it along. */
1913
+ const printCompanions = ({ output, release }, { companions, split }) => {
1914
+ if (companions.length === 0) return;
1915
+ const names = companions.map(({ app }) => app);
1916
+ const verb = names.length === 1 ? "is not picked but ships too" : "are not picked but ship too";
1917
+ output.line(` ${paint(["bold", "yellow"], "!")} ${paint("bold", `${listed(names)} ${verb}:`)}`);
1918
+ companions.forEach(({ app, version, why }) => {
1919
+ const packageName = release.units.find(({ name }) => name === app)?.packageName;
1920
+ const waiting = split.waits.filter(({ releases }) => releases.some(({ name }) => name === packageName)).length;
1921
+ const own = waiting > 0 ? ` · picking it ships its ${plural$2(waiting, "changeset")} too` : "";
1922
+ output.line(` ${app.padEnd(11)}${version.padEnd(20)}${paint("dim", `${why}${own}`)}`);
1923
+ });
1924
+ output.line();
1925
+ };
1926
+ /** The table a person reads before anything is written: each unit, its move, what ships. */
1927
+ const printSummary = (context, prepared) => {
1928
+ const { output, release } = context;
1929
+ const { bumps, packages, pending, held, unreleased, contributions, companions } = prepared;
1930
+ const dot = paint("dim", "·");
1931
+ const stays = held.filter((app) => !bumps.some((bump) => bump.app === app));
1932
+ const heldLabel = stays.length > 0 ? ` ${dot} ${stays.join(", ")} held` : "";
1933
+ const where = environmentLabel(context, bumps.map(({ app }) => app), "preview");
1934
+ output.line();
1935
+ output.line(` ${paint("bold", "Release")} ${dot} ${where} ${dot} ${plural$2(pending, "changeset")}${heldLabel}`);
1936
+ output.line();
1937
+ const width = Math.max(13, ...release.units.map(({ name }) => name.length)) + 2;
1938
+ output.line(paint("dim", ` ${"Unit".padEnd(width)}${"Version".padEnd(20)}${where === "live" ? "Ships live" : "Ships to preview"}`));
1939
+ release.units.forEach((unit) => {
1940
+ const bump = bumps.find(({ app }) => app === unit.name);
1941
+ const version = bump ? `${bump.from} → ${bump.to}` : unit.version;
1942
+ const left = unreleased.find(({ app }) => app === unit.name);
1943
+ const ships = (() => {
1944
+ if (held.includes(unit.name) && !bump) return paint("yellow", "⏸ held, its changesets stay pending");
1945
+ if (left && !bump) return paint("yellow", `! ${plural$2(left.commits.length, "commit")} since ${left.version}, no changeset: not in this release`);
1946
+ const contributed = contributions[unit.name]?.summary;
1947
+ if (contributed && contributed.length > 0) return contributed.join(`\n ${" ".repeat(width + 20)}`);
1948
+ if (!bump) return paint("dim", "– nothing changed");
1949
+ const along = companions.some(({ app }) => app === unit.name) ? paint("yellow", " not picked, goes along") : "";
1950
+ return `${paint("green", "↑ ship")} ${paint("dim", moduleOf(context, unit)?.provider ?? "")}${along}`;
1951
+ })();
1952
+ output.line(` ${unit.name.padEnd(width)}${version.padEnd(20)}${ships}`);
1953
+ });
1954
+ if (packages > 0) output.line(` ${"packages".padEnd(width)}${`${packages} bumped`.padEnd(20)}${paint("dim", "changelogs only, nothing published")}`);
1955
+ output.line();
1956
+ printCompanions(context, prepared);
1957
+ };
1958
+ /**
1959
+ * Versions what `prepared` covers on one branch from main, opens its PR, and goes back to main.
1960
+ * Null, with what to do, when it must not run.
1961
+ */
1962
+ const openReleasePr = async (context, prepared, replaces = []) => {
1963
+ const { output, services, clock } = context;
1964
+ printSummary(context, prepared);
1965
+ const blocked = Object.values(prepared.contributions).find((entry) => entry.blocked)?.blocked;
1966
+ if (blocked) {
1967
+ fail(context, blocked.title, blocked.detail, blocked.commands);
1968
+ return null;
1969
+ }
1970
+ const source = releaseSource("build", "preview", await services.sourceControl.position());
1971
+ if (!source.allowed) {
1972
+ fail(context, source.why === "not-main" ? "Not from main" : "main is behind origin", "a release versions what is merged.", [
1973
+ "git switch main",
1974
+ "git pull",
1975
+ "shiplane"
1976
+ ]);
1977
+ return null;
1978
+ }
1979
+ if (!await services.sourceControl.isClean()) {
1980
+ fail(context, "Uncommitted changes", "commit or stash them first, the release PR commits every change.");
1981
+ return null;
1982
+ }
1983
+ const kindOf = (app) => {
1984
+ const unit = context.release.units.find(({ name }) => name === app);
1985
+ return unit && moduleOf(context, unit)?.kind;
1986
+ };
1987
+ const groups = prGroupsOf(context, prepared);
1988
+ const titles = groups.map((group) => releaseTitle(group, kindOf));
1989
+ const planned = [
1990
+ groups.length > 1 ? `Open ${groups.length} release PRs from main, one per app, then wait for you to squash merge each:\n${titles.map((title) => ` ${title}`).join("\n")}` : "Open the release PR, then wait for you to squash merge it",
1991
+ "Tag each version and publish its release notes",
1992
+ ...Object.values(prepared.contributions).flatMap(({ step }) => step ? [step] : [])
1993
+ ];
1994
+ output.line(paint("dim", " Steps"));
1995
+ planned.forEach((step, index) => output.line(` ${index + 1}. ${step}`));
1996
+ output.line();
1997
+ if (!await confirm(context, `Release these ${environmentLabel(context, prepared.bumps.map(({ app }) => app), "preview") === "live" ? "live" : "to preview"}?`, true)) {
1998
+ output.line(paint("dim", "Nothing ran."));
1999
+ return null;
2000
+ }
2001
+ const now = clock.now();
2002
+ const prs = [];
2003
+ for (const group of groups) {
2004
+ const apps = new Set(group.map(({ app }) => app));
2005
+ const scoped = groups.length > 1 ? await prepareRelease(context, apps, prepared.contributions) : prepared;
2006
+ const [first] = group;
2007
+ const pr = await openOne(context, scoped, kindOf, `${releaseBranchName(now)}${groups.length > 1 && first ? `-${first.app}` : ""}`, replaces);
2008
+ if (!pr) {
2009
+ if (prs.length > 0) output.line(paint("dim", ` ${listed(prs.map(({ number }) => `#${number}`))} stay open: merge them, then run shiplane for the rest.`));
2010
+ return null;
2011
+ }
2012
+ prs.push(pr);
2013
+ }
2014
+ return prs;
2015
+ };
2016
+ /**
2017
+ * The apps each release PR takes: one PR per app, a family as one. Apps one changeset names or
2018
+ * one moving with the other share a PR. A release moving internal packages stays one PR: their
2019
+ * changelog lines have no app to go with.
2020
+ */
2021
+ const prGroupsOf = ({ release }, prepared) => {
2022
+ if (prepared.packages > 0) return [prepared.bumps];
2023
+ const appOf = (packageName) => release.units.find((unit) => unit.packageName === packageName)?.name;
2024
+ const linked = [...prepared.shipped.map(({ releases }) => releases.map(({ name }) => appOf(name) ?? name)), ...prepared.bumps.map(({ app, movedWith }) => [app, ...movedWith.map((name) => appOf(name) ?? name)])];
2025
+ return releasePrGroups(prepared.bumps, linked);
2026
+ };
2027
+ /** The line a release PR opens with when it takes the place of release PRs main moved past. */
2028
+ const replacedLine = (replaces) => replaces.length === 0 ? "" : `Replaces ${listed(replaces.map(({ number }) => `#${number}`))}, which went out of date when main moved.\n\n`;
2029
+ /** Versions `prepared` on `branch` from main, opens its PR, and goes back to main. */
2030
+ const openOne = async (context, prepared, kindOf, branch, replaces) => {
2031
+ const { services } = context;
2032
+ const title = releaseTitle(prepared.bumps, kindOf);
2033
+ const skipHooks = !titleFits(title);
2034
+ const created = {};
2035
+ return await runSteps(context, [
2036
+ branchStep(context, branch),
2037
+ {
2038
+ label: "versions and changelogs",
2039
+ run: () => services.versioning.apply(prepared.added, prepared.split.waits)
2040
+ },
2041
+ ...Object.values(prepared.contributions).flatMap(({ writes }) => writes),
2042
+ {
2043
+ label: `commit "${title}"`,
2044
+ run: async () => services.sourceControl.commit(await services.sourceControl.changedFiles(), title, releaseCommitBody(prepared.bumps) || void 0, { skipHooks })
2045
+ },
2046
+ pushStep(context, branch),
2047
+ openPrStep(context, "open the release pull request", async () => {
2048
+ created.pr = await services.codeHost.createPr({
2049
+ base: "main",
2050
+ head: branch,
2051
+ title,
2052
+ body: replacedLine(replaces) + releasePrBody(prepared.bumps, shipsOnMerge(context, prepared)),
2053
+ label: "type: chore"
2054
+ });
2055
+ return created.pr;
2056
+ }),
2057
+ {
2058
+ label: "back to main",
2059
+ run: () => services.sourceControl.switchTo("main")
2060
+ }
2061
+ ]) && created.pr ? created.pr : null;
2062
+ };
2063
+ //#endregion
2064
+ //#region src/domain/scope.ts
2065
+ const plural$1 = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
2066
+ const previewChoice = ({ version, changesets, commits, tagged, versioned, firstRelease, onChannel, decidedBy, releaseOnly }) => {
2067
+ const later = decidedBy ? ` · ${decidedBy.platform} decides ${decidedBy.choice} once picked` : "";
2068
+ if (changesets > 0) return {
2069
+ pending: true,
2070
+ hint: `${plural$1(changesets, "changeset")}${later}`
2071
+ };
2072
+ if (commits > 0) return {
2073
+ pending: true,
2074
+ hint: `${plural$1(commits, "commit")} since ${version}, changelog from its commits${later}`
2075
+ };
2076
+ if (!tagged) {
2077
+ if (versioned) return {
2078
+ pending: true,
2079
+ hint: `${version} versioned, not tagged yet${later}`
2080
+ };
2081
+ return firstRelease ? {
2082
+ pending: true,
2083
+ hint: `${version} first release${later}`
2084
+ } : {
2085
+ pending: false,
2086
+ hint: "nothing new"
2087
+ };
2088
+ }
2089
+ if (releaseOnly) return {
2090
+ pending: false,
2091
+ hint: `${version} released, nothing deploys it`
2092
+ };
2093
+ if (decidedBy) return {
2094
+ pending: false,
2095
+ hint: `${version} released, nothing new (${decidedBy.check} shows its builds)`
2096
+ };
2097
+ return onChannel ? {
2098
+ pending: false,
2099
+ hint: `${version} is on preview, nothing new`
2100
+ } : {
2101
+ pending: true,
2102
+ hint: `${version} released, not on preview yet`
2103
+ };
2104
+ };
2105
+ const productionChoice = ({ version, tagged, onChannel, onPreview, decidedBy, releaseOnly }) => {
2106
+ if (!tagged) return {
2107
+ pending: false,
2108
+ hint: "not released yet"
2109
+ };
2110
+ if (releaseOnly) return {
2111
+ pending: false,
2112
+ hint: `${version} released, nothing deploys it`
2113
+ };
2114
+ if (decidedBy) return {
2115
+ pending: true,
2116
+ hint: `${version} released, ${decidedBy.platform} decides once picked`
2117
+ };
2118
+ if (onChannel) return {
2119
+ pending: false,
2120
+ hint: `${version} is on production, nothing new`
2121
+ };
2122
+ return onPreview ? {
2123
+ pending: true,
2124
+ hint: `${version} is on preview, promotes it`
2125
+ } : {
2126
+ pending: false,
2127
+ hint: `${version} is not on preview yet: release it there first`
2128
+ };
2129
+ };
2130
+ /** The first question: which units have something to release here, and why not the rest. */
2131
+ const scopeChoices = (apps, channel) => apps.map((info) => ({
2132
+ app: info.app,
2133
+ ...channel === "production" ? productionChoice(info) : previewChoice(info)
2134
+ }));
2135
+ //#endregion
2136
+ //#region src/application/pickScope.ts
2137
+ /** Every unit with something to release here: what --yes and a run without a terminal cover. */
2138
+ const defaultScope = (info, environment) => new Set(scopeChoices(info, environment).filter(({ pending }) => pending).map(({ app }) => app));
2139
+ /**
2140
+ * The first question: which units this run covers. Every unit is listed; those with nothing to
2141
+ * release are greyed out with why. Null when cancelled or when nothing is pending.
2142
+ */
2143
+ const pickScope = async (context, environment) => {
2144
+ const { output, prompter, options, progress } = context;
2145
+ const info = await progress.during("Reading what changed: changesets, commits, tags and GitHub deployments", "thinking", () => readScope(context, environment));
2146
+ const choices = scopeChoices(info, environment);
2147
+ if (!choices.some(({ pending }) => pending)) {
2148
+ output.line();
2149
+ choices.forEach(({ app, hint }) => output.line(` ${paint("dim", `${app.padEnd(15)}${hint}`)}`));
2150
+ output.line();
2151
+ progress.say("resting", `${paint("bold", `Nothing to release to ${environment}.`)} ${paint("dim", environment === "preview" ? "Queue a change first:" : "Release to preview first:")}`);
2152
+ output.line(` ${paint("cyan", environment === "preview" ? "pnpm changeset" : "shiplane")}`);
2153
+ output.line();
2154
+ return null;
2155
+ }
2156
+ if (options.yes || !prompter.interactive) return {
2157
+ scope: defaultScope(info, environment),
2158
+ info
2159
+ };
2160
+ const picked = await prompter.multiselect(`What do you want to release to ${environment}? Greyed units have nothing to release.`, choices.map(({ app, pending, hint }) => ({
2161
+ value: app,
2162
+ label: app,
2163
+ hint,
2164
+ disabled: !pending
2165
+ })), choices.filter(({ pending }) => pending).map(({ app }) => app));
2166
+ return picked ? {
2167
+ scope: new Set(picked),
2168
+ info
2169
+ } : null;
2170
+ };
2171
+ //#endregion
2172
+ //#region src/application/followUps.ts
2173
+ const reasonOf = (error) => error instanceof Error ? error.message : String(error);
2174
+ /** What every feature asks for once these apps ship, in order. One that cannot read is said, then skipped. */
2175
+ const followUpsOf = async (context, shipped) => {
2176
+ const all = [];
2177
+ if (shipped.length === 0) return all;
2178
+ for (const feature of context.release.features) try {
2179
+ const asked = await context.progress.during(`${feature.name}: reading what to follow up`, "thinking", () => feature.afterShip(afterShipContext(context), shipped));
2180
+ all.push(...asked);
2181
+ } catch (error) {
2182
+ context.output.line(` ${paint("yellow", "!")} ${feature.name} ${paint("dim", `could not read: ${reasonOf(error)}`)}`);
2183
+ }
2184
+ return all;
2185
+ };
2186
+ /** Runs what the features ask for once units shipped. A failure is said and never fails the release. */
2187
+ const runFollowUps = async (context, shipped) => {
2188
+ for (const { label, run } of await followUpsOf(context, shipped)) try {
2189
+ await run();
2190
+ context.output.line(` ${paint("green", "✓")} ${label}`);
2191
+ } catch (error) {
2192
+ context.output.line(` ${paint("yellow", "!")} ${label} ${paint("dim", reasonOf(error))}`);
2193
+ }
2194
+ };
2195
+ /** What the features would do once these units ship, run nothing. */
2196
+ const planFollowUps = async (context, shipped) => {
2197
+ const all = await followUpsOf(context, shipped);
2198
+ if (all.length === 0) return;
2199
+ context.output.line();
2200
+ context.output.line(` ${paint("bold", "Then")} ${paint("dim", "once shipped")}`);
2201
+ all.forEach(({ label }) => context.output.line(` ${label}`));
2202
+ };
2203
+ //#endregion
2204
+ //#region src/application/planShips.ts
2205
+ /**
2206
+ * `shiplane plan`: every command shipping the current tags would run, both ways, in release order,
2207
+ * then what the features would do. It runs nothing and asks nothing; it reads git, and the code host
2208
+ * for features.
2209
+ */
2210
+ const planShips = async (context, environment) => {
2211
+ const { release, services, output } = context;
2212
+ const { head } = await services.sourceControl.position();
2213
+ output.line();
2214
+ output.line(` ${paint("bold", "Plan")} ${paint("dim", "·")} ${environment} ${paint("dim", "· nothing runs")}`);
2215
+ output.line(` ${paint("bold", "Order")} ${releaseOrder(release.units)}`);
2216
+ const shipped = [];
2217
+ for (const unit of release.units) {
2218
+ const module = moduleOf(context, unit);
2219
+ if (!module) continue;
2220
+ const tag = tagName(unit.name, unit.version, context.release.tagFormat);
2221
+ const tagged = await services.sourceControl.tagCommit(tag) !== null;
2222
+ if (tagged && !module.releaseOnly) shipped.push({
2223
+ unit,
2224
+ tag,
2225
+ environment
2226
+ });
2227
+ const plan = shipPlanOf(context, module, jobInput(context, module, unit, {
2228
+ tag,
2229
+ environment,
2230
+ commit: head
2231
+ }));
2232
+ output.line();
2233
+ output.line(` ${paint("bold", tag)} → ${plan.where}${tagged ? "" : paint("yellow", " (not tagged yet: release first)")}`);
2234
+ plan.jobs.forEach((job) => {
2235
+ output.line(` ${paint("dim", "this machine")}`);
2236
+ job.local.forEach((command) => output.line(` ${commandLine(command)}`));
2237
+ if (job.record) output.line(` ${paint("dim", `then record ${tag} on ${environment} in GitHub Deployments`)}`);
2238
+ if (job.ci) {
2239
+ const workflow = services.ciPipeline.shipWorkflow;
2240
+ output.line(` ${paint("dim", "GitHub Actions")}`);
2241
+ output.line(` gh workflow run ${workflow} --ref ${job.ci.ref} -f units=${unit.name} -f environment=${environment}`);
2242
+ }
2243
+ });
2244
+ }
2245
+ await planFollowUps(context, shipped);
2246
+ output.line();
2247
+ };
2248
+ //#endregion
2249
+ //#region src/application/askPath.ts
2250
+ const PATH_LABEL = {
2251
+ github: "GitHub Actions",
2252
+ local: "this machine"
2253
+ };
2254
+ /** The minutes block above the question: status, what is left, this release shaded in, the pace. */
2255
+ const showMinutes = ({ output, clock }, budget, estimate) => {
2256
+ const drawn = minutesBudget(budget, clock.now(), 30, estimate.total);
2257
+ output.line();
2258
+ output.line(` ${paint("bold", drawn.title)} ${paint(["bold", drawn.tone], drawn.status)}`);
2259
+ output.line(` ${paint(drawn.tone, drawn.bar)} ${paint(["bold", drawn.tone], drawn.amount)}`);
2260
+ if (drawn.after) {
2261
+ output.line(` ${drawn.after}`);
2262
+ const each = estimate.lines.map(({ app, minutes, measured }) => `${app} ~${minutes} ${measured ? "(its last runs)" : "(typical, no run yet)"}`);
2263
+ output.line(` ${paint("dim", ` ${each.join(" · ")}`)}`);
2264
+ }
2265
+ output.line(` ${paint("dim", drawn.pace)}`);
2266
+ output.line();
2267
+ };
2268
+ /**
2269
+ * How each unit ships, asked one by one with this month's Actions minutes shown once: GitHub Actions
2270
+ * or this machine, in the order given. Null when cancelled or without a terminal to ask.
2271
+ */
2272
+ const askPaths = async (context, environment, shipments) => {
2273
+ const { services, prompter, clock } = context;
2274
+ const measured = Object.fromEntries(await Promise.all(shipments.map(async ({ item, workflows }) => [item.app, (await Promise.all(workflows.map((workflow) => services.ciPipeline.measuredMinutes(workflow)))).flat()])));
2275
+ const typical = Object.fromEntries(shipments.flatMap(({ item, typicalMinutes }) => typicalMinutes === void 0 ? [] : [[item.app, typicalMinutes]]));
2276
+ const estimate = deployEstimate(shipments.map(({ item }) => item), measured, typical);
2277
+ const budget = await services.ciPipeline.minutes();
2278
+ if (budget) showMinutes(context, budget, estimate);
2279
+ if (!prompter.interactive) {
2280
+ fail(context, "Not a terminal", "say how to ship.", ["shiplane ship --via github", "shiplane ship --via local"]);
2281
+ return null;
2282
+ }
2283
+ const low = budget !== null && minutesBudget(budget, clock.now(), 30, estimate.total).tone === "red";
2284
+ const paths = [];
2285
+ for (const { item } of shipments) {
2286
+ const minutes = estimate.lines.find(({ app }) => app === item.app)?.minutes;
2287
+ const path = await prompter.select(`How should ${item.tag} ship to ${environment}?`, [{
2288
+ value: "github",
2289
+ label: PATH_LABEL.github,
2290
+ hint: budget ? `runs on GitHub from its tag, about ${minutes} of ${budget.left.toLocaleString("en-US")} minutes left` : "its workflow runs on GitHub, from its tag"
2291
+ }, {
2292
+ value: "local",
2293
+ label: PATH_LABEL.local,
2294
+ hint: "the same commands, run here: no Actions minutes"
2295
+ }], low ? "local" : "github");
2296
+ if (!path) return null;
2297
+ paths.push(path);
2298
+ }
2299
+ return paths;
2300
+ };
2301
+ //#endregion
2302
+ //#region src/application/waitForMerge.ts
2303
+ const POLL_MS = 15e3;
2304
+ /** Merges the pull request with the method the person picks. GitHub refuses approving your own PR. */
2305
+ const mergeHere = async (context, pr) => {
2306
+ const { choices, initial } = mergeChoices(await context.services.codeHost.mergeMethods());
2307
+ if (choices.length === 0) {
2308
+ fail(context, "No merge method", "the repository allows none: merge it on GitHub.");
2309
+ return;
2310
+ }
2311
+ const method = await context.prompter.select(`Merge #${pr.number} into main?`, [...choices, {
2312
+ value: "no",
2313
+ label: "Not now"
2314
+ }], initial);
2315
+ if (!method || method === "no") {
2316
+ context.output.line(paint("dim", " Not merged."));
2317
+ return;
2318
+ }
2319
+ await context.services.codeHost.merge(pr, method);
2320
+ };
2321
+ const ACTIONS = {
2322
+ diff: (context, pr) => context.services.codeHost.showDiff(pr),
2323
+ merge: mergeHere,
2324
+ open: (context, pr) => context.services.codeHost.openInBrowser(pr)
2325
+ };
2326
+ /** The keys a wait offers. Someone else approves a release that requires it: no merge from here. */
2327
+ const hintsFor = (approvalRequired) => [
2328
+ {
2329
+ key: "d",
2330
+ label: "see the diff"
2331
+ },
2332
+ ...approvalRequired ? [] : [{
2333
+ key: "m",
2334
+ label: "merge it from here"
2335
+ }],
2336
+ {
2337
+ key: "o",
2338
+ label: "open it on GitHub"
2339
+ },
2340
+ {
2341
+ key: "Ctrl-C",
2342
+ label: "leave, continue later"
2343
+ }
2344
+ ];
2345
+ /**
2346
+ * Polls the host until the PR merges or closes; in a terminal the person can also read the diff
2347
+ * (d), merge from here (m, unless approval is required) or open it in the browser (o). Without a
2348
+ * terminal, a release waiting on someone's approval is left for a later run instead.
2349
+ */
2350
+ const waitForMerge = async (context, pr) => {
2351
+ const { output, prompter, services } = context;
2352
+ const approvalRequired = context.release.flow.approval === "required";
2353
+ output.line(` ${paint("green", "✓")} Release PR ${paint("cyan", pr.url)}`);
2354
+ if (approvalRequired) {
2355
+ output.line(` Waiting for approval on #${pr.number}. This can take a while.`);
2356
+ output.line(paint("dim", " It's safe to leave: run shiplane later and it picks up here."));
2357
+ } else output.line(paint("dim", " Review and merge it here or on GitHub; this carries on by itself once merged."));
2358
+ if (approvalRequired && !prompter.interactive) {
2359
+ const state = await services.codeHost.prState(pr).catch(() => "OPEN");
2360
+ if (state === "OPEN") return "left";
2361
+ return state === "MERGED" ? "merged" : "closed";
2362
+ }
2363
+ const hints = hintsFor(approvalRequired);
2364
+ if (prompter.interactive) {
2365
+ output.line();
2366
+ output.line(` ${keyHints(hints)}`);
2367
+ }
2368
+ output.line();
2369
+ const keys = prompter.interactive ? hints.map(({ key }) => key).filter((key) => key.length === 1) : [];
2370
+ for (;;) {
2371
+ const state = await services.codeHost.prState(pr).catch(() => "OPEN");
2372
+ if (state !== "OPEN") return state === "MERGED" ? "merged" : "closed";
2373
+ const key = await prompter.waitForKey(approvalRequired ? `Waiting for #${pr.number} to be approved and merged` : `Waiting for #${pr.number} to merge`, POLL_MS, keys);
2374
+ const action = key && keys.includes(key) ? waitKey(key) : null;
2375
+ if (action) await ACTIONS[action](context, pr);
2376
+ }
2377
+ };
2378
+ //#endregion
2379
+ //#region src/application/pullRequestFirst.ts
2380
+ /**
2381
+ * A small PR a plugin needs merged before it ships, such as production's version moving: branch,
2382
+ * write, commit, push, open, back to main, wait for the merge, pull. `declined` when the person
2383
+ * said no.
2384
+ */
2385
+ const pullRequestFirst = async (context, request) => {
2386
+ const { output, services } = context;
2387
+ if (!await confirm(context, request.question)) {
2388
+ output.line(paint("dim", " Not now."));
2389
+ return "declined";
2390
+ }
2391
+ const created = {};
2392
+ const opened = await runSteps(context, [
2393
+ branchStep(context, request.branch),
2394
+ {
2395
+ label: `commit "${request.title}"`,
2396
+ run: async () => {
2397
+ await request.write();
2398
+ for (const changeset of request.changesets) await services.versioning.write(changeset);
2399
+ await services.sourceControl.commit(await services.sourceControl.changedFiles(), request.title);
2400
+ }
2401
+ },
2402
+ pushStep(context, request.branch),
2403
+ openPrStep(context, "open the pull request", async () => {
2404
+ created.pr = await services.codeHost.createPr({
2405
+ base: "main",
2406
+ head: request.branch,
2407
+ title: request.title,
2408
+ body: request.body,
2409
+ label: "type: chore"
2410
+ });
2411
+ return created.pr;
2412
+ }),
2413
+ {
2414
+ label: "back to main",
2415
+ run: () => services.sourceControl.switchTo("main")
2416
+ }
2417
+ ]);
2418
+ const { pr } = created;
2419
+ if (!opened || !pr) return "failed";
2420
+ output.line();
2421
+ if (!await waitForMerge(context, pr)) {
2422
+ fail(context, `#${pr.number} was closed without a merge`, "nothing shipped.", ["shiplane"]);
2423
+ return "failed";
2424
+ }
2425
+ return await runSteps(context, [{
2426
+ label: "pull main",
2427
+ run: () => services.sourceControl.pull()
2428
+ }]) ? "merged" : "failed";
2429
+ };
2430
+ //#endregion
2431
+ //#region src/application/ship.ts
2432
+ /** Builds and submits run on their own platform: a build asks only when a workflow can start it. */
2433
+ const choosesPath = ({ kind, jobs }) => kind === "update" || kind === "deploy" || kind === "build" && jobs.every(({ ci }) => ci);
2434
+ const WEB_STATUS = {
2435
+ deploying: "deploying already",
2436
+ shipped: "already there",
2437
+ "not-on-preview": "not on preview yet: ship it there first"
2438
+ };
2439
+ /** A web unit decides from GitHub Deployments, which a ship records once it rolled out. */
2440
+ const webDecision = (context, module, input, history) => {
2441
+ const { jobs } = shipPlanOf(context, module, input);
2442
+ const ship = webShip({
2443
+ environment: input.environment,
2444
+ run: deployedOn(history, input.tag, input.environment),
2445
+ onPreview: deployedOn(history, input.tag, "preview") === "done"
2446
+ });
2447
+ return ship === "deploy" ? {
2448
+ action: "ship",
2449
+ kind: "deploy",
2450
+ jobs
2451
+ } : {
2452
+ action: "none",
2453
+ status: WEB_STATUS[ship]
2454
+ };
2455
+ };
2456
+ /** Where a choice stands, then the person's pick: its jobs ship, or nothing does and it is held. */
2457
+ const chosen = async (context, choice) => {
2458
+ const { output, prompter } = context;
2459
+ output.line();
2460
+ choice.lines.forEach((line) => output.line(` ${line}`));
2461
+ output.line();
2462
+ const value = prompter.interactive ? await prompter.select(choice.question, choice.options.map(({ value, label, hint, disabled }) => ({
2463
+ value,
2464
+ label,
2465
+ hint,
2466
+ disabled
2467
+ })), choice.suggested) : null;
2468
+ const jobs = choice.options.find((option) => option.value === value)?.jobs ?? [];
2469
+ return jobs.length > 0 ? {
2470
+ action: "ship",
2471
+ kind: "update",
2472
+ jobs
2473
+ } : {
2474
+ action: "none",
2475
+ status: choice.held
2476
+ };
2477
+ };
2478
+ /**
2479
+ * What every picked unit needs on the environment, in dispatch order, said as it goes. A module may
2480
+ * first need a small PR merged (a version moving): it opens, merges, and the module decides again.
2481
+ * Null when one of them refused.
2482
+ */
2483
+ const decideAll = async (context, environment, scope) => {
2484
+ const { release, services, output } = context;
2485
+ const recorded = await services.codeHost.deployments().catch(() => []);
2486
+ const ready = [];
2487
+ for (const unit of release.units) {
2488
+ const module = moduleOf(context, unit);
2489
+ if (scope && !scope.has(unit.name) || !module) continue;
2490
+ const tag = tagName(unit.name, unit.version, context.release.tagFormat);
2491
+ if (!module.decide && !await services.sourceControl.tagCommit(tag)) continue;
2492
+ const decide = async () => {
2493
+ const { head } = await services.sourceControl.position();
2494
+ const input = jobInput(context, module, unit, {
2495
+ tag,
2496
+ environment,
2497
+ commit: head
2498
+ });
2499
+ return {
2500
+ input,
2501
+ decision: module.decide ? await module.decide(decideContext(context), input) : webDecision(context, module, input, recorded)
2502
+ };
2503
+ };
2504
+ let { input, decision } = await context.progress.during(`Checking what ${tag} needs on ${environment}`, "thinking", decide);
2505
+ while (decision.action === "pull-request") {
2506
+ const merged = await pullRequestFirst(context, decision);
2507
+ if (merged === "failed") return null;
2508
+ if (merged === "declined") {
2509
+ decision = {
2510
+ action: "none",
2511
+ status: "left for later"
2512
+ };
2513
+ break;
2514
+ }
2515
+ ({input, decision} = await decide());
2516
+ }
2517
+ if (decision.action === "choose") decision = await chosen(context, decision);
2518
+ if (decision.action === "fail") {
2519
+ fail(context, decision.title, decision.detail, decision.commands);
2520
+ return null;
2521
+ }
2522
+ if (decision.action === "none") {
2523
+ output.line(` ${paint("dim", "·")} ${tag} ${paint("dim", decision.status)}`);
2524
+ continue;
2525
+ }
2526
+ ready.push({
2527
+ unit,
2528
+ module,
2529
+ input,
2530
+ kind: decision.kind,
2531
+ jobs: decision.jobs,
2532
+ decided: module.decide !== void 0,
2533
+ notLocal: decision.notLocal ?? null
2534
+ });
2535
+ }
2536
+ return ready;
2537
+ };
2538
+ /** Why a path cannot ship a unit, or null when it can. */
2539
+ const blockedOn = async (context, path, { input, jobs, decided, notLocal }) => {
2540
+ const { services } = context;
2541
+ if (path === "github") {
2542
+ const workflow = services.ciPipeline.shipWorkflow;
2543
+ for (const { ci } of jobs) {
2544
+ if (!ci) return "only ships from this machine";
2545
+ const file = `.github/workflows/${workflow}`;
2546
+ if (await services.sourceControl.fileAt(ci.ref, file) !== null) continue;
2547
+ return ci.ref !== "main" && await services.sourceControl.fileAt("main", file) !== null ? `predates ${workflow}` : `no ${workflow}`;
2548
+ }
2549
+ return null;
2550
+ }
2551
+ if (decided) return notLocal;
2552
+ return shipsFrom(path, { sinceTagOnlyVersionFiles: onlyVersionFiles(await services.sourceControl.diffNames(input.tag, "HEAD"), versionFiles(context)) }) ? null : "main moved past it";
2553
+ };
2554
+ const OTHER_PATH = {
2555
+ github: "local",
2556
+ local: "github"
2557
+ };
2558
+ /** What to do instead, when the path a person forced cannot ship a unit. */
2559
+ const INSTEAD = {
2560
+ github: "ship it from this machine",
2561
+ local: "this machine builds its checkout, ship it through GitHub Actions"
2562
+ };
2563
+ const TAKES = {
2564
+ github: "ships through GitHub Actions",
2565
+ local: "ships from this machine"
2566
+ };
2567
+ /**
2568
+ * The way a unit ships: the forced one when it can, the only one left when the other cannot, or
2569
+ * asked. Said whenever it is not asked.
2570
+ */
2571
+ const routeOf = async (context, entry, forced) => {
2572
+ const say = (mark, why) => context.output.line(` ${mark} ${entry.input.tag} ${paint("dim", why)}`);
2573
+ if (forced) {
2574
+ const why = await blockedOn(context, forced, entry);
2575
+ if (!why) return forced;
2576
+ say(paint("yellow", "!"), `${why}: ${INSTEAD[forced]}`);
2577
+ return "skip";
2578
+ }
2579
+ const github = await blockedOn(context, "github", entry);
2580
+ const local = await blockedOn(context, "local", entry);
2581
+ if (github && local) {
2582
+ say(paint("red", "✗"), `${github}, and ${local}: nothing can ship it`);
2583
+ return "stuck";
2584
+ }
2585
+ const blocked = github ? "github" : local ? "local" : null;
2586
+ if (!blocked) return "ask";
2587
+ say(paint("dim", "·"), `${github ?? local}: ${TAKES[OTHER_PATH[blocked]]}`);
2588
+ return OTHER_PATH[blocked];
2589
+ };
2590
+ const shipmentOf = (shipWorkflow) => ({ unit, module, input, jobs }) => ({
2591
+ item: {
2592
+ app: unit.name,
2593
+ tag: input.tag,
2594
+ kind: "deploy"
2595
+ },
2596
+ workflows: jobs.some(({ ci }) => ci) ? [shipWorkflow] : [],
2597
+ typicalMinutes: module.typicalMinutes
2598
+ });
2599
+ /**
2600
+ * The ship workflow's runs: one per ref, each naming its units. A tag on main's commit runs from
2601
+ * main, so a release whose tags all sit there costs one run.
2602
+ */
2603
+ const shipRuns = async ({ services }, entries) => {
2604
+ const { originMain } = await services.sourceControl.position();
2605
+ const runs = /* @__PURE__ */ new Map();
2606
+ for (const { unit, jobs } of entries) for (const { ci } of jobs) {
2607
+ if (!ci) continue;
2608
+ const ref = (ci.ref === "main" ? originMain : await services.sourceControl.tagCommit(ci.ref)) === originMain ? "main" : ci.ref;
2609
+ const units = runs.get(ref) ?? [];
2610
+ if (!units.includes(unit.name)) runs.set(ref, [...units, unit.name]);
2611
+ }
2612
+ return [...runs.entries()].map(([ref, units]) => ({
2613
+ ref,
2614
+ units
2615
+ }));
2616
+ };
2617
+ /** `Ship a through GitHub Actions`, or each tag with its way when they differ. */
2618
+ const shipQuestion = (going, paths, environment, context) => {
2619
+ const label = environmentLabel(context, going.map(({ unit }) => unit.name), environment);
2620
+ const used = [...new Set(going.flatMap((entry) => paths.get(entry) ?? []))];
2621
+ const [only] = used;
2622
+ const names = going.map((entry) => {
2623
+ const path = paths.get(entry);
2624
+ return used.length > 1 && path ? `${entry.input.tag} (${PATH_LABEL[path]})` : entry.input.tag;
2625
+ }).join(", ");
2626
+ const how = used.length === 1 && only ? ` through ${PATH_LABEL[only]}` : "";
2627
+ return `Ship ${names} ${label === "live" ? "live" : `to ${label}`}${how}?`;
2628
+ };
2629
+ /**
2630
+ * Ships every picked unit its environment does not run yet, and returns once each one is
2631
+ * triggered: EAS builds and workflows go on on their own, a Fly deploy from here once rolled out.
2632
+ * Production asks for its name first. False on a failure.
2633
+ */
2634
+ const shipTo = async (context, environment, { scope, via }) => {
2635
+ const { output, prompter, options, services } = context;
2636
+ if (environment === "production" && !options.ci) {
2637
+ if (options.yes) {
2638
+ fail(context, "No --yes on production", "every production step asks a person.", ["shiplane ship --channel production"]);
2639
+ return false;
2640
+ }
2641
+ if (!await prompter.typed("Type \"production\" to start:", "production")) {
2642
+ output.line(paint("dim", "Nothing ran."));
2643
+ return false;
2644
+ }
2645
+ }
2646
+ const ready = await decideAll(context, environment, scope);
2647
+ if (!ready) return false;
2648
+ if (ready.length === 0) {
2649
+ context.progress.say("resting", paint("dim", `Nothing to ship to ${environment}.`));
2650
+ return true;
2651
+ }
2652
+ const forced = options.ci ? "local" : via;
2653
+ const paths = /* @__PURE__ */ new Map();
2654
+ const unanswered = [];
2655
+ let stuck = false;
2656
+ for (const entry of ready.filter(choosesPath)) {
2657
+ const route = await routeOf(context, entry, forced);
2658
+ if (route === "ask") unanswered.push(entry);
2659
+ else if (route === "stuck") stuck = true;
2660
+ else if (route !== "skip") paths.set(entry, route);
2661
+ }
2662
+ if (unanswered.length > 0) {
2663
+ const answers = await askPaths(context, environment, unanswered.map(shipmentOf(services.ciPipeline.shipWorkflow)));
2664
+ if (!answers) {
2665
+ output.line(paint("dim", " Nothing shipped."));
2666
+ return prompter.interactive;
2667
+ }
2668
+ unanswered.forEach((entry, index) => {
2669
+ const answer = answers[index];
2670
+ if (answer) paths.set(entry, answer);
2671
+ });
2672
+ }
2673
+ const going = ready.filter((entry) => !choosesPath(entry) || paths.has(entry));
2674
+ if (going.length === 0) return !stuck;
2675
+ if (going.some((entry) => paths.get(entry) === "local") && !await services.sourceControl.isClean()) {
2676
+ fail(context, "Uncommitted changes", "this machine ships its checkout: commit or stash them first.");
2677
+ return false;
2678
+ }
2679
+ if (!await confirm(context, shipQuestion(going, paths, environment, context), environment === "preview")) {
2680
+ if (environment === "preview" && prompter.interactive && await prompter.confirm("Ship to production instead?")) return shipTo(context, "production", {
2681
+ scope,
2682
+ via
2683
+ });
2684
+ context.progress.say("resting", paint("dim", "Nothing shipped."));
2685
+ return true;
2686
+ }
2687
+ const jobs = going.filter((entry) => paths.get(entry) !== "github").flatMap((entry) => entry.jobs.map((job) => ({
2688
+ entry,
2689
+ job
2690
+ })));
2691
+ const runs = await shipRuns(context, going.filter((entry) => paths.get(entry) === "github"));
2692
+ const total = jobs.length + runs.length;
2693
+ for (const [index, { entry, job }] of jobs.entries()) try {
2694
+ await context.progress.during(job.label, "working", () => runHere(context, job, entry.input), {
2695
+ index,
2696
+ total
2697
+ });
2698
+ } catch (error) {
2699
+ const reason = error instanceof Error ? error.message : String(error);
2700
+ fail(context, `${job.label} failed`, `${reason}, nothing after it ran.`);
2701
+ return false;
2702
+ }
2703
+ const workflow = services.ciPipeline.shipWorkflow;
2704
+ for (const [index, run] of runs.entries()) {
2705
+ const label = `ship ${run.units.join(", ")} from ${run.ref} (${workflow})`;
2706
+ try {
2707
+ await context.progress.during(label, "working", () => dispatchShip(context, run, environment), {
2708
+ index: jobs.length + index,
2709
+ total
2710
+ });
2711
+ } catch (error) {
2712
+ const reason = error instanceof Error ? error.message : String(error);
2713
+ fail(context, `${label} failed`, `${reason}, nothing after it ran.`);
2714
+ return false;
2715
+ }
2716
+ }
2717
+ const names = going.map(({ input }) => input.tag).join(", ");
2718
+ output.line();
2719
+ context.progress.say("happy", `${paint(["bold", "green"], "✓ Triggered.")} ${paint("dim", `${names}, shipping to ${environment} on their own.`)}`);
2720
+ await runFollowUps(context, going.map(({ unit, input }) => ({
2721
+ unit,
2722
+ tag: input.tag,
2723
+ environment
2724
+ })));
2725
+ if (runs.length > 0) output.line(` ${paint("cyan", "gh run list --limit 5")}`);
2726
+ output.line(` ${paint("cyan", `shiplane status --channel ${environment}`)}`);
2727
+ output.line();
2728
+ return !stuck;
2729
+ };
2730
+ //#endregion
2731
+ //#region src/application/promote.ts
2732
+ const STAGES$1 = ["What to promote", "Ship"];
2733
+ /** Each unit's version on preview with its notes, read from its tag. */
2734
+ const releasedVersions = async ({ release, services }, apps) => Promise.all(release.units.filter(({ name }) => apps.includes(name)).map(async ({ name, dir, version }) => {
2735
+ return {
2736
+ app: name,
2737
+ version,
2738
+ notes: changelogSection(await services.sourceControl.fileAt(tagName(name, version, release.tagFormat), services.versioning.changelogFile(dir)) ?? "", version)
2739
+ };
2740
+ }));
2741
+ /**
2742
+ * Which units production gets: the person's pick, plus what preview only ever ran with it when they
2743
+ * accept. Offered ticked with why, never added silently. Null when cancelled.
2744
+ */
2745
+ const pickPromotion = async (context) => {
2746
+ const { output } = context;
2747
+ const picked = await pickScope(context, "production");
2748
+ if (!picked || picked.scope.size === 0) return null;
2749
+ const left = scopeChoices(picked.info, "production").filter(({ app, pending }) => pending && !picked.scope.has(app)).map(({ app }) => app);
2750
+ if (left.length === 0) return picked.scope;
2751
+ const companions = await context.progress.during("Reading the notes of what preview runs, to see what went there together", "thinking", async () => releasedTogether(await releasedVersions(context, [...picked.scope]), await releasedVersions(context, left)));
2752
+ if (companions.length === 0) return picked.scope;
2753
+ const names = companions.map(({ app }) => app);
2754
+ const partners = [...new Set(companions.flatMap(({ with: partner }) => partner))];
2755
+ output.line();
2756
+ output.line(` ${paint(["bold", "yellow"], "!")} ${paint("bold", `Preview runs ${listed(names)} with what you picked:`)}`);
2757
+ companions.forEach(({ app, version, why }) => output.line(` ${app.padEnd(11)}${version.padEnd(10)}${paint("dim", why)}`));
2758
+ output.line();
2759
+ const versions = companions.map(({ app, version }) => `${app} ${version}`);
2760
+ const them = companions.length === 1 ? "it" : "them";
2761
+ if (await confirm(context, `Promote ${listed(versions)} too? Preview has only run ${them} with ${listed(partners)}.`, true)) return new Set([...picked.scope, ...names]);
2762
+ const promoted = picked.info.filter(({ app }) => partners.includes(app)).map(({ app, version }) => `${app} ${version}`);
2763
+ output.line(paint("dim", ` ${listed(names)} ${companions.length === 1 ? "stays" : "stay"} on preview: production runs ${listed(promoted)} next to the ${listed(names)} it has.`));
2764
+ return picked.scope;
2765
+ };
2766
+ /** How each picked unit does on preview, said; when one looks unwell, asks before going on. */
2767
+ const previewLooksWell = async (context, scope) => {
2768
+ const { output, release, services } = context;
2769
+ const { head } = await services.sourceControl.position();
2770
+ const healths = (await context.progress.during("Reading how preview runs what you picked", "thinking", () => Promise.all(release.units.filter(({ name }) => scope.has(name)).map(async (unit) => {
2771
+ const module = moduleOf(context, unit);
2772
+ if (!module?.health) return [];
2773
+ const tag = tagName(unit.name, unit.version, context.release.tagFormat);
2774
+ const input = jobInput(context, module, unit, {
2775
+ tag,
2776
+ environment: "preview",
2777
+ commit: head
2778
+ });
2779
+ const health = await module.health(decideContext(context), input).catch(() => null);
2780
+ return health ? [{
2781
+ tag,
2782
+ ...health
2783
+ }] : [];
2784
+ })))).flat();
2785
+ if (healths.length === 0) return true;
2786
+ output.line();
2787
+ healths.forEach(({ tag, ok, summary }) => output.line(` ${ok ? paint("green", "✓") : paint(["bold", "yellow"], "!")} ${tag.padEnd(18)}${paint("dim", summary)}`));
2788
+ output.line();
2789
+ const unwell = healths.filter(({ ok }) => !ok);
2790
+ if (unwell.length === 0) return true;
2791
+ return confirm(context, `Promote anyway? ${unwell.map(({ tag, why }) => `${tag}: ${why ?? "looks unwell"}`).join("; ")}.`, false);
2792
+ };
2793
+ /** Production, from what preview runs: every unit picked, its name typed, each step asked. */
2794
+ const promote = async (context, via) => {
2795
+ context.progress.stage(STAGES$1, 0);
2796
+ const scope = await pickPromotion(context);
2797
+ if (!scope) return true;
2798
+ if (!await previewLooksWell(context, scope)) {
2799
+ context.output.line(paint("dim", " Nothing promoted."));
2800
+ return true;
2801
+ }
2802
+ context.progress.stage(STAGES$1, 1);
2803
+ return shipTo(context, "production", {
2804
+ scope,
2805
+ via
2806
+ });
2807
+ };
2808
+ //#endregion
2809
+ //#region src/application/tagRelease.ts
2810
+ /** The tags and release notes still missing for the versions merged release PRs brought. */
2811
+ const missingTags = async (context) => {
2812
+ const { release, services } = context;
2813
+ const [tags, notes, named] = await Promise.all([
2814
+ services.sourceControl.tags(),
2815
+ services.codeHost.releasedTags().catch(() => /* @__PURE__ */ new Set()),
2816
+ namedUnits(context)
2817
+ ]);
2818
+ return releaseTags((await Promise.all(release.units.map(async ({ name, dir, version }) => {
2819
+ const commit = await services.sourceControl.versionCommit(dir, MANIFEST, version);
2820
+ const first = !named.has(name) && firstRelease(name, version, tags, release.tagFormat);
2821
+ return commit ? [{
2822
+ app: name,
2823
+ version,
2824
+ commit,
2825
+ first
2826
+ }] : [];
2827
+ }))).flat(), tags, notes, release.tagFormat);
2828
+ };
2829
+ const notesFor = async ({ release, services }, tag) => {
2830
+ const unit = release.units.find(({ name }) => name === tag.app);
2831
+ return changelogSection((unit ? await services.sourceControl.fileAt(tag.sha, services.versioning.changelogFile(unit.dir)) : null) ?? "", tag.version);
2832
+ };
2833
+ /** Tags each version on the commit that brought it, pushes the tags, publishes their notes. */
2834
+ const tagRelease = async (context, tags) => {
2835
+ if (tags.length === 0) return true;
2836
+ const { output, release, services } = context;
2837
+ const names = tags.map(({ tag }) => tag).join(", ");
2838
+ output.line(` ${paint("bold", "Tags and release notes")} ${paint("dim", names)}`);
2839
+ if (!await confirm(context, `Tag ${names} and publish their release notes?`, true)) {
2840
+ output.line(paint("dim", "Nothing ran."));
2841
+ return false;
2842
+ }
2843
+ const created = tags.filter(({ needsTag }) => needsTag);
2844
+ return runSteps(context, [
2845
+ ...created.map((tag) => ({
2846
+ label: `tag ${tag.tag} on ${tag.sha.slice(0, 7)}`,
2847
+ run: async () => services.sourceControl.tag(tag.tag, tag.sha, `${tag.tag}\n\n${await notesFor(context, tag)}`),
2848
+ undo: {
2849
+ label: `delete the tag ${tag.tag} here`,
2850
+ run: () => services.sourceControl.deleteTag(tag.tag),
2851
+ byHand: () => [`git tag --delete ${tag.tag}`]
2852
+ }
2853
+ })),
2854
+ ...created.length > 0 ? [{
2855
+ label: "push the tags",
2856
+ run: () => services.sourceControl.pushTags(created.map(({ tag }) => tag)),
2857
+ kept: {
2858
+ label: `${created.map(({ tag }) => tag).join(", ")} ${created.length > 1 ? "stay" : "stays"} on origin`,
2859
+ byHand: () => ["shiplane tag"]
2860
+ }
2861
+ }] : [],
2862
+ ...tags.filter(({ needsNotes }) => needsNotes).map((tag) => ({
2863
+ label: `release notes for ${tag.tag}`,
2864
+ run: async () => services.codeHost.createRelease(tag.tag, await notesFor(context, tag), tag.app === release.units[0]?.name)
2865
+ }))
2866
+ ]);
2867
+ };
2868
+ //#endregion
2869
+ //#region src/application/releaseToPreview.ts
2870
+ const plural = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
2871
+ /** The commits main gained since a release PR's branch, or none when the host did not say. */
2872
+ const movedPast = async (context, pr, originMain) => {
2873
+ if (!pr.head) return [];
2874
+ return context.services.sourceControl.commitsBetween(pr.head, originMain).catch(() => []);
2875
+ };
2876
+ /** Why a stale release PR closed, said on it, so a reviewer landing there knows where to go. */
2877
+ const closedComment = (replacement, subjects) => [
2878
+ `Closed by shiplane: ${plural(subjects.length, "commit")} ${subjects.length === 1 ? "was" : "were"} merged into main after this release PR was opened, so its changelog no longer matched what would ship.`,
2879
+ `Replaced by ${listed(replacement.map(({ number }) => `#${number}`))}, which versions everything merged so far. Please review that one.`,
2880
+ "",
2881
+ ...subjects.map((subject) => `- ${subject}`)
2882
+ ].join("\n");
2883
+ /**
2884
+ * Release PRs main moved past are replaced: a fresh one versions everything merged, then each
2885
+ * stale one closes with a comment pointing to it. The open ones, or null when that failed.
2886
+ */
2887
+ const refreshStale = async (context, prs, scope) => {
2888
+ const { originMain } = await context.services.sourceControl.position();
2889
+ const moved = await Promise.all(prs.map((pr) => movedPast(context, pr, originMain)));
2890
+ const subjects = [...new Set(moved.flat().map(({ subject }) => subject))];
2891
+ if (subjects.length === 0) return prs;
2892
+ const { output, progress } = context;
2893
+ const names = listed(prs.map(({ number }) => `#${number}`));
2894
+ progress.say("thinking", `↻ Release ${names} is out of date: ${plural(subjects.length, "commit")} landed on main since.`);
2895
+ output.line(paint("dim", " Replacing it so the changelog matches what ships."));
2896
+ const opened = await openReleasePr(context, await prepareRelease(context, scope), prs);
2897
+ if (!opened) return null;
2898
+ for (const pr of prs) await context.services.codeHost.closePr(pr, closedComment(opened, subjects));
2899
+ output.line(` ${paint("green", "✓")} Opened ${listed(opened.map(({ number }) => `#${number}`))}${context.release.flow.approval === "required" ? " (needs approval again)" : ""} ${paint("green", "✓")} Closed ${names}, with a comment pointing to it`);
2900
+ return opened;
2901
+ };
2902
+ const STAGES = [
2903
+ "What to release",
2904
+ "Versions",
2905
+ "Release PR",
2906
+ "Merge",
2907
+ "Tags",
2908
+ "Ship"
2909
+ ];
2910
+ /**
2911
+ * `release` on preview: the release PR, the wait for its merge, the tags, then the ship. It reads where things
2912
+ * stand first, so a run stopped anywhere picks up where it left off. False when something failed.
2913
+ */
2914
+ const releaseToPreview = async (context) => {
2915
+ const { output, services, progress } = context;
2916
+ const stage = (name) => progress.stage(STAGES, STAGES.indexOf(name));
2917
+ stage("What to release");
2918
+ const picked = await pickScope(context, "preview");
2919
+ if (!picked || picked.scope.size === 0) {
2920
+ progress.say("resting", paint("dim", "Nothing ran."));
2921
+ return true;
2922
+ }
2923
+ if (!await preflight(context, picked.scope)) return false;
2924
+ const covered = picked.info.filter(({ app }) => picked.scope.has(app));
2925
+ const [releasePrs, missing] = await progress.during("Looking for an open release PR and versions not tagged yet", "thinking", () => Promise.all([services.codeHost.openPrsFrom(RELEASE_BRANCH_PREFIX), missingTags(context)]));
2926
+ const step = nextStep({
2927
+ pending: covered.reduce((sum, { changesets }) => sum + changesets, 0),
2928
+ releasePrs,
2929
+ untagged: missing.length,
2930
+ unreleased: covered.filter(({ changesets, commits }) => changesets === 0 && commits > 0).length
2931
+ });
2932
+ let prs = [];
2933
+ let current = context;
2934
+ if (step.step === "release-pr") {
2935
+ stage("Versions");
2936
+ const prepared = await progress.during("Planning each app's version with changesets, and what its target ships", "thinking", () => prepareRelease(context, picked.scope));
2937
+ if (prepared.bumps.length === 0 && prepared.packages === 0) {
2938
+ printSummary(context, prepared);
2939
+ output.line(paint("dim", " Nothing to version for these units: the others wait for a later release."));
2940
+ return true;
2941
+ }
2942
+ stage("Release PR");
2943
+ const opened = await openReleasePr(context, prepared);
2944
+ if (!opened) return false;
2945
+ prs = opened;
2946
+ } else if (step.step === "wait-merge") {
2947
+ const fresh = await refreshStale(context, step.prs, picked.scope);
2948
+ if (!fresh) return false;
2949
+ if (fresh === step.prs) {
2950
+ const waiting = context.release.flow.approval === "required" ? "approval" : "a merge";
2951
+ progress.say("thinking", `↻ Picking up release ${listed(fresh.map(({ number }) => `#${number}`))}: still waiting for ${waiting}`);
2952
+ output.line(paint("dim", " To cancel it, close it on GitHub."));
2953
+ }
2954
+ prs = fresh;
2955
+ } else if (missing.length > 0) {
2956
+ progress.say("thinking", `↻ Picking up a merged release`);
2957
+ output.line(paint("dim", ` Left to do: tag ${plural(missing.length, "version")} → ship to preview`));
2958
+ }
2959
+ if (prs.length > 0) stage("Merge");
2960
+ for (const pr of prs) {
2961
+ output.line();
2962
+ const outcome = await waitForMerge(context, pr);
2963
+ if (outcome === "closed") {
2964
+ progress.say("resting", `○ Release #${pr.number} was closed: nothing shipped.`);
2965
+ output.line(paint("dim", " Run shiplane to open a new release with everything pending."));
2966
+ return true;
2967
+ }
2968
+ if (outcome === "left") {
2969
+ output.line(paint("dim", ` Left #${pr.number} waiting. Run shiplane once it's approved.`));
2970
+ return true;
2971
+ }
2972
+ progress.say("happy", `${paint("green", "✓")} Release PR #${pr.number} merged`);
2973
+ }
2974
+ if (prs.length > 0) {
2975
+ if (!await runSteps(context, [{
2976
+ label: "switch to main",
2977
+ run: () => services.sourceControl.switchTo("main")
2978
+ }, {
2979
+ label: "pull main",
2980
+ run: () => services.sourceControl.pull()
2981
+ }])) return false;
2982
+ current = {
2983
+ ...context,
2984
+ release: await context.load()
2985
+ };
2986
+ }
2987
+ const tags = prs.length > 0 ? await missingTags(current) : missing;
2988
+ if (tags.length > 0) stage("Tags");
2989
+ if (!await tagRelease(current, tags)) return false;
2990
+ stage("Ship");
2991
+ return shipTo(current, "preview", { scope: new Set([...picked.scope, ...tags.map(({ app }) => app)]) });
2992
+ };
2993
+ //#endregion
2994
+ //#region src/application/customAdapter.ts
2995
+ const CUSTOM_PORTS = {
2996
+ sourceControl: {
2997
+ key: "sourceControl",
2998
+ type: "SourceControlPort",
2999
+ label: "source control",
3000
+ kind: "flow",
3001
+ subject: `head: async () => (await port.position()).head,
3002
+ // TODO: write a file the repository does not track yet.
3003
+ change: () => Promise.resolve(),`
3004
+ },
3005
+ codeHost: {
3006
+ key: "codeHost",
3007
+ type: "CodeHostPort",
3008
+ label: "code host",
3009
+ kind: "flow",
3010
+ subject: `// TODO: a branch pushed with one commit, a tag, an issue comments can go on.
3011
+ branch: (name) => Promise.resolve(name),
3012
+ tag: () => Promise.resolve("app@1.0.0"),
3013
+ issue: { repository: "acme/repo", number: 1 },`
3014
+ },
3015
+ ciPipeline: {
3016
+ key: "ciPipeline",
3017
+ type: "CiPipelinePort",
3018
+ label: "CI pipeline",
3019
+ kind: "flow",
3020
+ subject: `// TODO: a workflow that exists and has never run.
3021
+ idle: "ship.yml",`
3022
+ },
3023
+ versioning: {
3024
+ key: "versioning",
3025
+ type: "VersioningPort",
3026
+ label: "versioning",
3027
+ kind: "flow",
3028
+ subject: `// TODO: a package this workspace holds, and its folder.
3029
+ workspace: { name: "@acme/api", folder: "apps/api" },`
3030
+ },
3031
+ serverHosting: {
3032
+ key: "serverHosting",
3033
+ type: "ServerHostingPort",
3034
+ label: "server hosting",
3035
+ kind: "delivery",
3036
+ subject: `{}`
3037
+ },
3038
+ staticHosting: {
3039
+ key: "staticHosting",
3040
+ type: "StaticHostingPort",
3041
+ label: "static hosting",
3042
+ kind: "delivery",
3043
+ subject: `{}`
3044
+ },
3045
+ mobileDistribution: {
3046
+ key: "mobileDistribution",
3047
+ type: "MobileDistributionPort",
3048
+ label: "mobile distribution",
3049
+ kind: "delivery",
3050
+ subject: `{}`
3051
+ },
3052
+ packageRegistry: {
3053
+ key: "packageRegistry",
3054
+ type: "PackageRegistryPort",
3055
+ label: "package registry",
3056
+ kind: "delivery",
3057
+ subject: `{}`
3058
+ }
3059
+ };
3060
+ /** `jenkinsCiPipeline` → `jenkins-ci-pipeline`. */
3061
+ const kebab = (name) => name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
3062
+ /** A factory name a person can type: a letter, then letters and digits. */
3063
+ const isFactoryName = (name) => /^[a-z][a-zA-Z0-9]*$/.test(name);
3064
+ /** The name offered first: `customCiPipeline`. */
3065
+ const suggestedName = (port) => `custom${port.charAt(0).toUpperCase()}${port.slice(1)}`;
3066
+ /** Where a custom adapter lives, and what the config imports it from. */
3067
+ const customFiles = (name) => ({
3068
+ file: `shiplane/adapters/${kebab(name)}.ts`,
3069
+ test: `shiplane/adapters/${kebab(name)}.test.ts`,
3070
+ from: `./shiplane/adapters/${kebab(name)}`
3071
+ });
3072
+ const share = (name) => ` * Works? Share it: publish it as shiplane-${kebab(name)}, or open a pull request at
3073
+ * https://github.com/arnaud-zg/packages so everyone gets it.`;
3074
+ /** The adapter's file: shiplane's in-memory one under your name, ready to be replaced. */
3075
+ const renderCustomAdapter = (port, name, pkg) => {
3076
+ const { type, label, kind } = CUSTOM_PORTS[port];
3077
+ const memory = `${port}Memory`;
3078
+ if (kind === "delivery") return `import type { DeliveryAdapter, ${type} } from "${pkg}";
3079
+ import { z } from "${pkg}";
3080
+ import { ${memory} } from "${pkg}/memory";
3081
+
3082
+ /**
3083
+ * ${name}: your own ${label}. It starts in memory: it records each delivery it is asked for and
3084
+ * ships nothing, so the release runs end to end while you write it. To make it real, replace the
3085
+ * spread with define${type.replace(/Port$/, "")}({ ... }) from "${pkg}" (see: shiplane docs ${port}).
3086
+ * ${kebab(name)}.test.ts runs the contract every ${label} passes.
3087
+ ${share(name)}
3088
+ */
3089
+ export const ${name} = (): DeliveryAdapter<${type}> => ({
3090
+ ...${memory}(),
3091
+ name: "${name}",
3092
+ // The keys an app's unit file gives it: add yours, such as z.object({ service: z.string() }).
3093
+ settings: z.object({}),
3094
+ });
3095
+ `;
3096
+ return `import type { ${type}, ServiceAdapter } from "${pkg}";
3097
+ import { ${memory} } from "${pkg}/memory";
3098
+
3099
+ /**
3100
+ * ${name}: your own ${label}. It starts in memory: it records each call and does nothing real, so
3101
+ * the release runs end to end while you write it. Replace its methods one at a time;
3102
+ * ${kebab(name)}.test.ts runs the contract every ${label} passes.
3103
+ ${share(name)}
3104
+ */
3105
+ export const ${name} = (): ServiceAdapter<${type}> => ({
3106
+ name: "${name}",
3107
+ create: (context) => {
3108
+ const port: ${type} = ${memory}().create(context);
3109
+ // TODO: replace what it does with your own calls, for example:
3110
+ // port.someMethod = async (...args) => { ... };
3111
+ return port;
3112
+ },
3113
+ });
3114
+ `;
3115
+ };
3116
+ /** Its test: the port's contract, run on it. */
3117
+ const renderCustomTest = (port, name, pkg) => {
3118
+ const { kind, subject } = CUSTOM_PORTS[port];
3119
+ const contract = `${port}Contract`;
3120
+ const file = `./${kebab(name)}`;
3121
+ if (kind === "delivery") return `import { ${contract} } from "${pkg}/testing";
3122
+
3123
+ import { ${name} } from "${file}";
3124
+
3125
+ // The contract every ${CUSTOM_PORTS[port].label} passes. TODO: the settings an app gives it.
3126
+ ${contract}([{ adapter: ${name}(), settings: ${subject} }]);
3127
+ `;
3128
+ return `import { ${contract}, systemShell } from "${pkg}/testing";
3129
+
3130
+ import { ${name} } from "${file}";
3131
+
3132
+ // The contract every ${CUSTOM_PORTS[port].label} passes: green means ${name} is done.
3133
+ ${contract}("${name}", () => {
3134
+ const port = ${name}().create({ root: process.cwd(), shell: systemShell });
3135
+ return Promise.resolve({
3136
+ port,
3137
+ ${subject}
3138
+ });
3139
+ });
3140
+ `;
3141
+ };
3142
+ //#endregion
3143
+ //#region src/application/rehearse.ts
3144
+ var StepFailed = class extends Error {};
3145
+ /** One rehearsal check under a spinner when there is one: true when `work` says it passed. */
3146
+ const check = async (context, label, work) => {
3147
+ const run = async () => {
3148
+ if (!await work()) throw new StepFailed();
3149
+ };
3150
+ try {
3151
+ if (context.progress) await context.progress.during(label, "working", run);
3152
+ else {
3153
+ await run();
3154
+ context.output.line(` ${paint("green", "✓")} ${label}`);
3155
+ }
3156
+ return true;
3157
+ } catch (error) {
3158
+ if (!(error instanceof StepFailed)) {
3159
+ context.output.line(` ${paint("red", "✗")} ${label}`);
3160
+ context.output.line(` ${paint("dim", error instanceof Error ? error.message : String(error))}`);
3161
+ } else if (!context.progress) context.output.line(` ${paint("red", "✗")} ${label}`);
3162
+ return false;
3163
+ }
3164
+ };
3165
+ /** The package manager this repository runs scripts with. */
3166
+ const runner = (context) => context.files.exists("pnpm-lock.yaml") ? "pnpm" : context.files.exists("yarn.lock") ? "yarn" : context.files.exists("bun.lock") || context.files.exists("bun.lockb") ? "bun" : "npm";
3167
+ /** How a unit builds: its `buildCommand:`, else its package.json "build" script, else nothing. */
3168
+ const buildCommandOf = (context, unit) => {
3169
+ if (unit.buildCommand) return {
3170
+ command: "sh",
3171
+ args: ["-c", unit.buildCommand],
3172
+ shown: unit.buildCommand
3173
+ };
3174
+ if (!JSON.parse(context.files.read(path.posix.join(unit.dir, "package.json")) ?? "{}").scripts?.build) return null;
3175
+ const pm = runner(context);
3176
+ return {
3177
+ command: pm,
3178
+ args: ["run", "build"],
3179
+ shown: `${pm} run build`
3180
+ };
3181
+ };
3182
+ /**
3183
+ * A release played through with nothing pushed, published or deployed: the config loads, every app
3184
+ * builds, every ship plan resolves, every sign-in is there. Each failure says how to fix it.
3185
+ */
3186
+ const rehearse = async (context) => {
3187
+ const { output, shell, root } = context;
3188
+ output.line();
3189
+ output.line(` ${paint("bold", "Rehearsal")} ${paint("dim", "· nothing is pushed, published or deployed")}`);
3190
+ const release = await context.load();
3191
+ if (release.problems.length > 0) {
3192
+ release.problems.forEach(({ file, line, message, hint }) => {
3193
+ output.line(` ${paint("red", "✗")} ${line === void 0 ? file : `${file}:${line}`} ${message}`);
3194
+ if (hint) output.line(` ${paint("dim", hint)}`);
3195
+ });
3196
+ return false;
3197
+ }
3198
+ const builds = release.units.flatMap((unit) => {
3199
+ const build = buildCommandOf(context, unit);
3200
+ return build ? [{
3201
+ unit,
3202
+ build
3203
+ }] : [];
3204
+ });
3205
+ const results = [];
3206
+ const built = builds.length === 0 || await check(context, `build ${builds.length} app${builds.length === 1 ? "" : "s"}`, async () => {
3207
+ results.push(...await Promise.all(builds.map(async ({ unit, build }) => {
3208
+ const started = Date.now();
3209
+ const result = await shell.capture(build.command, build.args, { cwd: path.join(root, unit.dir) });
3210
+ return {
3211
+ unit,
3212
+ shown: build.shown,
3213
+ failed: result.status !== 0,
3214
+ seconds: `${((Date.now() - started) / 1e3).toFixed(1)}s`,
3215
+ tail: `${result.stderr}${result.stdout}`.trim().split("\n").slice(-3)
3216
+ };
3217
+ })));
3218
+ return results.every(({ failed }) => !failed);
3219
+ });
3220
+ for (const { unit, shown, failed, seconds, tail } of results) {
3221
+ output.line(` ${failed ? paint("red", "✗") : paint("green", "✓")} ${unit.dir.padEnd(18)}${paint("dim", `${shown} ${seconds}`)}`);
3222
+ if (!failed) continue;
3223
+ tail.forEach((line) => output.line(` ${paint("dim", line)}`));
3224
+ output.line(` ${paint("dim", `fix the build, or set buildCommand: in ${unit.file}`)}`);
3225
+ }
3226
+ const releaseContext = context.compose?.(release);
3227
+ const planned = !releaseContext || await check(context, `plan ${release.units.length} apps, nothing runs`, async () => {
3228
+ const { head } = await releaseContext.services.sourceControl.position();
3229
+ for (const unit of release.units) {
3230
+ const module = moduleOf(releaseContext, unit);
3231
+ if (!module) continue;
3232
+ shipPlanOf(releaseContext, module, jobInput(releaseContext, module, unit, {
3233
+ tag: tagName(unit.name, unit.version, release.tagFormat),
3234
+ environment: "preview",
3235
+ commit: head
3236
+ }));
3237
+ }
3238
+ return true;
3239
+ });
3240
+ let signedIn = true;
3241
+ for (const requirement of requirementsOf(release)) {
3242
+ const status = await checkStatus(shell, root, requirement);
3243
+ if (await check(context, requirement.label, () => Promise.resolve(status === 0))) continue;
3244
+ signedIn = false;
3245
+ const fix = status === 127 ? `not installed: ${requirement.check.command}` : requirement.fix ? `run ${commandLine(requirement.fix)}, then shiplane setup` : "not available here";
3246
+ output.line(` ${paint("dim", fix)}`);
3247
+ }
3248
+ return built && planned && signedIn;
3249
+ };
3250
+ //#endregion
3251
+ //#region src/application/setup.ts
3252
+ const ok = paint("green", "✓");
3253
+ const unsure = paint("yellow", "?");
3254
+ /** What a flow port is called, and what proves the ready-made adapter fits. */
3255
+ const FLOW_LABEL = {
3256
+ sourceControl: {
3257
+ label: "Source control",
3258
+ ready: "git"
3259
+ },
3260
+ codeHost: {
3261
+ label: "Code host",
3262
+ ready: "GitHub"
3263
+ },
3264
+ ciPipeline: {
3265
+ label: "CI pipeline",
3266
+ ready: "GitHub Actions"
3267
+ },
3268
+ versioning: {
3269
+ label: "Versioning",
3270
+ ready: "Changesets"
3271
+ }
3272
+ };
3273
+ /** The kinds of app a person picks from, in their words, and the delivery each one needs. */
3274
+ const APP_KINDS = [
3275
+ {
3276
+ value: "server-hosting",
3277
+ label: "Backend service",
3278
+ hint: "a server that runs"
3279
+ },
3280
+ {
3281
+ value: "static-hosting",
3282
+ label: "Web application",
3283
+ hint: "static files on a CDN"
3284
+ },
3285
+ {
3286
+ value: "mobile-distribution",
3287
+ label: "Mobile application",
3288
+ hint: "store builds and updates"
3289
+ },
3290
+ {
3291
+ value: "package-registry",
3292
+ label: "Published package",
3293
+ hint: "a library others install"
3294
+ },
3295
+ {
3296
+ value: "skip",
3297
+ label: "Internal tool",
3298
+ hint: "versioned, never deployed"
3299
+ }
3300
+ ];
3301
+ const CUSTOM_PORT_OF = {
3302
+ "server-hosting": "serverHosting",
3303
+ "static-hosting": "staticHosting",
3304
+ "mobile-distribution": "mobileDistribution",
3305
+ "package-registry": "packageRegistry"
3306
+ };
3307
+ const MODULE_OF = {
3308
+ sourceControl: "",
3309
+ codeHost: "",
3310
+ ciPipeline: "",
3311
+ versioning: "",
3312
+ serverHosting: "backendService",
3313
+ staticHosting: "webApp",
3314
+ mobileDistribution: "mobileApp",
3315
+ packageRegistry: "publishedPackage"
3316
+ };
3317
+ /** What proves each ready-made flow adapter fits this repository: hard evidence only. */
3318
+ const flowEvidence = async (context) => {
3319
+ const { files, shell, root } = context;
3320
+ const remote = files.exists(".git") ? (await shell.capture("git", [
3321
+ "remote",
3322
+ "get-url",
3323
+ "origin"
3324
+ ], { cwd: root })).stdout.trim() : "";
3325
+ const github = /github\.com[:/]([^/]+\/[^/.]+)/.exec(remote)?.[1];
3326
+ const workflows = files.list(".github/workflows").filter((file) => /\.ya?ml$/.test(file));
3327
+ return {
3328
+ sourceControl: files.exists(".git") ? ".git" : null,
3329
+ codeHost: github ? `remote github.com/${github}` : null,
3330
+ ciPipeline: workflows[0] ? `.github/workflows/${workflows[0]}` : null,
3331
+ versioning: files.exists(".changeset/config.json") ? ".changeset/config.json" : null
3332
+ };
3333
+ };
3334
+ /** A name for a custom adapter: asked, checked, unused. Null when cancelled. */
3335
+ const askName = async (context, port, initial) => {
3336
+ const { prompter, output, files } = context;
3337
+ for (;;) {
3338
+ const name = await prompter.text("Name it (you can rename it later)", initial);
3339
+ if (name === null) return null;
3340
+ if (!isFactoryName(name)) {
3341
+ output.line(` ${paint("red", "✗")} ${name}: a name like ${suggestedName(port)}`);
3342
+ continue;
3343
+ }
3344
+ if (files.exists(customFiles(name).file)) {
3345
+ output.line(` ${paint("red", "✗")} ${customFiles(name).file} already exists`);
3346
+ continue;
3347
+ }
3348
+ return name;
3349
+ }
3350
+ };
3351
+ /** The custom adapter's two files. */
3352
+ const customWrites = (port, name, pkg) => [{
3353
+ file: customFiles(name).file,
3354
+ text: renderCustomAdapter(port, name, pkg),
3355
+ created: true
3356
+ }, {
3357
+ file: customFiles(name).test,
3358
+ text: renderCustomTest(port, name, pkg),
3359
+ created: true
3360
+ }];
3361
+ /** The flow, from what the repository proves; asked part by part when unsure or when asked to. */
3362
+ const chooseFlow = async (context, yes, needsPerson, writes, pkg) => {
3363
+ const { output, prompter } = context;
3364
+ const evidence = await flowEvidence(context);
3365
+ output.line(paint("bold", " Flow"));
3366
+ FLOW_PORTS.forEach((port) => {
3367
+ const proof = evidence[port];
3368
+ const { label, ready } = FLOW_LABEL[port];
3369
+ output.line(proof ? ` ${ok} ${ready.padEnd(16)}${paint("dim", proof)}` : ` ${unsure} ${label.padEnd(16)}${paint("dim", "not sure: nothing here proves one")}`);
3370
+ });
3371
+ if (FLOW_PORTS.every((port) => evidence[port] !== null)) return DEFAULT_FLOW;
3372
+ if (yes) {
3373
+ needsPerson.push(...FLOW_PORTS.filter((port) => !evidence[port]).map((port) => `the ${FLOW_LABEL[port].label.toLowerCase()} (nothing proves one)`));
3374
+ return null;
3375
+ }
3376
+ const flow = { ...DEFAULT_FLOW };
3377
+ for (const port of FLOW_PORTS) {
3378
+ const { label, ready } = FLOW_LABEL[port];
3379
+ const picked = await prompter.select(`${label}?`, [{
3380
+ value: "ready",
3381
+ label: ready,
3382
+ hint: `${DEFAULT_FLOW[port].from}${evidence[port] ? "" : ", not found here"}`
3383
+ }, {
3384
+ value: "custom",
3385
+ label: "Custom",
3386
+ hint: "a no-op in memory you implement"
3387
+ }], evidence[port] ? "ready" : "custom");
3388
+ if (picked === null) return null;
3389
+ if (picked === "custom") {
3390
+ const name = await askName(context, port, suggestedName(port));
3391
+ if (name === null) return null;
3392
+ flow[port] = {
3393
+ factory: name,
3394
+ from: customFiles(name).from
3395
+ };
3396
+ writes.push(...customWrites(port, name, pkg));
3397
+ }
3398
+ }
3399
+ return flow;
3400
+ };
3401
+ /** Where the apps live: prefilled from the workspace when those folders exist, else typed. */
3402
+ const chooseFolders = async (context, yes, needsPerson) => {
3403
+ const { prompter, output, files } = context;
3404
+ const known = workspacePatterns(files).filter((pattern) => pattern.startsWith("!") || expandPatterns(files, [pattern]).length > 0);
3405
+ const found = expandPatterns(files, known).filter((dir) => dir !== ".");
3406
+ output.line();
3407
+ output.line(paint("bold", " Apps"));
3408
+ if (found.length > 0) {
3409
+ const patterns = known.filter((pattern) => !pattern.startsWith("!")).join(", ");
3410
+ if (yes || await prompter.confirm(`Your apps and packages are in ${patterns} (${found.length} folders)?`, true)) return known;
3411
+ } else if (yes) {
3412
+ needsPerson.push("where the apps are (no workspace folders found)");
3413
+ return null;
3414
+ }
3415
+ for (;;) {
3416
+ const typed = await prompter.text("Where are your apps and packages? (e.g. apps/*, web)");
3417
+ if (typed === null) return null;
3418
+ const patterns = typed.split(",").map((part) => part.trim()).filter(Boolean);
3419
+ const empty = patterns.filter((pattern) => expandPatterns(files, [pattern]).length === 0);
3420
+ if (patterns.length > 0 && empty.length === 0) return patterns;
3421
+ output.line(` ${paint("red", "✗")} ${empty.join(", ") || "nothing typed"} matches no folder: try again`);
3422
+ }
3423
+ };
3424
+ /** Folders under these patterns with a manifest and no unit file yet. */
3425
+ const newFolders = (context, patterns) => expandPatterns(context.files, patterns).filter((dir) => dir !== "." && context.files.exists(path.posix.join(dir, "package.json"))).filter((dir) => !UNIT_FILES.some((name) => context.files.exists(path.posix.join(dir, name)))).map((dir) => folderView(context.files, dir));
3426
+ /** How a folder ships: taken when an adapter is sure, asked otherwise. Null: not shipped. */
3427
+ const placeFolder = async (context, folder, state) => {
3428
+ const { prompter, output, adapters } = context;
3429
+ const sure = adapters.map((adapter) => ({
3430
+ adapter,
3431
+ detection: adapter.detect?.(folder) ?? null
3432
+ })).find(({ detection }) => detection?.certainty === "found");
3433
+ const place = (adapter) => {
3434
+ const { name, entry } = placeModule(adapter, state.modules, state.pkg);
3435
+ if (entry) {
3436
+ state.entries.push(entry);
3437
+ state.modules.push(moduleFor(adapter, name));
3438
+ }
3439
+ return name;
3440
+ };
3441
+ if (sure?.detection) {
3442
+ const kind = APP_KINDS.find(({ value }) => value === sure.adapter.capability)?.label ?? "";
3443
+ output.line(` ${ok} ${folder.dir.padEnd(18)}${kind} → ${sure.adapter.name} ${paint("dim", `proof: ${sure.detection.reason}`)}`);
3444
+ const options = await askOptions(context, folder, sure.adapter, sure.detection.options, state.yes);
3445
+ return {
3446
+ folder,
3447
+ module: place(sure.adapter),
3448
+ options,
3449
+ reason: sure.detection.reason
3450
+ };
3451
+ }
3452
+ if (state.yes) {
3453
+ state.needsPerson.push(`${folder.dir} (no adapter is sure what it is)`);
3454
+ return null;
3455
+ }
3456
+ output.line(` ${unsure} ${folder.dir.padEnd(18)}${paint("dim", "not sure what this is")}`);
3457
+ const answer = await prompter.select(`What is ${folder.dir}?`, [...state.modules.map((module) => ({
3458
+ value: `module:${module.name}`,
3459
+ label: `Like ${module.name}`,
3460
+ hint: `${module.kind} on ${module.provider}, already in your config`
3461
+ })), ...APP_KINDS.map(({ value, label, hint }) => ({
3462
+ value,
3463
+ label,
3464
+ hint
3465
+ }))]);
3466
+ if (answer === null) return null;
3467
+ if (answer.startsWith("module:")) return {
3468
+ folder,
3469
+ module: answer.slice(7),
3470
+ options: {}
3471
+ };
3472
+ const kind = answer;
3473
+ if (kind === "skip") return "skip";
3474
+ const fitting = adapters.filter((a) => a.capability === kind);
3475
+ const picked = fitting.length === 0 ? "custom" : await prompter.select(`Where does ${folder.dir} go?`, [...fitting.map((adapter) => ({
3476
+ value: adapter.name,
3477
+ label: adapter.name
3478
+ })), {
3479
+ value: "custom",
3480
+ label: "Custom",
3481
+ hint: "a no-op adapter you implement"
3482
+ }], fitting[0]?.name);
3483
+ if (picked === null) return null;
3484
+ const adapter = fitting.find(({ name }) => name === picked);
3485
+ if (adapter) {
3486
+ const options = await askOptions(context, folder, adapter, {}, false);
3487
+ return {
3488
+ folder,
3489
+ module: place(adapter),
3490
+ options
3491
+ };
3492
+ }
3493
+ const port = CUSTOM_PORT_OF[kind];
3494
+ const name = await askName(context, port, `${path.posix.basename(folder.dir)}Delivery`.replace(/-([a-z])/g, (_m, c) => c.toUpperCase()));
3495
+ if (name === null) return null;
3496
+ const module = kebab(name);
3497
+ state.entries.push({
3498
+ factory: MODULE_OF[port],
3499
+ port,
3500
+ adapter: name,
3501
+ name: module,
3502
+ from: customFiles(name).from
3503
+ });
3504
+ state.writes.push(...customWrites(port, name, state.pkg));
3505
+ return {
3506
+ folder,
3507
+ module,
3508
+ options: {}
3509
+ };
3510
+ };
3511
+ /** The command that builds a folder: its unit's, its package.json script's, or one asked once. */
3512
+ const buildFor = async (context, folder, yes) => {
3513
+ if (JSON.parse(context.files.read(path.posix.join(folder.dir, "package.json")) ?? "{}").scripts?.build) return null;
3514
+ if (yes) return null;
3515
+ const typed = await context.prompter.text(`${folder.dir} has no "build" script. Command to build it? (empty: nothing to build)`);
3516
+ return typed?.trim() ? typed.trim() : null;
3517
+ };
3518
+ /**
3519
+ * `shiplane setup`: the one command to set releases up and keep them right. It reads the
3520
+ * repository, takes what it can prove, asks only the rest, then rehearses a release (builds, plan,
3521
+ * sign-ins) with nothing pushed or deployed. Files are kept only when the rehearsal passes. Run
3522
+ * again, it says all is set or offers what changed.
3523
+ */
3524
+ const setup = async (context, { yes }) => {
3525
+ const { output, prompter, files } = context;
3526
+ const pkg = releasePackage(files);
3527
+ const needsPerson = [];
3528
+ const writes = [];
3529
+ output.line();
3530
+ output.line(` ${paint("bold", "shiplane setup")} ${paint("dim", path.basename(context.root))}`);
3531
+ output.line();
3532
+ const existing = files.exists("shiplane.config.ts") ? await context.load() : null;
3533
+ if (existing && existing.problems.length > 0) {
3534
+ existing.problems.forEach(({ file, line, message, hint }) => {
3535
+ output.line(` ${paint("red", "✗")} ${paint("bold", line === void 0 ? file : `${file}:${line}`)} ${message}`);
3536
+ if (hint) output.line(` ${paint("dim", hint)}`);
3537
+ });
3538
+ output.line(` ${paint("dim", "Fix these, then run shiplane setup again. Nothing written.")}`);
3539
+ return false;
3540
+ }
3541
+ const flow = existing ? null : await chooseFlow(context, yes, needsPerson, writes, pkg);
3542
+ if (existing) output.line(` ${ok} flow ${paint("dim", CONFIG_FILE)}`);
3543
+ else if (!flow && needsPerson.length === 0) return cancelled(context);
3544
+ const patterns = existing ? existing.units.length > 0 ? workspacePatterns(files) : await chooseFolders(context, yes, needsPerson) : await chooseFolders(context, yes, needsPerson);
3545
+ if (!patterns && needsPerson.length === 0) return cancelled(context);
3546
+ if (existing && existing.units.length > 0) output.line(` ${ok} ${existing.units.length} apps ${paint("dim", "unchanged, your edits kept")}`);
3547
+ const modules = [...existing?.modules ?? []];
3548
+ const entries = [];
3549
+ const placed = [];
3550
+ for (const folder of patterns ? newFolders(context, patterns) : []) {
3551
+ const result = await placeFolder(context, folder, {
3552
+ yes,
3553
+ needsPerson,
3554
+ modules,
3555
+ entries,
3556
+ writes,
3557
+ pkg
3558
+ });
3559
+ if (result === null && needsPerson.length === 0) return cancelled(context);
3560
+ if (result && result !== "skip") {
3561
+ const buildCommand = await buildFor(context, folder, yes);
3562
+ placed.push(buildCommand ? {
3563
+ ...result,
3564
+ options: {
3565
+ buildCommand,
3566
+ ...result.options
3567
+ }
3568
+ } : result);
3569
+ }
3570
+ }
3571
+ if (needsPerson.length > 0) {
3572
+ output.line();
3573
+ output.line(` ${paint("red", "✗")} ${needsPerson.length} thing${needsPerson.length === 1 ? "" : "s"} need${needsPerson.length === 1 ? "s" : ""} a person:`);
3574
+ needsPerson.forEach((item) => output.line(` ${item}`));
3575
+ output.line(` ${paint("dim", "Run shiplane setup without --yes. Nothing written.")}`);
3576
+ return false;
3577
+ }
3578
+ if (!existing) {
3579
+ const units = patterns && patterns.join() !== workspacePatterns(files).join() ? patterns : void 0;
3580
+ writes.unshift({
3581
+ file: CONFIG_FILE,
3582
+ text: renderConfig(entries, pkg, flow ?? DEFAULT_FLOW, units),
3583
+ created: true
3584
+ });
3585
+ } else if (entries.length > 0) {
3586
+ let config = files.read("shiplane.config.ts") ?? "";
3587
+ for (const entry of entries) config = addToConfig(config, entry, pkg) ?? config;
3588
+ writes.unshift({
3589
+ file: CONFIG_FILE,
3590
+ text: config,
3591
+ created: false
3592
+ });
3593
+ }
3594
+ placed.forEach(({ folder, module, options, reason }) => writes.push({
3595
+ file: path.posix.join(folder.dir, UNIT_FILE),
3596
+ text: renderUnit(module, options, {
3597
+ reason,
3598
+ schemaLine: schemaLineFor(folder.dir)
3599
+ }),
3600
+ created: true
3601
+ }));
3602
+ if (writes.length === 0) {
3603
+ const passed = await rehearse(context);
3604
+ if (passed) output.line(` ${ok} all set`);
3605
+ return passed;
3606
+ }
3607
+ const before = [...writes.map(({ file }) => file), SCHEMA_FILE].map((file) => ({
3608
+ file,
3609
+ text: files.read(file)
3610
+ }));
3611
+ writes.forEach(({ file, text }) => files.write(file, text));
3612
+ if (existing === null || entries.length > 0) {
3613
+ const release = await context.load();
3614
+ if (release.modules.length > 0) files.write(SCHEMA_FILE, schemaText(release.modules));
3615
+ }
3616
+ const passed = await rehearse(context);
3617
+ if (!(passed && (yes || await prompter.confirm("Releasable. Write it?", true)))) {
3618
+ before.forEach(({ file, text }) => text === null ? files.remove(file) : files.write(file, text));
3619
+ output.line(` ${paint("dim", passed ? "Nothing written." : "Fix it, then run shiplane setup again. Nothing written.")}`);
3620
+ return false;
3621
+ }
3622
+ writes.forEach(({ file, created }) => output.line(` ${created ? paint("green", "+") : paint("yellow", "~")} ${file}`));
3623
+ if (writes.some(({ file }) => file.startsWith("shiplane/adapters/"))) {
3624
+ output.line(` ${paint("dim", "Custom adapters start in memory: fill them in until their contract test passes.")}`);
3625
+ output.line(` ${paint("dim", "Works? Share it as shiplane-<name>, or open a pull request at github.com/arnaud-zg/packages.")}`);
3626
+ }
3627
+ output.line();
3628
+ output.line(` ${ok} ${paint("bold", "Ready.")} Add a changeset, merge, and run ${paint("cyan", "shiplane")}`);
3629
+ return true;
3630
+ };
3631
+ const cancelled = (context) => {
3632
+ context.output.line(` ${paint("dim", "Nothing written.")}`);
3633
+ return false;
3634
+ };
3635
+ //#endregion
3636
+ //#region src/adapters/terminal/live-line.ts
3637
+ const TICK_MS = 140;
3638
+ /**
3639
+ * The one line the release redraws in place, an ora spinner. Anything else printed goes above it,
3640
+ * and a prompt or a child process holds it so the terminal is theirs meanwhile.
3641
+ */
3642
+ var LiveLine = class {
3643
+ spinner = null;
3644
+ held = 0;
3645
+ get busy() {
3646
+ return this.spinner !== null;
3647
+ }
3648
+ show({ frames, text, suffix }, animate) {
3649
+ this.spinner = ora({
3650
+ text,
3651
+ suffixText: suffix,
3652
+ stream: process.stdout,
3653
+ discardStdin: false,
3654
+ isEnabled: animate,
3655
+ ...frames && frames.length > 0 ? { spinner: {
3656
+ interval: TICK_MS,
3657
+ frames: [...frames]
3658
+ } } : { spinner: "dots" }
3659
+ });
3660
+ if (this.held === 0) this.spinner.start();
3661
+ }
3662
+ /** Ends the live line with a symbol kept on screen: ✓, ✗ or !. */
3663
+ finish(symbol, text) {
3664
+ const spinner = this.spinner;
3665
+ this.spinner = null;
3666
+ if (!spinner) return;
3667
+ if (this.held > 0) {
3668
+ process.stdout.write(`${symbol} ${text ?? spinner.text}\n`);
3669
+ return;
3670
+ }
3671
+ spinner.stopAndPersist({
3672
+ symbol,
3673
+ ...text === void 0 ? {} : { text }
3674
+ });
3675
+ }
3676
+ clear() {
3677
+ this.spinner?.stop();
3678
+ this.spinner = null;
3679
+ }
3680
+ /** Prints a line above the live one. */
3681
+ above(text) {
3682
+ const live = this.spinner && this.held === 0 ? this.spinner : null;
3683
+ live?.clear();
3684
+ process.stdout.write(`${text}\n`);
3685
+ live?.render();
3686
+ }
3687
+ /** Gives the terminal to `work`, a prompt or a child process, then draws the live line again. */
3688
+ async hold(work) {
3689
+ if (this.spinner && this.held === 0) this.spinner.stop();
3690
+ this.held += 1;
3691
+ try {
3692
+ return await work();
3693
+ } finally {
3694
+ this.held -= 1;
3695
+ if (this.spinner && this.held === 0) this.spinner.start();
3696
+ }
3697
+ }
3698
+ };
3699
+ const liveLine = new LiveLine();
3700
+ //#endregion
3701
+ //#region src/adapters/shell/system-shell.adapter.ts
3702
+ const MAX_BUFFER = 256 * 1024 * 1024;
3703
+ const environment = (options) => ({
3704
+ ...process.env,
3705
+ ...options.env
3706
+ });
3707
+ const systemShell = {
3708
+ capture: (command, args, options = {}) => new Promise((resolve) => {
3709
+ const child = execFile(command, [...args], {
3710
+ cwd: options.cwd,
3711
+ env: environment(options),
3712
+ maxBuffer: MAX_BUFFER
3713
+ }, (error, stdout, stderr) => {
3714
+ const code = error?.code;
3715
+ resolve({
3716
+ status: !error ? 0 : typeof code === "number" ? code : code === "ENOENT" ? 127 : 1,
3717
+ stdout,
3718
+ stderr
3719
+ });
3720
+ });
3721
+ if (options.input !== void 0) child.stdin?.end(options.input);
3722
+ }),
3723
+ attach: (command, args, options = {}) => liveLine.hold(() => new Promise((resolve) => {
3724
+ const child = spawn(command, [...args], {
3725
+ cwd: options.cwd,
3726
+ env: environment(options),
3727
+ stdio: options.input === void 0 ? "inherit" : [
3728
+ "pipe",
3729
+ "inherit",
3730
+ "inherit"
3731
+ ]
3732
+ });
3733
+ if (options.input !== void 0) child.stdin?.end(options.input);
3734
+ child.on("error", () => resolve(127));
3735
+ child.on("close", (code) => resolve(code ?? 1));
3736
+ })),
3737
+ env: (name) => process.env[name]
3738
+ };
3739
+ //#endregion
3740
+ //#region src/application/readStatus.ts
3741
+ /** Where every unit stands on an environment, and the step a release takes next. Reads only. */
3742
+ const readStatus = async (context, environment) => {
3743
+ const info = await readScope(context, environment);
3744
+ const choices = scopeChoices(info, environment);
3745
+ const [releasePrs, untagged] = await Promise.all([context.services.codeHost.openPrsFrom(RELEASE_BRANCH_PREFIX).catch(() => []), missingTags(context)]);
3746
+ const { head } = await context.services.sourceControl.position();
3747
+ const live = async (name) => {
3748
+ const unit = context.release.units.find((candidate) => candidate.name === name);
3749
+ const module = unit && moduleOf(context, unit);
3750
+ if (!unit || !module?.inspect) return {};
3751
+ const input = jobInput(context, module, unit, {
3752
+ tag: tagName(unit.name, unit.version, context.release.tagFormat),
3753
+ environment,
3754
+ commit: head
3755
+ });
3756
+ return { live: await module.inspect(decideContext(context), input).catch((error) => ({ error: error instanceof Error ? error.message : String(error) })) };
3757
+ };
3758
+ return {
3759
+ environment,
3760
+ units: await Promise.all(info.map(async (entry) => {
3761
+ const choice = choices.find(({ app }) => app === entry.app);
3762
+ const unit = context.release.units.find(({ name }) => name === entry.app);
3763
+ return {
3764
+ unit: entry.app,
3765
+ target: (unit && moduleOf(context, unit)?.provider) ?? "",
3766
+ version: entry.version,
3767
+ tag: tagName(entry.app, entry.version, context.release.tagFormat),
3768
+ tagged: entry.tagged,
3769
+ changesets: entry.changesets,
3770
+ commits: entry.commits,
3771
+ pending: choice?.pending ?? false,
3772
+ hint: choice?.hint ?? "",
3773
+ ...await live(entry.app)
3774
+ };
3775
+ })),
3776
+ releasePrs,
3777
+ untagged,
3778
+ next: nextStep({
3779
+ pending: info.reduce((sum, { changesets }) => sum + changesets, 0),
3780
+ releasePrs,
3781
+ untagged: untagged.length,
3782
+ unreleased: info.filter(({ changesets, commits }) => changesets === 0 && commits > 0).length
3783
+ })
3784
+ };
3785
+ };
3786
+ //#endregion
3787
+ export { refreshEditorSchema as C, nodeFiles as D, keysAt as E, CONFIG_FILE as S, ENVIRONMENTS as T, loadRelease as _, releaseToPreview as a, initRelease as b, promote as c, pickScope as d, openReleasePr as f, findConfig as g, docsFor as h, setup as i, shipTo as l, newAdapter as m, systemShell as n, missingTags as o, prepareRelease as p, liveLine as r, tagRelease as s, readStatus as t, planShips as u, addUnit as v, optionsFor as w, doctor as x, removeUnit as y };
3788
+
3789
+ //# sourceMappingURL=readStatus-YTZXH_Hh.js.map