@scalar/json-magic 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/.turbo/turbo-build.log +9 -0
- package/CHANGELOG.md +7 -0
- package/LICENSE +21 -0
- package/README.md +356 -0
- package/dist/bundle/bundle.d.ts +292 -0
- package/dist/bundle/bundle.d.ts.map +1 -0
- package/dist/bundle/bundle.js +259 -0
- package/dist/bundle/bundle.js.map +7 -0
- package/dist/bundle/create-limiter.d.ts +21 -0
- package/dist/bundle/create-limiter.d.ts.map +1 -0
- package/dist/bundle/create-limiter.js +31 -0
- package/dist/bundle/create-limiter.js.map +7 -0
- package/dist/bundle/index.d.ts +2 -0
- package/dist/bundle/index.d.ts.map +1 -0
- package/dist/bundle/index.js +5 -0
- package/dist/bundle/index.js.map +7 -0
- package/dist/bundle/plugins/browser.d.ts +4 -0
- package/dist/bundle/plugins/browser.d.ts.map +1 -0
- package/dist/bundle/plugins/browser.js +9 -0
- package/dist/bundle/plugins/browser.js.map +7 -0
- package/dist/bundle/plugins/fetch-urls/index.d.ts +39 -0
- package/dist/bundle/plugins/fetch-urls/index.d.ts.map +1 -0
- package/dist/bundle/plugins/fetch-urls/index.js +48 -0
- package/dist/bundle/plugins/fetch-urls/index.js.map +7 -0
- package/dist/bundle/plugins/node.d.ts +5 -0
- package/dist/bundle/plugins/node.d.ts.map +1 -0
- package/dist/bundle/plugins/node.js +11 -0
- package/dist/bundle/plugins/node.js.map +7 -0
- package/dist/bundle/plugins/parse-json/index.d.ts +13 -0
- package/dist/bundle/plugins/parse-json/index.d.ts.map +1 -0
- package/dist/bundle/plugins/parse-json/index.js +22 -0
- package/dist/bundle/plugins/parse-json/index.js.map +7 -0
- package/dist/bundle/plugins/parse-yaml/index.d.ts +13 -0
- package/dist/bundle/plugins/parse-yaml/index.d.ts.map +1 -0
- package/dist/bundle/plugins/parse-yaml/index.js +23 -0
- package/dist/bundle/plugins/parse-yaml/index.js.map +7 -0
- package/dist/bundle/plugins/read-files/index.d.ts +29 -0
- package/dist/bundle/plugins/read-files/index.d.ts.map +1 -0
- package/dist/bundle/plugins/read-files/index.js +30 -0
- package/dist/bundle/plugins/read-files/index.js.map +7 -0
- package/dist/bundle/value-generator.d.ts +79 -0
- package/dist/bundle/value-generator.d.ts.map +1 -0
- package/dist/bundle/value-generator.js +55 -0
- package/dist/bundle/value-generator.js.map +7 -0
- package/dist/dereference/dereference.d.ts +45 -0
- package/dist/dereference/dereference.d.ts.map +1 -0
- package/dist/dereference/dereference.js +37 -0
- package/dist/dereference/dereference.js.map +7 -0
- package/dist/dereference/index.d.ts +2 -0
- package/dist/dereference/index.d.ts.map +1 -0
- package/dist/dereference/index.js +5 -0
- package/dist/dereference/index.js.map +7 -0
- package/dist/diff/apply.d.ts +35 -0
- package/dist/diff/apply.d.ts.map +1 -0
- package/dist/diff/apply.js +40 -0
- package/dist/diff/apply.js.map +7 -0
- package/dist/diff/diff.d.ts +56 -0
- package/dist/diff/diff.d.ts.map +1 -0
- package/dist/diff/diff.js +33 -0
- package/dist/diff/diff.js.map +7 -0
- package/dist/diff/index.d.ts +5 -0
- package/dist/diff/index.d.ts.map +1 -0
- package/dist/diff/index.js +9 -0
- package/dist/diff/index.js.map +7 -0
- package/dist/diff/merge.d.ts +43 -0
- package/dist/diff/merge.d.ts.map +1 -0
- package/dist/diff/merge.js +61 -0
- package/dist/diff/merge.js.map +7 -0
- package/dist/diff/trie.d.ts +64 -0
- package/dist/diff/trie.d.ts.map +1 -0
- package/dist/diff/trie.js +82 -0
- package/dist/diff/trie.js.map +7 -0
- package/dist/diff/utils.d.ts +63 -0
- package/dist/diff/utils.d.ts.map +1 -0
- package/dist/diff/utils.js +48 -0
- package/dist/diff/utils.js.map +7 -0
- package/dist/magic-proxy/index.d.ts +2 -0
- package/dist/magic-proxy/index.d.ts.map +1 -0
- package/dist/magic-proxy/index.js +6 -0
- package/dist/magic-proxy/index.js.map +7 -0
- package/dist/magic-proxy/proxy.d.ts +63 -0
- package/dist/magic-proxy/proxy.d.ts.map +1 -0
- package/dist/magic-proxy/proxy.js +108 -0
- package/dist/magic-proxy/proxy.js.map +7 -0
- package/dist/polyfills/index.d.ts +2 -0
- package/dist/polyfills/index.d.ts.map +1 -0
- package/dist/polyfills/index.js +25 -0
- package/dist/polyfills/index.js.map +7 -0
- package/dist/polyfills/path.d.ts +24 -0
- package/dist/polyfills/path.d.ts.map +1 -0
- package/dist/polyfills/path.js +174 -0
- package/dist/polyfills/path.js.map +7 -0
- package/dist/types.d.ts +2 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +1 -0
- package/dist/types.js.map +7 -0
- package/dist/utils/escape-json-pointer.d.ts +7 -0
- package/dist/utils/escape-json-pointer.d.ts.map +1 -0
- package/dist/utils/escape-json-pointer.js +7 -0
- package/dist/utils/escape-json-pointer.js.map +7 -0
- package/dist/utils/get-segments-from-path.d.ts +5 -0
- package/dist/utils/get-segments-from-path.d.ts.map +1 -0
- package/dist/utils/get-segments-from-path.js +11 -0
- package/dist/utils/get-segments-from-path.js.map +7 -0
- package/dist/utils/is-json-object.d.ts +18 -0
- package/dist/utils/is-json-object.d.ts.map +1 -0
- package/dist/utils/is-json-object.js +16 -0
- package/dist/utils/is-json-object.js.map +7 -0
- package/dist/utils/is-object.d.ts +5 -0
- package/dist/utils/is-object.d.ts.map +1 -0
- package/dist/utils/is-object.js +5 -0
- package/dist/utils/is-object.js.map +7 -0
- package/dist/utils/is-yaml.d.ts +17 -0
- package/dist/utils/is-yaml.d.ts.map +1 -0
- package/dist/utils/is-yaml.js +7 -0
- package/dist/utils/is-yaml.js.map +7 -0
- package/dist/utils/json-path-utils.d.ts +23 -0
- package/dist/utils/json-path-utils.d.ts.map +1 -0
- package/dist/utils/json-path-utils.js +16 -0
- package/dist/utils/json-path-utils.js.map +7 -0
- package/dist/utils/normalize.d.ts +5 -0
- package/dist/utils/normalize.d.ts.map +1 -0
- package/dist/utils/normalize.js +28 -0
- package/dist/utils/normalize.js.map +7 -0
- package/dist/utils/unescape-json-pointer.d.ts +8 -0
- package/dist/utils/unescape-json-pointer.d.ts.map +1 -0
- package/dist/utils/unescape-json-pointer.js +7 -0
- package/dist/utils/unescape-json-pointer.js.map +7 -0
- package/esbuild.ts +13 -0
- package/package.json +65 -0
- package/src/bundle/bundle.test.ts +1843 -0
- package/src/bundle/bundle.ts +758 -0
- package/src/bundle/create-limiter.test.ts +28 -0
- package/src/bundle/create-limiter.ts +52 -0
- package/src/bundle/index.ts +2 -0
- package/src/bundle/plugins/browser.ts +4 -0
- package/src/bundle/plugins/fetch-urls/index.test.ts +147 -0
- package/src/bundle/plugins/fetch-urls/index.ts +94 -0
- package/src/bundle/plugins/node.ts +5 -0
- package/src/bundle/plugins/parse-json/index.test.ts +22 -0
- package/src/bundle/plugins/parse-json/index.ts +30 -0
- package/src/bundle/plugins/parse-yaml/index.test.ts +24 -0
- package/src/bundle/plugins/parse-yaml/index.ts +31 -0
- package/src/bundle/plugins/read-files/index.test.ts +35 -0
- package/src/bundle/plugins/read-files/index.ts +55 -0
- package/src/bundle/value-generator.test.ts +166 -0
- package/src/bundle/value-generator.ts +147 -0
- package/src/dereference/dereference.test.ts +137 -0
- package/src/dereference/dereference.ts +84 -0
- package/src/dereference/index.ts +2 -0
- package/src/diff/apply.test.ts +262 -0
- package/src/diff/apply.ts +78 -0
- package/src/diff/diff.test.ts +328 -0
- package/src/diff/diff.ts +94 -0
- package/src/diff/index.test.ts +150 -0
- package/src/diff/index.ts +5 -0
- package/src/diff/merge.test.ts +1109 -0
- package/src/diff/merge.ts +136 -0
- package/src/diff/trie.test.ts +30 -0
- package/src/diff/trie.ts +113 -0
- package/src/diff/utils.test.ts +169 -0
- package/src/diff/utils.ts +113 -0
- package/src/magic-proxy/index.ts +2 -0
- package/src/magic-proxy/proxy.test.ts +145 -0
- package/src/magic-proxy/proxy.ts +225 -0
- package/src/polyfills/index.ts +12 -0
- package/src/polyfills/path.ts +248 -0
- package/src/types.ts +1 -0
- package/src/utils/escape-json-pointer.test.ts +13 -0
- package/src/utils/escape-json-pointer.ts +8 -0
- package/src/utils/get-segments-from-path.test.ts +17 -0
- package/src/utils/get-segments-from-path.ts +17 -0
- package/src/utils/is-json-object.ts +31 -0
- package/src/utils/is-object.test.ts +27 -0
- package/src/utils/is-object.ts +4 -0
- package/src/utils/is-yaml.ts +18 -0
- package/src/utils/json-path-utils.test.ts +13 -0
- package/src/utils/json-path-utils.ts +38 -0
- package/src/utils/normalize.test.ts +91 -0
- package/src/utils/normalize.ts +34 -0
- package/src/utils/unescape-json-pointer.test.ts +23 -0
- package/src/utils/unescape-json-pointer.ts +9 -0
- package/tsconfig.build.json +12 -0
- package/tsconfig.json +16 -0
- package/vite.config.ts +8 -0
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
import { escapeJsonPointer } from "../utils/escape-json-pointer.js";
|
|
2
|
+
import path from "../polyfills/path.js";
|
|
3
|
+
import { getSegmentsFromPath } from "../utils/get-segments-from-path.js";
|
|
4
|
+
import { isObject } from "../utils/is-object.js";
|
|
5
|
+
import { isYaml } from "../utils/is-yaml.js";
|
|
6
|
+
import { isJsonObject } from "../utils/is-json-object.js";
|
|
7
|
+
import { getHash, uniqueValueGeneratorFactory } from "./value-generator.js";
|
|
8
|
+
function isRemoteUrl(value) {
|
|
9
|
+
try {
|
|
10
|
+
const url = new URL(value);
|
|
11
|
+
return url.protocol === "http:" || url.protocol === "https:";
|
|
12
|
+
} catch {
|
|
13
|
+
return false;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
function isFilePath(value) {
|
|
17
|
+
return !isRemoteUrl(value) && !isYaml(value) && !isJsonObject(value);
|
|
18
|
+
}
|
|
19
|
+
function isLocalRef(value) {
|
|
20
|
+
return value.startsWith("#");
|
|
21
|
+
}
|
|
22
|
+
async function resolveContents(value, plugins) {
|
|
23
|
+
const plugin = plugins.find((p) => p.validate(value));
|
|
24
|
+
if (plugin) {
|
|
25
|
+
return plugin.exec(value);
|
|
26
|
+
}
|
|
27
|
+
return {
|
|
28
|
+
ok: false
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
function getNestedValue(target, segments) {
|
|
32
|
+
return segments.reduce((acc, key) => {
|
|
33
|
+
if (acc === void 0) {
|
|
34
|
+
return void 0;
|
|
35
|
+
}
|
|
36
|
+
return acc[key];
|
|
37
|
+
}, target);
|
|
38
|
+
}
|
|
39
|
+
function setValueAtPath(obj, path2, value) {
|
|
40
|
+
if (path2 === "") {
|
|
41
|
+
throw new Error("Cannot set value at root ('') pointer");
|
|
42
|
+
}
|
|
43
|
+
const parts = getSegmentsFromPath(path2);
|
|
44
|
+
let current = obj;
|
|
45
|
+
for (let i = 0; i < parts.length; i++) {
|
|
46
|
+
const key = parts[i];
|
|
47
|
+
const isLast = i === parts.length - 1;
|
|
48
|
+
const nextKey = parts[i + 1];
|
|
49
|
+
const shouldBeArray = /^\d+$/.test(nextKey ?? "");
|
|
50
|
+
if (isLast) {
|
|
51
|
+
current[key] = value;
|
|
52
|
+
} else {
|
|
53
|
+
if (!(key in current) || typeof current[key] !== "object") {
|
|
54
|
+
current[key] = shouldBeArray ? [] : {};
|
|
55
|
+
}
|
|
56
|
+
current = current[key];
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
function resolveReferencePath(base, relativePath) {
|
|
61
|
+
if (isRemoteUrl(relativePath)) {
|
|
62
|
+
return relativePath;
|
|
63
|
+
}
|
|
64
|
+
if (isRemoteUrl(base)) {
|
|
65
|
+
const url = new URL(base);
|
|
66
|
+
const mergedPath = path.join(path.dirname(url.pathname), relativePath);
|
|
67
|
+
return new URL(mergedPath, base).toString();
|
|
68
|
+
}
|
|
69
|
+
return path.join(path.dirname(base), relativePath);
|
|
70
|
+
}
|
|
71
|
+
function prefixInternalRef(input, prefix) {
|
|
72
|
+
if (!isLocalRef(input)) {
|
|
73
|
+
throw "Please provide an internal ref";
|
|
74
|
+
}
|
|
75
|
+
return `#/${prefix.map(escapeJsonPointer).join("/")}${input.substring(1)}`;
|
|
76
|
+
}
|
|
77
|
+
function prefixInternalRefRecursive(input, prefix) {
|
|
78
|
+
if (!isObject(input)) {
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
Object.values(input).forEach((el) => prefixInternalRefRecursive(el, prefix));
|
|
82
|
+
if (typeof input === "object" && "$ref" in input && typeof input["$ref"] === "string") {
|
|
83
|
+
const ref = input["$ref"];
|
|
84
|
+
if (!isLocalRef(ref)) {
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
input["$ref"] = prefixInternalRef(ref, prefix);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
const resolveAndCopyReferences = (targetDocument, sourceDocument, referencePath, externalRefsKey, documentKey, processedNodes = /* @__PURE__ */ new Set()) => {
|
|
91
|
+
const referencedValue = getNestedValue(sourceDocument, getSegmentsFromPath(referencePath));
|
|
92
|
+
if (processedNodes.has(referencedValue)) {
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
processedNodes.add(referencedValue);
|
|
96
|
+
setValueAtPath(targetDocument, referencePath, referencedValue);
|
|
97
|
+
const traverse = (node) => {
|
|
98
|
+
if (!node || typeof node !== "object") {
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
if ("$ref" in node && typeof node["$ref"] === "string") {
|
|
102
|
+
if (node["$ref"].startsWith(`#/${externalRefsKey}/${escapeJsonPointer(documentKey)}`)) {
|
|
103
|
+
resolveAndCopyReferences(
|
|
104
|
+
targetDocument,
|
|
105
|
+
sourceDocument,
|
|
106
|
+
node["$ref"].substring(1),
|
|
107
|
+
documentKey,
|
|
108
|
+
externalRefsKey,
|
|
109
|
+
processedNodes
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
for (const value of Object.values(node)) {
|
|
114
|
+
traverse(value);
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
traverse(referencedValue);
|
|
118
|
+
};
|
|
119
|
+
const extensions = {
|
|
120
|
+
/**
|
|
121
|
+
* Custom OpenAPI extension key used to store external references.
|
|
122
|
+
* This key will contain all bundled external documents.
|
|
123
|
+
* The x-ext key is used to maintain a clean separation between the main
|
|
124
|
+
* OpenAPI document and its bundled external references.
|
|
125
|
+
*/
|
|
126
|
+
externalDocuments: "x-ext",
|
|
127
|
+
/**
|
|
128
|
+
* Custom OpenAPI extension key used to maintain a mapping between
|
|
129
|
+
* hashed keys and their original URLs in x-ext.
|
|
130
|
+
* This mapping is essential for tracking the source of bundled references
|
|
131
|
+
*/
|
|
132
|
+
externalDocumentsMappings: "x-ext-urls"
|
|
133
|
+
};
|
|
134
|
+
async function bundle(input, config) {
|
|
135
|
+
const cache = config.cache ?? /* @__PURE__ */ new Map();
|
|
136
|
+
const resolveInput = async () => {
|
|
137
|
+
if (typeof input !== "string") {
|
|
138
|
+
return input;
|
|
139
|
+
}
|
|
140
|
+
const result = await resolveContents(input, config.plugins);
|
|
141
|
+
if (result.ok && typeof result.data === "object") {
|
|
142
|
+
return result.data;
|
|
143
|
+
}
|
|
144
|
+
throw new Error(
|
|
145
|
+
"Failed to resolve input: Please provide a valid string value or pass a loader to process the input"
|
|
146
|
+
);
|
|
147
|
+
};
|
|
148
|
+
const rawSpecification = await resolveInput();
|
|
149
|
+
const documentRoot = config.root ?? rawSpecification;
|
|
150
|
+
const isPartialBundling = config.root !== void 0 && config.root !== rawSpecification || config.depth !== void 0;
|
|
151
|
+
const processedNodes = config.visitedNodes ?? /* @__PURE__ */ new Set();
|
|
152
|
+
const defaultOrigin = () => {
|
|
153
|
+
if (typeof input !== "string") {
|
|
154
|
+
return "";
|
|
155
|
+
}
|
|
156
|
+
if (isRemoteUrl(input) || isFilePath(input)) {
|
|
157
|
+
return input;
|
|
158
|
+
}
|
|
159
|
+
return "";
|
|
160
|
+
};
|
|
161
|
+
if (documentRoot[extensions.externalDocumentsMappings] === void 0) {
|
|
162
|
+
documentRoot[extensions.externalDocumentsMappings] = {};
|
|
163
|
+
}
|
|
164
|
+
const { generate } = uniqueValueGeneratorFactory(
|
|
165
|
+
config.compress ?? getHash,
|
|
166
|
+
documentRoot[extensions.externalDocumentsMappings]
|
|
167
|
+
);
|
|
168
|
+
const bundler = async (root, origin = defaultOrigin(), isChunkParent = false, depth = 0) => {
|
|
169
|
+
if (config.depth !== void 0 && depth > config.depth) {
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
if (!isObject(root) && !Array.isArray(root)) {
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
if (processedNodes.has(root)) {
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
processedNodes.add(root);
|
|
179
|
+
if (typeof root === "object" && "$ref" in root && typeof root["$ref"] === "string") {
|
|
180
|
+
const ref = root["$ref"];
|
|
181
|
+
const isChunk = "$global" in root && typeof root["$global"] === "boolean" && root["$global"];
|
|
182
|
+
if (isLocalRef(ref)) {
|
|
183
|
+
if (isPartialBundling) {
|
|
184
|
+
await bundler(
|
|
185
|
+
getNestedValue(documentRoot, getSegmentsFromPath(ref.substring(1))),
|
|
186
|
+
origin,
|
|
187
|
+
isChunkParent,
|
|
188
|
+
depth + 1
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
const [prefix, path2 = ""] = ref.split("#", 2);
|
|
194
|
+
const resolvedPath = resolveReferencePath(origin, prefix);
|
|
195
|
+
const compressedPath = await generate(resolvedPath);
|
|
196
|
+
const seen = cache.has(resolvedPath);
|
|
197
|
+
if (!seen) {
|
|
198
|
+
cache.set(resolvedPath, resolveContents(resolvedPath, config.plugins));
|
|
199
|
+
}
|
|
200
|
+
config?.hooks?.onResolveStart?.(root);
|
|
201
|
+
const result = await cache.get(resolvedPath);
|
|
202
|
+
if (result.ok) {
|
|
203
|
+
if (!seen) {
|
|
204
|
+
if (!isChunk) {
|
|
205
|
+
prefixInternalRefRecursive(result.data, [extensions.externalDocuments, compressedPath]);
|
|
206
|
+
}
|
|
207
|
+
await bundler(result.data, isChunk ? origin : resolvedPath, isChunk, depth + 1);
|
|
208
|
+
setValueAtPath(
|
|
209
|
+
documentRoot,
|
|
210
|
+
`/${extensions.externalDocumentsMappings}/${escapeJsonPointer(compressedPath)}`,
|
|
211
|
+
resolvedPath
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
if (config.treeShake === true) {
|
|
215
|
+
resolveAndCopyReferences(
|
|
216
|
+
documentRoot,
|
|
217
|
+
{ [extensions.externalDocuments]: { [compressedPath]: result.data } },
|
|
218
|
+
prefixInternalRef(`#${path2}`, [extensions.externalDocuments, compressedPath]).substring(1),
|
|
219
|
+
extensions.externalDocuments,
|
|
220
|
+
compressedPath
|
|
221
|
+
);
|
|
222
|
+
} else if (!seen) {
|
|
223
|
+
setValueAtPath(documentRoot, `/${extensions.externalDocuments}/${compressedPath}`, result.data);
|
|
224
|
+
}
|
|
225
|
+
root.$ref = prefixInternalRef(`#${path2}`, [extensions.externalDocuments, compressedPath]);
|
|
226
|
+
config?.hooks?.onResolveSuccess?.(root);
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
config?.hooks?.onResolveError?.(root);
|
|
230
|
+
return console.warn(
|
|
231
|
+
`Failed to resolve external reference "${resolvedPath}". The reference may be invalid, inaccessible, or missing a loader for this type of reference.`
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
await Promise.all(
|
|
235
|
+
Object.entries(root).map(async ([key, value]) => {
|
|
236
|
+
if (key === extensions.externalDocuments) {
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
await bundler(value, origin, isChunkParent, depth + 1);
|
|
240
|
+
})
|
|
241
|
+
);
|
|
242
|
+
};
|
|
243
|
+
await bundler(rawSpecification);
|
|
244
|
+
if (!config.urlMap && !isPartialBundling) {
|
|
245
|
+
delete documentRoot[extensions.externalDocumentsMappings];
|
|
246
|
+
}
|
|
247
|
+
return rawSpecification;
|
|
248
|
+
}
|
|
249
|
+
export {
|
|
250
|
+
bundle,
|
|
251
|
+
getNestedValue,
|
|
252
|
+
isFilePath,
|
|
253
|
+
isLocalRef,
|
|
254
|
+
isRemoteUrl,
|
|
255
|
+
prefixInternalRef,
|
|
256
|
+
prefixInternalRefRecursive,
|
|
257
|
+
setValueAtPath
|
|
258
|
+
};
|
|
259
|
+
//# sourceMappingURL=bundle.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/bundle/bundle.ts"],
|
|
4
|
+
"sourcesContent": ["import type { UnknownObject } from '@/types'\n\nimport { escapeJsonPointer } from '../utils/escape-json-pointer'\nimport path from '@/polyfills/path'\nimport { getSegmentsFromPath } from '../utils/get-segments-from-path'\nimport { isObject } from '../utils/is-object'\nimport { isYaml } from '../utils/is-yaml'\nimport { isJsonObject } from '../utils/is-json-object'\nimport { getHash, uniqueValueGeneratorFactory } from './value-generator'\n\n/**\n * Checks if a string is a remote URL (starts with http:// or https://)\n * @param value - The URL string to check\n * @returns true if the string is a remote URL, false otherwise\n * @example\n * ```ts\n * isRemoteUrl('https://example.com/schema.json') // true\n * isRemoteUrl('http://api.example.com/schemas/user.json') // true\n * isRemoteUrl('#/components/schemas/User') // false\n * isRemoteUrl('./local-schema.json') // false\n * ```\n */\nexport function isRemoteUrl(value: string) {\n try {\n const url = new URL(value)\n return url.protocol === 'http:' || url.protocol === 'https:'\n } catch {\n return false\n }\n}\n\n/**\n * Checks if a string represents a file path by ensuring it's not a remote URL,\n * YAML content, or JSON content.\n *\n * @param value - The string to check\n * @returns true if the string appears to be a file path, false otherwise\n * @example\n * ```ts\n * isFilePath('./schemas/user.json') // true\n * isFilePath('https://example.com/schema.json') // false\n * isFilePath('{\"type\": \"object\"}') // false\n * isFilePath('type: object') // false\n * ```\n */\nexport function isFilePath(value: string) {\n return !isRemoteUrl(value) && !isYaml(value) && !isJsonObject(value)\n}\n\n/**\n * Checks if a string is a local reference (starts with #)\n * @param value - The reference string to check\n * @returns true if the string is a local reference, false otherwise\n * @example\n * ```ts\n * isLocalRef('#/components/schemas/User') // true\n * isLocalRef('https://example.com/schema.json') // false\n * isLocalRef('./local-schema.json') // false\n * ```\n */\nexport function isLocalRef(value: string): boolean {\n return value.startsWith('#')\n}\n\nexport type ResolveResult = { ok: true; data: unknown } | { ok: false }\n\n/**\n * Resolves a string by finding and executing the appropriate plugin.\n * @param value - The string to resolve (URL, file path, etc)\n * @param plugins - Array of plugins that can handle different types of strings\n * @returns A promise that resolves to either the content or an error result\n * @example\n * // Using a URL plugin\n * await resolveContents('https://example.com/schema.json', [urlPlugin])\n * // Using a file plugin\n * await resolveContents('./schemas/user.json', [filePlugin])\n * // No matching plugin returns { ok: false }\n * await resolveContents('#/components/schemas/User', [urlPlugin, filePlugin])\n */\nasync function resolveContents(value: string, plugins: Plugin[]): Promise<ResolveResult> {\n const plugin = plugins.find((p) => p.validate(value))\n\n if (plugin) {\n return plugin.exec(value)\n }\n\n return {\n ok: false,\n }\n}\n\n/**\n * Retrieves a nested value from an object using an array of property segments.\n * @param target - The target object to traverse\n * @param segments - Array of property names representing the path to the desired value\n * @returns The value at the specified path, or undefined if the path doesn't exist\n * @example\n * const obj = { foo: { bar: { baz: 42 } } };\n * getNestedValue(obj, ['foo', 'bar', 'baz']); // returns 42\n */\nexport function getNestedValue(target: Record<string, any>, segments: string[]) {\n return segments.reduce<any>((acc, key) => {\n if (acc === undefined) {\n return undefined\n }\n return acc[key]\n }, target)\n}\n\n/**\n * Sets a value at a specified path in an object, creating intermediate objects/arrays as needed.\n * This function traverses the object structure and creates any missing intermediate objects\n * or arrays based on the path segments. If the next segment is a numeric string, it creates\n * an array instead of an object.\n *\n * \u26A0\uFE0F Warning: Be careful with object keys that look like numbers (e.g. \"123\") as this function\n * will interpret them as array indices and create arrays instead of objects. If you need to\n * use numeric-looking keys, consider prefixing them with a non-numeric character.\n *\n * @param obj - The target object to set the value in\n * @param path - The JSON pointer path where the value should be set\n * @param value - The value to set at the specified path\n * @throws {Error} If attempting to set a value at the root path ('')\n *\n * @example\n * const obj = {}\n * setValueAtPath(obj, '/foo/bar/0', 'value')\n * // Result:\n * // {\n * // foo: {\n * // bar: ['value']\n * // }\n * // }\n *\n * @example\n * const obj = { existing: { path: 'old' } }\n * setValueAtPath(obj, '/existing/path', 'new')\n * // Result:\n * // {\n * // existing: {\n * // path: 'new'\n * // }\n * // }\n *\n * @example\n * // \u26A0\uFE0F Warning: This will create an array instead of an object with key \"123\"\n * setValueAtPath(obj, '/foo/123/bar', 'value')\n * // Result:\n * // {\n * // foo: [\n * // undefined,\n * // undefined,\n * // undefined,\n * // { bar: 'value' }\n * // ]\n * // }\n */\nexport function setValueAtPath(obj: any, path: string, value: any): void {\n if (path === '') {\n throw new Error(\"Cannot set value at root ('') pointer\")\n }\n\n const parts = getSegmentsFromPath(path)\n\n let current = obj\n\n for (let i = 0; i < parts.length; i++) {\n const key = parts[i]\n const isLast = i === parts.length - 1\n\n const nextKey = parts[i + 1]\n const shouldBeArray = /^\\d+$/.test(nextKey ?? '')\n\n if (isLast) {\n current[key] = value\n } else {\n if (!(key in current) || typeof current[key] !== 'object') {\n current[key] = shouldBeArray ? [] : {}\n }\n current = current[key]\n }\n }\n}\n\n/**\n * Resolves a reference path by combining a base path with a relative path.\n * Handles both remote URLs and local file paths.\n *\n * @param base - The base path (can be a URL or local file path)\n * @param relativePath - The relative path to resolve against the base\n * @returns The resolved absolute path\n * @example\n * // Resolve remote URL\n * resolveReferencePath('https://example.com/api/schema.json', 'user.json')\n * // Returns: 'https://example.com/api/user.json'\n *\n * // Resolve local path\n * resolveReferencePath('/path/to/schema.json', 'user.json')\n * // Returns: '/path/to/user.json'\n */\nfunction resolveReferencePath(base: string, relativePath: string) {\n if (isRemoteUrl(relativePath)) {\n return relativePath\n }\n\n if (isRemoteUrl(base)) {\n const url = new URL(base)\n\n const mergedPath = path.join(path.dirname(url.pathname), relativePath)\n return new URL(mergedPath, base).toString()\n }\n\n return path.join(path.dirname(base), relativePath)\n}\n\n/**\n * Prefixes an internal JSON reference with a given path prefix.\n * Takes a local reference (starting with #) and prepends the provided prefix segments.\n *\n * @param input - The internal reference string to prefix (must start with #)\n * @param prefix - Array of path segments to prepend to the reference\n * @returns The prefixed reference string\n * @throws Error if input is not a local reference\n * @example\n * prefixInternalRef('#/components/schemas/User', ['definitions'])\n * // Returns: '#/definitions/components/schemas/User'\n */\nexport function prefixInternalRef(input: string, prefix: string[]) {\n if (!isLocalRef(input)) {\n throw 'Please provide an internal ref'\n }\n\n return `#/${prefix.map(escapeJsonPointer).join('/')}${input.substring(1)}`\n}\n\n/**\n * Updates internal references in an object by adding a prefix to their paths.\n * Recursively traverses the input object and modifies any local $ref references\n * by prepending the given prefix to their paths. This is used when embedding external\n * documents to maintain correct reference paths relative to the main document.\n *\n * @param input - The object to update references in\n * @param prefix - Array of path segments to prepend to internal reference paths\n * @returns void\n * @example\n * ```ts\n * const input = {\n * foo: {\n * $ref: '#/components/schemas/User'\n * }\n * }\n * prefixInternalRefRecursive(input, ['definitions'])\n * // Result:\n * // {\n * // foo: {\n * // $ref: '#/definitions/components/schemas/User'\n * // }\n * // }\n * ```\n */\nexport function prefixInternalRefRecursive(input: unknown, prefix: string[]) {\n if (!isObject(input)) {\n return\n }\n\n Object.values(input).forEach((el) => prefixInternalRefRecursive(el, prefix))\n\n if (typeof input === 'object' && '$ref' in input && typeof input['$ref'] === 'string') {\n const ref = input['$ref']\n\n if (!isLocalRef(ref)) {\n return\n }\n\n input['$ref'] = prefixInternalRef(ref, prefix)\n }\n}\n\n/**\n * Resolves and copies referenced values from a source document to a target document.\n * This function traverses the document and copies referenced values to the target document,\n * while tracking processed references to avoid duplicates. It only processes references\n * that belong to the same external document.\n *\n * @param targetDocument - The document to copy referenced values to\n * @param sourceDocument - The source document containing the references\n * @param referencePath - The JSON pointer path to the reference\n * @param externalRefsKey - The key used for external references (e.g. 'x-ext')\n * @param documentKey - The key identifying the external document\n * @param processedNodes - Set of already processed nodes to prevent duplicates\n * @example\n * ```ts\n * const source = {\n * components: {\n * schemas: {\n * User: {\n * $ref: '#/x-ext/users~1schema/definitions/Person'\n * }\n * }\n * }\n * }\n *\n * const target = {}\n * resolveAndCopyReferences(\n * target,\n * source,\n * '/components/schemas/User',\n * 'x-ext',\n * 'users/schema'\n * )\n * // Result: target will contain the User schema with resolved references\n * ```\n */\nconst resolveAndCopyReferences = (\n targetDocument: unknown,\n sourceDocument: unknown,\n referencePath: string,\n externalRefsKey: string,\n documentKey: string,\n processedNodes = new Set(),\n) => {\n const referencedValue = getNestedValue(sourceDocument, getSegmentsFromPath(referencePath))\n\n if (processedNodes.has(referencedValue)) {\n return\n }\n processedNodes.add(referencedValue)\n\n setValueAtPath(targetDocument, referencePath, referencedValue)\n\n // Do the same for each local ref\n const traverse = (node: unknown) => {\n if (!node || typeof node !== 'object') {\n return\n }\n\n if ('$ref' in node && typeof node['$ref'] === 'string') {\n // We only process references from the same external document because:\n // 1. Other documents will be handled in separate recursive branches\n // 2. The source document only contains the current document's content\n // This prevents undefined behavior and maintains proper document boundaries\n if (node['$ref'].startsWith(`#/${externalRefsKey}/${escapeJsonPointer(documentKey)}`)) {\n resolveAndCopyReferences(\n targetDocument,\n sourceDocument,\n node['$ref'].substring(1),\n documentKey,\n externalRefsKey,\n processedNodes,\n )\n }\n }\n\n for (const value of Object.values(node)) {\n traverse(value)\n }\n }\n\n traverse(referencedValue)\n}\n\n/**\n * Represents a plugin that handles resolving references from external sources.\n * Plugins are responsible for fetching and processing data from different sources\n * like URLs or the filesystem. Each plugin must implement validation to determine\n * if it can handle a specific reference, and an execution function to perform\n * the actual resolution.\n *\n * @property validate - Determines if this plugin can handle the given reference\n * @property exec - Fetches and processes the reference, returning the resolved data\n */\nexport type Plugin = {\n // Determines if this plugin can handle the given reference value\n validate: (value: string) => boolean\n // Fetches and processes the reference, returning the resolved data\n exec: (value: string) => Promise<ResolveResult>\n}\n\n/**\n * Configuration options for the bundler.\n * Controls how external references are resolved and processed during bundling.\n */\ntype Config = {\n /**\n * Array of plugins that handle resolving references from different sources.\n * Each plugin is responsible for fetching and processing data from specific sources\n * like URLs or the filesystem.\n */\n plugins: Plugin[]\n\n /**\n * Optional root object that serves as the base document when bundling a subpart.\n * This allows resolving references relative to the root document's location,\n * ensuring proper path resolution for nested references.\n */\n root?: UnknownObject\n\n /**\n * Optional maximum depth for reference resolution.\n * Limits how deeply the bundler will follow and resolve nested $ref pointers.\n * Useful for preventing infinite recursion or excessive resource usage.\n */\n depth?: number\n\n /**\n * Optional cache to store promises of resolved references.\n * Helps avoid duplicate fetches/reads of the same resource by storing\n * the resolution promises for reuse.\n */\n cache?: Map<string, Promise<ResolveResult>>\n\n /**\n * Cache of visited nodes during partial bundling.\n * Used to prevent re-bundling the same tree multiple times when doing partial bundling,\n * improving performance by avoiding redundant processing of already bundled sections.\n */\n visitedNodes?: Set<unknown>\n\n /**\n * Enable tree shaking to optimize the bundle size.\n * When enabled, only the parts of external documents that are actually referenced\n * will be included in the final bundle.\n */\n treeShake: boolean\n\n /**\n * Optional flag to generate a URL map.\n * When enabled, tracks the original source URLs of bundled references\n * in an x-ext-urls section for reference mapping.\n */\n urlMap?: boolean\n\n /**\n * Optional function to compress input URLs or file paths before bundling.\n * Returns either a Promise resolving to the compressed string or the compressed string directly.\n */\n compress?: (value: string) => Promise<string> | string\n\n /**\n * Optional hooks to monitor the bundler's lifecycle.\n * Allows tracking the progress and status of reference resolution.\n */\n hooks?: Partial<{\n /** Called when starting to resolve a reference */\n onResolveStart: (node: Record<string, unknown> & Record<'$ref', unknown>) => void\n /** Called when a reference resolution fails */\n onResolveError: (node: Record<string, unknown> & Record<'$ref', unknown>) => void\n /** Called when a reference is successfully resolved */\n onResolveSuccess: (node: Record<string, unknown> & Record<'$ref', unknown>) => void\n }>\n}\n\n/**\n * Extension keys used for bundling external references in OpenAPI documents.\n * These custom extensions help maintain the structure and traceability of bundled documents.\n */\nconst extensions = {\n /**\n * Custom OpenAPI extension key used to store external references.\n * This key will contain all bundled external documents.\n * The x-ext key is used to maintain a clean separation between the main\n * OpenAPI document and its bundled external references.\n */\n externalDocuments: 'x-ext',\n\n /**\n * Custom OpenAPI extension key used to maintain a mapping between\n * hashed keys and their original URLs in x-ext.\n * This mapping is essential for tracking the source of bundled references\n */\n externalDocumentsMappings: 'x-ext-urls',\n} as const\n\n/**\n * Bundles an OpenAPI specification by resolving all external references.\n * This function traverses the input object recursively and embeds external $ref\n * references into an x-ext section. External references can be URLs or local files.\n * The original $refs are updated to point to their embedded content in the x-ext section.\n * If the input is an object, it will be modified in place by adding an x-ext\n * property to store resolved external references.\n *\n * @param input - The OpenAPI specification to bundle. Can be either an object or string.\n * If a string is provided, it will be resolved using the provided plugins.\n * If no plugin can process the input, the onReferenceError hook will be invoked\n * and an error will be emitted to the console.\n * @param config - Configuration object containing plugins and options for bundling OpenAPI specifications\n * @returns A promise that resolves to the bundled specification with all references embedded\n * @example\n * // Example with object input\n * const spec = {\n * paths: {\n * '/users': {\n * $ref: 'https://example.com/schemas/users.yaml'\n * }\n * }\n * }\n *\n * const bundled = await bundle(spec, {\n * plugins: [fetchUrls()],\n * treeShake: true,\n * urlMap: true,\n * hooks: {\n * onResolveStart: (ref) => console.log('Resolving:', ref.$ref),\n * onResolveSuccess: (ref) => console.log('Resolved:', ref.$ref),\n * onResolveError: (ref) => console.log('Failed to resolve:', ref.$ref)\n * }\n * })\n * // Result:\n * // {\n * // paths: {\n * // '/users': {\n * // $ref: '#/x-ext/abc123'\n * // }\n * // },\n * // 'x-ext': {\n * // 'abc123': {\n * // // Resolved content from users.yaml\n * // }\n * // },\n * // 'x-ext-urls': {\n * // 'https://example.com/schemas/users.yaml': 'abc123'\n * // }\n * // }\n *\n * // Example with URL input\n * const bundledFromUrl = await bundle('https://example.com/openapi.yaml', {\n * plugins: [fetchUrls()],\n * treeShake: true,\n * urlMap: true,\n * hooks: {\n * onResolveStart: (ref) => console.log('Resolving:', ref.$ref),\n * onResolveSuccess: (ref) => console.log('Resolved:', ref.$ref),\n * onResolveError: (ref) => console.log('Failed to resolve:', ref.$ref)\n * }\n * })\n * // The function will first fetch the OpenAPI spec from the URL,\n * // then bundle all its external references into the x-ext section\n */\nexport async function bundle(input: UnknownObject | string, config: Config) {\n // Cache for storing promises of resolved external references (URLs and local files)\n // to avoid duplicate fetches/reads of the same resource\n const cache = config.cache ?? new Map<string, Promise<ResolveResult>>()\n\n /**\n * Resolves the input value by either returning it directly if it's not a string,\n * or attempting to resolve it using the provided plugins if it is a string.\n * @returns The resolved input data or throws an error if resolution fails\n */\n const resolveInput = async () => {\n if (typeof input !== 'string') {\n return input\n }\n const result = await resolveContents(input, config.plugins)\n\n if (result.ok && typeof result.data === 'object') {\n return result.data\n }\n\n throw new Error(\n 'Failed to resolve input: Please provide a valid string value or pass a loader to process the input',\n )\n }\n\n // Resolve the input specification, which could be either a direct object or a string URL/path\n const rawSpecification = await resolveInput()\n\n // Document root used to write all external documents\n // We need this when we want to do a partial bundle of a document\n const documentRoot = config.root ?? rawSpecification\n\n // Determines if the bundling operation is partial.\n // Partial bundling occurs when:\n // - A root document is provided that is different from the raw specification being bundled, or\n // - A maximum depth is specified in the config.\n // In these cases, only a subset of the document may be bundled.\n const isPartialBundling =\n (config.root !== undefined && config.root !== rawSpecification) || config.depth !== undefined\n\n // Set of nodes that have already been processed during bundling to prevent duplicate processing\n const processedNodes = config.visitedNodes ?? new Set()\n\n // Determines the initial origin path for the bundler based on the input type.\n // For string inputs that are URLs or file paths, uses the input as the origin.\n // For non-string inputs or other string types, returns an empty string.\n const defaultOrigin = () => {\n if (typeof input !== 'string') {\n return ''\n }\n\n if (isRemoteUrl(input) || isFilePath(input)) {\n return input\n }\n\n return ''\n }\n\n // Create the cache to store the compressed values to their map values\n if (documentRoot[extensions.externalDocumentsMappings] === undefined) {\n documentRoot[extensions.externalDocumentsMappings] = {}\n }\n const { generate } = uniqueValueGeneratorFactory(\n config.compress ?? getHash,\n documentRoot[extensions.externalDocumentsMappings],\n )\n\n const bundler = async (root: unknown, origin: string = defaultOrigin(), isChunkParent = false, depth = 0) => {\n // If a maximum depth is set in the config, stop bundling when the current depth reaches or exceeds it\n if (config.depth !== undefined && depth > config.depth) {\n return\n }\n\n if (!isObject(root) && !Array.isArray(root)) {\n return\n }\n\n // Skip if this node has already been processed to prevent infinite recursion\n // and duplicate processing of the same node\n if (processedNodes.has(root)) {\n return\n }\n // Mark this node as processed before continuing\n processedNodes.add(root)\n\n if (typeof root === 'object' && '$ref' in root && typeof root['$ref'] === 'string') {\n const ref = root['$ref']\n const isChunk = '$global' in root && typeof root['$global'] === 'boolean' && root['$global']\n\n if (isLocalRef(ref)) {\n if (isPartialBundling) {\n // When doing partial bundling, we need to recursively bundle all dependencies\n // referenced by this local reference to ensure the partial bundle is complete.\n // This includes not just the direct reference but also all its dependencies,\n // creating a complete and self-contained partial bundle.\n await bundler(\n getNestedValue(documentRoot, getSegmentsFromPath(ref.substring(1))),\n origin,\n isChunkParent,\n depth + 1,\n )\n }\n return\n }\n\n const [prefix, path = ''] = ref.split('#', 2)\n\n // Combine the current origin with the new path to resolve relative references\n // correctly within the context of the external file being processed\n const resolvedPath = resolveReferencePath(origin, prefix)\n\n // Generate a unique compressed path for the external document\n // This is used as a key to store and reference the bundled external document\n // The compression helps reduce the overall file size of the bundled document\n const compressedPath = await generate(resolvedPath)\n\n const seen = cache.has(resolvedPath)\n\n if (!seen) {\n cache.set(resolvedPath, resolveContents(resolvedPath, config.plugins))\n }\n\n config?.hooks?.onResolveStart?.(root)\n\n // Resolve the remote document\n const result = await cache.get(resolvedPath)\n\n if (result.ok) {\n // Process the result only once to avoid duplicate processing and prevent multiple prefixing\n // of internal references, which would corrupt the reference paths\n if (!seen) {\n // Skip prefixing for chunks since they are meant to be self-contained and their\n // internal references should remain relative to their original location. Chunks\n // are typically used for modular components that need to maintain their own\n // reference context without being affected by the main document's structure.\n if (!isChunk) {\n // Update internal references in the resolved document to use the correct base path.\n // When we embed external documents, their internal references need to be updated to\n // maintain the correct path context relative to the main document. This is crucial\n // because internal references in the external document are relative to its original\n // location, but when embedded, they need to be relative to their new location in\n // the main document's x-ext section. Without this update, internal references\n // would point to incorrect locations and break the document structure.\n prefixInternalRefRecursive(result.data, [extensions.externalDocuments, compressedPath])\n }\n\n // Recursively process the resolved content\n // to handle any nested references it may contain. We pass the resolvedPath as the new origin\n // to ensure any relative references within this content are resolved correctly relative to\n // their new location in the bundled document.\n await bundler(result.data, isChunk ? origin : resolvedPath, isChunk, depth + 1)\n\n // Store the mapping between hashed keys and original URLs in x-ext-urls\n // This allows tracking which external URLs were bundled and their corresponding locations\n setValueAtPath(\n documentRoot,\n `/${extensions.externalDocumentsMappings}/${escapeJsonPointer(compressedPath)}`,\n resolvedPath,\n )\n }\n\n if (config.treeShake === true) {\n // Store only the subtree that is actually used\n // This optimizes the bundle size by only including the parts of the external document\n // that are referenced, rather than the entire document\n resolveAndCopyReferences(\n documentRoot,\n { [extensions.externalDocuments]: { [compressedPath]: result.data } },\n prefixInternalRef(`#${path}`, [extensions.externalDocuments, compressedPath]).substring(1),\n extensions.externalDocuments,\n compressedPath,\n )\n } else if (!seen) {\n // Store the external document in the main document's x-ext key\n // When tree shaking is disabled, we include the entire external document\n // This preserves all content and is faster since we don't need to analyze and copy\n // specific parts. This approach is ideal when storing the result in memory\n // as it avoids the overhead of tree shaking operations\n setValueAtPath(documentRoot, `/${extensions.externalDocuments}/${compressedPath}`, result.data)\n }\n\n // Update the $ref to point to the embedded document in x-ext\n // This is necessary because we need to maintain the correct path context\n // for the embedded document while preserving its internal structure\n root.$ref = prefixInternalRef(`#${path}`, [extensions.externalDocuments, compressedPath])\n config?.hooks?.onResolveSuccess?.(root)\n return\n }\n\n config?.hooks?.onResolveError?.(root)\n return console.warn(\n `Failed to resolve external reference \"${resolvedPath}\". The reference may be invalid, inaccessible, or missing a loader for this type of reference.`,\n )\n }\n\n // Recursively process all child objects to handle nested references\n // This ensures we catch and resolve any $refs that exist deeper in the object tree\n // We skip EXTERNAL_KEY to avoid processing already bundled content\n await Promise.all(\n Object.entries(root).map(async ([key, value]) => {\n if (key === extensions.externalDocuments) {\n return\n }\n\n await bundler(value, origin, isChunkParent, depth + 1)\n }),\n )\n }\n\n await bundler(rawSpecification)\n\n // Keep urlMappings when doing partial bundling to track hash values and handle collisions\n // For full bundling without urlMap config, remove the mappings to clean up the output\n if (!config.urlMap && !isPartialBundling) {\n // Remove the external document mappings from the output when doing a full bundle without urlMap config\n delete documentRoot[extensions.externalDocumentsMappings]\n }\n\n return rawSpecification\n}\n"],
|
|
5
|
+
"mappings": "AAEA,SAAS,yBAAyB;AAClC,OAAO,UAAU;AACjB,SAAS,2BAA2B;AACpC,SAAS,gBAAgB;AACzB,SAAS,cAAc;AACvB,SAAS,oBAAoB;AAC7B,SAAS,SAAS,mCAAmC;AAc9C,SAAS,YAAY,OAAe;AACzC,MAAI;AACF,UAAM,MAAM,IAAI,IAAI,KAAK;AACzB,WAAO,IAAI,aAAa,WAAW,IAAI,aAAa;AAAA,EACtD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAgBO,SAAS,WAAW,OAAe;AACxC,SAAO,CAAC,YAAY,KAAK,KAAK,CAAC,OAAO,KAAK,KAAK,CAAC,aAAa,KAAK;AACrE;AAaO,SAAS,WAAW,OAAwB;AACjD,SAAO,MAAM,WAAW,GAAG;AAC7B;AAiBA,eAAe,gBAAgB,OAAe,SAA2C;AACvF,QAAM,SAAS,QAAQ,KAAK,CAAC,MAAM,EAAE,SAAS,KAAK,CAAC;AAEpD,MAAI,QAAQ;AACV,WAAO,OAAO,KAAK,KAAK;AAAA,EAC1B;AAEA,SAAO;AAAA,IACL,IAAI;AAAA,EACN;AACF;AAWO,SAAS,eAAe,QAA6B,UAAoB;AAC9E,SAAO,SAAS,OAAY,CAAC,KAAK,QAAQ;AACxC,QAAI,QAAQ,QAAW;AACrB,aAAO;AAAA,IACT;AACA,WAAO,IAAI,GAAG;AAAA,EAChB,GAAG,MAAM;AACX;AAkDO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ACF,WAAW,CAAC,MAAM;AAMhB,yBAAe,cAAc,IAAI,WAAW,iBAAiB,IAAI,cAAc,IAAI,OAAO,IAAI;AAAA,QAChG;AAKA,aAAK,OAAO,kBAAkB,IAAIA,KAAI,IAAI,CAAC,WAAW,mBAAmB,cAAc,CAAC;AACxF,gBAAQ,OAAO,mBAAmB,IAAI;AACtC;AAAA,MACF;AAEA,cAAQ,OAAO,iBAAiB,IAAI;AACpC,aAAO,QAAQ;AAAA,QACb,yCAAyC,YAAY;AAAA,MACvD;AAAA,IACF;AAKA,UAAM,QAAQ;AAAA,MACZ,OAAO,QAAQ,IAAI,EAAE,IAAI,OAAO,CAAC,KAAK,KAAK,MAAM;AAC/C,YAAI,QAAQ,WAAW,mBAAmB;AACxC;AAAA,QACF;AAEA,cAAM,QAAQ,OAAO,QAAQ,eAAe,QAAQ,CAAC;AAAA,MACvD,CAAC;AAAA,IACH;AAAA,EACF;AAEA,QAAM,QAAQ,gBAAgB;AAI9B,MAAI,CAAC,OAAO,UAAU,CAAC,mBAAmB;AAExC,WAAO,aAAa,WAAW,yBAAyB;AAAA,EAC1D;AAEA,SAAO;AACT;",
|
|
6
|
+
"names": ["path"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Creates a function that limits the number of concurrent executions of async functions.
|
|
3
|
+
*
|
|
4
|
+
* @param maxConcurrent - Maximum number of concurrent executions allowed
|
|
5
|
+
* @returns A function that wraps async functions to limit their concurrent execution
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```ts
|
|
9
|
+
* const limiter = createLimiter(2) // Allow max 2 concurrent executions
|
|
10
|
+
*
|
|
11
|
+
* // These will run with max 2 at a time
|
|
12
|
+
* const results = await Promise.all([
|
|
13
|
+
* limiter(() => fetch('/api/1')),
|
|
14
|
+
* limiter(() => fetch('/api/2')),
|
|
15
|
+
* limiter(() => fetch('/api/3')),
|
|
16
|
+
* limiter(() => fetch('/api/4'))
|
|
17
|
+
* ])
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
export declare function createLimiter(maxConcurrent: number): <T>(fn: () => Promise<T>) => Promise<T>;
|
|
21
|
+
//# sourceMappingURL=create-limiter.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"create-limiter.d.ts","sourceRoot":"","sources":["../../src/bundle/create-limiter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,aAAa,CAAC,aAAa,EAAE,MAAM,IAgB9B,CAAC,MAAM,MAAM,OAAO,CAAC,CAAC,CAAC,KAAG,OAAO,CAAC,CAAC,CAAC,CAgBxD"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
function createLimiter(maxConcurrent) {
|
|
2
|
+
let activeCount = 0;
|
|
3
|
+
const queue = [];
|
|
4
|
+
const next = () => {
|
|
5
|
+
if (queue.length === 0 || activeCount >= maxConcurrent) {
|
|
6
|
+
return;
|
|
7
|
+
}
|
|
8
|
+
const resolve = queue.shift();
|
|
9
|
+
if (resolve) {
|
|
10
|
+
resolve();
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
const run = async (fn) => {
|
|
14
|
+
if (activeCount >= maxConcurrent) {
|
|
15
|
+
await new Promise((resolve) => queue.push(resolve));
|
|
16
|
+
}
|
|
17
|
+
activeCount++;
|
|
18
|
+
try {
|
|
19
|
+
const result = await fn();
|
|
20
|
+
return result;
|
|
21
|
+
} finally {
|
|
22
|
+
activeCount--;
|
|
23
|
+
next();
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
return run;
|
|
27
|
+
}
|
|
28
|
+
export {
|
|
29
|
+
createLimiter
|
|
30
|
+
};
|
|
31
|
+
//# sourceMappingURL=create-limiter.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/bundle/create-limiter.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Creates a function that limits the number of concurrent executions of async functions.\n *\n * @param maxConcurrent - Maximum number of concurrent executions allowed\n * @returns A function that wraps async functions to limit their concurrent execution\n *\n * @example\n * ```ts\n * const limiter = createLimiter(2) // Allow max 2 concurrent executions\n *\n * // These will run with max 2 at a time\n * const results = await Promise.all([\n * limiter(() => fetch('/api/1')),\n * limiter(() => fetch('/api/2')),\n * limiter(() => fetch('/api/3')),\n * limiter(() => fetch('/api/4'))\n * ])\n * ```\n */\nexport function createLimiter(maxConcurrent: number) {\n let activeCount = 0\n const queue: (() => void)[] = []\n\n const next = () => {\n if (queue.length === 0 || activeCount >= maxConcurrent) {\n return\n }\n\n const resolve = queue.shift()\n\n if (resolve) {\n resolve()\n }\n }\n\n const run = async <T>(fn: () => Promise<T>): Promise<T> => {\n if (activeCount >= maxConcurrent) {\n await new Promise<void>((resolve) => queue.push(resolve))\n }\n\n activeCount++\n try {\n const result = await fn()\n return result\n } finally {\n activeCount--\n next()\n }\n }\n\n return run\n}\n"],
|
|
5
|
+
"mappings": "AAmBO,SAAS,cAAc,eAAuB;AACnD,MAAI,cAAc;AAClB,QAAM,QAAwB,CAAC;AAE/B,QAAM,OAAO,MAAM;AACjB,QAAI,MAAM,WAAW,KAAK,eAAe,eAAe;AACtD;AAAA,IACF;AAEA,UAAM,UAAU,MAAM,MAAM;AAE5B,QAAI,SAAS;AACX,cAAQ;AAAA,IACV;AAAA,EACF;AAEA,QAAM,MAAM,OAAU,OAAqC;AACzD,QAAI,eAAe,eAAe;AAChC,YAAM,IAAI,QAAc,CAAC,YAAY,MAAM,KAAK,OAAO,CAAC;AAAA,IAC1D;AAEA;AACA,QAAI;AACF,YAAM,SAAS,MAAM,GAAG;AACxB,aAAO;AAAA,IACT,UAAE;AACA;AACA,WAAK;AAAA,IACP;AAAA,EACF;AAEA,SAAO;AACT;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/bundle/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,KAAK,MAAM,EAAE,KAAK,aAAa,EAAE,MAAM,UAAU,CAAA"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/bundle/index.ts"],
|
|
4
|
+
"sourcesContent": ["// biome-ignore lint/performance/noBarrelFile: <explanation>\nexport { bundle, type Plugin, type ResolveResult } from './bundle'\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,cAA+C;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"browser.d.ts","sourceRoot":"","sources":["../../../src/bundle/plugins/browser.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAA;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAA;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAA"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/bundle/plugins/browser.ts"],
|
|
4
|
+
"sourcesContent": ["// biome-ignore lint/performance/noBarrelFile: <explanation>\nexport { fetchUrls } from './fetch-urls'\nexport { parseJson } from './parse-json'\nexport { parseYaml } from './parse-yaml'\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,iBAAiB;AAC1B,SAAS,iBAAiB;AAC1B,SAAS,iBAAiB;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { Plugin, ResolveResult } from '../../../bundle/index.js';
|
|
2
|
+
type FetchConfig = Partial<{
|
|
3
|
+
headers: {
|
|
4
|
+
headers: HeadersInit;
|
|
5
|
+
domains: string[];
|
|
6
|
+
}[];
|
|
7
|
+
fetch: (input: string | URL | globalThis.Request, init?: RequestInit) => Promise<Response>;
|
|
8
|
+
}>;
|
|
9
|
+
/**
|
|
10
|
+
* Fetches and normalizes data from a remote URL
|
|
11
|
+
* @param url - The URL to fetch data from
|
|
12
|
+
* @returns A promise that resolves to either the normalized data or an error result
|
|
13
|
+
* @example
|
|
14
|
+
* ```ts
|
|
15
|
+
* const result = await fetchUrl('https://api.example.com/data.json')
|
|
16
|
+
* if (result.ok) {
|
|
17
|
+
* console.log(result.data) // The normalized data
|
|
18
|
+
* } else {
|
|
19
|
+
* console.log('Failed to fetch data')
|
|
20
|
+
* }
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
export declare function fetchUrl(url: string, limiter: <T>(fn: () => Promise<T>) => Promise<T>, config?: FetchConfig): Promise<ResolveResult>;
|
|
24
|
+
/**
|
|
25
|
+
* Creates a plugin for handling remote URL references.
|
|
26
|
+
* This plugin validates and fetches data from HTTP/HTTPS URLs.
|
|
27
|
+
*
|
|
28
|
+
* @returns A plugin object with validate and exec functions
|
|
29
|
+
* @example
|
|
30
|
+
* const urlPlugin = fetchUrls()
|
|
31
|
+
* if (urlPlugin.validate('https://example.com/schema.json')) {
|
|
32
|
+
* const result = await urlPlugin.exec('https://example.com/schema.json')
|
|
33
|
+
* }
|
|
34
|
+
*/
|
|
35
|
+
export declare function fetchUrls(config?: FetchConfig & Partial<{
|
|
36
|
+
limit: number | null;
|
|
37
|
+
}>): Plugin;
|
|
38
|
+
export {};
|
|
39
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/bundle/plugins/fetch-urls/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AAGrD,KAAK,WAAW,GAAG,OAAO,CAAC;IACzB,OAAO,EAAE;QAAE,OAAO,EAAE,WAAW,CAAC;QAAC,OAAO,EAAE,MAAM,EAAE,CAAA;KAAE,EAAE,CAAA;IACtD,KAAK,EAAE,CAAC,KAAK,EAAE,MAAM,GAAG,GAAG,GAAG,UAAU,CAAC,OAAO,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAA;CAC3F,CAAC,CAAA;AAcF;;;;;;;;;;;;;GAaG;AACH,wBAAsB,QAAQ,CAC5B,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,EAChD,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,aAAa,CAAC,CAgCxB;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,SAAS,CAAC,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC;IAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CAAC,GAAG,MAAM,CAQ1F"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { normalize } from "../../../utils/normalize.js";
|
|
2
|
+
import { createLimiter } from "../../../bundle/create-limiter.js";
|
|
3
|
+
import { isRemoteUrl } from "../../../bundle/bundle.js";
|
|
4
|
+
const getHost = (url) => {
|
|
5
|
+
try {
|
|
6
|
+
return new URL(url).host;
|
|
7
|
+
} catch {
|
|
8
|
+
return null;
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
async function fetchUrl(url, limiter, config) {
|
|
12
|
+
try {
|
|
13
|
+
const host = getHost(url);
|
|
14
|
+
const headers = config?.headers?.find((a) => a.domains.find((d) => d === host) !== void 0)?.headers;
|
|
15
|
+
const exec = config?.fetch ?? fetch;
|
|
16
|
+
const result = await limiter(
|
|
17
|
+
() => exec(url, {
|
|
18
|
+
headers
|
|
19
|
+
})
|
|
20
|
+
);
|
|
21
|
+
if (result.ok) {
|
|
22
|
+
const body = await result.text();
|
|
23
|
+
return {
|
|
24
|
+
ok: true,
|
|
25
|
+
data: normalize(body)
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
return {
|
|
29
|
+
ok: false
|
|
30
|
+
};
|
|
31
|
+
} catch {
|
|
32
|
+
return {
|
|
33
|
+
ok: false
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function fetchUrls(config) {
|
|
38
|
+
const limiter = config?.limit ? createLimiter(config.limit) : (fn) => fn();
|
|
39
|
+
return {
|
|
40
|
+
validate: isRemoteUrl,
|
|
41
|
+
exec: (value) => fetchUrl(value, limiter, config)
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
export {
|
|
45
|
+
fetchUrl,
|
|
46
|
+
fetchUrls
|
|
47
|
+
};
|
|
48
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/bundle/plugins/fetch-urls/index.ts"],
|
|
4
|
+
"sourcesContent": ["import { normalize } from '@/utils/normalize'\nimport { createLimiter } from '@/bundle/create-limiter'\nimport type { Plugin, ResolveResult } from '@/bundle'\nimport { isRemoteUrl } from '@/bundle/bundle'\n\ntype FetchConfig = Partial<{\n headers: { headers: HeadersInit; domains: string[] }[]\n fetch: (input: string | URL | globalThis.Request, init?: RequestInit) => Promise<Response>\n}>\n\n/**\n * Safely checks for host from a URL\n * Needed because we cannot create a URL from a relative remote URL ex: examples/openapi.json\n */\nconst getHost = (url: string): string | null => {\n try {\n return new URL(url).host\n } catch {\n return null\n }\n}\n\n/**\n * Fetches and normalizes data from a remote URL\n * @param url - The URL to fetch data from\n * @returns A promise that resolves to either the normalized data or an error result\n * @example\n * ```ts\n * const result = await fetchUrl('https://api.example.com/data.json')\n * if (result.ok) {\n * console.log(result.data) // The normalized data\n * } else {\n * console.log('Failed to fetch data')\n * }\n * ```\n */\nexport async function fetchUrl(\n url: string,\n limiter: <T>(fn: () => Promise<T>) => Promise<T>,\n config?: FetchConfig,\n): Promise<ResolveResult> {\n try {\n const host = getHost(url)\n\n // Get the headers that match the domain\n const headers = config?.headers?.find((a) => a.domains.find((d) => d === host) !== undefined)?.headers\n\n const exec = config?.fetch ?? fetch\n\n const result = await limiter(() =>\n exec(url, {\n headers,\n }),\n )\n\n if (result.ok) {\n const body = await result.text()\n\n return {\n ok: true,\n data: normalize(body),\n }\n }\n\n return {\n ok: false,\n }\n } catch {\n return {\n ok: false,\n }\n }\n}\n\n/**\n * Creates a plugin for handling remote URL references.\n * This plugin validates and fetches data from HTTP/HTTPS URLs.\n *\n * @returns A plugin object with validate and exec functions\n * @example\n * const urlPlugin = fetchUrls()\n * if (urlPlugin.validate('https://example.com/schema.json')) {\n * const result = await urlPlugin.exec('https://example.com/schema.json')\n * }\n */\nexport function fetchUrls(config?: FetchConfig & Partial<{ limit: number | null }>): Plugin {\n // If there is a limit specified we limit the number of concurrent calls\n const limiter = config?.limit ? createLimiter(config.limit) : <T>(fn: () => Promise<T>) => fn()\n\n return {\n validate: isRemoteUrl,\n exec: (value) => fetchUrl(value, limiter, config),\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,iBAAiB;AAC1B,SAAS,qBAAqB;AAE9B,SAAS,mBAAmB;AAW5B,MAAM,UAAU,CAAC,QAA+B;AAC9C,MAAI;AACF,WAAO,IAAI,IAAI,GAAG,EAAE;AAAA,EACtB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAgBA,eAAsB,SACpB,KACA,SACA,QACwB;AACxB,MAAI;AACF,UAAM,OAAO,QAAQ,GAAG;AAGxB,UAAM,UAAU,QAAQ,SAAS,KAAK,CAAC,MAAM,EAAE,QAAQ,KAAK,CAAC,MAAM,MAAM,IAAI,MAAM,MAAS,GAAG;AAE/F,UAAM,OAAO,QAAQ,SAAS;AAE9B,UAAM,SAAS,MAAM;AAAA,MAAQ,MAC3B,KAAK,KAAK;AAAA,QACR;AAAA,MACF,CAAC;AAAA,IACH;AAEA,QAAI,OAAO,IAAI;AACb,YAAM,OAAO,MAAM,OAAO,KAAK;AAE/B,aAAO;AAAA,QACL,IAAI;AAAA,QACJ,MAAM,UAAU,IAAI;AAAA,MACtB;AAAA,IACF;AAEA,WAAO;AAAA,MACL,IAAI;AAAA,IACN;AAAA,EACF,QAAQ;AACN,WAAO;AAAA,MACL,IAAI;AAAA,IACN;AAAA,EACF;AACF;AAaO,SAAS,UAAU,QAAkE;AAE1F,QAAM,UAAU,QAAQ,QAAQ,cAAc,OAAO,KAAK,IAAI,CAAI,OAAyB,GAAG;AAE9F,SAAO;AAAA,IACL,UAAU;AAAA,IACV,MAAM,CAAC,UAAU,SAAS,OAAO,SAAS,MAAM;AAAA,EAClD;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../../../src/bundle/plugins/node.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAA;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAA;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAA;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAA"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { fetchUrls } from "./fetch-urls/index.js";
|
|
2
|
+
import { readFiles } from "./read-files/index.js";
|
|
3
|
+
import { parseJson } from "./parse-json/index.js";
|
|
4
|
+
import { parseYaml } from "./parse-yaml/index.js";
|
|
5
|
+
export {
|
|
6
|
+
fetchUrls,
|
|
7
|
+
parseJson,
|
|
8
|
+
parseYaml,
|
|
9
|
+
readFiles
|
|
10
|
+
};
|
|
11
|
+
//# sourceMappingURL=node.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/bundle/plugins/node.ts"],
|
|
4
|
+
"sourcesContent": ["// biome-ignore lint/performance/noBarrelFile: <explanation>\nexport { fetchUrls } from './fetch-urls'\nexport { readFiles } from './read-files'\nexport { parseJson } from './parse-json'\nexport { parseYaml } from './parse-yaml'\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,iBAAiB;AAC1B,SAAS,iBAAiB;AAC1B,SAAS,iBAAiB;AAC1B,SAAS,iBAAiB;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Plugin } from '../../../bundle/index.js';
|
|
2
|
+
/**
|
|
3
|
+
* Creates a plugin that parses JSON strings into JavaScript objects.
|
|
4
|
+
* @returns A plugin object with validate and exec functions
|
|
5
|
+
* @example
|
|
6
|
+
* ```ts
|
|
7
|
+
* const jsonPlugin = parseJson()
|
|
8
|
+
* const result = jsonPlugin.exec('{"name": "John", "age": 30}')
|
|
9
|
+
* // result = { name: 'John', age: 30 }
|
|
10
|
+
* ```
|
|
11
|
+
*/
|
|
12
|
+
export declare function parseJson(): Plugin;
|
|
13
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/bundle/plugins/parse-json/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAiB,MAAM,UAAU,CAAA;AAErD;;;;;;;;;GASG;AACH,wBAAgB,SAAS,IAAI,MAAM,CAgBlC"}
|