deltafold 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +278 -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 +517 -1
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +2126 -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 +968 -0
  34. package/src/features/execution/handler.ts +485 -0
  35. package/src/features/execution/settlement.ts +52 -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,485 @@
1
+ import { Context, Data, Effect, Predicate, Schema, Scope } 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: the read-only prepare phase, or the apply phase that
9
+ * changes state.
10
+ *
11
+ * @since @next
12
+ */
13
+ export type Phase = "prepare" | "apply";
14
+
15
+ /**
16
+ * A Promise handler rejected or threw a value that none of its declared error guards
17
+ * recognized, or its prepare phase returned something other than `Handler.prepared` or
18
+ * `Handler.skip`.
19
+ *
20
+ * @since @next
21
+ */
22
+ export class UnexpectedHandlerError extends Data.TaggedError("UnexpectedHandlerError")<{
23
+ readonly actionId: string;
24
+ readonly kind: string;
25
+ readonly phase: Phase;
26
+ readonly cause: unknown;
27
+ }> {
28
+ override get message() {
29
+ return `Handler for action "${this.actionId}" failed unexpectedly in its ${this.phase} phase`;
30
+ }
31
+ }
32
+
33
+ const PreparationTypeId = "~deltafold/Preparation";
34
+
35
+ /**
36
+ * A prepare phase decided to apply. The apply phase receives `value` unchanged; the
37
+ * executor never reads, validates, or serializes it.
38
+ *
39
+ * @since @next
40
+ */
41
+ export type Prepared<out P> = {
42
+ readonly [PreparationTypeId]: typeof PreparationTypeId;
43
+ readonly _tag: "Prepared";
44
+ readonly value: P;
45
+ };
46
+
47
+ /**
48
+ * A prepare phase decided that the action does not apply. The occurrence is skipped
49
+ * with `reason`.
50
+ *
51
+ * @since @next
52
+ */
53
+ export type Skip = {
54
+ readonly [PreparationTypeId]: typeof PreparationTypeId;
55
+ readonly _tag: "Skip";
56
+ readonly reason: string;
57
+ };
58
+
59
+ /**
60
+ * What a prepare phase returns: `Handler.prepared(value)` or `Handler.skip(reason)`.
61
+ *
62
+ * @since @next
63
+ */
64
+ export type Preparation<P> = Prepared<P> | Skip;
65
+
66
+ /** The value that a prepare phase passes to its apply phase. */
67
+ type PreparedValue<T> = T extends Prepared<infer P> ? P : never;
68
+
69
+ /**
70
+ * Ends a prepare phase with the value its apply phase receives. Wrapping the value keeps
71
+ * it apart from a skip, whatever its shape.
72
+ *
73
+ * @since @next
74
+ */
75
+ export function prepared(): Prepared<void>;
76
+ export function prepared<P>(value: P): Prepared<P>;
77
+ export function prepared(value?: unknown): Prepared<unknown> {
78
+ return { [PreparationTypeId]: PreparationTypeId, _tag: "Prepared", value };
79
+ }
80
+
81
+ /**
82
+ * Ends a prepare phase by skipping the occurrence. The apply phase does not run.
83
+ *
84
+ * @since @next
85
+ */
86
+ export const skip = (reason: string): Skip => ({
87
+ [PreparationTypeId]: PreparationTypeId,
88
+ _tag: "Skip",
89
+ reason,
90
+ });
91
+
92
+ const isPreparation = (value: unknown): value is Preparation<unknown> =>
93
+ Predicate.hasProperty(value, PreparationTypeId);
94
+
95
+ const notAPreparation = () =>
96
+ new TypeError("A prepare phase must return Handler.prepared(value) or Handler.skip(reason)");
97
+
98
+ /**
99
+ * How an occurrence continues after its prepare phase: skipped, or applied by an effect
100
+ * that already holds the prepared value.
101
+ *
102
+ * @since @next
103
+ */
104
+ export type Step<E, R> =
105
+ | Skip
106
+ | { readonly _tag: "Apply"; readonly apply: Effect.Effect<void, E, R> };
107
+
108
+ const applyStep = <E, R>(apply: Effect.Effect<void, E, R>): Step<E, R> => ({
109
+ _tag: "Apply",
110
+ apply,
111
+ });
112
+
113
+ const TypeId = "~deltafold/Handler";
114
+
115
+ /**
116
+ * Implements one action instance. `E` and `R` are the errors and Effect services of both
117
+ * phases together. A prepared value stays inside the handler, so handlers with
118
+ * different prepared values share this type.
119
+ *
120
+ * @since @next
121
+ */
122
+ export type Handler<out A extends Action.Any, out E = never, out R = never> = {
123
+ readonly [TypeId]: typeof TypeId;
124
+ readonly action: A;
125
+ /** Whether the handler has a prepare phase. */
126
+ readonly prepares: boolean;
127
+ /**
128
+ * Runs the prepare phase, if any, and resolves to the next step. Both phases share
129
+ * `scope`, the occurrence's scope, so resources acquired while preparing stay open
130
+ * until the executor closes it after the occurrence ends.
131
+ */
132
+ readonly prepare: (scope: Scope.Scope) => Effect.Effect<Step<E, R>, E, R>;
133
+ };
134
+
135
+ /**
136
+ * Any handler.
137
+ *
138
+ * @since @next
139
+ */
140
+ export type Any = Handler<Action.Any, any, any>;
141
+
142
+ /**
143
+ * The errors of a handler or a union of handlers.
144
+ *
145
+ * @since @next
146
+ */
147
+ export type Error<H> = H extends Handler<any, infer E, any> ? E : never;
148
+
149
+ /**
150
+ * The Effect services of a handler or a union of handlers.
151
+ *
152
+ * @since @next
153
+ */
154
+ export type Services<H> = H extends Handler<any, any, infer R> ? R : never;
155
+
156
+ /**
157
+ * The action identifiers implemented by a handler or a union of handlers.
158
+ *
159
+ * @since @next
160
+ */
161
+ export type ActionId<H> = H extends Handler<infer A, any, any> ? A["id"] : never;
162
+
163
+ /** @since @next */
164
+ export const isHandler = (value: unknown): value is Any => Predicate.hasProperty(value, TypeId);
165
+
166
+ const make = <A extends Action.Any, E, R>(
167
+ action: A,
168
+ prepares: boolean,
169
+ prepare: (scope: Scope.Scope) => Effect.Effect<Step<E, R>, E, R>,
170
+ ): Handler<A, E, R> => ({ [TypeId]: TypeId, action, prepares, prepare });
171
+
172
+ /**
173
+ * Named Effect services that a Promise handler declares.
174
+ *
175
+ * @since @next
176
+ */
177
+ export type ServiceMap = { readonly [name: string | symbol]: Context.Key<any, any> };
178
+
179
+ // oxlint-disable-next-line typescript/no-generated-empty-object-type -- A handler without services declares an empty service map.
180
+ type NoServices = Record<never, never>;
181
+
182
+ /**
183
+ * The second argument of Promise handler callbacks: the `AbortSignal` that
184
+ * `Effect.tryPromise` aborts on interruption, and the declared services, resolved.
185
+ *
186
+ * @since @next
187
+ */
188
+ export type PromiseContext<S extends ServiceMap = NoServices> = {
189
+ readonly signal: AbortSignal;
190
+ readonly services: { readonly [K in keyof S]: S[K]["Service"] };
191
+ };
192
+
193
+ /**
194
+ * The second argument of a Promise apply phase: the Promise context and the action
195
+ * payload.
196
+ *
197
+ * @since @next
198
+ */
199
+ export type PromiseApplyContext<Payload, S extends ServiceMap = NoServices> = PromiseContext<S> & {
200
+ readonly payload: Payload;
201
+ };
202
+
203
+ /**
204
+ * A Promise handler with a prepare phase. `prepare` reads state and returns
205
+ * `Handler.prepared(value)` or `Handler.skip(reason)`; `apply` receives the value. Each
206
+ * phase gets its own signal.
207
+ *
208
+ * @since @next
209
+ */
210
+ export type PromisePhases<Payload, T extends Preparation<unknown>, S extends ServiceMap> = {
211
+ readonly prepare: (payload: Payload, context: PromiseContext<S>) => PromiseLike<T> | T;
212
+ readonly apply: (
213
+ prepared: PreparedValue<T>,
214
+ context: PromiseApplyContext<Payload, S>,
215
+ ) => PromiseLike<unknown>;
216
+ };
217
+
218
+ type ServiceIds<S extends ServiceMap> = ValueOf<{
219
+ [K in keyof S]: S[K] extends Context.Key<infer I, any> ? I : never;
220
+ }>;
221
+
222
+ /**
223
+ * Recognizes a declared rejection: a schema, or a type guard such as an `instanceof`
224
+ * check. Guards must declare their parameter type, for example
225
+ * `(cause: unknown): cause is NotFound => cause instanceof NotFound`.
226
+ *
227
+ * @since @next
228
+ */
229
+ export type ErrorGuard = Schema.Top | ((cause: unknown) => cause is any);
230
+
231
+ type GuardedError<G> = G extends Schema.Top
232
+ ? G["Type"]
233
+ : G extends ((cause: unknown) => cause is infer E)
234
+ ? E
235
+ : never;
236
+
237
+ /** @since @next */
238
+ export type PromiseOptions<S extends ServiceMap, G extends ReadonlyArray<ErrorGuard>> = {
239
+ /** Effect services resolved for the callbacks and added to the handler requirements. */
240
+ readonly services?: S;
241
+ /**
242
+ * Guards for rejections that keep their own type. Other rejections become
243
+ * `UnexpectedHandlerError`. A guard does not prove that the callback throws only
244
+ * those errors.
245
+ */
246
+ readonly errors?: G;
247
+ };
248
+
249
+ const declaredError =
250
+ <G extends ReadonlyArray<ErrorGuard>>(guards: G) =>
251
+ (cause: unknown): cause is GuardedError<G[number]> =>
252
+ guards.some((guard) => (Schema.isSchema(guard) ? Schema.is(guard)(cause) : guard(cause)));
253
+
254
+ type PromiseHandler<A extends Action.Any, S extends ServiceMap, G> = Handler<
255
+ A,
256
+ GuardedError<G> | UnexpectedHandlerError,
257
+ ServiceIds<S>
258
+ >;
259
+
260
+ /**
261
+ * Implements an action with Promise callbacks. The callbacks run lazily through
262
+ * `Effect.tryPromise`, and receive its `AbortSignal` and the declared services.
263
+ *
264
+ * Pass one callback to apply the action directly, or `{ prepare, apply }` to decide
265
+ * first. `prepare` must only read: a dry run calls it and never calls `apply`. A real
266
+ * run calls `apply` once with the prepared value.
267
+ *
268
+ * @example
269
+ * ```ts
270
+ * Handler.promise(
271
+ * updateRemoteConfig,
272
+ * async (payload, { signal, services: { editor } }) => {
273
+ * await editor.update(payload, { signal });
274
+ * },
275
+ * { services: { editor: ConfigEditor } },
276
+ * );
277
+ * ```
278
+ *
279
+ * @example
280
+ * ```ts
281
+ * Handler.promise(renameTimeout, {
282
+ * prepare: async ({ file, from }, { signal }) => {
283
+ * const config = await readConfig(file, { signal });
284
+ * return from in config ? Handler.prepared(config) : Handler.skip(`${file} has no ${from}`);
285
+ * },
286
+ * apply: async (config, { payload, signal }) => {
287
+ * await writeConfig(payload.file, rename(config, payload), { signal });
288
+ * },
289
+ * });
290
+ * ```
291
+ *
292
+ * @since @next
293
+ */
294
+ export function promise<
295
+ A extends Action.Any,
296
+ const S extends ServiceMap = NoServices,
297
+ const G extends ReadonlyArray<ErrorGuard> = [],
298
+ >(
299
+ action: A,
300
+ apply: (payload: A["payload"], context: PromiseContext<S>) => PromiseLike<unknown>,
301
+ options?: PromiseOptions<S, G>,
302
+ ): PromiseHandler<A, S, G[number]>;
303
+ export function promise<
304
+ A extends Action.Any,
305
+ T extends Preparation<unknown> = Skip,
306
+ const S extends ServiceMap = NoServices,
307
+ const G extends ReadonlyArray<ErrorGuard> = [],
308
+ >(
309
+ action: A,
310
+ phases: PromisePhases<A["payload"], T, S>,
311
+ options?: PromiseOptions<S, G>,
312
+ ): PromiseHandler<A, S, G[number]>;
313
+ export function promise<
314
+ A extends Action.Any,
315
+ S extends ServiceMap,
316
+ G extends ReadonlyArray<ErrorGuard>,
317
+ >(
318
+ action: A,
319
+ run:
320
+ | ((payload: A["payload"], context: PromiseContext<S>) => PromiseLike<unknown>)
321
+ | PromisePhases<A["payload"], Preparation<unknown>, S>,
322
+ options?: PromiseOptions<S, G>,
323
+ ): PromiseHandler<A, S, G[number]> {
324
+ type E = GuardedError<G[number]> | UnexpectedHandlerError;
325
+
326
+ const isDeclared = declaredError(options?.errors ?? []);
327
+ const services: ServiceMap = options?.services ?? {};
328
+ // The handler requires exactly the declared services. Reading them from its context
329
+ // keeps that requirement typed; only the record of resolved services needs a cast,
330
+ // because Object.fromEntries does not track keys.
331
+ const resolve = Effect.map(
332
+ Effect.context<ServiceIds<S>>(),
333
+ (context) =>
334
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion
335
+ Object.fromEntries(
336
+ Reflect.ownKeys(services).map((name) => [
337
+ name,
338
+ Context.get(context, services[name]!),
339
+ ]),
340
+ ) as { readonly [K in keyof S]: S[K]["Service"] },
341
+ );
342
+ const unexpected = (phase: Phase, cause: unknown) =>
343
+ new UnexpectedHandlerError({ actionId: action.id, kind: action.kind, phase, cause });
344
+
345
+ const adapt = <T>(
346
+ phase: Phase,
347
+ callback: (context: PromiseContext<S>) => PromiseLike<T> | T,
348
+ ): Effect.Effect<T, E, ServiceIds<S>> =>
349
+ Effect.flatMap(resolve, (resolved) =>
350
+ trackPromise((capture) =>
351
+ Effect.tryPromise({
352
+ // Declaring `signal` makes Effect.tryPromise allocate an AbortController.
353
+ try: (signal) =>
354
+ capture(Promise.resolve(callback({ signal, services: resolved }))),
355
+ catch: (cause) => (isDeclared(cause) ? cause : unexpected(phase, cause)),
356
+ }),
357
+ ),
358
+ );
359
+
360
+ if (Predicate.isFunction(run)) {
361
+ const apply = Effect.asVoid(adapt("apply", (context) => run(action.payload, context)));
362
+
363
+ return make(action, false, () => Effect.succeed(applyStep(apply)));
364
+ }
365
+
366
+ const prepare = adapt("prepare", (context) => run.prepare(action.payload, context)).pipe(
367
+ Effect.filterOrFail(isPreparation, () => unexpected("prepare", notAPreparation())),
368
+ Effect.map((preparation): Step<E, ServiceIds<S>> =>
369
+ preparation._tag === "Skip"
370
+ ? preparation
371
+ : applyStep(
372
+ Effect.asVoid(
373
+ adapt("apply", (context) =>
374
+ run.apply(preparation.value, {
375
+ ...context,
376
+ payload: action.payload,
377
+ }),
378
+ ),
379
+ ),
380
+ ),
381
+ ),
382
+ );
383
+
384
+ return make(action, true, () => prepare);
385
+ }
386
+
387
+ /**
388
+ * The second argument of an Effect apply phase.
389
+ *
390
+ * @since @next
391
+ */
392
+ export type EffectApplyContext<Payload> = { readonly payload: Payload };
393
+
394
+ /**
395
+ * An Effect handler with a prepare phase. `prepare` reads state and succeeds with
396
+ * `Handler.prepared(value)` or `Handler.skip(reason)`; `apply` receives the value.
397
+ *
398
+ * @since @next
399
+ */
400
+ export type EffectPhases<Payload, T extends Preparation<unknown>, E1, R1, E2, R2> = {
401
+ readonly prepare: (payload: Payload) => Effect.Effect<T, E1, R1>;
402
+ readonly apply: (
403
+ prepared: PreparedValue<T>,
404
+ context: EffectApplyContext<Payload>,
405
+ ) => Effect.Effect<unknown, E2, R2>;
406
+ };
407
+
408
+ /**
409
+ * Implements an action with an Effect. The handler keeps its own errors and services,
410
+ * and stops through native Effect interruption.
411
+ *
412
+ * Pass one function to apply the action directly, or `{ prepare, apply }` to decide
413
+ * first. `prepare` must only read: a dry run runs it and never runs `apply`. A real run
414
+ * runs `apply` once with the prepared value. Both phases run in the occurrence's
415
+ * `Scope`, so a resource acquired while preparing, such as a lock, stays open until the
416
+ * occurrence ends; the handler does not require `Scope`.
417
+ *
418
+ * @example
419
+ * ```ts
420
+ * Handler.effect(renameTimeout, {
421
+ * prepare: ({ file, from }) =>
422
+ * Effect.gen(function* () {
423
+ * const files = yield* ConfigFiles;
424
+ * const config = yield* files.lock(file);
425
+ * return from in config.data ? Handler.prepared(config) : Handler.skip(`${file} has no ${from}`);
426
+ * }),
427
+ * apply: (config, { payload }) => config.write(rename(config.data, payload)),
428
+ * });
429
+ * ```
430
+ *
431
+ * @since @next
432
+ */
433
+ export function effect<A extends Action.Any, E = never, R = never>(
434
+ action: A,
435
+ apply: (payload: A["payload"]) => Effect.Effect<unknown, E, R>,
436
+ ): Handler<A, E, Exclude<R, Scope.Scope>>;
437
+ export function effect<
438
+ A extends Action.Any,
439
+ T extends Preparation<unknown> = Skip,
440
+ E1 = never,
441
+ R1 = never,
442
+ E2 = never,
443
+ R2 = never,
444
+ >(
445
+ action: A,
446
+ phases: EffectPhases<A["payload"], T, E1, R1, E2, R2>,
447
+ ): Handler<A, E1 | E2, Exclude<R1 | R2, Scope.Scope>>;
448
+ export function effect<A extends Action.Any, E1, R1, E2, R2>(
449
+ action: A,
450
+ run:
451
+ | ((payload: A["payload"]) => Effect.Effect<unknown, E1, R1>)
452
+ | EffectPhases<A["payload"], Preparation<unknown>, E1, R1, E2, R2>,
453
+ ): Handler<A, E1 | E2, Exclude<R1 | R2, Scope.Scope>> {
454
+ type E = E1 | E2;
455
+ type R = Exclude<R1 | R2, Scope.Scope>;
456
+
457
+ if (Predicate.isFunction(run)) {
458
+ const apply = Effect.asVoid(Effect.suspend(() => run(action.payload)));
459
+
460
+ return make(action, false, (scope) =>
461
+ Effect.succeed(applyStep<E, R>(Scope.provide(apply, scope))),
462
+ );
463
+ }
464
+
465
+ return make(action, true, (scope) =>
466
+ Effect.suspend(() => run.prepare(action.payload)).pipe(
467
+ Scope.provide(scope),
468
+ Effect.filterOrElse(isPreparation, () => Effect.die(notAPreparation())),
469
+ Effect.map((preparation): Step<E, R> =>
470
+ preparation._tag === "Skip"
471
+ ? preparation
472
+ : applyStep(
473
+ Scope.provide(
474
+ Effect.asVoid(
475
+ Effect.suspend(() =>
476
+ run.apply(preparation.value, { payload: action.payload }),
477
+ ),
478
+ ),
479
+ scope,
480
+ ),
481
+ ),
482
+ ),
483
+ ),
484
+ );
485
+ }
@@ -0,0 +1,52 @@
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
+ /** Receives an interrupted Promise that did not settle within the grace period. */
11
+ readonly unsettled: (promise: Promise<void>) => void;
12
+ };
13
+
14
+ export const SettlementReference = Context.Reference<Settlement>("deltafold/Settlement", {
15
+ defaultValue: () => ({ grace: Duration.zero, unsettled: () => {} }),
16
+ });
17
+
18
+ /**
19
+ * Runs a Promise-producing effect. If it is interrupted after the Promise started,
20
+ * waits up to the settlement grace period and hands a still-pending Promise to the
21
+ * settlement, which can hold resources until it settles.
22
+ */
23
+ export const trackPromise = <T, E, R>(
24
+ start: (capture: (promise: Promise<T>) => Promise<T>) => Effect.Effect<T, E, R>,
25
+ ): Effect.Effect<T, E, R> =>
26
+ Effect.suspend(() => {
27
+ let pending: Promise<T> | undefined;
28
+ const capture = (promise: Promise<T>) => {
29
+ pending = promise;
30
+
31
+ return promise;
32
+ };
33
+
34
+ return start(capture).pipe(
35
+ Effect.onInterrupt(() =>
36
+ Effect.gen(function* () {
37
+ const started = pending;
38
+ if (started === undefined) return;
39
+
40
+ const settles = started.then(
41
+ () => undefined,
42
+ () => undefined,
43
+ );
44
+ const settlement = yield* SettlementReference;
45
+ const settled = yield* Effect.promise(() => settles).pipe(
46
+ Effect.timeoutOption(settlement.grace),
47
+ );
48
+ if (Option.isNone(settled)) settlement.unsettled(settles);
49
+ }),
50
+ ),
51
+ );
52
+ });
@@ -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
+ };