@scalar/asyncapi-upgrader 0.1.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,10 @@
1
+ # @scalar/asyncapi-upgrader
2
+
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#9303](https://github.com/scalar/scalar/pull/9303): feat: add `@scalar/asyncapi-upgrader` to bump AsyncAPI documents to the latest version
8
+ - [#9356](https://github.com/scalar/scalar/pull/9356): feat: actually upgrade AsyncAPI 1.x documents to 2.x (servers, channels, parameters, stream, events) instead of only bumping the version string
9
+ - [#9357](https://github.com/scalar/scalar/pull/9357): feat: actually upgrade AsyncAPI 2.x documents to 3.0 (servers, channels, operations, security/OAuth) instead of only bumping the version string
10
+ - [#9358](https://github.com/scalar/scalar/pull/9358): feat: rewrite operation `messages` $refs from `#/components/messages/X` to `#/channels/{id}/messages/X` on 3.0 → 3.1 upgrade (the channel-scoped form 3.1 clarified as required)
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023-present Scalar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,31 @@
1
+ <!--
2
+ This file is auto-generated by the Scalar README generator.
3
+ Command: pnpm --filter @scalar-internal/build-scripts start generate-readme
4
+
5
+ Do not edit this file manually. Changes will be lost when the file is regenerated.
6
+ -->
7
+
8
+ # Scalar AsyncAPI Upgrader
9
+
10
+ [![Version](https://img.shields.io/npm/v/@scalar/asyncapi-upgrader)](https://www.npmjs.com/package/@scalar/asyncapi-upgrader)
11
+ [![Downloads](https://img.shields.io/npm/dm/@scalar/asyncapi-upgrader)](https://www.npmjs.com/package/@scalar/asyncapi-upgrader)
12
+ [![License](https://img.shields.io/npm/l/@scalar/asyncapi-upgrader)](https://www.npmjs.com/package/@scalar/asyncapi-upgrader)
13
+ [![Discord](https://img.shields.io/discord/1135330207960678410?style=flat&color=5865F2)](https://discord.gg/scalar)
14
+
15
+ Upgrade AsyncAPI documents to the latest and greatest version
16
+
17
+ ## Documentation
18
+
19
+ [Read the documentation here](https://scalar.com/tools/asyncapi-upgrader/getting-started)
20
+
21
+ ## Changelog
22
+
23
+ See [CHANGELOG.md](https://github.com/scalar/scalar/blob/main/packages/asyncapi-upgrader/CHANGELOG.md) for a list of changes.
24
+
25
+ ## Community
26
+
27
+ We are API nerds. You too? Let’s chat on Discord: <https://discord.gg/scalar>
28
+
29
+ ## License
30
+
31
+ The source code in this repository is licensed under [MIT](https://github.com/scalar/scalar/blob/main/LICENSE).
@@ -0,0 +1,2 @@
1
+ export { upgradeFromOneToTwo } from './upgrade-from-one-to-two.js';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/1.2-to-2.6/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAA"}
@@ -0,0 +1 @@
1
+ export { upgradeFromOneToTwo } from './upgrade-from-one-to-two.js';
@@ -0,0 +1,9 @@
1
+ import type { UnknownObject } from '@scalar/types/utils';
2
+ /**
3
+ * Upgrade an AsyncAPI 1.x document to 2.6.0.
4
+ *
5
+ * Each transformation is the smallest change needed to bring the 1.x shape in line with 2.x.
6
+ * See `upgrade-from-one-to-two.test.ts` for the source of truth — every rule is one test.
7
+ */
8
+ export declare function upgradeFromOneToTwo(originalDocument: UnknownObject): UnknownObject;
9
+ //# sourceMappingURL=upgrade-from-one-to-two.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upgrade-from-one-to-two.d.ts","sourceRoot":"","sources":["../../src/1.2-to-2.6/upgrade-from-one-to-two.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAQxD;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,gBAAgB,EAAE,aAAa,GAAG,aAAa,CAclF"}
@@ -0,0 +1,166 @@
1
+ import { isObject } from '@scalar/helpers/object/is-object';
2
+ import { slugify } from '@scalar/helpers/string/slugify';
3
+ /** The AsyncAPI version produced by this upgrade step. */
4
+ const ASYNCAPI_VERSION = '2.6.0';
5
+ /** The synthetic channel name used when consolidating a 1.x `stream` or `events` object. */
6
+ const ROOT_CHANNEL = '/';
7
+ /**
8
+ * Upgrade an AsyncAPI 1.x document to 2.6.0.
9
+ *
10
+ * Each transformation is the smallest change needed to bring the 1.x shape in line with 2.x.
11
+ * See `upgrade-from-one-to-two.test.ts` for the source of truth — every rule is one test.
12
+ */
13
+ export function upgradeFromOneToTwo(originalDocument) {
14
+ const document = originalDocument;
15
+ if (!isObject(document) || typeof document.asyncapi !== 'string' || !document.asyncapi.startsWith('1.')) {
16
+ return document;
17
+ }
18
+ document.asyncapi = ASYNCAPI_VERSION;
19
+ upgradeServers(document);
20
+ upgradeChannels(document);
21
+ upgradeStream(document);
22
+ upgradeEvents(document);
23
+ return document;
24
+ }
25
+ /** Servers: array of { url, scheme, schemeVersion, ... } → map { key: { url, protocol, protocolVersion, ... } }. */
26
+ function upgradeServers(document) {
27
+ if (!Array.isArray(document.servers)) {
28
+ return;
29
+ }
30
+ const result = {};
31
+ const usedKeys = new Set();
32
+ for (const [index, server] of document.servers.entries()) {
33
+ if (!isObject(server)) {
34
+ continue;
35
+ }
36
+ const upgraded = {};
37
+ for (const [field, value] of Object.entries(server)) {
38
+ if (field === 'scheme') {
39
+ upgraded.protocol = value;
40
+ }
41
+ else if (field === 'schemeVersion') {
42
+ upgraded.protocolVersion = value;
43
+ }
44
+ else {
45
+ upgraded[field] = value;
46
+ }
47
+ }
48
+ const key = uniqueServerKey(typeof server.description === 'string' ? server.description : '', index, usedKeys);
49
+ usedKeys.add(key);
50
+ result[key] = upgraded;
51
+ }
52
+ document.servers = result;
53
+ }
54
+ /** Slugify a description; fall back to `server-{index}`; dedupe collisions with `-2`, `-3`, … */
55
+ function uniqueServerKey(description, index, usedKeys) {
56
+ const base = slugify(description) || `server-${index}`;
57
+ if (!usedKeys.has(base)) {
58
+ return base;
59
+ }
60
+ let suffix = 2;
61
+ while (usedKeys.has(`${base}-${suffix}`)) {
62
+ suffix += 1;
63
+ }
64
+ return `${base}-${suffix}`;
65
+ }
66
+ /** topics → channels, with operation/parameter shape changes and `baseTopic` prepending. */
67
+ function upgradeChannels(document) {
68
+ if (!isObject(document.topics)) {
69
+ if (typeof document.baseTopic === 'string') {
70
+ delete document.baseTopic;
71
+ }
72
+ return;
73
+ }
74
+ const baseTopic = typeof document.baseTopic === 'string' ? document.baseTopic : '';
75
+ const channels = {};
76
+ for (const [topic, item] of Object.entries(document.topics)) {
77
+ if (!isObject(item)) {
78
+ continue;
79
+ }
80
+ const channelName = baseTopic ? `${baseTopic}.${topic}` : topic;
81
+ const channel = {};
82
+ for (const [field, value] of Object.entries(item)) {
83
+ if (field === 'parameters') {
84
+ const parameters = upgradeChannelParameters(value);
85
+ if (parameters) {
86
+ channel.parameters = parameters;
87
+ }
88
+ }
89
+ else if (field === 'publish' || field === 'subscribe') {
90
+ channel[field] = { message: value };
91
+ }
92
+ else {
93
+ channel[field] = value;
94
+ }
95
+ }
96
+ channels[channelName] = channel;
97
+ }
98
+ document.channels = channels;
99
+ delete document.topics;
100
+ delete document.baseTopic;
101
+ }
102
+ /** `parameters: [{ name, ... }]` → `parameters: { name: { ... } }`. Also handles `$ref` items. */
103
+ function upgradeChannelParameters(parameters) {
104
+ if (!Array.isArray(parameters)) {
105
+ return undefined;
106
+ }
107
+ const result = {};
108
+ for (const parameter of parameters) {
109
+ if (!isObject(parameter)) {
110
+ continue;
111
+ }
112
+ if (typeof parameter.$ref === 'string') {
113
+ const key = parameter.$ref.split('/').pop() ?? '';
114
+ if (key) {
115
+ result[key] = { $ref: parameter.$ref };
116
+ }
117
+ continue;
118
+ }
119
+ if (typeof parameter.name !== 'string') {
120
+ continue;
121
+ }
122
+ const { name, ...rest } = parameter;
123
+ result[name] = rest;
124
+ }
125
+ return result;
126
+ }
127
+ /**
128
+ * `stream: { framing, read, write }` → `channels['/']` with subscribe/publish. Framing is dropped.
129
+ *
130
+ * AsyncAPI 1.x makes `topics`, `stream`, and `events` mutually exclusive at the document root, so a
131
+ * collision on the `/` channel between this transform, `upgradeEvents`, and any user-defined topic
132
+ * cannot happen in valid input.
133
+ */
134
+ function upgradeStream(document) {
135
+ if (!isObject(document.stream)) {
136
+ return;
137
+ }
138
+ const channel = {};
139
+ if (Array.isArray(document.stream.read)) {
140
+ channel.subscribe = { message: { oneOf: document.stream.read } };
141
+ }
142
+ if (Array.isArray(document.stream.write)) {
143
+ channel.publish = { message: { oneOf: document.stream.write } };
144
+ }
145
+ const channels = isObject(document.channels) ? document.channels : {};
146
+ channels[ROOT_CHANNEL] = channel;
147
+ document.channels = channels;
148
+ delete document.stream;
149
+ }
150
+ /** `events: { receive, send }` → `channels['/']` with subscribe/publish. */
151
+ function upgradeEvents(document) {
152
+ if (!isObject(document.events)) {
153
+ return;
154
+ }
155
+ const channel = {};
156
+ if (Array.isArray(document.events.receive)) {
157
+ channel.subscribe = { message: { oneOf: document.events.receive } };
158
+ }
159
+ if (Array.isArray(document.events.send)) {
160
+ channel.publish = { message: { oneOf: document.events.send } };
161
+ }
162
+ const channels = isObject(document.channels) ? document.channels : {};
163
+ channels[ROOT_CHANNEL] = channel;
164
+ document.channels = channels;
165
+ delete document.events;
166
+ }
@@ -0,0 +1,2 @@
1
+ export { upgradeFromTwoToThree } from './upgrade-from-two-to-three.js';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/2.6-to-3.0/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAA"}
@@ -0,0 +1 @@
1
+ export { upgradeFromTwoToThree } from './upgrade-from-two-to-three.js';
@@ -0,0 +1,9 @@
1
+ import type { UnknownObject } from '@scalar/types/utils';
2
+ /**
3
+ * Upgrade an AsyncAPI 2.x document to 3.0.0.
4
+ *
5
+ * Each transformation is the smallest change needed to bring the 2.x shape in line with 3.0.
6
+ * See `upgrade-from-two-to-three.test.ts` for the source of truth — every rule is one test.
7
+ */
8
+ export declare function upgradeFromTwoToThree(originalDocument: UnknownObject): UnknownObject;
9
+ //# sourceMappingURL=upgrade-from-two-to-three.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upgrade-from-two-to-three.d.ts","sourceRoot":"","sources":["../../src/2.6-to-3.0/upgrade-from-two-to-three.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAKxD;;;;;GAKG;AACH,wBAAgB,qBAAqB,CAAC,gBAAgB,EAAE,aAAa,GAAG,aAAa,CAepF"}
@@ -0,0 +1,269 @@
1
+ import { isObject } from '@scalar/helpers/object/is-object';
2
+ import { slugify } from '@scalar/helpers/string/slugify';
3
+ /** The AsyncAPI version produced by this upgrade step. */
4
+ const ASYNCAPI_VERSION = '3.0.0';
5
+ /**
6
+ * Upgrade an AsyncAPI 2.x document to 3.0.0.
7
+ *
8
+ * Each transformation is the smallest change needed to bring the 2.x shape in line with 3.0.
9
+ * See `upgrade-from-two-to-three.test.ts` for the source of truth — every rule is one test.
10
+ */
11
+ export function upgradeFromTwoToThree(originalDocument) {
12
+ const document = originalDocument;
13
+ if (!isObject(document) || typeof document.asyncapi !== 'string' || !document.asyncapi.startsWith('2.')) {
14
+ return document;
15
+ }
16
+ document.asyncapi = ASYNCAPI_VERSION;
17
+ // OAuth flows must be rewritten before security requirements consult them.
18
+ upgradeComponentOAuthScopes(document);
19
+ upgradeServers(document);
20
+ upgradeChannelsAndOperations(document);
21
+ return document;
22
+ }
23
+ // ---------------------------------------------------------------------------
24
+ // Servers
25
+ // ---------------------------------------------------------------------------
26
+ /**
27
+ * Servers: `url` becomes `host` (+ optional `pathname` when the URL contains a path).
28
+ * `security` entries become either `$ref` (non-OAuth) or inline scheme + scopes array (OAuth).
29
+ */
30
+ function upgradeServers(document) {
31
+ if (!isObject(document.servers)) {
32
+ return;
33
+ }
34
+ const securitySchemes = getSecuritySchemes(document);
35
+ for (const server of Object.values(document.servers)) {
36
+ if (!isObject(server)) {
37
+ continue;
38
+ }
39
+ if (typeof server.url === 'string') {
40
+ const { host, pathname } = splitUrl(server.url);
41
+ server.host = host;
42
+ if (pathname) {
43
+ server.pathname = pathname;
44
+ }
45
+ delete server.url;
46
+ }
47
+ if (Array.isArray(server.security)) {
48
+ server.security = upgradeSecurity(server.security, securitySchemes);
49
+ }
50
+ }
51
+ }
52
+ /**
53
+ * Splits a 2.x server URL into a 3.0 `host` (hostname plus optional port) and `pathname`.
54
+ *
55
+ * The scheme is dropped because AsyncAPI 3.0 carries the protocol exclusively in the `protocol`
56
+ * field — keeping it on `host` would duplicate that information and violate the spec.
57
+ */
58
+ function splitUrl(url) {
59
+ const schemeMatch = url.match(/^[a-zA-Z][a-zA-Z0-9+\-.]*:\/\/(.*)$/);
60
+ const rest = schemeMatch ? schemeMatch[1] : url;
61
+ const slashIndex = rest.indexOf('/');
62
+ if (slashIndex === -1) {
63
+ return { host: rest, pathname: '' };
64
+ }
65
+ return { host: rest.slice(0, slashIndex), pathname: rest.slice(slashIndex) };
66
+ }
67
+ /** Maps every 2.x security requirement to its 3.0 form (`$ref` or inline OAuth + `scopes`). */
68
+ function upgradeSecurity(security, securitySchemes) {
69
+ return security
70
+ .map((requirement) => upgradeSecurityRequirement(requirement, securitySchemes))
71
+ .filter((entry) => entry !== undefined);
72
+ }
73
+ /**
74
+ * Rewrites one 2.x security requirement object into its 3.0 form. 2.x security requirement objects
75
+ * have exactly one key (the scheme name) and an array of scope names — we read that single entry.
76
+ */
77
+ function upgradeSecurityRequirement(requirement, securitySchemes) {
78
+ if (!isObject(requirement)) {
79
+ return undefined;
80
+ }
81
+ const [entry] = Object.entries(requirement);
82
+ if (!entry) {
83
+ return undefined;
84
+ }
85
+ const [name, scopes] = entry;
86
+ const scheme = securitySchemes[name];
87
+ if (isObject(scheme) && scheme.type === 'oauth2' && Array.isArray(scopes)) {
88
+ return { ...scheme, scopes };
89
+ }
90
+ return { $ref: `#/components/securitySchemes/${name}` };
91
+ }
92
+ function getSecuritySchemes(document) {
93
+ if (!isObject(document.components) || !isObject(document.components.securitySchemes)) {
94
+ return {};
95
+ }
96
+ const schemes = {};
97
+ for (const [name, value] of Object.entries(document.components.securitySchemes)) {
98
+ if (isObject(value)) {
99
+ schemes[name] = value;
100
+ }
101
+ }
102
+ return schemes;
103
+ }
104
+ // ---------------------------------------------------------------------------
105
+ // OAuth scopes → availableScopes (in components.securitySchemes)
106
+ // ---------------------------------------------------------------------------
107
+ /** Renames `scopes` → `availableScopes` on every flow of every OAuth scheme in components. */
108
+ function upgradeComponentOAuthScopes(document) {
109
+ if (!isObject(document.components) || !isObject(document.components.securitySchemes)) {
110
+ return;
111
+ }
112
+ for (const scheme of Object.values(document.components.securitySchemes)) {
113
+ if (!isObject(scheme) || scheme.type !== 'oauth2' || !isObject(scheme.flows)) {
114
+ continue;
115
+ }
116
+ for (const flow of Object.values(scheme.flows)) {
117
+ if (isObject(flow) && 'scopes' in flow) {
118
+ flow.availableScopes = flow.scopes;
119
+ delete flow.scopes;
120
+ }
121
+ }
122
+ }
123
+ }
124
+ // ---------------------------------------------------------------------------
125
+ // Channels & operations
126
+ // ---------------------------------------------------------------------------
127
+ /**
128
+ * Channels become identifier-keyed with an `address` field. Each `publish`/`subscribe` operation is
129
+ * lifted to the top-level `operations` map with `action: 'receive' | 'send'`, and its message(s)
130
+ * move into `channel.messages` (keyed by message id derived from the `$ref` or `name`).
131
+ *
132
+ * The 2.x `publish` semantics — the application receives the message — maps to 3.0 `action: 'receive'`.
133
+ * The 2.x `subscribe` semantics — the application sends the message — maps to 3.0 `action: 'send'`.
134
+ */
135
+ function upgradeChannelsAndOperations(document) {
136
+ if (!isObject(document.channels)) {
137
+ return;
138
+ }
139
+ const securitySchemes = getSecuritySchemes(document);
140
+ const channels = {};
141
+ const operations = {};
142
+ const usedChannelIds = new Set();
143
+ const usedOperationKeys = new Set();
144
+ for (const [path, channel] of Object.entries(document.channels)) {
145
+ if (!isObject(channel)) {
146
+ continue;
147
+ }
148
+ const channelId = uniqueKey(slugifyChannelPath(path), usedChannelIds);
149
+ const newChannel = { address: path };
150
+ const messages = {};
151
+ for (const [field, value] of Object.entries(channel)) {
152
+ if (field === 'publish' || field === 'subscribe' || field === 'parameters') {
153
+ continue;
154
+ }
155
+ if (field === 'servers' && Array.isArray(value)) {
156
+ newChannel.servers = value.map((name) => ({ $ref: `#/servers/${name}` }));
157
+ continue;
158
+ }
159
+ newChannel[field] = value;
160
+ }
161
+ if (isObject(channel.parameters)) {
162
+ newChannel.parameters = channel.parameters;
163
+ }
164
+ const publishMessages = collectMessages(channel.publish, messages);
165
+ const subscribeMessages = collectMessages(channel.subscribe, messages);
166
+ newChannel.messages = messages;
167
+ channels[channelId] = newChannel;
168
+ if (isObject(channel.publish)) {
169
+ const opKey = uniqueKey(operationKey(channel.publish, 'receive', channelId), usedOperationKeys);
170
+ operations[opKey] = buildOperation(channel.publish, 'receive', channelId, publishMessages, securitySchemes);
171
+ }
172
+ if (isObject(channel.subscribe)) {
173
+ const opKey = uniqueKey(operationKey(channel.subscribe, 'send', channelId), usedOperationKeys);
174
+ operations[opKey] = buildOperation(channel.subscribe, 'send', channelId, subscribeMessages, securitySchemes);
175
+ }
176
+ }
177
+ document.channels = channels;
178
+ document.operations = operations;
179
+ }
180
+ /**
181
+ * Extracts each message reference from a 2.x operation's `message` field (single or `oneOf`) into
182
+ * the channel-level `messages` map; returns the message ids in order for use in `operation.messages`.
183
+ */
184
+ function collectMessages(operation, channelMessages) {
185
+ if (!isObject(operation) || !isObject(operation.message)) {
186
+ return [];
187
+ }
188
+ const message = operation.message;
189
+ const items = Array.isArray(message.oneOf) ? message.oneOf : [message];
190
+ const ids = [];
191
+ for (const item of items) {
192
+ if (!isObject(item)) {
193
+ continue;
194
+ }
195
+ const id = messageId(item, channelMessages);
196
+ channelMessages[id] = item;
197
+ ids.push(id);
198
+ }
199
+ return ids;
200
+ }
201
+ /**
202
+ * Derives a channel-message map key from a message: last `$ref` segment, `name`, or a generated
203
+ * `message-N`. The generated fallback is checked against the keys already present in the shared
204
+ * channel-message map so that anonymous inline messages from `publish` and `subscribe` do not
205
+ * collide on `message-0` and overwrite each other.
206
+ */
207
+ function messageId(message, existingMessages) {
208
+ if (typeof message.$ref === 'string') {
209
+ const last = message.$ref.split('/').pop();
210
+ if (last) {
211
+ return last;
212
+ }
213
+ }
214
+ if (typeof message.name === 'string' && message.name) {
215
+ return message.name;
216
+ }
217
+ let index = 0;
218
+ while (`message-${index}` in existingMessages) {
219
+ index += 1;
220
+ }
221
+ return `message-${index}`;
222
+ }
223
+ /** Reuses 2.x `operationId` when present; otherwise generates `${action}-${channelId}`. */
224
+ function operationKey(operation, action, channelId) {
225
+ if (typeof operation.operationId === 'string' && operation.operationId) {
226
+ return operation.operationId;
227
+ }
228
+ return `${action}-${channelId}`;
229
+ }
230
+ /** Assembles the 3.0 Operation Object from the 2.x publish/subscribe shape. */
231
+ function buildOperation(operation, action, channelId, messageIds, securitySchemes) {
232
+ const result = { action, channel: { $ref: `#/channels/${channelId}` } };
233
+ for (const [field, value] of Object.entries(operation)) {
234
+ if (field === 'message' || field === 'operationId') {
235
+ continue;
236
+ }
237
+ if (field === 'security' && Array.isArray(value)) {
238
+ result.security = upgradeSecurity(value, securitySchemes);
239
+ continue;
240
+ }
241
+ result[field] = value;
242
+ }
243
+ result.messages = messageIds.map((id) => ({ $ref: `#/channels/${channelId}/messages/${id}` }));
244
+ return result;
245
+ }
246
+ /**
247
+ * Slugify a channel path (e.g. `user/{id}/signedup` → `user-id-signedup`).
248
+ *
249
+ * `@scalar/helpers/string/slugify` drops non-word characters outright, but channel paths use `/`,
250
+ * `.`, `{`, and `}` as logical separators we want preserved as hyphens — so we pre-replace any run
251
+ * of non-alphanumerics with a space and let the shared slugify collapse those into hyphens.
252
+ */
253
+ function slugifyChannelPath(value) {
254
+ return slugify(value.replace(/[^a-zA-Z0-9]+/g, ' '));
255
+ }
256
+ /** Returns the base key if unused, otherwise appends `-2`, `-3`, … until unique. Mutates `usedKeys`. */
257
+ function uniqueKey(base, usedKeys) {
258
+ if (!usedKeys.has(base)) {
259
+ usedKeys.add(base);
260
+ return base;
261
+ }
262
+ let suffix = 2;
263
+ while (usedKeys.has(`${base}-${suffix}`)) {
264
+ suffix += 1;
265
+ }
266
+ const key = `${base}-${suffix}`;
267
+ usedKeys.add(key);
268
+ return key;
269
+ }
@@ -0,0 +1,2 @@
1
+ export { upgradeFromThreeToThreeOne } from './upgrade-from-three-to-three-one.js';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/3.0-to-3.1/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,MAAM,mCAAmC,CAAA"}
@@ -0,0 +1 @@
1
+ export { upgradeFromThreeToThreeOne } from './upgrade-from-three-to-three-one.js';
@@ -0,0 +1,12 @@
1
+ import type { UnknownObject } from '@scalar/types/utils';
2
+ /**
3
+ * Upgrade an AsyncAPI 3.0 document to 3.1.0.
4
+ *
5
+ * 3.1 is a clarification release — the only real schema rule it tightens is that operation
6
+ * `messages` $refs MUST use the channel-scoped form (`#/channels/{id}/messages/{name}`). The 3.0
7
+ * spec's own examples used the components-scoped form, so many real-world 3.0 documents do too.
8
+ * We canonicalize on upgrade and pull the referenced message into the channel's `messages` map if
9
+ * it isn't already there.
10
+ */
11
+ export declare function upgradeFromThreeToThreeOne(originalDocument: UnknownObject): UnknownObject;
12
+ //# sourceMappingURL=upgrade-from-three-to-three-one.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upgrade-from-three-to-three-one.d.ts","sourceRoot":"","sources":["../../src/3.0-to-3.1/upgrade-from-three-to-three-one.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAOxD;;;;;;;;GAQG;AACH,wBAAgB,0BAA0B,CAAC,gBAAgB,EAAE,aAAa,GAAG,aAAa,CAWzF"}
@@ -0,0 +1,108 @@
1
+ import { isObject } from '@scalar/helpers/object/is-object';
2
+ /** The AsyncAPI version produced by this upgrade step. */
3
+ const ASYNCAPI_VERSION = '3.1.0';
4
+ const COMPONENT_MESSAGE_REF = /^#\/components\/messages\/(.+)$/;
5
+ /**
6
+ * Upgrade an AsyncAPI 3.0 document to 3.1.0.
7
+ *
8
+ * 3.1 is a clarification release — the only real schema rule it tightens is that operation
9
+ * `messages` $refs MUST use the channel-scoped form (`#/channels/{id}/messages/{name}`). The 3.0
10
+ * spec's own examples used the components-scoped form, so many real-world 3.0 documents do too.
11
+ * We canonicalize on upgrade and pull the referenced message into the channel's `messages` map if
12
+ * it isn't already there.
13
+ */
14
+ export function upgradeFromThreeToThreeOne(originalDocument) {
15
+ const document = originalDocument;
16
+ if (!isObject(document) || typeof document.asyncapi !== 'string' || !document.asyncapi.startsWith('3.0')) {
17
+ return document;
18
+ }
19
+ document.asyncapi = ASYNCAPI_VERSION;
20
+ rewriteOperationMessageRefs(document);
21
+ return document;
22
+ }
23
+ /**
24
+ * For every operation with a channel `$ref`, rewrite any `#/components/messages/{name}` entry in
25
+ * its `messages` (and `reply.messages`) to `#/channels/{channelId}/messages/{name}`, registering
26
+ * the message on the channel if needed.
27
+ */
28
+ function rewriteOperationMessageRefs(document) {
29
+ if (!isObject(document.operations) || !isObject(document.channels)) {
30
+ return;
31
+ }
32
+ const channels = document.channels;
33
+ for (const operation of Object.values(document.operations)) {
34
+ if (!isObject(operation)) {
35
+ continue;
36
+ }
37
+ rewriteMessageList(operation.messages, operation.channel, channels);
38
+ if (isObject(operation.reply)) {
39
+ // Reply's `channel` is optional in 3.0 — when omitted, the reply runs on the parent
40
+ // operation's channel.
41
+ rewriteMessageList(operation.reply.messages, operation.reply.channel ?? operation.channel, channels);
42
+ }
43
+ }
44
+ }
45
+ /**
46
+ * Rewrites every `#/components/messages/{name}` entry in `messageList` in-place, given the channel
47
+ * reference that the surrounding operation/reply points at.
48
+ */
49
+ function rewriteMessageList(messageList, channelRef, channels) {
50
+ if (!Array.isArray(messageList)) {
51
+ return;
52
+ }
53
+ const channelId = extractChannelId(channelRef);
54
+ if (!channelId) {
55
+ return;
56
+ }
57
+ const channel = channels[channelId];
58
+ if (!isObject(channel)) {
59
+ return;
60
+ }
61
+ for (let i = 0; i < messageList.length; i += 1) {
62
+ const entry = messageList[i];
63
+ if (!isObject(entry) || typeof entry.$ref !== 'string') {
64
+ continue;
65
+ }
66
+ const [, messageName] = entry.$ref.match(COMPONENT_MESSAGE_REF) ?? [];
67
+ if (!messageName) {
68
+ continue;
69
+ }
70
+ registerChannelMessage(channel, messageName, entry.$ref);
71
+ messageList[i] = { $ref: `#/channels/${channelId}/messages/${messageName}` };
72
+ }
73
+ dedupeRefs(messageList);
74
+ }
75
+ /** Removes duplicate `{ $ref: 'X' }` entries (keeps the first occurrence). Mutates `list`. */
76
+ function dedupeRefs(list) {
77
+ const seen = new Set();
78
+ let writeIndex = 0;
79
+ for (const entry of list) {
80
+ if (isObject(entry) && typeof entry.$ref === 'string') {
81
+ if (seen.has(entry.$ref)) {
82
+ continue;
83
+ }
84
+ seen.add(entry.$ref);
85
+ }
86
+ list[writeIndex] = entry;
87
+ writeIndex += 1;
88
+ }
89
+ list.length = writeIndex;
90
+ }
91
+ /** Returns the channel id from a `{ $ref: '#/channels/{id}' }` value, or `undefined` for anything else. */
92
+ function extractChannelId(channelRef) {
93
+ if (!isObject(channelRef) || typeof channelRef.$ref !== 'string') {
94
+ return undefined;
95
+ }
96
+ const match = channelRef.$ref.match(/^#\/channels\/([^/]+)$/);
97
+ return match ? match[1] : undefined;
98
+ }
99
+ /** Ensures `channel.messages[name]` exists, defaulting to a `$ref` pointing at the original component message. */
100
+ function registerChannelMessage(channel, name, componentRef) {
101
+ if (!isObject(channel.messages)) {
102
+ channel.messages = {};
103
+ }
104
+ const messages = channel.messages;
105
+ if (!(name in messages)) {
106
+ messages[name] = { $ref: componentRef };
107
+ }
108
+ }
@@ -0,0 +1,2 @@
1
+ export { upgrade } from './upgrade.js';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { upgrade } from './upgrade.js';
@@ -0,0 +1,10 @@
1
+ import type { UnknownObject } from '@scalar/types/utils';
2
+ /**
3
+ * Upgrade an AsyncAPI document to the latest version.
4
+ *
5
+ * Each step only bumps the `asyncapi` version string for now — no structural
6
+ * transformations are applied yet. The version-specific upgraders exist so the
7
+ * real migration logic can be filled in later, mirroring `@scalar/openapi-upgrader`.
8
+ */
9
+ export declare function upgrade(value: UnknownObject): UnknownObject;
10
+ //# sourceMappingURL=upgrade.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upgrade.d.ts","sourceRoot":"","sources":["../src/upgrade.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAMxD;;;;;;GAMG;AACH,wBAAgB,OAAO,CAAC,KAAK,EAAE,aAAa,GAAG,aAAa,CAS3D"}
@@ -0,0 +1,18 @@
1
+ import { upgradeFromOneToTwo } from './1.2-to-2.6/index.js';
2
+ import { upgradeFromTwoToThree } from './2.6-to-3.0/index.js';
3
+ import { upgradeFromThreeToThreeOne } from './3.0-to-3.1/index.js';
4
+ /**
5
+ * Upgrade an AsyncAPI document to the latest version.
6
+ *
7
+ * Each step only bumps the `asyncapi` version string for now — no structural
8
+ * transformations are applied yet. The version-specific upgraders exist so the
9
+ * real migration logic can be filled in later, mirroring `@scalar/openapi-upgrader`.
10
+ */
11
+ export function upgrade(value) {
12
+ // AsyncAPI 1.x -> 2.6
13
+ const asyncapi26 = upgradeFromOneToTwo(value);
14
+ // AsyncAPI 2.x -> 3.0
15
+ const asyncapi30 = upgradeFromTwoToThree(asyncapi26);
16
+ // AsyncAPI 3.0 -> 3.1
17
+ return upgradeFromThreeToThreeOne(asyncapi30);
18
+ }
package/package.json ADDED
@@ -0,0 +1,85 @@
1
+ {
2
+ "name": "@scalar/asyncapi-upgrader",
3
+ "description": "Upgrade AsyncAPI documents to the latest and greatest version",
4
+ "license": "MIT",
5
+ "author": "Scalar (https://github.com/scalar)",
6
+ "homepage": "https://github.com/scalar/scalar",
7
+ "bugs": "https://github.com/scalar/scalar/issues/new/choose",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/scalar/scalar.git",
11
+ "directory": "packages/asyncapi-upgrader"
12
+ },
13
+ "keywords": [
14
+ "asyncapi",
15
+ "scalar",
16
+ "parser",
17
+ "typescript",
18
+ "upgrade",
19
+ "asyncapi 2.6",
20
+ "asyncapi 3.0",
21
+ "asyncapi 3.1"
22
+ ],
23
+ "version": "0.1.0",
24
+ "engines": {
25
+ "node": ">=22"
26
+ },
27
+ "type": "module",
28
+ "main": "./dist/index.js",
29
+ "module": "./dist/index.js",
30
+ "types": "./dist/index.d.ts",
31
+ "exports": {
32
+ ".": {
33
+ "import": "./dist/index.js",
34
+ "types": "./dist/index.d.ts",
35
+ "default": "./dist/index.js"
36
+ },
37
+ "./1.2-to-2.6": {
38
+ "import": "./dist/1.2-to-2.6/index.js",
39
+ "types": "./dist/1.2-to-2.6/index.d.ts",
40
+ "default": "./dist/1.2-to-2.6/index.js"
41
+ },
42
+ "./2.6-to-3.0": {
43
+ "import": "./dist/2.6-to-3.0/index.js",
44
+ "types": "./dist/2.6-to-3.0/index.d.ts",
45
+ "default": "./dist/2.6-to-3.0/index.js"
46
+ },
47
+ "./3.0-to-3.1": {
48
+ "import": "./dist/3.0-to-3.1/index.js",
49
+ "types": "./dist/3.0-to-3.1/index.d.ts",
50
+ "default": "./dist/3.0-to-3.1/index.js"
51
+ }
52
+ },
53
+ "files": [
54
+ "dist",
55
+ "CHANGELOG.md"
56
+ ],
57
+ "readme": {
58
+ "title": "Scalar AsyncAPI Upgrader",
59
+ "badges": [
60
+ {
61
+ "type": "npm-version"
62
+ },
63
+ {
64
+ "type": "npm-downloads"
65
+ },
66
+ {
67
+ "type": "npm-license"
68
+ }
69
+ ],
70
+ "documentation": "https://scalar.com/tools/asyncapi-upgrader/getting-started"
71
+ },
72
+ "sideEffects": false,
73
+ "dependencies": {
74
+ "@scalar/helpers": "0.8.1"
75
+ },
76
+ "devDependencies": {
77
+ "vite": "8.0.0",
78
+ "@scalar/types": "0.12.3"
79
+ },
80
+ "scripts": {
81
+ "build": "tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json",
82
+ "test": "vitest --run",
83
+ "types:check": "tsc --noEmit"
84
+ }
85
+ }