deltafold 0.0.0 → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +274 -4
- package/dist/changelog.d.ts +116 -0
- package/dist/changelog.d.ts.map +1 -0
- package/dist/changelog.js +304 -0
- package/dist/changelog.js.map +1 -0
- package/dist/document-BZcZo9nr.js +171 -0
- package/dist/document-BZcZo9nr.js.map +1 -0
- package/dist/document-DWHsgywm.d.ts +257 -0
- package/dist/document-DWHsgywm.d.ts.map +1 -0
- package/dist/html.d.ts +8 -0
- package/dist/html.d.ts.map +1 -0
- package/dist/html.js +13 -0
- package/dist/html.js.map +1 -0
- package/dist/index.d.ts +378 -1
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2058 -0
- package/dist/index.js.map +1 -0
- package/dist/markdown.d.ts +8 -0
- package/dist/markdown.d.ts.map +1 -0
- package/dist/markdown.js +16 -0
- package/dist/markdown.js.map +1 -0
- package/dist/mdast-DiRsYwPU.js +108 -0
- package/dist/mdast-DiRsYwPU.js.map +1 -0
- package/dist/package-BfBYnaCz.d.ts +1125 -0
- package/dist/package-BfBYnaCz.d.ts.map +1 -0
- package/dist/rolldown-runtime-D8jQpDG7.js +12 -0
- package/package.json +13 -1
- package/src/features/documents/changelog.ts +450 -0
- package/src/features/documents/document.ts +357 -0
- package/src/features/documents/index.ts +4 -0
- package/src/features/documents/public-document.ts +31 -0
- package/src/features/documents/sections.ts +44 -0
- package/src/features/execution/executor.ts +826 -0
- package/src/features/execution/handler.ts +257 -0
- package/src/features/execution/settlement.ts +49 -0
- package/src/features/package.ts +32 -0
- package/src/features/planning/guide.ts +56 -0
- package/src/features/planning/history.ts +174 -0
- package/src/features/planning/identifiers.ts +43 -0
- package/src/features/planning/resolve-error.ts +201 -0
- package/src/features/planning/resolve.ts +724 -0
- package/src/features/planning/rewrite.ts +331 -0
- package/src/features/planning/validate.ts +388 -0
- package/src/foundation/action.ts +188 -0
- package/src/foundation/change.ts +147 -0
- package/src/foundation/instruction.ts +110 -0
- package/src/foundation/migration.ts +236 -0
- package/src/foundation/plan.ts +245 -0
- package/src/foundation/rule.ts +74 -0
- package/src/foundation/shortcut.ts +79 -0
- package/src/foundation/template.ts +28 -0
- package/src/foundation/version.ts +78 -0
- package/src/index.ts +22 -11
- package/src/renderers/html.ts +12 -0
- package/src/renderers/markdown.ts +12 -0
- package/src/renderers/mdast.ts +120 -0
- package/src/types.ts +2 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["define","make","effect","Arr","replace","validate","Arr","Arr","resolve","make","validateDeclarations","resolveRoute","lookupVersion","make","make","make"],"sources":["../src/foundation/action.ts","../src/foundation/template.ts","../src/foundation/change.ts","../src/features/execution/settlement.ts","../src/features/execution/handler.ts","../src/features/execution/executor.ts","../src/features/planning/resolve-error.ts","../src/features/planning/guide.ts","../src/features/planning/identifiers.ts","../src/features/planning/rewrite.ts","../src/features/planning/validate.ts","../src/features/planning/resolve.ts","../src/features/planning/history.ts","../src/foundation/instruction.ts","../src/foundation/migration.ts","../src/features/package.ts","../src/foundation/plan.ts","../src/foundation/rule.ts","../src/foundation/shortcut.ts","../src/foundation/version.ts"],"sourcesContent":["import { Predicate } from \"effect\";\n\nimport type { Instruction } from \"./instruction.ts\";\n\n/**\n * Describes one kind of consumer-owned operation and its payload.\n *\n * @since @next\n */\nexport type Kind<P> = {\n\treadonly _tag: \"ActionKind\";\n\treadonly kind: string;\n\treadonly describe: (payload: P) => string;\n\t/** Creates an action instance with a stable identifier. */\n\treadonly make: <const Id extends string>(id: Id, payload: P) => Action<Id, P>;\n};\n\n/**\n * One concrete instruction. Its `id` identifies the instruction across plans, handler\n * bindings, rules, and reports.\n *\n * @since @next\n */\nexport type Action<Id extends string = string, P = unknown> = {\n\treadonly _tag: \"Action\";\n\treadonly id: Id;\n\treadonly kind: string;\n\treadonly payload: P;\n\t/** The description produced by the kind's `describe` function. */\n\treadonly description: string;\n};\n\n/**\n * Any action instance.\n *\n * @since @next\n */\nexport type Any = Action<string, any>;\n\n/**\n * A mention of an action in prose. It does not declare an occurrence.\n *\n * @since @next\n */\nexport type Ref = {\n\treadonly _tag: \"ActionRef\";\n\treadonly action: Any;\n};\n\n/**\n * Children run one after another.\n *\n * @since @next\n */\nexport type Sequence<A extends Any = Any> = {\n\treadonly _tag: \"Sequence\";\n\treadonly children: ReadonlyArray<Step>;\n\t/** Type-level record of the action instances in `children`. */\n\treadonly \"~actions\"?: A;\n};\n\n/**\n * How many branches of a parallel group may run at the same time.\n *\n * @since @next\n */\nexport type Concurrency = number | \"unbounded\";\n\n/**\n * Branches are independent of each other and may run concurrently. The group asserts\n * that independence; the concurrency limit only controls scheduling.\n *\n * @since @next\n */\nexport type Parallel<A extends Any = Any> = {\n\treadonly _tag: \"Parallel\";\n\treadonly branches: ReadonlyArray<Step>;\n\treadonly concurrency: Concurrency;\n\t/** Type-level record of the action instances in `branches`. */\n\treadonly \"~actions\"?: A;\n};\n\n/**\n * A node that declares action occurrences.\n *\n * @since @next\n */\nexport type Step<A extends Any = Any> = A | Instruction<A> | Sequence<A> | Parallel<A>;\n\n/**\n * Extracts the action instances declared by a step.\n *\n * @since @next\n */\nexport type ActionsOf<S> =\n\tS extends Action<infer Id, infer P>\n\t\t? Action<Id, P>\n\t\t: S extends Instruction<infer A>\n\t\t\t? A\n\t\t\t: S extends Sequence<infer A>\n\t\t\t\t? A\n\t\t\t\t: S extends Parallel<infer A>\n\t\t\t\t\t? A\n\t\t\t\t\t: never;\n\n/**\n * Defines an action kind.\n *\n * @example\n * ```ts\n * const RenameKey = Action.define<{ target: string; from: string; to: string }>(\n * \t\"config.rename\",\n * \t{ describe: ({ target, from, to }) => `In ${target}, rename \"${from}\" to \"${to}\"` },\n * );\n * const renameExportA = RenameKey.make(\"rename-export-a-timeout\", {\n * \ttarget: \"export-a\",\n * \tfrom: \"timeout\",\n * \tto: \"requestTimeout\",\n * });\n * ```\n *\n * @since @next\n */\nexport const define = <P>(\n\tkind: string,\n\toptions: { readonly describe?: (payload: P) => string } = {},\n): Kind<P> => {\n\tconst describe = options.describe ?? (() => kind);\n\n\treturn {\n\t\t_tag: \"ActionKind\",\n\t\tkind,\n\t\tdescribe,\n\t\tmake: (id, payload) => ({\n\t\t\t_tag: \"Action\",\n\t\t\tid,\n\t\t\tkind,\n\t\t\tpayload,\n\t\t\tdescription: describe(payload),\n\t\t}),\n\t};\n};\n\n/**\n * Mentions an action in prose without declaring another occurrence.\n *\n * @since @next\n */\nexport const ref = (action: Any): Ref => ({ _tag: \"ActionRef\", action });\n\n/**\n * Declares steps that run one after another.\n *\n * @since @next\n */\nexport const sequence = <const S extends ReadonlyArray<Step>>(\n\tchildren: S,\n): Sequence<ActionsOf<S[number]>> => ({ _tag: \"Sequence\", children });\n\n/**\n * Declares independent branches that may run concurrently. Each branch can be a single\n * step or a sequence.\n *\n * @since @next\n */\nexport const parallel = <const S extends ReadonlyArray<Step>>(\n\tbranches: S,\n\toptions: { readonly concurrency?: Concurrency } = {},\n): Parallel<ActionsOf<S[number]>> => ({\n\t_tag: \"Parallel\",\n\tbranches,\n\tconcurrency: options.concurrency ?? \"unbounded\",\n});\n\n/** @since @next */\nexport const isAction = (value: unknown): value is Any =>\n\tPredicate.isTagged(value, \"Action\") && Predicate.hasProperty(value, \"id\");\n\n/** @since @next */\nexport const isRef = (value: unknown): value is Ref => Predicate.isTagged(value, \"ActionRef\");\n\n/** @since @next */\nexport const isSequence = (value: unknown): value is Sequence =>\n\tPredicate.isTagged(value, \"Sequence\");\n\n/** @since @next */\nexport const isParallel = (value: unknown): value is Parallel =>\n\tPredicate.isTagged(value, \"Parallel\");\n","import dedentText from \"dedent\";\n\nconst placeholder = \"\\u0000\";\n\n/**\n * Removes the common indentation of a tagged template and its surrounding whitespace.\n *\n * Returns one literal string per original literal, so interpolated values stay at their\n * positions and are never stringified or re-indented.\n */\nexport const dedent = (strings: ReadonlyArray<string>): ReadonlyArray<string> =>\n\tdedentText(strings.join(placeholder)).split(placeholder);\n\n/** Scalar values that interpolate as text. */\nexport type Scalar = string | number | boolean | bigint;\n\nexport const isScalar = (value: unknown): value is Scalar =>\n\ttypeof value === \"string\" ||\n\ttypeof value === \"number\" ||\n\ttypeof value === \"boolean\" ||\n\ttypeof value === \"bigint\";\n\nexport const describeValue = (value: unknown): string => {\n\tif (value === null) return \"null\";\n\tif (Array.isArray(value)) return \"an array\";\n\n\treturn typeof value === \"object\" ? \"an object\" : typeof value;\n};\n","import { Predicate } from \"effect\";\n\nimport { describeValue, dedent, isScalar, type Scalar } from \"./template.ts\";\n\n/**\n * The metadata of a change whose shape is not known statically.\n *\n * @since @next\n */\nexport type Metadata = { readonly [field: string]: unknown };\n\n/** @since @next */\nexport type NoMetadata = { readonly [field: string]: undefined };\n\n/**\n * A human-readable record of one logical change. A change can exist before it is\n * assigned to a release, and it does not need an executable migration.\n *\n * deltafold does not interpret `metadata`. Consumers choose its fields, such as a\n * classification or a breaking flag, and what they mean.\n *\n * @since @next\n */\nexport type Change<M extends object = Metadata> = {\n\treadonly _tag: \"Change\";\n\t/** Stable identifier. Editing the description does not change identity. */\n\treadonly id: string;\n\treadonly metadata: M;\n\treadonly description: string;\n\t/** Historical relationship only: it does not cancel actions or create routes. */\n\treadonly reverts: ReadonlyArray<Any>;\n\t/** The change that an adapted backport was derived from. */\n\treadonly backportOf: Any | undefined;\n};\n\n/**\n * A change whose metadata type is not known statically. Its metadata is an object, so\n * reading a field requires narrowing first.\n *\n * @since @next\n */\nexport type Any = Change<object>;\n\n/**\n * Relationships to other changes.\n *\n * @since @next\n */\nexport type Relations = {\n\treadonly reverts?: ReadonlyArray<Any>;\n\treadonly backportOf?: Any;\n};\n\n/**\n * Takes the description as a tagged template and returns the change.\n *\n * @since @next\n */\nexport type Describe<M extends object> = (\n\tstrings: TemplateStringsArray,\n\t...values: ReadonlyArray<Scalar>\n) => Change<M>;\n\nconst describe =\n\t<M extends object>(id: string, metadata: M, relations: Relations): Describe<M> =>\n\t(strings, ...values) => {\n\t\tconst literals = dedent(strings);\n\t\tlet description = \"\";\n\t\tfor (const [index, literal] of literals.entries()) {\n\t\t\tdescription += literal;\n\t\t\tif (index >= values.length) continue;\n\n\t\t\tconst value: unknown = values[index];\n\t\t\tif (!isScalar(value)) {\n\t\t\t\tthrow new TypeError(`Change \"${id}\": cannot interpolate ${describeValue(value)}.`);\n\t\t\t}\n\t\t\tdescription += String(value);\n\t\t}\n\n\t\treturn {\n\t\t\t_tag: \"Change\",\n\t\t\tid,\n\t\t\tmetadata,\n\t\t\tdescription,\n\t\t\treverts: relations.reverts ?? [],\n\t\t\tbackportOf: relations.backportOf,\n\t\t};\n\t};\n\n/**\n * Declares a change. The tagged template is its description. Metadata is optional, and\n * its type is inferred from the value, literals included.\n *\n * @example\n * ```ts\n * const retriesAdded = Change.make(\"2026-11-20.add-retries\")`\n * \tAdd a retry limit option.\n * `;\n * const timeoutRenamed = Change.make(\"2026-11-06.rename-timeout\", { breaking: true })`\n * \tRename the timeout configuration option to requestTimeout.\n * `;\n * ```\n *\n * @since @next\n */\nexport function make(id: string): Describe<NoMetadata>;\nexport function make<const M extends object>(\n\tid: string,\n\tmetadata: M,\n\trelations?: Relations,\n): Describe<M>;\nexport function make(id: string, metadata: object = {}, relations: Relations = {}) {\n\treturn describe(id, metadata, relations);\n}\n\n/**\n * Makes changes that share one metadata shape.\n *\n * @since @next\n */\nexport type Definition<M extends object> = {\n\treadonly make: (id: string, metadata: M, relations?: Relations) => Describe<M>;\n};\n\n/**\n * Defines a reusable change factory whose metadata must have the type `M`.\n *\n * @example\n * ```ts\n * const ConfigChange = Change.define<{\n * \treadonly kind: \"added\" | \"changed\" | \"fixed\";\n * \treadonly breaking: boolean;\n * }>();\n * const timeoutRenamed = ConfigChange.make(\"2026-11-06.rename-timeout\", {\n * \tkind: \"changed\",\n * \tbreaking: true,\n * })`\n * \tRename the timeout configuration option to requestTimeout.\n * `;\n * ```\n *\n * @since @next\n */\nexport const define = <M extends object>(): Definition<M> => ({ make: make<M> });\n\n/** @since @next */\nexport const isChange = (value: unknown): value is Change => Predicate.isTagged(value, \"Change\");\n","import { Context, Duration, Effect, Option } from \"effect\";\n\n/**\n * How the executor learns whether an interrupted Promise callback settled. Effect stops\n * waiting for a Promise when it is interrupted, but the Promise itself can keep running.\n */\nexport type Settlement = {\n\t/** How long to keep waiting for an interrupted Promise before reporting it pending. */\n\treadonly grace: Duration.Input;\n\treadonly record: (settled: boolean) => void;\n};\n\nexport const SettlementReference = Context.Reference<Settlement>(\"deltafold/Settlement\", {\n\tdefaultValue: () => ({ grace: Duration.zero, record: () => {} }),\n});\n\n/**\n * Runs a Promise-producing effect. If it is interrupted after the Promise started,\n * waits up to the settlement grace period and records whether the Promise settled.\n */\nexport const trackPromise = <T, E, R>(\n\tstart: (capture: (promise: Promise<T>) => Promise<T>) => Effect.Effect<T, E, R>,\n): Effect.Effect<T, E, R> =>\n\tEffect.suspend(() => {\n\t\tlet pending: Promise<T> | undefined;\n\t\tconst capture = (promise: Promise<T>) => {\n\t\t\tpending = promise;\n\n\t\t\treturn promise;\n\t\t};\n\n\t\treturn start(capture).pipe(\n\t\t\tEffect.onInterrupt(() =>\n\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\tconst started = pending;\n\t\t\t\t\tif (started === undefined) return;\n\n\t\t\t\t\tconst settlement = yield* SettlementReference;\n\t\t\t\t\tconst settled = yield* Effect.promise(() =>\n\t\t\t\t\t\tstarted.then(\n\t\t\t\t\t\t\t() => undefined,\n\t\t\t\t\t\t\t() => undefined,\n\t\t\t\t\t\t),\n\t\t\t\t\t).pipe(Effect.timeoutOption(settlement.grace));\n\t\t\t\t\tsettlement.record(Option.isSome(settled));\n\t\t\t\t}),\n\t\t\t),\n\t\t);\n\t});\n","import { Context, Data, Effect, Predicate, Schema } from \"effect\";\n\nimport type * as Action from \"../../foundation/action.ts\";\nimport type { ValueOf } from \"../../types.ts\";\nimport { trackPromise } from \"./settlement.ts\";\n\n/**\n * Where a handler failure happened.\n *\n * @since @next\n */\nexport type Phase = \"precondition\" | \"body\";\n\n/**\n * A Promise handler rejected or threw a value that none of its declared error guards\n * recognized.\n *\n * @since @next\n */\nexport class UnexpectedHandlerError extends Data.TaggedError(\"UnexpectedHandlerError\")<{\n\treadonly actionId: string;\n\treadonly kind: string;\n\treadonly phase: Phase;\n\treadonly cause: unknown;\n}> {\n\toverride get message() {\n\t\treturn `Handler for action \"${this.actionId}\" failed unexpectedly in its ${this.phase}`;\n\t}\n}\n\nconst TypeId = \"~deltafold/Handler\";\n\n/**\n * Implements one action instance. `E` and `R` are the errors and Effect services of the\n * body and precondition together.\n *\n * @since @next\n */\nexport type Handler<out A extends Action.Any, out E = never, out R = never> = {\n\treadonly [TypeId]: typeof TypeId;\n\treadonly action: A;\n\t/** Runs the action body. */\n\treadonly body: Effect.Effect<void, E, R>;\n\t/** Decides whether the body applies. `false` skips the occurrence. */\n\treadonly precondition: Effect.Effect<boolean, E, R> | undefined;\n\t/** Explains a skip when the precondition returns `false`. */\n\treadonly skipReason: string;\n};\n\n/**\n * Any handler.\n *\n * @since @next\n */\nexport type Any = Handler<Action.Any, any, any>;\n\n/**\n * The errors of a handler or a union of handlers.\n *\n * @since @next\n */\nexport type Error<H> = H extends Handler<any, infer E, any> ? E : never;\n\n/**\n * The Effect services of a handler or a union of handlers.\n *\n * @since @next\n */\nexport type Services<H> = H extends Handler<any, any, infer R> ? R : never;\n\n/**\n * The action identifiers implemented by a handler or a union of handlers.\n *\n * @since @next\n */\nexport type ActionId<H> = H extends Handler<infer A, any, any> ? A[\"id\"] : never;\n\n/** @since @next */\nexport const isHandler = (value: unknown): value is Any => Predicate.hasProperty(value, TypeId);\n\ntype SkipReason<P> = string | ((payload: P) => string);\n\nconst skipReasonOf = <P>(action: Action.Action<string, P>, reason: SkipReason<P> | undefined) => {\n\tif (reason === undefined) return \"Precondition returned false\";\n\n\treturn typeof reason === \"string\" ? reason : reason(action.payload);\n};\n\n/**\n * Named Effect services that a Promise handler declares.\n *\n * @since @next\n */\nexport type ServiceMap = { readonly [name: string | symbol]: Context.Key<any, any> };\n\n// oxlint-disable-next-line typescript/no-generated-empty-object-type -- A handler without services declares an empty service map.\ntype NoServices = Record<never, never>;\n\n/**\n * The second argument of Promise handler callbacks: the `AbortSignal` that\n * `Effect.tryPromise` aborts on interruption, and the declared services, resolved.\n *\n * @since @next\n */\nexport type PromiseContext<S extends ServiceMap = NoServices> = {\n\treadonly signal: AbortSignal;\n\treadonly services: { readonly [K in keyof S]: S[K][\"Service\"] };\n};\n\ntype ServiceIds<S extends ServiceMap> = ValueOf<{\n\t[K in keyof S]: S[K] extends Context.Key<infer I, any> ? I : never;\n}>;\n\n/**\n * Recognizes a declared rejection: a schema, or a type guard such as an `instanceof`\n * check. Guards must declare their parameter type, for example\n * `(cause: unknown): cause is NotFound => cause instanceof NotFound`.\n *\n * @since @next\n */\nexport type ErrorGuard = Schema.Top | ((cause: unknown) => cause is any);\n\ntype GuardedError<G> = G extends Schema.Top\n\t? G[\"Type\"]\n\t: G extends ((cause: unknown) => cause is infer E)\n\t\t? E\n\t\t: never;\n\n/** @since @next */\nexport type PromiseOptions<P, S extends ServiceMap, G extends ReadonlyArray<ErrorGuard>> = {\n\t/** Effect services resolved for the callbacks and added to the handler requirements. */\n\treadonly services?: S;\n\t/**\n\t * Guards for rejections that keep their own type. Other rejections become\n\t * `UnexpectedHandlerError`. A guard does not prove that the callback throws only\n\t * those errors.\n\t */\n\treadonly errors?: G;\n\t/** Read-only precondition. Returning `false` skips the occurrence. */\n\treadonly when?: (payload: P, context: PromiseContext<S>) => boolean | PromiseLike<boolean>;\n\treadonly skipReason?: SkipReason<P>;\n};\n\nconst declaredError =\n\t<G extends ReadonlyArray<ErrorGuard>>(guards: G) =>\n\t(cause: unknown): cause is GuardedError<G[number]> =>\n\t\tguards.some((guard) => (Schema.isSchema(guard) ? Schema.is(guard)(cause) : guard(cause)));\n\n/**\n * Implements an action with Promise callbacks. The callbacks run lazily through\n * `Effect.tryPromise`, and receive its `AbortSignal` and the declared services in\n * their second argument.\n *\n * @example\n * ```ts\n * Handler.promise(\n * \tupdateRemoteConfig,\n * \tasync (payload, { signal, services: { editor } }) => {\n * \t\tawait editor.update(payload, { signal });\n * \t},\n * \t{ services: { editor: ConfigEditor } },\n * );\n * ```\n *\n * @since @next\n */\nexport const promise = <\n\tA extends Action.Any,\n\tconst S extends ServiceMap = NoServices,\n\tconst G extends ReadonlyArray<ErrorGuard> = [],\n>(\n\taction: A,\n\trun: (payload: A[\"payload\"], context: PromiseContext<S>) => PromiseLike<unknown>,\n\toptions?: PromiseOptions<A[\"payload\"], S, G>,\n): Handler<A, GuardedError<G[number]> | UnexpectedHandlerError, ServiceIds<S>> => {\n\tconst isDeclared = declaredError(options?.errors ?? []);\n\tconst services: ServiceMap = options?.services ?? {};\n\t// The handler requires exactly the declared services. Reading them from its context\n\t// keeps that requirement typed; only the record of resolved services needs a cast,\n\t// because Object.fromEntries does not track keys.\n\tconst resolve = Effect.map(\n\t\tEffect.context<ServiceIds<S>>(),\n\t\t(context) =>\n\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion\n\t\t\tObject.fromEntries(\n\t\t\t\tReflect.ownKeys(services).map((name) => [\n\t\t\t\t\tname,\n\t\t\t\t\tContext.get(context, services[name]!),\n\t\t\t\t]),\n\t\t\t) as { readonly [K in keyof S]: S[K][\"Service\"] },\n\t);\n\n\tconst adapt = <T>(\n\t\tphase: Phase,\n\t\tcallback: (context: PromiseContext<S>) => PromiseLike<T> | T,\n\t): Effect.Effect<T, GuardedError<G[number]> | UnexpectedHandlerError, ServiceIds<S>> =>\n\t\tEffect.flatMap(resolve, (resolved) =>\n\t\t\ttrackPromise((capture) =>\n\t\t\t\tEffect.tryPromise({\n\t\t\t\t\t// Declaring `signal` makes Effect.tryPromise allocate an AbortController.\n\t\t\t\t\ttry: (signal) =>\n\t\t\t\t\t\tcapture(Promise.resolve(callback({ signal, services: resolved }))),\n\t\t\t\t\tcatch: (cause) =>\n\t\t\t\t\t\tisDeclared(cause)\n\t\t\t\t\t\t\t? cause\n\t\t\t\t\t\t\t: new UnexpectedHandlerError({\n\t\t\t\t\t\t\t\t\tactionId: action.id,\n\t\t\t\t\t\t\t\t\tkind: action.kind,\n\t\t\t\t\t\t\t\t\tphase,\n\t\t\t\t\t\t\t\t\tcause,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t}),\n\t\t\t),\n\t\t);\n\n\tconst when = options?.when;\n\n\treturn {\n\t\t[TypeId]: TypeId,\n\t\taction,\n\t\tbody: Effect.asVoid(adapt(\"body\", (context) => run(action.payload, context))),\n\t\tprecondition:\n\t\t\twhen === undefined\n\t\t\t\t? undefined\n\t\t\t\t: adapt(\"precondition\", (context) => when(action.payload, context)),\n\t\tskipReason: skipReasonOf(action, options?.skipReason),\n\t};\n};\n\n/** @since @next */\nexport type EffectOptions<P, E, R> = {\n\t/** Read-only precondition. Succeeding with `false` skips the occurrence. */\n\treadonly when?: (payload: P) => Effect.Effect<boolean, E, R>;\n\treadonly skipReason?: SkipReason<P>;\n};\n\n/**\n * Implements an action with an Effect. The body keeps its own errors and services, and\n * stops through native Effect interruption.\n *\n * @since @next\n */\nexport const effect = <A extends Action.Any, E = never, R = never, E2 = never, R2 = never>(\n\taction: A,\n\trun: (payload: A[\"payload\"]) => Effect.Effect<unknown, E, R>,\n\toptions: EffectOptions<A[\"payload\"], E2, R2> = {},\n): Handler<A, E | E2, R | R2> => {\n\tconst when = options.when;\n\n\treturn {\n\t\t[TypeId]: TypeId,\n\t\taction,\n\t\tbody: Effect.asVoid(Effect.suspend(() => run(action.payload))),\n\t\tprecondition: when === undefined ? undefined : Effect.suspend(() => when(action.payload)),\n\t\tskipReason: skipReasonOf(action, options.skipReason),\n\t};\n};\n","import {\n\tCause,\n\tContext,\n\tData,\n\tDeferred,\n\tDuration,\n\tEffect,\n\tEqual,\n\tExit,\n\tLayer,\n\tOption,\n} from \"effect\";\n\nimport type * as Action from \"../../foundation/action.ts\";\nimport type * as Plan from \"../../foundation/plan.ts\";\nimport type { Node, Occurrence } from \"../../foundation/plan.ts\";\nimport * as Handler from \"./handler.ts\";\nimport { SettlementReference } from \"./settlement.ts\";\n\n/**\n * What happened to one occurrence, or what a dry run predicts.\n *\n * @since @next\n */\nexport type Outcome<E = unknown> =\n\t| { readonly _tag: \"Completed\" }\n\t| { readonly _tag: \"Skipped\"; readonly reason: string }\n\t| {\n\t\t\treadonly _tag: \"Failed\";\n\t\t\treadonly phase: Handler.Phase;\n\t\t\t/** The typed failure, when the cause has one. Defects only appear in `cause`. */\n\t\t\treadonly error: E | undefined;\n\t\t\treadonly cause: Cause.Cause<E>;\n\t }\n\t| {\n\t\t\treadonly _tag: \"Interrupted\";\n\t\t\treadonly phase: Handler.Phase;\n\t\t\t/** `handler`: an Effect handler interrupted itself. */\n\t\t\treadonly reason: InterruptReason;\n\t\t\t/**\n\t\t\t * Whether the interrupted work is known to have stopped. An interrupted Promise\n\t\t\t * that has not settled within the grace period may still be changing external\n\t\t\t * state.\n\t\t\t */\n\t\t\treadonly settled: boolean;\n\t }\n\t/** Not started because execution stopped first. */\n\t| { readonly _tag: \"Unattempted\" }\n\t| { readonly _tag: \"WouldExecute\"; readonly evaluated: boolean }\n\t| { readonly _tag: \"WouldSkip\"; readonly reason: string }\n\t| { readonly _tag: \"Undetermined\"; readonly reason: string }\n\t| {\n\t\t\treadonly _tag: \"PreconditionFailed\";\n\t\t\treadonly error: E | undefined;\n\t\t\treadonly cause: Cause.Cause<E>;\n\t };\n\n/** @since @next */\nexport type OccurrenceReport<A extends Action.Any = Action.Any, E = unknown> = {\n\treadonly occurrence: Occurrence<A>;\n\treadonly outcome: Outcome<E>;\n};\n\n/** @since @next */\nexport type Report<A extends Action.Any = Action.Any, E = unknown> = {\n\treadonly _tag: \"Report\";\n\treadonly mode: \"execute\" | \"dry-run\";\n\treadonly status:\n\t\t| \"completed\"\n\t\t| \"failed\"\n\t\t| \"interrupted\"\n\t\t| \"not-started\"\n\t\t| \"would-complete\"\n\t\t| \"would-fail\";\n\treadonly from: string;\n\treadonly to: string;\n\treadonly route: string;\n\t/** Every occurrence in plan order. */\n\treadonly occurrences: ReadonlyArray<OccurrenceReport<A, E>>;\n\t/** Whether any action body started. A started body may have partially changed state. */\n\treadonly bodiesStarted: boolean;\n\t/** Progress is not persisted. Rerunning the plan repeats completed actions. */\n\treadonly persistence: \"none\";\n};\n\n/**\n * A handler is missing, duplicated, or bound to a different definition.\n *\n * @since @next\n */\nexport type CoverageIssue = {\n\treadonly _tag: \"Missing\" | \"Duplicate\" | \"Mismatched\";\n\treadonly occurrenceId: string;\n\treadonly actionId: string;\n\treadonly description: string;\n\treadonly migrationId: string;\n\t/** The rule that produced the occurrence, for replacements. */\n\treadonly rule: string | undefined;\n\t/** The occurrences a replacement stands for, so the missing handler is discoverable. */\n\treadonly replaces: ReadonlyArray<{\n\t\treadonly occurrenceId: string;\n\t\treadonly description: string;\n\t}>;\n};\n\nconst HandlerCoverageBase = Data.TaggedError(\"HandlerCoverageError\");\n\n/**\n * Handler coverage failed before any precondition or body ran. Every occurrence needs\n * exactly one handler, for the same action definition: the same identifier, kind, and\n * payload. For an occurrence that a rule produced, the issue names the rule and the\n * occurrences it replaced.\n *\n * @since @next\n */\nexport class HandlerCoverageError<A extends Action.Any = Action.Any> extends HandlerCoverageBase<{\n\treadonly issues: ReadonlyArray<CoverageIssue>;\n\treadonly report: Report<A, never>;\n}> {\n\toverride get message() {\n\t\treturn `Handler coverage failed for ${this.issues.length} occurrence(s): ${this.issues\n\t\t\t.map(\n\t\t\t\t(issue) =>\n\t\t\t\t\t`${issue._tag.toLowerCase()} handler for \"${issue.actionId}\" (${issue.description})`,\n\t\t\t)\n\t\t\t.join(\"; \")}.`;\n\t}\n}\n\nconst ExecutionFailedBase = Data.TaggedError(\"ExecutionFailed\");\n\n/**\n * An occurrence failed. Execution stopped admitting new actions; started ones settled.\n *\n * @since @next\n */\nexport class ExecutionFailed<\n\tA extends Action.Any = Action.Any,\n\tE = unknown,\n> extends ExecutionFailedBase<{\n\treadonly failures: ReadonlyArray<OccurrenceReport<A, E>>;\n\treadonly report: Report<A, E>;\n}> {\n\toverride get message() {\n\t\treturn `Execution failed at ${this.failures\n\t\t\t.map((failure) => `\"${failure.occurrence.id}\"`)\n\t\t\t.join(\", \")}. Completed actions were not rolled back.`;\n\t}\n}\n\nconst ExecutionInterruptedBase = Data.TaggedError(\"ExecutionInterrupted\");\n\n/**\n * Why an execution or an occurrence was interrupted: explicit cancellation, a configured\n * timeout, or an Effect handler that interrupted itself.\n *\n * @since @next\n */\nexport type InterruptReason = \"cancelled\" | \"timeout\" | \"handler\";\n\nconst interruptedBy: Record<InterruptReason, string> = {\n\tcancelled: \"cancelled\",\n\ttimeout: \"stopped by a timeout\",\n\thandler: \"interrupted by a handler\",\n};\n\n/**\n * Explicit cancellation, a configured timeout, or a handler's own interruption stopped\n * execution.\n *\n * @since @next\n */\nexport class ExecutionInterrupted<\n\tA extends Action.Any = Action.Any,\n\tE = unknown,\n> extends ExecutionInterruptedBase<{\n\treadonly reason: InterruptReason;\n\treadonly report: Report<A, E>;\n}> {\n\toverride get message() {\n\t\tconst pending = this.report.occurrences.filter(\n\t\t\t(entry) => entry.outcome._tag === \"Interrupted\" && !entry.outcome.settled,\n\t\t);\n\t\tconst suffix =\n\t\t\tpending.length === 0\n\t\t\t\t? \"\"\n\t\t\t\t: ` ${pending.length} interrupted action(s) had not settled and may still be running.`;\n\n\t\treturn `Execution was ${interruptedBy[this.reason]}.${suffix}`;\n\t}\n}\n\n/** @since @next */\nexport type ExecutionError<A extends Action.Any, E> =\n\t| HandlerCoverageError<A>\n\t| ExecutionFailed<A, E>\n\t| ExecutionInterrupted<A, E>;\n\n/**\n * Action identifiers of a statically covered plan that no handler in the array\n * implements.\n *\n * @since @next\n */\nexport type Uncovered<A extends Action.Any, H, C extends Plan.Coverage> = \"runtime\" extends C\n\t? never\n\t: A extends Action.Any\n\t\t? string extends A[\"id\"]\n\t\t\t? never\n\t\t\t: A[\"id\"] extends Handler.ActionId<H>\n\t\t\t\t? never\n\t\t\t\t: A[\"id\"]\n\t\t: never;\n\n/** Rejects a handler array that leaves statically known actions uncovered, naming them. */\ntype CoverageCheck<A extends Action.Any, H, C extends Plan.Coverage> = [\n\tUncovered<A, H, C>,\n] extends [never]\n\t? unknown\n\t: { readonly handlers: `Missing a handler for action \"${Uncovered<A, H, C>}\"` };\n\n/**\n * Errors an execution can report for its occurrences.\n *\n * @since @next\n */\nexport type Errors<H> = Handler.Error<H>;\n\n/**\n * Effect services an execution requires: the services of its handlers.\n *\n * @since @next\n */\nexport type Requirements<H> = Handler.Services<H>;\n\n/** @since @next */\nexport type Options<H extends Handler.Any> = {\n\treadonly handlers?: ReadonlyArray<H>;\n\t/**\n\t * Evaluate preconditions without running any action body. A precondition that may\n\t * depend on an earlier action is reported `Undetermined`, because the dry run does not\n\t * apply that action.\n\t */\n\treadonly dryRun?: boolean;\n\t/**\n\t * Per-occurrence limit for a precondition or body. Exceeding it interrupts that action\n\t * and stops admitting new ones. It applies to dry-run preconditions too.\n\t */\n\treadonly timeout?: Duration.Input;\n\t/**\n\t * How long to wait for an interrupted Promise callback to settle before reporting it\n\t * as possibly still running. Defaults to 5 seconds.\n\t */\n\treadonly settleTimeout?: Duration.Input;\n};\n\n/** A handler as the executor runs it: its action is erased, its channels are not. */\ntype Internal<E, R> = Handler.Handler<Action.Any, E, R>;\n\ntype Resolved<E, R> = Map<string, Internal<E, R>>;\n\nconst describeReplaces = (occurrence: Occurrence) =>\n\toccurrence.origin._tag === \"Replacement\"\n\t\t? occurrence.origin.replaces.map((replaced) => ({\n\t\t\t\toccurrenceId: replaced.id,\n\t\t\t\tdescription: replaced.action.description,\n\t\t\t}))\n\t\t: [];\n\nconst coverage = <E, R>(\n\tplan: Plan.Any,\n\thandlers: ReadonlyArray<Internal<E, R>>,\n): { readonly resolved: Resolved<E, R>; readonly issues: ReadonlyArray<CoverageIssue> } => {\n\tconst byAction = new Map<string, Array<Internal<E, R>>>();\n\tfor (const handler of handlers) {\n\t\tconst list = byAction.get(handler.action.id) ?? [];\n\t\tlist.push(handler);\n\t\tbyAction.set(handler.action.id, list);\n\t}\n\n\tconst resolved: Resolved<E, R> = new Map();\n\tconst issues: Array<CoverageIssue> = [];\n\tfor (const occurrence of plan.occurrences) {\n\t\tconst issue = (tag: CoverageIssue[\"_tag\"]) =>\n\t\t\tissues.push({\n\t\t\t\t_tag: tag,\n\t\t\t\toccurrenceId: occurrence.id,\n\t\t\t\tactionId: occurrence.action.id,\n\t\t\t\tdescription: occurrence.action.description,\n\t\t\t\tmigrationId: occurrence.migration.id,\n\t\t\t\trule:\n\t\t\t\t\toccurrence.origin._tag === \"Replacement\"\n\t\t\t\t\t\t? occurrence.origin.rule.id\n\t\t\t\t\t\t: undefined,\n\t\t\t\treplaces: describeReplaces(occurrence),\n\t\t\t});\n\n\t\tconst candidates = byAction.get(occurrence.action.id) ?? [];\n\t\tconst [selected] = candidates;\n\t\tif (candidates.length > 1) issue(\"Duplicate\");\n\t\telse if (selected === undefined) issue(\"Missing\");\n\t\telse if (\n\t\t\tselected.action.kind !== occurrence.action.kind ||\n\t\t\t!Equal.equals(selected.action.payload, occurrence.action.payload)\n\t\t) {\n\t\t\tissue(\"Mismatched\");\n\t\t} else resolved.set(occurrence.id, selected);\n\t}\n\n\treturn { resolved, issues };\n};\n\nconst report = <A extends Action.Any, E>(\n\tplan: Plan.Plan<A, Plan.Coverage>,\n\tmode: Report[\"mode\"],\n\tstatus: Report[\"status\"],\n\toutcomes: ReadonlyMap<string, Outcome<E>>,\n\tbodiesStarted: boolean,\n): Report<A, E> => ({\n\t_tag: \"Report\",\n\tmode,\n\tstatus,\n\tfrom: plan.from.id,\n\tto: plan.to.id,\n\troute: plan.route.id,\n\toccurrences: plan.occurrences.map((occurrence) => ({\n\t\toccurrence,\n\t\toutcome: outcomes.get(occurrence.id) ?? { _tag: \"Unattempted\" },\n\t})),\n\tbodiesStarted,\n\tpersistence: \"none\",\n});\n\nconst failureOf = <E>(cause: Cause.Cause<E>) => ({\n\terror: Option.getOrUndefined(Cause.findErrorOption(cause)),\n\tcause,\n});\n\nconst forEachBranch = <R>(\n\tbranches: ReadonlyArray<Node>,\n\tconcurrency: Action.Concurrency,\n\trun: (node: Node) => Effect.Effect<void, never, R>,\n) => Effect.forEach(branches, run, { concurrency, discard: true });\n\n/** Registers a callback that cancels the execution. Only `runPromise` uses it. */\ntype Subscribe = (cancel: () => void) => void;\n\ntype StopReason = \"failure\" | InterruptReason;\n\ntype PhaseResult<T, E> =\n\t| { readonly _tag: \"Done\"; readonly exit: Exit.Exit<T, E> }\n\t| {\n\t\t\treadonly _tag: \"Interrupted\";\n\t\t\treadonly reason: \"cancelled\" | \"timeout\";\n\t\t\treadonly settled: boolean;\n\t };\n\ntype ControlOptions = Pick<Options<never>, \"timeout\" | \"settleTimeout\">;\n\n/** Admission state, cancellation, and timeouts shared by real and dry runs. */\nconst makeControl = (options: ControlOptions, subscribe: Subscribe | undefined) =>\n\tEffect.gen(function* () {\n\t\tconst halt: { reason: StopReason | undefined } = { reason: undefined };\n\t\tconst cancelled = yield* Deferred.make<\"cancelled\">();\n\t\tconst settleTimeout = options.settleTimeout ?? Duration.seconds(5);\n\n\t\tconst stop = (reason: StopReason) => {\n\t\t\thalt.reason ??= reason;\n\t\t};\n\t\tsubscribe?.(() => {\n\t\t\tstop(\"cancelled\");\n\t\t\tDeferred.doneUnsafe(cancelled, Exit.succeed(\"cancelled\"));\n\t\t});\n\n\t\t/** Runs one precondition or body, racing it against cancellation and the timeout. */\n\t\tconst runPhase = <T, E, R>(\n\t\t\twork: Effect.Effect<T, E, R>,\n\t\t): Effect.Effect<PhaseResult<T, E>, never, R> =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tlet settled = true;\n\t\t\t\tconst tracked = work.pipe(\n\t\t\t\t\tEffect.provideService(SettlementReference, {\n\t\t\t\t\t\tgrace: settleTimeout,\n\t\t\t\t\t\trecord: (value) => {\n\t\t\t\t\t\t\tsettled = value;\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tconst stopSignals: Array<Effect.Effect<\"cancelled\" | \"timeout\">> = [\n\t\t\t\t\tDeferred.await(cancelled),\n\t\t\t\t];\n\t\t\t\tif (options.timeout !== undefined) {\n\t\t\t\t\tstopSignals.push(Effect.as(Effect.sleep(options.timeout), \"timeout\" as const));\n\t\t\t\t}\n\t\t\t\tconst result = yield* Effect.raceFirst(\n\t\t\t\t\tEffect.map(Effect.exit(tracked), (exit) => ({ _tag: \"Done\" as const, exit })),\n\t\t\t\t\tEffect.raceAll(stopSignals).pipe(\n\t\t\t\t\t\t// Stop admission as soon as the signal fires. The race returns only after\n\t\t\t\t\t\t// the interrupted work has had its settlement grace period.\n\t\t\t\t\t\tEffect.tap((reason) => Effect.sync(() => stop(reason))),\n\t\t\t\t\t\tEffect.map((reason) => ({ _tag: \"Stop\" as const, reason })),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tif (result._tag === \"Done\") return result;\n\n\t\t\t\t// A timeout interrupts only this action. Siblings settle as after any failure.\n\t\t\t\treturn { _tag: \"Interrupted\" as const, reason: result.reason, settled };\n\t\t\t});\n\n\t\treturn { halt, stop, runPhase };\n\t});\n\nconst interrupted = <A extends Action.Any, E>(\n\tplan: Plan.Plan<A, Plan.Coverage>,\n\tmode: Report[\"mode\"],\n\treason: InterruptReason,\n\toutcomes: ReadonlyMap<string, Outcome<E>>,\n\tbodiesStarted: boolean,\n) =>\n\tnew ExecutionInterrupted({\n\t\treason,\n\t\treport: report(plan, mode, \"interrupted\", outcomes, bodiesStarted),\n\t});\n\nconst execute = <A extends Action.Any, E, R>(\n\tplan: Plan.Plan<A, Plan.Coverage>,\n\tresolved: Resolved<E, R>,\n\toptions: ControlOptions,\n\tsubscribe: Subscribe | undefined,\n): Effect.Effect<Report<A, E>, ExecutionFailed<A, E> | ExecutionInterrupted<A, E>, R> =>\n\tEffect.gen(function* () {\n\t\tconst outcomes = new Map<string, Outcome<E>>();\n\t\tconst { halt, stop, runPhase } = yield* makeControl(options, subscribe);\n\t\tlet bodiesStarted = false;\n\n\t\tconst runOccurrence = (occurrence: Occurrence) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tif (halt.reason !== undefined) return;\n\n\t\t\t\tconst handler = resolved.get(occurrence.id);\n\t\t\t\tif (handler === undefined) return;\n\n\t\t\t\tif (handler.precondition !== undefined) {\n\t\t\t\t\tconst checked = yield* runPhase(handler.precondition);\n\t\t\t\t\tif (checked._tag === \"Interrupted\") {\n\t\t\t\t\t\toutcomes.set(occurrence.id, {\n\t\t\t\t\t\t\t_tag: \"Interrupted\",\n\t\t\t\t\t\t\tphase: \"precondition\",\n\t\t\t\t\t\t\treason: checked.reason,\n\t\t\t\t\t\t\tsettled: checked.settled,\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\tExit.isFailure(checked.exit) &&\n\t\t\t\t\t\tCause.hasInterruptsOnly(checked.exit.cause)\n\t\t\t\t\t) {\n\t\t\t\t\t\tstop(\"handler\");\n\t\t\t\t\t\toutcomes.set(occurrence.id, {\n\t\t\t\t\t\t\t_tag: \"Interrupted\",\n\t\t\t\t\t\t\tphase: \"precondition\",\n\t\t\t\t\t\t\treason: \"handler\",\n\t\t\t\t\t\t\tsettled: true,\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (Exit.isFailure(checked.exit)) {\n\t\t\t\t\t\tstop(\"failure\");\n\t\t\t\t\t\toutcomes.set(occurrence.id, {\n\t\t\t\t\t\t\t_tag: \"Failed\",\n\t\t\t\t\t\t\tphase: \"precondition\",\n\t\t\t\t\t\t\t...failureOf(checked.exit.cause),\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (!checked.exit.value) {\n\t\t\t\t\t\toutcomes.set(occurrence.id, {\n\t\t\t\t\t\t\t_tag: \"Skipped\",\n\t\t\t\t\t\t\treason: handler.skipReason,\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\t// The occurrence has started, so a sibling failure lets it finish.\n\t\t\t\t\t// Cancellation that arrived during the precondition keeps the body from starting.\n\t\t\t\t\tif (halt.reason === \"cancelled\") return;\n\t\t\t\t}\n\n\t\t\t\tbodiesStarted = true;\n\t\t\t\tconst ran = yield* runPhase(handler.body);\n\t\t\t\tif (ran._tag === \"Interrupted\") {\n\t\t\t\t\toutcomes.set(occurrence.id, {\n\t\t\t\t\t\t_tag: \"Interrupted\",\n\t\t\t\t\t\tphase: \"body\",\n\t\t\t\t\t\treason: ran.reason,\n\t\t\t\t\t\tsettled: ran.settled,\n\t\t\t\t\t});\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (Exit.isFailure(ran.exit) && Cause.hasInterruptsOnly(ran.exit.cause)) {\n\t\t\t\t\tstop(\"handler\");\n\t\t\t\t\toutcomes.set(occurrence.id, {\n\t\t\t\t\t\t_tag: \"Interrupted\",\n\t\t\t\t\t\tphase: \"body\",\n\t\t\t\t\t\treason: \"handler\",\n\t\t\t\t\t\tsettled: true,\n\t\t\t\t\t});\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (Exit.isFailure(ran.exit)) {\n\t\t\t\t\tstop(\"failure\");\n\t\t\t\t\toutcomes.set(occurrence.id, {\n\t\t\t\t\t\t_tag: \"Failed\",\n\t\t\t\t\t\tphase: \"body\",\n\t\t\t\t\t\t...failureOf(ran.exit.cause),\n\t\t\t\t\t});\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\toutcomes.set(occurrence.id, { _tag: \"Completed\" });\n\t\t\t});\n\n\t\tconst runNode = (node: Node): Effect.Effect<void, never, R> => {\n\t\t\tswitch (node._tag) {\n\t\t\t\tcase \"Occurrence\":\n\t\t\t\t\treturn runOccurrence(node);\n\t\t\t\tcase \"Sequence\":\n\t\t\t\t\treturn Effect.forEach(node.children, runNode, { discard: true });\n\t\t\t}\n\n\t\t\t// Sibling failures stop admission through `halt`; they never interrupt branches.\n\t\t\treturn forEachBranch(node.branches, node.concurrency, runNode);\n\t\t};\n\n\t\tfor (const step of plan.steps) {\n\t\t\t// Migration steps are barriers: a step starts only after the previous one settled.\n\t\t\tif (halt.reason !== undefined) break;\n\t\t\tyield* runNode(step.node);\n\t\t}\n\n\t\tif (halt.reason === undefined)\n\t\t\treturn report(plan, \"execute\", \"completed\", outcomes, bodiesStarted);\n\t\tif (halt.reason === \"failure\") {\n\t\t\tconst result = report(plan, \"execute\", \"failed\", outcomes, bodiesStarted);\n\n\t\t\treturn yield* new ExecutionFailed({\n\t\t\t\tfailures: result.occurrences.filter((entry) => entry.outcome._tag === \"Failed\"),\n\t\t\t\treport: result,\n\t\t\t});\n\t\t}\n\n\t\treturn yield* interrupted(plan, \"execute\", halt.reason, outcomes, bodiesStarted);\n\t});\n\nconst dryRun = <A extends Action.Any, E, R>(\n\tplan: Plan.Plan<A, Plan.Coverage>,\n\tresolved: Resolved<E, R>,\n\toptions: ControlOptions,\n\tsubscribe: Subscribe | undefined,\n): Effect.Effect<Report<A, E>, ExecutionInterrupted<A, E>, R> =>\n\tEffect.gen(function* () {\n\t\tconst outcomes = new Map<string, Outcome<E>>();\n\t\tconst { halt, stop, runPhase } = yield* makeControl(options, subscribe);\n\t\tlet failedAt: string | undefined;\n\n\t\t/** Returns whether the node would or might change state. */\n\t\tconst visit = (node: Node, dirty: boolean): Effect.Effect<boolean, never, R> =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tif (node._tag === \"Sequence\") {\n\t\t\t\t\tlet current = dirty;\n\t\t\t\t\tfor (const child of node.children) current = yield* visit(child, current);\n\n\t\t\t\t\treturn current;\n\t\t\t\t}\n\t\t\t\tif (node._tag === \"Parallel\") {\n\t\t\t\t\t// Branches are independent: each starts from the state before the group.\n\t\t\t\t\t// They are evaluated one at a time so the report is deterministic.\n\t\t\t\t\tlet changed = dirty;\n\t\t\t\t\tfor (const branch of node.branches)\n\t\t\t\t\t\tchanged = (yield* visit(branch, dirty)) || changed;\n\n\t\t\t\t\treturn changed;\n\t\t\t\t}\n\n\t\t\t\tconst handler = resolved.get(node.id);\n\t\t\t\tif (handler === undefined || halt.reason !== undefined) return dirty;\n\t\t\t\tif (failedAt !== undefined) {\n\t\t\t\t\toutcomes.set(node.id, {\n\t\t\t\t\t\t_tag: \"Undetermined\",\n\t\t\t\t\t\treason: `Execution would stop at the failed precondition of \"${failedAt}\".`,\n\t\t\t\t\t});\n\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (handler.precondition === undefined) {\n\t\t\t\t\toutcomes.set(node.id, { _tag: \"WouldExecute\", evaluated: false });\n\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (dirty) {\n\t\t\t\t\toutcomes.set(node.id, {\n\t\t\t\t\t\t_tag: \"Undetermined\",\n\t\t\t\t\t\treason: \"The precondition depends on earlier actions that a dry run does not apply.\",\n\t\t\t\t\t});\n\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t\tconst checked = yield* runPhase(handler.precondition);\n\t\t\t\tif (checked._tag === \"Interrupted\") {\n\t\t\t\t\toutcomes.set(node.id, {\n\t\t\t\t\t\t_tag: \"Interrupted\",\n\t\t\t\t\t\tphase: \"precondition\",\n\t\t\t\t\t\treason: checked.reason,\n\t\t\t\t\t\tsettled: checked.settled,\n\t\t\t\t\t});\n\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (Exit.isFailure(checked.exit) && Cause.hasInterruptsOnly(checked.exit.cause)) {\n\t\t\t\t\tstop(\"handler\");\n\t\t\t\t\toutcomes.set(node.id, {\n\t\t\t\t\t\t_tag: \"Interrupted\",\n\t\t\t\t\t\tphase: \"precondition\",\n\t\t\t\t\t\treason: \"handler\",\n\t\t\t\t\t\tsettled: true,\n\t\t\t\t\t});\n\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (Exit.isFailure(checked.exit)) {\n\t\t\t\t\tfailedAt = node.id;\n\t\t\t\t\toutcomes.set(node.id, {\n\t\t\t\t\t\t_tag: \"PreconditionFailed\",\n\t\t\t\t\t\t...failureOf(checked.exit.cause),\n\t\t\t\t\t});\n\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (!checked.exit.value) {\n\t\t\t\t\toutcomes.set(node.id, { _tag: \"WouldSkip\", reason: handler.skipReason });\n\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\toutcomes.set(node.id, { _tag: \"WouldExecute\", evaluated: true });\n\n\t\t\t\treturn true;\n\t\t\t});\n\n\t\t// Later migrations conservatively depend on every earlier migration.\n\t\tlet dirty = false;\n\t\tfor (const step of plan.steps) dirty = yield* visit(step.node, dirty);\n\n\t\tif (halt.reason !== undefined && halt.reason !== \"failure\") {\n\t\t\treturn yield* interrupted(plan, \"dry-run\", halt.reason, outcomes, false);\n\t\t}\n\n\t\treturn report(\n\t\t\tplan,\n\t\t\t\"dry-run\",\n\t\t\tfailedAt === undefined ? \"would-complete\" : \"would-fail\",\n\t\t\toutcomes,\n\t\t\tfalse,\n\t\t);\n\t});\n\nconst run = <A extends Action.Any, C extends Plan.Coverage, H extends Handler.Any>(\n\tplan: Plan.Plan<A, C>,\n\toptions: Options<H>,\n\tsubscribe: Subscribe | undefined,\n): Effect.Effect<Report<A, Errors<H>>, ExecutionError<A, Errors<H>>, Requirements<H>> => {\n\t// Handlers are covariant in their errors and services, and `Errors<H>` and\n\t// `Requirements<H>` collect them from each handler in `H`, so every handler fits this\n\t// shape. From here on the compiler checks both channels.\n\tconst handlers: ReadonlyArray<Internal<Errors<H>, Requirements<H>>> = options.handlers ?? [];\n\n\treturn Effect.gen(function* () {\n\t\tconst checked = coverage(plan, handlers);\n\t\tif (checked.issues.length > 0) {\n\t\t\treturn yield* new HandlerCoverageError({\n\t\t\t\tissues: checked.issues,\n\t\t\t\treport: report(\n\t\t\t\t\tplan,\n\t\t\t\t\toptions.dryRun === true ? \"dry-run\" : \"execute\",\n\t\t\t\t\t\"not-started\",\n\t\t\t\t\tnew Map<string, Outcome<never>>(),\n\t\t\t\t\tfalse,\n\t\t\t\t),\n\t\t\t});\n\t\t}\n\n\t\treturn options.dryRun === true\n\t\t\t? yield* dryRun(plan, checked.resolved, options, subscribe)\n\t\t\t: yield* execute(plan, checked.resolved, options, subscribe);\n\t});\n};\n\n/**\n * Runs a plan as an Effect. Coverage is checked before any precondition or body runs.\n * Steps are sequential barriers; parallel groups run their branches concurrently. On\n * failure, no new action starts, and actions already running settle before the effect\n * fails with the partial report.\n *\n * To cancel, interrupt the fiber. Interruption reaches running actions and aborts the\n * signal passed to Promise callbacks. The effect then ends as interrupted, without a\n * report.\n *\n * @since @next\n */\nexport const effect = <\n\tA extends Action.Any,\n\tC extends Plan.Coverage,\n\tH extends Handler.Any = never,\n>(\n\tplan: Plan.Plan<A, C>,\n\toptions: Options<H> & CoverageCheck<A, H, C>,\n): Effect.Effect<Report<A, Errors<H>>, ExecutionError<A, Errors<H>>, Requirements<H>> =>\n\trun(plan, options, undefined);\n\ntype ServicesOption<R, LE> = [R] extends [never]\n\t? {\n\t\t\t/** Handlers without Effect services need none. */\n\t\t\treadonly services?: Context.Context<never> | Layer.Layer<never, LE>;\n\t\t}\n\t: {\n\t\t\t/** Supplies the handlers' Effect services. */\n\t\t\treadonly services: Context.Context<R> | Layer.Layer<R, LE>;\n\t\t};\n\n/** @since @next */\nexport type PromiseOptions<H extends Handler.Any> = Options<H> & {\n\t/**\n\t * Explicit cancellation. Aborting stops admission, interrupts running actions, and\n\t * rejects with `ExecutionInterrupted` and the partial report.\n\t */\n\treadonly signal?: AbortSignal;\n};\n\n/**\n * Runs a plan and returns a Promise. It rejects with `HandlerCoverageError`,\n * `ExecutionFailed`, or `ExecutionInterrupted`, each carrying the partial report.\n * Building a supplied services layer can also reject with the layer's own error,\n * without a report.\n *\n * A services layer is built for this run and finalized when the run ends. A services\n * context stays owned by the caller. A Promise callback that ignores its signal can keep\n * running after cancellation or a timeout, beyond `settleTimeout`, and so after the\n * run's layer resources are finalized; the report marks it as possibly still running.\n *\n * @since @next\n */\nexport const runPromise = <\n\tA extends Action.Any,\n\tC extends Plan.Coverage,\n\tH extends Handler.Any = never,\n\tLE = never,\n>(\n\tplan: Plan.Plan<A, C>,\n\toptions: PromiseOptions<H> & ServicesOption<Requirements<H>, LE> & CoverageCheck<A, H, C>,\n): Promise<Report<A, Errors<H>>> => {\n\tconst { signal } = options;\n\tconst notStarted = () =>\n\t\tnew ExecutionInterrupted({\n\t\t\treason: \"cancelled\",\n\t\t\treport: report(\n\t\t\t\tplan,\n\t\t\t\toptions.dryRun === true ? \"dry-run\" : \"execute\",\n\t\t\t\t\"interrupted\",\n\t\t\t\tnew Map<string, Outcome<Errors<H>>>(),\n\t\t\t\tfalse,\n\t\t\t),\n\t\t});\n\tif (signal?.aborted === true) return Promise.reject(notStarted());\n\n\t// Until the run installs its own cancellation, an abort stops building the services\n\t// layer. Afterwards the run stops admission and reports partial progress.\n\tconst abortedBeforeRun = Deferred.makeUnsafe<void>();\n\tlet cancelRun: (() => void) | undefined;\n\tconst onAbort = () => {\n\t\tif (cancelRun === undefined) Deferred.doneUnsafe(abortedBeforeRun, Effect.void);\n\t\telse cancelRun();\n\t};\n\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\tconst subscribe: Subscribe | undefined =\n\t\tsignal === undefined\n\t\t\t? undefined\n\t\t\t: (cancel) => {\n\t\t\t\t\tcancelRun = cancel;\n\t\t\t\t\tif (signal.aborted) cancel();\n\t\t\t\t};\n\tconst program = run(plan, options, subscribe);\n\tconst services: Context.Context<never> | Layer.Layer<never, LE> | undefined = options.services;\n\tconst provided =\n\t\tservices === undefined\n\t\t\t? program\n\t\t\t: Context.isContext(services)\n\t\t\t\t? Effect.provideContext(program, services)\n\t\t\t\t: // runPromise is the entry point: the caller's layer is built for this one run.\n\t\t\t\t\t// oxlint-disable-next-line effecttsgo/strict-effect-provide\n\t\t\t\t\tEffect.provide(program, services);\n\tconst cancellable =\n\t\tsignal === undefined\n\t\t\t? provided\n\t\t\t: Effect.raceFirst(\n\t\t\t\t\tprovided,\n\t\t\t\t\tEffect.andThen(Deferred.await(abortedBeforeRun), Effect.fail(notStarted())),\n\t\t\t\t);\n\n\treturn Effect.runPromiseExit(\n\t\t// `ServicesOption` requires services that cover every requirement. A layer that\n\t\t// fails to build rejects with its own error.\n\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion, effecttsgo/unsafe-effect-type-assertion\n\t\tcancellable as Effect.Effect<Report<A, Errors<H>>, ExecutionError<A, Errors<H>> | LE>,\n\t)\n\t\t.finally(() => signal?.removeEventListener(\"abort\", onAbort))\n\t\t.then((exit) => {\n\t\t\tif (Exit.isSuccess(exit)) return exit.value;\n\n\t\t\tthrow Cause.squash(exit.cause);\n\t\t});\n};\n","import { Data } from \"effect\";\n\nimport type { RequestDirection } from \"../../foundation/plan.ts\";\nimport type { Issue } from \"./validate.ts\";\n\n/**\n * A candidate route, summarized for diagnostics and explicit selection.\n *\n * @since @next\n */\nexport type RouteSummary = {\n\t/** Pass this as the `route` option to select the route. */\n\treadonly id: string;\n\treadonly migrations: ReadonlyArray<string>;\n\treadonly shortcuts: ReadonlyArray<string>;\n\t/** Optimized action count, or `undefined` when the route failed to optimize. */\n\treadonly actions: number | undefined;\n\treadonly cost: number;\n\t/** Why the route cannot be planned, if it cannot. */\n\treadonly failure: string | undefined;\n};\n\n/**\n * An ancestry hop with no declared route in the requested direction.\n *\n * @since @next\n */\nexport type Blocker = {\n\treadonly from: string;\n\treadonly to: string;\n\treadonly reason: string;\n};\n\n/**\n * The history's declarations are invalid. Resolution needs a valid history.\n *\n * @since @next\n */\nexport class InvalidHistory extends Data.TaggedError(\"InvalidHistory\")<{\n\treadonly issues: ReadonlyArray<Issue>;\n}> {\n\toverride get message() {\n\t\treturn `The history has ${this.issues.length} declaration issue(s): ${this.issues\n\t\t\t.map((issue) => issue.message)\n\t\t\t.join(\" \")}`;\n\t}\n}\n\n/** @since @next */\nexport class UnknownVersion extends Data.TaggedError(\"UnknownVersion\")<{\n\treadonly version: string;\n\treadonly known: ReadonlyArray<string>;\n}> {\n\toverride get message() {\n\t\treturn `Version \"${this.version}\" is not registered in the history.`;\n\t}\n}\n\n/**\n * No declared route connects the versions. This never means that no work is needed:\n * declare `Migration.noop` for a supported zero-work transition.\n *\n * @since @next\n */\nexport class UnsupportedRoute extends Data.TaggedError(\"UnsupportedRoute\")<{\n\treadonly from: string;\n\treadonly to: string;\n\treadonly direction: RequestDirection;\n\t/** Versions that are reachable from `from` in the requested direction. */\n\treadonly reachable: ReadonlyArray<string>;\n\t/** Reachable versions closest to `to` along release ancestry. Ties are all listed. */\n\treadonly closest: ReadonlyArray<string>;\n\treadonly blockers: ReadonlyArray<Blocker>;\n}> {\n\toverride get message() {\n\t\tconst closest =\n\t\t\tthis.closest.length === 0 ? \"\" : ` Closest reachable: ${this.closest.join(\", \")}.`;\n\n\t\treturn `No declared ${this.direction} route from \"${this.from}\" to \"${this.to}\".${closest}`;\n\t}\n}\n\n/**\n * Several routes connect the versions and no selection or policy chose one.\n *\n * @since @next\n */\nexport class AmbiguousRoute extends Data.TaggedError(\"AmbiguousRoute\")<{\n\treadonly from: string;\n\treadonly to: string;\n\treadonly candidates: ReadonlyArray<RouteSummary>;\n\treadonly policy: string | undefined;\n}> {\n\toverride get message() {\n\t\tconst ids = this.candidates.map((candidate) => `\"${candidate.id}\"`).join(\", \");\n\t\tconst reason =\n\t\t\tthis.policy === undefined ? \"\" : ` after applying the \"${this.policy}\" policy`;\n\n\t\treturn `${this.candidates.length} routes connect \"${this.from}\" and \"${this.to}\"${reason}: ${ids}. Select one with the \\`route\\` option, or choose a route policy.`;\n\t}\n}\n\n/**\n * The `route` option names no candidate route.\n *\n * @since @next\n */\nexport class UnknownRoute extends Data.TaggedError(\"UnknownRoute\")<{\n\treadonly route: string;\n\treadonly candidates: ReadonlyArray<RouteSummary>;\n}> {\n\toverride get message() {\n\t\treturn `No candidate route has the identifier \"${this.route}\". Candidates: ${this.candidates\n\t\t\t.map((candidate) => `\"${candidate.id}\"`)\n\t\t\t.join(\", \")}.`;\n\t}\n}\n\n/**\n * Rules rewrite a sequence back into itself.\n *\n * @since @next\n */\nexport class RewriteCycle extends Data.TaggedError(\"RewriteCycle\")<{\n\treadonly route: string;\n\treadonly rules: ReadonlyArray<string>;\n\treadonly actions: string;\n}> {\n\toverride get message() {\n\t\treturn `Rules ${this.rules.map((rule) => `\"${rule}\"`).join(\", \")} rewrite a sequence back into itself on route \"${this.route}\".`;\n\t}\n}\n\n/**\n * Rules can produce different results depending on which applies first.\n *\n * @since @next\n */\nexport class ConflictingRewrites extends Data.TaggedError(\"ConflictingRewrites\")<{\n\treadonly route: string;\n\treadonly outcomes: ReadonlyArray<{\n\t\treadonly actions: string;\n\t\treadonly rules: ReadonlyArray<string>;\n\t}>;\n}> {\n\toverride get message() {\n\t\treturn `Rules produce ${this.outcomes.length} different results on route \"${this.route}\", depending on the order they apply in.`;\n\t}\n}\n\n/**\n * Optimization explored too many states or chained too many rule applications, for\n * example because a rule keeps growing the sequence.\n *\n * @since @next\n */\nexport class RewriteLimitExceeded extends Data.TaggedError(\"RewriteLimitExceeded\")<{\n\treadonly route: string;\n\treadonly limit: \"states\" | \"depth\";\n\treadonly value: number;\n}> {\n\toverride get message() {\n\t\treturn this.limit === \"states\"\n\t\t\t? `Optimizing route \"${this.route}\" explored more than ${this.value} states.`\n\t\t\t: `Optimizing route \"${this.route}\" chained more than ${this.value} rule applications.`;\n\t}\n}\n\n/**\n * More candidate routes exist than the resolver enumerates.\n *\n * @since @next\n */\nexport class TooManyRoutes extends Data.TaggedError(\"TooManyRoutes\")<{\n\treadonly from: string;\n\treadonly to: string;\n\treadonly limit: number;\n}> {\n\toverride get message() {\n\t\treturn `More than ${this.limit} routes connect \"${this.from}\" and \"${this.to}\".`;\n\t}\n}\n\n/** @since @next */\nexport type RewriteError = RewriteCycle | ConflictingRewrites | RewriteLimitExceeded;\n\n/**\n * Why a plan could not be resolved. `UnsupportedRoute` lists the reachable versions, the\n * closest ones by release ancestry, and blockers. `AmbiguousRoute` lists the candidate\n * routes: pass one as `route`, or choose a `policy`.\n *\n * @since @next\n */\nexport type ResolveError =\n\t| InvalidHistory\n\t| UnknownVersion\n\t| UnsupportedRoute\n\t| AmbiguousRoute\n\t| UnknownRoute\n\t| TooManyRoutes\n\t| RewriteError;\n","import type * as Action from \"../../foundation/action.ts\";\nimport type * as Migration from \"../../foundation/migration.ts\";\nimport type { GuideItem, Occurrence } from \"../../foundation/plan.ts\";\n\n/** The declared occurrence a retained occurrence is rendered at. */\nconst anchorOf = (occurrence: Occurrence): Occurrence => {\n\tif (occurrence.origin._tag === \"Declared\") return occurrence;\n\n\tconst first = occurrence.origin.replaces[0];\n\n\treturn first === undefined ? occurrence : anchorOf(first);\n};\n\n/**\n * Resolves a migration's content against the occurrences that survived optimization.\n * Removed occurrences disappear with their instruction blocks. Replacements render at\n * the position of the first occurrence they replaced, using their own instruction or\n * description. Unassociated prose stays.\n */\nexport const resolveGuide = (\n\tcontent: Migration.Content,\n\tretained: ReadonlyArray<Occurrence>,\n\tdeclaredId: (action: Action.Any) => string,\n): ReadonlyArray<GuideItem> => {\n\tconst byAnchor = new Map<string, Array<Occurrence>>();\n\tfor (const occurrence of retained) {\n\t\tconst anchor = anchorOf(occurrence).id;\n\t\tconst list = byAnchor.get(anchor) ?? [];\n\t\tlist.push(occurrence);\n\t\tbyAnchor.set(anchor, list);\n\t}\n\n\tconst renderStep = (step: Action.Step): ReadonlyArray<GuideItem> => {\n\t\tif (step._tag === \"Action\" || step._tag === \"Instruction\") {\n\t\t\tconst action = step._tag === \"Action\" ? step : step.action;\n\n\t\t\treturn (byAnchor.get(declaredId(action)) ?? []).map((occurrence) => ({\n\t\t\t\t_tag: \"Occurrence\",\n\t\t\t\toccurrence,\n\t\t\t}));\n\t\t}\n\n\t\tconst children = (step._tag === \"Sequence\" ? step.children : step.branches)\n\t\t\t.map((child) => renderStep(child))\n\t\t\t.filter((items) => items.length > 0);\n\t\tif (children.length === 0) return [];\n\n\t\treturn [{ _tag: \"Group\", kind: step._tag, children }];\n\t};\n\n\treturn content.flatMap((fragment): ReadonlyArray<GuideItem> => {\n\t\tif (fragment._tag === \"Text\" || fragment._tag === \"ActionRef\") return [fragment];\n\n\t\treturn renderStep(fragment);\n\t});\n};\n","import type * as Action from \"../../foundation/action.ts\";\nimport type * as Migration from \"../../foundation/migration.ts\";\nimport type { Direction, Occurrence } from \"../../foundation/plan.ts\";\nimport type * as Rule from \"../../foundation/rule.ts\";\n\n// Author identifiers may contain any character. Each format escapes its own separators,\n// and the backslash itself, so distinct components never produce the same identifier.\nconst escape = (value: string, separators: RegExp) => value.replace(separators, \"\\\\$&\");\n\nconst occurrencePart = (id: string) => escape(id, /[\\\\/()+]/g);\n\nconst routePart = (id: string) => escape(id, /[\\\\>[\\]]/g);\n\n/** `<migration>/<action>` forward, `<migration>/revert/<action>` in reverse. */\nexport const declaredOccurrenceId = (\n\tmigration: Migration.Any,\n\tdirection: Direction,\n\taction: Action.Any,\n): string =>\n\tdirection === \"forward\"\n\t\t? `${occurrencePart(migration.id)}/${occurrencePart(action.id)}`\n\t\t: `${occurrencePart(migration.id)}/revert/${occurrencePart(action.id)}`;\n\n/**\n * `<rule>(<replaced>+<replaced>)/<action>`. Replaced identifiers are complete occurrence\n * identifiers, so they nest without further escaping.\n */\nexport const replacementOccurrenceId = (\n\trule: Rule.Any,\n\treplaced: ReadonlyArray<Occurrence>,\n\taction: Action.Any,\n): string =>\n\t`${occurrencePart(rule.id)}(${replaced.map((occurrence) => occurrence.id).join(\"+\")})/${occurrencePart(action.id)}`;\n\n/** The first version of a route identifier. */\nexport const routeStart = (version: string): string => routePart(version);\n\n/** A migration hop: `>` and the target version. */\nexport const routeHop = (to: string): string => `>${routePart(to)}`;\n\n/** A shortcut hop: `>[shortcut]>` and the target version. */\nexport const routeShortcut = (shortcut: string, to: string): string =>\n\t`>[${routePart(shortcut)}]>${routePart(to)}`;\n","import { Array as Arr, Order } from \"effect\";\n\nimport type * as Action from \"../../foundation/action.ts\";\nimport type * as Migration from \"../../foundation/migration.ts\";\nimport type { Occurrence } from \"../../foundation/plan.ts\";\nimport type * as Rule from \"../../foundation/rule.ts\";\nimport { replacementOccurrenceId } from \"./identifiers.ts\";\n\n/**\n * A top-level element of a route's sequential spine, or of one parallel branch. `step`\n * is the index of the plan step that owns the element.\n */\nexport type Item =\n\t| { readonly _tag: \"Occ\"; readonly occurrence: Occurrence; readonly step: number }\n\t| {\n\t\t\treadonly _tag: \"Par\";\n\t\t\treadonly branches: ReadonlyArray<ReadonlyArray<Item>>;\n\t\t\treadonly concurrency: Action.Concurrency;\n\t\t\treadonly step: number;\n\t }\n\t/** A text-only migration: manual work that rules must not match around. */\n\t| { readonly _tag: \"Barrier\"; readonly step: number };\n\nexport type Application = {\n\treadonly rule: Rule.Any;\n\treadonly removed: ReadonlyArray<Occurrence>;\n\treadonly produced: ReadonlyArray<Occurrence>;\n};\n\nexport type Outcome = {\n\treadonly items: ReadonlyArray<Item>;\n\treadonly trace: ReadonlyArray<Application>;\n};\n\nexport type Failure =\n\t| {\n\t\t\treadonly _tag: \"RewriteCycle\";\n\t\t\t/** Rules applied around the cycle, in order. */\n\t\t\treadonly rules: ReadonlyArray<string>;\n\t\t\t/** The action sequence that repeats. */\n\t\t\treadonly actions: string;\n\t }\n\t| {\n\t\t\treadonly _tag: \"ConflictingRewrites\";\n\t\t\treadonly outcomes: ReadonlyArray<{\n\t\t\t\treadonly actions: string;\n\t\t\t\treadonly rules: ReadonlyArray<string>;\n\t\t\t}>;\n\t }\n\t| {\n\t\t\treadonly _tag: \"RewriteLimitExceeded\";\n\t\t\treadonly limit: \"states\" | \"depth\";\n\t\t\treadonly value: number;\n\t };\n\nclass RewriteFailure {\n\treadonly failure: Failure;\n\n\tconstructor(failure: Failure) {\n\t\tthis.failure = failure;\n\t}\n}\n\n/** The largest number of distinct states explored while normalizing one sequence. */\nexport const stateLimit = 10_000;\n\n/** The largest number of rule applications in one chain of rewrites. */\nexport const depthLimit = 256;\n\nconst occurrencesOf = (items: ReadonlyArray<Item>): ReadonlyArray<Occurrence> =>\n\titems.flatMap((item) => {\n\t\tif (item._tag === \"Occ\") return [item.occurrence];\n\t\tif (item._tag === \"Par\") return item.branches.flatMap(occurrencesOf);\n\n\t\treturn [];\n\t});\n\nexport { occurrencesOf };\n\nconst groupKey = (branches: ReadonlyArray<string>) =>\n\t`{${Arr.sort(\n\t\tbranches.map((branch) => `[${branch}]`),\n\t\tOrder.String,\n\t).join(\"|\")}}`;\n\n/** A key that identifies a sequence by its action structure. Branch order is ignored. */\nexport const keyOf = (items: ReadonlyArray<Item>): string =>\n\titems\n\t\t.map((item) => {\n\t\t\tif (item._tag === \"Occ\") return JSON.stringify(item.occurrence.action.id);\n\t\t\tif (item._tag === \"Barrier\") return \"#\";\n\n\t\t\treturn groupKey(item.branches.map(keyOf));\n\t\t})\n\t\t.join(\",\");\n\n/** A key that identifies declared steps by their action structure. Branch order is ignored. */\nexport const stepKey = (steps: ReadonlyArray<Action.Step>): string =>\n\tsteps\n\t\t.map((step) => {\n\t\t\tswitch (step._tag) {\n\t\t\t\tcase \"Action\":\n\t\t\t\t\treturn JSON.stringify(step.id);\n\t\t\t\tcase \"Instruction\":\n\t\t\t\t\treturn JSON.stringify(step.action.id);\n\t\t\t\tcase \"Sequence\":\n\t\t\t\t\treturn stepKey(step.children);\n\t\t\t}\n\t\t\tconst branches = step.branches.map((branch) => stepKey([branch]));\n\t\t\tif (branches.length === 1) return branches[0];\n\n\t\t\treturn groupKey(branches);\n\t\t})\n\t\t.filter((key) => key !== \"\")\n\t\t.join(\",\");\n\nexport type MakeOccurrence = (\n\taction: Action.Any,\n\tinstruction: Migration.Instruction | undefined,\n) => Occurrence;\n\n/** Converts declared steps to items. Sequences flatten; single-branch groups flatten. */\nexport const itemsOf = (\n\tsteps: ReadonlyArray<Action.Step>,\n\tmake: MakeOccurrence,\n\tstep: number,\n): ReadonlyArray<Item> =>\n\tsteps.flatMap((declared): ReadonlyArray<Item> => {\n\t\tswitch (declared._tag) {\n\t\t\tcase \"Action\":\n\t\t\t\treturn [{ _tag: \"Occ\", occurrence: make(declared, undefined), step }];\n\t\t\tcase \"Instruction\":\n\t\t\t\treturn [{ _tag: \"Occ\", occurrence: make(declared.action, declared), step }];\n\t\t\tcase \"Sequence\":\n\t\t\t\treturn itemsOf(declared.children, make, step);\n\t\t}\n\n\t\treturn parallelOf(\n\t\t\tdeclared.branches.map((branch) => itemsOf([branch], make, step)),\n\t\t\tdeclared.concurrency,\n\t\t\tstep,\n\t\t);\n\t});\n\n/** Drops empty branches and flattens a group that has a single branch left. */\nconst parallelOf = (\n\tbranches: ReadonlyArray<ReadonlyArray<Item>>,\n\tconcurrency: Action.Concurrency,\n\tstep: number,\n): ReadonlyArray<Item> => {\n\tconst nonEmpty = branches.filter((branch) => branch.length > 0);\n\tif (nonEmpty.length === 0) return [];\n\tif (nonEmpty.length === 1) return nonEmpty[0] ?? [];\n\n\treturn [{ _tag: \"Par\", branches: nonEmpty, concurrency, step }];\n};\n\nconst matchesAt = (\n\tpattern: ReadonlyArray<Rule.Pattern>,\n\titems: ReadonlyArray<Item>,\n\tposition: number,\n): boolean =>\n\tpattern.every((expected, offset) => {\n\t\tconst item = items[position + offset];\n\t\tif (item === undefined) return false;\n\t\tif (expected._tag === \"Action\") {\n\t\t\treturn item._tag === \"Occ\" && item.occurrence.action.id === expected.id;\n\t\t}\n\n\t\treturn item._tag === \"Par\" && keyOf([item]) === stepKey([expected]);\n\t});\n\ntype Transition = {\n\treadonly next: ReadonlyArray<Item>;\n\treadonly application: Application;\n};\n\n/** Replaces the match of a rule at a position with occurrences that record their provenance. */\nconst replace = (rule: Rule.Any, items: ReadonlyArray<Item>, position: number): Transition => {\n\tconst matched = items.slice(position, position + rule.match.length);\n\tconst removed = occurrencesOf(matched);\n\tconst first = removed[0];\n\t// A non-empty match always covers at least one occurrence.\n\tif (first === undefined) throw new Error(`Rule \"${rule.id}\" matched no occurrences`);\n\tconst step = matched[0]?.step ?? 0;\n\tconst produced: Array<Occurrence> = [];\n\tconst make: MakeOccurrence = (action, instruction) => {\n\t\tconst occurrence: Occurrence = {\n\t\t\t_tag: \"Occurrence\",\n\t\t\tid: replacementOccurrenceId(rule, removed, action),\n\t\t\taction,\n\t\t\tmigration: first.migration,\n\t\t\tdirection: first.direction,\n\t\t\tinstruction,\n\t\t\torigin: { _tag: \"Replacement\", rule, replaces: removed },\n\t\t};\n\t\tproduced.push(occurrence);\n\n\t\treturn occurrence;\n\t};\n\tconst next = [\n\t\t...items.slice(0, position),\n\t\t...itemsOf(rule.replacement, make, step),\n\t\t...items.slice(position + rule.match.length),\n\t];\n\n\treturn { next, application: { rule, removed, produced } };\n};\n\nconst makeNormalizer = (rules: ReadonlyArray<Rule.Any>) => {\n\tconst ordered = Arr.sort(\n\t\trules,\n\t\tOrder.mapInput(Order.String, (rule: Rule.Any) => rule.id),\n\t);\n\n\t/**\n\t * Every single rule application available in a sequence: at any position of the\n\t * sequence itself, or inside any branch of its groups. Branch-local and whole-group\n\t * rewrites compete as transitions from the same state.\n\t */\n\tconst transitions = (items: ReadonlyArray<Item>): ReadonlyArray<Transition> => {\n\t\tconst found: Array<Transition> = [];\n\t\tfor (let position = 0; position < items.length; position++) {\n\t\t\tfor (const rule of ordered) {\n\t\t\t\tif (rule.match.length > 0 && matchesAt(rule.match, items, position)) {\n\t\t\t\t\tfound.push(replace(rule, items, position));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst item = items[position];\n\t\t\tif (item?._tag !== \"Par\") continue;\n\t\t\tfor (const [index, branch] of item.branches.entries()) {\n\t\t\t\tfor (const inner of transitions(branch)) {\n\t\t\t\t\tconst branches = item.branches.map((other, otherIndex) =>\n\t\t\t\t\t\totherIndex === index ? inner.next : other,\n\t\t\t\t\t);\n\t\t\t\t\tfound.push({\n\t\t\t\t\t\tnext: [\n\t\t\t\t\t\t\t...items.slice(0, position),\n\t\t\t\t\t\t\t...parallelOf(branches, item.concurrency, item.step),\n\t\t\t\t\t\t\t...items.slice(position + 1),\n\t\t\t\t\t\t],\n\t\t\t\t\t\tapplication: inner.application,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn found;\n\t};\n\n\t/**\n\t * Explores every rewrite order of the whole sequence, nested groups included, under\n\t * one shared state and depth budget.\n\t */\n\tconst normalize = (input: ReadonlyArray<Item>): Outcome => {\n\t\tconst seen = new Set<string>();\n\t\tconst onPath = new Map<string, number>();\n\t\tconst normals = new Map<string, Outcome>();\n\n\t\tconst visit = (items: ReadonlyArray<Item>, trace: ReadonlyArray<Application>): void => {\n\t\t\tconst key = keyOf(items);\n\t\t\tconst entered = onPath.get(key);\n\t\t\tif (entered !== undefined) {\n\t\t\t\tthrow new RewriteFailure({\n\t\t\t\t\t_tag: \"RewriteCycle\",\n\t\t\t\t\trules: trace.slice(entered).map((application) => application.rule.id),\n\t\t\t\t\tactions: key,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (seen.has(key)) return;\n\n\t\t\tseen.add(key);\n\t\t\tif (seen.size > stateLimit) {\n\t\t\t\tthrow new RewriteFailure({\n\t\t\t\t\t_tag: \"RewriteLimitExceeded\",\n\t\t\t\t\tlimit: \"states\",\n\t\t\t\t\tvalue: stateLimit,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (trace.length > depthLimit) {\n\t\t\t\tthrow new RewriteFailure({\n\t\t\t\t\t_tag: \"RewriteLimitExceeded\",\n\t\t\t\t\tlimit: \"depth\",\n\t\t\t\t\tvalue: depthLimit,\n\t\t\t\t});\n\t\t\t}\n\t\t\tonPath.set(key, trace.length);\n\n\t\t\tconst available = transitions(items);\n\t\t\tfor (const { next, application } of available) visit(next, [...trace, application]);\n\t\t\tif (available.length === 0) normals.set(key, { items, trace });\n\n\t\t\tonPath.delete(key);\n\t\t};\n\n\t\tvisit(input, []);\n\n\t\tif (normals.size > 1) {\n\t\t\tthrow new RewriteFailure({\n\t\t\t\t_tag: \"ConflictingRewrites\",\n\t\t\t\toutcomes: [...normals.entries()].map(([actions, outcome]) => ({\n\t\t\t\t\tactions,\n\t\t\t\t\trules: outcome.trace.map((application) => application.rule.id),\n\t\t\t\t})),\n\t\t\t});\n\t\t}\n\n\t\tconst [outcome] = normals.values();\n\n\t\treturn outcome ?? { items: input, trace: [] };\n\t};\n\n\treturn { normalize };\n};\n\n/** Applies rules to a sequence until no rule matches. */\nexport const rewrite = (\n\titems: ReadonlyArray<Item>,\n\trules: ReadonlyArray<Rule.Any>,\n):\n\t| { readonly _tag: \"Success\"; readonly outcome: Outcome }\n\t| { readonly _tag: \"Failure\"; readonly failure: Failure } => {\n\ttry {\n\t\treturn { _tag: \"Success\", outcome: makeNormalizer(rules).normalize(items) };\n\t} catch (error) {\n\t\tif (error instanceof RewriteFailure) return { _tag: \"Failure\", failure: error.failure };\n\n\t\tthrow error;\n\t}\n};\n","import { Array as Arr, Equal, Graph, Option, Order } from \"effect\";\n\nimport type * as Action from \"../../foundation/action.ts\";\nimport type * as Change from \"../../foundation/change.ts\";\nimport type * as Migration from \"../../foundation/migration.ts\";\nimport type * as Rule from \"../../foundation/rule.ts\";\nimport type * as Shortcut from \"../../foundation/shortcut.ts\";\nimport type { Version } from \"../../foundation/version.ts\";\nimport { stepKey } from \"./rewrite.ts\";\n\n/**\n * A problem in a history's declarations.\n *\n * @since @next\n */\nexport type Issue = {\n\treadonly _tag:\n\t\t| \"DuplicateVersion\"\n\t\t| \"UnregisteredVersion\"\n\t\t| \"AncestryCycle\"\n\t\t| \"ConflictingChange\"\n\t\t| \"ConflictingAction\"\n\t\t| \"DuplicateMigration\"\n\t\t| \"DuplicateEdge\"\n\t\t| \"SelfMigration\"\n\t\t| \"EmptyMigration\"\n\t\t| \"DuplicateOccurrence\"\n\t\t| \"DuplicateRule\"\n\t\t| \"InvalidRule\"\n\t\t| \"DuplicateShortcut\"\n\t\t| \"InvalidShortcut\";\n\t/** The identifier of the declaration the issue is about. */\n\treadonly subject: string;\n\treadonly message: string;\n};\n\nexport type Declarations = {\n\treadonly versions: ReadonlyArray<Version>;\n\treadonly migrations: ReadonlyArray<Migration.Any>;\n\treadonly rules: ReadonlyArray<Rule.Any>;\n\treadonly shortcuts: ReadonlyArray<Shortcut.Any>;\n};\n\nconst issueOrder = Order.combine(\n\tOrder.combine(\n\t\tOrder.mapInput(Order.String, (issue: Issue) => issue._tag),\n\t\tOrder.mapInput(Order.String, (issue: Issue) => issue.subject),\n\t),\n\tOrder.mapInput(Order.String, (issue: Issue) => issue.message),\n);\n\n/** Action instances declared by steps, in declaration order. */\nexport const actionsOfSteps = (steps: ReadonlyArray<Action.Step>): ReadonlyArray<Action.Any> =>\n\tsteps.flatMap((step): ReadonlyArray<Action.Any> => {\n\t\tswitch (step._tag) {\n\t\t\tcase \"Action\":\n\t\t\t\treturn [step];\n\t\t\tcase \"Instruction\":\n\t\t\t\treturn [step.action];\n\t\t\tcase \"Sequence\":\n\t\t\t\treturn actionsOfSteps(step.children);\n\t\t}\n\n\t\treturn actionsOfSteps(step.branches);\n\t});\n\nexport const stepsOf = (content: Migration.Content): ReadonlyArray<Action.Step> =>\n\tcontent.flatMap((fragment) =>\n\t\tfragment._tag === \"Text\" || fragment._tag === \"ActionRef\" ? [] : [fragment],\n\t);\n\n/** Whether two definitions with the same identifier describe the same change. */\nconst sameDefinition = (self: Change.Any, that: Change.Any): boolean =>\n\tself === that ||\n\t(self.id === that.id &&\n\t\tEqual.equals(self.metadata, that.metadata) &&\n\t\tself.description === that.description &&\n\t\tself.backportOf?.id === that.backportOf?.id &&\n\t\tself.reverts.length === that.reverts.length &&\n\t\tself.reverts.every((change, index) => change.id === that.reverts[index]?.id));\n\n/** Whether content declares at least one occurrence. Empty groups declare none. */\nconst hasOccurrences = (content: Migration.Content): boolean =>\n\tactionsOfSteps(stepsOf(content)).length > 0;\n\n/** Whether content has prose or mentions. */\nexport const hasProse = (content: Migration.Content): boolean =>\n\tcontent.some(\n\t\t(fragment) =>\n\t\t\tfragment._tag === \"ActionRef\" ||\n\t\t\t(fragment._tag === \"Text\" && fragment.text.trim() !== \"\"),\n\t);\n\nconst sameAction = (self: Action.Any, that: Action.Any) =>\n\tself === that || (self.kind === that.kind && Equal.equals(self.payload, that.payload));\n\n/** Collects every distinct migration: registered ones and those inside shortcuts. */\nexport const allMigrations = (declarations: Declarations): ReadonlyArray<Migration.Any> => {\n\tconst result: Array<Migration.Any> = [...declarations.migrations];\n\tfor (const shortcut of declarations.shortcuts) {\n\t\tfor (const migration of shortcut.migrations) {\n\t\t\tif (!result.includes(migration)) result.push(migration);\n\t\t}\n\t}\n\n\treturn result;\n};\n\nconst isChain = (migrations: ReadonlyArray<Migration.Any>, from: Version, to: Version): boolean => {\n\tlet current = from.id;\n\tfor (const migration of migrations) {\n\t\tif (migration.from.id !== current) return false;\n\t\tcurrent = migration.to.id;\n\t}\n\n\treturn migrations.length > 0 && current === to.id;\n};\n\nexport const validate = (declarations: Declarations): ReadonlyArray<Issue> => {\n\tconst issues: Array<Issue> = [];\n\tconst issue = (tag: Issue[\"_tag\"], subject: string, message: string) =>\n\t\tissues.push({ _tag: tag, subject, message });\n\n\t// Versions and ancestry.\n\tconst versions = new Map<string, Version>();\n\tfor (const version of declarations.versions) {\n\t\tif (versions.has(version.id)) {\n\t\t\tissue(\n\t\t\t\t\"DuplicateVersion\",\n\t\t\t\tversion.id,\n\t\t\t\t`Version \"${version.id}\" is registered more than once.`,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tversions.set(version.id, version);\n\t}\n\tconst unregistered = new Map<string, Array<string>>();\n\tconst requireVersion = (version: Version, referencedBy: string) => {\n\t\tif (versions.get(version.id) !== undefined) return;\n\n\t\tconst referrers = unregistered.get(version.id) ?? [];\n\t\tif (!referrers.includes(referencedBy)) referrers.push(referencedBy);\n\t\tunregistered.set(version.id, referrers);\n\t};\n\tfor (const version of versions.values()) {\n\t\tif (version.previous !== undefined)\n\t\t\trequireVersion(version.previous, `version \"${version.id}\"`);\n\t}\n\tconst ancestry = Graph.directed<string, undefined>((graph) => {\n\t\tconst nodes = new Map<string, Graph.NodeIndex>();\n\t\tfor (const id of versions.keys()) nodes.set(id, Graph.addNode(graph, id));\n\t\tfor (const version of versions.values()) {\n\t\t\tconst source = nodes.get(version.id);\n\t\t\tconst target =\n\t\t\t\tversion.previous === undefined ? undefined : nodes.get(version.previous.id);\n\t\t\tif (source !== undefined && target !== undefined)\n\t\t\t\tGraph.addEdge(graph, source, target, undefined);\n\t\t}\n\t});\n\tconst cycle = Graph.findCycle(ancestry);\n\tif (Option.isSome(cycle)) {\n\t\tconst ids = cycle.value.path.flatMap((index) =>\n\t\t\tOption.toArray(Graph.getNode(ancestry, index)),\n\t\t);\n\t\tissue(\n\t\t\t\"AncestryCycle\",\n\t\t\tids[0] ?? \"\",\n\t\t\t`Release ancestry contains a cycle: ${ids.join(\" -> \")}.`,\n\t\t);\n\t}\n\n\t// Change definitions.\n\tconst changes = new Map<string, Change.Any>();\n\t// Every distinct object is compared and has its relationships followed, so a repeated\n\t// definition cannot hide a conflict between the changes it refers to.\n\tconst visited = new Set<Change.Any>();\n\tconst conflictingChanges = new Set<string>();\n\tconst visitChange = (change: Change.Any) => {\n\t\tif (visited.has(change)) return;\n\t\tvisited.add(change);\n\t\tconst known = changes.get(change.id);\n\t\tif (known === undefined) changes.set(change.id, change);\n\t\telse if (!sameDefinition(known, change) && !conflictingChanges.has(change.id)) {\n\t\t\tconflictingChanges.add(change.id);\n\t\t\tissue(\n\t\t\t\t\"ConflictingChange\",\n\t\t\t\tchange.id,\n\t\t\t\t`Change \"${change.id}\" has conflicting definitions.`,\n\t\t\t);\n\t\t}\n\t\tfor (const reverted of change.reverts) visitChange(reverted);\n\t\tif (change.backportOf !== undefined) visitChange(change.backportOf);\n\t};\n\tfor (const version of declarations.versions) {\n\t\tfor (const change of version.changes) visitChange(change);\n\t}\n\n\t// Action identities.\n\tconst actions = new Map<string, Action.Any>();\n\tconst conflicting = new Set<string>();\n\tconst visitAction = (action: Action.Any) => {\n\t\tconst known = actions.get(action.id);\n\t\tif (known === undefined) {\n\t\t\tactions.set(action.id, action);\n\n\t\t\treturn;\n\t\t}\n\t\tif (!sameAction(known, action) && !conflicting.has(action.id)) {\n\t\t\tconflicting.add(action.id);\n\t\t\tissue(\n\t\t\t\t\"ConflictingAction\",\n\t\t\t\taction.id,\n\t\t\t\t`Action \"${action.id}\" has conflicting definitions; action identifiers must be unique.`,\n\t\t\t);\n\t\t}\n\t};\n\n\t// Migrations.\n\tconst migrations = allMigrations(declarations);\n\tconst migrationIds = new Map<string, Migration.Any>();\n\tconst registered = new Set<Migration.Any>();\n\tfor (const migration of declarations.migrations) {\n\t\tif (registered.has(migration) || migrationIds.has(migration.id)) {\n\t\t\tissue(\n\t\t\t\t\"DuplicateMigration\",\n\t\t\t\tmigration.id,\n\t\t\t\t`Migration \"${migration.id}\" is registered more than once. Register a migration once; register the result of Migration.withRevert in place of the original.`,\n\t\t\t);\n\t\t}\n\t\tregistered.add(migration);\n\t\tmigrationIds.set(migration.id, migration);\n\t}\n\tfor (const migration of migrations) {\n\t\tconst known = migrationIds.get(migration.id);\n\t\tif (known !== undefined && known !== migration && !registered.has(migration)) {\n\t\t\tissue(\n\t\t\t\t\"DuplicateMigration\",\n\t\t\t\tmigration.id,\n\t\t\t\t`Migration \"${migration.id}\" has another definition inside a shortcut.`,\n\t\t\t);\n\t\t}\n\t\tif (known === undefined) migrationIds.set(migration.id, migration);\n\n\t\trequireVersion(migration.from, `migration \"${migration.id}\"`);\n\t\trequireVersion(migration.to, `migration \"${migration.id}\"`);\n\t\tif (migration.from.id === migration.to.id) {\n\t\t\tissue(\n\t\t\t\t\"SelfMigration\",\n\t\t\t\tmigration.id,\n\t\t\t\t`Migration \"${migration.id}\" starts and ends at the same version.`,\n\t\t\t);\n\t\t}\n\t\tfor (const change of migration.addresses) visitChange(change);\n\n\t\tconst sides: ReadonlyArray<[string, Migration.Content | undefined]> = [\n\t\t\t[\"forward\", migration.content],\n\t\t\t[\"revert\", migration.revert],\n\t\t];\n\t\tfor (const [direction, content] of sides) {\n\t\t\tif (content === undefined) continue;\n\t\t\tif (!migration.noop && !hasOccurrences(content) && !hasProse(content)) {\n\t\t\t\tissue(\n\t\t\t\t\t\"EmptyMigration\",\n\t\t\t\t\tmigration.id,\n\t\t\t\t\t`The ${direction} side of migration \"${migration.id}\" is empty. Use Migration.noop to declare a zero-work transition.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst counts = new Map<string, number>();\n\t\t\tfor (const action of actionsOfSteps(stepsOf(content))) {\n\t\t\t\tvisitAction(action);\n\t\t\t\tcounts.set(action.id, (counts.get(action.id) ?? 0) + 1);\n\t\t\t}\n\t\t\tfor (const [actionId, count] of counts) {\n\t\t\t\tif (count < 2) continue;\n\n\t\t\t\tissue(\n\t\t\t\t\t\"DuplicateOccurrence\",\n\t\t\t\t\tmigration.id,\n\t\t\t\t\t`Action \"${actionId}\" occurs ${count} times in the ${direction} side of migration \"${migration.id}\". Use Action.ref to mention an action, or a separate action instance to repeat the work.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Edges. Each pair of versions has at most one migration side, so a transition's work\n\t// lives in one migration.\n\tconst edgeSides = new Map<\n\t\tstring,\n\t\t{ readonly from: string; readonly to: string; readonly labels: Array<string> }\n\t>();\n\tconst addSide = (from: Version, to: Version, label: string) => {\n\t\tconst key = JSON.stringify([from.id, to.id]);\n\t\tconst side = edgeSides.get(key) ?? { from: from.id, to: to.id, labels: [] };\n\t\tside.labels.push(label);\n\t\tedgeSides.set(key, side);\n\t};\n\t// A migration registered twice is already a DuplicateMigration issue.\n\tfor (const migration of new Set(migrationIds.values())) {\n\t\tif (!registered.has(migration)) continue;\n\t\taddSide(migration.from, migration.to, `\"${migration.id}\"`);\n\t\tif (migration.revert !== undefined)\n\t\t\taddSide(migration.to, migration.from, `the revert of \"${migration.id}\"`);\n\t}\n\tfor (const { from, to, labels } of edgeSides.values()) {\n\t\tif (labels.length < 2) continue;\n\n\t\tissue(\n\t\t\t\"DuplicateEdge\",\n\t\t\t`${from} -> ${to}`,\n\t\t\t`${labels.join(\" and \")} both go from \"${from}\" to \"${to}\". Merge them into one migration.`,\n\t\t);\n\t}\n\n\t// Rules.\n\tconst rules = new Set<string>();\n\tfor (const rule of declarations.rules) {\n\t\tif (rules.has(rule.id)) {\n\t\t\tissue(\"DuplicateRule\", rule.id, `Rule \"${rule.id}\" is registered more than once.`);\n\t\t}\n\t\trules.add(rule.id);\n\t\tif (rule.match.length === 0) {\n\t\t\tissue(\"InvalidRule\", rule.id, `Rule \"${rule.id}\" matches nothing.`);\n\t\t}\n\t\tconst patternActions = actionsOfSteps(rule.match);\n\t\tconst replacementActions = actionsOfSteps(rule.replacement);\n\t\tfor (const action of [...patternActions, ...replacementActions]) visitAction(action);\n\t\tconst unique = new Set(replacementActions.map((action) => action.id));\n\t\tif (unique.size !== replacementActions.length) {\n\t\t\tissue(\n\t\t\t\t\"InvalidRule\",\n\t\t\t\trule.id,\n\t\t\t\t`Rule \"${rule.id}\" repeats an action in its replacement.`,\n\t\t\t);\n\t\t}\n\t\t// Same actions in a different structure, such as a sequence made parallel, is a\n\t\t// real replacement.\n\t\tif (rule.match.length > 0 && stepKey(rule.match) === stepKey(rule.replacement)) {\n\t\t\tissue(\"InvalidRule\", rule.id, `Rule \"${rule.id}\" replaces its match with itself.`);\n\t\t}\n\t}\n\n\t// Shortcuts.\n\tconst shortcuts = new Set<string>();\n\tfor (const shortcut of declarations.shortcuts) {\n\t\tif (shortcuts.has(shortcut.id)) {\n\t\t\tissue(\n\t\t\t\t\"DuplicateShortcut\",\n\t\t\t\tshortcut.id,\n\t\t\t\t`Shortcut \"${shortcut.id}\" is registered more than once.`,\n\t\t\t);\n\t\t}\n\t\tshortcuts.add(shortcut.id);\n\t\trequireVersion(shortcut.from, `shortcut \"${shortcut.id}\"`);\n\t\trequireVersion(shortcut.to, `shortcut \"${shortcut.id}\"`);\n\t\tconst unknown = shortcut.replaces.filter((migration) => !registered.has(migration));\n\t\tif (unknown.length > 0) {\n\t\t\tissue(\n\t\t\t\t\"InvalidShortcut\",\n\t\t\t\tshortcut.id,\n\t\t\t\t`Shortcut \"${shortcut.id}\" replaces unregistered migrations: ${unknown.map((migration) => migration.id).join(\", \")}.`,\n\t\t\t);\n\t\t}\n\t\tif (!isChain(shortcut.replaces, shortcut.from, shortcut.to)) {\n\t\t\tissue(\n\t\t\t\t\"InvalidShortcut\",\n\t\t\t\tshortcut.id,\n\t\t\t\t`Shortcut \"${shortcut.id}\" must replace a consecutive route from \"${shortcut.from.id}\" to \"${shortcut.to.id}\".`,\n\t\t\t);\n\t\t}\n\t\tif (!isChain(shortcut.migrations, shortcut.from, shortcut.to)) {\n\t\t\tissue(\n\t\t\t\t\"InvalidShortcut\",\n\t\t\t\tshortcut.id,\n\t\t\t\t`The migrations of shortcut \"${shortcut.id}\" must form a route from \"${shortcut.from.id}\" to \"${shortcut.to.id}\".`,\n\t\t\t);\n\t\t}\n\t}\n\n\tfor (const [id, referrers] of unregistered) {\n\t\tissue(\n\t\t\t\"UnregisteredVersion\",\n\t\t\tid,\n\t\t\t`Version \"${id}\" is referenced by ${referrers.join(\", \")} but is not registered.`,\n\t\t);\n\t}\n\n\treturn Arr.sort(issues, issueOrder);\n};\n","import { Array as Arr, Graph, Order, Result, SemVer } from \"effect\";\n\nimport type * as Change from \"../../foundation/change.ts\";\nimport type * as Migration from \"../../foundation/migration.ts\";\nimport type {\n\tDirection,\n\tExplanation,\n\tHop,\n\tNode,\n\tPlan,\n\tRequestDirection,\n\tRoute,\n\tStep,\n} from \"../../foundation/plan.ts\";\nimport type * as Shortcut from \"../../foundation/shortcut.ts\";\nimport type { Version } from \"../../foundation/version.ts\";\nimport { resolveGuide } from \"./guide.ts\";\nimport { declaredOccurrenceId, routeHop, routeShortcut, routeStart } from \"./identifiers.ts\";\nimport {\n\tAmbiguousRoute,\n\tConflictingRewrites,\n\tRewriteCycle,\n\tRewriteLimitExceeded,\n\tTooManyRoutes,\n\tUnknownRoute,\n\tUnknownVersion,\n\tUnsupportedRoute,\n\ttype Blocker,\n\ttype ResolveError,\n\ttype RewriteError,\n\ttype RouteSummary,\n} from \"./resolve-error.ts\";\nimport { itemsOf, occurrencesOf, rewrite, type Item, type MakeOccurrence } from \"./rewrite.ts\";\nimport { actionsOfSteps, hasProse, stepsOf, type Declarations } from \"./validate.ts\";\n\n/**\n * Route policies for choosing between candidate routes. Each one is opt-in, and a policy\n * that leaves a tie still fails as ambiguous.\n *\n * - `fewest-actions`: the fewest action occurrences after optimization.\n * - `fewest-migrations`: the fewest migration steps.\n * - `lowest-cost`: the lowest total cost. A migration costs 1 unless it declares\n * `cost`; a shortcut costs its declared `cost` or the total of its migrations.\n * - `prefer-shortcuts`: a route through a shortcut over the route the shortcut replaces.\n *\n * @since @next\n */\nexport type RoutePolicy =\n\t| \"fewest-actions\"\n\t| \"fewest-migrations\"\n\t| \"lowest-cost\"\n\t| \"prefer-shortcuts\";\n\n/** The largest number of candidate routes enumerated between two versions. */\nexport const routeLimit = 100;\n\ntype Member = { readonly migration: Migration.Any; readonly direction: Direction };\n\ntype Edge = {\n\treadonly from: Version;\n\treadonly to: Version;\n\treadonly members: ReadonlyArray<Member>;\n\treadonly shortcut: Shortcut.Any | undefined;\n\treadonly cost: number;\n\treadonly class: \"up\" | \"down\" | \"cross\";\n};\n\ntype Candidate = {\n\treadonly route: Route;\n\treadonly edges: ReadonlyArray<Edge>;\n\treadonly plan: Result.Result<Plan, RewriteError>;\n\treadonly cost: number;\n};\n\nexport type Context = {\n\treadonly declarations: Declarations;\n\treadonly versions: ReadonlyMap<string, Version>;\n\t/** Strict ancestors of each version, by identifier. */\n\treadonly ancestors: ReadonlyMap<string, ReadonlySet<string>>;\n\treadonly edges: ReadonlyArray<Edge>;\n};\n\nconst memberCost = (migration: Migration.Any) => migration.cost ?? 1;\n\nexport const makeContext = (declarations: Declarations): Context => {\n\tconst versions = new Map(declarations.versions.map((version) => [version.id, version]));\n\tconst ancestors = new Map<string, ReadonlySet<string>>();\n\tconst ancestorsOf = (id: string): ReadonlySet<string> => {\n\t\tconst known = ancestors.get(id);\n\t\tif (known !== undefined) return known;\n\n\t\tconst result = new Set<string>();\n\t\tlet current = versions.get(id)?.previous;\n\t\twhile (current !== undefined && !result.has(current.id)) {\n\t\t\tresult.add(current.id);\n\t\t\tcurrent = versions.get(current.id)?.previous;\n\t\t}\n\t\tancestors.set(id, result);\n\n\t\treturn result;\n\t};\n\tfor (const id of versions.keys()) ancestorsOf(id);\n\n\tconst classOf = (from: string, to: string): Edge[\"class\"] => {\n\t\tif (ancestorsOf(to).has(from)) return \"up\";\n\t\tif (ancestorsOf(from).has(to)) return \"down\";\n\n\t\treturn \"cross\";\n\t};\n\n\t// Validation guarantees at most one migration side per pair of versions.\n\tconst edges: Array<Edge> = declarations.migrations.flatMap((migration): Array<Edge> => {\n\t\tconst forward: Edge = {\n\t\t\tfrom: migration.from,\n\t\t\tto: migration.to,\n\t\t\tmembers: [{ migration, direction: \"forward\" }],\n\t\t\tshortcut: undefined,\n\t\t\tcost: memberCost(migration),\n\t\t\tclass: classOf(migration.from.id, migration.to.id),\n\t\t};\n\t\tif (migration.revert === undefined) return [forward];\n\n\t\treturn [\n\t\t\tforward,\n\t\t\t{\n\t\t\t\tfrom: migration.to,\n\t\t\t\tto: migration.from,\n\t\t\t\tmembers: [{ migration, direction: \"revert\" }],\n\t\t\t\tshortcut: undefined,\n\t\t\t\tcost: memberCost(migration),\n\t\t\t\tclass: classOf(migration.to.id, migration.from.id),\n\t\t\t},\n\t\t];\n\t});\n\tfor (const shortcut of declarations.shortcuts) {\n\t\tedges.push({\n\t\t\tfrom: shortcut.from,\n\t\t\tto: shortcut.to,\n\t\t\tmembers: shortcut.migrations.map((migration) => ({ migration, direction: \"forward\" })),\n\t\t\tshortcut,\n\t\t\tcost:\n\t\t\t\tshortcut.cost ??\n\t\t\t\tshortcut.migrations.reduce((total, migration) => total + memberCost(migration), 0),\n\t\t\tclass: classOf(shortcut.from.id, shortcut.to.id),\n\t\t});\n\t}\n\n\treturn { declarations, versions, ancestors, edges };\n};\n\nconst requestDirection = (context: Context, from: string, to: string): RequestDirection => {\n\tif (from === to) return \"none\";\n\tif (context.ancestors.get(to)?.has(from)) return \"upgrade\";\n\tif (context.ancestors.get(from)?.has(to)) return \"downgrade\";\n\n\treturn \"cross-branch\";\n};\n\n/**\n * Edge classes allowed together in one route. A route never mixes moves toward\n * ancestors with moves toward descendants, so sharing an ancestor does not authorize a\n * downgrade-and-upgrade detour. Explicit cross-branch migrations fit either family.\n */\nconst families: ReadonlyArray<ReadonlySet<Edge[\"class\"]>> = [\n\tnew Set([\"up\", \"cross\"]),\n\tnew Set([\"down\", \"cross\"]),\n];\n\nconst routeCost = (edges: ReadonlyArray<Edge>) =>\n\tedges.reduce((total, edge) => total + edge.cost, 0);\n\nconst routeOf = (from: Version, edges: ReadonlyArray<Edge>): Route => {\n\tlet id = routeStart(from.id);\n\tconst hops: Array<Hop> = [];\n\tfor (const edge of edges) {\n\t\tif (edge.shortcut === undefined) {\n\t\t\tid += routeHop(edge.to.id);\n\t\t\thops.push({\n\t\t\t\t_tag: \"Migrations\",\n\t\t\t\tfrom: edge.from,\n\t\t\t\tto: edge.to,\n\t\t\t\tmigrations: edge.members,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tid += routeShortcut(edge.shortcut.id, edge.to.id);\n\t\thops.push({ _tag: \"Shortcut\", from: edge.from, to: edge.to, shortcut: edge.shortcut });\n\t}\n\n\treturn { id, hops };\n};\n\nconst graphOf = (context: Context, family: ReadonlySet<Edge[\"class\"]>) => {\n\tconst nodes = new Map<string, Graph.NodeIndex>();\n\tconst graph = Graph.directed<string, Edge>((mutable) => {\n\t\tfor (const id of context.versions.keys()) nodes.set(id, Graph.addNode(mutable, id));\n\t\tfor (const edge of context.edges) {\n\t\t\tif (!family.has(edge.class)) continue;\n\n\t\t\tconst source = nodes.get(edge.from.id);\n\t\t\tconst target = nodes.get(edge.to.id);\n\t\t\tif (source !== undefined && target !== undefined)\n\t\t\t\tGraph.addEdge(mutable, source, target, edge);\n\t\t}\n\t});\n\n\treturn { graph, nodes };\n};\n\ntype Enumerated = {\n\t/** At most `routeLimit` routes, in search order. */\n\treadonly routes: ReadonlyArray<ReadonlyArray<Edge>>;\n\t/** Whether the search stopped because more routes exist. */\n\treadonly overLimit: boolean;\n};\n\nconst enumerateRoutes = (context: Context, from: Version, to: Version): Enumerated => {\n\tconst routes = new Map<string, ReadonlyArray<Edge>>();\n\tfor (const family of families) {\n\t\tconst { graph, nodes } = graphOf(context, family);\n\t\tconst source = nodes.get(from.id);\n\t\tconst target = nodes.get(to.id);\n\t\tif (source === undefined || target === undefined) continue;\n\n\t\tfor (const path of Graph.simplePaths(graph, { source, target, limit: routeLimit + 1 })) {\n\t\t\troutes.set(routeOf(from, path.costs).id, path.costs);\n\t\t}\n\t}\n\tconst found = [...routes.values()];\n\n\treturn { routes: found.slice(0, routeLimit), overLimit: found.length > routeLimit };\n};\n\nconst toNode = (items: ReadonlyArray<Item>): ReadonlyArray<Node> =>\n\titems.flatMap((item): ReadonlyArray<Node> => {\n\t\tif (item._tag === \"Occ\") return [item.occurrence];\n\t\tif (item._tag === \"Barrier\") return [];\n\n\t\treturn [\n\t\t\t{\n\t\t\t\t_tag: \"Parallel\",\n\t\t\t\tbranches: item.branches.map((branch) => {\n\t\t\t\t\tconst children = toNode(branch);\n\t\t\t\t\tconst [only] = children;\n\n\t\t\t\t\treturn children.length === 1 && only !== undefined\n\t\t\t\t\t\t? only\n\t\t\t\t\t\t: { _tag: \"Sequence\", children };\n\t\t\t\t}),\n\t\t\t\tconcurrency: item.concurrency,\n\t\t\t},\n\t\t];\n\t});\n\nconst contentOf = (member: Member): Migration.Content =>\n\t(member.direction === \"forward\" ? member.migration.content : member.migration.revert) ?? [];\n\nconst buildPlan = (\n\tcontext: Context,\n\tfrom: Version,\n\tto: Version,\n\tdirection: RequestDirection,\n\tedges: ReadonlyArray<Edge>,\n): Result.Result<Plan, RewriteError> => {\n\tconst route = routeOf(from, edges);\n\tconst members = edges.flatMap((edge) => edge.members);\n\n\tconst items = members.flatMap((member, index): ReadonlyArray<Item> => {\n\t\tconst content = contentOf(member);\n\t\tconst make: MakeOccurrence = (action, instruction) => ({\n\t\t\t_tag: \"Occurrence\",\n\t\t\tid: declaredOccurrenceId(member.migration, member.direction, action),\n\t\t\taction,\n\t\t\tmigration: member.migration,\n\t\t\tdirection: member.direction,\n\t\t\tinstruction,\n\t\t\torigin: { _tag: \"Declared\" },\n\t\t});\n\t\tconst declared = itemsOf(stepsOf(content), make, index);\n\t\tif (declared.length === 0 && hasProse(content)) return [{ _tag: \"Barrier\", step: index }];\n\n\t\treturn declared;\n\t});\n\n\tconst rewritten = rewrite(items, context.declarations.rules);\n\tif (rewritten._tag === \"Failure\") {\n\t\tconst failure = rewritten.failure;\n\t\tswitch (failure._tag) {\n\t\t\tcase \"RewriteCycle\":\n\t\t\t\treturn Result.fail(\n\t\t\t\t\tnew RewriteCycle({\n\t\t\t\t\t\troute: route.id,\n\t\t\t\t\t\trules: failure.rules,\n\t\t\t\t\t\tactions: failure.actions,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\tcase \"ConflictingRewrites\":\n\t\t\t\treturn Result.fail(\n\t\t\t\t\tnew ConflictingRewrites({ route: route.id, outcomes: failure.outcomes }),\n\t\t\t\t);\n\t\t}\n\n\t\treturn Result.fail(\n\t\t\tnew RewriteLimitExceeded({\n\t\t\t\troute: route.id,\n\t\t\t\tlimit: failure.limit,\n\t\t\t\tvalue: failure.value,\n\t\t\t}),\n\t\t);\n\t}\n\tconst { items: optimized, trace } = rewritten.outcome;\n\n\tconst explanations: Array<Explanation> = trace.map((application) => ({\n\t\t_tag: \"Rewrite\",\n\t\trule: application.rule,\n\t\tremoved: application.removed,\n\t\tproduced: application.produced,\n\t}));\n\n\tconst steps = members.map((member, index): Step => {\n\t\tconst stepItems = optimized.filter((item) => item.step === index);\n\t\tconst content = contentOf(member);\n\t\tconst declaredCount = actionsOfSteps(stepsOf(content)).length;\n\t\tconst retained = occurrencesOf(stepItems);\n\t\tconst guide = resolveGuide(content, retained, (action) =>\n\t\t\tdeclaredOccurrenceId(member.migration, member.direction, action),\n\t\t);\n\t\tconst allRemoved = declaredCount > 0 && retained.length === 0;\n\t\t// `noop` describes the zero-work sides. A revert added to a noop migration is work.\n\t\tconst noop = member.migration.noop && content.length === 0;\n\t\tconst omitted = noop || allRemoved;\n\t\tif (omitted) {\n\t\t\texplanations.push({\n\t\t\t\t_tag: \"OmittedStep\",\n\t\t\t\tmigration: member.migration,\n\t\t\t\tdirection: member.direction,\n\t\t\t\treason: noop ? \"noop\" : \"all-actions-removed\",\n\t\t\t});\n\t\t}\n\t\tconst [stepFrom, stepTo] =\n\t\t\tmember.direction === \"forward\"\n\t\t\t\t? [member.migration.from, member.migration.to]\n\t\t\t\t: [member.migration.to, member.migration.from];\n\n\t\treturn {\n\t\t\t_tag: \"Step\",\n\t\t\tmigration: member.migration,\n\t\t\tdirection: member.direction,\n\t\t\tfrom: stepFrom,\n\t\t\tto: stepTo,\n\t\t\tnode: { _tag: \"Sequence\", children: toNode(stepItems) },\n\t\t\tguide: omitted ? [] : guide,\n\t\t\tomitted,\n\t\t};\n\t});\n\n\tconst changes: Array<Change.Any> = [];\n\tfor (const member of members) {\n\t\tfor (const change of member.migration.addresses) {\n\t\t\tif (!changes.some((known) => known.id === change.id)) changes.push(change);\n\t\t}\n\t}\n\n\treturn Result.succeed({\n\t\t_tag: \"Plan\",\n\t\tfrom,\n\t\tto,\n\t\tdirection,\n\t\troute,\n\t\tsteps,\n\t\toccurrences: occurrencesOf(optimized),\n\t\tchanges,\n\t\texplanations,\n\t\tcoverage: \"static\",\n\t});\n};\n\nconst summaryOf = (candidate: Candidate): RouteSummary => ({\n\tid: candidate.route.id,\n\tmigrations: candidate.edges.flatMap((edge) =>\n\t\tedge.members.map((member) => member.migration.id),\n\t),\n\tshortcuts: candidate.edges.flatMap((edge) =>\n\t\tedge.shortcut === undefined ? [] : [edge.shortcut.id],\n\t),\n\tactions: Result.isSuccess(candidate.plan)\n\t\t? candidate.plan.success.occurrences.length\n\t\t: undefined,\n\tcost: candidate.cost,\n\tfailure: Result.isFailure(candidate.plan) ? candidate.plan.failure.message : undefined,\n});\n\n/** Migration tokens of a route, with shortcut hops expanded to the route they replace. */\nconst canonicalTokens = (candidate: Candidate) =>\n\tJSON.stringify(\n\t\tcandidate.edges.flatMap((edge) =>\n\t\t\tedge.shortcut === undefined\n\t\t\t\t? edge.members.map((member) => [member.direction, member.migration.id])\n\t\t\t\t: edge.shortcut.replaces.map((migration) => [\"forward\", migration.id]),\n\t\t),\n\t);\n\nconst shortcutCount = (candidate: Candidate) =>\n\tcandidate.edges.filter((edge) => edge.shortcut !== undefined).length;\n\nconst minimal = (\n\tcandidates: ReadonlyArray<Candidate>,\n\tmeasure: (candidate: Candidate) => number | undefined,\n): ReadonlyArray<Candidate> => {\n\tconst measured = candidates.flatMap((candidate) => {\n\t\tconst value = measure(candidate);\n\n\t\treturn value === undefined ? [] : [{ candidate, value }];\n\t});\n\tconst best = Math.min(...measured.map((entry) => entry.value));\n\n\treturn measured.filter((entry) => entry.value === best).map((entry) => entry.candidate);\n};\n\nconst applyPolicy = (\n\tpolicy: RoutePolicy,\n\tcandidates: ReadonlyArray<Candidate>,\n): ReadonlyArray<Candidate> => {\n\tswitch (policy) {\n\t\tcase \"fewest-actions\":\n\t\t\treturn minimal(candidates, (candidate) =>\n\t\t\t\tResult.isSuccess(candidate.plan)\n\t\t\t\t\t? candidate.plan.success.occurrences.length\n\t\t\t\t\t: undefined,\n\t\t\t);\n\t\tcase \"fewest-migrations\":\n\t\t\treturn minimal(candidates, (candidate) =>\n\t\t\t\tcandidate.edges.reduce((total, edge) => total + edge.members.length, 0),\n\t\t\t);\n\t\tcase \"lowest-cost\":\n\t\t\treturn minimal(candidates, (candidate) => candidate.cost);\n\t}\n\n\t// prefer-shortcuts: drop a route when another candidate is the same canonical route\n\t// with more of it replaced by shortcuts. Unrelated routes stay ambiguous.\n\treturn candidates.filter(\n\t\t(candidate) =>\n\t\t\t!candidates.some(\n\t\t\t\t(other) =>\n\t\t\t\t\tother !== candidate &&\n\t\t\t\t\tcanonicalTokens(other) === canonicalTokens(candidate) &&\n\t\t\t\t\tshortcutCount(other) > shortcutCount(candidate),\n\t\t\t),\n\t);\n};\n\nconst depthOf = (context: Context, id: string) => context.ancestors.get(id)?.size ?? 0;\n\n/** Distance between two versions in the release ancestry tree. */\nconst ancestryDistance = (context: Context, self: string, that: string): number => {\n\tconst selfLine = [self, ...ancestorsInOrder(context, self)];\n\tconst thatLine = new Set([that, ...ancestorsInOrder(context, that)]);\n\tconst common = selfLine.find((id) => thatLine.has(id));\n\tif (common === undefined) return Number.POSITIVE_INFINITY;\n\n\treturn depthOf(context, self) + depthOf(context, that) - 2 * depthOf(context, common);\n};\n\nconst ancestorsInOrder = (context: Context, id: string): ReadonlyArray<string> => {\n\tconst result: Array<string> = [];\n\tlet current = context.versions.get(id)?.previous;\n\twhile (current !== undefined && !result.includes(current.id)) {\n\t\tresult.push(current.id);\n\t\tcurrent = context.versions.get(current.id)?.previous;\n\t}\n\n\treturn result;\n};\n\n/** The ancestry path between two versions, through their closest common ancestor. */\nconst ancestryPath = (context: Context, from: string, to: string): ReadonlyArray<string> => {\n\tconst fromLine = [from, ...ancestorsInOrder(context, from)];\n\tconst toLine = [to, ...ancestorsInOrder(context, to)];\n\tconst common = fromLine.find((id) => toLine.includes(id));\n\tif (common === undefined) return [];\n\n\treturn [\n\t\t...fromLine.slice(0, fromLine.indexOf(common) + 1),\n\t\t...Arr.reverse(toLine.slice(0, toLine.indexOf(common))),\n\t];\n};\n\nexport const reachable = (\n\tcontext: Context,\n\tfrom: string,\n\tfamily: ReadonlySet<Edge[\"class\"]>,\n): ReadonlyArray<string> => {\n\tconst seen = new Set([from]);\n\tconst queue = [from];\n\tfor (let current = queue.shift(); current !== undefined; current = queue.shift()) {\n\t\tfor (const edge of context.edges) {\n\t\t\tif (edge.from.id !== current || !family.has(edge.class) || seen.has(edge.to.id))\n\t\t\t\tcontinue;\n\n\t\t\tseen.add(edge.to.id);\n\t\t\tqueue.push(edge.to.id);\n\t\t}\n\t}\n\tseen.delete(from);\n\n\treturn [...seen];\n};\n\nconst familiesFor = (direction: RequestDirection) => {\n\tif (direction === \"upgrade\") return [families[0]];\n\tif (direction === \"downgrade\") return [families[1]];\n\n\treturn families;\n};\n\nconst unsupported = (context: Context, from: string, to: string, direction: RequestDirection) => {\n\tconst allowed = familiesFor(direction).flatMap((family) =>\n\t\tfamily === undefined ? [] : [family],\n\t);\n\tconst reachableIds = Arr.sort(\n\t\tnew Set(allowed.flatMap((family) => reachable(context, from, family))),\n\t\tOrder.String,\n\t);\n\tconst distances = reachableIds.map((id) => ({\n\t\tid,\n\t\tdistance: ancestryDistance(context, id, to),\n\t}));\n\tconst best = Math.min(...distances.map((entry) => entry.distance));\n\tconst closest = Number.isFinite(best)\n\t\t? distances.filter((entry) => entry.distance === best).map((entry) => entry.id)\n\t\t: [];\n\n\tconst path = ancestryPath(context, from, to);\n\tconst blockers: Array<Blocker> = [];\n\tfor (let index = 0; index + 1 < path.length; index++) {\n\t\tconst hopFrom = path[index];\n\t\tconst hopTo = path[index + 1];\n\t\tif (hopFrom === undefined || hopTo === undefined) continue;\n\t\tif (context.edges.some((edge) => edge.from.id === hopFrom && edge.to.id === hopTo))\n\t\t\tcontinue;\n\n\t\tblockers.push({\n\t\t\tfrom: hopFrom,\n\t\t\tto: hopTo,\n\t\t\treason: `No migration is declared from \"${hopFrom}\" to \"${hopTo}\".`,\n\t\t});\n\t}\n\n\t// The common ancestor where an ancestry path turns from moving down to moving up.\n\tconst turn = path.find(\n\t\t(id) =>\n\t\t\tcontext.ancestors.get(from)?.has(id) === true &&\n\t\t\tcontext.ancestors.get(to)?.has(id) === true,\n\t);\n\tif (blockers.length === 0 && turn !== undefined) {\n\t\tblockers.push({\n\t\t\tfrom,\n\t\t\tto,\n\t\t\treason: `A route through \"${turn}\" would combine a downgrade with an upgrade. Declare a migration from \"${from}\" to \"${to}\".`,\n\t\t});\n\t}\n\n\treturn new UnsupportedRoute({\n\t\tfrom,\n\t\tto,\n\t\tdirection,\n\t\treachable: reachableIds,\n\t\tclosest,\n\t\tblockers,\n\t});\n};\n\n/** @since @next */\nexport type ResolveOptions = {\n\treadonly from: Version | string;\n\treadonly to: Version | string;\n\t/** Selects a candidate route by identifier. */\n\treadonly route?: string;\n\t/** Chooses between candidate routes. Ties still fail as ambiguous. */\n\treadonly policy?: RoutePolicy;\n};\n\nexport const lookup = (context: Context, reference: Version | string) => {\n\tconst id = typeof reference === \"string\" ? reference : reference.id;\n\tconst version = context.versions.get(id);\n\n\treturn version === undefined\n\t\t? Result.fail(new UnknownVersion({ version: id, known: [...context.versions.keys()] }))\n\t\t: Result.succeed(version);\n};\n\nexport const candidatesBetween = (\n\tcontext: Context,\n\tfrom: Version,\n\tto: Version,\n): Result.Result<ReadonlyArray<Candidate>, TooManyRoutes> => {\n\tconst direction = requestDirection(context, from.id, to.id);\n\tconst { routes, overLimit } = enumerateRoutes(context, from, to);\n\tif (overLimit) {\n\t\treturn Result.fail(new TooManyRoutes({ from: from.id, to: to.id, limit: routeLimit }));\n\t}\n\n\treturn Result.succeed(\n\t\troutes.map((edges) => ({\n\t\t\troute: routeOf(from, edges),\n\t\t\tedges,\n\t\t\tplan: buildPlan(context, from, to, direction, edges),\n\t\t\tcost: routeCost(edges),\n\t\t})),\n\t);\n};\n\nexport const resolve = (\n\tcontext: Context,\n\toptions: ResolveOptions,\n): Result.Result<Plan, ResolveError> =>\n\tResult.gen(function* () {\n\t\tconst from = yield* lookup(context, options.from);\n\t\tconst to = yield* lookup(context, options.to);\n\t\tconst direction = requestDirection(context, from.id, to.id);\n\t\tif (direction === \"none\") {\n\t\t\treturn yield* buildPlan(context, from, to, direction, []);\n\t\t}\n\n\t\tconst candidates = yield* candidatesBetween(context, from, to);\n\t\tif (candidates.length === 0)\n\t\t\treturn yield* Result.fail(unsupported(context, from.id, to.id, direction));\n\n\t\tif (options.route !== undefined) {\n\t\t\tconst selected = candidates.find((candidate) => candidate.route.id === options.route);\n\t\t\tif (selected === undefined) {\n\t\t\t\treturn yield* Result.fail(\n\t\t\t\t\tnew UnknownRoute({\n\t\t\t\t\t\troute: options.route,\n\t\t\t\t\t\tcandidates: candidates.map(summaryOf),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn yield* selected.plan;\n\t\t}\n\n\t\tconst chosen =\n\t\t\toptions.policy === undefined ? candidates : applyPolicy(options.policy, candidates);\n\t\tconst [only] = chosen;\n\t\tif (chosen.length === 1 && only !== undefined) return yield* only.plan;\n\n\t\treturn yield* Result.fail(\n\t\t\tnew AmbiguousRoute({\n\t\t\t\tfrom: from.id,\n\t\t\t\tto: to.id,\n\t\t\t\tcandidates: (chosen.length === 0 ? candidates : chosen).map(summaryOf),\n\t\t\t\tpolicy: options.policy,\n\t\t\t}),\n\t\t);\n\t});\n\n/**\n * A reachable destination and the identifiers of its candidate routes.\n *\n * @since @next\n */\nexport type Destination = {\n\treadonly version: Version;\n\treadonly routes: ReadonlyArray<string>;\n\t/**\n\t * Present when more routes exist than route search explores. `routes` then lists the\n\t * routes found, cheapest first, and `History.resolve` to this destination fails with\n\t * `TooManyRoutes`.\n\t */\n\treadonly overLimit?: true;\n};\n\nconst semverOrder = (self: string, that: string): number | undefined => {\n\tconst parsedSelf = SemVer.parse(self);\n\tconst parsedThat = SemVer.parse(that);\n\tif (Result.isFailure(parsedSelf) || Result.isFailure(parsedThat)) return undefined;\n\n\treturn SemVer.Order(parsedSelf.success, parsedThat.success);\n};\n\n/**\n * Destinations reachable from a version. Cross-branch destinations are classified by\n * semver order when both identifiers parse, and listed in both directions otherwise.\n * Classification is presentation only; it does not change routing.\n */\nexport const destinations = (\n\tcontext: Context,\n\tfrom: Version,\n\tkind: \"upgrade\" | \"downgrade\",\n): ReadonlyArray<Destination> => {\n\tconst family = kind === \"upgrade\" ? families[0] : families[1];\n\tif (family === undefined) return [];\n\n\treturn reachable(context, from.id, family).flatMap((id) => {\n\t\tconst version = context.versions.get(id);\n\t\tif (version === undefined) return [];\n\n\t\tconst direction = requestDirection(context, from.id, id);\n\t\tif (direction === \"cross-branch\") {\n\t\t\tconst order = semverOrder(id, from.id);\n\t\t\tif (order !== undefined && (kind === \"upgrade\" ? order < 0 : order > 0)) return [];\n\t\t} else if (direction !== kind) {\n\t\t\treturn [];\n\t\t}\n\n\t\tconst { routes, overLimit } = enumerateRoutes(context, from, version);\n\t\tif (!overLimit) {\n\t\t\treturn [{ version, routes: routes.map((edges) => routeOf(from, edges).id) }];\n\t\t}\n\t\tconst cheapest = Arr.sort(\n\t\t\troutes,\n\t\t\tOrder.mapInput(Order.Number, (edges: ReadonlyArray<Edge>) => routeCost(edges)),\n\t\t);\n\n\t\treturn [\n\t\t\t{\n\t\t\t\tversion,\n\t\t\t\troutes: cheapest.map((edges) => routeOf(from, edges).id),\n\t\t\t\toverLimit: true as const,\n\t\t\t},\n\t\t];\n\t});\n};\n","import { Predicate, Result } from \"effect\";\n\nimport type * as Action from \"../../foundation/action.ts\";\nimport type * as Change from \"../../foundation/change.ts\";\nimport type * as Migration from \"../../foundation/migration.ts\";\nimport type { Plan } from \"../../foundation/plan.ts\";\nimport type * as Rule from \"../../foundation/rule.ts\";\nimport type * as Shortcut from \"../../foundation/shortcut.ts\";\nimport type { Version } from \"../../foundation/version.ts\";\nimport { InvalidHistory, type ResolveError, type UnknownVersion } from \"./resolve-error.ts\";\nimport {\n\tdestinations,\n\tlookup as lookupVersion,\n\tmakeContext,\n\tresolve as resolveRoute,\n\ttype Context,\n\ttype Destination,\n\ttype ResolveOptions,\n\ttype RoutePolicy,\n} from \"./resolve.ts\";\nimport { validate as validateDeclarations, type Issue } from \"./validate.ts\";\n\nexport * from \"./resolve-error.ts\";\nexport type { Destination, Issue, ResolveOptions, RoutePolicy };\n\n/** @since @next */\nexport type History<A extends Action.Any = Action.Any, C extends Change.Any = Change.Any> = {\n\treadonly _tag: \"History\";\n\treadonly versions: ReadonlyArray<Version>;\n\treadonly migrations: ReadonlyArray<Migration.Any>;\n\treadonly rules: ReadonlyArray<Rule.Any>;\n\treadonly shortcuts: ReadonlyArray<Shortcut.Any>;\n\t/** Type-level record of every action instance that a plan can contain. */\n\treadonly \"~actions\"?: A;\n\t/** Type-level record of every change that a plan's `changes` can contain. */\n\treadonly \"~changes\"?: C;\n};\n\n/**\n * Any history.\n *\n * @since @next\n */\nexport type Any = History<any>;\n\n/**\n * Every action instance that a plan resolved from the history can contain.\n *\n * @since @next\n */\nexport type ActionsOf<H> = H extends History<infer A> ? A : never;\n\n/**\n * Every change that a plan resolved from the history can list in `changes`.\n *\n * @since @next\n */\nexport type ChangesOf<H> = H extends History<any, infer C> ? C : never;\n\n/**\n * Registers declarations. Migrations are registered independently of versions, so\n * routes can be added later without changing published release definitions.\n *\n * `make` does not throw. Use `History.validate` to list declaration issues;\n * resolution fails with `InvalidHistory` when there are any.\n *\n * @since @next\n */\nexport const make = <\n\tconst M extends ReadonlyArray<Migration.Any>,\n\tconst R extends ReadonlyArray<Rule.Any> = [],\n\tconst S extends ReadonlyArray<Shortcut.Any> = [],\n>(declarations: {\n\treadonly versions: ReadonlyArray<Version>;\n\treadonly migrations: M;\n\treadonly rules?: R;\n\treadonly shortcuts?: S;\n}): History<\n\tMigration.ActionsOf<M[number]> | Rule.ActionsOf<R[number]> | Shortcut.ActionsOf<S[number]>,\n\tMigration.ChangesOf<M[number]> | Shortcut.ChangesOf<S[number]>\n> => ({\n\t_tag: \"History\",\n\tversions: declarations.versions,\n\tmigrations: declarations.migrations,\n\trules: declarations.rules ?? [],\n\tshortcuts: declarations.shortcuts ?? [],\n});\n\n/** @since @next */\nexport const isHistory = (value: unknown): value is Any => Predicate.isTagged(value, \"History\");\n\nconst contexts = new WeakMap<\n\tAny,\n\t{ readonly issues: ReadonlyArray<Issue>; readonly context: Context }\n>();\n\nconst prepare = (history: Any) => {\n\tconst cached = contexts.get(history);\n\tif (cached !== undefined) return cached;\n\n\tconst prepared = { issues: validateDeclarations(history), context: makeContext(history) };\n\tcontexts.set(history, prepared);\n\n\treturn prepared;\n};\n\n/**\n * Lists declaration issues in a deterministic order. An empty list means valid.\n *\n * @since @next\n */\nexport const validate = (history: Any): ReadonlyArray<Issue> => prepare(history).issues;\n\nconst valid = (history: Any): Result.Result<Context, InvalidHistory> => {\n\tconst { issues, context } = prepare(history);\n\n\treturn issues.length === 0\n\t\t? Result.succeed(context)\n\t\t: Result.fail(new InvalidHistory({ issues }));\n};\n\n/**\n * Resolves an optimized plan between two versions. Planning needs no handlers or\n * execution services, and it never reads or modifies consumer files.\n *\n * When several routes connect the versions, resolution fails with `AmbiguousRoute`\n * unless the `route` option selects one or a route `policy` leaves exactly one.\n *\n * @example\n * ```ts\n * const result = History.resolve(history, { from: \"1.5.3\", to: \"2.0.0\" });\n * if (Result.isSuccess(result)) console.log(result.success.route.id);\n * ```\n *\n * @since @next\n */\nexport const resolve = <A extends Action.Any, C extends Change.Any>(\n\thistory: History<A, C>,\n\toptions: ResolveOptions,\n): Result.Result<Plan<A, \"static\", C>, ResolveError> =>\n\t// Every occurrence and change comes from the history's declarations, whose unions are\n\t// `A` and `C`.\n\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion\n\tResult.flatMap(valid(history), (context) => resolveRoute(context, options)) as Result.Result<\n\t\tPlan<A, \"static\", C>,\n\t\tResolveError\n\t>;\n\n/**\n * Destinations reachable by upgrade from a version, with their candidate routes.\n *\n * @since @next\n */\nexport const upgrades = (\n\thistory: Any,\n\toptions: { readonly from: Version | string },\n): Result.Result<ReadonlyArray<Destination>, InvalidHistory | UnknownVersion> =>\n\treachableFrom(history, options.from, \"upgrade\");\n\n/**\n * Destinations reachable by downgrade from a version, with their candidate routes.\n *\n * @since @next\n */\nexport const downgrades = (\n\thistory: Any,\n\toptions: { readonly from: Version | string },\n): Result.Result<ReadonlyArray<Destination>, InvalidHistory | UnknownVersion> =>\n\treachableFrom(history, options.from, \"downgrade\");\n\nconst reachableFrom = (history: Any, from: Version | string, kind: \"upgrade\" | \"downgrade\") =>\n\tResult.flatMap(valid(history), (context) =>\n\t\tResult.map(lookupVersion(context, from), (version) => destinations(context, version, kind)),\n\t);\n","import { Predicate } from \"effect\";\n\nimport type * as Action from \"./action.ts\";\nimport { isAction, isRef } from \"./action.ts\";\nimport { describeValue, dedent, isScalar, type Scalar } from \"./template.ts\";\n\n/**\n * Literal prose.\n *\n * @since @next\n */\nexport type Text = {\n\treadonly _tag: \"Text\";\n\treadonly text: string;\n};\n\n/**\n * Prose content: text and action mentions.\n *\n * @since @next\n */\nexport type Prose = ReadonlyArray<Text | Action.Ref>;\n\n/**\n * Values accepted inside prose templates.\n *\n * @since @next\n */\nexport type ProseValue = Scalar | Action.Ref;\n\n/**\n * Prose associated with exactly one action occurrence. The block declares that\n * occurrence; when optimization removes the action, the block leaves the resolved guide\n * with it.\n *\n * @since @next\n */\nexport type Instruction<A extends Action.Any = Action.Any> = {\n\treadonly _tag: \"Instruction\";\n\treadonly action: A;\n\treadonly content: Prose;\n};\n\nexport const isInstruction = (value: unknown): value is Instruction =>\n\tPredicate.isTagged(value, \"Instruction\");\n\n/** Builds prose from a tagged template. Throws on values that are not text or mentions. */\nexport const prose = (\n\tstrings: ReadonlyArray<string>,\n\tvalues: ReadonlyArray<unknown>,\n\tcontext: string,\n): Prose => {\n\tconst literals = dedent(strings);\n\tconst content: Array<Text | Action.Ref> = [];\n\n\tconst pushText = (text: string) => {\n\t\tif (text === \"\") return;\n\n\t\tconst last = content.at(-1);\n\t\tif (last?._tag === \"Text\") {\n\t\t\tcontent[content.length - 1] = { _tag: \"Text\", text: last.text + text };\n\n\t\t\treturn;\n\t\t}\n\t\tcontent.push({ _tag: \"Text\", text });\n\t};\n\n\tfor (const [index, literal] of literals.entries()) {\n\t\tpushText(literal);\n\t\tif (index >= values.length) continue;\n\n\t\tconst value = values[index];\n\t\tif (isScalar(value)) {\n\t\t\tpushText(String(value));\n\t\t\tcontinue;\n\t\t}\n\t\tif (isRef(value)) {\n\t\t\tcontent.push(value);\n\t\t\tcontinue;\n\t\t}\n\t\tif (isAction(value)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${context}: action \"${value.id}\" cannot be interpolated here because it would declare another occurrence. Use Action.ref(action) to mention it.`,\n\t\t\t);\n\t\t}\n\t\tthrow new TypeError(`${context}: cannot interpolate ${describeValue(value)}.`);\n\t}\n\n\treturn content;\n};\n\n/**\n * Associates prose with one action occurrence.\n *\n * @example\n * ```ts\n * Migration.instruction(renameTimeout)`\n * \tRename the timeout option, keeping its existing value.\n * `;\n * ```\n *\n * @since @next\n */\nexport const instruction =\n\t<A extends Action.Any>(action: A) =>\n\t(strings: TemplateStringsArray, ...values: ReadonlyArray<ProseValue>): Instruction<A> => ({\n\t\t_tag: \"Instruction\",\n\t\taction,\n\t\tcontent: prose(strings, values, `Instruction for \"${action.id}\"`),\n\t});\n","import { Predicate } from \"effect\";\n\nimport type * as Action from \"./action.ts\";\nimport { isAction, isParallel, isRef, isSequence } from \"./action.ts\";\nimport type * as Change from \"./change.ts\";\nimport { instruction, isInstruction, type Text } from \"./instruction.ts\";\nimport { describeValue, dedent, isScalar, type Scalar } from \"./template.ts\";\nimport type { Version } from \"./version.ts\";\n\nexport { instruction };\nexport type { Instruction, Prose, ProseValue, Text } from \"./instruction.ts\";\n\n/**\n * Prose, mentions, and occurrence-declaring steps in template order.\n *\n * @since @next\n */\nexport type Content<A extends Action.Any = Action.Any> = ReadonlyArray<\n\tText | Action.Ref | Action.Step<A>\n>;\n\n/**\n * Values accepted in migration templates.\n *\n * @since @next\n */\nexport type Interpolation = Scalar | Action.Ref | Action.Step;\n\n/** @since @next */\nexport type Migration<A extends Action.Any = Action.Any, C extends Change.Any = Change.Any> = {\n\treadonly _tag: \"Migration\";\n\treadonly id: string;\n\treadonly from: Version;\n\treadonly to: Version;\n\t/** The logical changes this transition handles. */\n\treadonly addresses: ReadonlyArray<C>;\n\t/** Whether this is an explicit zero-work transition. */\n\treadonly noop: boolean;\n\t/** Author-declared cost, used only by the `lowest-cost` route policy. */\n\treadonly cost: number | undefined;\n\treadonly content: Content;\n\t/** The reverse transition, from `to` back to `from`. Absent means no reverse edge. */\n\treadonly revert: Content | undefined;\n\t/** Type-level record of the action instances in `content` and `revert`. */\n\treadonly \"~actions\"?: A;\n};\n\n/**\n * Any migration.\n *\n * @since @next\n */\nexport type Any = Migration<any>;\n\n/**\n * The action instances a migration can contribute to a plan.\n *\n * @since @next\n */\nexport type ActionsOf<M> = M extends Migration<infer A> ? A : never;\n\n/**\n * The changes a migration addresses.\n *\n * @since @next\n */\nexport type ChangesOf<M> = M extends Migration<any, infer C> ? C : never;\n\n/** @since @next */\nexport type Options<C extends Change.Any = Change.Any> = {\n\treadonly from: Version;\n\treadonly to: Version;\n\treadonly addresses?: ReadonlyArray<C>;\n\treadonly cost?: number;\n};\n\n/** @since @next */\nexport const isMigration = (value: unknown): value is Any => Predicate.isTagged(value, \"Migration\");\n\nconst isStep = (value: unknown): value is Action.Step =>\n\tisAction(value) || isInstruction(value) || isSequence(value) || isParallel(value);\n\nconst validateStep = (step: Action.Step, context: string): void => {\n\tif (isSequence(step)) {\n\t\tfor (const child of step.children) checkStep(child, context);\n\n\t\treturn;\n\t}\n\tif (isParallel(step)) {\n\t\tfor (const branch of step.branches) checkStep(branch, context);\n\t}\n};\n\nconst checkStep = (value: unknown, context: string): void => {\n\tif (!isStep(value)) {\n\t\tthrow new TypeError(\n\t\t\t`${context}: a group can only contain actions, instructions, and groups.`,\n\t\t);\n\t}\n\tvalidateStep(value, context);\n};\n\n/** Builds content from a tagged template. */\nconst content = (\n\tstrings: ReadonlyArray<string>,\n\tvalues: ReadonlyArray<unknown>,\n\tcontext: string,\n): Content => {\n\tconst literals = dedent(strings);\n\tconst result: Array<Text | Action.Ref | Action.Step> = [];\n\n\tconst pushText = (text: string) => {\n\t\tif (text === \"\") return;\n\n\t\tconst last = result.at(-1);\n\t\tif (last?._tag === \"Text\") {\n\t\t\tresult[result.length - 1] = { _tag: \"Text\", text: last.text + text };\n\n\t\t\treturn;\n\t\t}\n\t\tresult.push({ _tag: \"Text\", text });\n\t};\n\n\tfor (const [index, literal] of literals.entries()) {\n\t\tpushText(literal);\n\t\tif (index >= values.length) continue;\n\n\t\tconst value = values[index];\n\t\tif (isScalar(value)) {\n\t\t\tpushText(String(value));\n\t\t\tcontinue;\n\t\t}\n\t\tif (isRef(value)) {\n\t\t\tresult.push(value);\n\t\t\tcontinue;\n\t\t}\n\t\tif (isStep(value)) {\n\t\t\tvalidateStep(value, context);\n\t\t\tresult.push(value);\n\t\t\tcontinue;\n\t\t}\n\t\tthrow new TypeError(`${context}: cannot interpolate ${describeValue(value)}.`);\n\t}\n\n\treturn result;\n};\n\n/**\n * Declares a migration between exact versions. Interpolated actions, instruction blocks,\n * and groups declare occurrences; `Action.ref` only mentions an action.\n *\n * @example\n * ```ts\n * const migrate152To200 = Migration.make(\"1.5.2-to-2.0.0\", {\n * \tfrom: v152,\n * \tto: v200,\n * \taddresses: [timeoutRenamed],\n * })`\n * \tUpdate the configuration for export A:\n *\n * \t${renameExportA}\n * `;\n * ```\n *\n * @since @next\n */\nexport const make =\n\t<C extends Change.Any = never>(id: string, options: Options<C>) =>\n\t<const V extends ReadonlyArray<Interpolation>>(\n\t\tstrings: TemplateStringsArray,\n\t\t...values: V\n\t): Migration<Action.ActionsOf<V[number]>, C> => ({\n\t\t_tag: \"Migration\",\n\t\tid,\n\t\tfrom: options.from,\n\t\tto: options.to,\n\t\taddresses: options.addresses ?? [],\n\t\tnoop: false,\n\t\tcost: options.cost,\n\t\tcontent: content(strings, values, `Migration \"${id}\"`),\n\t\trevert: undefined,\n\t});\n\n/** @since @next */\nexport type NoopOptions<C extends Change.Any = Change.Any> = Options<C> & {\n\t/** Also declares the reverse transition as zero-work. */\n\treadonly reversible?: boolean;\n};\n\n/**\n * Declares a supported transition that requires no consumer work. It is a directed edge\n * like any migration. Do not use it to hide missing support for changes that need\n * instructions.\n *\n * @since @next\n */\nexport const noop = <C extends Change.Any = never>(\n\tid: string,\n\toptions: NoopOptions<C>,\n): Migration<never, C> => ({\n\t_tag: \"Migration\",\n\tid,\n\tfrom: options.from,\n\tto: options.to,\n\taddresses: options.addresses ?? [],\n\tnoop: true,\n\tcost: options.cost,\n\tcontent: [],\n\trevert: options.reversible === true ? [] : undefined,\n});\n\n/**\n * Adds a reverse transition. Register the returned migration in place of the original:\n * both share the same identifier. On a `Migration.noop`, the reverse is real work: only\n * the forward side stays zero-work.\n *\n * @example\n * ```ts\n * const reversible = Migration.withRevert(migrate152To200)`\n * \tRestore the previous configuration:\n *\n * \t${restoreTimeout}\n * `;\n * ```\n *\n * @since @next\n */\nexport const withRevert =\n\t<A extends Action.Any, C extends Change.Any>(migration: Migration<A, C>) =>\n\t<const V extends ReadonlyArray<Interpolation>>(\n\t\tstrings: TemplateStringsArray,\n\t\t...values: V\n\t): Migration<A | Action.ActionsOf<V[number]>, C> => ({\n\t\t...migration,\n\t\trevert: content(strings, values, `Revert of migration \"${migration.id}\"`),\n\t});\n","import { Predicate } from \"effect\";\n\nimport type * as Action from \"../foundation/action.ts\";\nimport type { History } from \"./planning/history.ts\";\n\n/** @since @next */\nexport type Package<A extends Action.Any = Action.Any> = {\n\treadonly _tag: \"Package\";\n\t/** The name of the modeled package, for example `@acme/widgets`. */\n\treadonly name: string;\n\treadonly history: History<A>;\n};\n\n/**\n * Defines the modeled package. It holds no renderer settings, release metadata, or\n * handlers.\n *\n * @example\n * ```ts\n * export const widgets = Package.make(\"@acme/widgets\", { history });\n * ```\n *\n * @since @next\n */\nexport const make = <A extends Action.Any>(\n\tname: string,\n\toptions: { readonly history: History<A> },\n): Package<A> => ({ _tag: \"Package\", name, history: options.history });\n\n/** @since @next */\nexport const isPackage = (value: unknown): value is Package<any> =>\n\tPredicate.isTagged(value, \"Package\");\n","import type * as Action from \"./action.ts\";\nimport type * as Change from \"./change.ts\";\nimport type { Instruction, Text } from \"./instruction.ts\";\nimport type * as Migration from \"./migration.ts\";\nimport type * as Rule from \"./rule.ts\";\nimport type * as Shortcut from \"./shortcut.ts\";\nimport type { Version } from \"./version.ts\";\n\n/**\n * Which side of a migration runs.\n *\n * @since @next\n */\nexport type Direction = \"forward\" | \"revert\";\n\n/**\n * How an occurrence entered the plan.\n *\n * @since @next\n */\nexport type Origin =\n\t| { readonly _tag: \"Declared\" }\n\t| {\n\t\t\treadonly _tag: \"Replacement\";\n\t\t\treadonly rule: Rule.Any;\n\t\t\t/** The occurrences the rule replaced, in order. */\n\t\t\treadonly replaces: ReadonlyArray<Occurrence>;\n\t };\n\n/**\n * One execution of an action instance in a plan. Its `id` is stable across prose edits:\n * it combines the migration, direction, and action identifiers, or the rule and the\n * replaced occurrences for a replacement.\n *\n * @since @next\n */\nexport type Occurrence<A extends Action.Any = Action.Any> = {\n\treadonly _tag: \"Occurrence\";\n\t/**\n\t * Unique within the plan. Built from the migration, direction, and action identifiers,\n\t * or from the rule and the replaced occurrences. Separator characters in author\n\t * identifiers are escaped with a backslash, so identifiers never collide.\n\t */\n\treadonly id: string;\n\treadonly action: A;\n\t/** The migration whose step contains this occurrence. */\n\treadonly migration: Migration.Any;\n\treadonly direction: Direction;\n\t/** The instruction block that declared this occurrence, if any. */\n\treadonly instruction: Instruction | undefined;\n\treadonly origin: Origin;\n};\n\n/** @since @next */\nexport type Sequence<A extends Action.Any = Action.Any> = {\n\treadonly _tag: \"Sequence\";\n\treadonly children: ReadonlyArray<Node<A>>;\n};\n\n/** @since @next */\nexport type Parallel<A extends Action.Any = Action.Any> = {\n\treadonly _tag: \"Parallel\";\n\treadonly branches: ReadonlyArray<Node<A>>;\n\treadonly concurrency: Action.Concurrency;\n};\n\n/**\n * The declared execution structure.\n *\n * @since @next\n */\nexport type Node<A extends Action.Any = Action.Any> = Occurrence<A> | Sequence<A> | Parallel<A>;\n\n/**\n * Resolved prose for a guide. Occurrences render as their instruction or description.\n *\n * @since @next\n */\nexport type GuideItem<A extends Action.Any = Action.Any> =\n\t| Text\n\t| Action.Ref\n\t| { readonly _tag: \"Occurrence\"; readonly occurrence: Occurrence<A> }\n\t| {\n\t\t\treadonly _tag: \"Group\";\n\t\t\treadonly kind: \"Sequence\" | \"Parallel\";\n\t\t\t/** One entry per retained child or branch. */\n\t\t\treadonly children: ReadonlyArray<ReadonlyArray<GuideItem<A>>>;\n\t };\n\n/**\n * One migration in the route. Steps are sequential barriers: a step starts only after\n * the previous step completed.\n *\n * @since @next\n */\nexport type Step<A extends Action.Any = Action.Any> = {\n\treadonly _tag: \"Step\";\n\treadonly migration: Migration.Any;\n\treadonly direction: Direction;\n\treadonly from: Version;\n\treadonly to: Version;\n\treadonly node: Sequence<A>;\n\t/** Resolved guide content. Empty when the step is omitted from the guide. */\n\treadonly guide: ReadonlyArray<GuideItem<A>>;\n\t/**\n\t * Whether the normal resolved guide leaves this step out: a noop, or a migration whose\n\t * actions were all removed by rules.\n\t */\n\treadonly omitted: boolean;\n};\n\n/**\n * Why the plan differs from the declared migrations.\n *\n * @since @next\n */\nexport type Explanation =\n\t| {\n\t\t\treadonly _tag: \"Rewrite\";\n\t\t\treadonly rule: Rule.Any;\n\t\t\treadonly removed: ReadonlyArray<Occurrence>;\n\t\t\treadonly produced: ReadonlyArray<Occurrence>;\n\t }\n\t| {\n\t\t\treadonly _tag: \"OmittedStep\";\n\t\t\treadonly migration: Migration.Any;\n\t\t\treadonly direction: Direction;\n\t\t\treadonly reason: \"noop\" | \"all-actions-removed\";\n\t };\n\n/**\n * A hop in a route: the migrations between two versions, or a shortcut.\n *\n * @since @next\n */\nexport type Hop =\n\t| {\n\t\t\treadonly _tag: \"Migrations\";\n\t\t\treadonly from: Version;\n\t\t\treadonly to: Version;\n\t\t\t/**\n\t\t\t * The migration side that moves between these versions. Validation allows one\n\t\t\t * side per transition, so this holds exactly one entry.\n\t\t\t */\n\t\t\treadonly migrations: ReadonlyArray<{\n\t\t\t\treadonly migration: Migration.Any;\n\t\t\t\treadonly direction: Direction;\n\t\t\t}>;\n\t }\n\t| {\n\t\t\treadonly _tag: \"Shortcut\";\n\t\t\treadonly from: Version;\n\t\t\treadonly to: Version;\n\t\t\treadonly shortcut: Shortcut.Any;\n\t };\n\n/** @since @next */\nexport type Route = {\n\t/**\n\t * Identifies the route for explicit selection: version identifiers joined by `>`,\n\t * with shortcut hops written as `[shortcut-id]`. A backslash escapes `\\`, `>`, `[`,\n\t * and `]` inside identifiers, so a version `a>b` appears as `a\\>b`.\n\t */\n\treadonly id: string;\n\treadonly hops: ReadonlyArray<Hop>;\n};\n\n/**\n * How the requested target relates to the source in release ancestry.\n *\n * @since @next\n */\nexport type RequestDirection = \"none\" | \"upgrade\" | \"downgrade\" | \"cross-branch\";\n\n/**\n * When executors check handler coverage. Static plans also expose uncovered actions in\n * the execution's type.\n *\n * @since @next\n */\nexport type Coverage = \"static\" | \"runtime\";\n\n/**\n * A resolved, optimized route between two versions. Every step stays traceable to its\n * migration and the changes that migration addresses.\n *\n * @since @next\n */\nexport type Plan<\n\tA extends Action.Any = Action.Any,\n\tC extends Coverage = \"static\",\n\tCh extends Change.Any = Change.Any,\n> = {\n\treadonly _tag: \"Plan\";\n\treadonly from: Version;\n\treadonly to: Version;\n\treadonly direction: RequestDirection;\n\treadonly route: Route;\n\treadonly steps: ReadonlyArray<Step<A>>;\n\t/** Occurrences in plan order. */\n\treadonly occurrences: ReadonlyArray<Occurrence<A>>;\n\t/** The changes addressed by the route's migrations. */\n\treadonly changes: ReadonlyArray<Ch>;\n\treadonly explanations: ReadonlyArray<Explanation>;\n\t/**\n\t * Whether executors check handler coverage only at run time. Plans resolved from a\n\t * history are checked statically against its conservative action union.\n\t */\n\treadonly coverage: C;\n};\n\n/**\n * Any plan.\n *\n * @since @next\n */\nexport type Any = Plan<any, any>;\n\n/**\n * The action instances of a plan.\n *\n * @since @next\n */\nexport type ActionsOf<P> = P extends Plan<infer A, any> ? A : never;\n\n/**\n * Whether the plan has no action occurrences. An empty plan is valid.\n *\n * @since @next\n */\nexport const isEmpty = (plan: Any): boolean => plan.occurrences.length === 0;\n\n/**\n * Marks a plan for run-time coverage checks only. Use it for dynamically selected or\n * loaded plans whose action union is not known statically. Executors still reject\n * missing handlers before any action body runs.\n *\n * @since @next\n */\nexport const withRuntimeCoverage = <A extends Action.Any, Ch extends Change.Any>(\n\tplan: Plan<A, Coverage, Ch>,\n): Plan<A, \"runtime\", Ch> => ({\n\t...plan,\n\tcoverage: \"runtime\",\n});\n","import { Predicate } from \"effect\";\n\nimport type * as Action from \"./action.ts\";\n\n/**\n * What a rule matches: an action instance, or a parallel group matched by its branch\n * structure. Matching a parallel group is an explicit structural rule.\n *\n * @since @next\n */\nexport type Pattern = Action.Any | Action.Parallel;\n\n/** @since @next */\nexport type Rule<A extends Action.Any = Action.Any> = {\n\treadonly _tag: \"Rule\";\n\treadonly id: string;\n\treadonly match: ReadonlyArray<Pattern>;\n\t/** Steps that take the place of the match. An empty replacement cancels it. */\n\treadonly replacement: ReadonlyArray<Action.Step<A>>;\n};\n\n/**\n * Any rule.\n *\n * @since @next\n */\nexport type Any = Rule<any>;\n\n/**\n * The action instances a rule can contribute to a plan.\n *\n * @since @next\n */\nexport type ActionsOf<R> = R extends Rule<infer A> ? A : never;\n\n/**\n * Declares a replacement. Cancellation, composition, and supersession all use it.\n *\n * The author asserts that the replacement is equivalent to the matched occurrences.\n * deltafold checks the rule's structure and where it applies, but it cannot prove the\n * equivalence.\n *\n * Ordinary rules match consecutive occurrences inside one sequential branch, including\n * across migration boundaries of a route. They never match across parallel branches.\n *\n * @example\n * ```ts\n * const cancelRoundTrip = Rule.replace(\"cancel-timeout-round-trip\", {\n * \tmatch: [renameTimeout, restoreTimeout],\n * \treplacement: [],\n * });\n * const combineRenames = Rule.replace(\"combine-renames\", {\n * \tmatch: [renameAtoB, renameBtoC],\n * \treplacement: [renameAtoC],\n * });\n * ```\n *\n * @since @next\n */\nexport const replace = <A extends Action.Any = never>(\n\tid: string,\n\toptions: {\n\t\treadonly match: ReadonlyArray<Pattern>;\n\t\treadonly replacement: ReadonlyArray<Action.Step<A>>;\n\t},\n): Rule<A> => ({\n\t_tag: \"Rule\",\n\tid,\n\tmatch: options.match,\n\treplacement: options.replacement,\n});\n\n/** @since @next */\nexport const isRule = (value: unknown): value is Any => Predicate.isTagged(value, \"Rule\");\n","import { Predicate } from \"effect\";\n\nimport type * as Action from \"./action.ts\";\nimport type * as Change from \"./change.ts\";\nimport type * as Migration from \"./migration.ts\";\nimport type { Version } from \"./version.ts\";\n\n/** @since @next */\nexport type Shortcut<A extends Action.Any = Action.Any, C extends Change.Any = Change.Any> = {\n\treadonly _tag: \"Shortcut\";\n\treadonly id: string;\n\treadonly from: Version;\n\treadonly to: Version;\n\t/** The canonical route this shortcut replaces, in order. */\n\treadonly replaces: ReadonlyArray<Migration.Any>;\n\t/** The migrations that run instead, in order. */\n\treadonly migrations: ReadonlyArray<Migration.Migration<A, C>>;\n\t/** Author-declared cost, used only by the `lowest-cost` route policy. */\n\treadonly cost: number | undefined;\n};\n\n/**\n * Any shortcut.\n *\n * @since @next\n */\nexport type Any = Shortcut<any>;\n\n/**\n * The action instances a shortcut can contribute to a plan.\n *\n * @since @next\n */\nexport type ActionsOf<S> = S extends Shortcut<infer A> ? A : never;\n\n/**\n * The changes addressed by a shortcut's migrations.\n *\n * @since @next\n */\nexport type ChangesOf<S> = S extends Shortcut<any, infer C> ? C : never;\n\n/**\n * Declares a shortcut. The author asserts that its migrations are equivalent to the\n * canonical route it replaces; deltafold does not prove it.\n *\n * @example\n * ```ts\n * const fastUpgrade = Shortcut.make(\"fast-upgrade\", {\n * \tfrom: v201,\n * \tto: v208,\n * \treplaces: [migrate202, migrate203, migrate204],\n * \tmigrations: [migrateDirectlyTo208],\n * });\n * ```\n *\n * @since @next\n */\nexport const make = <A extends Action.Any, C extends Change.Any = never>(\n\tid: string,\n\toptions: {\n\t\treadonly from: Version;\n\t\treadonly to: Version;\n\t\treadonly replaces: ReadonlyArray<Migration.Any>;\n\t\treadonly migrations: ReadonlyArray<Migration.Migration<A, C>>;\n\t\treadonly cost?: number;\n\t},\n): Shortcut<A, C> => ({\n\t_tag: \"Shortcut\",\n\tid,\n\tfrom: options.from,\n\tto: options.to,\n\treplaces: options.replaces,\n\tmigrations: options.migrations,\n\tcost: options.cost,\n});\n\n/** @since @next */\nexport const isShortcut = (value: unknown): value is Any => Predicate.isTagged(value, \"Shortcut\");\n","import { Predicate } from \"effect\";\n\nimport type * as Change from \"./change.ts\";\n\n/** @since @next */\nexport type Version<C extends Change.Any = Change.Any> = {\n\treadonly _tag: \"Version\";\n\treadonly id: string;\n\t/**\n\t * The release this version descends from. Absent for a root such as `0.0.0`. Only\n\t * this field sets ancestry: several versions can share a predecessor, and declaration\n\t * order and semver order have no effect.\n\t */\n\treadonly previous: Version | undefined;\n\t/** The changes that shipped in this release. */\n\treadonly changes: ReadonlyArray<C>;\n};\n\n/** @since @next */\nexport type Options<C extends Change.Any = Change.Any> = {\n\treadonly previous?: Version;\n\treadonly changes: ReadonlyArray<C>;\n};\n\n/**\n * Declares a version.\n *\n * @example\n * ```ts\n * const v0 = Version.make(\"0.0.0\", { changes: [] });\n * const v100 = Version.make(\"1.0.0\", { previous: v0, changes: [timeoutRenamed] });\n * ```\n *\n * @since @next\n */\nexport const make = <C extends Change.Any = never>(\n\tid: string,\n\toptions: Options<C>,\n): Version<C> => ({\n\t_tag: \"Version\",\n\tid,\n\tprevious: options.previous,\n\tchanges: options.changes,\n});\n\n/** @since @next */\nexport const isVersion = (value: unknown): value is Version => Predicate.isTagged(value, \"Version\");\n\n/**\n * Release metadata attached to a version by release tooling. It does not modify the\n * version registered in history.\n *\n * @since @next\n */\nexport type Release<M> = {\n\treadonly _tag: \"Release\";\n\treadonly version: Version;\n\treadonly metadata: M;\n};\n\n/**\n * Annotates a version with release metadata.\n *\n * @example\n * ```ts\n * export const release200 = Version.withMetadata(v200, {\n * \treleasedAt: \"2026-11-06T12:00:00Z\",\n * \tcommit: \"abc123\",\n * });\n * ```\n *\n * @since @next\n */\nexport const withMetadata = <const M>(version: Version, metadata: M): Release<M> => ({\n\t_tag: \"Release\",\n\tversion,\n\tmetadata,\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2HA,MAAaA,YACZ,MACA,UAA0D,CAAC,MAC9C;CACb,MAAM,WAAW,QAAQ,mBAAmB;CAE5C,OAAO;EACN,MAAM;EACN;EACA;EACA,OAAO,IAAI,aAAa;GACvB,MAAM;GACN;GACA;GACA;GACA,aAAa,SAAS,OAAO;EAC9B;CACD;AACD;;;;;;AAOA,MAAa,OAAO,YAAsB;CAAE,MAAM;CAAa;AAAO;;;;;;AAOtE,MAAa,YACZ,cACqC;CAAE,MAAM;CAAY;AAAS;;;;;;;AAQnE,MAAa,YACZ,UACA,UAAkD,CAAC,OACd;CACrC,MAAM;CACN;CACA,aAAa,QAAQ,eAAe;AACrC;;AAGA,MAAa,YAAY,UACxB,UAAU,SAAS,OAAO,QAAQ,KAAK,UAAU,YAAY,OAAO,IAAI;;AAGzE,MAAa,SAAS,UAAiC,UAAU,SAAS,OAAO,WAAW;;AAG5F,MAAa,cAAc,UAC1B,UAAU,SAAS,OAAO,UAAU;;AAGrC,MAAa,cAAc,UAC1B,UAAU,SAAS,OAAO,UAAU;;ACzLrC,MAAM,cAAc;;;;;;;AAQpB,MAAa,UAAU,YACtB,WAAW,QAAQ,KAAK,WAAW,CAAC,CAAC,CAAC,MAAM,WAAW;AAKxD,MAAa,YAAY,UACxB,OAAO,UAAU,YACjB,OAAO,UAAU,YACjB,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WAAW,SAAuB,KAAK,YAAY,WAAW;;;;;;;;AAS3E,MAAa,uBACZ,UAC6B;CAC7B,GAAG;CACH,UAAU;AACX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACzLA,MAAa,WACZ,IACA,aAIc;CACd,MAAM;CACN;CACA,OAAO,QAAQ;CACf,aAAa,QAAQ;AACtB;;AAGA,MAAa,UAAU,UAAiC,UAAU,SAAS,OAAO,MAAM;;;;;;;;;;;;;;;;;;;;;;ACfxF,MAAaC,UACZ,IACA,aAOqB;CACrB,MAAM;CACN;CACA,MAAM,QAAQ;CACd,IAAI,QAAQ;CACZ,UAAU,QAAQ;CAClB,YAAY,QAAQ;CACpB,MAAM,QAAQ;AACf;;AAGA,MAAa,cAAc,UAAiC,UAAU,SAAS,OAAO,UAAU;;;;;;;;;;;;;;;;;;AC3ChG,MAAa,QACZ,IACA,aACiB;CACjB,MAAM;CACN;CACA,UAAU,QAAQ;CAClB,SAAS,QAAQ;AAClB;;AAGA,MAAa,aAAa,UAAqC,UAAU,SAAS,OAAO,SAAS;;;;;;;;;;;;;;AA2BlG,MAAa,gBAAyB,SAAkB,cAA6B;CACpF,MAAM;CACN;CACA;AACD"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { o as Document } from "./document-DWHsgywm.js";
|
|
2
|
+
/**
|
|
3
|
+
* Renders a document as Markdown. Throws `DocumentError` for unsupported structure.
|
|
4
|
+
*
|
|
5
|
+
* @since @next
|
|
6
|
+
*/
|
|
7
|
+
export declare const render: (document: Document) => string;
|
|
8
|
+
//# sourceMappingURL=markdown.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"markdown.d.ts","names":[],"sources":["../src/renderers/markdown.ts"],"mappings":";;;;;;qBAUa,SAAM,UAAc"}
|
package/dist/markdown.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { t as toMdast } from "./mdast-DiRsYwPU.js";
|
|
2
|
+
import { toMarkdown } from "mdast-util-to-markdown";
|
|
3
|
+
// src/renderers/markdown.ts
|
|
4
|
+
/**
|
|
5
|
+
* Renders a document as Markdown. Throws `DocumentError` for unsupported structure.
|
|
6
|
+
*
|
|
7
|
+
* @since @next
|
|
8
|
+
*/
|
|
9
|
+
const render = (document) => toMarkdown(toMdast(document), {
|
|
10
|
+
bullet: "-",
|
|
11
|
+
emphasis: "_",
|
|
12
|
+
strong: "*"
|
|
13
|
+
});
|
|
14
|
+
export { render };
|
|
15
|
+
|
|
16
|
+
//# sourceMappingURL=markdown.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"markdown.js","names":[],"sources":["../src/renderers/markdown.ts"],"sourcesContent":["import { toMarkdown } from \"mdast-util-to-markdown\";\n\nimport type { Document } from \"../features/documents/document.ts\";\nimport { toMdast } from \"./mdast.ts\";\n\n/**\n * Renders a document as Markdown. Throws `DocumentError` for unsupported structure.\n *\n * @since @next\n */\nexport const render = (document: Document): string =>\n\ttoMarkdown(toMdast(document), { bullet: \"-\", emphasis: \"_\", strong: \"*\" });\n"],"mappings":";;;;;;;;AAUA,MAAa,UAAU,aACtB,WAAW,QAAQ,QAAQ,GAAG;CAAE,QAAQ;CAAK,UAAU;CAAK,QAAQ;AAAI,CAAC"}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { i as DocumentError } from "./document-BZcZo9nr.js";
|
|
2
|
+
import { normalizeUri, sanitizeUri } from "micromark-util-sanitize-uri";
|
|
3
|
+
// src/renderers/mdast.ts
|
|
4
|
+
/** Link schemes kept in rendered output. Relative URLs are always kept. */
|
|
5
|
+
const safeSchemes = /^(https?|mailto)$/i;
|
|
6
|
+
/**
|
|
7
|
+
* Keeps a URL whose scheme is allowed, and replaces any other URL with an empty one.
|
|
8
|
+
* `sanitizeUri` also HTML-escapes its result, which the serializers would escape again,
|
|
9
|
+
* so only its scheme check is used here.
|
|
10
|
+
*/
|
|
11
|
+
const safeUrl = (url) => sanitizeUri(url, safeSchemes) === "" ? "" : normalizeUri(url);
|
|
12
|
+
const maximumLevel = 6;
|
|
13
|
+
const isDepth = (level) => Number.isInteger(level) && level >= 1 && level <= maximumLevel;
|
|
14
|
+
const lowerInline = (value) => {
|
|
15
|
+
switch (value._tag) {
|
|
16
|
+
case "Text": return {
|
|
17
|
+
type: "text",
|
|
18
|
+
value: value.value
|
|
19
|
+
};
|
|
20
|
+
case "Code": return {
|
|
21
|
+
type: "inlineCode",
|
|
22
|
+
value: value.value
|
|
23
|
+
};
|
|
24
|
+
case "Link": return {
|
|
25
|
+
type: "link",
|
|
26
|
+
url: safeUrl(value.url),
|
|
27
|
+
children: value.children.map(lowerInline)
|
|
28
|
+
};
|
|
29
|
+
case "Strong": return {
|
|
30
|
+
type: "strong",
|
|
31
|
+
children: value.children.map(lowerInline)
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
return {
|
|
35
|
+
type: "emphasis",
|
|
36
|
+
children: value.children.map(lowerInline)
|
|
37
|
+
};
|
|
38
|
+
};
|
|
39
|
+
const lowerBlocks = (blocks, depth, scope) => blocks.flatMap((block) => {
|
|
40
|
+
switch (block._tag) {
|
|
41
|
+
case "Paragraph": return [{
|
|
42
|
+
type: "paragraph",
|
|
43
|
+
children: block.children.map(lowerInline)
|
|
44
|
+
}];
|
|
45
|
+
case "CodeBlock": return [{
|
|
46
|
+
type: "code",
|
|
47
|
+
value: block.value,
|
|
48
|
+
lang: block.lang ?? null
|
|
49
|
+
}];
|
|
50
|
+
case "List": return [{
|
|
51
|
+
type: "list",
|
|
52
|
+
ordered: block.ordered,
|
|
53
|
+
spread: false,
|
|
54
|
+
children: block.items.map((item) => ({
|
|
55
|
+
type: "listItem",
|
|
56
|
+
spread: false,
|
|
57
|
+
children: lowerBlocks(item, depth, scope)
|
|
58
|
+
}))
|
|
59
|
+
}];
|
|
60
|
+
}
|
|
61
|
+
if (scope.ids.has(block.id)) throw new DocumentError({
|
|
62
|
+
reason: "duplicate-section",
|
|
63
|
+
message: `Section "${block.id}" appears more than once in ${scope.label}.`
|
|
64
|
+
});
|
|
65
|
+
scope.ids.add(block.id);
|
|
66
|
+
const inner = block.release === void 0 ? scope : {
|
|
67
|
+
ids: /* @__PURE__ */ new Set(),
|
|
68
|
+
label: `release "${block.release.id}"`
|
|
69
|
+
};
|
|
70
|
+
if (block.title === void 0) return [
|
|
71
|
+
...lowerBlocks(block.before, depth, inner),
|
|
72
|
+
...lowerBlocks(block.after, depth, inner),
|
|
73
|
+
...lowerBlocks(block.children, depth, inner)
|
|
74
|
+
];
|
|
75
|
+
const level = block.title.level ?? depth;
|
|
76
|
+
if (!isDepth(level)) throw new DocumentError({
|
|
77
|
+
reason: "heading-level",
|
|
78
|
+
message: `Section "${block.id}" needs heading level ${level}, but levels range from 1 to ${maximumLevel}.`
|
|
79
|
+
});
|
|
80
|
+
return [
|
|
81
|
+
...lowerBlocks(block.before, level + 1, inner),
|
|
82
|
+
{
|
|
83
|
+
type: "heading",
|
|
84
|
+
depth: level,
|
|
85
|
+
children: block.title.children.map(lowerInline)
|
|
86
|
+
},
|
|
87
|
+
...lowerBlocks(block.after, level + 1, inner),
|
|
88
|
+
...lowerBlocks(block.children, level + 1, inner)
|
|
89
|
+
];
|
|
90
|
+
});
|
|
91
|
+
/**
|
|
92
|
+
* Lowers a document to an mdast root. Untitled sections contribute only their content,
|
|
93
|
+
* and titled sections get the next heading level unless their title sets one. Link URLs
|
|
94
|
+
* with a scheme other than http, https, or mailto become empty.
|
|
95
|
+
*
|
|
96
|
+
* Throws `DocumentError` when a section identifier repeats within the document or within
|
|
97
|
+
* one release, or when a heading level falls outside 1 to 6.
|
|
98
|
+
*/
|
|
99
|
+
const toMdast = (document) => ({
|
|
100
|
+
type: "root",
|
|
101
|
+
children: lowerBlocks(document.children, 1, {
|
|
102
|
+
ids: /* @__PURE__ */ new Set(),
|
|
103
|
+
label: "the document"
|
|
104
|
+
})
|
|
105
|
+
});
|
|
106
|
+
export { toMdast as t };
|
|
107
|
+
|
|
108
|
+
//# sourceMappingURL=mdast-DiRsYwPU.js.map
|