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