@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
@@ -0,0 +1,213 @@
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
+ var _apidomDatamodel = require("@speclynx/apidom-datamodel");
9
+ var _arazzoRuntimeExpression = require("@swaggerexpert/arazzo-runtime-expression");
10
+ var _jsonPointer = require("@swaggerexpert/json-pointer");
11
+ var _mediaTypes = require("@swaggerexpert/media-types");
12
+ /**
13
+ * The parts of a parsed runtime expression that name what it reads.
14
+ */
15
+
16
+ /**
17
+ * A parsed media type, lowercased by the parser.
18
+ */
19
+
20
+ /**
21
+ * Options for the Redactor.
22
+ * @public
23
+ */
24
+
25
+ /**
26
+ * Masks credentials in events before they leave the process.
27
+ *
28
+ * Events carry what the run saw, credentials included, like the request a
29
+ * request interceptor receives. Pass every event through
30
+ * {@link Redactor.event} before logging, exporting or writing it.
31
+ *
32
+ * It masks by name, whatever the event:
33
+ *
34
+ * - the value of any field whose name matches a pattern: headers, query
35
+ * parameters, body and output fields, at any depth;
36
+ * - a criterion value whose runtime expression reads a matching name, in its
37
+ * base or in any token of its JSON Pointer (`$inputs.password`,
38
+ * `$steps.login.outputs.token#/value`);
39
+ * - in every absolute URL, as `URL` parses it, the userinfo and the matching
40
+ * query and fragment parameters;
41
+ * - a request or response body that is JSON or a URL-encoded form, field by
42
+ * field, and any other body, or any object that is not plain data, whole.
43
+ *
44
+ * A credential under a name no pattern matches is carried as it is. The
45
+ * masked value is `REDACTED`.
46
+ * @public
47
+ */
48
+ class Redactor {
49
+ static CENSOR = 'REDACTED';
50
+
51
+ /**
52
+ * Elastic APM's `sanitizeFieldNames` defaults, with `*secret*` for its exact
53
+ * `secret` (which misses OAuth's `client_secret`), plus the signed-URL query
54
+ * parameters OpenTelemetry's HTTP conventions mask.
55
+ */
56
+ static defaultFields = Object.freeze(['password', 'passwd', 'pwd', '*secret*', '*key', '*token*', '*session*', '*credit*', '*card*', '*auth*', 'set-cookie', '*principal*', 'pw', 'pass', 'connect.sid', 'cookie', 'AWSAccessKeyId', 'Signature', 'sig', 'X-Goog-Signature']);
57
+ #patterns;
58
+ #matches = new Map();
59
+ constructor(options = {}) {
60
+ this.#patterns = (options.fields ?? Redactor.defaultFields).map(Redactor.#compile);
61
+ }
62
+
63
+ /**
64
+ * A masked copy of the event.
65
+ */
66
+ event(event) {
67
+ return this.#walk(event, new WeakSet());
68
+ }
69
+ #walk(value, seen) {
70
+ if (typeof value === 'string') return URL.canParse(value) ? this.#url(value) : value;
71
+ if (typeof value !== 'object' || value === null) return value;
72
+ // an ApiDOM element (a selected action) is the document's own, and a date
73
+ // holds no credential; any other object that is not plain data cannot be
74
+ // walked field by field.
75
+ if ((0, _apidomDatamodel.isElement)(value) || value instanceof Date) return value;
76
+ if (!Array.isArray(value) && !(0, _ramdaAdjunct.isPlainObject)(value)) return Redactor.CENSOR;
77
+ // only the objects on the current path: a shared, acyclic one is walked
78
+ // again where it reappears, a cycle is cut.
79
+ if (seen.has(value)) return Redactor.CENSOR;
80
+ seen.add(value);
81
+ try {
82
+ return Array.isArray(value) ? value.map(item => this.#walk(item, seen)) : this.#fields(value, seen);
83
+ } finally {
84
+ seen.delete(value);
85
+ }
86
+ }
87
+ #fields(object, seen) {
88
+ const redacted = {};
89
+ for (const [name, item] of Object.entries(object)) {
90
+ let masked;
91
+ if (this.#masks(name)) masked = Redactor.CENSOR;else if (name === 'body' && (0, _ramdaAdjunct.isPlainObject)(object.headers)) {
92
+ masked = this.#body(item, object.headers, seen);
93
+ } else masked = this.#walk(item, seen);
94
+ // defined, not assigned, so an own `__proto__` key stays data
95
+ Object.defineProperty(redacted, name, {
96
+ value: masked,
97
+ enumerable: true,
98
+ writable: true,
99
+ configurable: true
100
+ });
101
+ }
102
+ return redacted;
103
+ }
104
+
105
+ /**
106
+ * Whether a name matches a pattern. A runtime expression matches when any
107
+ * name it reads does.
108
+ */
109
+ #masks(name) {
110
+ let matches = this.#matches.get(name);
111
+ if (matches === undefined) {
112
+ const names = name.startsWith('$') ? Redactor.#namesRead(name) : [name];
113
+ matches = names.some(candidate => this.#patterns.some(pattern => pattern.test(candidate)));
114
+ this.#matches.set(name, matches);
115
+ }
116
+ return matches;
117
+ }
118
+
119
+ /**
120
+ * The absolute URL with its userinfo and matching query and fragment
121
+ * parameters masked. A URL with nothing to mask comes back exactly as it
122
+ * was, not normalized.
123
+ */
124
+ #url(value) {
125
+ const url = new URL(value);
126
+ let masked = false;
127
+ if (url.username !== '' || url.password !== '') {
128
+ url.username = Redactor.CENSOR;
129
+ url.password = Redactor.CENSOR;
130
+ masked = true;
131
+ }
132
+ const query = this.#params(url.search.slice(1));
133
+ if (query !== undefined) {
134
+ url.search = query;
135
+ masked = true;
136
+ }
137
+ const fragment = this.#params(url.hash.slice(1));
138
+ if (fragment !== undefined) {
139
+ url.hash = fragment;
140
+ masked = true;
141
+ }
142
+ return masked ? url.href : value;
143
+ }
144
+
145
+ /**
146
+ * A body masked by what its `Content-Type` says it is.
147
+ */
148
+ #body(body, headers, seen) {
149
+ if (typeof body !== 'string' || body === '') return this.#walk(body, seen);
150
+ const mediaType = Redactor.#contentType(headers);
151
+ if (mediaType?.subtype === 'json' || mediaType?.suffix === 'json') {
152
+ try {
153
+ return JSON.stringify(this.#walk(JSON.parse(body), seen));
154
+ } catch {
155
+ return Redactor.CENSOR;
156
+ }
157
+ }
158
+ if (mediaType?.type === 'application' && mediaType.subtype === 'x-www-form-urlencoded') {
159
+ return this.#params(body) ?? body;
160
+ }
161
+ return Redactor.CENSOR;
162
+ }
163
+
164
+ /**
165
+ * URL-encoded `name=value` pairs with matching values masked, or
166
+ * `undefined` when none matches, so the caller keeps the text as it was.
167
+ */
168
+ #params(text) {
169
+ let masked = false;
170
+ const params = [...new URLSearchParams(text)].map(([name, value]) => {
171
+ if (!this.#masks(name)) return [name, value];
172
+ masked = true;
173
+ return [name, Redactor.CENSOR];
174
+ });
175
+ return masked ? new URLSearchParams(params).toString() : undefined;
176
+ }
177
+ static #contentType(headers) {
178
+ const name = Object.keys(headers).find(key => key.toLowerCase() === 'content-type');
179
+ if (name === undefined) return undefined;
180
+ try {
181
+ return (0, _mediaTypes.parse)(headers[name], {
182
+ type: 'media-type'
183
+ }).tree;
184
+ } catch {
185
+ return undefined;
186
+ }
187
+ }
188
+
189
+ /**
190
+ * Every name a runtime expression reads: the header, query, path, input,
191
+ * output or component name, and each token of its JSON Pointer, e.g.
192
+ * `token` and `value` for `$steps.login.outputs.token#/value`. A string
193
+ * that does not parse as an expression is its own name.
194
+ */
195
+ static #namesRead(expression) {
196
+ let tree;
197
+ try {
198
+ tree = (0, _arazzoRuntimeExpression.parse)(expression).tree;
199
+ } catch {
200
+ return [expression];
201
+ }
202
+ if (tree === undefined) return [expression];
203
+ const reference = tree.source?.reference;
204
+ const tokens = (tree.jsonPointer ?? reference?.jsonPointer)?.referenceTokens ?? [];
205
+ const names = [reference?.token, reference?.name, tree.name, tree.outputName, tree.fieldName, tree.componentName, ...tokens.map(token => (0, _jsonPointer.unescape)(token.value))];
206
+ return names.filter(name => name !== undefined);
207
+ }
208
+ static #compile(pattern) {
209
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*');
210
+ return new RegExp(`^${escaped}$`, 'i');
211
+ }
212
+ }
213
+ var _default = exports.default = Redactor;
@@ -0,0 +1,208 @@
1
+ import { isPlainObject } from 'ramda-adjunct';
2
+ import { isElement } from '@speclynx/apidom-datamodel';
3
+ import { parse as parseExpression } from '@swaggerexpert/arazzo-runtime-expression';
4
+ import { unescape as unescapeToken } from '@swaggerexpert/json-pointer';
5
+ import { parse as parseMediaType } from '@swaggerexpert/media-types';
6
+
7
+ /**
8
+ * The parts of a parsed runtime expression that name what it reads.
9
+ */
10
+
11
+ /**
12
+ * A parsed media type, lowercased by the parser.
13
+ */
14
+
15
+ /**
16
+ * Options for the Redactor.
17
+ * @public
18
+ */
19
+
20
+ /**
21
+ * Masks credentials in events before they leave the process.
22
+ *
23
+ * Events carry what the run saw, credentials included, like the request a
24
+ * request interceptor receives. Pass every event through
25
+ * {@link Redactor.event} before logging, exporting or writing it.
26
+ *
27
+ * It masks by name, whatever the event:
28
+ *
29
+ * - the value of any field whose name matches a pattern: headers, query
30
+ * parameters, body and output fields, at any depth;
31
+ * - a criterion value whose runtime expression reads a matching name, in its
32
+ * base or in any token of its JSON Pointer (`$inputs.password`,
33
+ * `$steps.login.outputs.token#/value`);
34
+ * - in every absolute URL, as `URL` parses it, the userinfo and the matching
35
+ * query and fragment parameters;
36
+ * - a request or response body that is JSON or a URL-encoded form, field by
37
+ * field, and any other body, or any object that is not plain data, whole.
38
+ *
39
+ * A credential under a name no pattern matches is carried as it is. The
40
+ * masked value is `REDACTED`.
41
+ * @public
42
+ */
43
+ class Redactor {
44
+ static CENSOR = 'REDACTED';
45
+
46
+ /**
47
+ * Elastic APM's `sanitizeFieldNames` defaults, with `*secret*` for its exact
48
+ * `secret` (which misses OAuth's `client_secret`), plus the signed-URL query
49
+ * parameters OpenTelemetry's HTTP conventions mask.
50
+ */
51
+ static defaultFields = Object.freeze(['password', 'passwd', 'pwd', '*secret*', '*key', '*token*', '*session*', '*credit*', '*card*', '*auth*', 'set-cookie', '*principal*', 'pw', 'pass', 'connect.sid', 'cookie', 'AWSAccessKeyId', 'Signature', 'sig', 'X-Goog-Signature']);
52
+ #patterns;
53
+ #matches = new Map();
54
+ constructor(options = {}) {
55
+ this.#patterns = (options.fields ?? Redactor.defaultFields).map(Redactor.#compile);
56
+ }
57
+
58
+ /**
59
+ * A masked copy of the event.
60
+ */
61
+ event(event) {
62
+ return this.#walk(event, new WeakSet());
63
+ }
64
+ #walk(value, seen) {
65
+ if (typeof value === 'string') return URL.canParse(value) ? this.#url(value) : value;
66
+ if (typeof value !== 'object' || value === null) return value;
67
+ // an ApiDOM element (a selected action) is the document's own, and a date
68
+ // holds no credential; any other object that is not plain data cannot be
69
+ // walked field by field.
70
+ if (isElement(value) || value instanceof Date) return value;
71
+ if (!Array.isArray(value) && !isPlainObject(value)) return Redactor.CENSOR;
72
+ // only the objects on the current path: a shared, acyclic one is walked
73
+ // again where it reappears, a cycle is cut.
74
+ if (seen.has(value)) return Redactor.CENSOR;
75
+ seen.add(value);
76
+ try {
77
+ return Array.isArray(value) ? value.map(item => this.#walk(item, seen)) : this.#fields(value, seen);
78
+ } finally {
79
+ seen.delete(value);
80
+ }
81
+ }
82
+ #fields(object, seen) {
83
+ const redacted = {};
84
+ for (const [name, item] of Object.entries(object)) {
85
+ let masked;
86
+ if (this.#masks(name)) masked = Redactor.CENSOR;else if (name === 'body' && isPlainObject(object.headers)) {
87
+ masked = this.#body(item, object.headers, seen);
88
+ } else masked = this.#walk(item, seen);
89
+ // defined, not assigned, so an own `__proto__` key stays data
90
+ Object.defineProperty(redacted, name, {
91
+ value: masked,
92
+ enumerable: true,
93
+ writable: true,
94
+ configurable: true
95
+ });
96
+ }
97
+ return redacted;
98
+ }
99
+
100
+ /**
101
+ * Whether a name matches a pattern. A runtime expression matches when any
102
+ * name it reads does.
103
+ */
104
+ #masks(name) {
105
+ let matches = this.#matches.get(name);
106
+ if (matches === undefined) {
107
+ const names = name.startsWith('$') ? Redactor.#namesRead(name) : [name];
108
+ matches = names.some(candidate => this.#patterns.some(pattern => pattern.test(candidate)));
109
+ this.#matches.set(name, matches);
110
+ }
111
+ return matches;
112
+ }
113
+
114
+ /**
115
+ * The absolute URL with its userinfo and matching query and fragment
116
+ * parameters masked. A URL with nothing to mask comes back exactly as it
117
+ * was, not normalized.
118
+ */
119
+ #url(value) {
120
+ const url = new URL(value);
121
+ let masked = false;
122
+ if (url.username !== '' || url.password !== '') {
123
+ url.username = Redactor.CENSOR;
124
+ url.password = Redactor.CENSOR;
125
+ masked = true;
126
+ }
127
+ const query = this.#params(url.search.slice(1));
128
+ if (query !== undefined) {
129
+ url.search = query;
130
+ masked = true;
131
+ }
132
+ const fragment = this.#params(url.hash.slice(1));
133
+ if (fragment !== undefined) {
134
+ url.hash = fragment;
135
+ masked = true;
136
+ }
137
+ return masked ? url.href : value;
138
+ }
139
+
140
+ /**
141
+ * A body masked by what its `Content-Type` says it is.
142
+ */
143
+ #body(body, headers, seen) {
144
+ if (typeof body !== 'string' || body === '') return this.#walk(body, seen);
145
+ const mediaType = Redactor.#contentType(headers);
146
+ if (mediaType?.subtype === 'json' || mediaType?.suffix === 'json') {
147
+ try {
148
+ return JSON.stringify(this.#walk(JSON.parse(body), seen));
149
+ } catch {
150
+ return Redactor.CENSOR;
151
+ }
152
+ }
153
+ if (mediaType?.type === 'application' && mediaType.subtype === 'x-www-form-urlencoded') {
154
+ return this.#params(body) ?? body;
155
+ }
156
+ return Redactor.CENSOR;
157
+ }
158
+
159
+ /**
160
+ * URL-encoded `name=value` pairs with matching values masked, or
161
+ * `undefined` when none matches, so the caller keeps the text as it was.
162
+ */
163
+ #params(text) {
164
+ let masked = false;
165
+ const params = [...new URLSearchParams(text)].map(([name, value]) => {
166
+ if (!this.#masks(name)) return [name, value];
167
+ masked = true;
168
+ return [name, Redactor.CENSOR];
169
+ });
170
+ return masked ? new URLSearchParams(params).toString() : undefined;
171
+ }
172
+ static #contentType(headers) {
173
+ const name = Object.keys(headers).find(key => key.toLowerCase() === 'content-type');
174
+ if (name === undefined) return undefined;
175
+ try {
176
+ return parseMediaType(headers[name], {
177
+ type: 'media-type'
178
+ }).tree;
179
+ } catch {
180
+ return undefined;
181
+ }
182
+ }
183
+
184
+ /**
185
+ * Every name a runtime expression reads: the header, query, path, input,
186
+ * output or component name, and each token of its JSON Pointer, e.g.
187
+ * `token` and `value` for `$steps.login.outputs.token#/value`. A string
188
+ * that does not parse as an expression is its own name.
189
+ */
190
+ static #namesRead(expression) {
191
+ let tree;
192
+ try {
193
+ tree = parseExpression(expression).tree;
194
+ } catch {
195
+ return [expression];
196
+ }
197
+ if (tree === undefined) return [expression];
198
+ const reference = tree.source?.reference;
199
+ const tokens = (tree.jsonPointer ?? reference?.jsonPointer)?.referenceTokens ?? [];
200
+ const names = [reference?.token, reference?.name, tree.name, tree.outputName, tree.fieldName, tree.componentName, ...tokens.map(token => unescapeToken(token.value))];
201
+ return names.filter(name => name !== undefined);
202
+ }
203
+ static #compile(pattern) {
204
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*');
205
+ return new RegExp(`^${escaped}$`, 'i');
206
+ }
207
+ }
208
+ export default Redactor;
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -15,6 +15,7 @@ var _DocumentLoadError = _interopRequireDefault(require("../errors/DocumentLoadE
15
15
  var _InvalidEntryDocumentError = _interopRequireDefault(require("../errors/InvalidEntryDocumentError.cjs"));
16
16
  var _UnmatchedProviderError = _interopRequireDefault(require("../errors/UnmatchedProviderError.cjs"));
17
17
  var constants = _interopRequireWildcard(require("../constants.cjs"));
18
+ var _EventChannel = _interopRequireDefault(require("../observability/EventChannel.cjs"));
18
19
  /**
19
20
  * Options for the DocumentRegistry.
20
21
  * @public
@@ -30,9 +31,15 @@ var constants = _interopRequireWildcard(require("../constants.cjs"));
30
31
  */
31
32
  class DocumentRegistry {
32
33
  #documents = new Map();
34
+ #loading = new Map();
33
35
  #providers;
36
+ #events;
34
37
  constructor(options = {}) {
35
38
  this.#providers = options.providers ?? [new _ArazzoDocumentRegistryProvider.default(), new _OpenAPIDocumentRegistryProvider.default()];
39
+ this.#events = _EventChannel.default.open({
40
+ observer: options.observer,
41
+ now: options.now
42
+ });
36
43
  }
37
44
 
38
45
  /**
@@ -52,6 +59,10 @@ class DocumentRegistry {
52
59
  * otherwise detects the format, loads via the matching provider,
53
60
  * caches, and returns it.
54
61
  *
62
+ * Concurrent calls for a document that is still loading share that one
63
+ * load instead of each fetching and parsing it. A failed load is not
64
+ * remembered: the next call tries again.
65
+ *
55
66
  * @throws DocumentLoadError - When the document cannot be read or loaded
56
67
  * @throws UnmatchedProviderError - When no provider can load the document
57
68
  */
@@ -59,12 +70,30 @@ class DocumentRegistry {
59
70
  const canonicalURI = this.#canonicalize(uri);
60
71
  const cachedDocument = this.#get(canonicalURI);
61
72
  if (cachedDocument) return cachedDocument;
73
+ const loading = this.#loading.get(canonicalURI);
74
+ if (loading) return loading;
75
+ const load = this.#load(canonicalURI).finally(() => {
76
+ // only its own entry: after clear(), a newer load may hold the key
77
+ if (this.#loading.get(canonicalURI) === load) this.#loading.delete(canonicalURI);
78
+ });
79
+ this.#loading.set(canonicalURI, load);
80
+ return load;
81
+ }
82
+
83
+ /**
84
+ * Loads a document through the first provider that can provide it, and
85
+ * caches it.
86
+ */
87
+ async #load(canonicalURI) {
88
+ this.#events?.emit({
89
+ type: 'document-load-start',
90
+ uri: canonicalURI
91
+ });
62
92
  for (const provider of this.#providers) {
93
+ let document;
63
94
  try {
64
95
  if (await provider.canProvide(canonicalURI)) {
65
- const document = await provider.provide(canonicalURI);
66
- this.#set(canonicalURI, document);
67
- return document;
96
+ document = await provider.provide(canonicalURI);
68
97
  }
69
98
  } catch (error) {
70
99
  // a document that cannot be read or loaded fails in ApiDOM or the parser;
@@ -75,6 +104,16 @@ class DocumentRegistry {
75
104
  cause: error
76
105
  });
77
106
  }
107
+ if (document !== undefined) {
108
+ // outside the try, so an observer's own error is not a failed load, and
109
+ // before caching, so a run it aborts leaves no half-registered document.
110
+ this.#events?.emit({
111
+ type: 'document-load-settled',
112
+ uri: canonicalURI
113
+ });
114
+ this.#set(canonicalURI, document);
115
+ return document;
116
+ }
78
117
  }
79
118
  throw new _UnmatchedProviderError.default(`No provider can handle the document at "${canonicalURI}"`, {
80
119
  uri: canonicalURI
@@ -82,16 +121,17 @@ class DocumentRegistry {
82
121
  }
83
122
 
84
123
  /**
85
- * Returns an already-loaded document by URI, or undefined if not cached.
124
+ * Whether a source description of `type` can be loaded at all: some provider
125
+ * loads that type, or does not say which type it loads. A source with no
126
+ * `type` may be of any type, so it can.
86
127
  *
87
- * Synchronous counterpart to `acquire`: it never loads a document, only
88
- * returns one the registry already holds, marking it most recently used like
89
- * any other access. Consumers that must resolve a reference without awaiting
90
- * (e.g. runtime expression evaluation) use this; the executor is responsible
91
- * for having acquired the document beforehand.
128
+ * Answered from the providers alone, without fetching anything — so a
129
+ * caller can skip a load that could only fail, such as an AsyncAPI source
130
+ * while no provider loads AsyncAPI.
92
131
  */
93
- get(uri) {
94
- return this.#get(this.#canonicalize(uri));
132
+ canLoad(type) {
133
+ if (type === undefined) return true;
134
+ return this.#providers.some(provider => provider.sourceDescriptionType === undefined || provider.sourceDescriptionType === type);
95
135
  }
96
136
 
97
137
  /**
@@ -127,8 +167,14 @@ class DocumentRegistry {
127
167
  document.isEntry = true;
128
168
  return document;
129
169
  }
170
+
171
+ /**
172
+ * Drops every cached document. A load still in progress is no longer shared:
173
+ * the next `acquire` of that document starts a fresh load.
174
+ */
130
175
  clear() {
131
176
  this.#documents.clear();
177
+ this.#loading.clear();
132
178
  }
133
179
 
134
180
  /**
@@ -7,6 +7,7 @@ import DocumentLoadError from "../errors/DocumentLoadError.mjs";
7
7
  import InvalidEntryDocumentError from "../errors/InvalidEntryDocumentError.mjs";
8
8
  import UnmatchedProviderError from "../errors/UnmatchedProviderError.mjs";
9
9
  import * as constants from "../constants.mjs";
10
+ import EventChannel from "../observability/EventChannel.mjs";
10
11
  /**
11
12
  * Options for the DocumentRegistry.
12
13
  * @public
@@ -21,9 +22,15 @@ import * as constants from "../constants.mjs";
21
22
  */
22
23
  class DocumentRegistry {
23
24
  #documents = new Map();
25
+ #loading = new Map();
24
26
  #providers;
27
+ #events;
25
28
  constructor(options = {}) {
26
29
  this.#providers = options.providers ?? [new ArazzoDocumentRegistryProvider(), new OpenAPIDocumentRegistryProvider()];
30
+ this.#events = EventChannel.open({
31
+ observer: options.observer,
32
+ now: options.now
33
+ });
27
34
  }
28
35
 
29
36
  /**
@@ -43,6 +50,10 @@ class DocumentRegistry {
43
50
  * otherwise detects the format, loads via the matching provider,
44
51
  * caches, and returns it.
45
52
  *
53
+ * Concurrent calls for a document that is still loading share that one
54
+ * load instead of each fetching and parsing it. A failed load is not
55
+ * remembered: the next call tries again.
56
+ *
46
57
  * @throws DocumentLoadError - When the document cannot be read or loaded
47
58
  * @throws UnmatchedProviderError - When no provider can load the document
48
59
  */
@@ -50,12 +61,30 @@ class DocumentRegistry {
50
61
  const canonicalURI = this.#canonicalize(uri);
51
62
  const cachedDocument = this.#get(canonicalURI);
52
63
  if (cachedDocument) return cachedDocument;
64
+ const loading = this.#loading.get(canonicalURI);
65
+ if (loading) return loading;
66
+ const load = this.#load(canonicalURI).finally(() => {
67
+ // only its own entry: after clear(), a newer load may hold the key
68
+ if (this.#loading.get(canonicalURI) === load) this.#loading.delete(canonicalURI);
69
+ });
70
+ this.#loading.set(canonicalURI, load);
71
+ return load;
72
+ }
73
+
74
+ /**
75
+ * Loads a document through the first provider that can provide it, and
76
+ * caches it.
77
+ */
78
+ async #load(canonicalURI) {
79
+ this.#events?.emit({
80
+ type: 'document-load-start',
81
+ uri: canonicalURI
82
+ });
53
83
  for (const provider of this.#providers) {
84
+ let document;
54
85
  try {
55
86
  if (await provider.canProvide(canonicalURI)) {
56
- const document = await provider.provide(canonicalURI);
57
- this.#set(canonicalURI, document);
58
- return document;
87
+ document = await provider.provide(canonicalURI);
59
88
  }
60
89
  } catch (error) {
61
90
  // a document that cannot be read or loaded fails in ApiDOM or the parser;
@@ -66,6 +95,16 @@ class DocumentRegistry {
66
95
  cause: error
67
96
  });
68
97
  }
98
+ if (document !== undefined) {
99
+ // outside the try, so an observer's own error is not a failed load, and
100
+ // before caching, so a run it aborts leaves no half-registered document.
101
+ this.#events?.emit({
102
+ type: 'document-load-settled',
103
+ uri: canonicalURI
104
+ });
105
+ this.#set(canonicalURI, document);
106
+ return document;
107
+ }
69
108
  }
70
109
  throw new UnmatchedProviderError(`No provider can handle the document at "${canonicalURI}"`, {
71
110
  uri: canonicalURI
@@ -73,16 +112,17 @@ class DocumentRegistry {
73
112
  }
74
113
 
75
114
  /**
76
- * Returns an already-loaded document by URI, or undefined if not cached.
115
+ * Whether a source description of `type` can be loaded at all: some provider
116
+ * loads that type, or does not say which type it loads. A source with no
117
+ * `type` may be of any type, so it can.
77
118
  *
78
- * Synchronous counterpart to `acquire`: it never loads a document, only
79
- * returns one the registry already holds, marking it most recently used like
80
- * any other access. Consumers that must resolve a reference without awaiting
81
- * (e.g. runtime expression evaluation) use this; the executor is responsible
82
- * for having acquired the document beforehand.
119
+ * Answered from the providers alone, without fetching anything — so a
120
+ * caller can skip a load that could only fail, such as an AsyncAPI source
121
+ * while no provider loads AsyncAPI.
83
122
  */
84
- get(uri) {
85
- return this.#get(this.#canonicalize(uri));
123
+ canLoad(type) {
124
+ if (type === undefined) return true;
125
+ return this.#providers.some(provider => provider.sourceDescriptionType === undefined || provider.sourceDescriptionType === type);
86
126
  }
87
127
 
88
128
  /**
@@ -118,8 +158,14 @@ class DocumentRegistry {
118
158
  document.isEntry = true;
119
159
  return document;
120
160
  }
161
+
162
+ /**
163
+ * Drops every cached document. A load still in progress is no longer shared:
164
+ * the next `acquire` of that document starts a fresh load.
165
+ */
121
166
  clear() {
122
167
  this.#documents.clear();
168
+ this.#loading.clear();
123
169
  }
124
170
 
125
171
  /**