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.
Files changed (57) hide show
  1. package/README.md +274 -4
  2. package/dist/changelog.d.ts +116 -0
  3. package/dist/changelog.d.ts.map +1 -0
  4. package/dist/changelog.js +304 -0
  5. package/dist/changelog.js.map +1 -0
  6. package/dist/document-BZcZo9nr.js +171 -0
  7. package/dist/document-BZcZo9nr.js.map +1 -0
  8. package/dist/document-DWHsgywm.d.ts +257 -0
  9. package/dist/document-DWHsgywm.d.ts.map +1 -0
  10. package/dist/html.d.ts +8 -0
  11. package/dist/html.d.ts.map +1 -0
  12. package/dist/html.js +13 -0
  13. package/dist/html.js.map +1 -0
  14. package/dist/index.d.ts +378 -1
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +2058 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/markdown.d.ts +8 -0
  19. package/dist/markdown.d.ts.map +1 -0
  20. package/dist/markdown.js +16 -0
  21. package/dist/markdown.js.map +1 -0
  22. package/dist/mdast-DiRsYwPU.js +108 -0
  23. package/dist/mdast-DiRsYwPU.js.map +1 -0
  24. package/dist/package-BfBYnaCz.d.ts +1125 -0
  25. package/dist/package-BfBYnaCz.d.ts.map +1 -0
  26. package/dist/rolldown-runtime-D8jQpDG7.js +12 -0
  27. package/package.json +13 -1
  28. package/src/features/documents/changelog.ts +450 -0
  29. package/src/features/documents/document.ts +357 -0
  30. package/src/features/documents/index.ts +4 -0
  31. package/src/features/documents/public-document.ts +31 -0
  32. package/src/features/documents/sections.ts +44 -0
  33. package/src/features/execution/executor.ts +826 -0
  34. package/src/features/execution/handler.ts +257 -0
  35. package/src/features/execution/settlement.ts +49 -0
  36. package/src/features/package.ts +32 -0
  37. package/src/features/planning/guide.ts +56 -0
  38. package/src/features/planning/history.ts +174 -0
  39. package/src/features/planning/identifiers.ts +43 -0
  40. package/src/features/planning/resolve-error.ts +201 -0
  41. package/src/features/planning/resolve.ts +724 -0
  42. package/src/features/planning/rewrite.ts +331 -0
  43. package/src/features/planning/validate.ts +388 -0
  44. package/src/foundation/action.ts +188 -0
  45. package/src/foundation/change.ts +147 -0
  46. package/src/foundation/instruction.ts +110 -0
  47. package/src/foundation/migration.ts +236 -0
  48. package/src/foundation/plan.ts +245 -0
  49. package/src/foundation/rule.ts +74 -0
  50. package/src/foundation/shortcut.ts +79 -0
  51. package/src/foundation/template.ts +28 -0
  52. package/src/foundation/version.ts +78 -0
  53. package/src/index.ts +22 -11
  54. package/src/renderers/html.ts +12 -0
  55. package/src/renderers/markdown.ts +12 -0
  56. package/src/renderers/mdast.ts +120 -0
  57. package/src/types.ts +2 -0
@@ -0,0 +1,257 @@
1
+ import { Context, Data, Effect, Predicate, Schema } from "effect";
2
+
3
+ import type * as Action from "../../foundation/action.ts";
4
+ import type { ValueOf } from "../../types.ts";
5
+ import { trackPromise } from "./settlement.ts";
6
+
7
+ /**
8
+ * Where a handler failure happened.
9
+ *
10
+ * @since @next
11
+ */
12
+ export type Phase = "precondition" | "body";
13
+
14
+ /**
15
+ * A Promise handler rejected or threw a value that none of its declared error guards
16
+ * recognized.
17
+ *
18
+ * @since @next
19
+ */
20
+ export class UnexpectedHandlerError extends Data.TaggedError("UnexpectedHandlerError")<{
21
+ readonly actionId: string;
22
+ readonly kind: string;
23
+ readonly phase: Phase;
24
+ readonly cause: unknown;
25
+ }> {
26
+ override get message() {
27
+ return `Handler for action "${this.actionId}" failed unexpectedly in its ${this.phase}`;
28
+ }
29
+ }
30
+
31
+ const TypeId = "~deltafold/Handler";
32
+
33
+ /**
34
+ * Implements one action instance. `E` and `R` are the errors and Effect services of the
35
+ * body and precondition together.
36
+ *
37
+ * @since @next
38
+ */
39
+ export type Handler<out A extends Action.Any, out E = never, out R = never> = {
40
+ readonly [TypeId]: typeof TypeId;
41
+ readonly action: A;
42
+ /** Runs the action body. */
43
+ readonly body: Effect.Effect<void, E, R>;
44
+ /** Decides whether the body applies. `false` skips the occurrence. */
45
+ readonly precondition: Effect.Effect<boolean, E, R> | undefined;
46
+ /** Explains a skip when the precondition returns `false`. */
47
+ readonly skipReason: string;
48
+ };
49
+
50
+ /**
51
+ * Any handler.
52
+ *
53
+ * @since @next
54
+ */
55
+ export type Any = Handler<Action.Any, any, any>;
56
+
57
+ /**
58
+ * The errors of a handler or a union of handlers.
59
+ *
60
+ * @since @next
61
+ */
62
+ export type Error<H> = H extends Handler<any, infer E, any> ? E : never;
63
+
64
+ /**
65
+ * The Effect services of a handler or a union of handlers.
66
+ *
67
+ * @since @next
68
+ */
69
+ export type Services<H> = H extends Handler<any, any, infer R> ? R : never;
70
+
71
+ /**
72
+ * The action identifiers implemented by a handler or a union of handlers.
73
+ *
74
+ * @since @next
75
+ */
76
+ export type ActionId<H> = H extends Handler<infer A, any, any> ? A["id"] : never;
77
+
78
+ /** @since @next */
79
+ export const isHandler = (value: unknown): value is Any => Predicate.hasProperty(value, TypeId);
80
+
81
+ type SkipReason<P> = string | ((payload: P) => string);
82
+
83
+ const skipReasonOf = <P>(action: Action.Action<string, P>, reason: SkipReason<P> | undefined) => {
84
+ if (reason === undefined) return "Precondition returned false";
85
+
86
+ return typeof reason === "string" ? reason : reason(action.payload);
87
+ };
88
+
89
+ /**
90
+ * Named Effect services that a Promise handler declares.
91
+ *
92
+ * @since @next
93
+ */
94
+ export type ServiceMap = { readonly [name: string | symbol]: Context.Key<any, any> };
95
+
96
+ // oxlint-disable-next-line typescript/no-generated-empty-object-type -- A handler without services declares an empty service map.
97
+ type NoServices = Record<never, never>;
98
+
99
+ /**
100
+ * The second argument of Promise handler callbacks: the `AbortSignal` that
101
+ * `Effect.tryPromise` aborts on interruption, and the declared services, resolved.
102
+ *
103
+ * @since @next
104
+ */
105
+ export type PromiseContext<S extends ServiceMap = NoServices> = {
106
+ readonly signal: AbortSignal;
107
+ readonly services: { readonly [K in keyof S]: S[K]["Service"] };
108
+ };
109
+
110
+ type ServiceIds<S extends ServiceMap> = ValueOf<{
111
+ [K in keyof S]: S[K] extends Context.Key<infer I, any> ? I : never;
112
+ }>;
113
+
114
+ /**
115
+ * Recognizes a declared rejection: a schema, or a type guard such as an `instanceof`
116
+ * check. Guards must declare their parameter type, for example
117
+ * `(cause: unknown): cause is NotFound => cause instanceof NotFound`.
118
+ *
119
+ * @since @next
120
+ */
121
+ export type ErrorGuard = Schema.Top | ((cause: unknown) => cause is any);
122
+
123
+ type GuardedError<G> = G extends Schema.Top
124
+ ? G["Type"]
125
+ : G extends ((cause: unknown) => cause is infer E)
126
+ ? E
127
+ : never;
128
+
129
+ /** @since @next */
130
+ export type PromiseOptions<P, S extends ServiceMap, G extends ReadonlyArray<ErrorGuard>> = {
131
+ /** Effect services resolved for the callbacks and added to the handler requirements. */
132
+ readonly services?: S;
133
+ /**
134
+ * Guards for rejections that keep their own type. Other rejections become
135
+ * `UnexpectedHandlerError`. A guard does not prove that the callback throws only
136
+ * those errors.
137
+ */
138
+ readonly errors?: G;
139
+ /** Read-only precondition. Returning `false` skips the occurrence. */
140
+ readonly when?: (payload: P, context: PromiseContext<S>) => boolean | PromiseLike<boolean>;
141
+ readonly skipReason?: SkipReason<P>;
142
+ };
143
+
144
+ const declaredError =
145
+ <G extends ReadonlyArray<ErrorGuard>>(guards: G) =>
146
+ (cause: unknown): cause is GuardedError<G[number]> =>
147
+ guards.some((guard) => (Schema.isSchema(guard) ? Schema.is(guard)(cause) : guard(cause)));
148
+
149
+ /**
150
+ * Implements an action with Promise callbacks. The callbacks run lazily through
151
+ * `Effect.tryPromise`, and receive its `AbortSignal` and the declared services in
152
+ * their second argument.
153
+ *
154
+ * @example
155
+ * ```ts
156
+ * Handler.promise(
157
+ * updateRemoteConfig,
158
+ * async (payload, { signal, services: { editor } }) => {
159
+ * await editor.update(payload, { signal });
160
+ * },
161
+ * { services: { editor: ConfigEditor } },
162
+ * );
163
+ * ```
164
+ *
165
+ * @since @next
166
+ */
167
+ export const promise = <
168
+ A extends Action.Any,
169
+ const S extends ServiceMap = NoServices,
170
+ const G extends ReadonlyArray<ErrorGuard> = [],
171
+ >(
172
+ action: A,
173
+ run: (payload: A["payload"], context: PromiseContext<S>) => PromiseLike<unknown>,
174
+ options?: PromiseOptions<A["payload"], S, G>,
175
+ ): Handler<A, GuardedError<G[number]> | UnexpectedHandlerError, ServiceIds<S>> => {
176
+ const isDeclared = declaredError(options?.errors ?? []);
177
+ const services: ServiceMap = options?.services ?? {};
178
+ // The handler requires exactly the declared services. Reading them from its context
179
+ // keeps that requirement typed; only the record of resolved services needs a cast,
180
+ // because Object.fromEntries does not track keys.
181
+ const resolve = Effect.map(
182
+ Effect.context<ServiceIds<S>>(),
183
+ (context) =>
184
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion
185
+ Object.fromEntries(
186
+ Reflect.ownKeys(services).map((name) => [
187
+ name,
188
+ Context.get(context, services[name]!),
189
+ ]),
190
+ ) as { readonly [K in keyof S]: S[K]["Service"] },
191
+ );
192
+
193
+ const adapt = <T>(
194
+ phase: Phase,
195
+ callback: (context: PromiseContext<S>) => PromiseLike<T> | T,
196
+ ): Effect.Effect<T, GuardedError<G[number]> | UnexpectedHandlerError, ServiceIds<S>> =>
197
+ Effect.flatMap(resolve, (resolved) =>
198
+ trackPromise((capture) =>
199
+ Effect.tryPromise({
200
+ // Declaring `signal` makes Effect.tryPromise allocate an AbortController.
201
+ try: (signal) =>
202
+ capture(Promise.resolve(callback({ signal, services: resolved }))),
203
+ catch: (cause) =>
204
+ isDeclared(cause)
205
+ ? cause
206
+ : new UnexpectedHandlerError({
207
+ actionId: action.id,
208
+ kind: action.kind,
209
+ phase,
210
+ cause,
211
+ }),
212
+ }),
213
+ ),
214
+ );
215
+
216
+ const when = options?.when;
217
+
218
+ return {
219
+ [TypeId]: TypeId,
220
+ action,
221
+ body: Effect.asVoid(adapt("body", (context) => run(action.payload, context))),
222
+ precondition:
223
+ when === undefined
224
+ ? undefined
225
+ : adapt("precondition", (context) => when(action.payload, context)),
226
+ skipReason: skipReasonOf(action, options?.skipReason),
227
+ };
228
+ };
229
+
230
+ /** @since @next */
231
+ export type EffectOptions<P, E, R> = {
232
+ /** Read-only precondition. Succeeding with `false` skips the occurrence. */
233
+ readonly when?: (payload: P) => Effect.Effect<boolean, E, R>;
234
+ readonly skipReason?: SkipReason<P>;
235
+ };
236
+
237
+ /**
238
+ * Implements an action with an Effect. The body keeps its own errors and services, and
239
+ * stops through native Effect interruption.
240
+ *
241
+ * @since @next
242
+ */
243
+ export const effect = <A extends Action.Any, E = never, R = never, E2 = never, R2 = never>(
244
+ action: A,
245
+ run: (payload: A["payload"]) => Effect.Effect<unknown, E, R>,
246
+ options: EffectOptions<A["payload"], E2, R2> = {},
247
+ ): Handler<A, E | E2, R | R2> => {
248
+ const when = options.when;
249
+
250
+ return {
251
+ [TypeId]: TypeId,
252
+ action,
253
+ body: Effect.asVoid(Effect.suspend(() => run(action.payload))),
254
+ precondition: when === undefined ? undefined : Effect.suspend(() => when(action.payload)),
255
+ skipReason: skipReasonOf(action, options.skipReason),
256
+ };
257
+ };
@@ -0,0 +1,49 @@
1
+ import { Context, Duration, Effect, Option } from "effect";
2
+
3
+ /**
4
+ * How the executor learns whether an interrupted Promise callback settled. Effect stops
5
+ * waiting for a Promise when it is interrupted, but the Promise itself can keep running.
6
+ */
7
+ export type Settlement = {
8
+ /** How long to keep waiting for an interrupted Promise before reporting it pending. */
9
+ readonly grace: Duration.Input;
10
+ readonly record: (settled: boolean) => void;
11
+ };
12
+
13
+ export const SettlementReference = Context.Reference<Settlement>("deltafold/Settlement", {
14
+ defaultValue: () => ({ grace: Duration.zero, record: () => {} }),
15
+ });
16
+
17
+ /**
18
+ * Runs a Promise-producing effect. If it is interrupted after the Promise started,
19
+ * waits up to the settlement grace period and records whether the Promise settled.
20
+ */
21
+ export const trackPromise = <T, E, R>(
22
+ start: (capture: (promise: Promise<T>) => Promise<T>) => Effect.Effect<T, E, R>,
23
+ ): Effect.Effect<T, E, R> =>
24
+ Effect.suspend(() => {
25
+ let pending: Promise<T> | undefined;
26
+ const capture = (promise: Promise<T>) => {
27
+ pending = promise;
28
+
29
+ return promise;
30
+ };
31
+
32
+ return start(capture).pipe(
33
+ Effect.onInterrupt(() =>
34
+ Effect.gen(function* () {
35
+ const started = pending;
36
+ if (started === undefined) return;
37
+
38
+ const settlement = yield* SettlementReference;
39
+ const settled = yield* Effect.promise(() =>
40
+ started.then(
41
+ () => undefined,
42
+ () => undefined,
43
+ ),
44
+ ).pipe(Effect.timeoutOption(settlement.grace));
45
+ settlement.record(Option.isSome(settled));
46
+ }),
47
+ ),
48
+ );
49
+ });
@@ -0,0 +1,32 @@
1
+ import { Predicate } from "effect";
2
+
3
+ import type * as Action from "../foundation/action.ts";
4
+ import type { History } from "./planning/history.ts";
5
+
6
+ /** @since @next */
7
+ export type Package<A extends Action.Any = Action.Any> = {
8
+ readonly _tag: "Package";
9
+ /** The name of the modeled package, for example `@acme/widgets`. */
10
+ readonly name: string;
11
+ readonly history: History<A>;
12
+ };
13
+
14
+ /**
15
+ * Defines the modeled package. It holds no renderer settings, release metadata, or
16
+ * handlers.
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * export const widgets = Package.make("@acme/widgets", { history });
21
+ * ```
22
+ *
23
+ * @since @next
24
+ */
25
+ export const make = <A extends Action.Any>(
26
+ name: string,
27
+ options: { readonly history: History<A> },
28
+ ): Package<A> => ({ _tag: "Package", name, history: options.history });
29
+
30
+ /** @since @next */
31
+ export const isPackage = (value: unknown): value is Package<any> =>
32
+ Predicate.isTagged(value, "Package");
@@ -0,0 +1,56 @@
1
+ import type * as Action from "../../foundation/action.ts";
2
+ import type * as Migration from "../../foundation/migration.ts";
3
+ import type { GuideItem, Occurrence } from "../../foundation/plan.ts";
4
+
5
+ /** The declared occurrence a retained occurrence is rendered at. */
6
+ const anchorOf = (occurrence: Occurrence): Occurrence => {
7
+ if (occurrence.origin._tag === "Declared") return occurrence;
8
+
9
+ const first = occurrence.origin.replaces[0];
10
+
11
+ return first === undefined ? occurrence : anchorOf(first);
12
+ };
13
+
14
+ /**
15
+ * Resolves a migration's content against the occurrences that survived optimization.
16
+ * Removed occurrences disappear with their instruction blocks. Replacements render at
17
+ * the position of the first occurrence they replaced, using their own instruction or
18
+ * description. Unassociated prose stays.
19
+ */
20
+ export const resolveGuide = (
21
+ content: Migration.Content,
22
+ retained: ReadonlyArray<Occurrence>,
23
+ declaredId: (action: Action.Any) => string,
24
+ ): ReadonlyArray<GuideItem> => {
25
+ const byAnchor = new Map<string, Array<Occurrence>>();
26
+ for (const occurrence of retained) {
27
+ const anchor = anchorOf(occurrence).id;
28
+ const list = byAnchor.get(anchor) ?? [];
29
+ list.push(occurrence);
30
+ byAnchor.set(anchor, list);
31
+ }
32
+
33
+ const renderStep = (step: Action.Step): ReadonlyArray<GuideItem> => {
34
+ if (step._tag === "Action" || step._tag === "Instruction") {
35
+ const action = step._tag === "Action" ? step : step.action;
36
+
37
+ return (byAnchor.get(declaredId(action)) ?? []).map((occurrence) => ({
38
+ _tag: "Occurrence",
39
+ occurrence,
40
+ }));
41
+ }
42
+
43
+ const children = (step._tag === "Sequence" ? step.children : step.branches)
44
+ .map((child) => renderStep(child))
45
+ .filter((items) => items.length > 0);
46
+ if (children.length === 0) return [];
47
+
48
+ return [{ _tag: "Group", kind: step._tag, children }];
49
+ };
50
+
51
+ return content.flatMap((fragment): ReadonlyArray<GuideItem> => {
52
+ if (fragment._tag === "Text" || fragment._tag === "ActionRef") return [fragment];
53
+
54
+ return renderStep(fragment);
55
+ });
56
+ };
@@ -0,0 +1,174 @@
1
+ import { Predicate, Result } from "effect";
2
+
3
+ import type * as Action from "../../foundation/action.ts";
4
+ import type * as Change from "../../foundation/change.ts";
5
+ import type * as Migration from "../../foundation/migration.ts";
6
+ import type { Plan } from "../../foundation/plan.ts";
7
+ import type * as Rule from "../../foundation/rule.ts";
8
+ import type * as Shortcut from "../../foundation/shortcut.ts";
9
+ import type { Version } from "../../foundation/version.ts";
10
+ import { InvalidHistory, type ResolveError, type UnknownVersion } from "./resolve-error.ts";
11
+ import {
12
+ destinations,
13
+ lookup as lookupVersion,
14
+ makeContext,
15
+ resolve as resolveRoute,
16
+ type Context,
17
+ type Destination,
18
+ type ResolveOptions,
19
+ type RoutePolicy,
20
+ } from "./resolve.ts";
21
+ import { validate as validateDeclarations, type Issue } from "./validate.ts";
22
+
23
+ export * from "./resolve-error.ts";
24
+ export type { Destination, Issue, ResolveOptions, RoutePolicy };
25
+
26
+ /** @since @next */
27
+ export type History<A extends Action.Any = Action.Any, C extends Change.Any = Change.Any> = {
28
+ readonly _tag: "History";
29
+ readonly versions: ReadonlyArray<Version>;
30
+ readonly migrations: ReadonlyArray<Migration.Any>;
31
+ readonly rules: ReadonlyArray<Rule.Any>;
32
+ readonly shortcuts: ReadonlyArray<Shortcut.Any>;
33
+ /** Type-level record of every action instance that a plan can contain. */
34
+ readonly "~actions"?: A;
35
+ /** Type-level record of every change that a plan's `changes` can contain. */
36
+ readonly "~changes"?: C;
37
+ };
38
+
39
+ /**
40
+ * Any history.
41
+ *
42
+ * @since @next
43
+ */
44
+ export type Any = History<any>;
45
+
46
+ /**
47
+ * Every action instance that a plan resolved from the history can contain.
48
+ *
49
+ * @since @next
50
+ */
51
+ export type ActionsOf<H> = H extends History<infer A> ? A : never;
52
+
53
+ /**
54
+ * Every change that a plan resolved from the history can list in `changes`.
55
+ *
56
+ * @since @next
57
+ */
58
+ export type ChangesOf<H> = H extends History<any, infer C> ? C : never;
59
+
60
+ /**
61
+ * Registers declarations. Migrations are registered independently of versions, so
62
+ * routes can be added later without changing published release definitions.
63
+ *
64
+ * `make` does not throw. Use `History.validate` to list declaration issues;
65
+ * resolution fails with `InvalidHistory` when there are any.
66
+ *
67
+ * @since @next
68
+ */
69
+ export const make = <
70
+ const M extends ReadonlyArray<Migration.Any>,
71
+ const R extends ReadonlyArray<Rule.Any> = [],
72
+ const S extends ReadonlyArray<Shortcut.Any> = [],
73
+ >(declarations: {
74
+ readonly versions: ReadonlyArray<Version>;
75
+ readonly migrations: M;
76
+ readonly rules?: R;
77
+ readonly shortcuts?: S;
78
+ }): History<
79
+ Migration.ActionsOf<M[number]> | Rule.ActionsOf<R[number]> | Shortcut.ActionsOf<S[number]>,
80
+ Migration.ChangesOf<M[number]> | Shortcut.ChangesOf<S[number]>
81
+ > => ({
82
+ _tag: "History",
83
+ versions: declarations.versions,
84
+ migrations: declarations.migrations,
85
+ rules: declarations.rules ?? [],
86
+ shortcuts: declarations.shortcuts ?? [],
87
+ });
88
+
89
+ /** @since @next */
90
+ export const isHistory = (value: unknown): value is Any => Predicate.isTagged(value, "History");
91
+
92
+ const contexts = new WeakMap<
93
+ Any,
94
+ { readonly issues: ReadonlyArray<Issue>; readonly context: Context }
95
+ >();
96
+
97
+ const prepare = (history: Any) => {
98
+ const cached = contexts.get(history);
99
+ if (cached !== undefined) return cached;
100
+
101
+ const prepared = { issues: validateDeclarations(history), context: makeContext(history) };
102
+ contexts.set(history, prepared);
103
+
104
+ return prepared;
105
+ };
106
+
107
+ /**
108
+ * Lists declaration issues in a deterministic order. An empty list means valid.
109
+ *
110
+ * @since @next
111
+ */
112
+ export const validate = (history: Any): ReadonlyArray<Issue> => prepare(history).issues;
113
+
114
+ const valid = (history: Any): Result.Result<Context, InvalidHistory> => {
115
+ const { issues, context } = prepare(history);
116
+
117
+ return issues.length === 0
118
+ ? Result.succeed(context)
119
+ : Result.fail(new InvalidHistory({ issues }));
120
+ };
121
+
122
+ /**
123
+ * Resolves an optimized plan between two versions. Planning needs no handlers or
124
+ * execution services, and it never reads or modifies consumer files.
125
+ *
126
+ * When several routes connect the versions, resolution fails with `AmbiguousRoute`
127
+ * unless the `route` option selects one or a route `policy` leaves exactly one.
128
+ *
129
+ * @example
130
+ * ```ts
131
+ * const result = History.resolve(history, { from: "1.5.3", to: "2.0.0" });
132
+ * if (Result.isSuccess(result)) console.log(result.success.route.id);
133
+ * ```
134
+ *
135
+ * @since @next
136
+ */
137
+ export const resolve = <A extends Action.Any, C extends Change.Any>(
138
+ history: History<A, C>,
139
+ options: ResolveOptions,
140
+ ): Result.Result<Plan<A, "static", C>, ResolveError> =>
141
+ // Every occurrence and change comes from the history's declarations, whose unions are
142
+ // `A` and `C`.
143
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion
144
+ Result.flatMap(valid(history), (context) => resolveRoute(context, options)) as Result.Result<
145
+ Plan<A, "static", C>,
146
+ ResolveError
147
+ >;
148
+
149
+ /**
150
+ * Destinations reachable by upgrade from a version, with their candidate routes.
151
+ *
152
+ * @since @next
153
+ */
154
+ export const upgrades = (
155
+ history: Any,
156
+ options: { readonly from: Version | string },
157
+ ): Result.Result<ReadonlyArray<Destination>, InvalidHistory | UnknownVersion> =>
158
+ reachableFrom(history, options.from, "upgrade");
159
+
160
+ /**
161
+ * Destinations reachable by downgrade from a version, with their candidate routes.
162
+ *
163
+ * @since @next
164
+ */
165
+ export const downgrades = (
166
+ history: Any,
167
+ options: { readonly from: Version | string },
168
+ ): Result.Result<ReadonlyArray<Destination>, InvalidHistory | UnknownVersion> =>
169
+ reachableFrom(history, options.from, "downgrade");
170
+
171
+ const reachableFrom = (history: Any, from: Version | string, kind: "upgrade" | "downgrade") =>
172
+ Result.flatMap(valid(history), (context) =>
173
+ Result.map(lookupVersion(context, from), (version) => destinations(context, version, kind)),
174
+ );
@@ -0,0 +1,43 @@
1
+ import type * as Action from "../../foundation/action.ts";
2
+ import type * as Migration from "../../foundation/migration.ts";
3
+ import type { Direction, Occurrence } from "../../foundation/plan.ts";
4
+ import type * as Rule from "../../foundation/rule.ts";
5
+
6
+ // Author identifiers may contain any character. Each format escapes its own separators,
7
+ // and the backslash itself, so distinct components never produce the same identifier.
8
+ const escape = (value: string, separators: RegExp) => value.replace(separators, "\\$&");
9
+
10
+ const occurrencePart = (id: string) => escape(id, /[\\/()+]/g);
11
+
12
+ const routePart = (id: string) => escape(id, /[\\>[\]]/g);
13
+
14
+ /** `<migration>/<action>` forward, `<migration>/revert/<action>` in reverse. */
15
+ export const declaredOccurrenceId = (
16
+ migration: Migration.Any,
17
+ direction: Direction,
18
+ action: Action.Any,
19
+ ): string =>
20
+ direction === "forward"
21
+ ? `${occurrencePart(migration.id)}/${occurrencePart(action.id)}`
22
+ : `${occurrencePart(migration.id)}/revert/${occurrencePart(action.id)}`;
23
+
24
+ /**
25
+ * `<rule>(<replaced>+<replaced>)/<action>`. Replaced identifiers are complete occurrence
26
+ * identifiers, so they nest without further escaping.
27
+ */
28
+ export const replacementOccurrenceId = (
29
+ rule: Rule.Any,
30
+ replaced: ReadonlyArray<Occurrence>,
31
+ action: Action.Any,
32
+ ): string =>
33
+ `${occurrencePart(rule.id)}(${replaced.map((occurrence) => occurrence.id).join("+")})/${occurrencePart(action.id)}`;
34
+
35
+ /** The first version of a route identifier. */
36
+ export const routeStart = (version: string): string => routePart(version);
37
+
38
+ /** A migration hop: `>` and the target version. */
39
+ export const routeHop = (to: string): string => `>${routePart(to)}`;
40
+
41
+ /** A shortcut hop: `>[shortcut]>` and the target version. */
42
+ export const routeShortcut = (shortcut: string, to: string): string =>
43
+ `>[${routePart(shortcut)}]>${routePart(to)}`;