gdp-wired 0.42.0 → 0.43.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.
@@ -19,16 +19,27 @@ import * as dsl from "./dsl.js";
19
19
  import { interpret, seeded } from "./machine.js";
20
20
  import { allowed } from "./watch.js";
21
21
  import * as I from "./extract-ir.js";
22
- import { Refusal, bare as strip, beside, impure, memberName, placed, refuse, shapeOf, sourceOf, text } from "./extract-read.js";
22
+ import { Refusal, bare as strip, beside, impure, memberName, normalize, placed, refuse, shapeOf, sourceOf, text, where } from "./extract-read.js";
23
23
  import { readFactory, setupOf } from "./extract-shapes.js";
24
24
  import { fromModel, namesOf } from "./extract.js";
25
- import { check } from "./extract-check.js";
25
+ import { check, sandbox } from "./extract-check.js";
26
+ import { Parts, readSchedule, replaySchedule, scheduleConforms, scheduleRule } from "./effect-schedule.js";
27
+ import { asRule, lift } from "./system.js";
26
28
  export { proveRule, proveSteps } from "./dsl.js";
27
- const REFS = new Set(['Ref', 'SynchronizedRef', 'SubscriptionRef', 'TxRef']), MAKES = ['make', 'makeUnsafe', 'unsafeMake'];
28
- const STM = (api) => `${api}: STM (v3) is not read (a Ref, SynchronizedRef, or v4's TxRef is)`, MATCH = (x) => `${x}: a matcher (write the dispatch as a switch on _tag, or ifs)`;
29
+ export { jitterRun, replaySchedule, scheduleConforms, stepper } from "./effect-schedule.js";
30
+ const REFS = new Set(['Ref', 'SynchronizedRef', 'SubscriptionRef', 'TxRef', 'TRef']), MAKES = ['make', 'makeUnsafe', 'unsafeMake'];
31
+ const STM = (api) => `${api} (of STM: gen, commit, succeed, sync, void, fail, die, check and retry are read)`, MATCH = (x) => `${x}: a matcher (write the dispatch as a switch on _tag, or ifs)`;
32
+ // The Effect line the file is read for (4.x unless the project's effect is 3.x), and the policies its methods retry or
33
+ // repeat with, each read into its schedule's rule.
34
+ let V4 = true;
35
+ let found = [];
36
+ const SLEPT = '$slept';
29
37
  // Where on a path the step has changed a Ref so far (a condition in the heap, so merges and helpers carry it).
30
38
  const CHANGED = '$changed';
31
- const changedOn = (p) => { const o = p.heap.get(CHANGED); return o?.k === 'alias' && o.to.t === 'bool' ? o.to.e : I.F; };
39
+ const changedOn = (p, k = CHANGED) => { const o = p.heap.get(k); return o?.k === 'alias' && o.to.t === 'bool' ? o.to.e : I.F; };
40
+ // Inside a transaction (STM.gen, STM.commit, 4.x's Effect.tx), the writes made before it: what a failure there keeps
41
+ // (the transaction's own are rolled back).
42
+ const OUTER = '$outer', flagged = (b) => ({ k: 'alias', to: { t: 'bool', e: b } });
32
43
  const changedOf = (v, c) => (v.t === 'phi' ? I.bite(v.c, changedOf(v.a, c), changedOf(v.b, c)) : v.t === 'ref' && c.t === 'ref' && v.id === c.id ? I.F
33
44
  : (v.t === 'num' || v.t === 'bool' || v.t === 'str' || v.t === 'choice') && v.t === c.t && I.same(v.e, c.e) ? I.F : I.T);
34
45
  // --- the reader -----------------------------------------------------------------------------------------------------
@@ -69,13 +80,13 @@ function fnOf(s, e) {
69
80
  refuse(e.arguments[1], `${head} with combinators after its body (their effects aren't read)`);
70
81
  return g;
71
82
  }
72
- const genOf = (s, e) => {
73
- if (callOf(s, e) !== 'Effect.gen')
83
+ const genOf = (s, e, which = 'Effect.gen') => {
84
+ if (callOf(s, e) !== which)
74
85
  return undefined;
75
86
  const args = strip(e).arguments, g = args.at(-1);
76
87
  if (args.length !== 1)
77
- refuse(e, 'Effect.gen with a this (a generator of one function is read)');
78
- return g && ts.isFunctionExpression(g) && g.asteriskToken ? g : refuse(e, 'Effect.gen of other than a function*');
88
+ refuse(e, `${which} with a this (a generator of one function is read)`);
89
+ return g && ts.isFunctionExpression(g) && g.asteriskToken ? g : refuse(e, `${which} of other than a function*`);
79
90
  };
80
91
  // A type's type argument: Ref<A>'s A, Effect<A, E, R>'s A, Generator<Y, R, N>'s R.
81
92
  const argOf = (s, t, i) => (t.aliasTypeArguments ?? (t.flags & ts.TypeFlags.Object ? s.checker.getTypeArguments(t) : undefined))?.[i];
@@ -158,7 +169,7 @@ function factoryOf(s, entry) {
158
169
  refs.set(id, m);
159
170
  return { shape: shapeOf(t, s.checker, d), init: start };
160
171
  }
161
- if (m === 'TRef' || m === 'STM')
172
+ if (m === 'STM')
162
173
  return refuse(d, STM(api));
163
174
  if (m === 'Semaphore' || /^Effect\.(unsafeM|m)akeSemaphore$/.test(api)) {
164
175
  const n = call.arguments[0];
@@ -199,11 +210,29 @@ function hook(s, refs, locks, effects) {
199
210
  // An error made of pure values: `new E({...})` of a class (an error class has no effects), or a plain value.
200
211
  const effectful = (x) => (x = strip(x), ts.isNewExpression(x) && ts.isIdentifier(x.expression) ? (x.arguments ?? []).some(impure) : impure(x));
201
212
  // A failure: the step refused where it is reached; where a Ref has been changed on the path, the Ref keeps it.
202
- const fail = (ex, at, q) => {
203
- if (!ex.known(q, I.not(changedOn(q))))
204
- refuse(at, `fails after writing ${q.wrote.join(', ')}: a Ref keeps what was written (a rule's refusal leaves the state as it was)`);
205
- ex.throws.push({ pc: q.pc });
206
- return [undef, { ...q, pc: [...q.pc, I.F] }];
213
+ const fail = (ex, at, q, when = I.T) => {
214
+ const kept = q.heap.has(OUTER) ? changedOn(q, OUTER) : changedOn(q), at2 = { ...q, pc: [...q.pc, when] };
215
+ if (!ex.known(at2, I.not(kept)))
216
+ refuse(at, `fails after writing ${q.wrote.join(', ')}${q.heap.has(OUTER) ? ' before the transaction' : ''}: a Ref keeps what was written (a rule's refusal leaves the state as it was)`);
217
+ ex.throws.push({ pc: at2.pc });
218
+ return [undef, { ...q, pc: [...q.pc, I.not(when)] }];
219
+ };
220
+ // A transaction: its writes kept where it succeeds, rolled back where it fails or waits (one inside another joins it).
221
+ const tx = (inner, at) => (inner.t !== 'eff' ? refuse(at, `${text(at)}: a transaction of other than an effect`) : eff(q => {
222
+ if (q.heap.has(OUTER))
223
+ return inner.run(q);
224
+ const [v, q2] = inner.run({ ...q, heap: new Map(q.heap).set(OUTER, flagged(changedOn(q))).set(CHANGED, flagged(I.F)) });
225
+ const heap = new Map(q2.heap).set(CHANGED, flagged(I.or(changedOn(q2, OUTER), changedOn(q2))));
226
+ heap.delete(OUTER);
227
+ return [v, { ...q2, heap }];
228
+ }));
229
+ // A transaction that waits (STM.check of false, STM.retry, 4.x's Effect.txRetry): the request isn't taken until a TRef it
230
+ // read changes, a refusal in the rule.
231
+ const waits = (ex, at, q, when = I.T) => {
232
+ if (!q.heap.has(OUTER))
233
+ refuse(at, `${text(at)} outside a transaction`);
234
+ s.notes.add('a transaction that waits (STM.check, STM.retry, Effect.txRetry) is not taken until a TRef it read changes: the rule refuses the request (it is taken later as a new one)');
235
+ return fail(ex, at, q, when);
207
236
  };
208
237
  // A function's body run on a path, with the locals where it was made.
209
238
  const body = (ex, f, at, locals, args = []) => eff(q => ex.inline({ decl: f }, args, at, q, locals));
@@ -227,10 +256,14 @@ function hook(s, refs, locks, effects) {
227
256
  }
228
257
  if (ts.isPropertyAccessExpression(e)) {
229
258
  const api = apiOf(s, e);
230
- if (api === 'Effect.void' || api === 'Effect.unit')
259
+ if (api === 'Effect.void' || api === 'Effect.unit' || api === 'STM.void' || api === 'STM.unit')
260
+ return [eff(q => [undef, q]), p];
261
+ if (api === 'Effect.txRetry' || api === 'STM.retry')
262
+ return [eff(q => waits(ex, e, q)), p];
263
+ if (api === 'Effect.yieldNow')
231
264
  return [eff(q => [undef, q]), p];
232
265
  if (api === 'Clock.currentTimeMillis')
233
- return [eff(q => ex.now(e, q)), p];
266
+ return [eff(q => (q.heap.has(SLEPT) ? refuse(e, 'the clock read after a repeat that waits (the time has moved on by its delays)') : ex.now(e, q))), p];
234
267
  if (api?.startsWith('Clock.'))
235
268
  return refuse(e, `${api} (Clock.currentTimeMillis is read, as an input)`);
236
269
  if (api && /^(Random|DateTime|Crypto|Console|Config|FileSystem)\./.test(api) && ts.isYieldExpression(e.parent))
@@ -252,12 +285,24 @@ function hook(s, refs, locks, effects) {
252
285
  // x.pipe(...): only annotations (a span, a log annotation) are read through.
253
286
  if (ts.isPropertyAccessExpression(callee) && memberName(callee.name) === 'pipe' && !api) {
254
287
  const head = strip(callee.expression);
288
+ if (e.arguments.length === 1 && apiOf(s, e.arguments[0]) === 'STM.commit') {
289
+ const [v, q] = ex.ev(head, p);
290
+ return [tx(v, head), q];
291
+ }
255
292
  if (callOf(s, head)?.startsWith('Match.'))
256
293
  return refuse(head, MATCH(text(head)));
257
- for (const a of e.arguments)
258
- if (!ANNOTATIONS.has(callOf(s, a) ?? ''))
259
- return refuse(a, `${text(a)} in a pipe (a combinator's effect isn't read: write the step in Effect.gen)`);
260
- return ex.ev(callee.expression, p);
294
+ let [v, q] = ex.ev(callee.expression, p);
295
+ for (const a of e.arguments) {
296
+ const c = callOf(s, a) ?? '';
297
+ if (ANNOTATIONS.has(c))
298
+ continue;
299
+ if ((c === 'Effect.retry' || c === 'Effect.repeat') && strip(a).arguments.length === 1) {
300
+ v = scheduled(ex, c, v, strip(a).arguments[0], e);
301
+ continue;
302
+ }
303
+ return refuse(a, `${text(a)} in a pipe (a combinator's effect isn't read: write the step in Effect.gen)`);
304
+ }
305
+ return [v, q];
261
306
  }
262
307
  // A helper of the same files written with Effect.fn: its body run where it is yielded.
263
308
  if (ts.isIdentifier(callee)) {
@@ -270,7 +315,27 @@ function hook(s, refs, locks, effects) {
270
315
  }
271
316
  if (REFS.has(m))
272
317
  return refOp(ex, e, m, op, p);
273
- if (m === 'Effect') {
318
+ if ((api === 'Effect.retry' || api === 'Effect.repeat') && e.arguments.length === 2) {
319
+ const [v, q] = ex.ev(one, p);
320
+ return [scheduled(ex, api, v, e.arguments[1], e), q];
321
+ }
322
+ if (api === 'Effect.tx' || api === 'STM.commit') {
323
+ const [v, q] = ex.ev(one ?? refuse(e, `${api}()`), p);
324
+ return [tx(v, e), q];
325
+ }
326
+ if (m === 'STM') {
327
+ if (op === 'gen')
328
+ return [tx(body(ex, genOf(s, e, 'STM.gen'), e, p.locals), e), p];
329
+ if (op === 'check') {
330
+ const f = one && fnOf(s, one);
331
+ if (!f || f.parameters.length || ts.isBlock(f.body))
332
+ return refuse(e, 'STM.check of other than () => condition written here');
333
+ return [eff(q => { const [c, q1] = ex.ev(f.body, q); return c.t === 'bool' ? waits(ex, e, q1, I.not(c.e)) : refuse(e, `STM.check of other than a condition (${c.t})`); }), p];
334
+ }
335
+ if (!['succeed', 'sync', 'fail', 'failSync', 'die', 'dieMessage'].includes(op))
336
+ return refuse(e, STM(api));
337
+ }
338
+ if (m === 'Effect' || m === 'STM') {
274
339
  if (op === 'gen')
275
340
  return [body(ex, genOf(s, e), e, p.locals), p];
276
341
  if (op === 'succeed') {
@@ -281,22 +346,134 @@ function hook(s, refs, locks, effects) {
281
346
  return [body(ex, fnOf(s, one ?? refuse(e, 'Effect.sync()')) ?? refuse(e, 'Effect.sync of other than a function written here'), e, p.locals), p];
282
347
  if (FAILS.has(op))
283
348
  return e.arguments.some(effectful) ? refuse(e, `Effect.${op} of a value that has effects`) : [eff(q => fail(ex, e, q)), p];
349
+ if (op === 'sleep') {
350
+ if (e.arguments.some(impure))
351
+ return refuse(e, 'Effect.sleep of a value that has effects');
352
+ return [eff(q => [undef, { ...q, heap: new Map(q.heap).set(SLEPT, flagged(I.T)) }]), p];
353
+ }
284
354
  if (LOGS.has(op)) {
285
355
  if (e.arguments.some(impure))
286
356
  return refuse(e, `Effect.${op} of values that have effects`);
287
357
  s.notes.add('Effect.log and span annotations are left out (they write nothing the rule keeps)');
288
358
  return [eff(q => [undef, q]), p];
289
359
  }
360
+ if (m === 'STM')
361
+ return refuse(e, STM(api));
290
362
  return refuse(e, op === 'fn' || op === 'fnUntraced' ? `Effect.${op} as a value inside a step (a method or a helper of the service is read)` : `Effect.${op} (Effect.gen, Effect.fn bodies, succeed, sync, fail, die, void and log are read; the effect of ${op} isn't)`);
291
363
  }
292
364
  if (m === 'Match')
293
365
  return refuse(e, MATCH(api));
294
- if (m === 'STM' || m === 'TRef')
295
- return refuse(e, STM(api));
366
+ if (m === 'TRef')
367
+ return refuse(e, `${api} (a TRef the service's make effect makes is read: get, set, update, modify and their variants)`);
296
368
  if (m === 'Semaphore')
297
369
  return refuse(e, `${api} (a Semaphore of 1 made by the service, as a lock, is read)`);
298
370
  return undefined;
299
371
  };
372
+ // Effect.retry / Effect.repeat of an effect read here, with a schedule (or {times, schedule, while, until}). The
373
+ // policy is read into its schedule's rule (its laws proven on their own: x.schedules). The effect is what the service
374
+ // does to its Refs, so each attempt of a retry fails as the first did (a failure leaves the Refs as they were, and the
375
+ // attempts read nothing else that moves): the step is the effect's, the policy's delays passing only on the way to the
376
+ // failure. A repeat runs it again as many times as the policy goes on, counted by running the policy's rule.
377
+ function scheduled(ex, api, v, policy, at) {
378
+ const use = api === 'Effect.retry' ? 'retry' : 'repeat', pol = strip(policy);
379
+ if (v.t !== 'eff')
380
+ return refuse(at, `${api} of other than an effect`);
381
+ let sched, times;
382
+ if (ts.isObjectLiteralExpression(pol)) {
383
+ for (const pr of pol.properties) {
384
+ const k = ts.isPropertyAssignment(pr) ? memberName(pr.name) : '';
385
+ if (k === 'schedule')
386
+ sched = pr.initializer;
387
+ else if (k === 'times') {
388
+ const n = strip(pr.initializer);
389
+ times = ts.isNumericLiteral(n) ? Number(n.text) : refuse(n, `${use}'s times of other than a number written here`);
390
+ }
391
+ else if ((k === 'while' || k === 'until') && use === 'retry')
392
+ s.notes.add(`${use}'s ${k} reads the error: each attempt fails with the same one, so it decides only how many attempts are made`);
393
+ else
394
+ return refuse(pr, `${use}'s ${text(pr)} (schedule, times${use === 'retry' ? ', while and until' : ''} are read)`);
395
+ }
396
+ }
397
+ else
398
+ sched = pol;
399
+ const outer = (n) => refuse(n, `${text(n)}: a ${use} policy reading the service's params (one written with literals and consts is read: the check runs it)`);
400
+ const P = new Parts(), base = sched ? readSchedule(sched, { api: x => apiOf(s, x), checker: s.checker, v4: V4, params: new Map(), sf: s.sf, outer }, P) : undefined;
401
+ let frag = base?.frag;
402
+ if (times !== undefined) {
403
+ const lim = (frag ?? { step: () => ({ cont: dsl.yes, delay: dsl.lit(0), next: {} }), names: [] }), n = times;
404
+ frag = { ...lim, step: (env, get, c) => { const x = lim.step(env, get, c); return { ...x, cont: x.cont.and(c.attempt.lt(n)) }; } };
405
+ }
406
+ if (!frag)
407
+ return refuse(at, `${use} with no schedule and no times (it would go on forever)`);
408
+ const sr = scheduleRule(frag, P, `${use} policy`, V4);
409
+ // (a method may be read more than once: one entry a place)
410
+ if (!found.some(f => f.at === where(at)))
411
+ found.push({ at: where(at), use, source: sched ? sched.getText() : `{times: ${times}}`, rule: sr });
412
+ // The policy run as Effect drives it, each attempt taking no time: how many times it goes on (for every input it
413
+ // may be fed, drawn), and how long it waits in all.
414
+ const g = sr.rule.compiled(), ps = sr.rule.encodeParams({}), rand = (() => { let x = 7; return (n) => (x = (x * 1103515245 + 12345) % 2147483648) % Math.max(1, n); })();
415
+ const runOnce = (draw) => {
416
+ let st = g.init(ps), n = 0, waited = 0;
417
+ for (; n < 1000; n++) {
418
+ const inp = { took: 0 };
419
+ for (const [f, k] of sr.fields)
420
+ inp[f === '_tag' ? 'input__tag' : f === 'input' ? 'input' : `input_${f}`] = k.sample(draw ? rand : () => 0, 3);
421
+ for (const j of sr.jitters)
422
+ inp[j.name] = 0;
423
+ try {
424
+ st = g.step(ps, st, sr.rule.encodeInput(inp));
425
+ }
426
+ catch {
427
+ return { stops: true, n, waited };
428
+ }
429
+ const d = sr.rule.decode(st);
430
+ if (d.done)
431
+ return { stops: true, n, waited };
432
+ waited += Number(d.delay);
433
+ }
434
+ return { stops: false, n, waited };
435
+ };
436
+ const runs = [runOnce(false), ...(sr.fields.size ? Array.from({ length: 8 }, () => runOnce(true)) : [])];
437
+ if (runs.some(r => !r.stops))
438
+ return refuse(policy, `a ${use} whose policy goes on past 1000 attempts${use === 'retry' ? ' around an effect read here, which fails the same way each time: the call would never return' : ''} (bound it: recurs, upTo, times)`);
439
+ if (sr.jitters.length)
440
+ s.notes.add(`the ${use} policy's jitter is left to its rule (x.schedules): it moves only the time the step waits`);
441
+ if (use === 'retry') {
442
+ s.notes.add(`${text(at)}: retried with ${sched ? text(sched) : `{times: ${times}}`}; each attempt fails as the first did (the effect reads only the Refs, which a failure leaves as they were), so the step is the effect's; the policy's own laws are proven on its rule (x.schedules)`);
443
+ return eff(q => withoutClock(ex, 'the clock read in an effect that is retried (each attempt reads a later time: a loop the step doesn\'t unroll)', () => v.run(q)));
444
+ }
445
+ if (sr.fields.size)
446
+ return refuse(sched, 'a repeat whose policy reads the effect\'s result (a loop the step doesn\'t unroll)');
447
+ const n = runs[0].n, waited = runs[0].waited;
448
+ if (n > 16)
449
+ return refuse(policy, `a repeat that runs the effect ${n + 1} times (up to 17 are unrolled)`);
450
+ let host = at;
451
+ while (host.parent && (ts.isCallExpression(host.parent) || ts.isParenthesizedExpression(host.parent) || ts.isPropertyAccessExpression(host.parent)))
452
+ host = host.parent;
453
+ if (!ts.isYieldExpression(host.parent) || !ts.isExpressionStatement(host.parent.parent))
454
+ return refuse(at, 'the value of a repeat (its policy\'s output): yield* it as a statement');
455
+ s.notes.add(`${text(at)}: the effect runs ${n + 1} times in the step (its policy goes on ${n} times)${waited ? `, waiting ${waited} ms in all` : ''}`);
456
+ return eff(q => {
457
+ let r = [undef, q];
458
+ withoutClock(ex, 'the clock read in an effect that is repeated (each run reads a later time)', () => { for (let i = 0; i <= n; i++)
459
+ r = v.run(r[1]); });
460
+ return [undef, waited ? { ...r[1], heap: new Map(r[1].heap).set(SLEPT, flagged(I.T)) } : r[1]];
461
+ });
462
+ }
463
+ // f run with the clock refused where it is read (an effect run again later in the step reads a later time).
464
+ function withoutClock(ex, why, f) {
465
+ const own = Object.getOwnPropertyDescriptor(ex, 'now');
466
+ Object.defineProperty(ex, 'now', { value: (n) => refuse(n, why), configurable: true, writable: true });
467
+ try {
468
+ return f();
469
+ }
470
+ finally {
471
+ if (own)
472
+ Object.defineProperty(ex, 'now', own);
473
+ else
474
+ delete ex.now;
475
+ }
476
+ }
300
477
  // Ref.op(ref, ...): the ref a Ref the service made (by its name), its value the state's field.
301
478
  function refOp(ex, e, m, op, p) {
302
479
  const r = e.arguments[0] && strip(e.arguments[0]), base = op.replace(/Effect$/, ''), answer = ANSWERS[base], f = e.arguments[1];
@@ -344,13 +521,40 @@ export function runner(E) {
344
521
  let now = 0;
345
522
  // A Clock at `now`: 4.x names its unsafe reads currentTime<X>Unsafe, 3.x unsafeCurrentTime<X>.
346
523
  const unsafe = (x) => (v4 ? `currentTime${x}Unsafe` : `unsafeCurrentTime${x}`), ns = () => BigInt(now) * 1000000n;
347
- const clock = Object.create(Effect.runSync(v4 ? Effect.clockWith((c) => Effect.succeed(c)) : Effect.clock), { [unsafe('Millis')]: { value: () => now }, currentTimeMillis: { value: Effect.sync(() => now) }, [unsafe('Nanos')]: { value: ns }, currentTimeNanos: { value: Effect.sync(ns) } });
524
+ // (a sleep, a retry's or a repeat's, passes at once: the clock moves on by its duration)
525
+ const clock = Object.create(Effect.runSync(v4 ? Effect.clockWith((c) => Effect.succeed(c)) : Effect.clock), { [unsafe('Millis')]: { value: () => now }, currentTimeMillis: { value: Effect.sync(() => now) }, [unsafe('Nanos')]: { value: ns }, currentTimeNanos: { value: Effect.sync(ns) },
526
+ sleep: { value: (d) => Effect.sync(() => { now += E.Duration.toMillis(d); }) } });
348
527
  const exit = (eff, t) => {
349
528
  if (!Effect.isEffect(eff))
350
529
  return { ok: false, error: `not an effect: ${String(eff).slice(0, 60)}` };
351
530
  now = t;
352
- const x = Effect.runSyncExit(v4 ? Effect.provideService(eff, Clock.Clock, clock) : Effect.withClock(eff, clock));
353
- return Exit.isSuccess(x) ? { ok: true, value: x.value } : { ok: false, error: String(Cause.pretty(x.cause)).split('\n')[0] };
531
+ // (3.x on a scheduler of its own, so a fiber left waiting, a transaction that retries, is interrupted at once: it
532
+ // would otherwise wake and commit inside a later request)
533
+ let x, waiting;
534
+ if (v4) {
535
+ x = Effect.runSyncExit(Effect.provideService(eff, Clock.Clock, clock));
536
+ waiting = Exit.isSuccess(x) ? undefined : (x.cause.reasons ?? []).map((r) => r.defect).find((d) => d && typeof d === 'object' && 'fiber' in d);
537
+ waiting?.fiber.interruptUnsafe();
538
+ }
539
+ else {
540
+ // (on a scheduler of its own: what yields to it (a SynchronizedRef's lock) runs on when it is flushed; a fiber still
541
+ // waiting then is interrupted there)
542
+ const sch = new E.Scheduler.SyncScheduler();
543
+ x = Effect.runSyncExit(Effect.withScheduler(Effect.withClock(eff, clock), sch));
544
+ const fiber = Exit.isSuccess(x) ? undefined : x.cause.defect?.fiber;
545
+ if (fiber) {
546
+ for (let i = 0; i < 64 && !(x = fiber.unsafePoll()); i++)
547
+ sch.flush();
548
+ if (!x) {
549
+ waiting = { fiber };
550
+ fiber.unsafeInterruptAsFork(E.FiberId.none);
551
+ sch.flush();
552
+ }
553
+ }
554
+ }
555
+ if (x && Exit.isSuccess(x))
556
+ return { ok: true, value: x.value };
557
+ return { ok: false, error: waiting ? 'it waits (an effect that suspends: a transaction that retries, a fiber it waits for)' : String(Cause.pretty(x.cause)).split('\n')[0] };
354
558
  };
355
559
  const run = (eff, t = now) => { const x = exit(eff, t); if (!x.ok)
356
560
  throw new Error(x.error); return x.value; };
@@ -364,7 +568,17 @@ export function extractEffect(at, opts = {}) {
364
568
  E = opts.effect ?? beside(file, 'effect');
365
569
  if (!E)
366
570
  throw new Refusal(file, 'no effect package resolves from the file (install it in its project, or give it: {effect: await import(\'effect\')})');
571
+ V4 = 'TxRef' in E;
572
+ found = [];
573
+ const sch = scheduleEntry(code, file, opts);
574
+ if (sch)
575
+ return fromScheduleEntry(code, file, sch, E, opts);
367
576
  const entry = opts.entry ?? serviceOf(code, file, opts);
577
+ if (opts.fibers !== false) {
578
+ const f = fibered(code, file, entry, E, opts);
579
+ if (f)
580
+ return f;
581
+ }
368
582
  m = readFactory(code, placed(file), { ...opts, entry }, s => factoryOf(s, entry));
369
583
  m.file = file;
370
584
  if (!opts.entry)
@@ -377,7 +591,316 @@ export function extractEffect(at, opts = {}) {
377
591
  }
378
592
  // The modules the code imports, by specifier (effect, effect/<Module>), and the check's runner.
379
593
  const model = m, modules = { effect: E, ...Object.fromEntries(Object.entries(E).map(([k, x]) => [`effect/${k}`, x])), 'gdp-wired:effect': runner(E), ...opts.modules };
380
- return { ...fromModel(model, file, opts.domains, [], (rule, sorts) => check(code, file, model, rule, sorts, { ...opts.check, modules, ...(opts.files ? { files: opts.files } : {}), ...(opts.domains ? { given: opts.domains } : {}) })), names: namesOf(model) };
594
+ const schedules = found;
595
+ return { ...fromModel(model, file, opts.domains, [], (rule, sorts) => check(code, file, model, rule, sorts, { ...opts.check, modules, ...(opts.files ? { files: opts.files } : {}), ...(opts.domains ? { given: opts.domains } : {}) })), names: namesOf(model), ...(schedules.length ? { schedules } : {}) };
596
+ }
597
+ // --- many fibers: a method that is several steps ---------------------------------------------------------------------
598
+ // A method's atomic units: the statements of its body that run an effect on the service's state (a transaction, a Ref
599
+ // operation, a helper's), each a step another fiber's may come between. A failure, a log, a sleep or a wait runs no
600
+ // such effect. A method of two or more is read as its steps: the service written again with one fiber's place in it
601
+ // (`__gdp_pc`) and what it carries from one step to the next (its arguments, its locals) in Refs of its own, read and
602
+ // checked as any service; then lift (core/system.ts) makes those Refs every fiber's at once (maps keyed by `fiber`, an
603
+ // input), the service's own Refs shared, and each request one fiber's next step.
604
+ const QUIET = new Set(['Effect.fail', 'Effect.failSync', 'Effect.die', 'Effect.dieMessage', 'Effect.void', 'Effect.sleep', 'Effect.yieldNow', 'Effect.txRetry', 'STM.fail', 'STM.die', 'STM.retry', ...[...LOGS].map(l => `Effect.${l}`)]);
605
+ const TX = /\b(TRef|TxRef|STM)\.|Effect\.tx\b/, WAITS = new Set(['Effect.txRetry', 'STM.retry']);
606
+ function fibered(code, file, entry, E, opts) {
607
+ const s = setupOf(code, placed(file), {}, opts.files), f = factoryOf(s, entry);
608
+ const failing = (y) => { const x = y.expression && strip(y.expression); return !!x && (ts.isNewExpression(x) || /^(Effect|STM)\.(fail|failSync|die|dieMessage)$/.test((ts.isCallExpression(x) ? callOf(s, x) : '') ?? '')); };
609
+ // How many effects on the state a piece of a method runs one after another, each a point another fiber's step may
610
+ // come between: a Ref or TRef operation, a transaction or a lock's body one each; an Effect.gen's or a helper's body
611
+ // counted through; a branch its larger side; a repeat several; a failure, a log, a sleep or a wait none.
612
+ const TXS = new Set(['Effect.tx', 'STM.gen', 'STM.commit']);
613
+ const units = (n) => {
614
+ if (ts.isFunctionLike(n))
615
+ return 0;
616
+ if (ts.isIfStatement(n))
617
+ return units(n.expression) + Math.max(units(n.thenStatement), n.elseStatement ? units(n.elseStatement) : 0);
618
+ if (ts.isConditionalExpression(n))
619
+ return units(n.condition) + Math.max(units(n.whenTrue), units(n.whenFalse));
620
+ // (a yield inside the effect's arguments runs before it: its own points first)
621
+ if (ts.isYieldExpression(n)) {
622
+ let inner = 0;
623
+ if (n.expression)
624
+ ts.forEachChild(n.expression, c => { inner += units(c); });
625
+ return inner + (n.expression ? ran(n.expression) : 0);
626
+ }
627
+ let t = 0;
628
+ ts.forEachChild(n, c => { t += units(c); });
629
+ return t;
630
+ };
631
+ const helper = (x) => { const d = ts.isIdentifier(x) ? s.checker.getSymbolAtLocation(x)?.valueDeclaration : undefined; return d && ts.isVariableDeclaration(d) && d.initializer ? fnOf(s, d.initializer) ?? genOf(s, d.initializer) : undefined; };
632
+ const bodyUnits = (fn) => (!fn.body ? 0 : ts.isBlock(fn.body) ? units(fn.body) : ran(fn.body));
633
+ const ran = (e0) => {
634
+ const e = strip(e0);
635
+ if (ts.isNewExpression(e))
636
+ return 0;
637
+ const api = (ts.isCallExpression(e) ? callOf(s, e) : apiOf(s, e)) ?? '';
638
+ if (QUIET.has(api))
639
+ return 0;
640
+ if (TXS.has(api))
641
+ return 1;
642
+ if (ts.isCallExpression(e)) {
643
+ const callee = strip(e.expression);
644
+ if (ts.isPropertyAccessExpression(callee) && memberName(callee.name) === 'pipe' && !api) {
645
+ const fs = e.arguments.map(a => callOf(s, a) ?? apiOf(s, a) ?? ''), head = ran(callee.expression);
646
+ return fs.includes('STM.commit') ? 1 : fs.includes('Effect.repeat') && head ? 2 : head;
647
+ }
648
+ // (a lock's body: one at a time)
649
+ if (ts.isCallExpression(callee) && ts.isPropertyAccessExpression(strip(callee.expression)) && /^withPermits?$/.test(memberName(strip(callee.expression).name)))
650
+ return e.arguments[0] && ran(e.arguments[0]) ? 1 : 0;
651
+ if (api === 'Effect.gen') {
652
+ const g = genOf(s, e);
653
+ return g ? bodyUnits(g) : 1;
654
+ }
655
+ if (api === 'Effect.retry')
656
+ return ran(e.arguments[0]);
657
+ if (api === 'Effect.repeat')
658
+ return ran(e.arguments[0]) ? 2 : 0;
659
+ const h = helper(callee);
660
+ if (h)
661
+ return bodyUnits(h);
662
+ }
663
+ if (ts.isIdentifier(e)) {
664
+ const d = s.checker.getSymbolAtLocation(e)?.valueDeclaration;
665
+ if (d && ts.isVariableDeclaration(d) && d.initializer && !fnOf(s, d.initializer))
666
+ return ran(d.initializer);
667
+ }
668
+ return 1;
669
+ };
670
+ const methods = [], several = [];
671
+ for (const pr of f.obj.properties) {
672
+ const name = pr.name ? memberName(pr.name) : '';
673
+ let init = ts.isPropertyAssignment(pr) ? pr.initializer : ts.isShorthandPropertyAssignment(pr) ? pr.name : undefined;
674
+ if (init && ts.isIdentifier(strip(init))) {
675
+ const d = (ts.isShorthandPropertyAssignment(pr) ? s.checker.getShorthandAssignmentValueSymbol(pr) : s.checker.getSymbolAtLocation(strip(init)))?.valueDeclaration;
676
+ init = d && ts.isVariableDeclaration(d) ? d.initializer : init;
677
+ }
678
+ const fn = init && fnOf(s, init);
679
+ if (!fn?.body)
680
+ continue;
681
+ if (!ts.isFunctionExpression(fn) || !fn.asteriskToken || !ts.isBlock(fn.body)) {
682
+ const n = bodyUnits(fn);
683
+ if (n >= 2)
684
+ several.push([name, fn, n]);
685
+ continue;
686
+ }
687
+ const stmts = fn.body.statements, per = stmts.map(units), units0 = stmts.flatMap((_, i) => (per[i] > 0 ? [i] : []));
688
+ if (per.reduce((a, b) => a + b, 0) >= 2)
689
+ for (const [i, n] of per.entries())
690
+ if (n >= 2)
691
+ several.push([name, stmts[i], n]);
692
+ methods.push({ name, fn, at: init, units: units0, stmts });
693
+ }
694
+ const split = methods.filter(mt => mt.units.length >= 2 || several.some(([n]) => n === mt.name));
695
+ if ((!split.length && !several.length) || (opts.fibers === undefined && !TX.test(code))) {
696
+ if (split.length || several.length)
697
+ s.notes.add(`${[...new Set([...split.map(mt => mt.name), ...several.map(([n]) => n)])].join(', ')} run several Ref operations one after another: each method is read as one step, which holds where calls don't interleave (fibers: true reads them as interleaving steps)`);
698
+ return undefined;
699
+ }
700
+ // (each step of a method read for many fibers is one statement of its body, with one effect on the state at most)
701
+ for (const [name, at, n] of several)
702
+ refuse(at, `${name}: ${text(at)} runs ${n} effects on the state one after another${ts.isStatement(at) ? ' in one statement' : ''}, and another fiber's step may come between them: write the method as Effect.fn('${name}')(function* ...) with each in a statement of its own (each a step), or in one transaction`);
703
+ // Each split method's segments, the names each carries on, and the service written again.
704
+ if (/\b__gdp_/.test(code))
705
+ return refuse(s.sf.statements[0] ?? s.sf, 'a name of the code starts with __gdp_ (the names the fibers\' places and carried values are given)');
706
+ const edits = [], decls = [], resumes = [], made = new Set(['__gdp_pc']);
707
+ const tyOf = (n) => { const t = s.checker.getTypeAtLocation(n), str = s.checker.typeToString(s.checker.getBaseTypeOfLiteralType(t)); return t.flags & ts.TypeFlags.BooleanLike ? ['boolean', 'false'] : t.flags & ts.TypeFlags.NumberLike ? ['number', '0'] : t.isUnion() && t.types.every(u => u.isStringLiteral()) ? [s.checker.typeToString(t), JSON.stringify(t.types[0].value)] : t.flags & ts.TypeFlags.StringLike ? ['string', "''"] : refuse(n, `${text(n)} is carried from one step to the next, and is a ${str} (a number, a boolean or a string is carried)`); };
708
+ split.forEach((mt, mi) => {
709
+ const base = (mi + 1) * 100, K = mt.units.length, segs = [];
710
+ mt.units.forEach((u, k) => segs.push([...mt.stmts.slice(k === 0 ? 0 : mt.units[k - 1] + 1, u + 1), ...(k === K - 1 ? mt.stmts.slice(u + 1) : [])]));
711
+ for (const [k, seg] of segs.entries())
712
+ for (const st of seg) {
713
+ // (a later step's failing transaction: the call would end with the earlier steps' writes kept and this one's rolled
714
+ // back, which a refusal of this step leaves the fiber waiting on instead)
715
+ if (k > 0) {
716
+ const go = (x, inner) => { if (ts.isYieldExpression(x) && inner && failing(x))
717
+ refuse(x, `${mt.name}: a transaction that fails in a step after the first (the call ends there, its earlier steps' writes kept): fail in the first step, or wait (STM.check, Effect.txRetry) instead`); ts.forEachChild(x, c => go(c, inner || ts.isFunctionLike(x))); };
718
+ go(st, false);
719
+ }
720
+ }
721
+ // What a later step reads of an earlier one: the arguments and the locals declared at the top of a segment.
722
+ const carried = new Map();
723
+ for (const p of mt.fn.parameters)
724
+ if (ts.isIdentifier(p.name))
725
+ carried.set(p, p.name.text);
726
+ segs.forEach(seg => seg.forEach(st => { if (ts.isVariableStatement(st))
727
+ for (const d of st.declarationList.declarations)
728
+ carried.set(d, ts.isIdentifier(d.name) ? d.name.text : refuse(d, `${mt.name}: ${text(d)} (a name is carried, not a pattern)`)); }));
729
+ const usedIn = (seg) => { const u = new Set(); const go = (x) => { if (ts.isIdentifier(x)) {
730
+ const d = s.checker.getSymbolAtLocation(x)?.valueDeclaration;
731
+ if (d && carried.has(d))
732
+ u.add(d);
733
+ } ts.forEachChild(x, go); }; seg.forEach(go); return u; };
734
+ const later = segs.map((_, k) => { const u = new Set(); segs.slice(k + 1).forEach(sg => usedIn(sg).forEach(d => u.add(d))); return u; });
735
+ const ref = (d) => `__gdp_${mt.name}_${carried.get(d)}`;
736
+ const kept = new Set();
737
+ later.forEach(u => u.forEach(d => kept.add(d)));
738
+ for (const d of kept) {
739
+ const [t, zero] = tyOf(d);
740
+ decls.push(`const ${ref(d)} = yield* __gdp_Ref.make<${t}>(${zero})`);
741
+ made.add(ref(d));
742
+ }
743
+ // (where each carried name is defined: a parameter, or the segment that declares it)
744
+ const defined = (d, k) => (ts.isParameter(d) ? k === 0 : segs[k].some(st => st.pos <= d.pos && d.end <= st.end));
745
+ const body = (seg, k) => {
746
+ // (what it reads of earlier steps loaded first; what a later step reads stored last: defined here, or loaded here
747
+ // and perhaps assigned again)
748
+ const used = usedIn(seg);
749
+ const loads = k === 0 ? '' : [...used].filter(d => !defined(d, k)).map(d => `let ${carried.get(d)} = yield* __gdp_Ref.get(${ref(d)})\n`).join('');
750
+ const stores = [...later[k]].filter(d => defined(d, k) || used.has(d) || ts.isParameter(d) && k === 0).map(d => `yield* __gdp_Ref.set(${ref(d)}, ${carried.get(d)})\n`).join('');
751
+ // (a return ends the call, its value left out (under fibers a step's result is no part of the rule): what it
752
+ // returns is run, then the fiber goes back to where it starts. In a later step a failure outside a transaction ends
753
+ // the call too, as a return (the earlier steps' writes kept, as Effect keeps them); a wait, or a failure in the
754
+ // first step, leaves the fiber where it is)
755
+ const textOf = (st) => {
756
+ let t = st.getText();
757
+ const rs = [];
758
+ const go = (x) => { if (ts.isReturnStatement(x) || k > 0 && ts.isExpressionStatement(x) && ts.isYieldExpression(strip(x.expression)) && failing(strip(x.expression)))
759
+ rs.push(x); if (!ts.isFunctionLike(x))
760
+ ts.forEachChild(x, go); };
761
+ go(st);
762
+ for (const r of rs.reverse()) {
763
+ const y = ts.isReturnStatement(r) ? r.expression && strip(r.expression) : strip(r.expression), fails = !!y && ts.isYieldExpression(y) && failing(y);
764
+ // (a wait leaves the fiber where it is; so does a failure in the first step, which ends the call with nothing done)
765
+ if (y && ts.isYieldExpression(y) && (WAITS.has(apiOf(s, strip(y.expression)) ?? '') || fails && k === 0))
766
+ continue;
767
+ const run = fails || !y ? '' : `${ts.isYieldExpression(y) ? '' : 'void '}(${y.getText()}); `;
768
+ t = t.slice(0, r.getStart() - st.getStart()) + `{ ${run}${k > 0 ? 'yield* __gdp_Ref.set(__gdp_pc, 0); ' : ''}return }` + t.slice(r.end - st.getStart());
769
+ }
770
+ return t;
771
+ };
772
+ return `${loads}${seg.map(textOf).join('\n')}\n${stores}yield* __gdp_Ref.set(__gdp_pc, ${k === K - 1 ? 0 : base + k + 2})`;
773
+ };
774
+ resumes.push(...segs.slice(1).map((seg, j) => `if (__gdp_p === ${base + j + 2}) {\n${body(seg, j + 1)}\n}`));
775
+ const params = mt.fn.parameters.map(p => p.getText()).join(', ');
776
+ edits.push([mt.fn.getStart(), mt.fn.end, `function* (${params}) {\nconst __gdp_p = yield* __gdp_Ref.get(__gdp_pc)\nif (__gdp_p !== 0) return yield* __gdp_resume()\n${body(segs[0], 0)}\n}`]);
777
+ });
778
+ const ret = f.fn.body.statements.at(-1);
779
+ edits.push([ret.getStart(), ret.getStart(), `const __gdp_pc = yield* __gdp_Ref.make<number>(0)\n${decls.join('\n')}\nconst __gdp_resume = __gdp_Effect.fn('__gdp_resume')(function* () {\nconst __gdp_p = yield* __gdp_Ref.get(__gdp_pc)\n${resumes.join(' else ')}\n})\n`]);
780
+ let out = code;
781
+ for (const [a, b, t] of edits.sort((x, y) => y[0] - x[0]))
782
+ out = out.slice(0, a) + t + out.slice(b);
783
+ out = `import {Effect as __gdp_Effect, Ref as __gdp_Ref} from 'effect'\n${out}`;
784
+ // One fiber: the service written again, read and checked as any.
785
+ // (by its absolute path, `..` resolved: the checker reads the code written again there, not the file on disk)
786
+ const one = extractEffect(out, { ...opts, file: normalize(placed(file)), entry, effect: E, fibers: false });
787
+ if (!one.ok || !one.rule)
788
+ return { ...one, notes: [`read as one fiber's steps (${split.map(mt => `${mt.name}: ${mt.units.length}`).join(', ')}), the service written again:`, out, ...one.notes] };
789
+ const m0 = one.rule.machine, model = one.model;
790
+ // (an integer is two naturals, x and x$neg)
791
+ const local = (n0) => { const n = n0.replace(/\$neg$/, ''); return made.has(n) || model.outputs.some(o => n === o || n.startsWith(`${o}_`)) || n === 'failed'; };
792
+ const shared = Object.keys(m0.state).filter(n => !local(n));
793
+ if (m0.inputs.includes('fiber'))
794
+ return { ok: false, refusals: [{ where: file, what: 'a method takes an argument named fiber (the name the fibers are told apart by)' }], notes: [] };
795
+ const lifted = lift(m0, 'fiber', shared);
796
+ const parts = one.rule.parts;
797
+ // (the kinds of the requests' choices kept; an integer is its two naturals, x and x$neg, as the machine has it)
798
+ const named = new Set([...lifted.params, ...lifted.inputs]), whole = ([n]) => named.has(n) && !named.has(`${n}$neg`);
799
+ const rule = asRule({ ...lifted, name: `${m0.name}, every fiber` }, Object.fromEntries([...parts.params, ...parts.inputs].filter(whole)));
800
+ const names = (one.names ?? []).filter(n => !(n.role === 'state' && local(n.rule)) && n.role !== 'result' && !made.has(n.code));
801
+ const inv = (one.invariants ?? []).filter(l => ![...JSON.stringify(l.holds).matchAll(/"name":"([^"]*)"/g)].some(m => local(m[1])));
802
+ const steps = split.map((mt, mi) => ({ name: mt.name, steps: mt.units.length, base: (mi + 1) * 100 }));
803
+ return { ...one, rule, names: [...names, { code: 'fiber', rule: 'fiber', role: 'input' }], invariants: inv, fibers: steps, replay: undefined,
804
+ notes: [`calls from many fibers at once: ${split.map(mt => `${mt.name} is ${mt.units.length} steps`).join(', ')} (each transaction or Ref operation one), the fibers interleaving them: the rule is every fiber's (lift: each fiber's place and what it carries a map keyed by the input fiber, the service's Refs (${shared.filter(n => !n.endsWith('$neg')).join(', ')}) shared); each other method is one step. A request is one fiber's next step: a fiber in the middle of a call takes its next step whatever method the request names. A failure in a later step ends the call as a return does. A law reads the service's Refs`, ...one.notes],
805
+ source: out };
806
+ }
807
+ // A run of every fiber's rule as what each fiber does: starts a call (with its arguments), or takes the next step of the
808
+ // call it is in.
809
+ export function fiberRun(x, run) {
810
+ const fibers = x.fibers ?? [], r = x.rule;
811
+ const go = interpret(r.machine), ps = r.encodeParams(run.params), method = new Map(r.parts.inputs).get('method');
812
+ let st = go.init(ps);
813
+ return run.trace.map(q => {
814
+ const f = Number(q.fiber), pc = st.maps.__gdp_pc?.get(f) ?? 0, m = method ? method.decode('method', q) : x.model?.events[0]?.call ?? 'step';
815
+ st = go.step(ps, st, q);
816
+ if (pc === 0) {
817
+ const sp = fibers.find(s2 => s2.name === m), args = (x.names ?? []).filter(n => n.role === 'input' && n.method === m && n.rule in q).map(n => `${n.code.split('.').pop()} = ${String(q[n.rule])}`);
818
+ return `fiber ${f}: ${m}(${args.join(', ')})${sp ? `, its step 1 of ${sp.steps}` : ''}`;
819
+ }
820
+ const sp = fibers.find(s2 => pc > s2.base && pc <= s2.base + s2.steps);
821
+ return `fiber ${f}: ${sp.name}, its step ${pc - sp.base} of ${sp.steps}`;
822
+ });
823
+ }
824
+ const isSchedule = (s, e) => {
825
+ e = strip(e);
826
+ if (ts.isCallExpression(e) && ts.isPropertyAccessExpression(e.expression) && memberName(e.expression.name) === 'pipe' && !apiOf(s, e.expression))
827
+ return isSchedule(s, e.expression.expression);
828
+ return (ts.isCallExpression(e) ? apiOf(s, e.expression) : apiOf(s, e))?.startsWith('Schedule.') ?? false;
829
+ };
830
+ function scheduleEntry(code, file, opts) {
831
+ if (!/\bSchedule\b/.test(code))
832
+ return undefined;
833
+ const s = setupOf(code, placed(file), {}, opts.files), found = [];
834
+ for (const st of s.sf.statements) {
835
+ const decls = ts.isVariableStatement(st) ? st.declarationList.declarations.filter(d => ts.isIdentifier(d.name) && d.initializer).map(d => [d.name.text, d.initializer])
836
+ : ts.isFunctionDeclaration(st) && st.name ? [[st.name.text, st]] : [];
837
+ for (const [name, init] of decls) {
838
+ if (opts.entry && opts.entry !== name)
839
+ continue;
840
+ const f = ts.isFunctionDeclaration(init) ? init : ts.isArrowFunction(strip(init)) || ts.isFunctionExpression(strip(init)) ? strip(init) : undefined;
841
+ const body = f ? lastReturn(f.body) : init;
842
+ if (!body || !isSchedule(s, body) || (f && ts.isBlock(f.body) && f.body.statements.length > 1))
843
+ continue;
844
+ found.push({ name, expr: body, params: (f?.parameters ?? []).map(p => (ts.isIdentifier(p.name) ? p.name.text : refuse(p, `${text(p)}: a parameter other than a name`))), s });
845
+ }
846
+ }
847
+ if (opts.entry)
848
+ return found[0];
849
+ // (a file with a service reads the service; else its one schedule, the exported ones first)
850
+ if (found.length === 0)
851
+ return undefined;
852
+ try {
853
+ serviceOf(code, file, opts);
854
+ return undefined;
855
+ }
856
+ catch (e) {
857
+ if (!(e instanceof Refusal))
858
+ throw e;
859
+ }
860
+ const exported = found.filter(f => new RegExp(`export\\s+(?:const|function)\\s+${f.name}\\b`).test(code));
861
+ const pick = exported.length ? exported : found;
862
+ if (pick.length > 1)
863
+ throw new Refusal(file, `several schedules in the file (${pick.map(f => f.name).join(', ')}): name one (entry)`);
864
+ return pick[0];
865
+ }
866
+ // The schedule read into its rule, and checked by stepping the file's own schedule on Effect beside it.
867
+ function fromScheduleEntry(code, file, e, E, opts) {
868
+ const t0 = Date.now(), v4 = 'TxRef' in E, s = e.s;
869
+ const params = new Map();
870
+ const fnDecl = (() => { let n = e.expr; while (n && !ts.isFunctionLike(n))
871
+ n = n.parent; return n; })();
872
+ for (const p of fnDecl?.parameters ?? [])
873
+ if (ts.isIdentifier(p.name))
874
+ params.set(p, p.name.text);
875
+ const P = new Parts();
876
+ for (const n of e.params)
877
+ P.params.set(n, dsl.nat);
878
+ let sr;
879
+ try {
880
+ sr = scheduleRule(readSchedule(e.expr, { api: x => apiOf(s, x), checker: s.checker, v4, params, sf: s.sf }, P).frag, P, e.name, v4);
881
+ }
882
+ catch (x) {
883
+ if (x instanceof Refusal)
884
+ return { ok: false, refusals: [{ where: x.where, what: x.what }], notes: [] };
885
+ throw x;
886
+ }
887
+ const notes = [`${e.name} is an Effect ${v4 ? '4' : '3'} Schedule: each step is one of its decisions (go on after a delay, or stop), at the time the attempt before it ended; attempt, retries, delay, elapsed and done are the rule's own${e.params.length ? `; its parameters (${e.params.join(', ')}) are the rule's params, naturals` : ''}`, ...sr.notes];
888
+ const modules = { effect: E, ...Object.fromEntries(Object.entries(E).map(([k, x]) => [`effect/${k}`, x])), ...opts.modules };
889
+ const box = sandbox(code, file, [e.name], modules, undefined, opts.files);
890
+ const value = box.get(e.name), make = (p) => (typeof value === 'function' ? value(...e.params.map(n => p[n])) : value);
891
+ const runs = opts.check?.runs ?? 60, c = scheduleConforms(sr, make, E, { runs, depth: 14 });
892
+ const evidence = { runs, requests: c.checked, fromStates: 0, probes: { conditions: 0, witnesses: 0, steps: 0 }, refusedBoth: 0, outside: 0, edge: 0, compiledAgreed: c.checked, coverage: { arms: 0, hit: 0, missed: [] }, ms: Date.now() - t0, ...(c.failure ? { mismatch: c.failure } : {}) };
893
+ const source = `// ${e.name}: ${e.expr.getText().replace(/\s+/g, ' ')}\n${sr.rule.machine.name}: state ${Object.keys(sr.rule.machine.state).join(', ')}; inputs ${sr.rule.machine.inputs.join(', ')}${sr.rule.machine.params.length ? `; params ${sr.rule.machine.params.join(', ')}` : ''}`;
894
+ if (c.failure)
895
+ return { ok: false, rule: sr.rule, source, refusals: [{ where: file, what: `the rule and Effect's own schedule part: ${c.failure}` }], notes, names: sr.names, evidence };
896
+ return { ok: true, rule: sr.rule, source, refusals: [], notes, names: sr.names, evidence, schedule: sr, replay: run => replaySchedule(sr, make(run.params), E, run) };
897
+ }
898
+ // A schedule written as source (an expression over Schedule and Duration, with `params` its free names) read into its
899
+ // rule and checked against the schedule Effect makes of it: fromSchedule('Schedule.exponential("10 millis").pipe(Schedule.upTo({times: 5}))', {effect}).
900
+ export function fromSchedule(source, opts) {
901
+ const ps = opts.params ?? [], name = opts.name ?? 'schedule';
902
+ const code = `import {Duration, Effect, Schedule} from 'effect'\nexport const ${name} = (${ps.map(p => `${p}: number`).join(', ')}) => ${source}\n`;
903
+ return extractEffect(code, { file: 'schedule.ts', entry: name, effect: opts.effect, check: { runs: opts.runs ?? 60 } });
381
904
  }
382
905
  // The service a file has: of its declarations (the exported ones first), those whose make effect reads, one make effect
383
906
  // however many names reach it (make, and a Layer of it).