@orkestrel/test 0.0.29 → 0.0.31

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.
@@ -1,5 +1,19 @@
1
1
  import { attempt, holds, isArray, isDefined, isError, isFiniteNumber, isFunction, isInteger, isNumber, isObject, isSymbol } from "@orkestrel/contract";
2
- //#region src/core/constants.ts
2
+ // src/core/constants.ts
3
+ /**
4
+ * Bounds how far a real timer can end short of its duration, in whole milliseconds.
5
+ *
6
+ * @remarks Node stamps an armed timer with libuv's whole-millisecond loop clock. Truncation and
7
+ * a coarse clock tick can each contribute under 1 ms of lead. Subtract this lead from an elapsed
8
+ * lower bound measured with `performance.now()` before arming the timer.
9
+ * @example
10
+ * ```ts
11
+ * const started = performance.now()
12
+ * await waitForDelay(10)
13
+ * performance.now() - started >= 10 - TIMER_LEAD // true
14
+ * ```
15
+ */
16
+ var TIMER_LEAD = 2;
3
17
  /**
4
18
  * Names the attributes a statechart harness publishes, keyed by the fact each one carries.
5
19
  *
@@ -58,8 +72,7 @@ var STATECHART_STATUSES = Object.freeze([
58
72
  "passed",
59
73
  "failed"
60
74
  ]);
61
- //#endregion
62
- //#region src/core/validators.ts
75
+ // src/core/validators.ts
63
76
  /**
64
77
  * Checks whether a value contains a recorder for every listed event.
65
78
  *
@@ -96,8 +109,28 @@ function isRecorderMapComplete(value, events) {
96
109
  });
97
110
  });
98
111
  }
99
- //#endregion
100
- //#region src/core/helpers.ts
112
+ // src/core/Production.ts
113
+ /** Holds one producer attempt across its native await and catch boundary. */
114
+ var Production = class {
115
+ #result;
116
+ get result() {
117
+ if (this.#result === void 0) throw new Error("Producer attempt has not settled");
118
+ return this.#result;
119
+ }
120
+ accept(value) {
121
+ this.#result = {
122
+ status: "fulfilled",
123
+ value
124
+ };
125
+ }
126
+ refuse(reason) {
127
+ this.#result = {
128
+ status: "rejected",
129
+ reason
130
+ };
131
+ }
132
+ };
133
+ // src/core/helpers.ts
101
134
  /**
102
135
  * Checks the resolved bounds one bounded wait runs under.
103
136
  *
@@ -298,12 +331,14 @@ async function waitForText(description, read, text, options) {
298
331
  if (absent !== void 0 && absent.length === 0) throw new Error("Text expectation must not be empty");
299
332
  if (absent !== void 0 && text.includes(absent)) throw new Error("Text departure must not appear in the text expectation");
300
333
  const exact = options?.exact ?? false;
301
- let reading = "";
334
+ const accepted = Promise.withResolvers();
302
335
  await waitForCondition(description, () => {
303
- reading = read();
304
- return (exact ? reading === text : reading.includes(text)) && (absent === void 0 || !reading.includes(absent));
336
+ const observed = read();
337
+ const held = (exact ? observed === text : observed.includes(text)) && (absent === void 0 || !observed.includes(absent));
338
+ if (held) accepted.resolve(observed);
339
+ return held;
305
340
  }, options);
306
- return reading;
341
+ return accepted.promise;
307
342
  }
308
343
  /**
309
344
  * Repeats a producer until one produced value satisfies a predicate.
@@ -327,47 +362,48 @@ async function retryUntil(description, produce, satisfied, options) {
327
362
  checkBounds("Retry", budget, interval);
328
363
  if (isDefined(attempts) && (!isInteger(attempts) || attempts < 1)) throw new Error("Retry attempts must be a positive integer");
329
364
  const start = performance.now();
330
- let count = 0;
331
- let cause;
332
- let last;
365
+ const outcomes = [];
333
366
  while (true) {
334
367
  options?.signal?.throwIfAborted();
335
- if (count > 0) {
368
+ const previous = outcomes.reduce((summary, outcome) => outcome.success ? {
369
+ ...summary,
370
+ last: outcome.value
371
+ } : {
372
+ ...summary,
373
+ cause: outcome.error
374
+ }, {
375
+ last: void 0,
376
+ cause: void 0
377
+ });
378
+ if (outcomes.length > 0) {
336
379
  const elapsed = performance.now() - start;
337
- if (elapsed >= budget) throw buildRetryExhausted(description, budget, elapsed, last, cause);
380
+ if (elapsed >= budget) throw buildRetryExhausted(description, budget, elapsed, previous.last, previous.cause);
338
381
  }
339
- let produced;
382
+ const production = new Production();
340
383
  try {
341
- produced = {
342
- success: true,
343
- value: await produce()
344
- };
384
+ production.accept(await produce());
345
385
  } catch (error) {
346
- produced = {
347
- success: false,
348
- error
349
- };
386
+ production.refuse(error);
350
387
  }
351
- count += 1;
388
+ const produced = production.result;
352
389
  options?.signal?.throwIfAborted();
353
- if (produced.success) {
390
+ if (produced.status === "fulfilled") {
354
391
  if (satisfied(produced.value)) return produced.value;
355
- let rendered;
356
- try {
357
- const serialized = JSON.stringify(produced.value);
358
- rendered = serialized === void 0 ? String(produced.value) : serialized;
359
- } catch {
360
- try {
361
- rendered = String(produced.value);
362
- } catch {
363
- rendered = "[unrenderable]";
364
- }
365
- }
366
- last = rendered.length > 200 ? `${rendered.slice(0, 197)}...` : rendered;
367
- } else cause = produced.error;
392
+ const rendered = renderRetryValue(produced.value);
393
+ outcomes.push({
394
+ success: true,
395
+ value: rendered.length > 200 ? `${rendered.slice(0, 197)}...` : rendered
396
+ });
397
+ } else outcomes.push({
398
+ success: false,
399
+ error: produced.reason
400
+ });
401
+ const latest = outcomes.at(-1);
402
+ const last = latest?.success === true ? latest.value : previous.last;
403
+ const cause = latest?.success === false ? latest.error : previous.cause;
368
404
  const elapsed = performance.now() - start;
369
405
  if (elapsed >= budget) throw buildRetryExhausted(description, budget, elapsed, last, cause);
370
- if (attempts !== void 0 && count >= attempts) throw new Error(`Retry "${description}" did not succeed within ${attempts} attempts${last === void 0 ? "" : ` (last value: ${last})`}`, { cause });
406
+ if (attempts !== void 0 && outcomes.length >= attempts) throw new Error(`Retry "${description}" did not succeed within ${attempts} attempts${last === void 0 ? "" : ` (last value: ${last})`}`, { cause });
371
407
  await waitForDelay(Math.min(interval, budget - elapsed));
372
408
  }
373
409
  }
@@ -433,30 +469,25 @@ async function waitForEvent(subscribe, description, options) {
433
469
  signal?.throwIfAborted();
434
470
  const delivery = Promise.withResolvers();
435
471
  const controller = new AbortController();
436
- let timeout;
437
- const pending = [delivery.promise, new Promise((_resolve, reject) => {
438
- timeout = setTimeout(() => {
439
- reject(/* @__PURE__ */ new Error(`Event "${description}" was not delivered within ${budget}ms`));
440
- }, budget);
441
- })];
472
+ const expiry = Promise.withResolvers();
473
+ const timeout = setTimeout(() => {
474
+ expiry.reject(/* @__PURE__ */ new Error(`Event "${description}" was not delivered within ${budget}ms`));
475
+ }, budget);
476
+ const pending = [delivery.promise, expiry.promise];
442
477
  if (signal !== void 0) pending.push(new Promise((_resolve, reject) => {
443
478
  AbortSignal.any([signal, controller.signal]).addEventListener("abort", () => {
444
479
  if (signal.aborted) reject(signal.reason);
445
480
  }, { once: true });
446
481
  }));
447
482
  const result = Promise.race(pending);
448
- let cleanup = void 0;
483
+ const subscription = attempt(() => subscribe((...args) => delivery.resolve(args)));
449
484
  try {
450
- try {
451
- cleanup = subscribe((...args) => delivery.resolve(args));
452
- } catch (error) {
453
- delivery.reject(error);
454
- }
485
+ if (!subscription.success) delivery.reject(subscription.error);
455
486
  return await result;
456
487
  } finally {
457
488
  controller.abort();
458
- if (timeout !== void 0) clearTimeout(timeout);
459
- cleanup?.();
489
+ clearTimeout(timeout);
490
+ if (subscription.success) subscription.value?.();
460
491
  }
461
492
  }
462
493
  /**
@@ -528,11 +559,11 @@ function decodeJSONLines(text) {
528
559
  function collectSelectorClasses(selector) {
529
560
  const escape = String.raw`\\(?:[0-9a-f]{1,6}(?:\r\n|[ \t\r\n\f])?|[^\r\n\f0-9a-f])`;
530
561
  const name = String.raw`(?:${escape}|[-\w\u{80}-\u{10FFFF}])`;
531
- const opening = String.raw`(?:--|-?(?:[_a-z\u{80}-\u{10FFFF}]|${escape}))`;
562
+ const prefix = String.raw`(?:--|-?(?:[_a-z\u{80}-\u{10FFFF}]|${escape}))`;
532
563
  const quoted = String.raw`"(?:[^"\\\r\n\f]|\\(?:\r\n|[\s\S]))*"|'(?:[^'\\\r\n\f]|\\(?:\r\n|[\s\S]))*'`;
533
564
  const comment = String.raw`/\*[\s\S]*?\*/`;
534
565
  const attribute = String.raw`\[(?:${quoted}|${comment}|${escape}|/(?!\*)|[^[\]"'\\/])*\]`;
535
- const tokens = [...selector.matchAll(new RegExp(String.raw`${quoted}|${comment}|${attribute}|\.(${opening}${name}*)|${name}+|[()]|[\s>+~,*:#|&=]`, "giuy"))];
566
+ const tokens = [...selector.matchAll(new RegExp(String.raw`${quoted}|${comment}|${attribute}|\.(${prefix}${name}*)|${name}+|[()]|[\s>+~,*:#|&=]`, "giuy"))];
536
567
  const covered = tokens.reduce((length, [text]) => length + text.length, 0);
537
568
  const depth = tokens.reduce((open, [text]) => open < 0 ? open : open + Number(text === "(") - Number(text === ")"), 0);
538
569
  if (covered !== selector.length || depth !== 0) throw new Error(`Unreadable selector: ${selector}`);
@@ -697,17 +728,73 @@ async function executeScenario(scenario, context) {
697
728
  */
698
729
  async function executeScenarios(scenarios, build) {
699
730
  for (const scenario of scenarios) {
700
- let context;
701
- try {
702
- context = await build(scenario);
703
- } catch (cause) {
704
- throw buildRefusal(scenario.transition.name, cause);
705
- }
706
- await executeScenario(scenario, context);
731
+ const context = await captureProduction(() => build(scenario));
732
+ if (context.status === "rejected") throw buildRefusal(scenario.transition.name, context.reason);
733
+ await executeScenario(scenario, context.value);
734
+ }
735
+ }
736
+ /**
737
+ * Captures a synchronous or asynchronous producer's value or exact refusal.
738
+ *
739
+ * @example
740
+ * ```ts
741
+ * await captureProduction(() => 7) // { status: 'fulfilled', value: 7 }
742
+ * ```
743
+ */
744
+ async function captureProduction(produce) {
745
+ try {
746
+ return {
747
+ status: "fulfilled",
748
+ value: await produce()
749
+ };
750
+ } catch (error) {
751
+ return {
752
+ status: "rejected",
753
+ reason: error
754
+ };
707
755
  }
708
756
  }
709
- //#endregion
710
- //#region src/core/factories.ts
757
+ /**
758
+ * Renders a retry value as JSON, plain text, or an unreadable-value marker.
759
+ *
760
+ * @example
761
+ * ```ts
762
+ * renderRetryValue({ ready: false }) // '{"ready":false}'
763
+ * ```
764
+ */
765
+ function renderRetryValue(value) {
766
+ const serialized = attempt(() => {
767
+ const text = JSON.stringify(value);
768
+ return text === void 0 ? String(value) : text;
769
+ });
770
+ if (serialized.success) return serialized.value;
771
+ const text = attempt(() => String(value));
772
+ return text.success ? text.value : "[unrenderable]";
773
+ }
774
+ // src/core/Teardown.ts
775
+ /** Owns the handlers behind a teardown projection. */
776
+ var Teardown = class {
777
+ #handlers = [];
778
+ get count() {
779
+ return this.#handlers.length;
780
+ }
781
+ add(handler) {
782
+ this.#handlers.push(handler);
783
+ }
784
+ async destroy() {
785
+ const snapshot = this.#handlers;
786
+ this.#handlers = [];
787
+ const failures = [];
788
+ for (const handler of snapshot.reverse()) try {
789
+ await handler();
790
+ } catch (error) {
791
+ failures.push(error);
792
+ }
793
+ if (failures.length === 1) throw failures[0];
794
+ if (failures.length > 1) throw new AggregateError(failures);
795
+ }
796
+ };
797
+ // src/core/factories.ts
711
798
  /**
712
799
  * Creates values that make common object readers throw or violate their assumptions.
713
800
  *
@@ -833,14 +920,14 @@ function createRecorder() {
833
920
  * reports `true` because it checks the listed events. Pass a literal array or a tuple.
834
921
  */
835
922
  function createRecorders(source, events) {
836
- const building = {};
923
+ const recorders = {};
837
924
  for (const event of events) {
838
925
  const recorder = createRecorder();
839
926
  source.on(event, recorder.handler);
840
- building[event] = recorder;
927
+ recorders[event] = recorder;
841
928
  }
842
- if (!isRecorderMapComplete(building, events)) throw new Error("Emitter recorder map is incomplete");
843
- return building;
929
+ if (!isRecorderMapComplete(recorders, events)) throw new Error("Emitter recorder map is incomplete");
930
+ return recorders;
844
931
  }
845
932
  /**
846
933
  * Creates a real abort controller whose signal reports its live abort listeners.
@@ -955,29 +1042,15 @@ function createResourceFactory() {
955
1042
  * @returns A teardown list that awaits every handler and collects failures.
956
1043
  */
957
1044
  function createTeardown() {
958
- let handlers = [];
1045
+ const teardown = new Teardown();
959
1046
  return {
960
1047
  get count() {
961
- return handlers.length;
962
- },
963
- add(handler) {
964
- handlers.push(handler);
1048
+ return teardown.count;
965
1049
  },
966
- async destroy() {
967
- const snapshot = handlers;
968
- handlers = [];
969
- const failures = [];
970
- for (const handler of snapshot.reverse()) try {
971
- await handler();
972
- } catch (error) {
973
- failures.push(error);
974
- }
975
- if (failures.length === 1) throw failures[0];
976
- if (failures.length > 1) throw new AggregateError(failures);
977
- }
1050
+ add: teardown.add.bind(teardown),
1051
+ destroy: teardown.destroy.bind(teardown)
978
1052
  };
979
1053
  }
980
- //#endregion
981
- export { STATECHART_ATTRIBUTES, STATECHART_STATUSES, buildRefusal, buildRetryExhausted, captureError, checkBounds, collect, collectSelectorClasses, collectStream, createHostileValues, createRecorder, createRecorders, createResourceFactory, createSignal, createTeardown, decodeJSONLines, dropRegistration, executeScenario, executeScenarios, flattenHeaders, invokeUnchecked, isRecorderMapComplete, readProperty, requireValue, resolveRoot, retryUntil, roundTripJSON, waitForAbort, waitForCondition, waitForDelay, waitForEvent, waitForText };
1054
+ export { STATECHART_ATTRIBUTES, STATECHART_STATUSES, TIMER_LEAD, buildRefusal, buildRetryExhausted, captureError, captureProduction, checkBounds, collect, collectSelectorClasses, collectStream, createHostileValues, createRecorder, createRecorders, createResourceFactory, createSignal, createTeardown, decodeJSONLines, dropRegistration, executeScenario, executeScenarios, flattenHeaders, invokeUnchecked, isRecorderMapComplete, readProperty, renderRetryValue, requireValue, resolveRoot, retryUntil, roundTripJSON, waitForAbort, waitForCondition, waitForDelay, waitForEvent, waitForText };
982
1055
 
983
1056
  //# sourceMappingURL=index.js.map