shiplane 0.2.0 → 0.3.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 @@
1
+ {"version":3,"file":"readStatus-Bo7hpUT3.js","names":["NAMES","reasonOf","plural","plural","STAGES"],"sources":["../src/adapters/files/node-files.adapter.ts","../src/modules/suggest.ts","../src/application/config/problem.ts","../src/application/config/unitSchema.ts","../src/domain/environment.ts","../src/application/config/values.ts","../src/application/config/readUnitFile.ts","../src/application/releaseOrder.ts","../src/application/say.ts","../src/domain/codeScope.ts","../src/application/config/optionsFor.ts","../src/application/targets.ts","../src/application/requirements.ts","../src/application/setupFiles.ts","../src/application/doctor.ts","../src/application/initRelease.ts","../src/application/addUnit.ts","../src/adapters/manifest/package-json-manifest.adapter.ts","../src/application/config/loadRelease.ts","../src/application/docsFor.ts","../src/application/newAdapter.ts","../src/domain/releasePr.ts","../src/domain/companions.ts","../src/application/readScope.ts","../src/application/prepareRelease.ts","../src/application/steps.ts","../src/application/openReleasePr.ts","../src/domain/scope.ts","../src/application/pickScope.ts","../src/application/followUps.ts","../src/application/planShips.ts","../src/application/askPath.ts","../src/application/waitForMerge.ts","../src/application/pullRequestFirst.ts","../src/application/ship.ts","../src/application/promote.ts","../src/application/tagRelease.ts","../src/application/releaseToPreview.ts","../src/application/customAdapter.ts","../src/application/rehearse.ts","../src/application/setup.ts","../src/adapters/terminal/live-line.ts","../src/adapters/shell/system-shell.adapter.ts","../src/application/readStatus.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport type { Files } from \"../../ports/files.port\";\n\n/** The repository on disk, under `root`. */\nexport const nodeFiles = (root: string): Files => {\n const at = (file: string) => path.join(root, file);\n return {\n exists: (file) => fs.existsSync(at(file)),\n read: (file) => (fs.existsSync(at(file)) ? fs.readFileSync(at(file), \"utf8\") : null),\n write: (file, text) => {\n fs.mkdirSync(path.dirname(at(file)), { recursive: true });\n fs.writeFileSync(at(file), text);\n },\n remove: (file) => fs.rmSync(at(file), { force: true }),\n list: (dir) => (fs.existsSync(at(dir)) ? fs.readdirSync(at(dir)) : []),\n folders: (dir) =>\n fs.existsSync(at(dir))\n ? fs\n .readdirSync(at(dir), { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name)\n : [],\n };\n};\n","import type { DeliveryAdapter } from \"../ports/adapter.port\";\nimport type { MobileDistributionPort } from \"../ports/mobile-distribution.port\";\nimport type { PackageRegistryPort } from \"../ports/package-registry.port\";\nimport type { ServerHostingPort } from \"../ports/server-hosting.port\";\nimport type { StaticHostingPort } from \"../ports/static-hosting.port\";\nimport type { ReleaseModule } from \"./module\";\nimport { backendService } from \"./backend-service/backend-service.module\";\nimport { mobileApp } from \"./mobile-app/mobile-app.module\";\nimport { publishedPackage } from \"./published-package/published-package.module\";\nimport { webApp } from \"./web-app/web-app.module\";\n\n/** An adapter of any delivery port, as `init` offers them. */\nexport type AnyDeliveryAdapter =\n | DeliveryAdapter<ServerHostingPort>\n | DeliveryAdapter<StaticHostingPort>\n | DeliveryAdapter<MobileDistributionPort>\n | DeliveryAdapter<PackageRegistryPort>;\n\n/** The module a provider suggests: its kind, the factory a config calls, the port it fills. */\nexport interface Suggested {\n kind: string;\n factory: string;\n port: string;\n}\n\nconst SUGGESTED: Record<AnyDeliveryAdapter[\"capability\"], Suggested> = {\n \"server-hosting\": { kind: \"backend-service\", factory: \"backendService\", port: \"serverHosting\" },\n \"static-hosting\": { kind: \"web-app\", factory: \"webApp\", port: \"staticHosting\" },\n \"mobile-distribution\": {\n kind: \"mobile-app\",\n factory: \"mobileApp\",\n port: \"mobileDistribution\",\n },\n \"package-registry\": {\n kind: \"published-package\",\n factory: \"publishedPackage\",\n port: \"packageRegistry\",\n },\n};\n\nexport const suggestedModule = (adapter: AnyDeliveryAdapter): Suggested =>\n SUGGESTED[adapter.capability];\n\n/** The module a provider makes under a name, as `init` composes it before the config exists. */\nexport const moduleFor = (adapter: AnyDeliveryAdapter, name: string): ReleaseModule => {\n switch (adapter.capability) {\n case \"server-hosting\":\n return backendService({ name, serverHosting: adapter });\n case \"static-hosting\":\n return webApp({ name, staticHosting: adapter });\n case \"mobile-distribution\":\n return mobileApp({ name, mobileDistribution: adapter });\n case \"package-registry\":\n return publishedPackage({ name, packageRegistry: adapter });\n }\n};\n","/** Something wrong in the config, said where a person can fix it. */\nexport interface ConfigProblem {\n /** Relative to the repository root. */\n file: string;\n line?: number;\n message: string;\n hint?: string;\n}\n\nconst distance = (left: string, right: string): number => {\n const previous = Array.from({ length: right.length + 1 }, (_, index) => index);\n for (let row = 1; row <= left.length; row += 1) {\n let diagonal = previous[0] ?? 0;\n previous[0] = row;\n for (let column = 1; column <= right.length; column += 1) {\n const above = previous[column] ?? 0;\n const cost = left[row - 1] === right[column - 1] ? 0 : 1;\n previous[column] = Math.min(above + 1, (previous[column - 1] ?? 0) + 1, diagonal + cost);\n diagonal = above;\n }\n }\n return previous[right.length] ?? 0;\n};\n\n/** The candidate a typo most likely meant, when one is close enough to be worth naming. */\nexport const didYouMean = (word: string, candidates: readonly string[]): string | undefined => {\n const [best] = candidates\n .map((candidate) => ({\n candidate,\n cost: distance(word.toLowerCase(), candidate.toLowerCase()),\n }))\n .sort((left, right) => left.cost - right.cost);\n return best && best.cost <= Math.max(2, Math.floor(word.length / 3))\n ? `did you mean \"${best.candidate}\"?`\n : undefined;\n};\n\n/** Top to bottom per file, problems without a line last. */\nexport const sortProblems = (problems: ConfigProblem[]) =>\n [...problems].sort(\n (left, right) =>\n left.file.localeCompare(right.file) ||\n (left.line ?? Number.MAX_SAFE_INTEGER) - (right.line ?? Number.MAX_SAFE_INTEGER),\n );\n","import { z } from \"zod\";\n\nimport type { ReleaseModule } from \"../../modules/module\";\n\ninterface Inspectable {\n def: {\n type: string;\n innerType?: z.ZodType;\n defaultValue?: unknown;\n keyType?: z.ZodType;\n valueType?: z.ZodType;\n element?: z.ZodType;\n options?: z.ZodType[];\n shape?: Record<string, z.ZodType>;\n };\n description?: string;\n}\n\nconst definition = (schema: z.ZodType) => (schema as unknown as Inspectable).def;\n\nconst mapShape = (shape: Record<string, z.ZodType>, map: (schema: z.ZodType) => z.ZodType) =>\n Object.fromEntries(Object.entries(shape).map(([key, value]) => [key, map(value)]));\n\n/**\n * The same schema, refusing unknown keys at every depth. Read through `def.type` rather than\n * `instanceof`: a config loads its own copy of zod.\n */\nexport const deepStrict = (schema: z.ZodType): z.ZodType => {\n const def = definition(schema);\n const strict = (): z.ZodType => {\n switch (def.type) {\n case \"object\":\n return z.strictObject(mapShape(def.shape ?? {}, deepStrict));\n case \"optional\":\n return def.innerType ? deepStrict(def.innerType).optional() : schema;\n case \"nullable\":\n return def.innerType ? deepStrict(def.innerType).nullable() : schema;\n case \"default\":\n return def.innerType ? deepStrict(def.innerType).default(def.defaultValue) : schema;\n case \"union\":\n return z.union((def.options ?? []).map(deepStrict));\n case \"record\":\n return def.keyType && def.valueType\n ? z.record(def.keyType as z.ZodString, deepStrict(def.valueType))\n : schema;\n case \"array\":\n return def.element ? z.array(deepStrict(def.element)) : schema;\n default:\n return schema;\n }\n };\n const result = strict();\n const { description } = schema as unknown as Inspectable;\n return description && result !== schema ? result.describe(description) : result;\n};\n\n/** The keys an object schema allows at a path, best effort, for \"did you mean\". */\nexport const keysAt = (schema: z.ZodType, at: readonly PropertyKey[]): string[] => {\n const def = definition(schema);\n if (def.type === \"optional\" || def.type === \"nullable\" || def.type === \"default\") {\n return def.innerType ? keysAt(def.innerType, at) : [];\n }\n if (def.type === \"union\") return (def.options ?? []).flatMap((option) => keysAt(option, at));\n if (def.type === \"record\" && at.length > 0 && def.valueType) {\n return keysAt(def.valueType, at.slice(1));\n }\n if (def.type !== \"object\") return [];\n const [first, ...rest] = at;\n if (first === undefined) return Object.keys(def.shape ?? {});\n const child = def.shape?.[String(first)];\n return child ? keysAt(child, rest) : [];\n};\n\n/** What a unit file naming this module may hold: `module`, then its adapter's settings. */\nexport const unitSchema = (module: ReleaseModule) =>\n z.strictObject({\n module: z\n .literal(module.name)\n .describe(`The module that ships this app, with ${module.provider}`),\n buildCommand: z\n .string()\n .optional()\n .describe('How to build this app, when its package.json has no \"build\" script'),\n ...mapShape(module.settings.shape, deepStrict),\n });\n\n/** The JSON Schema editors read for `shiplane.unit.yml`: the module an app names picks its keys. */\nexport const unitJsonSchema = (modules: readonly ReleaseModule[]) =>\n z.toJSONSchema(z.union(modules.map(unitSchema)), { io: \"input\", unrepresentable: \"any\" });\n","/** Where a unit runs, in promotion order: production ships what preview validated. */\nexport const ENVIRONMENTS = [\"preview\", \"production\"] as const;\n\nexport type Environment = (typeof ENVIRONMENTS)[number];\n","import type { Environment } from \"../../domain/environment\";\nimport { ENVIRONMENTS } from \"../../domain/environment\";\n\nexport const isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** A map keyed by exactly the environments: one of its values is picked per environment. */\nexport const isPerEnvValue = (value: unknown): value is Record<Environment, unknown> =>\n isRecord(value) &&\n Object.keys(value).length === ENVIRONMENTS.length &&\n ENVIRONMENTS.every((environment) => environment in value);\n\n/** `${units.<name>.<key>}`, where key may be dotted. */\nexport const REFERENCE = /\\$\\{units\\.([\\w-]+)\\.([\\w.-]+)\\}/g;\n\nexport interface Reference {\n unit: string;\n key: string;\n /** Where it is written in the unit file. */\n at: string[];\n}\n\nexport const referencesIn = (value: unknown, at: string[] = []): Reference[] => {\n if (typeof value === \"string\") {\n return [...value.matchAll(REFERENCE)].map(([, unit = \"\", key = \"\"]) => ({ unit, key, at }));\n }\n if (Array.isArray(value)) {\n return value.flatMap((item, index) => referencesIn(item, [...at, String(index)]));\n }\n if (isRecord(value)) {\n return Object.entries(value).flatMap(([key, item]) => referencesIn(item, [...at, key]));\n }\n return [];\n};\n\nexport const valueAt = (value: unknown, at: readonly string[]): unknown =>\n at.reduce<unknown>((current, key) => (isRecord(current) ? current[key] : undefined), value);\n","import type { Document } from \"yaml\";\nimport type { z } from \"zod\";\nimport { isMap, isScalar, isSeq, LineCounter, parseDocument } from \"yaml\";\n\nimport type { ReleaseModule } from \"../../modules/module\";\nimport type { ConfigProblem } from \"./problem\";\nimport { didYouMean } from \"./problem\";\nimport { keysAt, unitSchema } from \"./unitSchema\";\nimport { isRecord } from \"./values\";\n\nexport const UNIT_FILE = \"shiplane.unit.yml\";\n/** The name unit files had before shiplane: still read, listed to rename. */\nexport const LEGACY_UNIT_FILE = \"release.unit.yml\";\nexport const UNIT_FILES = [UNIT_FILE, LEGACY_UNIT_FILE];\n\nexport interface UnitFile {\n /** The module that ships it. */\n module: string;\n /** Its `buildCommand:`, when it says one. */\n buildCommand?: string;\n options: Record<string, unknown>;\n /** The line a key path sits on, for problems found after reading. */\n lineOf: (at: readonly string[]) => number | undefined;\n}\n\nconst locate =\n (doc: Document, counter: LineCounter) =>\n (at: readonly PropertyKey[], key?: string): number | undefined => {\n let node: unknown = doc.contents;\n for (const segment of at) {\n if (!isMap(node) && !isSeq(node)) return undefined;\n node = node.get(segment, true);\n }\n if (key !== undefined && isMap(node)) {\n node = node.items.find((pair) => isScalar(pair.key) && pair.key.value === key)?.key;\n }\n const offset = (node as { range?: number[] } | undefined)?.range?.[0];\n return offset === undefined ? undefined : counter.linePos(offset).line;\n };\n\nconst describeIssue = (\n issue: z.core.$ZodIssue,\n file: string,\n module: ReleaseModule,\n lineAt: ReturnType<typeof locate>,\n): ConfigProblem[] => {\n const at = issue.path;\n if (issue.code === \"unrecognized_keys\") {\n return issue.keys.map((key) => ({\n file,\n line: lineAt(at, key),\n message: `unknown key \"${[...at, key].join(\".\")}\" for ${module.name}`,\n hint: didYouMean(key, keysAt(module.settings, at)),\n }));\n }\n const name = at.join(\".\");\n if (issue.code === \"invalid_type\" && issue.message.endsWith(\"received undefined\")) {\n // A missing key has no line of its own: its parent map's, unless that is the whole file.\n const line = at.length > 1 ? lineAt(at.slice(0, -1)) : undefined;\n return [{ file, line, message: `\"${name}\" is required` }];\n }\n return [{ file, line: lineAt(at), message: `\"${name}\": ${issue.message}` }];\n};\n\nconst problem = (file: string, line: number | undefined, message: string, hint: string) => ({\n problems: [{ file, line, message, hint }],\n});\n\n/** A unit file checked against the adapter of the module it names, every problem with its line. */\nexport const readUnitFile = (\n file: string,\n text: string,\n modules: readonly ReleaseModule[],\n features: readonly string[] = [],\n): { unit?: UnitFile; problems: ConfigProblem[] } => {\n const counter = new LineCounter();\n const doc = parseDocument(text, { lineCounter: counter, uniqueKeys: true, prettyErrors: false });\n if (doc.errors.length > 0) {\n return {\n problems: doc.errors.map((error) => ({\n file,\n line: counter.linePos(error.pos[0]).line,\n message: error.message.split(\"\\n\")[0] ?? error.message,\n })),\n };\n }\n const lineAt = locate(doc, counter);\n const data: unknown = doc.toJS();\n const names = modules.map(({ name }) => name);\n const oneOf = `one of: ${names.join(\", \")}`;\n if (isRecord(data) && \"target\" in data && !(\"module\" in data)) {\n return problem(\n file,\n lineAt([\"target\"]),\n \"target: is now module: the module in shiplane.config.ts that ships this app\",\n oneOf,\n );\n }\n if (!isRecord(data) || typeof data.module !== \"string\") {\n return problem(file, 1, \"a unit file starts with module: the module that ships it\", oneOf);\n }\n const named = data.module;\n const module = modules.find(({ name }) => name === named);\n if (features.includes(named)) {\n return problem(\n file,\n lineAt([\"module\"]),\n `\"${named}\" ships no app: it runs on every ship`,\n oneOf,\n );\n }\n if (!module) {\n return problem(\n file,\n lineAt([\"module\"]),\n `no module named \"${named}\" in shiplane.config.ts`,\n didYouMean(named, names) ?? oneOf,\n );\n }\n const parsed = unitSchema(module).safeParse(data);\n if (!parsed.success) {\n return {\n problems: parsed.error.issues.flatMap((issue) => describeIssue(issue, file, module, lineAt)),\n };\n }\n const options = Object.fromEntries(\n Object.entries(data).filter(([key]) => key !== \"module\" && key !== \"buildCommand\"),\n );\n const buildCommand = typeof data.buildCommand === \"string\" ? data.buildCommand : undefined;\n return {\n unit: {\n module: named,\n ...(buildCommand ? { buildCommand } : {}),\n options,\n lineOf: (at) => lineAt(at),\n },\n problems: [],\n };\n};\n","import type { ReleaseUnit } from \"../domain/unit\";\nimport { referencesIn } from \"./config/values\";\n\n/** `admin (reads api.url)`: an app, with the values of other apps it reads. */\nconst withReads = ({ name, options }: ReleaseUnit) => {\n const reads = [\n ...new Set(\n referencesIn(options)\n .filter(({ unit }) => unit !== name)\n .map(({ unit, key }) => `${unit}.${key}`),\n ),\n ];\n return reads.length > 0 ? `${name} (reads ${reads.join(\", \")})` : name;\n};\n\n/** `1 expo · Latest → 2 api → 3 admin (reads api.url)`: the apps numbered in release order. */\nexport const releaseOrder = (units: readonly ReleaseUnit[]) =>\n units\n .map((unit, index) => `${index + 1} ${withReads(unit)}${index === 0 ? \" · Latest\" : \"\"}`)\n .join(\" → \");\n","import { styleText } from \"node:util\";\n\nimport type { ReleaseContext } from \"./context\";\n\ntype Style = Parameters<typeof styleText>[0];\n\nexport const paint = (style: Style, text: string) => styleText(style, text);\n\n/** A failure, said with what to run next; the caller returns false so nothing else runs. */\nexport const fail = (\n { output, progress }: ReleaseContext,\n title: string,\n detail: string,\n commands: string[] = [],\n) => {\n progress.say(\"worried\", `${paint([\"bold\", \"red\"], `✗ ${title}:`)} ${detail}`);\n commands.forEach((command) => output.line(` ${paint(\"cyan\", command)}`));\n};\n\n/** Yes without asking under --yes; without a terminal, no. */\nexport const confirm = async (\n { prompter, options, output }: ReleaseContext,\n question: string,\n initial = false,\n) => {\n if (options.yes) return true;\n if (!prompter.interactive) {\n output.line(paint(\"yellow\", \"Not a terminal: pass --yes to run it.\"));\n return false;\n }\n return prompter.confirm(question, initial);\n};\n\n/** `api`, `api and admin`, `api, admin and landing`. */\nexport const listed = (names: readonly string[]) =>\n names.length < 2\n ? names.join(\"\")\n : `${names.slice(0, -1).join(\", \")} and ${names.slice(-1).join(\"\")}`;\n\n/** The keys a screen offers, each the same way: `d see the diff o open it on GitHub`. */\nexport const keyHints = (hints: readonly { key: string; label: string }[]) =>\n hints.map(({ key, label }) => `${paint(\"cyan\", key)} ${paint(\"dim\", label)}`).join(\" \");\n","/** Where a unit's code comes from, to tell which changed files can reach what it ships. */\nexport interface CodeScope {\n /** Its own folder and those of the workspace packages it uses. */\n own: readonly string[];\n /** Every workspace package's folder. */\n workspace: readonly string[];\n versionFiles: ReadonlySet<string>;\n}\n\n// Notes, docs, CI and release config: they change how a release is made or read, never what it ships.\nconst NOT_SHIPPED = [\n /(^|\\/)(shiplane|release)\\.unit\\.yml$/,\n /^\\.changeset\\//,\n /^\\.planning\\//,\n /^\\.github\\//,\n /^\\.claude\\//,\n /^docs\\//,\n /\\.md$/,\n];\n\n/** A package's folder and the folders of every workspace package it uses, however deep. */\nexport const codeFolders = (\n packageName: string,\n dependencies: Record<string, string[]>,\n folders: Record<string, string>,\n): string[] => {\n const seen = new Set<string>([packageName]);\n const queue = [packageName];\n for (const name of queue) {\n for (const dependency of dependencies[name] ?? []) {\n if (seen.has(dependency)) continue;\n seen.add(dependency);\n queue.push(dependency);\n }\n }\n return [...seen].flatMap((name) => folders[name] ?? []);\n};\n\n/**\n * The changed files that can reach what a unit ships: in its own code folders, or at the root\n * outside every workspace folder, such as the lockfile. Another app's folder never does.\n */\nexport const changesReaching = (files: readonly string[], scope: CodeScope): string[] =>\n files.filter((file) => {\n if (scope.versionFiles.has(file) || NOT_SHIPPED.some((pattern) => pattern.test(file))) {\n return false;\n }\n const inside = (folder: string) => file.startsWith(`${folder}/`);\n return scope.own.some(inside) || !scope.workspace.some(inside);\n });\n","import type { Environment } from \"../../domain/environment\";\nimport type { ReleaseUnit } from \"../../domain/unit\";\nimport { isPerEnvValue, isRecord, REFERENCE, valueAt } from \"./values\";\n\nconst resolve = (value: unknown, env: Environment, units: readonly ReleaseUnit[]): unknown => {\n const picked = isPerEnvValue(value) ? value[env] : value;\n if (typeof picked === \"string\") {\n return picked.replace(REFERENCE, (_match, name: string, key: string) => {\n const other = units.find((unit) => unit.name === name);\n const resolved = other ? resolve(valueAt(other.options, key.split(\".\")), env, units) : \"\";\n return typeof resolved === \"string\" ? resolved : \"\";\n });\n }\n if (Array.isArray(picked)) return picked.map((item) => resolve(item, env, units));\n if (isRecord(picked)) {\n return Object.fromEntries(\n Object.entries(picked).map(([key, item]) => [key, resolve(item, env, units)]),\n );\n }\n return picked;\n};\n\n/** A unit's options for one environment: per-environment values picked, references filled in. */\nexport const optionsFor = (\n unit: ReleaseUnit,\n env: Environment,\n units: readonly ReleaseUnit[],\n): Record<string, unknown> => {\n const resolved = resolve(unit.options, env, units);\n return isRecord(resolved) ? resolved : {};\n};\n","import path from \"node:path\";\n\nimport type { Environment } from \"../domain/environment\";\nimport type { ReleaseUnit } from \"../domain/unit\";\nimport type { AfterShipContext, AppInput, ReleaseModule } from \"../modules/module\";\nimport type { Command, DecideContext, Job } from \"../ports/delivery.port\";\nimport type { ReleaseContext } from \"./context\";\nimport { changesReaching, codeFolders } from \"../domain/codeScope\";\nimport { optionsFor } from \"./config/optionsFor\";\n\n/** The module that ships an app: the one its unit file names. */\nexport const moduleOf = ({ release }: ReleaseContext, unit: ReleaseUnit) =>\n release.modules.find(({ name }) => name === unit.module);\n\n/** An app's settings for an environment, its module's defaults applied first. */\nexport const resolvedOptions = (\n module: ReleaseModule,\n unit: ReleaseUnit,\n environment: Environment,\n units: readonly ReleaseUnit[],\n): Record<string, unknown> => {\n const withDefaults = module.settings.parse(unit.options);\n return optionsFor({ ...unit, options: withDefaults }, environment, units);\n};\n\n/** What a module's stages are told about one app's tag. */\nexport const jobInput = (\n context: ReleaseContext,\n module: ReleaseModule,\n unit: ReleaseUnit,\n { tag, environment, commit }: { tag: string; environment: Environment; commit: string },\n): AppInput => ({\n unit,\n tag,\n environment,\n commit,\n options: resolvedOptions(module, unit, environment, context.release.units),\n});\n\n/** Where a tag lands and the jobs that ship it, as its module says. */\nexport const shipPlanOf = (context: ReleaseContext, module: ReleaseModule, input: AppInput) =>\n module.ship(decideContext(context), input);\n\n/** Every file a release may move after a tag without changing what ships. */\nexport const versionFiles = (context: ReleaseContext) =>\n new Set(\n context.release.units.flatMap(\n (unit) =>\n moduleOf(context, unit)?.versionFiles?.(unit, context.release.units, context.open) ?? [],\n ),\n );\n\n/** A command as a person would type it, variables first, secrets by name only. */\nexport const commandLine = ({ command, args, env, secrets }: Command) =>\n [\n ...Object.entries(env ?? {}).map(([key, value]) => `${key}=${value}`),\n command,\n ...args,\n ...(secrets ?? []).flatMap(({ flag, name }) => [flag, `${name}=$${name}`]),\n ].join(\" \");\n\n/** Runs a job's commands here in order, then records the deploy. Throws on the first failure. */\nexport const runHere = async (\n { shell, services, release, output }: ReleaseContext,\n job: Job,\n { tag, environment }: { tag: string; environment: Environment },\n) => {\n const secretArgs = (step: Command) =>\n (step.secrets ?? []).flatMap(({ flag, name }) => {\n const value = shell.env(name);\n if (value) return [flag, `${name}=${value}`];\n output.line(` ! ${name} is not set: ${flag} left out`);\n return [];\n });\n const run = (step: Command) =>\n shell.attach(step.command, [...step.args, ...secretArgs(step)], {\n cwd: path.join(release.root, step.cwd ?? \"\"),\n env: step.env,\n });\n try {\n for (const step of job.local) {\n const status = await run(step);\n if (status !== 0) throw new Error(`${step.command} exited with ${status}`);\n }\n } finally {\n for (const step of job.cleanup ?? []) await run(step);\n }\n if (job.record) await services.codeHost.recordDeployment(tag, environment);\n};\n\n/** Dispatches the ship workflow on a ref for its units and returns at once: the runner ships them. */\nexport const dispatchShip = async (\n { services }: ReleaseContext,\n { ref, units }: { ref: string; units: readonly string[] },\n environment: Environment,\n) =>\n services.ciPipeline.dispatch(services.ciPipeline.shipWorkflow, ref, {\n units: units.join(\" \"),\n environment,\n });\n\n/** Which changed files can reach what a unit ships. */\nconst reaching = async (context: ReleaseContext, unit: ReleaseUnit) => {\n const { versioning } = context.services;\n const [dependencies, folders] = await Promise.all([\n versioning.dependencies(),\n versioning.folders(),\n ]);\n const scope = {\n own: [unit.dir, ...codeFolders(unit.packageName, dependencies, folders)],\n workspace: Object.values(folders),\n versionFiles: versionFiles(context),\n };\n return (files: readonly string[]) => changesReaching(files, scope);\n};\n\n/** What a module's per-app stages may read and run. */\nexport const decideContext = (context: ReleaseContext): DecideContext => ({\n root: context.release.root,\n shell: context.shell,\n sourceControl: context.services.sourceControl,\n codeHost: context.services.codeHost,\n ciPipeline: context.services.ciPipeline,\n units: context.release.units,\n tagFormat: context.release.tagFormat,\n versionFiles: versionFiles(context),\n now: () => context.clock.now(),\n open: context.open,\n changedCode: async (unit, from, to) => {\n const [files, filter] = await Promise.all([\n context.services.sourceControl.diffNames(from, to),\n reaching(context, unit),\n ]);\n return filter(files);\n },\n});\n\n/** What a module may read once apps ship. */\nexport const afterShipContext = (context: ReleaseContext): AfterShipContext => ({\n open: context.open,\n tagFormat: context.release.tagFormat,\n subjectsReaching: async (unit, from, to) => {\n const [commits, filter] = await Promise.all([\n context.services.sourceControl.commitsBetween(from, to),\n reaching(context, unit),\n ]);\n return commits.filter(({ files }) => filter(files).length > 0).map(({ subject }) => subject);\n },\n});\n\n/**\n * What the person reads for an environment: a package registry has no staging, so when every unit\n * is a published package, preview is where users install it — it reads \"live\".\n */\nexport const environmentLabel = (\n context: ReleaseContext,\n units: Iterable<string>,\n environment: string,\n) => {\n if (environment !== \"preview\") return environment;\n const names = [...units];\n const allPackages =\n names.length > 0 &&\n names.every((name) => {\n const unit = context.release.units.find((candidate) => candidate.name === name);\n return unit !== undefined && moduleOf(context, unit)?.kind === \"published-package\";\n });\n return allPackages ? \"live\" : environment;\n};\n","import path from \"node:path\";\n\nimport type { Requirement } from \"../ports/delivery.port\";\nimport type { Shell } from \"../ports/shell.port\";\nimport type { Release } from \"./config/loadRelease\";\nimport type { ReleaseContext } from \"./context\";\nimport { fail } from \"./say\";\nimport { commandLine } from \"./targets\";\n\n/**\n * Every tool and sign-in the flow, the features and the modules need, once each. With `apps`, only\n * the modules shipping one of those apps count.\n */\nexport const requirementsOf = (release: Release, apps?: ReadonlySet<string>): Requirement[] => {\n const appsOf = (name: string) =>\n release.units.filter(({ module, name: app }) => module === name && (!apps || apps.has(app)));\n const required: Requirement[] = [\n ...[\n release.flow.sourceControl,\n release.flow.codeHost,\n release.flow.ciPipeline,\n release.flow.versioning,\n ].flatMap((adapter) => adapter.requirements?.() ?? []),\n ...release.modules.flatMap((module) => {\n const shipped = appsOf(module.name);\n return apps && shipped.length === 0 ? [] : (module.requirements?.(shipped) ?? []);\n }),\n ...release.features.flatMap((feature) => feature.requirements?.() ?? []),\n ];\n return required.filter(\n (requirement, index) =>\n required.findIndex(({ label }) => label === requirement.label) === index,\n );\n};\n\n/** A requirement's check run from the root: its exit status, 127 when the tool is missing. */\nexport const checkStatus = async (shell: Shell, root: string, { check }: Requirement) =>\n (\n await shell.capture(check.command, check.args, {\n cwd: path.join(root, check.cwd ?? \"\"),\n env: check.env,\n })\n ).status;\n\n/**\n * Before a release writes anything: each sign-in its picked units need. A failing one offers its\n * fix, then is checked again. False, with the commands to run, when one still fails.\n */\nexport const preflight = async (\n context: ReleaseContext,\n apps: ReadonlySet<string>,\n): Promise<boolean> => {\n const { shell, prompter, options, release } = context;\n const failing: Requirement[] = [];\n for (const requirement of requirementsOf(release, apps)) {\n const status = await checkStatus(shell, release.root, requirement);\n if (status === 0) continue;\n const { fix } = requirement;\n const offered =\n fix !== undefined && status !== 127 && prompter.interactive && !options.yes\n ? await prompter.confirm(`Run ${commandLine(fix)} now?`, true)\n : false;\n if (offered && fix) {\n await shell.attach(fix.command, fix.args, {\n cwd: path.join(release.root, fix.cwd ?? \"\"),\n env: fix.env,\n });\n if ((await checkStatus(shell, release.root, requirement)) === 0) continue;\n }\n failing.push(requirement);\n }\n if (failing.length === 0) return true;\n fail(\n context,\n `Not signed in: ${failing.map(({ label }) => label).join(\", \")}`,\n \"nothing was written. Sign in, then run the release again.\",\n [...failing.flatMap(({ fix }) => (fix ? [commandLine(fix)] : [])), \"shiplane\"],\n );\n return false;\n};\n","import path from \"node:path\";\nimport { Document } from \"yaml\";\nimport { z } from \"zod\";\n\nimport type { ReleaseModule } from \"../modules/module\";\nimport type { AnyDeliveryAdapter } from \"../modules/suggest\";\nimport type { FolderView } from \"../ports/delivery.port\";\nimport type { Files } from \"../ports/files.port\";\nimport type { Release } from \"./config/loadRelease\";\nimport { suggestedModule } from \"../modules/suggest\";\nimport { UNIT_FILE } from \"./config/readUnitFile\";\nimport { unitJsonSchema } from \"./config/unitSchema\";\n\nexport const CONFIG_FILE = \"shiplane.config.ts\";\n// Generated for the editor, never edited or committed: kept out of the repository's own folders.\nexport const SCHEMA_FILE = \"node_modules/.cache/shiplane/schema.json\";\nconst VSCODE_SETTINGS = \".vscode/settings.json\";\n\n/** `cloudflare-pages` → `cloudflarePages`. */\nexport const factoryName = (name: string) =>\n name.replace(/-([a-z])/g, (_match, letter: string) => letter.toUpperCase());\n\n/** `fly` serving servers → `flyServerHosting`, the factory an official adapter is imported by. */\nexport const adapterFactory = ({ name, capability }: AnyDeliveryAdapter) =>\n `${factoryName(name)}${factoryName(`-${capability}`)}`;\n\n/** A module as a config writes it: its factory, its name when not its kind, its adapter. */\nexport interface ModuleEntry {\n /** `webApp`. */\n factory: string;\n /** The port it fills: `staticHosting`. */\n port: string;\n /** The adapter's factory: `cloudflarePagesStaticHosting`. */\n adapter: string;\n /** Set when another module already holds the kind's name. */\n name?: string;\n /** Where the adapter's factory is imported from. */\n from: string;\n}\n\nexport const moduleCall = ({ factory, port, adapter, name }: ModuleEntry) =>\n `${factory}({ ${name ? `name: \"${name}\", ` : \"\"}${port}: ${adapter}() })`;\n\n/**\n * The module an app ships with, given what the release already composes: the one holding this\n * provider for that kind, else a new one under the kind's name, or the provider's when that is taken.\n */\nexport const placeModule = (\n adapter: AnyDeliveryAdapter,\n modules: readonly ReleaseModule[],\n pkg: string = INSTALLED,\n): { name: string; entry?: ModuleEntry } => {\n // A plugin is `<cli>-<provider>`; the shell adapter is built into the CLI itself.\n const from = adapter.name === \"shell\" ? pkg : pluginPackage(adapter.name);\n const { kind, factory, port } = suggestedModule(adapter);\n const held = modules.find((module) => module.kind === kind && module.provider === adapter.name);\n if (held) return { name: held.name };\n const taken = modules.some((module) => module.name === kind);\n const name = taken ? `${kind}-${adapter.name}` : kind;\n return {\n name,\n entry: {\n factory,\n port,\n adapter: adapterFactory(adapter),\n from,\n ...(taken ? { name } : {}),\n },\n };\n};\n\n/** The name other repositories install the CLI under. */\nconst INSTALLED = \"shiplane\";\nconst NAMES = /shiplane/;\n\n/** Where a plugin is installed from. */\nexport const pluginPackage = (plugin: string) => `@shiplane/${plugin}`;\n\n/** What a written config imports the CLI as. */\nexport const releasePackage = (files: Files) => {\n const manifest = JSON.parse(files.read(\"package.json\") ?? \"{}\") as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n const deps = { ...manifest.dependencies, ...manifest.devDependencies };\n return \"shiplane\" in deps ? \"shiplane\" : INSTALLED;\n};\n\nconst importLine = (names: Iterable<string>, from: string) =>\n `import { ${[...new Set(names)].sort().join(\", \")} } from \"${from}\";`;\n\n/** Which adapter fills a flow port in the config: its factory and where it is imported from. */\nexport interface FlowChoice {\n factory: string;\n from: string;\n}\n\nexport type FlowPort = \"sourceControl\" | \"codeHost\" | \"ciPipeline\" | \"versioning\";\n\nexport const FLOW_PORTS: readonly FlowPort[] = [\n \"sourceControl\",\n \"codeHost\",\n \"ciPipeline\",\n \"versioning\",\n];\n\n/** The flow init writes when nothing else is chosen: git, GitHub, GitHub Actions, changesets. */\nexport const DEFAULT_FLOW: Record<FlowPort, FlowChoice> = {\n sourceControl: { factory: \"gitSourceControl\", from: pluginPackage(\"git\") },\n codeHost: { factory: \"gitHubCodeHost\", from: pluginPackage(\"github\") },\n ciPipeline: { factory: \"gitHubActionsCiPipeline\", from: pluginPackage(\"github\") },\n versioning: { factory: \"changesetsVersioning\", from: pluginPackage(\"changesets\") },\n};\n\n/** A root config with this flow (today's by default) and these modules, in the order given. */\nexport const renderConfig = (\n entries: readonly ModuleEntry[],\n pkg: string = INSTALLED,\n flow: Record<FlowPort, FlowChoice> = DEFAULT_FLOW,\n units?: readonly string[],\n) => {\n const byPlugin = new Map<string, string[]>();\n const add = (from: string, name: string) =>\n byPlugin.set(from, [...(byPlugin.get(from) ?? []), name]);\n FLOW_PORTS.forEach((port) => add(flow[port].from, flow[port].factory));\n const own = [\"defineRelease\", \"releaseFlow\", ...entries.map(({ factory }) => factory)];\n entries.forEach(({ adapter, from }) => {\n if (from === pkg) own.push(adapter);\n else add(from, adapter);\n });\n const local = (from: string) => from.startsWith(\".\");\n return [\n importLine(own, pkg),\n ...[...byPlugin]\n .filter(([from]) => !local(from))\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([from, names]) => importLine(names, from)),\n ...[...byPlugin]\n .filter(([from]) => local(from))\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([from, names]) => importLine(names, from)),\n \"\",\n \"export default defineRelease({\",\n \" flow: releaseFlow({\",\n ...FLOW_PORTS.map((port) => ` ${port}: ${flow[port].factory}(),`),\n \" }),\",\n ...(units ? [` units: [${units.map((unit) => JSON.stringify(unit)).join(\", \")}],`] : []),\n \" // What gets released, in this order. The first app is the repository's Latest release.\",\n \" modules: [\",\n ...entries.map((entry) => ` ${moduleCall(entry)},`),\n \" ],\",\n \"});\",\n \"\",\n ].join(\"\\n\");\n};\n\n/** The index of the bracket closing the one at `open`, or -1. */\nconst closing = (text: string, open: number) => {\n let depth = 0;\n for (let index = open; index < text.length; index += 1) {\n if (text[index] === \"[\") depth += 1;\n if (text[index] === \"]\") depth -= 1;\n if (depth === 0) return index;\n }\n return -1;\n};\n\n/** Adds a name to the CLI's import, under whichever name it has, or a new import when there is none. */\nconst withNamedImport = (config: string, name: string, pkg: string) => {\n const match = new RegExp(`import \\\\{([^}]*)\\\\} from \"(${NAMES.source})\";`).exec(config);\n if (!match) return `import { ${name} } from \"${pkg}\";\\n${config}`;\n const names =\n match[1]\n ?.split(\",\")\n .map((part) => part.trim())\n .filter(Boolean) ?? [];\n if (names.includes(name)) return config;\n const line = `import { ${[...names, name].sort().join(\", \")} } from \"${match[2] ?? pkg}\";`;\n return config.replace(match[0], line);\n};\n\n/** Adds a module and its imports to an existing config, or null when its shape is not ours. */\nexport const addToConfig = (\n config: string,\n entry: ModuleEntry,\n pkg: string = INSTALLED,\n): string | null => {\n const start = config.search(/modules:\\s*\\[/);\n if (start < 0) return null;\n const open = config.indexOf(\"[\", start);\n const close = closing(config, open);\n if (close < 0) return null;\n const call = moduleCall(entry);\n const inner = config.slice(open + 1, close);\n const trimmed = inner.trimEnd();\n const tail = inner.slice(trimmed.length);\n const comma = trimmed === \"\" || trimmed.endsWith(\",\") ? \"\" : \",\";\n const added = inner.includes(\"\\n\")\n ? `${trimmed}${comma}\\n ${call},${tail}`\n : `${trimmed}${comma}${trimmed === \"\" ? \"\" : \" \"}${call}${tail}`;\n const withCall = withNamedImport(\n `${config.slice(0, open + 1)}${added}${config.slice(close)}`,\n entry.factory,\n pkg,\n );\n // The built-in shell adapter joins the CLI's own import.\n if (entry.from === pkg) {\n return withNamedImport(withCall, entry.adapter, pkg);\n }\n const importLine = `import { ${entry.adapter} } from \"${entry.from}\";`;\n if (withCall.includes(importLine)) return withCall;\n const imports = [...withCall.matchAll(/^import [^;]*;$/gm)];\n const last = imports.at(-1);\n const at = last?.index === undefined ? 0 : last.index + last[0].length;\n return `${withCall.slice(0, at)}${at === 0 ? \"\" : \"\\n\"}${importLine}${at === 0 ? \"\\n\" : \"\"}${withCall.slice(at)}`;\n};\n\n/** A unit file naming its module, with the settings init found, and where it found them. */\nexport const renderUnit = (\n module: string,\n options: Record<string, unknown>,\n { reason, schemaLine }: { reason?: string; schemaLine?: string },\n) => {\n const doc = new Document({ module, ...options });\n doc.commentBefore = [\n ...(schemaLine ? [` yaml-language-server: $schema=${schemaLine}`] : []),\n ` Written by shiplane init. Every key: shiplane docs ${module}`,\n ...(reason ? [` Read from ${reason}`] : []),\n ].join(\"\\n\");\n return doc.toString();\n};\n\ninterface JsonProperty {\n description?: string;\n default?: unknown;\n properties?: Record<string, JsonProperty>;\n required?: string[];\n}\n\ninterface DocumentedKey {\n key: string;\n description: string;\n default: unknown;\n required: boolean;\n}\n\n/** A schema's keys as dotted paths: a nested object lists each of its own keys, not itself. */\nconst flatten = (\n properties: Record<string, JsonProperty>,\n required: readonly string[],\n prefix = \"\",\n): DocumentedKey[] =>\n Object.entries(properties).flatMap(([name, property]) =>\n property.properties\n ? flatten(property.properties, property.required ?? [], `${prefix}${name}.`)\n : [\n {\n key: `${prefix}${name}`,\n description: property.description ?? \"\",\n default: property.default,\n required: required.includes(name),\n },\n ],\n );\n\n/** Every key a unit file takes, nested ones as `build.command`, for `shiplane docs`. */\nexport const documentedKeys = (settings: z.ZodObject): DocumentedKey[] => {\n const schema = z.toJSONSchema(settings, { io: \"input\", unrepresentable: \"any\" }) as JsonProperty;\n return flatten(schema.properties ?? {}, schema.required ?? []);\n};\n\n/** Each key a schema takes, with its description and default, from its JSON Schema. */\nexport const settingsKeys = (settings: z.ZodObject) => {\n const schema = z.toJSONSchema(settings, { io: \"input\", unrepresentable: \"any\" }) as {\n properties?: Record<string, JsonProperty>;\n required?: string[];\n };\n return Object.entries(schema.properties ?? {}).map(([key, property]) => ({\n key,\n description: property.description ?? \"\",\n default: property.default,\n required: schema.required?.includes(key) ?? false,\n }));\n};\n\n/** A unit file with only its module set and every other key commented, described. */\nexport const renderBlankUnit = (module: string, settings: z.ZodObject, schemaLine?: string) =>\n [\n ...(schemaLine ? [`# yaml-language-server: $schema=${schemaLine}`] : []),\n `# Written by shiplane init --blank. Uncomment and fill what applies.`,\n `module: ${module}`,\n ...settingsKeys(settings).flatMap(({ key, description, default: fallback, required }) => [\n \"\",\n `# ${description}${required ? \" (required)\" : \"\"}`,\n `# ${key}:${fallback === undefined ? \"\" : ` ${JSON.stringify(fallback)}`}`,\n ]),\n \"\",\n ].join(\"\\n\");\n\n/** The schema a unit file's editor reads, relative to that unit file. */\nexport const schemaLineFor = (dir: string) => path.posix.relative(dir, SCHEMA_FILE) || SCHEMA_FILE;\n\n/** The JSON Schema for every unit file: the module an app names picks the keys it takes. */\nexport const schemaText = (modules: readonly ReleaseModule[]) =>\n `${JSON.stringify(unitJsonSchema(modules), null, 2)}\\n`;\n\n/**\n * Writes the editor schema when it no longer matches the composed modules. It is generated, never\n * committed: every command keeps it current. True when it wrote.\n */\nexport const refreshEditorSchema = (files: Files, release: Release) => {\n const text = schemaText(release.modules);\n if (files.read(SCHEMA_FILE) === text) return false;\n files.write(SCHEMA_FILE, text);\n return true;\n};\n\n/** Maps every unit file to the schema once, keeping a settings file's comments as they are. */\nexport const withEditorSchema = (settings: string | null): string | null => {\n const entry = `\"yaml.schemas\": { \"./${SCHEMA_FILE}\": \"**/${UNIT_FILE}\" }`;\n if (settings === null) return `{\\n ${entry}\\n}\\n`;\n if (settings.includes('\"yaml.schemas\"')) return null;\n const open = settings.indexOf(\"{\");\n if (open < 0) return null;\n return `${settings.slice(0, open + 1)}\\n ${entry},${settings.slice(open + 1)}`;\n};\n\nexport const editorSettingsFile = VSCODE_SETTINGS;\n\n/** A folder as adapters see it when recognising what ships from it. */\nexport const folderView = (files: Files, dir: string): FolderView => ({\n dir,\n name: path.posix.basename(dir),\n files: files.list(dir),\n has: (file) => files.exists(path.posix.join(dir, file)),\n read: (file) => files.read(path.posix.join(dir, file)),\n});\n\n/** The repository's short name: its package name without scope, else its folder's. */\nexport const repositoryName = (files: Files, root: string) => {\n const parsed = z\n .object({ name: z.string() })\n .safeParse(JSON.parse(files.read(\"package.json\") ?? \"{}\"));\n return parsed.success ? parsed.data.name.replace(/^@[^/]+\\//, \"\") : path.basename(root);\n};\n","import path from \"node:path\";\n\nimport type { Requirement } from \"../ports/delivery.port\";\nimport type { SetupContext } from \"./setupContext\";\nimport { UNIT_FILE } from \"./config/readUnitFile\";\nimport { releaseOrder } from \"./releaseOrder\";\nimport { checkStatus, requirementsOf } from \"./requirements\";\nimport { paint } from \"./say\";\nimport { refreshEditorSchema } from \"./setupFiles\";\nimport { commandLine } from \"./targets\";\n\n/**\n * `shiplane doctor`: the config as written, the editor schema refreshed, the release order, a warning\n * for each module no app names, then every tool and sign-in the flow, modules and features need, each\n * failure with the command that fixes it, offered to run.\n */\nexport const doctor = async (context: SetupContext): Promise<boolean> => {\n const { output, files, shell, prompter, root } = context;\n output.line();\n output.line(`${paint(\"cyan\", \"◆\")} ${paint(\"bold\", \"shiplane doctor\")}`);\n const release = await context.load();\n if (release.problems.length > 0) {\n release.problems.forEach(({ file, line, message, hint }) => {\n output.line(\n `${paint(\"red\", \"✗\")} ${paint(\"bold\", line === undefined ? file : `${file}:${line}`)} ${message}`,\n );\n if (hint) output.line(` ${paint(\"dim\", hint)}`);\n });\n return false;\n }\n refreshEditorSchema(files, release);\n const appsOf = (name: string) => release.units.filter(({ module }) => module === name);\n if (release.units.length > 0) {\n output.line(`${paint(\"dim\", \"│\")} Order ${paint(\"dim\", releaseOrder(release.units))}`);\n }\n release.modules\n .filter((module) => appsOf(module.name).length === 0)\n .forEach(({ name }) =>\n output.line(\n `${paint(\"dim\", \"│\")} ${paint(\"yellow\", \"!\")} ${name} ${paint(\"dim\", `no app names it: module: ${name} in a ${UNIT_FILE}`)}`,\n ),\n );\n (release.renames ?? []).forEach(({ from, to }) =>\n output.line(\n `${paint(\"dim\", \"│\")} ${paint(\"yellow\", \"!\")} ${paint(\"dim\", `rename ${from} to ${to}: the old name still works for now`)}`,\n ),\n );\n const unique = requirementsOf(release);\n const failing: Requirement[] = [];\n const missing = new Set<string>();\n for (const requirement of unique) {\n const { check } = requirement;\n const status = await checkStatus(shell, root, requirement);\n if (status === 0) {\n output.line(`${paint(\"dim\", \"│\")} ${paint(\"green\", \"✓\")} ${requirement.label}`);\n } else {\n failing.push(requirement);\n if (status === 127) missing.add(check.command);\n const fix =\n status === 127\n ? `not installed: ${check.command}`\n : requirement.fix\n ? `fix: ${commandLine(requirement.fix)}`\n : \"not available here\";\n output.line(\n `${paint(\"dim\", \"│\")} ${paint(\"red\", \"✗\")} ${requirement.label} ${paint(\"dim\", fix)}`,\n );\n }\n }\n for (const { fix } of failing) {\n if (!fix || !prompter.interactive || missing.has(fix.command)) continue;\n if (await prompter.confirm(`Run ${commandLine(fix)} now?`)) {\n await shell.attach(fix.command, fix.args, {\n cwd: path.join(root, fix.cwd ?? \"\"),\n env: fix.env,\n });\n }\n }\n output.line(\n `${paint(\"dim\", \"└\")} Next: ${paint(\"cyan\", failing.length > 0 ? \"shiplane doctor\" : \"shiplane status\")}`,\n );\n return failing.length === 0;\n};\n","import path from \"node:path\";\n\nimport type { ReleaseModule } from \"../modules/module\";\nimport type { AnyDeliveryAdapter } from \"../modules/suggest\";\nimport type { Detection, FolderView } from \"../ports/delivery.port\";\nimport type { SetupContext } from \"./setupContext\";\nimport type { ModuleEntry } from \"./setupFiles\";\nimport { moduleFor } from \"../modules/suggest\";\nimport { UNIT_FILE, UNIT_FILES } from \"./config/readUnitFile\";\nimport { isRecord } from \"./config/values\";\nimport { expandPatterns, workspacePatterns } from \"./config/workspaceFolders\";\nimport { doctor } from \"./doctor\";\nimport { paint } from \"./say\";\nimport {\n addToConfig,\n CONFIG_FILE,\n editorSettingsFile,\n folderView,\n placeModule,\n releasePackage,\n renderBlankUnit,\n renderConfig,\n renderUnit,\n repositoryName,\n SCHEMA_FILE,\n schemaLineFor,\n schemaText,\n withEditorSchema,\n} from \"./setupFiles\";\n\ninterface Candidate {\n folder: FolderView;\n /** The adapter that recognised it best: found, then likely, then possible. */\n guess: { adapter: AnyDeliveryAdapter; detection: Detection } | null;\n}\n\ninterface Placed {\n folder: FolderView;\n adapter: AnyDeliveryAdapter;\n options: Record<string, unknown>;\n reason?: string;\n}\n\ninterface Write {\n file: string;\n text: string;\n created: boolean;\n}\n\nconst bar = paint(\"dim\", \"│\");\n\n/** Sets `key`, dotted, in a nested object. */\nconst setAt = (target: Record<string, unknown>, key: string, value: unknown) => {\n const [head = \"\", ...rest] = key.split(\".\");\n if (rest.length === 0) {\n target[head] = value;\n return;\n }\n const child = isRecord(target[head]) ? target[head] : {};\n target[head] = child;\n setAt(child, rest.join(\".\"), value);\n};\n\n/** Each workspace folder with a manifest and no unit file yet, with what adapters recognise in it. */\nexport const scanFolders = (\n context: SetupContext,\n adapters: readonly AnyDeliveryAdapter[],\n): Candidate[] =>\n expandPatterns(context.root, workspacePatterns(context.root))\n .filter((dir) => dir !== \".\" && context.files.exists(path.posix.join(dir, \"package.json\")))\n .filter((dir) => !UNIT_FILES.some((name) => context.files.exists(path.posix.join(dir, name))))\n .map((dir) => {\n const folder = folderView(context.files, dir);\n const detections = adapters.flatMap((adapter) => {\n const detection = adapter.detect?.(folder);\n return detection ? [{ adapter, detection }] : [];\n });\n const strongest = ([\"found\", \"likely\", \"possible\"] as const)\n .map((certainty) => detections.find(({ detection }) => detection.certainty === certainty))\n .find(Boolean);\n const guess = strongest ?? null;\n return { folder, guess };\n });\n\n/** The options a placed folder needs that its folder did not say, asked or taken as suggested. */\nexport const askOptions = async (\n context: SetupContext,\n folder: FolderView,\n adapter: AnyDeliveryAdapter,\n found: Record<string, unknown>,\n yes: boolean,\n) => {\n const options = structuredClone(found);\n const repository = repositoryName(context.files, context.root);\n for (const question of adapter.questions?.(folder, options, repository) ?? []) {\n const answer = yes\n ? (question.initial ?? null)\n : await context.prompter.text(`${folder.dir} · ${question.message}`, question.initial);\n if (answer !== null && answer !== \"\") setAt(options, question.key, answer);\n }\n return options;\n};\n\nconst candidateLine = ({ folder, guess }: Candidate, width: number) => {\n const target =\n guess?.detection.certainty === \"found\"\n ? paint(\"green\", guess.adapter.name)\n : paint(\"yellow\", \"?\");\n return `${folder.dir.padEnd(width)}${target.padEnd(18)}${paint(\"dim\", guess?.detection.reason ?? \"\")}`;\n};\n\n/** Whether the person writes, after seeing the list, the diff if asked. */\nconst review = async (context: SetupContext, writes: Write[], yes: boolean) => {\n const { output, prompter } = context;\n output.line(`${paint(\"cyan\", \"◆\")} ${paint(\"bold\", \"Write these files?\")}`);\n writes.forEach(({ file, created }) =>\n output.line(`${bar} ${created ? paint(\"green\", \"+\") : paint(\"yellow\", \"~\")} ${file}`),\n );\n if (yes) return true;\n for (;;) {\n const answer = await prompter.select(\n \"Write these files?\",\n [\n { value: \"write\", label: \"Write\" },\n { value: \"diff\", label: \"Show the files\" },\n { value: \"cancel\", label: \"Cancel, write nothing\" },\n ],\n \"write\",\n );\n if (answer !== \"diff\") return answer === \"write\";\n writes.forEach(({ file, text }) => {\n output.line();\n output.line(paint(\"bold\", file));\n text.split(\"\\n\").forEach((line) => output.line(` ${line}`));\n });\n }\n};\n\n/**\n * `shiplane init`: finds every workspace folder, guesses how each ships from what it holds, asks only\n * what it cannot tell, shows every file, writes them, then runs doctor. Run again, it offers the\n * folders added since and never rewrites a unit file. `--yes` takes every guess, `--blank` writes\n * commented templates.\n */\nexport const initRelease = async (\n context: SetupContext,\n { yes, blank }: { yes: boolean; blank: boolean },\n): Promise<boolean> => {\n const { output, prompter, files } = context;\n const existing = files.exists(CONFIG_FILE) ? await context.load() : null;\n const adapters = context.adapters;\n const candidates = scanFolders(context, adapters);\n output.line(`${paint(\"dim\", \"┌\")} ${paint(\"bold\", \"shiplane init\")}`);\n output.line(bar);\n output.line(\n `${paint(\"green\", \"◇\")} Workspace ${paint(\"dim\", workspacePatterns(context.root).join(\", \"))}`,\n );\n output.line(bar);\n if (existing) {\n output.line(`${paint(\"cyan\", \"◆\")} ${paint(\"bold\", \"Since the last init\")}`);\n candidates\n .filter(({ guess }) => guess)\n .forEach(({ folder, guess }) =>\n output.line(\n `${bar} ${paint(\"green\", \"+\")} ${folder.dir.padEnd(14)}${paint(\"dim\", `new folder, ${guess?.detection.reason ?? \"\"}`)}`,\n ),\n );\n output.line(\n `${bar} ${paint(\"dim\", \"=\")} ${`${existing.units.length} folders`.padEnd(14)}${paint(\"dim\", \"unchanged, your edits kept\")}`,\n );\n output.line(bar);\n }\n const placeable = candidates.filter(({ guess }) => guess !== null);\n const width = Math.max(14, ...placeable.map(({ folder }) => folder.dir.length)) + 2;\n placeable.forEach((candidate) => output.line(`${bar} ${candidateLine(candidate, width)}`));\n const unplaced = candidates.length - placeable.length;\n if (unplaced > 0) {\n const folders = `${unplaced} folder${unplaced === 1 ? \"\" : \"s\"}`;\n output.line(\n `${bar} ${paint(\"dim\", `◻ ${folders} with nothing to ship them, versioned only (shiplane add <folder> ships one)`)}`,\n );\n }\n output.line(bar);\n const offered = placeable;\n const pickedDirs = yes\n ? offered.map(({ folder }) => folder.dir)\n : await prompter.multiselect(\n \"Which folders ship somewhere?\",\n offered.map(({ folder, guess }) => ({\n value: folder.dir,\n label: folder.dir,\n hint: guess ? `${guess.adapter.name} · ${guess.detection.reason}` : \"\",\n })),\n offered.map(({ folder }) => folder.dir),\n );\n if (pickedDirs === null) {\n output.line(paint(\"dim\", \"Nothing written.\"));\n return true;\n }\n const placed: Placed[] = [];\n for (const candidate of candidates.filter(({ folder }) => pickedDirs.includes(folder.dir))) {\n const { folder, guess } = candidate;\n const sure = guess?.detection.certainty === \"found\";\n const name =\n sure || yes\n ? (guess?.adapter.name ?? \"skip\")\n : await prompter.select(\n `How does ${folder.dir} ship?`,\n [\n ...adapters.map((adapter) => ({\n value: adapter.name,\n label: adapter.name,\n hint:\n adapter.name === guess?.adapter.name\n ? `${guess.detection.reason} (recommended)`\n : \"\",\n })),\n { value: \"skip\", label: \"skip\", hint: \"versioned, never shipped\" },\n ],\n guess?.adapter.name,\n );\n const adapter = adapters.find((candidateAdapter) => candidateAdapter.name === name);\n if (!adapter) continue;\n const found = guess?.adapter === adapter ? guess.detection.options : {};\n const options = blank ? {} : await askOptions(context, folder, adapter, found, yes);\n placed.push({\n folder,\n adapter,\n options,\n reason: guess?.adapter === adapter ? guess.detection.reason : undefined,\n });\n }\n const extras = [\n ...(files.exists(\".vscode\")\n ? [{ value: \"editor\", label: \"editor autocompletion\", hint: editorSettingsFile }]\n : []),\n ];\n const chosen = yes\n ? extras.map(({ value }) => value)\n : extras.length === 0\n ? []\n : await prompter.multiselect(\n \"Also set up\",\n extras,\n extras.map(({ value }) => value),\n );\n const editor = (chosen ?? []).includes(\"editor\");\n const modules: ReleaseModule[] = [...(existing?.modules ?? [])];\n const entries: ModuleEntry[] = [];\n const pkg = releasePackage(files);\n const named = placed.map((entry) => {\n const { name, entry: added } = placeModule(entry.adapter, modules, pkg);\n if (added) {\n entries.push(added);\n modules.push(moduleFor(entry.adapter, name));\n }\n return { ...entry, module: name };\n });\n const writes: Write[] = [];\n if (!existing) {\n writes.push({ file: CONFIG_FILE, text: renderConfig(entries, pkg), created: true });\n } else {\n let config = files.read(CONFIG_FILE) ?? \"\";\n for (const entry of entries) config = addToConfig(config, entry, pkg) ?? config;\n if (config !== files.read(CONFIG_FILE))\n writes.push({ file: CONFIG_FILE, text: config, created: false });\n }\n named.forEach(({ folder, adapter, module, options, reason }) => {\n const schemaLine = editor ? undefined : schemaLineFor(folder.dir);\n writes.push({\n file: path.posix.join(folder.dir, UNIT_FILE),\n text: blank\n ? renderBlankUnit(module, adapter.settings, schemaLine)\n : renderUnit(module, options, { reason, schemaLine }),\n created: true,\n });\n });\n writes.push({\n file: SCHEMA_FILE,\n text: schemaText(modules),\n created: !files.exists(SCHEMA_FILE),\n });\n if (editor) {\n const current = files.read(editorSettingsFile);\n const settings = withEditorSchema(current);\n if (current?.includes(`./${SCHEMA_FILE}`)) {\n // Mapped already, by an earlier init.\n } else if (settings)\n writes.push({\n file: editorSettingsFile,\n text: settings,\n created: !files.exists(editorSettingsFile),\n });\n else\n output.line(\n `${bar} ${paint(\"dim\", `${editorSettingsFile} already maps yaml.schemas: add ./${SCHEMA_FILE} for **/${UNIT_FILE}`)}`,\n );\n }\n if (!(await review(context, writes, yes))) {\n output.line(paint(\"dim\", \"Nothing written.\"));\n return true;\n }\n writes.forEach(({ file, text }) => files.write(file, text));\n output.line(\n `${paint(\"green\", \"◇\")} Wrote ${writes.length} file${writes.length === 1 ? \"\" : \"s\"}`,\n );\n return doctor(context);\n};\n","import path from \"node:path\";\n\nimport type { SetupContext } from \"./setupContext\";\nimport { moduleFor } from \"../modules/suggest\";\nimport { UNIT_FILE } from \"./config/readUnitFile\";\nimport { askOptions, scanFolders } from \"./initRelease\";\nimport { paint } from \"./say\";\nimport {\n addToConfig,\n CONFIG_FILE,\n moduleCall,\n placeModule,\n releasePackage,\n renderUnit,\n SCHEMA_FILE,\n schemaText,\n} from \"./setupFiles\";\n\n/** `shiplane add <folder>`: init's questions for one folder, its unit file written. */\nexport const addUnit = async (context: SetupContext, dir: string): Promise<boolean> => {\n const { output, prompter, files } = context;\n const folderDir = path.posix.normalize(dir).replace(/\\/$/, \"\");\n const candidate = scanFolders(context, context.adapters).find(\n ({ folder }) => folder.dir === folderDir,\n );\n if (!candidate) {\n output.line(\n `${paint(\"red\", \"✗\")} ${folderDir} is not a workspace folder without a ${UNIT_FILE}`,\n );\n return false;\n }\n const { folder, guess } = candidate;\n const name =\n guess?.detection.certainty === \"found\"\n ? guess.adapter.name\n : await prompter.select(\n `How does ${folder.dir} ship?`,\n context.adapters.map((adapter) => ({\n value: adapter.name,\n label: adapter.name,\n hint:\n adapter.name === guess?.adapter.name ? `${guess.detection.reason} (recommended)` : \"\",\n })),\n guess?.adapter.name,\n );\n const adapter = context.adapters.find((offered) => offered.name === name);\n if (!adapter) return false;\n const found = guess?.adapter === adapter ? guess.detection.options : {};\n const options = await askOptions(context, folder, adapter, found, false);\n const file = path.posix.join(folder.dir, UNIT_FILE);\n if (!(await prompter.confirm(`Write ${file}?`))) {\n output.line(paint(\"dim\", \"Nothing written.\"));\n return true;\n }\n const release = await context.load();\n const pkg = releasePackage(files);\n const placed = placeModule(adapter, release.modules, pkg);\n files.write(file, renderUnit(placed.name, options, { reason: guess?.detection.reason }));\n if (placed.entry) {\n const config = addToConfig(files.read(CONFIG_FILE) ?? \"\", placed.entry, pkg);\n if (config) files.write(CONFIG_FILE, config);\n else\n output.line(\n `${paint(\"yellow\", \"!\")} add ${moduleCall(placed.entry)} to the modules in ${CONFIG_FILE}`,\n );\n }\n const modules = placed.entry\n ? [...release.modules, moduleFor(adapter, placed.name)]\n : release.modules;\n files.write(SCHEMA_FILE, schemaText(modules));\n output.line(`${paint(\"green\", \"◇\")} Wrote ${file}`);\n return true;\n};\n\n/** `shiplane remove <unit>`: its unit file goes; changesets still version it. */\nexport const removeUnit = async (context: SetupContext, name: string): Promise<boolean> => {\n const { output, prompter, files } = context;\n const unit = (await context.load()).units.find((candidate) => candidate.name === name);\n if (!unit) {\n output.line(`${paint(\"red\", \"✗\")} no unit named \"${name}\"`);\n return false;\n }\n if (!(await prompter.confirm(`Stop shipping ${name}? It stays versioned.`))) return true;\n files.remove(unit.file);\n output.line(`${paint(\"green\", \"◇\")} Removed ${unit.file}`);\n return true;\n};\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\n\nimport type { ManifestReader } from \"../../ports/manifest.port\";\n\nconst PackageSchema = z.object({ name: z.string(), version: z.string() });\n\nexport const packageJsonManifest: ManifestReader = {\n read: (root, dir) => {\n const file = path.join(root, dir, \"package.json\");\n if (!fs.existsSync(file)) return null;\n const parsed = PackageSchema.safeParse(JSON.parse(fs.readFileSync(file, \"utf8\")));\n return parsed.success ? parsed.data : null;\n },\n};\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { createJiti } from \"jiti\";\n\nimport type { DisplayChoice } from \"../../domain/display\";\nimport type { ReleaseUnit } from \"../../domain/unit\";\nimport type { Feature, ReleaseFlow, ReleaseModule } from \"../../modules/module\";\nimport type { ServiceAdapter } from \"../../ports/adapter.port\";\nimport type { ManifestReader } from \"../../ports/manifest.port\";\nimport type { ConfigProblem } from \"./problem\";\nimport type { UnitFile } from \"./readUnitFile\";\nimport { packageJsonManifest } from \"../../adapters/manifest/package-json-manifest.adapter\";\nimport { DEFAULT_TAG_FORMAT, TAG_FORMATS, tagFormatNamed } from \"../../domain/tags\";\nimport { releaseFlow } from \"../releaseFlow\";\nimport { sortProblems } from \"./problem\";\nimport { readUnitFile, UNIT_FILE, UNIT_FILES } from \"./readUnitFile\";\nimport { isRecord, referencesIn, valueAt } from \"./values\";\nimport { expandPatterns, workspacePatterns } from \"./workspaceFolders\";\n\nconst EXTENSIONS = [\"ts\", \"mts\", \"js\", \"mjs\"];\n\n/** The config's names, the one from before shiplane last: still read, listed to rename. */\nexport const CONFIG_FILES = [\n ...EXTENSIONS.map((extension) => `shiplane.config.${extension}`),\n ...EXTENSIONS.map((extension) => `release.config.${extension}`),\n];\n\n/** A file still under its name from before shiplane, and the name it takes. */\nexport interface Rename {\n from: string;\n to: string;\n}\n\nconst renameOf = (file: string): Rename | null =>\n /(^|\\/)release\\.(config|unit)\\./.test(file)\n ? { from: file, to: file.replace(/(^|\\/)release\\./, \"$1shiplane.\") }\n : null;\n\n/** The release as composed: the flow, the modules in release order, the features, then the apps. */\nexport interface Release {\n root: string;\n flow: ReleaseFlow;\n /** What gets released, in release order. */\n modules: ReleaseModule[];\n /** What happens around a release, in the order they run. */\n features: Feature[];\n /** In release order: by module, then by name inside a module. The first is the Latest release. */\n units: ReleaseUnit[];\n problems: ConfigProblem[];\n /** How a tag names a version, such as `{name}@{version}`. */\n tagFormat: string;\n /** Commits no changeset names release their unit, with a changelog from them. */\n releasesCommits?: boolean;\n /** How much the release says while it runs, as the config asks. */\n display?: DisplayChoice;\n /** Files still under their name from before shiplane. */\n renames?: Rename[];\n}\n\ntype Composed = Pick<\n Release,\n \"flow\" | \"modules\" | \"features\" | \"display\" | \"tagFormat\" | \"releasesCommits\"\n> & {\n units?: string[];\n};\n\nexport interface LoadOptions {\n /** Where `shiplane` resolves from inside the config; by default, this very package. */\n aliases?: Record<string, string>;\n manifests?: ManifestReader;\n}\n\nexport const findConfig = (root: string) =>\n CONFIG_FILES.map((file) => path.join(root, file)).find((file) => fs.existsSync(file));\n\n// The name a config imports the CLI under.\nconst NAMES = [\"shiplane\"];\n\nconst resolves = (specifier: string) => {\n try {\n return fileURLToPath(import.meta.resolve(specifier));\n } catch {\n return null;\n }\n};\n\n// One alias per entry: a bare \"shiplane\" alias would also rewrite \"shiplane/fly\" into a path\n// under index.js.\nconst selfAliases = (): Record<string, string> => {\n const own = NAMES.find((name) => resolves(name) !== null);\n if (!own) return {};\n return Object.fromEntries(\n [\"\", \"/plugin\", \"/testing\"].flatMap((sub) => {\n const target = resolves(`${own}${sub}`);\n return target ? NAMES.map((name) => [`${name}${sub}`, target]) : [];\n }),\n );\n};\n\n/** A port no flow fills yet: a release that never loaded has nothing to run on. */\nconst unset = <Port>(port: string): ServiceAdapter<Port> => ({\n name: \"unset\",\n create: () => {\n throw new Error(`no ${port} adapter: shiplane.config.ts sets none`);\n },\n});\n\n/** The flow of a release that did not load: every port unset. */\nconst unsetFlow = () =>\n releaseFlow({\n sourceControl: unset(\"sourceControl\"),\n codeHost: unset(\"codeHost\"),\n ciPipeline: unset(\"ciPipeline\"),\n versioning: unset(\"versioning\"),\n });\n\nconst FLOW_MISSING = [\n \"flow is missing: give it one, such as\",\n \"flow: releaseFlow({ sourceControl: gitSourceControl(), codeHost: gitHubCodeHost(),\",\n \"ciPipeline: gitHubActionsCiPipeline(), versioning: changesetsVersioning() }),\",\n \"from the shiplane-git, shiplane-github and shiplane-changesets plugins\",\n].join(\" \");\n\nconst typed = (value: unknown, type: string) =>\n isRecord(value) && value.type === type && typeof value.name === \"string\";\n\nconst isFlow = (value: unknown): value is ReleaseFlow => isRecord(value) && value.type === \"flow\";\nconst isModule = (value: unknown): value is ReleaseModule => typed(value, \"module\");\nconst isFeature = (value: unknown): value is Feature => typed(value, \"feature\");\n\nconst listOf = <Item>(\n value: unknown,\n key: string,\n is: (candidate: unknown) => candidate is Item,\n example: string,\n): Item[] => {\n if (value === undefined) return [];\n if (!Array.isArray(value)) throw new Error(`${key} is not a list, such as ${key}: [${example}]`);\n return value.map((item: unknown, index) => {\n if (!is(item)) throw new Error(`${key}[${index}] is not one of its ${key}, such as ${example}`);\n return item;\n });\n};\n\nconst LEFTOVERS: Record<string, string> = {\n plugins:\n \"plugins is gone: defineRelease takes flow, modules and features, such as modules: [backendService({ serverHosting: flyServerHosting() })]\",\n latest: \"latest is gone: the first app of the first module is the Latest release\",\n};\n\n/** The modules, their names unique and their adapters' settings free of `module`. */\nconst checkModules = (modules: readonly ReleaseModule[], features: readonly Feature[]) => {\n const names = [...modules, ...features].map(({ name }) => name);\n names.forEach((name, index) => {\n if (names.indexOf(name) !== index) {\n throw new Error(\n `two modules are named \"${name}\": give one its own, such as { name: \"${name}-2\", ... }`,\n );\n }\n });\n const clash = modules.find(({ settings }) => \"module\" in settings.shape);\n if (clash) {\n throw new Error(\n `\"module\" is reserved for the unit file's module, yet ${clash.name}'s adapter takes it`,\n );\n }\n};\n\nconst tagFormatOf = (tag: unknown) => {\n if (tag === undefined) return DEFAULT_TAG_FORMAT;\n const format = typeof tag === \"string\" ? tagFormatNamed(tag) : undefined;\n if (!format?.includes(\"{version}\")) {\n const names = Object.keys(TAG_FORMATS)\n .map((name) => `\"${name}\"`)\n .join(\", \");\n throw new Error(`tag is one of ${names}, or a format naming the version, such as \"v{version}\"`);\n }\n return format;\n};\n\nconst releasesCommitsOf = (choice: unknown) => {\n if (choice === undefined || choice === \"ignore\") return false;\n if (choice === \"release\") return true;\n throw new Error('commitsWithoutChangeset is \"release\" or \"ignore\"');\n};\n\nconst readConfig = async (file: string, aliases: Record<string, string>): Promise<Composed> => {\n const jiti = createJiti(import.meta.url, { alias: aliases, moduleCache: false, fsCache: false });\n const loaded: unknown = await jiti.import(file, { default: true });\n if (!isRecord(loaded)) throw new Error(\"its default export is not defineRelease({ modules })\");\n for (const [key, message] of Object.entries(LEFTOVERS)) {\n if (key in loaded) throw new Error(message);\n }\n if (loaded.flow === undefined) throw new Error(FLOW_MISSING);\n if (!isFlow(loaded.flow)) {\n throw new Error(\"flow is not a release flow, such as flow: releaseFlow({ ... })\");\n }\n const modules = listOf(loaded.modules, \"modules\", isModule, \"webApp({ ... })\");\n const features = listOf(loaded.features, \"features\", isFeature, \"releaseComments({ ... })\");\n checkModules(modules, features);\n const units = Array.isArray(loaded.units)\n ? loaded.units.filter((unit): unit is string => typeof unit === \"string\")\n : undefined;\n const display = isRecord(loaded.display) ? loaded.display : {};\n const flag = (value: unknown) => (typeof value === \"boolean\" ? value : undefined);\n return {\n flow: loaded.flow,\n modules,\n features,\n units,\n display: { verbose: flag(display.verbose), mascot: mascotOf(display.mascot) },\n tagFormat: tagFormatOf(loaded.tag),\n releasesCommits: releasesCommitsOf(loaded.commitsWithoutChangeset),\n };\n};\n\n/** A config's mascot: true, false, frames per mood, or a function; anything else is ignored. */\nconst mascotOf = (value: unknown): DisplayChoice[\"mascot\"] => {\n if (typeof value === \"boolean\" || typeof value === \"function\")\n return value as DisplayChoice[\"mascot\"];\n if (!isRecord(value)) return undefined;\n const frames = Object.entries(value).filter(\n ([, list]) => Array.isArray(list) && list.every((frame) => typeof frame === \"string\"),\n );\n return frames.length > 0 ? Object.fromEntries(frames) : undefined;\n};\n\ninterface Read {\n unit: ReleaseUnit;\n file: UnitFile;\n}\n\n/** Apps in release order: by module as the config lists them, then by name. */\nconst inReleaseOrder = (read: readonly Read[], modules: readonly ReleaseModule[]) => {\n const rank = (unit: ReleaseUnit) => modules.findIndex(({ name }) => name === unit.module);\n return [...read].sort(\n (left, right) =>\n rank(left.unit) - rank(right.unit) || left.unit.name.localeCompare(right.unit.name),\n );\n};\n\nconst referenceProblems = ({ unit, file }: Read, ordered: readonly Read[]): ConfigProblem[] =>\n referencesIn(unit.options).flatMap(({ unit: name, key, at }) => {\n const other = ordered.find((candidate) => candidate.unit.name === name)?.unit;\n const line = file.lineOf(at);\n if (!other) {\n return [{ file: unit.file, line, message: `\"${name}\" has no ${UNIT_FILE} to read from` }];\n }\n if (valueAt(other.options, key.split(\".\")) === undefined) {\n return [{ file: unit.file, line, message: `\"${name}\" has no \"${key}\" in ${other.file}` }];\n }\n const position = (target: ReleaseUnit) =>\n ordered.findIndex((candidate) => candidate.unit === target);\n if (other !== unit && position(other) > position(unit)) {\n return [\n {\n file: unit.file,\n line,\n message: `\"${unit.name}\" reads ${name}.${key}, which is released after it`,\n hint:\n other.module === unit.module\n ? `${unit.name} and ${name} share ${unit.module}: give ${name} a module of its own, listed first`\n : `move ${other.module} before ${unit.module} in the modules of shiplane.config.ts`,\n },\n ];\n }\n return [];\n });\n\n/**\n * The release as written: what `shiplane.config.ts` composes, and one app per folder that holds a\n * `shiplane.unit.yml`, in release order. Every problem is collected, never thrown.\n */\nexport const loadRelease = async (root: string, options: LoadOptions = {}): Promise<Release> => {\n const empty = (problems: ConfigProblem[]): Release => ({\n root,\n flow: unsetFlow(),\n tagFormat: DEFAULT_TAG_FORMAT,\n modules: [],\n features: [],\n units: [],\n problems,\n });\n const configFile = findConfig(root);\n if (!configFile) {\n return empty([\n {\n file: \"shiplane.config.ts\",\n message: \"No shiplane.config.ts in this repository\",\n hint: \"shiplane init writes it, with a shiplane.unit.yml next to each app\",\n },\n ]);\n }\n let config: Composed;\n try {\n config = await readConfig(configFile, options.aliases ?? selfAliases());\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n return empty([\n { file: path.basename(configFile), message: `it did not load: ${reason.split(\"\\n\")[0]}` },\n ]);\n }\n const manifests = options.manifests ?? packageJsonManifest;\n const problems: ConfigProblem[] = [];\n const features = config.features.map(({ name }) => name);\n const read: Read[] = expandPatterns(root, config.units ?? workspacePatterns(root)).flatMap(\n (dir) => {\n const relative = UNIT_FILES.map((name) => path.posix.join(dir, name)).find((file) =>\n fs.existsSync(path.join(root, file)),\n );\n if (!relative) return [];\n const result = readUnitFile(\n relative,\n fs.readFileSync(path.join(root, relative), \"utf8\"),\n config.modules,\n features,\n );\n problems.push(...result.problems);\n const manifest = manifests.read(root, dir);\n if (!manifest) {\n problems.push({\n file: relative,\n message: \"no package.json next to it to read its name and version\",\n });\n }\n if (!result.unit || !manifest) return [];\n const unit: ReleaseUnit = {\n name: dir === \".\" ? manifest.name.replace(/^@[^/]+\\//, \"\") : path.posix.basename(dir),\n dir,\n file: relative,\n packageName: manifest.name,\n version: manifest.version,\n module: result.unit.module,\n ...(result.unit.buildCommand ? { buildCommand: result.unit.buildCommand } : {}),\n options: result.unit.options,\n after: [],\n };\n return [{ unit, file: result.unit }];\n },\n );\n\n const ordered = inReleaseOrder(read, config.modules);\n ordered.forEach((entry, index) => {\n const twin = ordered.findIndex(({ unit }) => unit.name === entry.unit.name);\n if (twin !== index) {\n problems.push({\n file: entry.unit.file,\n message: `two folders are both named \"${entry.unit.name}\"`,\n hint: `rename one of ${ordered[twin]?.unit.dir} and ${entry.unit.dir}`,\n });\n }\n problems.push(...referenceProblems(entry, ordered));\n entry.unit.after = [\n ...new Set(referencesIn(entry.unit.options).map(({ unit }) => unit)),\n ].filter((name) => name !== entry.unit.name && ordered.some(({ unit }) => unit.name === name));\n });\n\n if (ordered.length > 1 && !config.tagFormat.includes(\"{name}\")) {\n problems.push({\n file: path.basename(configFile),\n message: `tag \"${config.tagFormat}\" names no unit, so ${ordered.length} units would share each tag`,\n hint: 'add {name} to the format, such as \"{name}--v{version}\", or release one unit',\n });\n }\n\n return {\n root,\n flow: config.flow,\n modules: config.modules,\n features: config.features,\n units: ordered.map(({ unit }) => unit),\n problems: sortProblems(problems),\n display: config.display,\n renames: [path.basename(configFile), ...ordered.map(({ unit }) => unit.file)].flatMap(\n (file) => renameOf(file) ?? [],\n ),\n tagFormat: config.tagFormat,\n releasesCommits: config.releasesCommits,\n };\n};\n","import type { z } from \"zod\";\n\nimport type { SetupContext } from \"./setupContext\";\nimport { paint } from \"./say\";\nimport { documentedKeys } from \"./setupFiles\";\n\n/**\n * `shiplane docs <module or adapter>`: every key a unit file takes, described, with its default. A\n * module name reads the release config; an adapter name, the official adapters and those composed.\n */\nexport const docsFor = async (context: SetupContext, name: string) => {\n const { output } = context;\n const release = await context.load();\n const module = release.modules.find((candidate) => candidate.name === name);\n const adapters = [\n ...context.adapters,\n ...release.modules.map(({ provider, settings }) => ({ name: provider, settings })),\n ];\n const adapter = adapters.find((candidate) => candidate.name === name);\n const found: { title: string; settings: z.ZodObject } | undefined = module\n ? {\n title: `module: ${module.name} ${paint(\"dim\", `with ${module.provider}`)}`,\n settings: module.settings,\n }\n : adapter && {\n title: `${adapter.name} ${paint(\"dim\", \"adapter\")}`,\n settings: adapter.settings,\n };\n if (!found) {\n const known = [\n ...new Set([\n ...release.modules.map((candidate) => candidate.name),\n ...adapters.map((candidate) => candidate.name),\n ]),\n ];\n output.line(`${paint(\"red\", \"✗\")} no module or adapter \"${name}\": ${known.join(\", \")}`);\n return false;\n }\n const keys = documentedKeys(found.settings);\n const width = Math.max(8, ...keys.map(({ key }) => key.length)) + 2;\n output.line();\n output.line(` ${paint(\"bold\", found.title)}`);\n output.line();\n keys.forEach(({ key, description, default: fallback, required }) => {\n const note = required\n ? paint(\"yellow\", \"required\")\n : fallback === undefined\n ? \"optional\"\n : `default: ${typeof fallback === \"string\" ? fallback : JSON.stringify(fallback)}`;\n output.line(` ${key.padEnd(width)}${description}`);\n output.line(` ${\" \".repeat(width)}${paint(\"dim\", note)}`);\n });\n output.line();\n return true;\n};\n","import type { SetupContext } from \"./setupContext\";\nimport { paint } from \"./say\";\nimport { addToConfig, CONFIG_FILE, factoryName, releasePackage } from \"./setupFiles\";\n\nconst adapterFile = (\n name: string,\n factory: string,\n pkg: string,\n) => `import { defineServerHosting, z } from \"${pkg}\";\n\n/** Hosts a server on ${name}. Replace the command with the one that deploys it. */\nexport const ${factory} = () =>\n defineServerHosting({\n name: \"${name}\",\n settings: z.object({\n service: z.string().describe(\"What to deploy\"),\n }),\n describe: ({ options }) => \\`\\${options.service} on ${name}\\`,\n jobs: ({ tag, options }) => [\n {\n label: \\`deploy \\${tag} to \\${options.service}\\`,\n local: [{ command: \"echo\", args: [\"deploy\", options.service] }],\n },\n ],\n });\n`;\n\nconst testFile = (\n name: string,\n factory: string,\n pkg: string,\n) => `import { serverHostingContract, serverHostingFake } from \"${pkg}/testing\";\n\nimport { ${factory} } from \"./${name}\";\n\n// The contract every server host passes, run on this adapter and on the Fake tests use in its place.\nserverHostingContract([\n { adapter: ${factory}(), settings: { service: \"web-preview\" } },\n { adapter: serverHostingFake(), settings: { service: \"web-preview\" } },\n]);\n`;\n\n/**\n * `shiplane adapter new <name>`: a server hosting adapter, the port's contract suite run on it and on\n * its Fake, and a module for it in the root config.\n */\nexport const newAdapter = async (context: SetupContext, name: string): Promise<boolean> => {\n const { output, files } = context;\n if (!/^[a-z][a-z0-9-]*$/.test(name)) {\n output.line(\n `${paint(\"red\", \"✗\")} an adapter name is lowercase words joined by dashes, like my-host`,\n );\n return false;\n }\n const factory = `${factoryName(name)}ServerHosting`;\n const pkg = releasePackage(files);\n const file = `release/adapters/${name}.ts`;\n if (files.exists(file)) {\n output.line(`${paint(\"red\", \"✗\")} ${file} already exists`);\n return false;\n }\n const config = addToConfig(\n files.read(CONFIG_FILE) ?? \"\",\n {\n factory: \"backendService\",\n port: \"serverHosting\",\n adapter: factory,\n name,\n from: `./release/adapters/${name}`,\n },\n pkg,\n );\n if (!config) {\n output.line(\n `${paint(\"red\", \"✗\")} ${CONFIG_FILE} has no modules list to add it to: run shiplane init first`,\n );\n return false;\n }\n files.write(file, adapterFile(name, factory, pkg));\n files.write(`release/adapters/${name}.test.ts`, testFile(name, factory, pkg));\n files.write(CONFIG_FILE, config);\n output.line(\n `${paint(\"green\", \"◇\")} Wrote ${file}, its contract test, and a ${name} module in ${CONFIG_FILE}`,\n );\n output.line(\n `${paint(\"dim\", \"└\")} Next: point an app at it with ${paint(\"cyan\", `module: ${name}`)}`,\n );\n return Promise.resolve(true);\n};\n","import type { AppBump } from \"./changes\";\n\nexport interface OpenPr {\n number: number;\n url: string;\n /** The commit the PR's branch stands on, when the host says: main moving past it makes the PR stale. */\n head?: string;\n}\n\n/** Whether a release PR merges from the terminal, or waits for someone else to approve it. */\nexport type Approval = \"none\" | \"required\";\n\nexport type MergeMethod = \"--squash\" | \"--merge\" | \"--rebase\";\n\n/** What the pull request page offers: the methods the repository allows, and the one it preselects. */\nexport interface MergeMethods {\n allowed: MergeMethod[];\n preselected: MergeMethod | null;\n}\n\nexport type ReleaseStep =\n { step: \"wait-merge\"; prs: OpenPr[] } | { step: \"release-pr\" } | { step: \"ship\" };\n\n/**\n * Where `pnpm shiplane` picks up, from what main and GitHub hold right now. A merged release is\n * tagged and shipped before the next one is opened.\n */\nexport const nextStep = ({\n pending,\n releasePrs,\n untagged,\n unreleased,\n}: {\n pending: number;\n /** The open release PR, if any; older releases may have left one per app. */\n releasePrs: OpenPr[];\n /** Versions a merged release moved that have no tag or release notes yet. */\n untagged: number;\n /** Apps changed since their current version with no changeset naming them. */\n unreleased: number;\n}): ReleaseStep => {\n if (releasePrs.length > 0) return { step: \"wait-merge\", prs: releasePrs };\n if ((pending > 0 || unreleased > 0) && untagged === 0) return { step: \"release-pr\" };\n return { step: \"ship\" };\n};\n\n// The tool's own name: a branch a person names chore/release-notes is never taken for one.\nexport const RELEASE_BRANCH_PREFIX = \"shiplane/release-\";\n\nexport const twoDigits = (value: number) => String(value).padStart(2, \"0\");\n\nexport const releaseBranchName = (now: Date) =>\n `${RELEASE_BRANCH_PREFIX}${now.getFullYear()}-${twoDigits(now.getMonth() + 1)}-${twoDigits(now.getDate())}-${twoDigits(now.getHours())}${twoDigits(now.getMinutes())}`;\n\nconst sentence = (items: string[]) =>\n items.length < 2 ? items.join(\"\") : `${items.slice(0, -1).join(\", \")} and ${items.at(-1)}`;\n\nconst MAX_LINE = 100;\n\n/** One app's release commit: `chore(api): release v0.0.4`. */\nexport const releaseCommitTitle = ({ app, to }: AppBump) => `chore(${app}): release v${to}`;\n\n// commitlint caps a header at 100; a squash merge appends \" (#12345)\", so a title keeps 9 spare.\nexport const MAX_TITLE = MAX_LINE - \" (#12345)\".length;\n\nconst counted = (count: number, word: string) => `${count} ${word}${count === 1 ? \"\" : \"s\"}`;\n\n/** Each app's module kind, so a title calls services services and packages plugins. */\nexport type KindOf = (app: string) => string | undefined;\n\n/** What a title calls a unit of each module kind; several kinds at once are apps. */\nconst NOUN: Record<string, string> = {\n \"published-package\": \"package\",\n \"backend-service\": \"service\",\n \"web-app\": \"web app\",\n \"mobile-app\": \"mobile app\",\n \"internal-tool\": \"tool\",\n};\n\n/**\n * The apps, gathered into families in their own order: a root moving with its `root-*` apps\n * (`shiplane`, `shiplane-npm`) is one family; any other app is a family of one.\n */\nexport const releaseFamilies = (bumps: AppBump[]): AppBump[][] => {\n const roots = bumps.filter(\n ({ app }) => !bumps.some((other) => other.app !== app && app.startsWith(`${other.app}-`)),\n );\n return roots.map((root) =>\n bumps.filter(({ app }) => app === root.app || app.startsWith(`${root.app}-`)),\n );\n};\n\n/** 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`. */\nconst familyLabel = ([root, ...members]: AppBump[], kindOf: KindOf) => {\n if (!root) return \"\";\n // One member is clearer named than counted: `api v0.3.0, api-worker v0.3.0`.\n if (members.length < 2)\n return [root, ...members].map(({ app, to }) => `${app} v${to}`).join(\", \");\n const kinds = new Set([root, ...members].map(({ app }) => kindOf(app)));\n const [kind] = kinds;\n const noun = (kinds.size === 1 && kind && NOUN[kind]) || \"app\";\n // A package's siblings extend it: plugins. Siblings of anything else are more of it.\n const rest =\n noun === \"package\"\n ? counted(members.length, \"plugin\")\n : `${members.length} more ${counted(members.length, noun).replace(/^\\d+ /, \"\")}`;\n return members.every(({ to }) => to === root.to)\n ? `${root.app} and ${rest} v${root.to}`\n : `${root.app} v${root.to} and ${rest}`;\n};\n\n/**\n * The release PRs a release opens, all from main at once: one per app, a family counting as one.\n * Apps `linked` (one changeset naming both, or one moving with the other) share a PR, so no two\n * PRs ever touch the same file.\n */\nexport const releasePrGroups = (\n bumps: AppBump[],\n linked: readonly (readonly string[])[],\n): AppBump[][] => {\n const groups = releaseFamilies(bumps).map((family) => new Set(family.map(({ app }) => app)));\n const merged = linked.reduce((current, apps) => {\n const touched = current.filter((group) => apps.some((app) => group.has(app)));\n if (touched.length < 2) return current;\n const union = new Set(touched.flatMap((group) => [...group]));\n return [...current.filter((group) => !touched.includes(group)), union];\n }, groups);\n // Kept in the release's own order, by each group's first app.\n const order = (group: Set<string>) => bumps.findIndex(({ app }) => group.has(app));\n return merged\n .sort((left, right) => order(left) - order(right))\n .map((group) => bumps.filter(({ app }) => group.has(app)));\n};\n\n/** Whether a title still fits once a squash merge appends its PR number. */\nexport const titleFits = (title: string) => title.length <= MAX_TITLE;\n\n/**\n * Conventional, and naming every app it brings, never a bare count: `chore(api): release v0.0.4`,\n * `chore(release): api v0.0.2 and admin v0.1.0`, or, when listing each one is too long, families\n * by their root: `chore(release): shiplane and 7 plugins v0.1.0, landing v1.2.0 and expo v2.1.0`.\n * One release is one PR: a title too long even then stays whole, see `titleFits`.\n */\nexport const releaseTitle = (bumps: AppBump[], kindOf: KindOf = () => undefined) => {\n const [first, ...others] = bumps;\n if (!first) return \"chore(release): package changelogs\";\n if (others.length === 0) return releaseCommitTitle(first);\n // One family is one app's release: `chore(shiplane): release v0.1.0`, its plugins in the body.\n const families = releaseFamilies(bumps);\n const [only] = families;\n if (families.length === 1 && only?.[0]) return releaseCommitTitle(only[0]);\n const every = `chore(release): ${sentence(bumps.map(({ app, to }) => `${app} v${to}`))}`;\n if (titleFits(every)) return every;\n // Families first: their own \"and\" never runs into the list's last one.\n families.sort((left, right) => Number(right.length > 1) - Number(left.length > 1));\n const labels = families.map((family) => familyLabel(family, kindOf));\n // Two families end the list: commas alone keep \"a and 2 more and b and 7 plugins\" from happening.\n const list = labels.at(-1)?.includes(\" and \") ? labels.join(\", \") : sentence(labels);\n return `chore(release): ${list}`;\n};\n\n/** A bullet wrapped to commitlint's 100-character body lines, continued under its text. */\nconst bullet = (text: string) =>\n text\n .split(\" \")\n .reduce<string[]>((lines, word) => {\n const last = lines.at(-1);\n if (last !== undefined && `${last} ${word}`.length <= MAX_LINE) {\n return [...lines.slice(0, -1), `${last} ${word}`];\n }\n return [...lines, `${last === undefined ? \"-\" : \" \"} ${word}`];\n }, [])\n .join(\"\\n\");\n\n/** The release commit's body: each app's version, then what its users get. */\nexport const releaseCommitBody = (bumps: AppBump[]) =>\n bumps\n .map(({ app, to, notes, movedWith }) => {\n const lines =\n notes.length > 0\n ? notes\n : movedWith.length > 0\n ? [`Moves with ${movedWith.join(\", \")}.`]\n : [];\n return [`${app} ${to}`, ...lines.map(bullet)].join(\"\\n\");\n })\n .join(\"\\n\\n\");\n\n/** The release PR's body; `onMerge` says what happens to each unit once it is merged. */\nexport const releasePrBody = (bumps: AppBump[], onMerge: (bump: AppBump) => string) => {\n const appWidth = Math.max(3, ...bumps.map(({ app }) => app.length));\n const versionWidth = Math.max(7, ...bumps.map(({ from, to }) => `${from} → ${to}`.length));\n const row = (cells: string[]) => `| ${cells.join(\" | \")} |`;\n const table = [\n row([\"App\".padEnd(appWidth), \"Version\".padEnd(versionWidth), \"On merge\"]),\n row([\"-\".repeat(appWidth), \"-\".repeat(versionWidth), \"--------\"]),\n ...bumps.map((bump) =>\n row([\n bump.app.padEnd(appWidth),\n `${bump.from} → ${bump.to}`.padEnd(versionWidth),\n onMerge(bump),\n ]),\n ),\n ];\n const notes = bumps.flatMap(({ app, to, notes: lines }) =>\n lines.length > 0 ? [\"\", `### ${app} ${to}`, \"\", ...lines.map((line) => `- ${line}`)] : [],\n );\n return [\n \"## 🎯 What & why\",\n \"\",\n \"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.\",\n \"\",\n ...(bumps.length > 0 ? table : [\"Internal packages only: changelogs, nothing ships.\"]),\n ...notes,\n \"\",\n \"## ✅ Testing\",\n \"\",\n \"Versions, changelogs and version files only. No UI change.\",\n ].join(\"\\n\");\n};\n\nconst MERGE_BUTTON: { value: MergeMethod; label: string; hint: string }[] = [\n {\n value: \"--merge\",\n label: \"Create a merge commit\",\n hint: \"every commit, joined by a merge commit\",\n },\n { value: \"--squash\", label: \"Squash and merge\", hint: \"the commits combined into one\" },\n { value: \"--rebase\", label: \"Rebase and merge\", hint: \"every commit, rebased onto main\" },\n];\n\n/** The methods as GitHub's merge button lists them, preselected as the pull request page does. */\nexport const mergeChoices = ({ allowed, preselected }: MergeMethods) => {\n const choices = MERGE_BUTTON.filter(({ value }) => allowed.includes(value));\n const initial = preselected && allowed.includes(preselected) ? preselected : choices[0]?.value;\n return { choices, initial };\n};\n\nexport type WaitAction = \"diff\" | \"merge\" | \"open\";\n\nconst WAIT_KEYS: Record<string, WaitAction> = { d: \"diff\", m: \"merge\", o: \"open\" };\n\n/** What a key does while the release waits for its pull request to merge. */\nexport const waitKey = (name: string | undefined): WaitAction | null =>\n (name && WAIT_KEYS[name]) || null;\n","import type { StatusPlan, UnitRef } from \"./changes\";\n\n/** A unit that goes out with the picked ones without being picked, and why. */\nexport interface Companion {\n /** The unit's name. */\n app: string;\n version: string;\n /** The picked units it goes with. */\n with: string[];\n /** Why, as a person reads it. */\n why: string;\n}\n\n/** The shortest chain of moving packages from `from` to one a changeset names, breadth first. */\nconst chainTo = (\n from: string,\n dependencies: Record<string, string[]>,\n moving: ReadonlySet<string>,\n named: ReadonlySet<string>,\n): string[] => {\n const seen = new Set<string>();\n let paths = [[from]];\n while (paths.length > 0) {\n const next: string[][] = [];\n for (const path of paths) {\n const last = path[path.length - 1] ?? from;\n for (const dependency of dependencies[last] ?? []) {\n if (!moving.has(dependency) || seen.has(dependency)) continue;\n seen.add(dependency);\n const chain = [...path, dependency];\n if (named.has(dependency)) return chain.slice(1);\n next.push(chain);\n }\n }\n paths = next;\n }\n return [];\n};\n\n/**\n * Preview: the units a release moves that the person did not pick. changesets moves a unit whenever\n * a workspace package it uses moves, so it cannot stay behind; this says through which package.\n */\nexport const draggedUnits = (\n plan: StatusPlan,\n dependencies: Record<string, string[]>,\n units: readonly UnitRef[],\n scope: ReadonlySet<string>,\n): Companion[] => {\n const moving = new Set(plan.releases.map(({ name }) => name));\n const named = new Set(\n plan.releases.filter(({ changesets }) => changesets.length > 0).map(({ name }) => name),\n );\n const picked = units.filter(({ name }) => scope.has(name));\n return units.flatMap(({ name: app, packageName }) => {\n const release = plan.releases.find(({ name }) => name === packageName);\n if (scope.has(app) || !release) return [];\n const chain = chainTo(packageName, dependencies, moving, named);\n const source = chain[chain.length - 1];\n const movers = picked\n .filter((unit) =>\n plan.changesets.some(\n ({ releases }) =>\n releases.some(({ name }) => name === source) &&\n releases.some(({ name }) => name === unit.packageName),\n ),\n )\n .map(({ name }) => name);\n const whose = movers.length > 0 ? `${movers.join(\", \")}'s changes move` : \"this release moves\";\n return [\n {\n app,\n version: release.newVersion,\n with: movers,\n why:\n chain.length > 0\n ? `uses ${chain.join(\" → \")}, which ${whose}`\n : \"moves with this release\",\n },\n ];\n });\n};\n\n/** A unit's version on preview with its release notes. */\nexport interface Released {\n app: string;\n version: string;\n notes: string;\n}\n\nconst OWN_CHANGE = /^- ([0-9a-f]{7,40}): /gm;\nconst DEPENDENCY_CHANGES = /^- Updated dependencies \\[([^\\]]+)\\]/gm;\n\n/** The changes a version carries: its own, and those a package it uses moved for. */\nconst changeIds = (notes: string) =>\n new Set([\n ...[...notes.matchAll(OWN_CHANGE)].flatMap(([, id]) => (id ? [id] : [])),\n ...[...notes.matchAll(DEPENDENCY_CHANGES)].flatMap(([, ids]) =>\n (ids ?? \"\").split(\",\").map((id) => id.trim()),\n ),\n ]);\n\n/** A change's first line in these notes, with an ellipsis when it goes on. */\nconst summaryOf = (notes: string, id: string) => {\n const lines = notes.split(\"\\n\");\n const index = lines.findIndex((line) => line.startsWith(`- ${id}: `));\n const first = lines[index]?.slice(`- ${id}: `.length).trim();\n if (index < 0 || !first) return null;\n const goesOn = /^ {2}\\S/.test(lines[index + 1] ?? \"\");\n return goesOn ? `${first}…` : first;\n};\n\n/** The packages listed under the `Updated dependencies` line that names this change. */\nconst packagesMovedFor = (notes: string, id: string) => {\n const lines = notes.split(\"\\n\");\n const start = lines.findIndex(\n (line) => line.startsWith(\"- Updated dependencies [\") && line.includes(id),\n );\n if (start < 0) return [];\n const listed = lines.slice(start + 1);\n const end = listed.findIndex((line) => !/^ {2}- \\S+@/.test(line));\n return (end < 0 ? listed : listed.slice(0, end)).map((line) =>\n line\n .trim()\n .slice(2)\n .replace(/@[^@]*$/, \"\"),\n );\n};\n\n/** Why two versions went out together: the change they share, or the package both moved for. */\nconst sharedReason = (partner: Released, other: Released, id: string) => {\n const summary = summaryOf(partner.notes, id) ?? summaryOf(other.notes, id);\n if (summary) return ` for: ${summary}`;\n const theirs = new Set(packagesMovedFor(partner.notes, id));\n const both = packagesMovedFor(other.notes, id).filter((name) => theirs.has(name));\n return both.length > 0 ? `: both use ${both.join(\", \")}, which moved` : \"\";\n};\n\n/**\n * Production: the units preview runs with the picked ones that are not picked. Two versions went to\n * preview together when their notes share a change, their own or one a package they use moved for.\n */\nexport const releasedTogether = (picked: Released[], others: Released[]): Companion[] =>\n others.flatMap((other) => {\n const ids = changeIds(other.notes);\n const partners = picked.flatMap((partner) => {\n const shared = [...changeIds(partner.notes)].find((id) => ids.has(id));\n return shared ? [{ partner, shared }] : [];\n });\n const [first] = partners;\n if (!first) return [];\n const names = partners.map(({ partner }) => `${partner.app} ${partner.version}`).join(\", \");\n return [\n {\n app: other.app,\n version: other.version,\n with: partners.map(({ partner }) => partner.app),\n why: `went to preview with ${names}${sharedReason(first.partner, other, first.shared)}`,\n },\n ];\n });\n","import type { UnitRef, UnreleasedApp } from \"../domain/changes\";\nimport type { Environment } from \"../domain/environment\";\nimport type { ScopeInfo } from \"../domain/scope\";\nimport type { ReleaseUnit } from \"../domain/unit\";\nimport type { Deploy } from \"../ports/code-host.port\";\nimport type { ReleaseContext } from \"./context\";\nimport { changesetApps, unreleasedApps } from \"../domain/changes\";\nimport { deployRunTitle } from \"../domain/deploys\";\nimport { cameWithRelease, firstRelease, tagName } from \"../domain/tags\";\nimport { UNIT_FILES } from \"./config/readUnitFile\";\nimport { decideContext, jobInput, moduleOf } from \"./targets\";\n\nexport const MANIFEST = \"package.json\";\n\nexport const unitRefs = (units: readonly ReleaseUnit[]): UnitRef[] =>\n units.map(({ name, packageName }) => ({ name, packageName }));\n\n/** The units the pending changesets name. */\nexport const namedUnits = async ({ release, services }: ReleaseContext) =>\n new Set(\n (await services.versioning.pending()).flatMap(({ text }) =>\n changesetApps(text, unitRefs(release.units)),\n ),\n );\n\n/** Units whose folder moved since their current version, that no changeset or bump ships. */\nexport const findUnreleased = async (\n { release, services: { sourceControl: source } }: ReleaseContext,\n named: ReadonlySet<string>,\n): Promise<UnreleasedApp[]> => {\n if (!release.releasesCommits) return [];\n const history = await Promise.all(\n release.units.map(async ({ name, dir, version }) => {\n const since =\n (await source.tagCommit(tagName(name, version, release.tagFormat))) ??\n (await source.versionCommit(dir, MANIFEST, version))?.sha;\n if (!since) return [];\n // Its own release config is not a change its users get.\n const commits = await source.subjectsSince(since, dir, UNIT_FILES);\n return [{ app: name, version, commits }];\n }),\n );\n return unreleasedApps(history.flat(), named);\n};\n\n/** A tag's deploy on an environment, from every record the host keeps. */\nexport const deployedOn = (history: readonly Deploy[], tag: string, environment: Environment) => {\n const states = history\n .filter(({ title }) => title === deployRunTitle(tag, environment))\n .map(({ state }) => state);\n if (states.includes(\"done\")) return \"done\";\n return states.includes(\"running\") ? \"running\" : \"none\";\n};\n\n/**\n * Each unit as the first question sees it: git for what is new, the host's deploy records for what\n * each environment runs (offline, nothing counts as deployed).\n */\nexport const readScope = async (\n context: ReleaseContext,\n environment: Environment,\n): Promise<ScopeInfo[]> => {\n const { release, services } = context;\n const pending = await services.versioning.pending();\n const refs = unitRefs(release.units);\n const named = pending.map(({ text }) => changesetApps(text, refs));\n const unreleased = await findUnreleased(context, new Set(named.flat()));\n const [deployed, tags] = await Promise.all([\n services.codeHost.deployments().catch(() => []),\n services.sourceControl.tags(),\n ]);\n return Promise.all(\n release.units.map(async (unit) => {\n const tag = tagName(unit.name, unit.version, context.release.tagFormat);\n const target = moduleOf(context, unit);\n const decidedBy = target?.decidedBy;\n const commit = await services.sourceControl.versionCommit(unit.dir, MANIFEST, unit.version);\n const tagged = (await services.sourceControl.tagCommit(tag)) !== null;\n // A module that reads its platform (a registry) says what runs; else deploy records do.\n const live = async (on: Environment) => {\n if (!target?.live || !tagged) return deployedOn(deployed, tag, on) === \"done\";\n const { head } = await services.sourceControl.position();\n const input = jobInput(context, target, unit, { tag, environment: on, commit: head });\n return target.live(decideContext(context), input).catch(() => false);\n };\n return {\n app: unit.name,\n version: unit.version,\n changesets: named.filter((apps) => apps.includes(unit.name)).length,\n commits: unreleased.find((entry) => entry.app === unit.name)?.commits.length ?? 0,\n tagged,\n versioned:\n commit !== null && cameWithRelease({ app: unit.name, version: unit.version, commit }),\n firstRelease:\n !tagged &&\n commit !== null &&\n firstRelease(unit.name, unit.version, tags, context.release.tagFormat),\n onChannel: await live(environment),\n onPreview: await live(\"preview\"),\n ...(decidedBy ? { decidedBy } : {}),\n ...(target?.releaseOnly ? { releaseOnly: true } : {}),\n };\n }),\n );\n};\n","import type { AppBump, PlannedChangeset, UnreleasedApp } from \"../domain/changes\";\nimport type { Companion } from \"../domain/companions\";\nimport type { VersionChoice, VersionContribution } from \"../ports/delivery.port\";\nimport type { ReleaseContext } from \"./context\";\nimport { appBumps, packageBumps, splitChangesets, unreleasedChangesets } from \"../domain/changes\";\nimport { draggedUnits } from \"../domain/companions\";\nimport { tagName } from \"../domain/tags\";\nimport { findUnreleased, namedUnits, unitRefs } from \"./readScope\";\nimport { decideContext, jobInput, moduleOf } from \"./targets\";\n\nexport type Split = ReturnType<typeof splitChangesets>;\n\nconst NOTHING_HELD: Split = { ships: [], waits: [] };\n\nexport interface Prepared {\n /** Changesets this release ships, the ones it writes included. */\n pending: number;\n /** Units the person left out: their changesets stay pending. */\n held: string[];\n /** Changed units the person left out: no changeset ships them. */\n unreleased: UnreleasedApp[];\n split: Split;\n bumps: AppBump[];\n /** Units the person did not pick that move anyway, with the package that drags each. */\n companions: Companion[];\n /** Internal packages moved along: changelogs only. */\n packages: number;\n /** Changesets the release writes itself. */\n added: PlannedChangeset[];\n /** Every changeset the release versions, with the lines it ships. */\n shipped: PlannedChangeset[];\n /** What plugins add to the release PR, by unit: an EAS app's build or update. */\n contributions: Record<string, VersionContribution>;\n}\n\n/** The person's answer to a plugin's choice; the suggestion without a terminal or with --yes. */\nconst choose = async ({ prompter, options }: ReleaseContext, choice: VersionChoice | undefined) => {\n if (!choice) return null;\n if (options.yes || !prompter.interactive) return choice.suggested;\n return prompter.select(choice.question, choice.options, choice.suggested);\n};\n\n/** What each picked unit's plugin adds, given the unit's bump so far. One at a time: it may ask. */\nconst contributionsOf = async (\n context: ReleaseContext,\n scope: ReadonlySet<string>,\n bumps: readonly AppBump[],\n known: Readonly<Record<string, VersionContribution>> = {},\n) => {\n const { head } = await context.services.sourceControl.position();\n const contributions: Record<string, VersionContribution> = {};\n for (const unit of context.release.units.filter(({ name }) => scope.has(name))) {\n // Already answered for the whole release: one release PR of several never asks twice.\n const answered = known[unit.name];\n if (answered) {\n contributions[unit.name] = answered;\n continue;\n }\n const module = moduleOf(context, unit);\n const version = module?.version?.bind(module);\n if (!module || !version) continue;\n const input = jobInput(context, module, unit, {\n tag: tagName(unit.name, unit.version, context.release.tagFormat),\n environment: \"preview\",\n commit: head,\n });\n const bump = bumps.find(({ app }) => app === unit.name);\n const contribute = (chosen?: string) =>\n version(decideContext(context), { ...input, bump, chosen });\n const suggested = await contribute();\n const chosen = await choose(context, suggested.choice);\n contributions[unit.name] =\n chosen && chosen !== suggested.choice?.suggested ? await contribute(chosen) : suggested;\n }\n return contributions;\n};\n\n/** What a release PR covering `scope` would version, computed without writing anything. */\nexport const prepareRelease = async (\n context: ReleaseContext,\n scope: ReadonlySet<string>,\n known: Readonly<Record<string, VersionContribution>> = {},\n): Promise<Prepared> => {\n const { release, services } = context;\n const refs = unitRefs(release.units);\n const [dependencies, named, base, pendingFiles] = await Promise.all([\n services.versioning.dependencies(),\n namedUnits(context),\n services.versioning.plan([], []),\n services.versioning.pending(),\n ]);\n const baseBumps = appBumps(base, dependencies, refs);\n const unreleased = await findUnreleased(\n context,\n new Set([...named, ...baseBumps.map(({ app }) => app)]),\n );\n const held = [...named].filter((app) => !scope.has(app));\n const adopted = unreleased\n .filter(({ app }) => scope.has(app))\n .flatMap(({ app, version, commits }) => {\n const ref = refs.find(({ name }) => name === app);\n return ref ? unreleasedChangesets(ref, version, commits) : [];\n });\n const split = held.length > 0 ? splitChangesets(base.changesets, held, refs) : NOTHING_HELD;\n const picked =\n held.length > 0 || adopted.length > 0\n ? await services.versioning.plan(adopted, split.waits)\n : base;\n const contributions = await contributionsOf(\n context,\n scope,\n appBumps(picked, dependencies, refs),\n known,\n );\n const contributed = Object.values(contributions).flatMap(({ added }) => added);\n const added = [...adopted, ...contributed];\n const plan = contributed.length > 0 ? await services.versioning.plan(added, split.waits) : picked;\n return {\n pending: (held.length > 0 ? split.ships.length : pendingFiles.length) + added.length,\n held,\n unreleased: unreleased.filter(({ app }) => !scope.has(app)),\n split,\n bumps: appBumps(plan, dependencies, refs),\n companions: draggedUnits(plan, dependencies, refs, scope),\n packages: packageBumps(plan, refs),\n added,\n shipped: plan.changesets,\n contributions,\n };\n};\n","import type { OpenPr } from \"../domain/releasePr\";\nimport type { ReleaseContext } from \"./context\";\nimport { CommandFailed } from \"../ports/shell.port\";\nimport { fail, paint } from \"./say\";\n\n/** How a step takes back what it did, and what a person runs when that fails too. */\nexport interface Undo {\n label: string;\n run: () => Promise<void>;\n byHand: () => string[];\n}\n\n/** What a step leaves in place on purpose when a later one fails, and what finishes the job. */\nexport interface Kept {\n label: string;\n byHand: () => string[];\n}\n\n/** One labelled thing a release does; the label is what a dry run or a failure shows. */\nexport interface Step {\n label: string;\n run: () => Promise<void>;\n /** Run when a later step fails, so a stopped release leaves nothing half done. */\n undo?: Undo;\n /** What stays when a later step fails, said instead of claiming all was undone. */\n kept?: Kept;\n}\n\nconst MAX_OUTPUT_LINES = 40;\n\nconst reasonOf = (error: unknown) => (error instanceof Error ? error.message : String(error));\n\n/** What the failed command printed, so the person reads why without running it again. */\nconst printOutput = ({ output }: ReleaseContext, error: unknown) => {\n if (!(error instanceof CommandFailed) || !error.output) return;\n const lines = error.output.split(\"\\n\");\n const shown = lines.slice(-MAX_OUTPUT_LINES);\n if (shown.length < lines.length) {\n output.line(paint(\"dim\", ` … ${lines.length - shown.length} earlier lines`));\n }\n shown.forEach((line) => output.line(paint(\"dim\", ` │ ${line}`)));\n};\n\n/** Takes back the steps that ran, newest first; one that cannot be undone never stops the rest. */\nconst cancel = async (context: ReleaseContext, ran: readonly Step[]) => {\n const undos = ran.flatMap(({ undo }) => (undo ? [undo] : [])).reverse();\n const kept = ran.flatMap((step) => (step.kept ? [step.kept] : []));\n if (undos.length === 0 && kept.length === 0) return;\n const left: Undo[] = [];\n for (const undo of undos) {\n try {\n await context.progress.during(`undo: ${undo.label}`, \"working\", undo.run);\n } catch (error) {\n left.push(undo);\n context.progress.say(\n \"worried\",\n `${paint(\"red\", \"✗\")} undo ${undo.label}: ${reasonOf(error)}`,\n );\n }\n }\n if (left.length === 0 && kept.length === 0) {\n context.progress.say(\"resting\", paint(\"dim\", \"Cancelled: everything this run did is undone.\"));\n return;\n }\n const commands = [...new Set([...left, ...kept].flatMap(({ byHand }) => byHand()))];\n const these = commands.length > 1 ? \"these\" : \"this\";\n const ask = kept.length === 0 ? \"run these to finish the cleanup:\" : `run ${these} to finish:`;\n fail(\n context,\n \"Cancelled, not all of it\",\n [...kept.map(({ label }) => label), ask].join(\"; \"),\n commands,\n );\n};\n\n/**\n * Runs steps in order, each shown with its place in the run. At the first failure it says why,\n * with the command's own output, and undoes the steps that ran.\n */\nexport const runSteps = async (context: ReleaseContext, steps: readonly Step[]) => {\n for (const [index, step] of steps.entries()) {\n try {\n await context.progress.during(step.label, \"working\", step.run, {\n index,\n total: steps.length,\n });\n } catch (error) {\n fail(context, `${step.label} failed`, `${reasonOf(error)}, the steps after it did not run.`);\n printOutput(context, error);\n await cancel(context, steps.slice(0, index));\n return false;\n }\n }\n return true;\n};\n\n/** A branch from main; undone by dropping the changes made on it and the branch itself. */\nexport const branchStep = (\n { services: { sourceControl: source } }: ReleaseContext,\n branch: string,\n): Step => {\n let untracked = new Set<string>();\n return {\n label: `branch ${branch} from main`,\n run: async () => {\n untracked = new Set(await source.changedFiles());\n await source.createBranch(branch);\n },\n undo: {\n label: `delete ${branch}`,\n run: async () => {\n const created = (await source.changedFiles()).filter((file) => !untracked.has(file));\n await source.discard(created);\n await source.switchTo(\"main\");\n await source.deleteBranch(branch);\n },\n byHand: () => [\"git reset --hard\", \"git switch main\", `git branch -D ${branch}`],\n },\n };\n};\n\nexport const pushStep = (\n { services: { sourceControl: source } }: ReleaseContext,\n branch: string,\n): Step => ({\n label: `push ${branch}`,\n run: () => source.push(branch),\n undo: {\n label: `delete ${branch} on origin`,\n run: () => source.deleteRemoteBranch(branch),\n byHand: () => [`git push origin --delete ${branch}`],\n },\n});\n\n/** Opens a pull request; undone by closing it, with a comment saying why. */\nexport const openPrStep = (\n { services: { codeHost: host } }: ReleaseContext,\n label: string,\n open: () => Promise<OpenPr>,\n): Step => {\n let opened: OpenPr | null = null;\n return {\n label,\n run: async () => {\n opened = await open();\n },\n undo: {\n label: \"close the pull request\",\n run: async () => {\n if (opened) await host.closePr(opened, \"The release stopped part way, so it closed this.\");\n },\n byHand: () => (opened ? [`gh pr close ${opened.number}`] : []),\n },\n };\n};\n","import type { AppBump } from \"../domain/changes\";\nimport type { KindOf, OpenPr } from \"../domain/releasePr\";\nimport type { ReleaseContext } from \"./context\";\nimport type { Prepared } from \"./prepareRelease\";\nimport { releaseSource } from \"../domain/governance\";\nimport {\n releaseBranchName,\n releaseCommitBody,\n releasePrBody,\n releasePrGroups,\n releaseTitle,\n titleFits,\n} from \"../domain/releasePr\";\nimport { prepareRelease } from \"./prepareRelease\";\nimport { confirm, fail, listed, paint } from \"./say\";\nimport { branchStep, openPrStep, pushStep, runSteps } from \"./steps\";\nimport { environmentLabel, moduleOf } from \"./targets\";\n\nconst plural = (count: number, word: string) => `${count} ${word}${count === 1 ? \"\" : \"s\"}`;\n\n/** What happens to a unit once the release PR merges: its module ships the version to preview. */\nconst shipsOnMerge =\n (context: ReleaseContext, { contributions, companions }: Prepared) =>\n (bump: AppBump) => {\n const contributed = contributions[bump.app]?.onMerge;\n if (contributed) return contributed;\n const unit = context.release.units.find(({ name }) => name === bump.app);\n const along = companions.find(({ app }) => app === bump.app);\n const reason = along\n ? ` (not picked: ${along.why})`\n : bump.movedWith.length > 0\n ? ` (moved with ${bump.movedWith.join(\", \")})`\n : \"\";\n return `${environmentLabel(context, [bump.app], \"preview\") === \"live\" ? \"Ship live\" : \"Ship to preview\"} with ${(unit && moduleOf(context, unit)?.provider) ?? \"its target\"}${reason}`;\n };\n\n/** Units going out unpicked, each with the package that takes it along. */\nconst printCompanions = ({ output, release }: ReleaseContext, { companions, split }: Prepared) => {\n if (companions.length === 0) return;\n const names = companions.map(({ app }) => app);\n const verb = names.length === 1 ? \"is not picked but ships too\" : \"are not picked but ship too\";\n output.line(` ${paint([\"bold\", \"yellow\"], \"!\")} ${paint(\"bold\", `${listed(names)} ${verb}:`)}`);\n companions.forEach(({ app, version, why }) => {\n const packageName = release.units.find(({ name }) => name === app)?.packageName;\n const waiting = split.waits.filter(({ releases }) =>\n releases.some(({ name }) => name === packageName),\n ).length;\n const own = waiting > 0 ? ` · picking it ships its ${plural(waiting, \"changeset\")} too` : \"\";\n output.line(` ${app.padEnd(11)}${version.padEnd(20)}${paint(\"dim\", `${why}${own}`)}`);\n });\n output.line();\n};\n\n/** The table a person reads before anything is written: each unit, its move, what ships. */\nexport const printSummary = (context: ReleaseContext, prepared: Prepared) => {\n const { output, release } = context;\n const { bumps, packages, pending, held, unreleased, contributions, companions } = prepared;\n const dot = paint(\"dim\", \"·\");\n const stays = held.filter((app) => !bumps.some((bump) => bump.app === app));\n const heldLabel = stays.length > 0 ? ` ${dot} ${stays.join(\", \")} held` : \"\";\n const where = environmentLabel(\n context,\n bumps.map(({ app }) => app),\n \"preview\",\n );\n output.line();\n output.line(\n ` ${paint(\"bold\", \"Release\")} ${dot} ${where} ${dot} ${plural(pending, \"changeset\")}${heldLabel}`,\n );\n output.line();\n // The unit column fits the longest name, as status does.\n const width = Math.max(13, ...release.units.map(({ name }) => name.length)) + 2;\n output.line(\n paint(\n \"dim\",\n ` ${\"Unit\".padEnd(width)}${\"Version\".padEnd(20)}${where === \"live\" ? \"Ships live\" : \"Ships to preview\"}`,\n ),\n );\n release.units.forEach((unit) => {\n const bump = bumps.find(({ app }) => app === unit.name);\n const version = bump ? `${bump.from} → ${bump.to}` : unit.version;\n const left = unreleased.find(({ app }) => app === unit.name);\n const ships = (() => {\n if (held.includes(unit.name) && !bump)\n return paint(\"yellow\", \"⏸ held, its changesets stay pending\");\n if (left && !bump) {\n return paint(\n \"yellow\",\n `! ${plural(left.commits.length, \"commit\")} since ${left.version}, no changeset: not in this release`,\n );\n }\n const contributed = contributions[unit.name]?.summary;\n if (contributed && contributed.length > 0)\n return contributed.join(`\\n ${\" \".repeat(width + 20)}`);\n if (!bump) return paint(\"dim\", \"– nothing changed\");\n const along = companions.some(({ app }) => app === unit.name)\n ? paint(\"yellow\", \" not picked, goes along\")\n : \"\";\n return `${paint(\"green\", \"↑ ship\")} ${paint(\"dim\", moduleOf(context, unit)?.provider ?? \"\")}${along}`;\n })();\n output.line(` ${unit.name.padEnd(width)}${version.padEnd(20)}${ships}`);\n });\n if (packages > 0) {\n output.line(\n ` ${\"packages\".padEnd(width)}${`${packages} bumped`.padEnd(20)}${paint(\"dim\", \"changelogs only, nothing published\")}`,\n );\n }\n output.line();\n printCompanions(context, prepared);\n};\n\n/**\n * Versions what `prepared` covers on one branch from main, opens its PR, and goes back to main.\n * Null, with what to do, when it must not run.\n */\nexport const openReleasePr = async (\n context: ReleaseContext,\n prepared: Prepared,\n /** Release PRs this one takes the place of, named at the top of its description. */\n replaces: readonly OpenPr[] = [],\n): Promise<OpenPr[] | null> => {\n const { output, services, clock } = context;\n printSummary(context, prepared);\n const blocked = Object.values(prepared.contributions).find((entry) => entry.blocked)?.blocked;\n if (blocked) {\n fail(context, blocked.title, blocked.detail, blocked.commands);\n return null;\n }\n const source = releaseSource(\"build\", \"preview\", await services.sourceControl.position());\n if (!source.allowed) {\n fail(\n context,\n source.why === \"not-main\" ? \"Not from main\" : \"main is behind origin\",\n \"a release versions what is merged.\",\n [\"git switch main\", \"git pull\", \"shiplane\"],\n );\n return null;\n }\n if (!(await services.sourceControl.isClean())) {\n fail(\n context,\n \"Uncommitted changes\",\n \"commit or stash them first, the release PR commits every change.\",\n );\n return null;\n }\n const kindOf: KindOf = (app) => {\n const unit = context.release.units.find(({ name }) => name === app);\n return unit && moduleOf(context, unit)?.kind;\n };\n const groups = prGroupsOf(context, prepared);\n const titles = groups.map((group) => releaseTitle(group, kindOf));\n const planned = [\n groups.length > 1\n ? `Open ${groups.length} release PRs from main, one per app, then wait for you to squash merge each:\\n${titles\n .map((title) => ` ${title}`)\n .join(\"\\n\")}`\n : \"Open the release PR, then wait for you to squash merge it\",\n \"Tag each version and publish its release notes\",\n ...Object.values(prepared.contributions).flatMap(({ step }) => (step ? [step] : [])),\n ];\n output.line(paint(\"dim\", \" Steps\"));\n planned.forEach((step, index) => output.line(` ${index + 1}. ${step}`));\n output.line();\n const where = environmentLabel(\n context,\n prepared.bumps.map(({ app }) => app),\n \"preview\",\n );\n if (\n !(await confirm(context, `Release these ${where === \"live\" ? \"live\" : \"to preview\"}?`, true))\n ) {\n output.line(paint(\"dim\", \"Nothing ran.\"));\n return null;\n }\n const now = clock.now();\n const prs: OpenPr[] = [];\n for (const group of groups) {\n const apps = new Set(group.map(({ app }) => app));\n const scoped =\n groups.length > 1 ? await prepareRelease(context, apps, prepared.contributions) : prepared;\n const [first] = group;\n const branch = `${releaseBranchName(now)}${groups.length > 1 && first ? `-${first.app}` : \"\"}`;\n const pr = await openOne(context, scoped, kindOf, branch, replaces);\n if (!pr) {\n if (prs.length > 0) {\n output.line(\n paint(\n \"dim\",\n ` ${listed(prs.map(({ number }) => `#${number}`))} stay open: merge them, then run shiplane for the rest.`,\n ),\n );\n }\n return null;\n }\n prs.push(pr);\n }\n return prs;\n};\n\n/**\n * The apps each release PR takes: one PR per app, a family as one. Apps one changeset names or\n * one moving with the other share a PR. A release moving internal packages stays one PR: their\n * changelog lines have no app to go with.\n */\nconst prGroupsOf = ({ release }: ReleaseContext, prepared: Prepared) => {\n if (prepared.packages > 0) return [prepared.bumps];\n const appOf = (packageName: string) =>\n release.units.find((unit) => unit.packageName === packageName)?.name;\n const linked = [\n ...prepared.shipped.map(({ releases }) => releases.map(({ name }) => appOf(name) ?? name)),\n ...prepared.bumps.map(({ app, movedWith }) => [\n app,\n ...movedWith.map((name) => appOf(name) ?? name),\n ]),\n ];\n return releasePrGroups(prepared.bumps, linked);\n};\n\n/** The line a release PR opens with when it takes the place of release PRs main moved past. */\nconst replacedLine = (replaces: readonly OpenPr[]) =>\n replaces.length === 0\n ? \"\"\n : `Replaces ${listed(replaces.map(({ number }) => `#${number}`))}, which went out of date when main moved.\\n\\n`;\n\n/** Versions `prepared` on `branch` from main, opens its PR, and goes back to main. */\nconst openOne = async (\n context: ReleaseContext,\n prepared: Prepared,\n kindOf: KindOf,\n branch: string,\n replaces: readonly OpenPr[],\n): Promise<OpenPr | null> => {\n const { services } = context;\n const title = releaseTitle(prepared.bumps, kindOf);\n // A title naming more apps than a header holds skips the commit hooks (commitlint's 100\n // characters) for this commit only.\n const skipHooks = !titleFits(title);\n const created: { pr?: OpenPr } = {};\n const done = await runSteps(context, [\n branchStep(context, branch),\n {\n label: \"versions and changelogs\",\n run: () => services.versioning.apply(prepared.added, prepared.split.waits),\n },\n ...Object.values(prepared.contributions).flatMap(({ writes }) => writes),\n {\n label: `commit \"${title}\"`,\n run: async () =>\n services.sourceControl.commit(\n await services.sourceControl.changedFiles(),\n title,\n releaseCommitBody(prepared.bumps) || undefined,\n { skipHooks },\n ),\n },\n pushStep(context, branch),\n openPrStep(context, \"open the release pull request\", async () => {\n created.pr = await services.codeHost.createPr({\n base: \"main\",\n head: branch,\n title,\n body:\n replacedLine(replaces) + releasePrBody(prepared.bumps, shipsOnMerge(context, prepared)),\n label: \"type: chore\",\n });\n return created.pr;\n }),\n { label: \"back to main\", run: () => services.sourceControl.switchTo(\"main\") },\n ]);\n return done && created.pr ? created.pr : null;\n};\n","import type { Environment } from \"./environment\";\n\n/** A unit whose live state its own platform knows, not GitHub Deployments: EAS for a mobile app. */\nexport interface DecidedBy {\n /** Who decides, as a person reads it: \"EAS\". */\n platform: string;\n /** What it decides between: \"build or update\". */\n choice: string;\n /** The command that shows its state: \"shiplane status\". */\n check: string;\n}\n\nexport interface ScopeInfo {\n /** The unit's name. */\n app: string;\n version: string;\n /** Pending changesets naming it. */\n changesets: number;\n /** Commits since its current version, when no changeset names it. */\n commits: number;\n /** Its current version has a release tag. */\n tagged: boolean;\n /** A merged release PR brought its current version: untagged, that release is unfinished. */\n versioned: boolean;\n /** No version of it was ever tagged, and a commit brought its version: its first release. */\n firstRelease?: boolean;\n /** GitHub Deployments record that version on the channel being released. */\n onChannel: boolean;\n /** ...and on preview, which production promotes from. */\n onPreview: boolean;\n decidedBy?: DecidedBy;\n /** Nothing deploys it: once tagged, every environment has it. */\n releaseOnly?: boolean;\n}\n\nexport interface ScopeChoice {\n app: string;\n /** Something to release: offered and ticked. Otherwise shown greyed, with why. */\n pending: boolean;\n hint: string;\n}\n\nconst plural = (count: number, word: string) => `${count} ${word}${count === 1 ? \"\" : \"s\"}`;\n\nconst previewChoice = ({\n version,\n changesets,\n commits,\n tagged,\n versioned,\n firstRelease,\n onChannel,\n decidedBy,\n releaseOnly,\n}: ScopeInfo) => {\n const later = decidedBy ? ` · ${decidedBy.platform} decides ${decidedBy.choice} once picked` : \"\";\n if (changesets > 0) return { pending: true, hint: `${plural(changesets, \"changeset\")}${later}` };\n if (commits > 0) {\n return {\n pending: true,\n hint: `${plural(commits, \"commit\")} since ${version}, changelog from its commits${later}`,\n };\n }\n if (!tagged) {\n if (versioned) return { pending: true, hint: `${version} versioned, not tagged yet${later}` };\n return firstRelease\n ? { pending: true, hint: `${version} first release${later}` }\n : { pending: false, hint: \"nothing new\" };\n }\n if (releaseOnly) return { pending: false, hint: `${version} released, nothing deploys it` };\n // Its builds and updates live on its platform, not in GitHub Deployments: the check reads them.\n if (decidedBy) {\n return {\n pending: false,\n hint: `${version} released, nothing new (${decidedBy.check} shows its builds)`,\n };\n }\n return onChannel\n ? { pending: false, hint: `${version} is on preview, nothing new` }\n : { pending: true, hint: `${version} released, not on preview yet` };\n};\n\nconst productionChoice = ({\n version,\n tagged,\n onChannel,\n onPreview,\n decidedBy,\n releaseOnly,\n}: ScopeInfo) => {\n if (!tagged) return { pending: false, hint: \"not released yet\" };\n if (releaseOnly) return { pending: false, hint: `${version} released, nothing deploys it` };\n if (decidedBy) {\n return {\n pending: true,\n hint: `${version} released, ${decidedBy.platform} decides once picked`,\n };\n }\n if (onChannel) return { pending: false, hint: `${version} is on production, nothing new` };\n return onPreview\n ? { pending: true, hint: `${version} is on preview, promotes it` }\n : { pending: false, hint: `${version} is not on preview yet: release it there first` };\n};\n\n/** The first question: which units have something to release here, and why not the rest. */\nexport const scopeChoices = (apps: ScopeInfo[], channel: Environment): ScopeChoice[] =>\n apps.map((info) => ({\n app: info.app,\n ...(channel === \"production\" ? productionChoice(info) : previewChoice(info)),\n }));\n","import type { Environment } from \"../domain/environment\";\nimport type { ScopeInfo } from \"../domain/scope\";\nimport type { ReleaseContext } from \"./context\";\nimport { scopeChoices } from \"../domain/scope\";\nimport { readScope } from \"./readScope\";\nimport { paint } from \"./say\";\n\n/** Every unit with something to release here: what --yes and a run without a terminal cover. */\nexport const defaultScope = (info: ScopeInfo[], environment: Environment) =>\n new Set(\n scopeChoices(info, environment)\n .filter(({ pending }) => pending)\n .map(({ app }) => app),\n );\n\n/**\n * The first question: which units this run covers. Every unit is listed; those with nothing to\n * release are greyed out with why. Null when cancelled or when nothing is pending.\n */\nexport const pickScope = async (\n context: ReleaseContext,\n environment: Environment,\n): Promise<{ scope: Set<string>; info: ScopeInfo[] } | null> => {\n const { output, prompter, options, progress } = context;\n const info = await progress.during(\n \"Reading what changed: changesets, commits, tags and GitHub deployments\",\n \"thinking\",\n () => readScope(context, environment),\n );\n const choices = scopeChoices(info, environment);\n if (!choices.some(({ pending }) => pending)) {\n output.line();\n choices.forEach(({ app, hint }) =>\n output.line(` ${paint(\"dim\", `${app.padEnd(15)}${hint}`)}`),\n );\n output.line();\n progress.say(\n \"resting\",\n `${paint(\"bold\", `Nothing to release to ${environment}.`)} ${paint(\"dim\", environment === \"preview\" ? \"Queue a change first:\" : \"Release to preview first:\")}`,\n );\n output.line(` ${paint(\"cyan\", environment === \"preview\" ? \"pnpm changeset\" : \"shiplane\")}`);\n output.line();\n return null;\n }\n if (options.yes || !prompter.interactive) return { scope: defaultScope(info, environment), info };\n const picked = await prompter.multiselect(\n `What do you want to release to ${environment}? Greyed units have nothing to release.`,\n choices.map(({ app, pending, hint }) => ({ value: app, label: app, hint, disabled: !pending })),\n choices.filter(({ pending }) => pending).map(({ app }) => app),\n );\n return picked ? { scope: new Set(picked), info } : null;\n};\n","import type { FollowUp, Shipped } from \"../modules/module\";\nimport type { ReleaseContext } from \"./context\";\nimport { paint } from \"./say\";\nimport { afterShipContext } from \"./targets\";\n\nconst reasonOf = (error: unknown) => (error instanceof Error ? error.message : String(error));\n\n/** What every feature asks for once these apps ship, in order. One that cannot read is said, then skipped. */\nconst followUpsOf = async (context: ReleaseContext, shipped: readonly Shipped[]) => {\n const all: FollowUp[] = [];\n if (shipped.length === 0) return all;\n for (const feature of context.release.features) {\n try {\n const asked = await context.progress.during(\n `${feature.name}: reading what to follow up`,\n \"thinking\",\n () => feature.afterShip(afterShipContext(context), shipped),\n );\n all.push(...asked);\n } catch (error) {\n context.output.line(\n ` ${paint(\"yellow\", \"!\")} ${feature.name} ${paint(\"dim\", `could not read: ${reasonOf(error)}`)}`,\n );\n }\n }\n return all;\n};\n\n/** Runs what the features ask for once units shipped. A failure is said and never fails the release. */\nexport const runFollowUps = async (context: ReleaseContext, shipped: readonly Shipped[]) => {\n for (const { label, run } of await followUpsOf(context, shipped)) {\n try {\n await run();\n context.output.line(` ${paint(\"green\", \"✓\")} ${label}`);\n } catch (error) {\n context.output.line(` ${paint(\"yellow\", \"!\")} ${label} ${paint(\"dim\", reasonOf(error))}`);\n }\n }\n};\n\n/** What the features would do once these units ship, run nothing. */\nexport const planFollowUps = async (context: ReleaseContext, shipped: readonly Shipped[]) => {\n const all = await followUpsOf(context, shipped);\n if (all.length === 0) return;\n context.output.line();\n context.output.line(` ${paint(\"bold\", \"Then\")} ${paint(\"dim\", \"once shipped\")}`);\n all.forEach(({ label }) => context.output.line(` ${label}`));\n};\n","import type { Environment } from \"../domain/environment\";\nimport type { Shipped } from \"../modules/module\";\nimport type { ReleaseContext } from \"./context\";\nimport { tagName } from \"../domain/tags\";\nimport { planFollowUps } from \"./followUps\";\nimport { releaseOrder } from \"./releaseOrder\";\nimport { paint } from \"./say\";\nimport { commandLine, jobInput, moduleOf, shipPlanOf } from \"./targets\";\n\n/**\n * `shiplane plan`: every command shipping the current tags would run, both ways, in release order,\n * then what the features would do. It runs nothing and asks nothing; it reads git, and the code host\n * for features.\n */\nexport const planShips = async (context: ReleaseContext, environment: Environment) => {\n const { release, services, output } = context;\n const { head } = await services.sourceControl.position();\n output.line();\n output.line(\n ` ${paint(\"bold\", \"Plan\")} ${paint(\"dim\", \"·\")} ${environment} ${paint(\"dim\", \"· nothing runs\")}`,\n );\n output.line(` ${paint(\"bold\", \"Order\")} ${releaseOrder(release.units)}`);\n const shipped: Shipped[] = [];\n for (const unit of release.units) {\n const module = moduleOf(context, unit);\n if (!module) continue;\n const tag = tagName(unit.name, unit.version, context.release.tagFormat);\n const tagged = (await services.sourceControl.tagCommit(tag)) !== null;\n if (tagged && !module.releaseOnly) shipped.push({ unit, tag, environment });\n const plan = shipPlanOf(\n context,\n module,\n jobInput(context, module, unit, { tag, environment, commit: head }),\n );\n output.line();\n output.line(\n ` ${paint(\"bold\", tag)} → ${plan.where}${tagged ? \"\" : paint(\"yellow\", \" (not tagged yet: release first)\")}`,\n );\n plan.jobs.forEach((job) => {\n output.line(` ${paint(\"dim\", \"this machine\")}`);\n job.local.forEach((command) => output.line(` ${commandLine(command)}`));\n if (job.record)\n output.line(\n ` ${paint(\"dim\", `then record ${tag} on ${environment} in GitHub Deployments`)}`,\n );\n if (job.ci) {\n const workflow = services.ciPipeline.shipWorkflow;\n output.line(` ${paint(\"dim\", \"GitHub Actions\")}`);\n output.line(\n ` gh workflow run ${workflow} --ref ${job.ci.ref} -f units=${unit.name} -f environment=${environment}`,\n );\n }\n });\n }\n await planFollowUps(context, shipped);\n output.line();\n};\n","import type { ActionsMinutes } from \"../domain/budget\";\nimport type { DeployPath, ShipItem } from \"../domain/deploys\";\nimport type { Environment } from \"../domain/environment\";\nimport type { ReleaseContext } from \"./context\";\nimport { deployEstimate, minutesBudget } from \"../domain/budget\";\nimport { fail, paint } from \"./say\";\n\nexport interface Shipment {\n item: ShipItem;\n /** The workflow its jobs dispatch on GitHub Actions, if any. */\n workflows: string[];\n typicalMinutes: number | undefined;\n}\n\nexport const PATH_LABEL: Record<DeployPath, string> = {\n github: \"GitHub Actions\",\n local: \"this machine\",\n};\n\n/** The minutes block above the question: status, what is left, this release shaded in, the pace. */\nconst showMinutes = (\n { output, clock }: ReleaseContext,\n budget: ActionsMinutes,\n estimate: ReturnType<typeof deployEstimate>,\n) => {\n const drawn = minutesBudget(budget, clock.now(), 30, estimate.total);\n output.line();\n output.line(` ${paint(\"bold\", drawn.title)} ${paint([\"bold\", drawn.tone], drawn.status)}`);\n output.line(` ${paint(drawn.tone, drawn.bar)} ${paint([\"bold\", drawn.tone], drawn.amount)}`);\n if (drawn.after) {\n output.line(` ${drawn.after}`);\n const each = estimate.lines.map(\n ({ app, minutes, measured }) =>\n `${app} ~${minutes} ${measured ? \"(its last runs)\" : \"(typical, no run yet)\"}`,\n );\n output.line(` ${paint(\"dim\", ` ${each.join(\" · \")}`)}`);\n }\n output.line(` ${paint(\"dim\", drawn.pace)}`);\n output.line();\n};\n\n/**\n * How each unit ships, asked one by one with this month's Actions minutes shown once: GitHub Actions\n * or this machine, in the order given. Null when cancelled or without a terminal to ask.\n */\nexport const askPaths = async (\n context: ReleaseContext,\n environment: Environment,\n shipments: readonly Shipment[],\n): Promise<DeployPath[] | null> => {\n const { services, prompter, clock } = context;\n const measured = Object.fromEntries(\n await Promise.all(\n shipments.map(async ({ item, workflows }) => [\n item.app,\n (\n await Promise.all(\n workflows.map((workflow) => services.ciPipeline.measuredMinutes(workflow)),\n )\n ).flat(),\n ]),\n ),\n );\n const typical = Object.fromEntries(\n shipments.flatMap(({ item, typicalMinutes }) =>\n typicalMinutes === undefined ? [] : [[item.app, typicalMinutes]],\n ),\n );\n const estimate = deployEstimate(\n shipments.map(({ item }) => item),\n measured,\n typical,\n );\n const budget = await services.ciPipeline.minutes();\n if (budget) showMinutes(context, budget, estimate);\n if (!prompter.interactive) {\n fail(context, \"Not a terminal\", \"say how to ship.\", [\n \"shiplane ship --via github\",\n \"shiplane ship --via local\",\n ]);\n return null;\n }\n const low =\n budget !== null && minutesBudget(budget, clock.now(), 30, estimate.total).tone === \"red\";\n const paths: DeployPath[] = [];\n for (const { item } of shipments) {\n const minutes = estimate.lines.find(({ app }) => app === item.app)?.minutes;\n const path = await prompter.select<DeployPath>(\n `How should ${item.tag} ship to ${environment}?`,\n [\n {\n value: \"github\",\n label: PATH_LABEL.github,\n hint: budget\n ? `runs on GitHub from its tag, about ${minutes} of ${budget.left.toLocaleString(\"en-US\")} minutes left`\n : \"its workflow runs on GitHub, from its tag\",\n },\n {\n value: \"local\",\n label: PATH_LABEL.local,\n hint: \"the same commands, run here: no Actions minutes\",\n },\n ],\n low ? \"local\" : \"github\",\n );\n if (!path) return null;\n paths.push(path);\n }\n return paths;\n};\n","import type { MergeMethod, OpenPr, WaitAction } from \"../domain/releasePr\";\nimport type { ReleaseContext } from \"./context\";\nimport { mergeChoices, waitKey } from \"../domain/releasePr\";\nimport { fail, keyHints, paint } from \"./say\";\n\nconst POLL_MS = 15_000;\n\n/** How a wait for the release PR ends: merged, closed on the host, or left to a later run. */\nexport type WaitOutcome = \"merged\" | \"closed\" | \"left\";\n\n/** Merges the pull request with the method the person picks. GitHub refuses approving your own PR. */\nconst mergeHere = async (context: ReleaseContext, pr: OpenPr) => {\n const { choices, initial } = mergeChoices(await context.services.codeHost.mergeMethods());\n if (choices.length === 0) {\n fail(context, \"No merge method\", \"the repository allows none: merge it on GitHub.\");\n return;\n }\n const method = await context.prompter.select<MergeMethod | \"no\">(\n `Merge #${pr.number} into main?`,\n [...choices, { value: \"no\", label: \"Not now\" }],\n initial,\n );\n if (!method || method === \"no\") {\n context.output.line(paint(\"dim\", \" Not merged.\"));\n return;\n }\n await context.services.codeHost.merge(pr, method);\n};\n\nconst ACTIONS: Record<WaitAction, (context: ReleaseContext, pr: OpenPr) => Promise<void>> = {\n diff: (context, pr) => context.services.codeHost.showDiff(pr),\n merge: mergeHere,\n open: (context, pr) => context.services.codeHost.openInBrowser(pr),\n};\n\n/** The keys a wait offers. Someone else approves a release that requires it: no merge from here. */\nconst hintsFor = (approvalRequired: boolean) => [\n { key: \"d\", label: \"see the diff\" },\n ...(approvalRequired ? [] : [{ key: \"m\", label: \"merge it from here\" }]),\n { key: \"o\", label: \"open it on GitHub\" },\n { key: \"Ctrl-C\", label: \"leave, continue later\" },\n];\n\n/**\n * Polls the host until the PR merges or closes; in a terminal the person can also read the diff\n * (d), merge from here (m, unless approval is required) or open it in the browser (o). Without a\n * terminal, a release waiting on someone's approval is left for a later run instead.\n */\nexport const waitForMerge = async (context: ReleaseContext, pr: OpenPr): Promise<WaitOutcome> => {\n const { output, prompter, services } = context;\n const approvalRequired = context.release.flow.approval === \"required\";\n output.line(` ${paint(\"green\", \"✓\")} Release PR ${paint(\"cyan\", pr.url)}`);\n if (approvalRequired) {\n output.line(` Waiting for approval on #${pr.number}. This can take a while.`);\n output.line(paint(\"dim\", \" It's safe to leave: run shiplane later and it picks up here.\"));\n } else {\n output.line(\n paint(\n \"dim\",\n \" Review and merge it here or on GitHub; this carries on by itself once merged.\",\n ),\n );\n }\n if (approvalRequired && !prompter.interactive) {\n const state = await services.codeHost.prState(pr).catch(() => \"OPEN\" as const);\n if (state === \"OPEN\") return \"left\";\n return state === \"MERGED\" ? \"merged\" : \"closed\";\n }\n const hints = hintsFor(approvalRequired);\n if (prompter.interactive) {\n output.line();\n output.line(` ${keyHints(hints)}`);\n }\n output.line();\n const keys = prompter.interactive\n ? hints.map(({ key }) => key).filter((key) => key.length === 1)\n : [];\n for (;;) {\n const state = await services.codeHost.prState(pr).catch(() => \"OPEN\" as const);\n if (state !== \"OPEN\") return state === \"MERGED\" ? \"merged\" : \"closed\";\n const key = await prompter.waitForKey(\n approvalRequired\n ? `Waiting for #${pr.number} to be approved and merged`\n : `Waiting for #${pr.number} to merge`,\n POLL_MS,\n keys,\n );\n const action = key && keys.includes(key) ? waitKey(key) : null;\n if (action) await ACTIONS[action](context, pr);\n }\n};\n","import type { OpenPr } from \"../domain/releasePr\";\nimport type { Decision } from \"../ports/delivery.port\";\nimport type { ReleaseContext } from \"./context\";\nimport { confirm, fail, paint } from \"./say\";\nimport { branchStep, openPrStep, pushStep, runSteps } from \"./steps\";\nimport { waitForMerge } from \"./waitForMerge\";\n\ntype PullRequest = Extract<Decision, { action: \"pull-request\" }>;\n\n/**\n * A small PR a plugin needs merged before it ships, such as production's version moving: branch,\n * write, commit, push, open, back to main, wait for the merge, pull. `declined` when the person\n * said no.\n */\nexport const pullRequestFirst = async (\n context: ReleaseContext,\n request: PullRequest,\n): Promise<\"merged\" | \"declined\" | \"failed\"> => {\n const { output, services } = context;\n if (!(await confirm(context, request.question))) {\n output.line(paint(\"dim\", \" Not now.\"));\n return \"declined\";\n }\n const created: { pr?: OpenPr } = {};\n const opened = await runSteps(context, [\n branchStep(context, request.branch),\n {\n label: `commit \"${request.title}\"`,\n run: async () => {\n await request.write();\n for (const changeset of request.changesets) await services.versioning.write(changeset);\n await services.sourceControl.commit(\n await services.sourceControl.changedFiles(),\n request.title,\n );\n },\n },\n pushStep(context, request.branch),\n openPrStep(context, \"open the pull request\", async () => {\n created.pr = await services.codeHost.createPr({\n base: \"main\",\n head: request.branch,\n title: request.title,\n body: request.body,\n label: \"type: chore\",\n });\n return created.pr;\n }),\n { label: \"back to main\", run: () => services.sourceControl.switchTo(\"main\") },\n ]);\n const { pr } = created;\n if (!opened || !pr) return \"failed\";\n output.line();\n if (!(await waitForMerge(context, pr))) {\n fail(context, `#${pr.number} was closed without a merge`, \"nothing shipped.\", [\"shiplane\"]);\n return \"failed\";\n }\n const pulled = await runSteps(context, [\n { label: \"pull main\", run: () => services.sourceControl.pull() },\n ]);\n return pulled ? \"merged\" : \"failed\";\n};\n","import type { DeployPath, WebShip } from \"../domain/deploys\";\nimport type { Environment } from \"../domain/environment\";\nimport type { ReleaseUnit } from \"../domain/unit\";\nimport type { AppInput, ReleaseModule } from \"../modules/module\";\nimport type { Deploy } from \"../ports/code-host.port\";\nimport type { Decision, Job } from \"../ports/delivery.port\";\nimport type { Shipment } from \"./askPath\";\nimport type { ReleaseContext } from \"./context\";\nimport { onlyVersionFiles, shipsFrom, webShip } from \"../domain/deploys\";\nimport { tagName } from \"../domain/tags\";\nimport { askPaths, PATH_LABEL } from \"./askPath\";\nimport { runFollowUps } from \"./followUps\";\nimport { pullRequestFirst } from \"./pullRequestFirst\";\nimport { deployedOn } from \"./readScope\";\nimport { confirm, fail, paint } from \"./say\";\nimport {\n decideContext,\n dispatchShip,\n environmentLabel,\n jobInput,\n moduleOf,\n runHere,\n shipPlanOf,\n versionFiles,\n} from \"./targets\";\n\ntype Kind = Extract<Decision, { action: \"ship\" }>[\"kind\"];\n\ninterface Ready {\n unit: ReleaseUnit;\n module: ReleaseModule;\n input: AppInput;\n kind: Kind;\n jobs: Job[];\n /** Its module decided for itself: the moved-past check is already its own. */\n decided: boolean;\n /** Why this machine cannot ship it, as its module decided. */\n notLocal: string | null;\n}\n\n/** Builds and submits run on their own platform: a build asks only when a workflow can start it. */\nconst choosesPath = ({ kind, jobs }: Ready) =>\n kind === \"update\" || kind === \"deploy\" || (kind === \"build\" && jobs.every(({ ci }) => ci));\n\nconst WEB_STATUS: Record<Exclude<WebShip, \"deploy\">, string> = {\n deploying: \"deploying already\",\n shipped: \"already there\",\n \"not-on-preview\": \"not on preview yet: ship it there first\",\n};\n\n/** A web unit decides from GitHub Deployments, which a ship records once it rolled out. */\nconst webDecision = (\n context: ReleaseContext,\n module: ReleaseModule,\n input: AppInput,\n history: Deploy[],\n): Decision => {\n const { jobs } = shipPlanOf(context, module, input);\n const ship = webShip({\n environment: input.environment,\n run: deployedOn(history, input.tag, input.environment),\n onPreview: deployedOn(history, input.tag, \"preview\") === \"done\",\n });\n return ship === \"deploy\"\n ? { action: \"ship\", kind: \"deploy\", jobs }\n : { action: \"none\", status: WEB_STATUS[ship] };\n};\n\n/** Where a choice stands, then the person's pick: its jobs ship, or nothing does and it is held. */\nconst chosen = async (\n context: ReleaseContext,\n choice: Extract<Decision, { action: \"choose\" }>,\n): Promise<Extract<Decision, { action: \"ship\" | \"none\" }>> => {\n const { output, prompter } = context;\n output.line();\n choice.lines.forEach((line) => output.line(` ${line}`));\n output.line();\n const value = prompter.interactive\n ? await prompter.select(\n choice.question,\n choice.options.map(({ value, label, hint, disabled }) => ({\n value,\n label,\n hint,\n disabled,\n })),\n choice.suggested,\n )\n : null;\n const jobs = choice.options.find((option) => option.value === value)?.jobs ?? [];\n return jobs.length > 0\n ? { action: \"ship\", kind: \"update\", jobs }\n : { action: \"none\", status: choice.held };\n};\n\n/**\n * What every picked unit needs on the environment, in dispatch order, said as it goes. A module may\n * first need a small PR merged (a version moving): it opens, merges, and the module decides again.\n * Null when one of them refused.\n */\nconst decideAll = async (\n context: ReleaseContext,\n environment: Environment,\n scope: ReadonlySet<string> | undefined,\n): Promise<Ready[] | null> => {\n const { release, services, output } = context;\n const recorded = await services.codeHost.deployments().catch(() => []);\n const ready: Ready[] = [];\n for (const unit of release.units) {\n const module = moduleOf(context, unit);\n if ((scope && !scope.has(unit.name)) || !module) continue;\n const tag = tagName(unit.name, unit.version, context.release.tagFormat);\n if (!module.decide && !(await services.sourceControl.tagCommit(tag))) continue;\n const decide = async () => {\n const { head } = await services.sourceControl.position();\n const input = jobInput(context, module, unit, { tag, environment, commit: head });\n const decision = module.decide\n ? await module.decide(decideContext(context), input)\n : webDecision(context, module, input, recorded);\n return { input, decision };\n };\n let { input, decision } = await context.progress.during(\n `Checking what ${tag} needs on ${environment}`,\n \"thinking\",\n decide,\n );\n while (decision.action === \"pull-request\") {\n const merged = await pullRequestFirst(context, decision);\n if (merged === \"failed\") return null;\n if (merged === \"declined\") {\n decision = { action: \"none\", status: \"left for later\" };\n break;\n }\n ({ input, decision } = await decide());\n }\n if (decision.action === \"choose\") decision = await chosen(context, decision);\n if (decision.action === \"fail\") {\n fail(context, decision.title, decision.detail, decision.commands);\n return null;\n }\n if (decision.action === \"none\") {\n output.line(` ${paint(\"dim\", \"·\")} ${tag} ${paint(\"dim\", decision.status)}`);\n continue;\n }\n ready.push({\n unit,\n module,\n input,\n kind: decision.kind,\n jobs: decision.jobs,\n decided: module.decide !== undefined,\n notLocal: decision.notLocal ?? null,\n });\n }\n return ready;\n};\n\n/** Why a path cannot ship a unit, or null when it can. */\nconst blockedOn = async (\n context: ReleaseContext,\n path: DeployPath,\n { input, jobs, decided, notLocal }: Ready,\n): Promise<string | null> => {\n const { services } = context;\n if (path === \"github\") {\n const workflow = services.ciPipeline.shipWorkflow;\n for (const { ci } of jobs) {\n if (!ci) return \"only ships from this machine\";\n // GitHub runs the workflow file the ref holds.\n const file = `.github/workflows/${workflow}`;\n if ((await services.sourceControl.fileAt(ci.ref, file)) !== null) continue;\n const onMain =\n ci.ref !== \"main\" && (await services.sourceControl.fileAt(\"main\", file)) !== null;\n return onMain ? `predates ${workflow}` : `no ${workflow}`;\n }\n return null;\n }\n if (decided) return notLocal;\n const changed = await services.sourceControl.diffNames(input.tag, \"HEAD\");\n const sinceTagOnlyVersionFiles = onlyVersionFiles(changed, versionFiles(context));\n return shipsFrom(path, { sinceTagOnlyVersionFiles }) ? null : \"main moved past it\";\n};\n\nconst OTHER_PATH: Record<DeployPath, DeployPath> = { github: \"local\", local: \"github\" };\n\n/** What to do instead, when the path a person forced cannot ship a unit. */\nconst INSTEAD: Record<DeployPath, string> = {\n github: \"ship it from this machine\",\n local: \"this machine builds its checkout, ship it through GitHub Actions\",\n};\n\nconst TAKES: Record<DeployPath, string> = {\n github: \"ships through GitHub Actions\",\n local: \"ships from this machine\",\n};\n\n/**\n * The way a unit ships: the forced one when it can, the only one left when the other cannot, or\n * asked. Said whenever it is not asked.\n */\nconst routeOf = async (\n context: ReleaseContext,\n entry: Ready,\n forced: DeployPath | undefined,\n): Promise<DeployPath | \"ask\" | \"skip\" | \"stuck\"> => {\n const say = (mark: string, why: string) =>\n context.output.line(` ${mark} ${entry.input.tag} ${paint(\"dim\", why)}`);\n if (forced) {\n const why = await blockedOn(context, forced, entry);\n if (!why) return forced;\n say(paint(\"yellow\", \"!\"), `${why}: ${INSTEAD[forced]}`);\n return \"skip\";\n }\n const github = await blockedOn(context, \"github\", entry);\n const local = await blockedOn(context, \"local\", entry);\n if (github && local) {\n say(paint(\"red\", \"✗\"), `${github}, and ${local}: nothing can ship it`);\n return \"stuck\";\n }\n const blocked = github ? \"github\" : local ? \"local\" : null;\n if (!blocked) return \"ask\";\n say(paint(\"dim\", \"·\"), `${github ?? local}: ${TAKES[OTHER_PATH[blocked]]}`);\n return OTHER_PATH[blocked];\n};\n\nconst shipmentOf =\n (shipWorkflow: string) =>\n ({ unit, module, input, jobs }: Ready): Shipment => ({\n item: { app: unit.name, tag: input.tag, kind: \"deploy\" },\n workflows: jobs.some(({ ci }) => ci) ? [shipWorkflow] : [],\n typicalMinutes: module.typicalMinutes,\n });\n\n/**\n * The ship workflow's runs: one per ref, each naming its units. A tag on main's commit runs from\n * main, so a release whose tags all sit there costs one run.\n */\nconst shipRuns = async ({ services }: ReleaseContext, entries: readonly Ready[]) => {\n const { originMain } = await services.sourceControl.position();\n const runs = new Map<string, string[]>();\n for (const { unit, jobs } of entries) {\n for (const { ci } of jobs) {\n if (!ci) continue;\n const commit =\n ci.ref === \"main\" ? originMain : await services.sourceControl.tagCommit(ci.ref);\n const ref = commit === originMain ? \"main\" : ci.ref;\n const units = runs.get(ref) ?? [];\n if (!units.includes(unit.name)) runs.set(ref, [...units, unit.name]);\n }\n }\n return [...runs.entries()].map(([ref, units]) => ({ ref, units }));\n};\n\n/** `Ship a through GitHub Actions`, or each tag with its way when they differ. */\nconst shipQuestion = (\n going: Ready[],\n paths: ReadonlyMap<Ready, DeployPath>,\n environment: string,\n context: ReleaseContext,\n) => {\n const label = environmentLabel(\n context,\n going.map(({ unit }) => unit.name),\n environment,\n );\n const used = [...new Set(going.flatMap((entry) => paths.get(entry) ?? []))];\n const [only] = used;\n const names = going\n .map((entry) => {\n const path = paths.get(entry);\n return used.length > 1 && path ? `${entry.input.tag} (${PATH_LABEL[path]})` : entry.input.tag;\n })\n .join(\", \");\n const how = used.length === 1 && only ? ` through ${PATH_LABEL[only]}` : \"\";\n return `Ship ${names} ${label === \"live\" ? \"live\" : `to ${label}`}${how}?`;\n};\n\n/**\n * Ships every picked unit its environment does not run yet, and returns once each one is\n * triggered: EAS builds and workflows go on on their own, a Fly deploy from here once rolled out.\n * Production asks for its name first. False on a failure.\n */\nexport const shipTo = async (\n context: ReleaseContext,\n environment: Environment,\n { scope, via }: { scope?: ReadonlySet<string>; via?: DeployPath },\n): Promise<boolean> => {\n const { output, prompter, options, services } = context;\n // On a runner, the person typed production before the dispatch that started it.\n if (environment === \"production\" && !options.ci) {\n if (options.yes) {\n fail(context, \"No --yes on production\", \"every production step asks a person.\", [\n \"shiplane ship --channel production\",\n ]);\n return false;\n }\n if (!(await prompter.typed('Type \"production\" to start:', \"production\"))) {\n output.line(paint(\"dim\", \"Nothing ran.\"));\n return false;\n }\n }\n const ready = await decideAll(context, environment, scope);\n if (!ready) return false;\n if (ready.length === 0) {\n context.progress.say(\"resting\", paint(\"dim\", `Nothing to ship to ${environment}.`));\n return true;\n }\n // On a CI runner, dispatching another workflow would pay for two: this runner ships.\n const forced = options.ci ? \"local\" : via;\n const paths = new Map<Ready, DeployPath>();\n const unanswered: Ready[] = [];\n // A picked unit nothing can ship fails the run, after the others shipped.\n let stuck = false;\n for (const entry of ready.filter(choosesPath)) {\n const route = await routeOf(context, entry, forced);\n if (route === \"ask\") unanswered.push(entry);\n else if (route === \"stuck\") stuck = true;\n else if (route !== \"skip\") paths.set(entry, route);\n }\n if (unanswered.length > 0) {\n const answers = await askPaths(\n context,\n environment,\n unanswered.map(shipmentOf(services.ciPipeline.shipWorkflow)),\n );\n if (!answers) {\n output.line(paint(\"dim\", \" Nothing shipped.\"));\n // Cancelled by the person is fine; no terminal to ask is a failure a script should see.\n return prompter.interactive;\n }\n unanswered.forEach((entry, index) => {\n const answer = answers[index];\n if (answer) paths.set(entry, answer);\n });\n }\n const going = ready.filter((entry) => !choosesPath(entry) || paths.has(entry));\n if (going.length === 0) return !stuck;\n const runsHere = going.some((entry) => paths.get(entry) === \"local\");\n if (runsHere && !(await services.sourceControl.isClean())) {\n fail(\n context,\n \"Uncommitted changes\",\n \"this machine ships its checkout: commit or stash them first.\",\n );\n return false;\n }\n if (\n !(await confirm(\n context,\n shipQuestion(going, paths, environment, context),\n environment === \"preview\",\n ))\n ) {\n // Production still asks for its name and decides each unit on its own rules.\n if (\n environment === \"preview\" &&\n prompter.interactive &&\n (await prompter.confirm(\"Ship to production instead?\"))\n ) {\n return shipTo(context, \"production\", { scope, via });\n }\n context.progress.say(\"resting\", paint(\"dim\", \"Nothing shipped.\"));\n return true;\n }\n const here = going.filter((entry) => paths.get(entry) !== \"github\");\n const jobs = here.flatMap((entry) => entry.jobs.map((job) => ({ entry, job })));\n const runs = await shipRuns(\n context,\n going.filter((entry) => paths.get(entry) === \"github\"),\n );\n const total = jobs.length + runs.length;\n for (const [index, { entry, job }] of jobs.entries()) {\n try {\n await context.progress.during(\n job.label,\n \"working\",\n () => runHere(context, job, entry.input),\n { index, total },\n );\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n fail(context, `${job.label} failed`, `${reason}, nothing after it ran.`);\n return false;\n }\n }\n const workflow = services.ciPipeline.shipWorkflow;\n for (const [index, run] of runs.entries()) {\n const label = `ship ${run.units.join(\", \")} from ${run.ref} (${workflow})`;\n try {\n await context.progress.during(\n label,\n \"working\",\n () => dispatchShip(context, run, environment),\n { index: jobs.length + index, total },\n );\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n fail(context, `${label} failed`, `${reason}, nothing after it ran.`);\n return false;\n }\n }\n const names = going.map(({ input }) => input.tag).join(\", \");\n output.line();\n context.progress.say(\n \"happy\",\n `${paint([\"bold\", \"green\"], \"✓ Triggered.\")} ${paint(\"dim\", `${names}, shipping to ${environment} on their own.`)}`,\n );\n await runFollowUps(\n context,\n going.map(({ unit, input }) => ({ unit, tag: input.tag, environment })),\n );\n if (runs.length > 0) {\n output.line(` ${paint(\"cyan\", \"gh run list --limit 5\")}`);\n }\n // A package has no channel to read, so status has nothing to show for one.\n if (going.some(({ module }) => module.kind !== \"published-package\")) {\n output.line(` ${paint(\"cyan\", `shiplane status --channel ${environment}`)}`);\n }\n output.line();\n return !stuck;\n};\n","import type { Released } from \"../domain/companions\";\nimport type { DeployPath } from \"../domain/deploys\";\nimport type { ReleaseContext } from \"./context\";\nimport { releasedTogether } from \"../domain/companions\";\nimport { scopeChoices } from \"../domain/scope\";\nimport { changelogSection, tagName } from \"../domain/tags\";\nimport { pickScope } from \"./pickScope\";\nimport { confirm, listed, paint } from \"./say\";\nimport { shipTo } from \"./ship\";\nimport { decideContext, jobInput, moduleOf } from \"./targets\";\n\nconst STAGES = [\"What to promote\", \"Ship\"] as const;\n\n/** Each unit's version on preview with its notes, read from its tag. */\nconst releasedVersions = async (\n { release, services }: ReleaseContext,\n apps: readonly string[],\n): Promise<Released[]> =>\n Promise.all(\n release.units\n .filter(({ name }) => apps.includes(name))\n .map(async ({ name, dir, version }) => {\n const changelog = await services.sourceControl.fileAt(\n tagName(name, version, release.tagFormat),\n services.versioning.changelogFile(dir),\n );\n return { app: name, version, notes: changelogSection(changelog ?? \"\", version) };\n }),\n );\n\n/**\n * Which units production gets: the person's pick, plus what preview only ever ran with it when they\n * accept. Offered ticked with why, never added silently. Null when cancelled.\n */\nexport const pickPromotion = async (context: ReleaseContext): Promise<Set<string> | null> => {\n const { output } = context;\n const picked = await pickScope(context, \"production\");\n if (!picked || picked.scope.size === 0) return null;\n const left = scopeChoices(picked.info, \"production\")\n .filter(({ app, pending }) => pending && !picked.scope.has(app))\n .map(({ app }) => app);\n if (left.length === 0) return picked.scope;\n const companions = await context.progress.during(\n \"Reading the notes of what preview runs, to see what went there together\",\n \"thinking\",\n async () =>\n releasedTogether(\n await releasedVersions(context, [...picked.scope]),\n await releasedVersions(context, left),\n ),\n );\n if (companions.length === 0) return picked.scope;\n const names = companions.map(({ app }) => app);\n const partners = [...new Set(companions.flatMap(({ with: partner }) => partner))];\n output.line();\n output.line(\n ` ${paint([\"bold\", \"yellow\"], \"!\")} ${paint(\"bold\", `Preview runs ${listed(names)} with what you picked:`)}`,\n );\n companions.forEach(({ app, version, why }) =>\n output.line(` ${app.padEnd(11)}${version.padEnd(10)}${paint(\"dim\", why)}`),\n );\n output.line();\n const versions = companions.map(({ app, version }) => `${app} ${version}`);\n const them = companions.length === 1 ? \"it\" : \"them\";\n if (\n await confirm(\n context,\n `Promote ${listed(versions)} too? Preview has only run ${them} with ${listed(partners)}.`,\n true,\n )\n ) {\n return new Set([...picked.scope, ...names]);\n }\n const promoted = picked.info\n .filter(({ app }) => partners.includes(app))\n .map(({ app, version }) => `${app} ${version}`);\n output.line(\n paint(\n \"dim\",\n ` ${listed(names)} ${companions.length === 1 ? \"stays\" : \"stay\"} on preview: production runs ${listed(promoted)} next to the ${listed(names)} it has.`,\n ),\n );\n return picked.scope;\n};\n\n/** How each picked unit does on preview, said; when one looks unwell, asks before going on. */\nconst previewLooksWell = async (context: ReleaseContext, scope: ReadonlySet<string>) => {\n const { output, release, services } = context;\n const { head } = await services.sourceControl.position();\n const reads = await context.progress.during(\n \"Reading how preview runs what you picked\",\n \"thinking\",\n () =>\n Promise.all(\n release.units\n .filter(({ name }) => scope.has(name))\n .map(async (unit) => {\n const module = moduleOf(context, unit);\n if (!module?.health) return [];\n const tag = tagName(unit.name, unit.version, context.release.tagFormat);\n const input = jobInput(context, module, unit, {\n tag,\n environment: \"preview\",\n commit: head,\n });\n const health = await module.health(decideContext(context), input).catch(() => null);\n return health ? [{ tag, ...health }] : [];\n }),\n ),\n );\n const healths = reads.flat();\n if (healths.length === 0) return true;\n output.line();\n healths.forEach(({ tag, ok, summary }) =>\n output.line(\n ` ${ok ? paint(\"green\", \"✓\") : paint([\"bold\", \"yellow\"], \"!\")} ${tag.padEnd(18)}${paint(\"dim\", summary)}`,\n ),\n );\n output.line();\n const unwell = healths.filter(({ ok }) => !ok);\n if (unwell.length === 0) return true;\n const reasons = unwell.map(({ tag, why }) => `${tag}: ${why ?? \"looks unwell\"}`);\n return confirm(context, `Promote anyway? ${reasons.join(\"; \")}.`, false);\n};\n\n/** Production, from what preview runs: every unit picked, its name typed, each step asked. */\nexport const promote = async (context: ReleaseContext, via: DeployPath | undefined) => {\n context.progress.stage(STAGES, 0);\n const scope = await pickPromotion(context);\n if (!scope) return true;\n if (!(await previewLooksWell(context, scope))) {\n context.output.line(paint(\"dim\", \" Nothing promoted.\"));\n return true;\n }\n context.progress.stage(STAGES, 1);\n return shipTo(context, \"production\", { scope, via });\n};\n","import type { ReleaseTag, TagCandidate } from \"../domain/tags\";\nimport type { ReleaseContext } from \"./context\";\nimport type { Step } from \"./steps\";\nimport { changelogSection, firstRelease, releaseTags } from \"../domain/tags\";\nimport { MANIFEST, namedUnits } from \"./readScope\";\nimport { confirm, paint } from \"./say\";\nimport { runSteps } from \"./steps\";\n\n/** The tags and release notes still missing for the versions merged release PRs brought. */\nexport const missingTags = async (context: ReleaseContext): Promise<ReleaseTag[]> => {\n const { release, services } = context;\n const [tags, notes, named] = await Promise.all([\n services.sourceControl.tags(),\n services.codeHost.releasedTags().catch(() => new Set<string>()),\n namedUnits(context),\n ]);\n const candidates = await Promise.all(\n release.units.map(async ({ name, dir, version }): Promise<TagCandidate[]> => {\n const commit = await services.sourceControl.versionCommit(dir, MANIFEST, version);\n // A unit a changeset names releases through its release PR, never as it stands.\n const first = !named.has(name) && firstRelease(name, version, tags, release.tagFormat);\n return commit ? [{ app: name, version, commit, first }] : [];\n }),\n );\n return releaseTags(candidates.flat(), tags, notes, release.tagFormat);\n};\n\nconst notesFor = async ({ release, services }: ReleaseContext, tag: ReleaseTag) => {\n const unit = release.units.find(({ name }) => name === tag.app);\n const changelog = unit\n ? await services.sourceControl.fileAt(tag.sha, services.versioning.changelogFile(unit.dir))\n : null;\n return changelogSection(changelog ?? \"\", tag.version);\n};\n\n/** Tags each version on the commit that brought it, pushes the tags, publishes their notes. */\nexport const tagRelease = async (context: ReleaseContext, tags: readonly ReleaseTag[]) => {\n if (tags.length === 0) return true;\n const { output, release, services } = context;\n const names = tags.map(({ tag }) => tag).join(\", \");\n output.line(` ${paint(\"bold\", \"Tags and release notes\")} ${paint(\"dim\", names)}`);\n if (!(await confirm(context, `Tag ${names} and publish their release notes?`, true))) {\n output.line(paint(\"dim\", \"Nothing ran.\"));\n return false;\n }\n const created = tags.filter(({ needsTag }) => needsTag);\n const steps: Step[] = [\n ...created.map((tag) => ({\n label: `tag ${tag.tag} on ${tag.sha.slice(0, 7)}`,\n run: async () =>\n services.sourceControl.tag(\n tag.tag,\n tag.sha,\n `${tag.tag}\\n\\n${await notesFor(context, tag)}`,\n ),\n // Kept here unpushed, the next run would take it for done and never push it.\n undo: {\n label: `delete the tag ${tag.tag} here`,\n run: () => services.sourceControl.deleteTag(tag.tag),\n byHand: () => [`git tag --delete ${tag.tag}`],\n },\n })),\n ...(created.length > 0\n ? [\n {\n label: \"push the tags\",\n run: () => services.sourceControl.pushTags(created.map(({ tag }) => tag)),\n // Once on origin, a tag is the release; the next run fetches it and publishes its notes.\n kept: {\n label: `${created.map(({ tag }) => tag).join(\", \")} ${created.length > 1 ? \"stay\" : \"stays\"} on origin`,\n byHand: () => [\"shiplane tag\"],\n },\n },\n ]\n : []),\n ...tags\n .filter(({ needsNotes }) => needsNotes)\n .map((tag) => ({\n label: `release notes for ${tag.tag}`,\n run: async () =>\n services.codeHost.createRelease(\n tag.tag,\n await notesFor(context, tag),\n tag.app === release.units[0]?.name,\n ),\n })),\n ];\n return runSteps(context, steps);\n};\n","import type { OpenPr } from \"../domain/releasePr\";\nimport type { ReleaseContext } from \"./context\";\nimport { nextStep, RELEASE_BRANCH_PREFIX } from \"../domain/releasePr\";\nimport { openReleasePr, printSummary } from \"./openReleasePr\";\nimport { pickScope } from \"./pickScope\";\nimport { prepareRelease } from \"./prepareRelease\";\nimport { preflight } from \"./requirements\";\nimport { listed, paint } from \"./say\";\nimport { shipTo } from \"./ship\";\nimport { runSteps } from \"./steps\";\nimport { missingTags, tagRelease } from \"./tagRelease\";\nimport { waitForMerge } from \"./waitForMerge\";\n\nconst plural = (count: number, word: string) => `${count} ${word}${count === 1 ? \"\" : \"s\"}`;\n\n/** The commits main gained since a release PR's branch, or none when the host did not say. */\nconst movedPast = async (context: ReleaseContext, pr: OpenPr, originMain: string) => {\n if (!pr.head) return [];\n return context.services.sourceControl.commitsBetween(pr.head, originMain).catch(() => []);\n};\n\n/** Why a stale release PR closed, said on it, so a reviewer landing there knows where to go. */\nconst closedComment = (replacement: readonly OpenPr[], subjects: readonly string[]) =>\n [\n `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.`,\n `Replaced by ${listed(replacement.map(({ number }) => `#${number}`))}, which versions everything merged so far. Please review that one.`,\n \"\",\n ...subjects.map((subject) => `- ${subject}`),\n ].join(\"\\n\");\n\n/**\n * Release PRs main moved past are replaced: a fresh one versions everything merged, then each\n * stale one closes with a comment pointing to it. The open ones, or null when that failed.\n */\nconst refreshStale = async (\n context: ReleaseContext,\n prs: OpenPr[],\n scope: ReadonlySet<string>,\n): Promise<OpenPr[] | null> => {\n const { originMain } = await context.services.sourceControl.position();\n const moved = await Promise.all(prs.map((pr) => movedPast(context, pr, originMain)));\n const subjects = [...new Set(moved.flat().map(({ subject }) => subject))];\n if (subjects.length === 0) return prs;\n const { output, progress } = context;\n const names = listed(prs.map(({ number }) => `#${number}`));\n progress.say(\n \"thinking\",\n `↻ Release ${names} is out of date: ${plural(subjects.length, \"commit\")} landed on main since.`,\n );\n output.line(paint(\"dim\", \" Replacing it so the changelog matches what ships.\"));\n const prepared = await prepareRelease(context, scope);\n const opened = await openReleasePr(context, prepared, prs);\n if (!opened) return null;\n for (const pr of prs)\n await context.services.codeHost.closePr(pr, closedComment(opened, subjects));\n output.line(\n ` ${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`,\n );\n return opened;\n};\n\nconst STAGES = [\"What to release\", \"Versions\", \"Release PR\", \"Merge\", \"Tags\", \"Ship\"] as const;\n\n/**\n * `release` on preview: the release PR, the wait for its merge, the tags, then the ship. It reads where things\n * stand first, so a run stopped anywhere picks up where it left off. False when something failed.\n */\nexport const releaseToPreview = async (context: ReleaseContext): Promise<boolean> => {\n const { output, services, progress } = context;\n const stage = (name: (typeof STAGES)[number]) => progress.stage(STAGES, STAGES.indexOf(name));\n stage(\"What to release\");\n const picked = await pickScope(context, \"preview\");\n if (!picked || picked.scope.size === 0) {\n progress.say(\"resting\", paint(\"dim\", \"Nothing ran.\"));\n return true;\n }\n if (!(await preflight(context, picked.scope))) return false;\n const covered = picked.info.filter(({ app }) => picked.scope.has(app));\n const [releasePrs, missing] = await progress.during(\n \"Looking for an open release PR and versions not tagged yet\",\n \"thinking\",\n () => Promise.all([services.codeHost.openPrsFrom(RELEASE_BRANCH_PREFIX), missingTags(context)]),\n );\n const step = nextStep({\n pending: covered.reduce((sum, { changesets }) => sum + changesets, 0),\n releasePrs,\n untagged: missing.length,\n unreleased: covered.filter(({ changesets, commits }) => changesets === 0 && commits > 0).length,\n });\n let prs: OpenPr[] = [];\n let current = context;\n if (step.step === \"release-pr\") {\n stage(\"Versions\");\n const prepared = await progress.during(\n \"Planning each app's version with changesets, and what its target ships\",\n \"thinking\",\n () => prepareRelease(context, picked.scope),\n );\n if (prepared.bumps.length === 0 && prepared.packages === 0) {\n printSummary(context, prepared);\n output.line(\n paint(\"dim\", \" Nothing to version for these units: the others wait for a later release.\"),\n );\n return true;\n }\n stage(\"Release PR\");\n const opened = await openReleasePr(context, prepared);\n if (!opened) return false;\n prs = opened;\n } else if (step.step === \"wait-merge\") {\n const fresh = await refreshStale(context, step.prs, picked.scope);\n if (!fresh) return false;\n if (fresh === step.prs) {\n const waiting = context.release.flow.approval === \"required\" ? \"approval\" : \"a merge\";\n progress.say(\n \"thinking\",\n `↻ Picking up release ${listed(fresh.map(({ number }) => `#${number}`))}: still waiting for ${waiting}`,\n );\n output.line(paint(\"dim\", \" To cancel it, close it on GitHub.\"));\n }\n prs = fresh;\n } else if (missing.length > 0) {\n progress.say(\"thinking\", `↻ Picking up a merged release`);\n output.line(\n paint(\"dim\", ` Left to do: tag ${plural(missing.length, \"version\")} → ship to preview`),\n );\n }\n if (prs.length > 0) stage(\"Merge\");\n for (const pr of prs) {\n output.line();\n const outcome = await waitForMerge(context, pr);\n if (outcome === \"closed\") {\n progress.say(\"resting\", `○ Release #${pr.number} was closed: nothing shipped.`);\n output.line(paint(\"dim\", \" Run shiplane to open a new release with everything pending.\"));\n return true;\n }\n if (outcome === \"left\") {\n output.line(paint(\"dim\", ` Left #${pr.number} waiting. Run shiplane once it's approved.`));\n return true;\n }\n progress.say(\"happy\", `${paint(\"green\", \"✓\")} Release PR #${pr.number} merged`);\n }\n if (prs.length > 0) {\n const pulled = await runSteps(context, [\n { label: \"switch to main\", run: () => services.sourceControl.switchTo(\"main\") },\n { label: \"pull main\", run: () => services.sourceControl.pull() },\n ]);\n if (!pulled) return false;\n current = { ...context, release: await context.load() };\n }\n const tags = prs.length > 0 ? await missingTags(current) : missing;\n if (tags.length > 0) stage(\"Tags\");\n if (!(await tagRelease(current, tags))) return false;\n stage(\"Ship\");\n // A unit the release took along unpicked is tagged with the rest, so it ships with them too.\n return shipTo(current, \"preview\", {\n scope: new Set([...picked.scope, ...tags.map(({ app }) => app)]),\n });\n};\n","/** A port a custom adapter fills: the flow's four, then the four ways an app is delivered. */\nexport interface CustomPort {\n /** `ciPipeline`: the key it takes in `releaseFlow`, or the module option. */\n key: string;\n /** `CiPipelinePort`. */\n type: string;\n /** \"CI pipeline\", as a person reads it. */\n label: string;\n kind: \"flow\" | \"delivery\";\n /** The contract's subject beyond `port`, or the settings a delivery contract runs with. */\n subject: string;\n}\n\nexport const CUSTOM_PORTS = {\n sourceControl: {\n key: \"sourceControl\",\n type: \"SourceControlPort\",\n label: \"source control\",\n kind: \"flow\",\n subject: `head: async () => (await port.position()).head,\n // TODO: write a file the repository does not track yet.\n change: () => Promise.resolve(),`,\n },\n codeHost: {\n key: \"codeHost\",\n type: \"CodeHostPort\",\n label: \"code host\",\n kind: \"flow\",\n subject: `// TODO: a branch pushed with one commit, a tag, an issue comments can go on.\n branch: (name) => Promise.resolve(name),\n tag: () => Promise.resolve(\"app@1.0.0\"),\n issue: { repository: \"acme/repo\", number: 1 },`,\n },\n ciPipeline: {\n key: \"ciPipeline\",\n type: \"CiPipelinePort\",\n label: \"CI pipeline\",\n kind: \"flow\",\n subject: `// TODO: a workflow that exists and has never run.\n idle: \"ship.yml\",`,\n },\n versioning: {\n key: \"versioning\",\n type: \"VersioningPort\",\n label: \"versioning\",\n kind: \"flow\",\n subject: `// TODO: a package this workspace holds, and its folder.\n workspace: { name: \"@acme/api\", folder: \"apps/api\" },`,\n },\n serverHosting: {\n key: \"serverHosting\",\n type: \"ServerHostingPort\",\n label: \"server hosting\",\n kind: \"delivery\",\n subject: `{}`,\n },\n staticHosting: {\n key: \"staticHosting\",\n type: \"StaticHostingPort\",\n label: \"static hosting\",\n kind: \"delivery\",\n subject: `{}`,\n },\n mobileDistribution: {\n key: \"mobileDistribution\",\n type: \"MobileDistributionPort\",\n label: \"mobile distribution\",\n kind: \"delivery\",\n subject: `{}`,\n },\n packageRegistry: {\n key: \"packageRegistry\",\n type: \"PackageRegistryPort\",\n label: \"package registry\",\n kind: \"delivery\",\n subject: `{}`,\n },\n} as const satisfies Record<string, CustomPort>;\n\nexport type CustomPortKey = keyof typeof CUSTOM_PORTS;\n\n/** `jenkinsCiPipeline` → `jenkins-ci-pipeline`. */\nexport const kebab = (name: string) => name.replace(/([a-z0-9])([A-Z])/g, \"$1-$2\").toLowerCase();\n\n/** A factory name a person can type: a letter, then letters and digits. */\nexport const isFactoryName = (name: string) => /^[a-z][a-zA-Z0-9]*$/.test(name);\n\n/** The name offered first: `customCiPipeline`. */\nexport const suggestedName = (port: CustomPortKey) =>\n `custom${port.charAt(0).toUpperCase()}${port.slice(1)}`;\n\n/** Where a custom adapter lives, and what the config imports it from. */\nexport const customFiles = (name: string) => ({\n file: `shiplane/adapters/${kebab(name)}.ts`,\n test: `shiplane/adapters/${kebab(name)}.test.ts`,\n from: `./shiplane/adapters/${kebab(name)}`,\n});\n\nconst share = (name: string) =>\n ` * Works? Share it: publish it as shiplane-${kebab(name)}, or open a pull request at\n * https://github.com/arnaud-zg/packages so everyone gets it.`;\n\n/** The adapter's file: shiplane's in-memory one under your name, ready to be replaced. */\nexport const renderCustomAdapter = (port: CustomPortKey, name: string, pkg: string) => {\n const { type, label, kind } = CUSTOM_PORTS[port];\n const memory = `${port}Memory`;\n if (kind === \"delivery\") {\n return `import type { DeliveryAdapter, ${type} } from \"${pkg}\";\nimport { z } from \"${pkg}\";\nimport { ${memory} } from \"${pkg}/memory\";\n\n/**\n * ${name}: your own ${label}. It starts in memory: it records each delivery it is asked for and\n * ships nothing, so the release runs end to end while you write it. To make it real, replace the\n * spread with define${type.replace(/Port$/, \"\")}({ ... }) from \"${pkg}\" (see: shiplane docs ${port}).\n * ${kebab(name)}.test.ts runs the contract every ${label} passes.\n${share(name)}\n */\nexport const ${name} = (): DeliveryAdapter<${type}> => ({\n ...${memory}(),\n name: \"${name}\",\n // The keys an app's unit file gives it: add yours, such as z.object({ service: z.string() }).\n settings: z.object({}),\n});\n`;\n }\n return `import type { ${type}, ServiceAdapter } from \"${pkg}\";\nimport { ${memory} } from \"${pkg}/memory\";\n\n/**\n * ${name}: your own ${label}. It starts in memory: it records each call and does nothing real, so\n * the release runs end to end while you write it. Replace its methods one at a time;\n * ${kebab(name)}.test.ts runs the contract every ${label} passes.\n${share(name)}\n */\nexport const ${name} = (): ServiceAdapter<${type}> => ({\n name: \"${name}\",\n create: (context) => {\n const port: ${type} = ${memory}().create(context);\n // TODO: replace what it does with your own calls, for example:\n // port.someMethod = async (...args) => { ... };\n return port;\n },\n});\n`;\n};\n\n/** Its test: the port's contract, run on it. */\nexport const renderCustomTest = (port: CustomPortKey, name: string, pkg: string) => {\n const { kind, subject } = CUSTOM_PORTS[port];\n const contract = `${port}Contract`;\n const file = `./${kebab(name)}`;\n if (kind === \"delivery\") {\n return `import { ${contract} } from \"${pkg}/testing\";\n\nimport { ${name} } from \"${file}\";\n\n// The contract every ${CUSTOM_PORTS[port].label} passes. TODO: the settings an app gives it.\n${contract}([{ adapter: ${name}(), settings: ${subject} }]);\n`;\n }\n return `import { ${contract}, systemShell } from \"${pkg}/testing\";\n\nimport { ${name} } from \"${file}\";\n\n// The contract every ${CUSTOM_PORTS[port].label} passes: green means ${name} is done.\n${contract}(\"${name}\", () => {\n const port = ${name}().create({ root: process.cwd(), shell: systemShell });\n return Promise.resolve({\n port,\n ${subject}\n });\n});\n`;\n};\n","import path from \"node:path\";\n\nimport type { ReleaseUnit } from \"../domain/unit\";\nimport type { SetupContext } from \"./setupContext\";\nimport { tagName } from \"../domain/tags\";\nimport { checkStatus, requirementsOf } from \"./requirements\";\nimport { paint } from \"./say\";\nimport { commandLine, jobInput, moduleOf, shipPlanOf } from \"./targets\";\n\nclass StepFailed extends Error {}\n\n/** One rehearsal check under a spinner when there is one: true when `work` says it passed. */\nconst check = async (context: SetupContext, label: string, work: () => Promise<boolean>) => {\n const run = async () => {\n if (!(await work())) throw new StepFailed();\n };\n try {\n if (context.progress) await context.progress.during(label, \"working\", run);\n else {\n await run();\n context.output.line(` ${paint(\"green\", \"✓\")} ${label}`);\n }\n return true;\n } catch (error) {\n if (!(error instanceof StepFailed)) {\n context.output.line(` ${paint(\"red\", \"✗\")} ${label}`);\n context.output.line(\n ` ${paint(\"dim\", error instanceof Error ? error.message : String(error))}`,\n );\n } else if (!context.progress) context.output.line(` ${paint(\"red\", \"✗\")} ${label}`);\n return false;\n }\n};\n\n/** The package manager this repository runs scripts with. */\nconst runner = (context: SetupContext) =>\n context.files.exists(\"pnpm-lock.yaml\")\n ? \"pnpm\"\n : context.files.exists(\"yarn.lock\")\n ? \"yarn\"\n : context.files.exists(\"bun.lock\") || context.files.exists(\"bun.lockb\")\n ? \"bun\"\n : \"npm\";\n\n/** How a unit builds: its `buildCommand:`, else its package.json \"build\" script, else nothing. */\nexport const buildCommandOf = (context: SetupContext, unit: ReleaseUnit) => {\n if (unit.buildCommand)\n return { command: \"sh\", args: [\"-c\", unit.buildCommand], shown: unit.buildCommand };\n const manifest = JSON.parse(\n context.files.read(path.posix.join(unit.dir, \"package.json\")) ?? \"{}\",\n ) as { scripts?: Record<string, string> };\n if (!manifest.scripts?.build) return null;\n const pm = runner(context);\n return { command: pm, args: [\"run\", \"build\"], shown: `${pm} run build` };\n};\n\n/**\n * A release played through with nothing pushed, published or deployed: the config loads, every app\n * builds, every ship plan resolves, every sign-in is there. Each failure says how to fix it.\n */\nexport const rehearse = async (context: SetupContext): Promise<boolean> => {\n const { output, shell, root } = context;\n output.line();\n output.line(\n ` ${paint(\"bold\", \"Rehearsal\")} ${paint(\"dim\", \"· nothing is pushed, published or deployed\")}`,\n );\n const release = await context.load();\n if (release.problems.length > 0) {\n release.problems.forEach(({ file, line, message, hint }) => {\n output.line(\n ` ${paint(\"red\", \"✗\")} ${line === undefined ? file : `${file}:${line}`} ${message}`,\n );\n if (hint) output.line(` ${paint(\"dim\", hint)}`);\n });\n return false;\n }\n const builds = release.units.flatMap((unit) => {\n const build = buildCommandOf(context, unit);\n return build ? [{ unit, build }] : [];\n });\n const results: {\n unit: ReleaseUnit;\n shown: string;\n failed: boolean;\n seconds: string;\n tail: string[];\n }[] = [];\n const built =\n builds.length === 0 ||\n (await check(\n context,\n `build ${builds.length} app${builds.length === 1 ? \"\" : \"s\"}`,\n async () => {\n results.push(\n ...(await Promise.all(\n builds.map(async ({ unit, build }) => {\n const started = Date.now();\n const result = await shell.capture(build.command, build.args, {\n cwd: path.join(root, unit.dir),\n });\n return {\n unit,\n shown: build.shown,\n failed: result.status !== 0,\n seconds: `${((Date.now() - started) / 1000).toFixed(1)}s`,\n tail: `${result.stderr}${result.stdout}`.trim().split(\"\\n\").slice(-3),\n };\n }),\n )),\n );\n return results.every(({ failed }) => !failed);\n },\n ));\n for (const { unit, shown, failed, seconds, tail } of results) {\n output.line(\n ` ${failed ? paint(\"red\", \"✗\") : paint(\"green\", \"✓\")} ${unit.dir.padEnd(18)}${paint(\"dim\", `${shown} ${seconds}`)}`,\n );\n if (!failed) continue;\n tail.forEach((line) => output.line(` ${paint(\"dim\", line)}`));\n output.line(` ${paint(\"dim\", `fix the build, or set buildCommand: in ${unit.file}`)}`);\n }\n\n const releaseContext = context.compose?.(release);\n const planned =\n !releaseContext ||\n (await check(context, `plan ${release.units.length} apps, nothing runs`, async () => {\n const { head } = await releaseContext.services.sourceControl.position();\n for (const unit of release.units) {\n const module = moduleOf(releaseContext, unit);\n if (!module) continue;\n const tag = tagName(unit.name, unit.version, release.tagFormat);\n shipPlanOf(\n releaseContext,\n module,\n jobInput(releaseContext, module, unit, { tag, environment: \"preview\", commit: head }),\n );\n }\n return true;\n }));\n\n let signedIn = true;\n for (const requirement of requirementsOf(release)) {\n const status = await checkStatus(shell, root, requirement);\n if (await check(context, requirement.label, () => Promise.resolve(status === 0))) continue;\n signedIn = false;\n const fix =\n status === 127\n ? `not installed: ${requirement.check.command}`\n : requirement.fix\n ? `run ${commandLine(requirement.fix)}, then shiplane setup`\n : \"not available here\";\n output.line(` ${paint(\"dim\", fix)}`);\n }\n return built && planned && signedIn;\n};\n","import path from \"node:path\";\n\nimport type { ReleaseModule } from \"../modules/module\";\nimport type { AnyDeliveryAdapter } from \"../modules/suggest\";\nimport type { FolderView } from \"../ports/delivery.port\";\nimport type { CustomPortKey } from \"./customAdapter\";\nimport type { SetupContext } from \"./setupContext\";\nimport type { FlowChoice, FlowPort, ModuleEntry } from \"./setupFiles\";\nimport { moduleFor } from \"../modules/suggest\";\nimport { UNIT_FILE, UNIT_FILES } from \"./config/readUnitFile\";\nimport { expandPatterns, workspacePatterns } from \"./config/workspaceFolders\";\nimport {\n customFiles,\n isFactoryName,\n kebab,\n renderCustomAdapter,\n renderCustomTest,\n suggestedName,\n} from \"./customAdapter\";\nimport { askOptions } from \"./initRelease\";\nimport { rehearse } from \"./rehearse\";\nimport { paint } from \"./say\";\nimport {\n addToConfig,\n CONFIG_FILE,\n DEFAULT_FLOW,\n FLOW_PORTS,\n folderView,\n placeModule,\n releasePackage,\n renderConfig,\n renderUnit,\n SCHEMA_FILE,\n schemaLineFor,\n schemaText,\n} from \"./setupFiles\";\n\n/** A file setup writes: its text, and whether it is new. */\nexport interface Write {\n file: string;\n text: string;\n created: boolean;\n}\n\nconst ok = paint(\"green\", \"✓\");\nconst unsure = paint(\"yellow\", \"?\");\n\n/** What a flow port is called, and what proves the ready-made adapter fits. */\nconst FLOW_LABEL: Record<FlowPort, { label: string; ready: string }> = {\n sourceControl: { label: \"Source control\", ready: \"git\" },\n codeHost: { label: \"Code host\", ready: \"GitHub\" },\n ciPipeline: { label: \"CI pipeline\", ready: \"GitHub Actions\" },\n versioning: { label: \"Versioning\", ready: \"Changesets\" },\n};\n\n/** The kinds of app a person picks from, in their words, and the delivery each one needs. */\nconst APP_KINDS = [\n { value: \"server-hosting\", label: \"Backend service\", hint: \"a server that runs\" },\n { value: \"static-hosting\", label: \"Web application\", hint: \"static files on a CDN\" },\n { value: \"mobile-distribution\", label: \"Mobile application\", hint: \"store builds and updates\" },\n { value: \"package-registry\", label: \"Published package\", hint: \"a library others install\" },\n { value: \"skip\", label: \"Internal tool\", hint: \"versioned, never deployed\" },\n] as const;\n\ntype AppKind = (typeof APP_KINDS)[number][\"value\"];\n\nconst CUSTOM_PORT_OF: Record<Exclude<AppKind, \"skip\">, CustomPortKey> = {\n \"server-hosting\": \"serverHosting\",\n \"static-hosting\": \"staticHosting\",\n \"mobile-distribution\": \"mobileDistribution\",\n \"package-registry\": \"packageRegistry\",\n};\n\nconst MODULE_OF: Record<CustomPortKey, string> = {\n sourceControl: \"\",\n codeHost: \"\",\n ciPipeline: \"\",\n versioning: \"\",\n serverHosting: \"backendService\",\n staticHosting: \"webApp\",\n mobileDistribution: \"mobileApp\",\n packageRegistry: \"publishedPackage\",\n};\n\n/** What proves each ready-made flow adapter fits this repository: hard evidence only. */\nconst flowEvidence = async (context: SetupContext): Promise<Record<FlowPort, string | null>> => {\n const { files, shell, root } = context;\n const remote = files.exists(\".git\")\n ? (await shell.capture(\"git\", [\"remote\", \"get-url\", \"origin\"], { cwd: root })).stdout.trim()\n : \"\";\n const github = /github\\.com[:/]([^/]+\\/[^/.]+)/.exec(remote)?.[1];\n const workflows = files.list(\".github/workflows\").filter((file) => /\\.ya?ml$/.test(file));\n return {\n sourceControl: files.exists(\".git\") ? \".git\" : null,\n codeHost: github ? `remote github.com/${github}` : null,\n ciPipeline: workflows[0] ? `.github/workflows/${workflows[0]}` : null,\n versioning: files.exists(\".changeset/config.json\") ? \".changeset/config.json\" : null,\n };\n};\n\n/** A name for a custom adapter: asked, checked, unused. Null when cancelled. */\nconst askName = async (\n context: SetupContext,\n port: CustomPortKey,\n initial: string,\n): Promise<string | null> => {\n const { prompter, output, files } = context;\n for (;;) {\n const name = await prompter.text(\"Name it (you can rename it later)\", initial);\n if (name === null) return null;\n if (!isFactoryName(name)) {\n output.line(` ${paint(\"red\", \"✗\")} ${name}: a name like ${suggestedName(port)}`);\n continue;\n }\n if (files.exists(customFiles(name).file)) {\n output.line(` ${paint(\"red\", \"✗\")} ${customFiles(name).file} already exists`);\n continue;\n }\n return name;\n }\n};\n\n/** The custom adapter's two files. */\nconst customWrites = (port: CustomPortKey, name: string, pkg: string): Write[] => [\n { file: customFiles(name).file, text: renderCustomAdapter(port, name, pkg), created: true },\n { file: customFiles(name).test, text: renderCustomTest(port, name, pkg), created: true },\n];\n\n/** The flow, from what the repository proves; asked part by part when unsure or when asked to. */\nconst chooseFlow = async (\n context: SetupContext,\n yes: boolean,\n needsPerson: string[],\n writes: Write[],\n pkg: string,\n): Promise<Record<FlowPort, FlowChoice> | null> => {\n const { output, prompter } = context;\n const evidence = await flowEvidence(context);\n output.line(paint(\"bold\", \" Flow\"));\n FLOW_PORTS.forEach((port) => {\n const proof = evidence[port];\n const { label, ready } = FLOW_LABEL[port];\n output.line(\n proof\n ? ` ${ok} ${ready.padEnd(16)}${paint(\"dim\", proof)}`\n : ` ${unsure} ${label.padEnd(16)}${paint(\"dim\", \"not sure: nothing here proves one\")}`,\n );\n });\n const sure = FLOW_PORTS.every((port) => evidence[port] !== null);\n // Proven: nothing to ask. The rehearsal and \"Write it?\" are the check.\n if (sure) return DEFAULT_FLOW;\n if (yes) {\n needsPerson.push(\n ...FLOW_PORTS.filter((port) => !evidence[port]).map(\n (port) => `the ${FLOW_LABEL[port].label.toLowerCase()} (nothing proves one)`,\n ),\n );\n return null;\n }\n const flow = { ...DEFAULT_FLOW };\n for (const port of FLOW_PORTS) {\n const { label, ready } = FLOW_LABEL[port];\n const picked = await prompter.select(\n `${label}?`,\n [\n {\n value: \"ready\",\n label: ready,\n hint: `${DEFAULT_FLOW[port].from}${evidence[port] ? \"\" : \", not found here\"}`,\n },\n { value: \"custom\", label: \"Custom\", hint: \"a no-op in memory you implement\" },\n ],\n evidence[port] ? \"ready\" : \"custom\",\n );\n if (picked === null) return null;\n if (picked === \"custom\") {\n const name = await askName(context, port, suggestedName(port));\n if (name === null) return null;\n flow[port] = { factory: name, from: customFiles(name).from };\n writes.push(...customWrites(port, name, pkg));\n }\n }\n return flow;\n};\n\n/** Where the apps live: prefilled from the workspace when those folders exist, else typed. */\nconst chooseFolders = async (\n context: SetupContext,\n yes: boolean,\n needsPerson: string[],\n): Promise<string[] | null> => {\n const { prompter, output, files } = context;\n const known = workspacePatterns(files).filter(\n (pattern) => pattern.startsWith(\"!\") || expandPatterns(files, [pattern]).length > 0,\n );\n const found = expandPatterns(files, known).filter((dir) => dir !== \".\");\n output.line();\n output.line(paint(\"bold\", \" Apps\"));\n if (found.length > 0) {\n const patterns = known.filter((pattern) => !pattern.startsWith(\"!\")).join(\", \");\n if (\n yes ||\n (await prompter.confirm(\n `Your apps and packages are in ${patterns} (${found.length} folders)?`,\n true,\n ))\n )\n return known;\n } else if (yes) {\n needsPerson.push(\"where the apps are (no workspace folders found)\");\n return null;\n }\n for (;;) {\n const typed = await prompter.text(\"Where are your apps and packages? (e.g. apps/*, web)\");\n if (typed === null) return null;\n const patterns = typed\n .split(\",\")\n .map((part) => part.trim())\n .filter(Boolean);\n const empty = patterns.filter((pattern) => expandPatterns(files, [pattern]).length === 0);\n if (patterns.length > 0 && empty.length === 0) return patterns;\n output.line(\n ` ${paint(\"red\", \"✗\")} ${empty.join(\", \") || \"nothing typed\"} matches no folder: try again`,\n );\n }\n};\n\n/** Folders under these patterns with a manifest and no unit file yet. */\nconst newFolders = (context: SetupContext, patterns: readonly string[]): FolderView[] =>\n expandPatterns(context.files, patterns)\n .filter((dir) => dir !== \".\" && context.files.exists(path.posix.join(dir, \"package.json\")))\n .filter((dir) => !UNIT_FILES.some((name) => context.files.exists(path.posix.join(dir, name))))\n .map((dir) => folderView(context.files, dir));\n\ninterface Placed {\n folder: FolderView;\n module: string;\n options: Record<string, unknown>;\n reason?: string;\n}\n\n/** How a folder ships: taken when an adapter is sure, asked otherwise. Null: not shipped. */\nconst placeFolder = async (\n context: SetupContext,\n folder: FolderView,\n state: {\n yes: boolean;\n needsPerson: string[];\n modules: ReleaseModule[];\n entries: ModuleEntry[];\n writes: Write[];\n pkg: string;\n },\n): Promise<Placed | \"skip\" | null> => {\n const { prompter, output, adapters } = context;\n const sure = adapters\n .map((adapter) => ({ adapter, detection: adapter.detect?.(folder) ?? null }))\n .find(({ detection }) => detection?.certainty === \"found\");\n const place = (adapter: AnyDeliveryAdapter) => {\n const { name, entry } = placeModule(adapter, state.modules, state.pkg);\n if (entry) {\n state.entries.push(entry);\n state.modules.push(moduleFor(adapter, name));\n }\n return name;\n };\n if (sure?.detection) {\n const kind = APP_KINDS.find(({ value }) => value === sure.adapter.capability)?.label ?? \"\";\n output.line(\n ` ${ok} ${folder.dir.padEnd(18)}${kind} → ${sure.adapter.name} ${paint(\"dim\", `proof: ${sure.detection.reason}`)}`,\n );\n const options = await askOptions(\n context,\n folder,\n sure.adapter,\n sure.detection.options,\n state.yes,\n );\n return {\n folder,\n module: place(sure.adapter),\n options,\n reason: sure.detection.reason,\n };\n }\n if (state.yes) {\n state.needsPerson.push(`${folder.dir} (no adapter is sure what it is)`);\n return null;\n }\n output.line(` ${unsure} ${folder.dir.padEnd(18)}${paint(\"dim\", \"not sure what this is\")}`);\n // The modules the config already has come first: your own adapters included.\n const answer = await prompter.select<string>(`What is ${folder.dir}?`, [\n ...state.modules.map((module) => ({\n value: `module:${module.name}`,\n label: `Like ${module.name}`,\n hint: `${module.kind} on ${module.provider}, already in your config`,\n })),\n ...APP_KINDS.map(({ value, label, hint }) => ({ value, label, hint })),\n ]);\n if (answer === null) return null;\n if (answer.startsWith(\"module:\")) {\n return { folder, module: answer.slice(\"module:\".length), options: {} };\n }\n const kind = answer as AppKind;\n if (kind === \"skip\") return \"skip\";\n const fitting = adapters.filter((a) => a.capability === kind);\n const picked =\n fitting.length === 0\n ? \"custom\"\n : await prompter.select(\n `Where does ${folder.dir} go?`,\n [\n ...fitting.map((adapter) => ({ value: adapter.name, label: adapter.name })),\n { value: \"custom\", label: \"Custom\", hint: \"a no-op adapter you implement\" },\n ],\n fitting[0]?.name,\n );\n if (picked === null) return null;\n const adapter = fitting.find(({ name }) => name === picked);\n if (adapter) {\n const options = await askOptions(context, folder, adapter, {}, false);\n return { folder, module: place(adapter), options };\n }\n const port = CUSTOM_PORT_OF[kind];\n const name = await askName(\n context,\n port,\n `${path.posix.basename(folder.dir)}Delivery`.replace(/-([a-z])/g, (_m, c: string) =>\n c.toUpperCase(),\n ),\n );\n if (name === null) return null;\n const module = kebab(name);\n state.entries.push({\n factory: MODULE_OF[port],\n port,\n adapter: name,\n name: module,\n from: customFiles(name).from,\n });\n state.writes.push(...customWrites(port, name, state.pkg));\n return { folder, module, options: {} };\n};\n\n/** The command that builds a folder: its unit's, its package.json script's, or one asked once. */\nconst buildFor = async (\n context: SetupContext,\n folder: FolderView,\n yes: boolean,\n): Promise<string | null> => {\n const manifest = JSON.parse(\n context.files.read(path.posix.join(folder.dir, \"package.json\")) ?? \"{}\",\n ) as {\n scripts?: Record<string, string>;\n };\n if (manifest.scripts?.build) return null;\n if (yes) return null;\n const typed = await context.prompter.text(\n `${folder.dir} has no \"build\" script. Command to build it? (empty: nothing to build)`,\n );\n return typed?.trim() ? typed.trim() : null;\n};\n\n/**\n * `shiplane setup`: the one command to set releases up and keep them right. It reads the\n * repository, takes what it can prove, asks only the rest, then rehearses a release (builds, plan,\n * sign-ins) with nothing pushed or deployed. Files are kept only when the rehearsal passes. Run\n * again, it says all is set or offers what changed.\n */\nexport const setup = async (context: SetupContext, { yes }: { yes: boolean }): Promise<boolean> => {\n const { output, prompter, files } = context;\n const pkg = releasePackage(files);\n const needsPerson: string[] = [];\n const writes: Write[] = [];\n output.line();\n output.line(` ${paint(\"bold\", \"shiplane setup\")} ${paint(\"dim\", path.basename(context.root))}`);\n output.line();\n\n const existing = files.exists(CONFIG_FILE) ? await context.load() : null;\n if (existing && existing.problems.length > 0) {\n existing.problems.forEach(({ file, line, message, hint }) => {\n output.line(\n ` ${paint(\"red\", \"✗\")} ${paint(\"bold\", line === undefined ? file : `${file}:${line}`)} ${message}`,\n );\n if (hint) output.line(` ${paint(\"dim\", hint)}`);\n });\n output.line(` ${paint(\"dim\", \"Fix these, then run shiplane setup again. Nothing written.\")}`);\n return false;\n }\n\n const flow = existing ? null : await chooseFlow(context, yes, needsPerson, writes, pkg);\n if (existing) output.line(` ${ok} flow ${paint(\"dim\", CONFIG_FILE)}`);\n else if (!flow && needsPerson.length === 0) return cancelled(context);\n\n const patterns = existing\n ? existing.units.length > 0\n ? workspacePatterns(files)\n : await chooseFolders(context, yes, needsPerson)\n : await chooseFolders(context, yes, needsPerson);\n if (!patterns && needsPerson.length === 0) return cancelled(context);\n if (existing && existing.units.length > 0) {\n output.line(\n ` ${ok} ${existing.units.length} apps ${paint(\"dim\", \"unchanged, your edits kept\")}`,\n );\n }\n\n const modules: ReleaseModule[] = [...(existing?.modules ?? [])];\n const entries: ModuleEntry[] = [];\n const placed: Placed[] = [];\n for (const folder of patterns ? newFolders(context, patterns) : []) {\n const result = await placeFolder(context, folder, {\n yes,\n needsPerson,\n modules,\n entries,\n writes,\n pkg,\n });\n if (result === null && needsPerson.length === 0) return cancelled(context);\n if (result && result !== \"skip\") {\n const buildCommand = await buildFor(context, folder, yes);\n placed.push(\n buildCommand ? { ...result, options: { buildCommand, ...result.options } } : result,\n );\n }\n }\n\n if (needsPerson.length > 0) {\n output.line();\n output.line(\n ` ${paint(\"red\", \"✗\")} ${needsPerson.length} thing${needsPerson.length === 1 ? \"\" : \"s\"} need${needsPerson.length === 1 ? \"s\" : \"\"} a person:`,\n );\n needsPerson.forEach((item) => output.line(` ${item}`));\n output.line(` ${paint(\"dim\", \"Run shiplane setup without --yes. Nothing written.\")}`);\n return false;\n }\n\n if (!existing) {\n const units =\n patterns && patterns.join() !== workspacePatterns(files).join() ? patterns : undefined;\n writes.unshift({\n file: CONFIG_FILE,\n text: renderConfig(entries, pkg, flow ?? DEFAULT_FLOW, units),\n created: true,\n });\n } else if (entries.length > 0) {\n let config = files.read(CONFIG_FILE) ?? \"\";\n for (const entry of entries) config = addToConfig(config, entry, pkg) ?? config;\n writes.unshift({ file: CONFIG_FILE, text: config, created: false });\n }\n placed.forEach(({ folder, module, options, reason }) =>\n writes.push({\n file: path.posix.join(folder.dir, UNIT_FILE),\n text: renderUnit(module, options, { reason, schemaLine: schemaLineFor(folder.dir) }),\n created: true,\n }),\n );\n\n if (writes.length === 0) {\n const passed = await rehearse(context);\n if (passed) output.line(` ${ok} all set`);\n return passed;\n }\n\n // Written to rehearse on, put back as they were unless it passes.\n const before = [...writes.map(({ file }) => file), SCHEMA_FILE].map((file) => ({\n file,\n text: files.read(file),\n }));\n writes.forEach(({ file, text }) => files.write(file, text));\n if (existing === null || entries.length > 0) {\n const release = await context.load();\n if (release.modules.length > 0) files.write(SCHEMA_FILE, schemaText(release.modules));\n }\n const passed = await rehearse(context);\n const keep = passed && (yes || (await prompter.confirm(\"Releasable. Write it?\", true)));\n if (!keep) {\n before.forEach(({ file, text }) =>\n text === null ? files.remove(file) : files.write(file, text),\n );\n output.line(\n ` ${paint(\"dim\", passed ? \"Nothing written.\" : \"Fix it, then run shiplane setup again. Nothing written.\")}`,\n );\n return false;\n }\n writes.forEach(({ file, created }) =>\n output.line(` ${created ? paint(\"green\", \"+\") : paint(\"yellow\", \"~\")} ${file}`),\n );\n const custom = writes.some(({ file }) => file.startsWith(\"shiplane/adapters/\"));\n if (custom) {\n output.line(\n ` ${paint(\"dim\", \"Custom adapters start in memory: fill them in until their contract test passes.\")}`,\n );\n output.line(\n ` ${paint(\"dim\", \"Works? Share it as shiplane-<name>, or open a pull request at github.com/arnaud-zg/packages.\")}`,\n );\n }\n output.line();\n output.line(\n ` ${ok} ${paint(\"bold\", \"Ready.\")} Add a changeset, merge, and run ${paint(\"cyan\", \"shiplane\")}`,\n );\n return true;\n};\n\nconst cancelled = (context: SetupContext) => {\n context.output.line(` ${paint(\"dim\", \"Nothing written.\")}`);\n return false;\n};\n","import type { Ora } from \"ora\";\nimport ora from \"ora\";\n\nconst TICK_MS = 140;\n\n/** What the live line shows: its frames (the mascot, or ora's dots), its text, what trails it. */\nexport interface LiveSpinner {\n frames?: readonly string[];\n text: string;\n suffix?: () => string;\n}\n\n/**\n * The one line the release redraws in place, an ora spinner. Anything else printed goes above it,\n * and a prompt or a child process holds it so the terminal is theirs meanwhile.\n */\nclass LiveLine {\n private spinner: Ora | null = null;\n private held = 0;\n\n get busy() {\n return this.spinner !== null;\n }\n\n show({ frames, text, suffix }: LiveSpinner, animate: boolean) {\n this.spinner = ora({\n text,\n suffixText: suffix,\n stream: process.stdout,\n discardStdin: false,\n isEnabled: animate,\n ...(frames && frames.length > 0\n ? { spinner: { interval: TICK_MS, frames: [...frames] } }\n : { spinner: \"dots\" }),\n });\n if (this.held === 0) this.spinner.start();\n }\n\n /** Ends the live line with a symbol kept on screen: ✓, ✗ or !. */\n finish(symbol: string, text?: string) {\n const spinner = this.spinner;\n this.spinner = null;\n if (!spinner) return;\n if (this.held > 0) {\n process.stdout.write(`${symbol} ${text ?? spinner.text}\\n`);\n return;\n }\n spinner.stopAndPersist({ symbol, ...(text === undefined ? {} : { text }) });\n }\n\n clear() {\n this.spinner?.stop();\n this.spinner = null;\n }\n\n /** Prints a line above the live one. */\n above(text: string) {\n const live = this.spinner && this.held === 0 ? this.spinner : null;\n live?.clear();\n process.stdout.write(`${text}\\n`);\n live?.render();\n }\n\n /** Gives the terminal to `work`, a prompt or a child process, then draws the live line again. */\n async hold<T>(work: () => Promise<T>) {\n if (this.spinner && this.held === 0) this.spinner.stop();\n this.held += 1;\n try {\n return await work();\n } finally {\n this.held -= 1;\n if (this.spinner && this.held === 0) this.spinner.start();\n }\n }\n}\n\nexport const liveLine = new LiveLine();\n","import { execFile, spawn } from \"node:child_process\";\n\nimport type { RunOptions, Shell } from \"../../ports/shell.port\";\nimport { liveLine } from \"../terminal/live-line\";\n\n// eas prints megabytes of fingerprint JSON: the default 1 MB buffer is far too small.\nconst MAX_BUFFER = 256 * 1024 * 1024;\n\n// The tools this CLI drives read their own variables (GH_TOKEN, EXPO_TOKEN, FLY_API_TOKEN).\n\nconst environment = (options: RunOptions) => ({ ...process.env, ...options.env });\n\nexport const systemShell: Shell = {\n capture: (command, args, options = {}) =>\n new Promise((resolve) => {\n const child = execFile(\n command,\n [...args],\n { cwd: options.cwd, env: environment(options), maxBuffer: MAX_BUFFER },\n (error, stdout, stderr) => {\n // A command that is not installed answers 127, as a shell would.\n const code = error?.code;\n const status = !error ? 0 : typeof code === \"number\" ? code : code === \"ENOENT\" ? 127 : 1;\n resolve({ status, stdout, stderr });\n },\n );\n if (options.input !== undefined) child.stdin?.end(options.input);\n }),\n // A child writing to the terminal owns it: the live line steps aside meanwhile.\n attach: (command, args, options = {}) =>\n liveLine.hold(\n () =>\n new Promise<number>((resolve) => {\n const child = spawn(command, [...args], {\n cwd: options.cwd,\n env: environment(options),\n stdio: options.input === undefined ? \"inherit\" : [\"pipe\", \"inherit\", \"inherit\"],\n });\n if (options.input !== undefined) child.stdin?.end(options.input);\n child.on(\"error\", () => resolve(127));\n child.on(\"close\", (code) => resolve(code ?? 1));\n }),\n ),\n\n env: (name) => process.env[name],\n};\n","import type { Environment } from \"../domain/environment\";\nimport type { OpenPr, ReleaseStep } from \"../domain/releasePr\";\nimport type { ReleaseTag } from \"../domain/tags\";\nimport type { ReleaseContext } from \"./context\";\nimport { nextStep, RELEASE_BRANCH_PREFIX } from \"../domain/releasePr\";\nimport { scopeChoices } from \"../domain/scope\";\nimport { tagName } from \"../domain/tags\";\nimport { readScope } from \"./readScope\";\nimport { missingTags } from \"./tagRelease\";\nimport { decideContext, jobInput, moduleOf } from \"./targets\";\n\nexport interface UnitStatus {\n unit: string;\n target: string;\n version: string;\n tag: string;\n tagged: boolean;\n changesets: number;\n commits: number;\n /** Something to release to this environment. */\n pending: boolean;\n hint: string;\n /** What its plugin reads from its own platform, such as each EAS build's verdict. */\n live?: unknown;\n}\n\nexport interface ReleaseStatus {\n environment: Environment;\n units: UnitStatus[];\n releasePrs: OpenPr[];\n untagged: ReleaseTag[];\n next: ReleaseStep;\n}\n\n/** Where every unit stands on an environment, and the step a release takes next. Reads only. */\nexport const readStatus = async (\n context: ReleaseContext,\n environment: Environment,\n): Promise<ReleaseStatus> => {\n const info = await readScope(context, environment);\n const choices = scopeChoices(info, environment);\n const [releasePrs, untagged] = await Promise.all([\n context.services.codeHost.openPrsFrom(RELEASE_BRANCH_PREFIX).catch(() => []),\n missingTags(context),\n ]);\n const { head } = await context.services.sourceControl.position();\n const live = async (name: string) => {\n const unit = context.release.units.find((candidate) => candidate.name === name);\n const module = unit && moduleOf(context, unit);\n if (!unit || !module?.inspect) return {};\n const input = jobInput(context, module, unit, {\n tag: tagName(unit.name, unit.version, context.release.tagFormat),\n environment,\n commit: head,\n });\n const inspected = await module\n .inspect(decideContext(context), input)\n .catch((error: unknown) => ({\n error: error instanceof Error ? error.message : String(error),\n }));\n return { live: inspected };\n };\n const units = await Promise.all(\n info.map(async (entry) => {\n const choice = choices.find(({ app }) => app === entry.app);\n const unit = context.release.units.find(({ name }) => name === entry.app);\n return {\n unit: entry.app,\n target: (unit && moduleOf(context, unit)?.provider) ?? \"\",\n version: entry.version,\n tag: tagName(entry.app, entry.version, context.release.tagFormat),\n tagged: entry.tagged,\n changesets: entry.changesets,\n commits: entry.commits,\n pending: choice?.pending ?? false,\n hint: choice?.hint ?? \"\",\n ...(await live(entry.app)),\n };\n }),\n );\n return {\n environment,\n units,\n releasePrs,\n untagged,\n next: nextStep({\n pending: info.reduce((sum, { changesets }) => sum + changesets, 0),\n releasePrs,\n untagged: untagged.length,\n unreleased: info.filter(({ changesets, commits }) => changesets === 0 && commits > 0).length,\n }),\n };\n};\n"],"mappings":";;;;;;;;;;;;;AAMA,MAAa,aAAa,SAAwB;CAChD,MAAM,MAAM,SAAiB,KAAK,KAAK,MAAM,KAAK;AAClD,QAAO;EACL,SAAS,SAAS,GAAG,WAAW,GAAG,KAAK,CAAC;EACzC,OAAO,SAAU,GAAG,WAAW,GAAG,KAAK,CAAC,GAAG,GAAG,aAAa,GAAG,KAAK,EAAE,OAAO,GAAG;EAC/E,QAAQ,MAAM,SAAS;AACrB,MAAG,UAAU,KAAK,QAAQ,GAAG,KAAK,CAAC,EAAE,EAAE,WAAW,MAAM,CAAC;AACzD,MAAG,cAAc,GAAG,KAAK,EAAE,KAAK;;EAElC,SAAS,SAAS,GAAG,OAAO,GAAG,KAAK,EAAE,EAAE,OAAO,MAAM,CAAC;EACtD,OAAO,QAAS,GAAG,WAAW,GAAG,IAAI,CAAC,GAAG,GAAG,YAAY,GAAG,IAAI,CAAC,GAAG,EAAE;EACrE,UAAU,QACR,GAAG,WAAW,GAAG,IAAI,CAAC,GAClB,GACG,YAAY,GAAG,IAAI,EAAE,EAAE,eAAe,MAAM,CAAC,CAC7C,QAAQ,UAAU,MAAM,aAAa,CAAC,CACtC,KAAK,UAAU,MAAM,KAAK,GAC7B,EAAE;EACT;;;;ACCH,MAAM,YAAiE;CACrE,kBAAkB;EAAE,MAAM;EAAmB,SAAS;EAAkB,MAAM;EAAiB;CAC/F,kBAAkB;EAAE,MAAM;EAAW,SAAS;EAAU,MAAM;EAAiB;CAC/E,uBAAuB;EACrB,MAAM;EACN,SAAS;EACT,MAAM;EACP;CACD,oBAAoB;EAClB,MAAM;EACN,SAAS;EACT,MAAM;EACP;CACF;AAED,MAAa,mBAAmB,YAC9B,UAAU,QAAQ;;AAGp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