@usearazzo/runner 1.0.1-alpha.32 → 1.0.1-alpha.34

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 (66) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +10 -1
  3. package/dist/arazzo-runner.browser.js +1789 -403
  4. package/dist/arazzo-runner.browser.min.js +1 -1
  5. package/package.json +18 -17
  6. package/src/ArazzoRunner.cjs +26 -3
  7. package/src/ArazzoRunner.mjs +26 -3
  8. package/src/action/ActionResolver.cjs +13 -12
  9. package/src/action/ActionResolver.mjs +13 -12
  10. package/src/client/OpenAPIOperationResponse.cjs +9 -0
  11. package/src/client/OpenAPIOperationResponse.mjs +9 -0
  12. package/src/criterion/CriterionEvaluator.cjs +13 -8
  13. package/src/criterion/CriterionEvaluator.mjs +13 -8
  14. package/src/criterion/SimpleCriterionEvaluator.cjs +5 -3
  15. package/src/criterion/SimpleCriterionEvaluator.mjs +6 -4
  16. package/src/document/APIDocument.cjs +53 -0
  17. package/src/document/APIDocument.mjs +53 -0
  18. package/src/executor/OpenAPIOperationExecutor.cjs +66 -6
  19. package/src/executor/OpenAPIOperationExecutor.mjs +66 -6
  20. package/src/executor/OpenAPIOperationLocatorNormalizer.cjs +1 -1
  21. package/src/executor/OpenAPIOperationLocatorNormalizer.mjs +1 -1
  22. package/src/executor/StepExecutor.cjs +34 -15
  23. package/src/executor/StepExecutor.mjs +34 -15
  24. package/src/executor/StepRetryRunner.cjs +5 -3
  25. package/src/executor/StepRetryRunner.mjs +5 -3
  26. package/src/executor/StepTransitionInterpreter.cjs +1 -1
  27. package/src/executor/StepTransitionInterpreter.mjs +1 -1
  28. package/src/executor/WorkflowCallStack.cjs +1 -1
  29. package/src/executor/WorkflowCallStack.mjs +1 -1
  30. package/src/executor/WorkflowExecutor.cjs +277 -61
  31. package/src/executor/WorkflowExecutor.mjs +277 -61
  32. package/src/expression/RuntimeExpressionEvaluator.cjs +52 -9
  33. package/src/expression/RuntimeExpressionEvaluator.mjs +52 -9
  34. package/src/index.cjs +7 -0
  35. package/src/index.mjs +2 -0
  36. package/src/observability/ArazzoRunnerEvent.cjs +5 -0
  37. package/src/observability/ArazzoRunnerEvent.mjs +1 -0
  38. package/src/observability/DocumentRegistryEvent.cjs +5 -0
  39. package/src/observability/DocumentRegistryEvent.mjs +1 -0
  40. package/src/observability/EventChannel.cjs +96 -0
  41. package/src/observability/EventChannel.mjs +91 -0
  42. package/src/observability/OpenAPIOperationEvent.cjs +5 -0
  43. package/src/observability/OpenAPIOperationEvent.mjs +1 -0
  44. package/src/observability/Redactor.cjs +213 -0
  45. package/src/observability/Redactor.mjs +208 -0
  46. package/src/observability/WorkflowExecutionEvent.cjs +5 -0
  47. package/src/observability/WorkflowExecutionEvent.mjs +1 -0
  48. package/src/registry/DocumentRegistry.cjs +57 -11
  49. package/src/registry/DocumentRegistry.mjs +57 -11
  50. package/src/registry/providers/ArazzoDocumentRegistryProvider.cjs +21 -0
  51. package/src/registry/providers/ArazzoDocumentRegistryProvider.mjs +22 -1
  52. package/src/registry/providers/DocumentRegistryProvider.cjs +33 -1
  53. package/src/registry/providers/DocumentRegistryProvider.mjs +33 -1
  54. package/src/registry/providers/OpenAPIDocumentRegistryProvider.cjs +28 -5
  55. package/src/registry/providers/OpenAPIDocumentRegistryProvider.mjs +28 -5
  56. package/src/resolver/ArazzoValueResolver.cjs +6 -3
  57. package/src/resolver/ArazzoValueResolver.mjs +6 -3
  58. package/src/resolver/OpenAPIOperationParameterResolver.cjs +2 -2
  59. package/src/resolver/OpenAPIOperationParameterResolver.mjs +2 -2
  60. package/src/resolver/OutputResolver.cjs +10 -3
  61. package/src/resolver/OutputResolver.mjs +10 -3
  62. package/src/resolver/RequestBodyResolver.cjs +37 -17
  63. package/src/resolver/RequestBodyResolver.mjs +37 -17
  64. package/src/resolver/WorkflowParameterResolver.cjs +2 -2
  65. package/src/resolver/WorkflowParameterResolver.mjs +2 -2
  66. package/types/runner.d.ts +788 -41
@@ -12,6 +12,8 @@ var _json = _interopRequireDefault(require("@swaggerexpert/json-pointer/evaluate
12
12
  var _apidomJsonPointer = require("@speclynx/apidom-json-pointer");
13
13
  var _apidomCore = require("@speclynx/apidom-core");
14
14
  var _RuntimeExpressionError = _interopRequireDefault(require("../errors/RuntimeExpressionError.cjs"));
15
+ var _DocumentLoadError = _interopRequireDefault(require("../errors/DocumentLoadError.cjs"));
16
+ var _UnmatchedProviderError = _interopRequireDefault(require("../errors/UnmatchedProviderError.cjs"));
15
17
  var _ArazzoDocument = _interopRequireDefault(require("../document/ArazzoDocument.cjs"));
16
18
  var _OpenAPIDocument = _interopRequireDefault(require("../document/OpenAPIDocument.cjs"));
17
19
  /**
@@ -55,6 +57,9 @@ const HTTP_EXCHANGE_NODES = new Set(['UrlExpression', 'MethodExpression', 'Statu
55
57
  * (via the registry) the source name points at. A step reference resolves to
56
58
  * the Step Object as authored — a locator, not the step's execution result.
57
59
  *
60
+ * Evaluation is asynchronous because a `$sourceDescriptions` reference may
61
+ * have to load the document it points at.
62
+ *
58
63
  * A reference resolves to `undefined` when it is absent. Runtime values
59
64
  * originate from JSON (or ApiDOM), which cannot represent `undefined` — an
60
65
  * absent value is a missing property and an explicit null is `null` — so
@@ -88,11 +93,19 @@ class RuntimeExpressionEvaluator {
88
93
  * The expression must be the bare form without surrounding braces
89
94
  * (e.g. `$inputs.username`, `$response.body#/pets/0/id`). In strict mode an
90
95
  * unresolvable reference throws; otherwise it returns `undefined`.
96
+ *
97
+ * A `$sourceDescriptions` reference whose document cannot be loaded is not
98
+ * merely unresolved: unless it names a field of the Source Description Object,
99
+ * it rejects with the load error in either mode, since nothing else can
100
+ * produce its value.
101
+ *
102
+ * @throws DocumentLoadError - When a referenced source document cannot be read or loaded
103
+ * @throws UnmatchedProviderError - When no provider can load a referenced source document
91
104
  */
92
- evaluate(expression) {
105
+ async evaluate(expression) {
93
106
  const node = this.#parse(expression);
94
107
  this.#assertAvailable(node, expression);
95
- const value = this.#evaluateNode(node, expression);
108
+ const value = await this.#evaluateNode(node, expression);
96
109
  if (value === undefined && this.#strict) {
97
110
  throw new _RuntimeExpressionError.default(`Runtime expression "${expression}" could not be resolved against the context`, {
98
111
  expression,
@@ -110,8 +123,20 @@ class RuntimeExpressionEvaluator {
110
123
  * mode, unresolvable references render as an empty string. A `{…}` that is not
111
124
  * a valid embedded expression (e.g. a literal JSON payload) is left unchanged.
112
125
  */
113
- interpolate(template) {
114
- return (0, _arazzoRuntimeExpression.interpolate)(template, expression => this.evaluate(expression));
126
+ async interpolate(template) {
127
+ // `interpolate` takes a synchronous resolver, so the embedded expressions are
128
+ // collected by a first pass, evaluated in order, and substituted by a second.
129
+ // Interpolation never skips an expression, so the result is the same.
130
+ const expressions = [];
131
+ (0, _arazzoRuntimeExpression.interpolate)(template, expression => {
132
+ expressions.push(expression);
133
+ return '';
134
+ });
135
+ const values = new Map();
136
+ for (const expression of expressions) {
137
+ if (!values.has(expression)) values.set(expression, await this.evaluate(expression));
138
+ }
139
+ return (0, _arazzoRuntimeExpression.interpolate)(template, expression => values.get(expression));
115
140
  }
116
141
 
117
142
  /**
@@ -125,7 +150,7 @@ class RuntimeExpressionEvaluator {
125
150
  * yields the string representation of its value, not the typed value. A
126
151
  * string containing no expressions is returned unchanged.
127
152
  */
128
- resolve(value) {
153
+ async resolve(value) {
129
154
  // `test` returns true only when the entire string is a valid runtime
130
155
  // expression, so a braced or mixed string falls through to interpolation.
131
156
  return (0, _arazzoRuntimeExpression.test)(value) ? this.evaluate(value) : this.interpolate(value);
@@ -263,17 +288,35 @@ class RuntimeExpressionEvaluator {
263
288
  * `$sourceDescriptions.{name}.url` yields the source's URL. An operationId
264
289
  * that collides with a field name takes precedence (tier 1 wins).
265
290
  *
291
+ * The referenced document is acquired only when the registry can load the
292
+ * source's `type`; a source no provider loads (e.g. AsyncAPI) resolves by
293
+ * tier 2 alone. When acquiring fails, a `{reference}` naming a field present
294
+ * on the Source Description Object still resolves to that field — it does
295
+ * not depend on the document — and any other reference rethrows the load
296
+ * error, since nothing else can produce its value.
297
+ *
266
298
  * Returns `undefined` when nothing matches.
267
299
  */
268
- #sourceDescription({
300
+ async #sourceDescription({
269
301
  sourceName,
270
302
  reference,
271
303
  stepsReference
272
304
  }) {
273
- const uri = this.#document?.resolveSourceDescriptionURI(sourceName);
305
+ const document = this.#document;
306
+ const uri = document?.resolveSourceDescriptionURI(sourceName);
307
+ const type = document?.resolveSourceDescriptionField(sourceName, 'type');
308
+ const field = document?.resolveSourceDescriptionField(sourceName, reference);
274
309
 
275
310
  // tier 1: operationId / workflowId / workflow step in the referenced document.
276
- const apiDocument = uri === undefined ? undefined : this.#registry?.get(uri);
311
+ let apiDocument;
312
+ if (uri !== undefined && this.#registry !== undefined && this.#registry.canLoad(typeof type === 'string' ? type : undefined)) {
313
+ try {
314
+ apiDocument = await this.#registry.acquire(uri);
315
+ } catch (error) {
316
+ const unloadable = error instanceof _DocumentLoadError.default || error instanceof _UnmatchedProviderError.default;
317
+ if (!unloadable || field === undefined) throw error;
318
+ }
319
+ }
277
320
  if (apiDocument !== undefined) {
278
321
  if (stepsReference !== undefined) {
279
322
  return this.#step(apiDocument, stepsReference.workflowId, stepsReference.stepId);
@@ -283,7 +326,7 @@ class RuntimeExpressionEvaluator {
283
326
  }
284
327
 
285
328
  // tier 2: a field of the Source Description Object (url, type, ...).
286
- return this.#document?.resolveSourceDescriptionField(sourceName, reference);
329
+ return field;
287
330
  }
288
331
 
289
332
  /**
@@ -5,6 +5,8 @@ import JSONEvaluationRealm from '@swaggerexpert/json-pointer/evaluate/realms/jso
5
5
  import { ApiDOMEvaluationRealm } from '@speclynx/apidom-json-pointer';
6
6
  import { toValue } from '@speclynx/apidom-core';
7
7
  import RuntimeExpressionError from "../errors/RuntimeExpressionError.mjs";
8
+ import DocumentLoadError from "../errors/DocumentLoadError.mjs";
9
+ import UnmatchedProviderError from "../errors/UnmatchedProviderError.mjs";
8
10
  import ArazzoDocument from "../document/ArazzoDocument.mjs";
9
11
  import OpenAPIDocument from "../document/OpenAPIDocument.mjs";
10
12
  /**
@@ -46,6 +48,9 @@ const HTTP_EXCHANGE_NODES = new Set(['UrlExpression', 'MethodExpression', 'Statu
46
48
  * (via the registry) the source name points at. A step reference resolves to
47
49
  * the Step Object as authored — a locator, not the step's execution result.
48
50
  *
51
+ * Evaluation is asynchronous because a `$sourceDescriptions` reference may
52
+ * have to load the document it points at.
53
+ *
49
54
  * A reference resolves to `undefined` when it is absent. Runtime values
50
55
  * originate from JSON (or ApiDOM), which cannot represent `undefined` — an
51
56
  * absent value is a missing property and an explicit null is `null` — so
@@ -79,11 +84,19 @@ class RuntimeExpressionEvaluator {
79
84
  * The expression must be the bare form without surrounding braces
80
85
  * (e.g. `$inputs.username`, `$response.body#/pets/0/id`). In strict mode an
81
86
  * unresolvable reference throws; otherwise it returns `undefined`.
87
+ *
88
+ * A `$sourceDescriptions` reference whose document cannot be loaded is not
89
+ * merely unresolved: unless it names a field of the Source Description Object,
90
+ * it rejects with the load error in either mode, since nothing else can
91
+ * produce its value.
92
+ *
93
+ * @throws DocumentLoadError - When a referenced source document cannot be read or loaded
94
+ * @throws UnmatchedProviderError - When no provider can load a referenced source document
82
95
  */
83
- evaluate(expression) {
96
+ async evaluate(expression) {
84
97
  const node = this.#parse(expression);
85
98
  this.#assertAvailable(node, expression);
86
- const value = this.#evaluateNode(node, expression);
99
+ const value = await this.#evaluateNode(node, expression);
87
100
  if (value === undefined && this.#strict) {
88
101
  throw new RuntimeExpressionError(`Runtime expression "${expression}" could not be resolved against the context`, {
89
102
  expression,
@@ -101,8 +114,20 @@ class RuntimeExpressionEvaluator {
101
114
  * mode, unresolvable references render as an empty string. A `{…}` that is not
102
115
  * a valid embedded expression (e.g. a literal JSON payload) is left unchanged.
103
116
  */
104
- interpolate(template) {
105
- return interpolate(template, expression => this.evaluate(expression));
117
+ async interpolate(template) {
118
+ // `interpolate` takes a synchronous resolver, so the embedded expressions are
119
+ // collected by a first pass, evaluated in order, and substituted by a second.
120
+ // Interpolation never skips an expression, so the result is the same.
121
+ const expressions = [];
122
+ interpolate(template, expression => {
123
+ expressions.push(expression);
124
+ return '';
125
+ });
126
+ const values = new Map();
127
+ for (const expression of expressions) {
128
+ if (!values.has(expression)) values.set(expression, await this.evaluate(expression));
129
+ }
130
+ return interpolate(template, expression => values.get(expression));
106
131
  }
107
132
 
108
133
  /**
@@ -116,7 +141,7 @@ class RuntimeExpressionEvaluator {
116
141
  * yields the string representation of its value, not the typed value. A
117
142
  * string containing no expressions is returned unchanged.
118
143
  */
119
- resolve(value) {
144
+ async resolve(value) {
120
145
  // `test` returns true only when the entire string is a valid runtime
121
146
  // expression, so a braced or mixed string falls through to interpolation.
122
147
  return test(value) ? this.evaluate(value) : this.interpolate(value);
@@ -254,17 +279,35 @@ class RuntimeExpressionEvaluator {
254
279
  * `$sourceDescriptions.{name}.url` yields the source's URL. An operationId
255
280
  * that collides with a field name takes precedence (tier 1 wins).
256
281
  *
282
+ * The referenced document is acquired only when the registry can load the
283
+ * source's `type`; a source no provider loads (e.g. AsyncAPI) resolves by
284
+ * tier 2 alone. When acquiring fails, a `{reference}` naming a field present
285
+ * on the Source Description Object still resolves to that field — it does
286
+ * not depend on the document — and any other reference rethrows the load
287
+ * error, since nothing else can produce its value.
288
+ *
257
289
  * Returns `undefined` when nothing matches.
258
290
  */
259
- #sourceDescription({
291
+ async #sourceDescription({
260
292
  sourceName,
261
293
  reference,
262
294
  stepsReference
263
295
  }) {
264
- const uri = this.#document?.resolveSourceDescriptionURI(sourceName);
296
+ const document = this.#document;
297
+ const uri = document?.resolveSourceDescriptionURI(sourceName);
298
+ const type = document?.resolveSourceDescriptionField(sourceName, 'type');
299
+ const field = document?.resolveSourceDescriptionField(sourceName, reference);
265
300
 
266
301
  // tier 1: operationId / workflowId / workflow step in the referenced document.
267
- const apiDocument = uri === undefined ? undefined : this.#registry?.get(uri);
302
+ let apiDocument;
303
+ if (uri !== undefined && this.#registry !== undefined && this.#registry.canLoad(typeof type === 'string' ? type : undefined)) {
304
+ try {
305
+ apiDocument = await this.#registry.acquire(uri);
306
+ } catch (error) {
307
+ const unloadable = error instanceof DocumentLoadError || error instanceof UnmatchedProviderError;
308
+ if (!unloadable || field === undefined) throw error;
309
+ }
310
+ }
268
311
  if (apiDocument !== undefined) {
269
312
  if (stepsReference !== undefined) {
270
313
  return this.#step(apiDocument, stepsReference.workflowId, stepsReference.stepId);
@@ -274,7 +317,7 @@ class RuntimeExpressionEvaluator {
274
317
  }
275
318
 
276
319
  // tier 2: a field of the Source Description Object (url, type, ...).
277
- return this.#document?.resolveSourceDescriptionField(sourceName, reference);
320
+ return field;
278
321
  }
279
322
 
280
323
  /**
package/src/index.cjs CHANGED
@@ -281,6 +281,12 @@ Object.defineProperty(exports, "OutputResolver", {
281
281
  return _OutputResolver.default;
282
282
  }
283
283
  });
284
+ Object.defineProperty(exports, "Redactor", {
285
+ enumerable: true,
286
+ get: function () {
287
+ return _Redactor.default;
288
+ }
289
+ });
284
290
  Object.defineProperty(exports, "RegexCriterionEvaluator", {
285
291
  enumerable: true,
286
292
  get: function () {
@@ -425,6 +431,7 @@ var _OpenAPIOperationExecutor = _interopRequireDefault(require("./executor/OpenA
425
431
  var _SourceDescriptionsLocatorNormalizer = _interopRequireDefault(require("./executor/SourceDescriptionsLocatorNormalizer.cjs"));
426
432
  var _OpenAPIOperationLocatorNormalizer = _interopRequireDefault(require("./executor/OpenAPIOperationLocatorNormalizer.cjs"));
427
433
  var _ArazzoWorkflowLocatorNormalizer = _interopRequireDefault(require("./executor/ArazzoWorkflowLocatorNormalizer.cjs"));
434
+ var _Redactor = _interopRequireDefault(require("./observability/Redactor.cjs"));
428
435
  var _ArazzoRunnerError = _interopRequireDefault(require("./errors/ArazzoRunnerError.cjs"));
429
436
  var _AssemblerError = _interopRequireDefault(require("./errors/AssemblerError.cjs"));
430
437
  var _ClientError = _interopRequireDefault(require("./errors/ClientError.cjs"));
package/src/index.mjs CHANGED
@@ -61,6 +61,8 @@ export { default as OpenAPIOperationExecutor } from "./executor/OpenAPIOperation
61
61
  export { default as SourceDescriptionsLocatorNormalizer } from "./executor/SourceDescriptionsLocatorNormalizer.mjs";
62
62
  export { default as OpenAPIOperationLocatorNormalizer } from "./executor/OpenAPIOperationLocatorNormalizer.mjs";
63
63
  export { default as ArazzoWorkflowLocatorNormalizer } from "./executor/ArazzoWorkflowLocatorNormalizer.mjs";
64
+ /* Observability */
65
+ export { default as Redactor } from "./observability/Redactor.mjs";
64
66
  /* Errors */
65
67
  export { default as ArazzoRunnerError } from "./errors/ArazzoRunnerError.mjs";
66
68
  export { default as AssemblerError } from "./errors/AssemblerError.mjs";
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ var _ramdaAdjunct = require("ramda-adjunct");
8
+ /**
9
+ * An event without its `timestamp`, which the channel stamps. Distributes over
10
+ * a union, so each member keeps its own discriminated shape.
11
+ * @internal
12
+ */
13
+
14
+ /**
15
+ * Options for the EventChannel.
16
+ * @internal
17
+ */
18
+
19
+ /**
20
+ * Delivers a building block's events to its observer: stamps each with the
21
+ * block's clock, snapshots it, and hands it over synchronously, without
22
+ * awaiting anything.
23
+ *
24
+ * A block holds a channel only when it was given an observer (see
25
+ * {@link EventChannel.open}), and emits through `this.#events?.emit(...)`: with
26
+ * no channel, optional chaining skips evaluating the event too, so an
27
+ * unobserved run builds no events at all.
28
+ * @internal
29
+ */
30
+ class EventChannel {
31
+ static #DEFAULT_NOW = () => performance.now();
32
+
33
+ /**
34
+ * A channel to `options.observer`, or `undefined` when there is none.
35
+ */
36
+ static open(options) {
37
+ const {
38
+ observer,
39
+ now
40
+ } = options;
41
+ return observer === undefined ? undefined : new EventChannel({
42
+ observer,
43
+ now
44
+ });
45
+ }
46
+
47
+ /**
48
+ * A frozen deep copy of the plain objects and arrays in `value`; anything
49
+ * else, an ApiDOM element above all, is shared as it is. The run keeps
50
+ * using the objects an event describes (the trace's records, the outputs,
51
+ * the context a request interceptor receives, the transition it acts on),
52
+ * so handing out the originals would let an observer change the run.
53
+ */
54
+ static #snapshot(value, copies) {
55
+ if (!Array.isArray(value) && !(0, _ramdaAdjunct.isPlainObject)(value)) return value;
56
+ const seen = copies.get(value);
57
+ if (seen !== undefined) return seen;
58
+ const copy = Array.isArray(value) ? [] : {};
59
+ copies.set(value, copy);
60
+ for (const [key, item] of Object.entries(value)) {
61
+ // defined, not assigned: assigning an own `__proto__` key (JSON.parse
62
+ // makes one) would set the copy's prototype instead of copying it.
63
+ Object.defineProperty(copy, key, {
64
+ value: EventChannel.#snapshot(item, copies),
65
+ enumerable: true,
66
+ writable: true,
67
+ configurable: true
68
+ });
69
+ }
70
+ return Object.freeze(copy);
71
+ }
72
+ #observer;
73
+ #now;
74
+ constructor(options) {
75
+ this.#observer = options.observer;
76
+ this.#now = options.now ?? EventChannel.#DEFAULT_NOW;
77
+ }
78
+
79
+ /**
80
+ * Emits the event. `timestamp` is the clock reading the event describes,
81
+ * when the caller already took one (so a start/settled pair matches a
82
+ * recorded duration exactly); otherwise the clock is read now.
83
+ */
84
+ emit(event, timestamp) {
85
+ // an absent optional field of the event itself is omitted, never present as
86
+ // undefined; undefined values inside its data (an output that resolved to
87
+ // undefined) are kept.
88
+ const fields = Object.entries(event).filter(([, value]) => value !== undefined);
89
+ const stamped = {
90
+ ...Object.fromEntries(fields),
91
+ timestamp: timestamp ?? this.#now()
92
+ };
93
+ this.#observer(EventChannel.#snapshot(stamped, new WeakMap()));
94
+ }
95
+ }
96
+ var _default = exports.default = EventChannel;
@@ -0,0 +1,91 @@
1
+ import { isPlainObject } from 'ramda-adjunct';
2
+
3
+ /**
4
+ * An event without its `timestamp`, which the channel stamps. Distributes over
5
+ * a union, so each member keeps its own discriminated shape.
6
+ * @internal
7
+ */
8
+
9
+ /**
10
+ * Options for the EventChannel.
11
+ * @internal
12
+ */
13
+
14
+ /**
15
+ * Delivers a building block's events to its observer: stamps each with the
16
+ * block's clock, snapshots it, and hands it over synchronously, without
17
+ * awaiting anything.
18
+ *
19
+ * A block holds a channel only when it was given an observer (see
20
+ * {@link EventChannel.open}), and emits through `this.#events?.emit(...)`: with
21
+ * no channel, optional chaining skips evaluating the event too, so an
22
+ * unobserved run builds no events at all.
23
+ * @internal
24
+ */
25
+ class EventChannel {
26
+ static #DEFAULT_NOW = () => performance.now();
27
+
28
+ /**
29
+ * A channel to `options.observer`, or `undefined` when there is none.
30
+ */
31
+ static open(options) {
32
+ const {
33
+ observer,
34
+ now
35
+ } = options;
36
+ return observer === undefined ? undefined : new EventChannel({
37
+ observer,
38
+ now
39
+ });
40
+ }
41
+
42
+ /**
43
+ * A frozen deep copy of the plain objects and arrays in `value`; anything
44
+ * else, an ApiDOM element above all, is shared as it is. The run keeps
45
+ * using the objects an event describes (the trace's records, the outputs,
46
+ * the context a request interceptor receives, the transition it acts on),
47
+ * so handing out the originals would let an observer change the run.
48
+ */
49
+ static #snapshot(value, copies) {
50
+ if (!Array.isArray(value) && !isPlainObject(value)) return value;
51
+ const seen = copies.get(value);
52
+ if (seen !== undefined) return seen;
53
+ const copy = Array.isArray(value) ? [] : {};
54
+ copies.set(value, copy);
55
+ for (const [key, item] of Object.entries(value)) {
56
+ // defined, not assigned: assigning an own `__proto__` key (JSON.parse
57
+ // makes one) would set the copy's prototype instead of copying it.
58
+ Object.defineProperty(copy, key, {
59
+ value: EventChannel.#snapshot(item, copies),
60
+ enumerable: true,
61
+ writable: true,
62
+ configurable: true
63
+ });
64
+ }
65
+ return Object.freeze(copy);
66
+ }
67
+ #observer;
68
+ #now;
69
+ constructor(options) {
70
+ this.#observer = options.observer;
71
+ this.#now = options.now ?? EventChannel.#DEFAULT_NOW;
72
+ }
73
+
74
+ /**
75
+ * Emits the event. `timestamp` is the clock reading the event describes,
76
+ * when the caller already took one (so a start/settled pair matches a
77
+ * recorded duration exactly); otherwise the clock is read now.
78
+ */
79
+ emit(event, timestamp) {
80
+ // an absent optional field of the event itself is omitted, never present as
81
+ // undefined; undefined values inside its data (an output that resolved to
82
+ // undefined) are kept.
83
+ const fields = Object.entries(event).filter(([, value]) => value !== undefined);
84
+ const stamped = {
85
+ ...Object.fromEntries(fields),
86
+ timestamp: timestamp ?? this.#now()
87
+ };
88
+ this.#observer(EventChannel.#snapshot(stamped, new WeakMap()));
89
+ }
90
+ }
91
+ export default EventChannel;
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
@@ -0,0 +1 @@
1
+ export {};