@scalar/asyncapi-to-markdown 0.0.0-stage → 0.2.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 +17 -0
- package/LICENSE +21 -0
- package/README.md +145 -2
- package/dist/binding-schemas.d.ts +3 -0
- package/dist/binding-schemas.d.ts.map +1 -0
- package/dist/binding-schemas.js +33 -0
- package/dist/browser.d.ts +5 -0
- package/dist/browser.d.ts.map +1 -0
- package/dist/browser.js +3 -0
- package/dist/document.d.ts +22 -0
- package/dist/document.d.ts.map +1 -0
- package/dist/document.js +85 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6 -0
- package/dist/load-document.d.ts +4 -0
- package/dist/load-document.d.ts.map +1 -0
- package/dist/load-document.js +66 -0
- package/dist/preserve-data.d.ts +4 -0
- package/dist/preserve-data.d.ts.map +1 -0
- package/dist/preserve-data.js +66 -0
- package/dist/render-content.d.ts +16 -0
- package/dist/render-content.d.ts.map +1 -0
- package/dist/render-content.js +306 -0
- package/dist/render-document.d.ts +4 -0
- package/dist/render-document.d.ts.map +1 -0
- package/dist/render-document.js +140 -0
- package/dist/render-examples.d.ts +4 -0
- package/dist/render-examples.d.ts.map +1 -0
- package/dist/render-examples.js +153 -0
- package/dist/render-schema.d.ts +10 -0
- package/dist/render-schema.d.ts.map +1 -0
- package/dist/render-schema.js +205 -0
- package/dist/schema-format.d.ts +3 -0
- package/dist/schema-format.d.ts.map +1 -0
- package/dist/schema-format.js +3 -0
- package/dist/schema-references.d.ts +12 -0
- package/dist/schema-references.d.ts.map +1 -0
- package/dist/schema-references.js +121 -0
- package/dist/schema-view.d.ts +5 -0
- package/dist/schema-view.d.ts.map +1 -0
- package/dist/schema-view.js +97 -0
- package/dist/types.d.ts +38 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +1 -0
- package/package.json +73 -3
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# @scalar/asyncapi-to-markdown
|
|
2
|
+
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#10586](https://github.com/scalar/scalar/pull/10586): Add AsyncAPI Markdown conversion with reusable renderers and individual reference pages. Share Markdown description parsing between the OpenAPI and AsyncAPI converters.
|
|
8
|
+
|
|
9
|
+
Include shared model links, contents navigation, tag pages, generated examples, and an interactive playground.
|
|
10
|
+
|
|
11
|
+
Preserve discriminators and linked schema descriptions, generate examples from primitive aliases, and compact property annotations.
|
|
12
|
+
|
|
13
|
+
Include full-export tag documentation, preserve XML schema examples, and normalize annotated primitive aliases.
|
|
14
|
+
|
|
15
|
+
Infer enum and const type labels and honor primitive-link settings in generated model examples.
|
|
16
|
+
|
|
17
|
+
Preserve AsyncAPI application and schema metadata, explain security alternatives, and render reply and unknown-address semantics accurately.
|
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
CHANGED
|
@@ -1,3 +1,146 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Scalar AsyncAPI to Markdown
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Generate LLM-friendly Markdown from AsyncAPI descriptions without rendering HTML or Vue.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install @scalar/asyncapi-to-markdown
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import {
|
|
11
|
+
createAsyncApiMarkdownRenderer,
|
|
12
|
+
createMarkdownFromAsyncApi,
|
|
13
|
+
} from '@scalar/asyncapi-to-markdown'
|
|
14
|
+
|
|
15
|
+
const markdown = await createMarkdownFromAsyncApi('./asyncapi.yaml')
|
|
16
|
+
|
|
17
|
+
// Load, upgrade and bundle references once for a documentation build.
|
|
18
|
+
const renderer = await createAsyncApiMarkdownRenderer('./asyncapi.yaml')
|
|
19
|
+
await renderer.render() // Complete description
|
|
20
|
+
await renderer.render({ introduction: true })
|
|
21
|
+
await renderer.render({ channel: 'orders' })
|
|
22
|
+
await renderer.render({ operation: 'receiveOrder' })
|
|
23
|
+
await renderer.render({ message: 'OrderCreated' })
|
|
24
|
+
await renderer.render({ model: 'Order' })
|
|
25
|
+
await renderer.render({ tag: 'Orders' })
|
|
26
|
+
await renderer.render({
|
|
27
|
+
message: { pointer: '#/channels/orders/messages/created' },
|
|
28
|
+
})
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
The Node.js entry point accepts objects, JSON/YAML strings, file paths, and HTTP(S) URLs.
|
|
32
|
+
Relative external references resolve against the source file or URL. Object and inline
|
|
33
|
+
string inputs need absolute external references. AsyncAPI 1.0–1.2, 2.0–2.6, 3.0 and 3.1
|
|
34
|
+
inputs use Scalar's upgrader to produce a 3.1 document. The original version stays visible
|
|
35
|
+
in the introduction. Input objects are not modified. Create a new renderer to pick up
|
|
36
|
+
source changes; rendering pages does not fetch the source again.
|
|
37
|
+
|
|
38
|
+
Choose at most one selector per call. Strings identify exact, case-sensitive map keys:
|
|
39
|
+
channels, operations, component messages, or component schemas. Channel addresses and
|
|
40
|
+
human-readable titles are not selectors. Every map selector also accepts an exact JSON
|
|
41
|
+
pointer, with optional `#` and standard `~0` / `~1` escaping. Message pointers can select
|
|
42
|
+
channel messages as well as component messages. Invalid or missing selections reject
|
|
43
|
+
that call; the renderer remains usable afterward.
|
|
44
|
+
|
|
45
|
+
Operation pages include the channel address, parameters, relevant servers, security,
|
|
46
|
+
selected messages, and reply details. Unknown channel addresses are labelled explicitly. Reply messages
|
|
47
|
+
are rendered only when declared; request messages are not inferred as replies. Channel pages include their operations and all
|
|
48
|
+
channel messages. Selected pages expand each shared schema once and include transitive schema dependencies.
|
|
49
|
+
Introduction pages contain API metadata, the application identifier, default content type, and servers. Complete exports include channels,
|
|
50
|
+
operations, component messages and schemas. Send/receive direction is from the described
|
|
51
|
+
application's perspective; legacy publish/subscribe operations are migrated accordingly.
|
|
52
|
+
|
|
53
|
+
Message and operation traits are merged before rendering. Authored examples are preserved.
|
|
54
|
+
Missing examples are generated from JSON schemas and labelled by context (**Generated headers example** or
|
|
55
|
+
**Generated payload example**). XML payloads use XML examples, including examples authored on their schemas, while headers use JSON. Repeated generated
|
|
56
|
+
examples link to their first occurrence within the same media type and context. JSON Schema and AsyncAPI schemas include properties,
|
|
57
|
+
required markers, constraints, composition, discriminator fields and mappings, and recursive-reference notices.
|
|
58
|
+
Property types and annotations share one line, followed by their Markdown descriptions and external
|
|
59
|
+
documentation links. Content encoding and media-type annotations are preserved. Other schema
|
|
60
|
+
formats, such as Avro and Protobuf, appear as labelled source blocks. Protocol bindings
|
|
61
|
+
are preserved as JSON. Descriptions preserve Markdown, tables and code blocks using the
|
|
62
|
+
same sanitization as the OpenAPI converter; images are excluded.
|
|
63
|
+
|
|
64
|
+
## Navigation and shared models
|
|
65
|
+
|
|
66
|
+
Complete exports include a contents index with explicit anchors. Shared structured
|
|
67
|
+
models render once and their usages link to that definition. Declared tags retain descriptions
|
|
68
|
+
and external documentation links in complete exports. Repeated servers and
|
|
69
|
+
security schemes also link to their first occurrence. Security alternatives are labelled explicitly;
|
|
70
|
+
operation security applies in addition to applicable server security. Primitive schemas remain inline.
|
|
71
|
+
Schema display normalization and description parsing are cached per prepared renderer.
|
|
72
|
+
|
|
73
|
+
Tag pages match exact tag names on channels, operations (including traits), and messages.
|
|
74
|
+
A channel tag includes the channel's operations and messages. An operation tag includes
|
|
75
|
+
that operation's context. Tags declared in `info.tags` retain descriptions and external links,
|
|
76
|
+
even when unused. Tag pages retain the API introduction, display only the selected tag, and link to
|
|
77
|
+
messages already rendered on the page. Unknown or duplicate tag declarations reject the render.
|
|
78
|
+
|
|
79
|
+
For documentation sites that publish model pages separately:
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
await renderer.render({
|
|
83
|
+
operation: 'receiveOrder',
|
|
84
|
+
schemaReferences: {
|
|
85
|
+
mode: 'linked',
|
|
86
|
+
resolveUrl: ({ name }) => `/models/${encodeURIComponent(name)}`,
|
|
87
|
+
inlinePrimitives: true,
|
|
88
|
+
},
|
|
89
|
+
})
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Linked pages expand root schemas and replace nested structured references with published
|
|
93
|
+
links. Returning `undefined` or omitting the callback keeps the model name as plain text.
|
|
94
|
+
Set `inlinePrimitives: false` to link primitive, enum and const references too.
|
|
95
|
+
Linked pages omit the transitive appendix and generated message examples. Selected model
|
|
96
|
+
pages still generate a local example with linked structured dependencies left as stubs.
|
|
97
|
+
Authored examples remain available in linked mode. URL callbacks receive the original reference and
|
|
98
|
+
its model name, preserving aliases. Empty or unsafe URLs render an unlinked name. Composition
|
|
99
|
+
branches retain their model links. Linked schema usages retain their descriptions, and primitive aliases
|
|
100
|
+
remain available when generating model examples.
|
|
101
|
+
|
|
102
|
+
## Browser
|
|
103
|
+
|
|
104
|
+
Use a document already upgraded and resolved by `@scalar/workspace-store`:
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
import { createMarkdownFromAsyncApi } from '@scalar/asyncapi-to-markdown/browser'
|
|
108
|
+
|
|
109
|
+
const markdown = await createMarkdownFromAsyncApi(document, {
|
|
110
|
+
operation: 'receiveOrder',
|
|
111
|
+
})
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
The browser entry point does not read files, fetch references, or upgrade raw documents.
|
|
115
|
+
|
|
116
|
+
## Limitations
|
|
117
|
+
|
|
118
|
+
This is a documentation converter, not a validator. Unsupported versions, failed loads,
|
|
119
|
+
and unresolved references needed for rendering reject with an error. Recursive schema
|
|
120
|
+
expansion stops at a repeated ancestor, ten levels, or 5,000 schema nodes per expansion,
|
|
121
|
+
with a visible notice. Generated examples exceeding 10,000 estimated values are omitted
|
|
122
|
+
with a visible notice. Custom schema
|
|
123
|
+
vocabularies are not interpreted, and output is not a replacement for the original schema.
|
|
124
|
+
Publishing Markdown routes and adding copy buttons to Scalar Docs are separate integrations.
|
|
125
|
+
|
|
126
|
+
## Playground and benchmarks
|
|
127
|
+
|
|
128
|
+
Run `pnpm --filter @scalar/asyncapi-to-markdown dev --port 3002 --strictPort`.
|
|
129
|
+
The playground includes local order events and a shared-schema stress fixture, page
|
|
130
|
+
selection and search, linked/full export modes, sanitized previews, Markdown source,
|
|
131
|
+
copy/download controls, output size and render timing. Click a published model link to
|
|
132
|
+
open that model page. It runs conversion in a worker to keep the UI responsive.
|
|
133
|
+
|
|
134
|
+
Run `pnpm --filter @scalar/asyncapi-to-markdown benchmark` for repeatable preparation,
|
|
135
|
+
cold/warm rendering, output size, and RSS measurements. See [the benchmark method](./benchmarks/README.md).
|
|
136
|
+
|
|
137
|
+
## Specification coverage
|
|
138
|
+
|
|
139
|
+
Rendering follows the [AsyncAPI 3.1 specification](https://www.asyncapi.com/docs/reference/specification/v3.1.0).
|
|
140
|
+
The converter covers application metadata, servers and variables, channel parameters, operation and
|
|
141
|
+
message traits, request/reply details, security schemes and OAuth flows, tags, external documentation,
|
|
142
|
+
and JSON Schema Draft 7 constraints. All mandatory JSON/YAML schema-format identifiers work for
|
|
143
|
+
both headers and payloads. Protocol bindings and other schema languages remain available as source
|
|
144
|
+
blocks. Referenced reusable objects render at their usage sites; unused component schemas and
|
|
145
|
+
messages are also included in complete exports. Custom extension semantics and validation remain
|
|
146
|
+
outside the converter's scope.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"binding-schemas.d.ts","sourceRoot":"","sources":["../src/binding-schemas.ts"],"names":[],"mappings":"AAMA,kGAAkG;AAClG,eAAO,MAAM,iBAAiB,GAAI,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EA2B3F,CAAA"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { isObject } from '@scalar/helpers/object/is-object';
|
|
2
|
+
import { getRaw } from '@scalar/json-magic/magic-proxy';
|
|
3
|
+
const schemaMaps = new Set(['properties', 'patternProperties', '$defs', 'definitions', 'dependencies']);
|
|
4
|
+
const literalFields = new Set(['example', 'examples', 'default', 'enum', 'const']);
|
|
5
|
+
/** Find schema references inside protocol bindings without interpreting authored example data. */
|
|
6
|
+
export const getBindingSchemas = (binding) => {
|
|
7
|
+
const references = [];
|
|
8
|
+
const seen = new Set();
|
|
9
|
+
const visit = (value, map = false) => {
|
|
10
|
+
if (value === null || typeof value !== 'object' || seen.has(getRaw(value))) {
|
|
11
|
+
return;
|
|
12
|
+
}
|
|
13
|
+
seen.add(getRaw(value));
|
|
14
|
+
if (Array.isArray(value)) {
|
|
15
|
+
value.forEach((entry) => visit(entry));
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
if (!isObject(value)) {
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
if (!map && typeof value.$ref === 'string') {
|
|
22
|
+
references.push(value);
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
for (const [key, child] of Object.entries(value)) {
|
|
26
|
+
if (map || (!literalFields.has(key) && !key.startsWith('x-'))) {
|
|
27
|
+
visit(child, !map && schemaMaps.has(key));
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
visit(binding);
|
|
32
|
+
return references;
|
|
33
|
+
};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { AsyncApiDocument } from '@scalar/types/asyncapi/3.1';
|
|
2
|
+
import type { AsyncApiRenderOptions } from './types.js';
|
|
3
|
+
/** Render an upgraded, workspace-resolved document without fetching or loading files. */
|
|
4
|
+
export declare const createMarkdownFromAsyncApi: (document: AsyncApiDocument | Record<string, unknown>, options?: AsyncApiRenderOptions) => Promise<string>;
|
|
5
|
+
//# sourceMappingURL=browser.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"browser.d.ts","sourceRoot":"","sources":["../src/browser.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAA;AAGlE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAA;AAEpD,yFAAyF;AACzF,eAAO,MAAM,0BAA0B,GACrC,UAAU,gBAAgB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACpD,UAAU,qBAAqB,KAC9B,OAAO,CAAC,MAAM,CAA6C,CAAA"}
|
package/dist/browser.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { AsyncApiRenderOptions } from './types.js';
|
|
2
|
+
/** Follow workspace reference wrappers without treating reference siblings as overrides. */
|
|
3
|
+
export declare const resolve: (value: unknown) => unknown;
|
|
4
|
+
/** Read an optional object while keeping malformed optional fields out of the renderer. */
|
|
5
|
+
export declare const object: (value: unknown) => Record<string, unknown>;
|
|
6
|
+
/** Preserve map keys such as __proto__ without looking up inherited properties. */
|
|
7
|
+
export declare const own: (value: unknown, key: string) => unknown;
|
|
8
|
+
/** Scalar metadata is optional; never serialize objects into headings or descriptions. */
|
|
9
|
+
export declare const string: (value: unknown) => string | undefined;
|
|
10
|
+
/** A normalized selection with an exact location in the prepared document. */
|
|
11
|
+
type Selection = {
|
|
12
|
+
kind: 'channel' | 'operation' | 'message' | 'model';
|
|
13
|
+
name: string;
|
|
14
|
+
value: unknown;
|
|
15
|
+
};
|
|
16
|
+
/** Reject combined or missing selections before writing any Markdown. */
|
|
17
|
+
export declare const select: (document: Record<string, unknown>, options: AsyncApiRenderOptions) => Selection | {
|
|
18
|
+
kind: "tag";
|
|
19
|
+
name: string;
|
|
20
|
+
} | "introduction" | undefined;
|
|
21
|
+
export {};
|
|
22
|
+
//# sourceMappingURL=document.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"document.d.ts","sourceRoot":"","sources":["../src/document.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,qBAAqB,EAAoB,MAAM,SAAS,CAAA;AAEtE,4FAA4F;AAC5F,eAAO,MAAM,OAAO,GAAI,OAAO,OAAO,KAAG,OAiBxC,CAAA;AAED,2FAA2F;AAC3F,eAAO,MAAM,MAAM,GAAI,OAAO,OAAO,KAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAG7D,CAAA;AAED,mFAAmF;AACnF,eAAO,MAAM,GAAG,GAAI,OAAO,OAAO,EAAE,KAAK,MAAM,KAAG,OAGjD,CAAA;AAED,0FAA0F;AAC1F,eAAO,MAAM,MAAM,GAAI,OAAO,OAAO,KAAG,MAAM,GAAG,SAA4D,CAAA;AAE7G,8EAA8E;AAC9E,KAAK,SAAS,GAAG;IAAE,IAAI,EAAE,SAAS,GAAG,WAAW,GAAG,SAAS,GAAG,OAAO,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,OAAO,CAAA;CAAE,CAAA;AAStG,yEAAyE;AACzE,eAAO,MAAM,MAAM,GACjB,UAAU,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACjC,SAAS,qBAAqB,KAC7B,SAAS,GAAG;IAAE,IAAI,EAAE,KAAK,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG,cAAc,GAAG,SAiD/D,CAAA"}
|
package/dist/document.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { parseJsonPointerSegments } from '@scalar/helpers/json/parse-json-pointer-segments';
|
|
2
|
+
import { isObject } from '@scalar/helpers/object/is-object';
|
|
3
|
+
import { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref';
|
|
4
|
+
/** Follow workspace reference wrappers without treating reference siblings as overrides. */
|
|
5
|
+
export const resolve = (value) => {
|
|
6
|
+
const seen = new Set();
|
|
7
|
+
const follow = (input) => {
|
|
8
|
+
if (!isObject(input) || typeof input.$ref !== 'string') {
|
|
9
|
+
return input;
|
|
10
|
+
}
|
|
11
|
+
if (seen.has(input)) {
|
|
12
|
+
throw new Error(`Circular reference alias: ${input.$ref}`);
|
|
13
|
+
}
|
|
14
|
+
seen.add(input);
|
|
15
|
+
const target = getResolvedRef(input);
|
|
16
|
+
if (target === undefined || target === input) {
|
|
17
|
+
throw new Error(`Unresolved reference: ${input.$ref}`);
|
|
18
|
+
}
|
|
19
|
+
return follow(target);
|
|
20
|
+
};
|
|
21
|
+
return follow(value);
|
|
22
|
+
};
|
|
23
|
+
/** Read an optional object while keeping malformed optional fields out of the renderer. */
|
|
24
|
+
export const object = (value) => {
|
|
25
|
+
const resolved = resolve(value);
|
|
26
|
+
return isObject(resolved) ? resolved : {};
|
|
27
|
+
};
|
|
28
|
+
/** Preserve map keys such as __proto__ without looking up inherited properties. */
|
|
29
|
+
export const own = (value, key) => {
|
|
30
|
+
const record = object(value);
|
|
31
|
+
return Object.hasOwn(record, key) ? record[key] : undefined;
|
|
32
|
+
};
|
|
33
|
+
/** Scalar metadata is optional; never serialize objects into headings or descriptions. */
|
|
34
|
+
export const string = (value) => (typeof value === 'string' ? value : undefined);
|
|
35
|
+
const locations = {
|
|
36
|
+
channel: ['channels'],
|
|
37
|
+
operation: ['operations'],
|
|
38
|
+
message: ['components', 'messages'],
|
|
39
|
+
model: ['components', 'schemas'],
|
|
40
|
+
};
|
|
41
|
+
/** Reject combined or missing selections before writing any Markdown. */
|
|
42
|
+
export const select = (document, options) => {
|
|
43
|
+
const keys = Object.keys(options).filter((key) => key !== 'schemaReferences' && options[key] !== undefined);
|
|
44
|
+
if (keys.length > 1 ||
|
|
45
|
+
keys.some((key) => key !== 'introduction' && key !== 'tag' && !Object.hasOwn(locations, key))) {
|
|
46
|
+
throw new Error('Choose exactly one AsyncAPI page selector');
|
|
47
|
+
}
|
|
48
|
+
const key = keys[0];
|
|
49
|
+
if (!key) {
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
if (key === 'introduction') {
|
|
53
|
+
if (options.introduction !== true) {
|
|
54
|
+
throw new Error('The introduction selector must be true');
|
|
55
|
+
}
|
|
56
|
+
return 'introduction';
|
|
57
|
+
}
|
|
58
|
+
if (key === 'tag') {
|
|
59
|
+
if (typeof options.tag !== 'string' || !options.tag) {
|
|
60
|
+
throw new Error('Invalid tag selector');
|
|
61
|
+
}
|
|
62
|
+
return { kind: 'tag', name: options.tag };
|
|
63
|
+
}
|
|
64
|
+
const kind = key;
|
|
65
|
+
const selector = options[kind];
|
|
66
|
+
if (isObject(selector) && typeof selector.pointer === 'string' && /~(?![01])/.test(selector.pointer)) {
|
|
67
|
+
throw new Error(`Invalid JSON pointer escape in ${selector.pointer}`);
|
|
68
|
+
}
|
|
69
|
+
const segments = typeof selector === 'string'
|
|
70
|
+
? [...locations[kind], selector]
|
|
71
|
+
: isObject(selector) && typeof selector.pointer === 'string' && /^#?\//.test(selector.pointer)
|
|
72
|
+
? parseJsonPointerSegments(selector.pointer.replace(/^#/, ''))
|
|
73
|
+
: [];
|
|
74
|
+
const expected = locations[kind];
|
|
75
|
+
const matches = segments.length === expected.length + 1 && expected.every((part, index) => segments[index] === part);
|
|
76
|
+
const channelMessage = kind === 'message' && segments.length === 4 && segments[0] === 'channels' && segments[2] === 'messages';
|
|
77
|
+
if (!matches && !channelMessage) {
|
|
78
|
+
throw new Error(`Invalid ${kind} selector`);
|
|
79
|
+
}
|
|
80
|
+
const value = segments.reduce((current, segment) => own(current, segment), document);
|
|
81
|
+
if (value === undefined) {
|
|
82
|
+
throw new Error(`Unknown ${kind}: ${segments.join('/')}`);
|
|
83
|
+
}
|
|
84
|
+
return { kind, name: segments.at(-1), value };
|
|
85
|
+
};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { AsyncApiInput, AsyncApiMarkdownRenderer, AsyncApiRenderOptions } from './types.js';
|
|
2
|
+
export type { AsyncApiInput, AsyncApiMarkdownRenderer, AsyncApiRenderOptions, AsyncApiSelector } from './types.js';
|
|
3
|
+
/** Prepare an immutable document snapshot once for a complete export or multiple pages. */
|
|
4
|
+
export declare const createAsyncApiMarkdownRenderer: (input: AsyncApiInput) => Promise<AsyncApiMarkdownRenderer>;
|
|
5
|
+
/** Generate LLM-friendly Markdown from an AsyncAPI description or one of its reference pages. */
|
|
6
|
+
export declare const createMarkdownFromAsyncApi: (input: AsyncApiInput, options?: AsyncApiRenderOptions) => Promise<string>;
|
|
7
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,wBAAwB,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAA;AAE7F,YAAY,EAAE,aAAa,EAAE,wBAAwB,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAE/G,2FAA2F;AAC3F,eAAO,MAAM,8BAA8B,GAAU,OAAO,aAAa,KAAG,OAAO,CAAC,wBAAwB,CACjE,CAAA;AAE3C,iGAAiG;AACjG,eAAO,MAAM,0BAA0B,GACrC,OAAO,aAAa,EACpB,UAAU,qBAAqB,KAC9B,OAAO,CAAC,MAAM,CAAkE,CAAA"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { loadDocument } from './load-document.js';
|
|
2
|
+
import { createRenderer } from './render-document.js';
|
|
3
|
+
/** Prepare an immutable document snapshot once for a complete export or multiple pages. */
|
|
4
|
+
export const createAsyncApiMarkdownRenderer = async (input) => createRenderer(await loadDocument(input));
|
|
5
|
+
/** Generate LLM-friendly Markdown from an AsyncAPI description or one of its reference pages. */
|
|
6
|
+
export const createMarkdownFromAsyncApi = async (input, options) => (await createAsyncApiMarkdownRenderer(input)).render(options);
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { AsyncApiInput } from './types.js';
|
|
2
|
+
/** Load once, preserving the source location for relative external references. */
|
|
3
|
+
export declare const loadDocument: (input: AsyncApiInput) => Promise<Record<string, unknown>>;
|
|
4
|
+
//# sourceMappingURL=load-document.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"load-document.d.ts","sourceRoot":"","sources":["../src/load-document.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAE5C,kFAAkF;AAClF,eAAO,MAAM,YAAY,GAAU,OAAO,aAAa,KAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CA2DxF,CAAA"}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { upgrade } from '@scalar/asyncapi-upgrader';
|
|
2
|
+
import { isObject } from '@scalar/helpers/object/is-object';
|
|
3
|
+
import { bundle } from '@scalar/json-magic/bundle';
|
|
4
|
+
import { fetchUrls, readFiles } from '@scalar/json-magic/bundle/plugins/node';
|
|
5
|
+
import { normalize } from '@scalar/json-magic/helpers/normalize';
|
|
6
|
+
import { createMagicProxy, getRaw } from '@scalar/json-magic/magic-proxy';
|
|
7
|
+
import { deepClone } from '@scalar/workspace-store/helpers/deep-clone';
|
|
8
|
+
import { object } from './document.js';
|
|
9
|
+
import { preserveData } from './preserve-data.js';
|
|
10
|
+
/** Load once, preserving the source location for relative external references. */
|
|
11
|
+
export const loadDocument = async (input) => {
|
|
12
|
+
const source = async () => {
|
|
13
|
+
if (typeof input !== 'string') {
|
|
14
|
+
return { value: deepClone(getRaw(input)) };
|
|
15
|
+
}
|
|
16
|
+
const parsed = normalize(input);
|
|
17
|
+
if (isObject(parsed)) {
|
|
18
|
+
return { value: parsed };
|
|
19
|
+
}
|
|
20
|
+
if (/^https?:\/\//i.test(input)) {
|
|
21
|
+
const response = await fetch(input);
|
|
22
|
+
if (!response.ok) {
|
|
23
|
+
throw new Error(`Failed to load AsyncAPI document (HTTP ${response.status})`);
|
|
24
|
+
}
|
|
25
|
+
return { value: normalize(await response.text()), origin: input };
|
|
26
|
+
}
|
|
27
|
+
const [{ resolve }, { readFile }] = await Promise.all([import('node:path'), import('node:fs/promises')]);
|
|
28
|
+
const origin = resolve(input);
|
|
29
|
+
return { value: normalize(await readFile(origin, 'utf8')), origin };
|
|
30
|
+
};
|
|
31
|
+
const { value, origin } = await source();
|
|
32
|
+
if (!isObject(value) || typeof value.asyncapi !== 'string') {
|
|
33
|
+
throw new Error('Expected an AsyncAPI document with an asyncapi version');
|
|
34
|
+
}
|
|
35
|
+
if (!/^(1\.[012]|2\.[0-6]|3\.[01])\.\d+(?:-[\w.-]+)?$/.test(value.asyncapi)) {
|
|
36
|
+
throw new Error(`Unsupported AsyncAPI version: ${value.asyncapi}`);
|
|
37
|
+
}
|
|
38
|
+
const originalVersion = value.asyncapi;
|
|
39
|
+
const errors = [];
|
|
40
|
+
const bundled = await bundle(value, {
|
|
41
|
+
origin,
|
|
42
|
+
plugins: [fetchUrls(), readFiles(), preserveData()],
|
|
43
|
+
treeShake: false,
|
|
44
|
+
hooks: { onResolveError: (node) => errors.push(`Failed to resolve ${node.$ref}`) },
|
|
45
|
+
});
|
|
46
|
+
if (errors.length) {
|
|
47
|
+
throw new Error(errors.join('\n'));
|
|
48
|
+
}
|
|
49
|
+
// Migration reads structural fields directly. Resolve wrappers after bundling so older
|
|
50
|
+
// channels and servers loaded from other files participate in the same upgrade.
|
|
51
|
+
const prepared = { ...bundled };
|
|
52
|
+
const resolved = createMagicProxy(prepared);
|
|
53
|
+
for (const key of ['channels', 'servers', 'operations']) {
|
|
54
|
+
if (prepared[key] !== undefined && !Array.isArray(prepared[key])) {
|
|
55
|
+
prepared[key] = Object.fromEntries(Object.entries(object(resolved[key])).map(([name, entry]) => [name, getRaw(object(entry))]));
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const components = object(resolved.components);
|
|
59
|
+
if (components.securitySchemes) {
|
|
60
|
+
prepared.components = {
|
|
61
|
+
...getRaw(components),
|
|
62
|
+
securitySchemes: Object.fromEntries(Object.entries(object(components.securitySchemes)).map(([name, entry]) => [name, getRaw(object(entry))])),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
return createMagicProxy({ ...upgrade(prepared), 'x-original-aas-version': originalVersion });
|
|
66
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"preserve-data.d.ts","sourceRoot":"","sources":["../src/preserve-data.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAA;AA+BhE,iGAAiG;AACjG,eAAO,MAAM,YAAY,QAAO,eAqC/B,CAAA"}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { isObject } from '@scalar/helpers/object/is-object';
|
|
2
|
+
const dataKeys = new Set(['example', 'examples', 'default', 'enum', 'const']);
|
|
3
|
+
const maps = new Set([
|
|
4
|
+
'channels',
|
|
5
|
+
'operations',
|
|
6
|
+
'messages',
|
|
7
|
+
'schemas',
|
|
8
|
+
'properties',
|
|
9
|
+
'patternProperties',
|
|
10
|
+
'$defs',
|
|
11
|
+
'definitions',
|
|
12
|
+
'parameters',
|
|
13
|
+
'servers',
|
|
14
|
+
'variables',
|
|
15
|
+
'securitySchemes',
|
|
16
|
+
'messageTraits',
|
|
17
|
+
'operationTraits',
|
|
18
|
+
'correlationIds',
|
|
19
|
+
'replies',
|
|
20
|
+
'replyAddresses',
|
|
21
|
+
'dependencies',
|
|
22
|
+
'tags',
|
|
23
|
+
'externalDocs',
|
|
24
|
+
'serverVariables',
|
|
25
|
+
'serverBindings',
|
|
26
|
+
'channelBindings',
|
|
27
|
+
'operationBindings',
|
|
28
|
+
'messageBindings',
|
|
29
|
+
]);
|
|
30
|
+
/** Keep literal data outside the generic bundler's reference walk, including in loaded files. */
|
|
31
|
+
export const preserveData = () => {
|
|
32
|
+
const mapNodes = new WeakSet();
|
|
33
|
+
const hidden = new WeakMap();
|
|
34
|
+
return {
|
|
35
|
+
type: 'lifecycle',
|
|
36
|
+
onBeforeNodeProcess: (node) => {
|
|
37
|
+
// Keys in maps are user-defined names, so a schema named "examples" is not example data.
|
|
38
|
+
if (mapNodes.has(node)) {
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
for (const key of maps) {
|
|
42
|
+
const value = node[key];
|
|
43
|
+
if (isObject(value)) {
|
|
44
|
+
mapNodes.add(value);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
const fields = Object.keys(node).filter((key) => dataKeys.has(key) || (key.startsWith('x-') && key !== 'x-ext' && key !== 'x-ext-urls'));
|
|
48
|
+
const descriptors = fields.flatMap((key) => {
|
|
49
|
+
const descriptor = Object.getOwnPropertyDescriptor(node, key);
|
|
50
|
+
if (!descriptor?.configurable) {
|
|
51
|
+
return [];
|
|
52
|
+
}
|
|
53
|
+
// Non-enumerable data remains available to the loader, but not to its reference traversal.
|
|
54
|
+
Object.defineProperty(node, key, { ...descriptor, enumerable: false });
|
|
55
|
+
return [[key, descriptor]];
|
|
56
|
+
});
|
|
57
|
+
hidden.set(node, descriptors);
|
|
58
|
+
},
|
|
59
|
+
onAfterNodeProcess: (node) => {
|
|
60
|
+
for (const [key, descriptor] of hidden.get(node) ?? []) {
|
|
61
|
+
Object.defineProperty(node, key, descriptor);
|
|
62
|
+
}
|
|
63
|
+
hidden.delete(node);
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Heading, RootContent } from 'mdast';
|
|
2
|
+
import type { createSchemaRegistry } from './schema-references.js';
|
|
3
|
+
/** Page-local rendering functions share output and schema expansion state. */
|
|
4
|
+
type ContentRenderer = {
|
|
5
|
+
blocks: RootContent[];
|
|
6
|
+
introduction: () => void;
|
|
7
|
+
finish: () => void;
|
|
8
|
+
channel: (name: string, value: unknown, depth: Heading['depth']) => void;
|
|
9
|
+
operation: (name: string, value: unknown, depth: Heading['depth'], includeChannel: boolean) => void;
|
|
10
|
+
message: (name: string, value: unknown, depth: Heading['depth']) => void;
|
|
11
|
+
model: (name: string, value: unknown, depth: Heading['depth']) => void;
|
|
12
|
+
};
|
|
13
|
+
/** Build the sections of one AsyncAPI page without retaining mutable state between calls. */
|
|
14
|
+
export declare const createContentRenderer: (document: Record<string, unknown>, references: ReturnType<ReturnType<typeof createSchemaRegistry>["forPage"]>, view: (input: Record<string, unknown>) => Record<string, unknown>, linked: boolean, selectedModel: boolean, selectedTag?: string, inlinePrimitives?: boolean) => ContentRenderer;
|
|
15
|
+
export {};
|
|
16
|
+
//# sourceMappingURL=render-content.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"render-content.d.ts","sourceRoot":"","sources":["../src/render-content.ts"],"names":[],"mappings":"AAkBA,OAAO,KAAK,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,OAAO,CAAA;AAMjD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAA;AAW/D,8EAA8E;AAC9E,KAAK,eAAe,GAAG;IACrB,MAAM,EAAE,WAAW,EAAE,CAAA;IACrB,YAAY,EAAE,MAAM,IAAI,CAAA;IACxB,MAAM,EAAE,MAAM,IAAI,CAAA;IAClB,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC,OAAO,CAAC,KAAK,IAAI,CAAA;IACxE,SAAS,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC,OAAO,CAAC,EAAE,cAAc,EAAE,OAAO,KAAK,IAAI,CAAA;IACnG,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC,OAAO,CAAC,KAAK,IAAI,CAAA;IACxE,KAAK,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC,OAAO,CAAC,KAAK,IAAI,CAAA;CACvE,CAAA;AAED,6FAA6F;AAC7F,eAAO,MAAM,qBAAqB,GAChC,UAAU,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACjC,YAAY,UAAU,CAAC,UAAU,CAAC,OAAO,oBAAoB,CAAC,CAAC,SAAS,CAAC,CAAC,EAC1E,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACjE,QAAQ,OAAO,EACf,eAAe,OAAO,EACtB,cAAc,MAAM,EACpB,0BAAuB,KACtB,eAwUF,CAAA"}
|