@scalar/workspace-store 0.11.0 → 0.12.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/README.md +60 -7
- package/dist/client.d.ts +3 -4
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +64 -29
- package/dist/client.js.map +2 -2
- package/dist/helpers/apply-selective-updates.d.ts +1 -1
- package/dist/helpers/apply-selective-updates.d.ts.map +1 -1
- package/dist/helpers/apply-selective-updates.js +1 -1
- package/dist/helpers/apply-selective-updates.js.map +1 -1
- package/dist/schemas/inmemory-workspace.d.ts +5633 -0
- package/dist/schemas/inmemory-workspace.d.ts.map +1 -1
- package/dist/schemas/inmemory-workspace.js +3 -1
- package/dist/schemas/inmemory-workspace.js.map +2 -2
- package/dist/schemas/typebox-types.d.ts +14 -0
- package/dist/schemas/typebox-types.d.ts.map +1 -0
- package/dist/schemas/typebox-types.js +19 -0
- package/dist/schemas/typebox-types.js.map +7 -0
- package/dist/server.js +1 -1
- package/dist/server.js.map +1 -1
- package/package.json +9 -5
- package/dist/helpers/proxy.d.ts +0 -63
- package/dist/helpers/proxy.d.ts.map +0 -1
- package/dist/helpers/proxy.js +0 -107
- package/dist/helpers/proxy.js.map +0 -7
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,22 @@
|
|
|
1
1
|
# @scalar/workspace-store
|
|
2
2
|
|
|
3
|
+
## 0.12.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 952bde2: feat(json-magic): move json tooling to the new package
|
|
8
|
+
- ae8d1b9: feat(workspace-store): rebase document origin with a remote origin
|
|
9
|
+
- 2888e18: feat(openapi-parser): partial bundle to a depth
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- 5301a80: feat: make content reactive and update workspace store
|
|
14
|
+
- 8199955: fix(workspace-store): never write overrides back to the intermediate state
|
|
15
|
+
- Updated dependencies [952bde2]
|
|
16
|
+
- Updated dependencies [2888e18]
|
|
17
|
+
- @scalar/openapi-parser@0.19.0
|
|
18
|
+
- @scalar/json-magic@0.1.0
|
|
19
|
+
|
|
3
20
|
## 0.11.0
|
|
4
21
|
|
|
5
22
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -196,7 +196,7 @@ const store = createWorkspaceStore({
|
|
|
196
196
|
})
|
|
197
197
|
|
|
198
198
|
// Add another OpenAPI document to the workspace
|
|
199
|
-
store.
|
|
199
|
+
await store.addDocument({
|
|
200
200
|
document: {
|
|
201
201
|
info: {
|
|
202
202
|
title: 'OpenApi document',
|
|
@@ -261,7 +261,7 @@ const store = createWorkspaceStore({
|
|
|
261
261
|
You can override specific document configuration when you add the document to the store
|
|
262
262
|
|
|
263
263
|
```ts
|
|
264
|
-
store.
|
|
264
|
+
await store.addDocument({
|
|
265
265
|
name: 'example',
|
|
266
266
|
document: {
|
|
267
267
|
openapi: '3.0.0',
|
|
@@ -276,7 +276,7 @@ store.addDocumentSync({
|
|
|
276
276
|
})
|
|
277
277
|
```
|
|
278
278
|
|
|
279
|
-
To get the active document configuration you can use config getter
|
|
279
|
+
To get the active document configuration you can use config getter
|
|
280
280
|
|
|
281
281
|
```ts
|
|
282
282
|
// Get the configuration for the active document
|
|
@@ -416,15 +416,68 @@ Create the workspace from a specification object
|
|
|
416
416
|
|
|
417
417
|
```ts
|
|
418
418
|
await store.importWorkspaceFromSpecification({
|
|
419
|
-
workspace: '
|
|
419
|
+
workspace: 'draft',
|
|
420
420
|
info: { title: 'My Workspace' },
|
|
421
421
|
documents: {
|
|
422
422
|
api: { $ref: '/examples/api.yaml' },
|
|
423
|
-
petstore: { $ref: '/examples/petstore.yaml' }
|
|
423
|
+
petstore: { $ref: '/examples/petstore.yaml' },
|
|
424
424
|
},
|
|
425
425
|
overrides: {
|
|
426
|
-
api: {
|
|
426
|
+
api: {
|
|
427
|
+
servers: [
|
|
428
|
+
{
|
|
429
|
+
url: 'http://localhost:9090',
|
|
430
|
+
},
|
|
431
|
+
],
|
|
432
|
+
},
|
|
427
433
|
},
|
|
428
|
-
|
|
434
|
+
'x-scalar-dark-mode': true,
|
|
429
435
|
})
|
|
436
|
+
```
|
|
437
|
+
|
|
438
|
+
### Override specific fields from the document and it's metadata
|
|
439
|
+
|
|
440
|
+
This feature is helpful when you want to override specific fields in a document without altering the original source. Overrides allow you to customize certain values in-memory, ensuring the original document remains unchanged.
|
|
441
|
+
|
|
442
|
+
```ts
|
|
443
|
+
const store = createWorkspaceStore()
|
|
444
|
+
await store.addDocument({
|
|
445
|
+
name: 'default',
|
|
446
|
+
document: {
|
|
447
|
+
openapi: '3.1.0',
|
|
448
|
+
info: {
|
|
449
|
+
title: 'Document Title',
|
|
450
|
+
version: '1.0.0',
|
|
451
|
+
},
|
|
452
|
+
paths: {},
|
|
453
|
+
components: {
|
|
454
|
+
schemas: {},
|
|
455
|
+
},
|
|
456
|
+
servers: [],
|
|
457
|
+
},
|
|
458
|
+
// Override the servers field
|
|
459
|
+
overrides: {
|
|
460
|
+
servers: [
|
|
461
|
+
{
|
|
462
|
+
url: 'http://localhost:8080',
|
|
463
|
+
description: 'Default dev server'
|
|
464
|
+
}
|
|
465
|
+
]
|
|
466
|
+
}
|
|
467
|
+
})
|
|
468
|
+
```
|
|
469
|
+
|
|
470
|
+
When you override specific fields, those changes are applied only in-memory and will never be written back to the original document. The original source remains unchanged, and any modifications made through overrides are isolated to the current session.
|
|
471
|
+
|
|
472
|
+
### Rebase document origin with the updated remote origin
|
|
473
|
+
|
|
474
|
+
Rebases a document in the workspace with a new origin, resolving conflicts if provided.
|
|
475
|
+
|
|
476
|
+
```ts
|
|
477
|
+
// Example: Rebase a document with a new origin and resolve conflicts
|
|
478
|
+
const conflicts = store.rebaseDocument('api', newOriginDoc)
|
|
479
|
+
if (conflicts && conflicts.length > 0) {
|
|
480
|
+
// User resolves conflicts here...
|
|
481
|
+
store.rebaseDocument('api', newOriginDoc, userResolvedConflicts)
|
|
482
|
+
}
|
|
430
483
|
```
|
package/dist/client.d.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { type OpenApiDocument } from './schemas/v3.1/strict/openapi-document.js'
|
|
|
4
4
|
import type { Config } from './schemas/workspace-specification/config.js';
|
|
5
5
|
import type { WorkspaceSpecification } from './schemas/workspace-specification/index.js';
|
|
6
6
|
import type { Workspace, WorkspaceDocumentMeta, WorkspaceMeta } from './schemas/workspace.js';
|
|
7
|
+
import { merge, type Difference } from '@scalar/json-magic/diff';
|
|
7
8
|
/**
|
|
8
9
|
* Input type for workspace document metadata and configuration.
|
|
9
10
|
* This type defines the required and optional fields for initializing a document in the workspace.
|
|
@@ -49,8 +50,6 @@ declare const defaultConfig: DeepRequired<Config>;
|
|
|
49
50
|
type WorkspaceProps = {
|
|
50
51
|
/** Optional metadata for the workspace including theme, active document, etc */
|
|
51
52
|
meta?: WorkspaceMeta;
|
|
52
|
-
/** In-mem open api documents. Async source documents (like URLs) can be loaded after initialization */
|
|
53
|
-
documents?: ObjectDoc[];
|
|
54
53
|
/** Workspace configuration */
|
|
55
54
|
config?: Config;
|
|
56
55
|
};
|
|
@@ -73,8 +72,6 @@ export type WorkspaceStore = {
|
|
|
73
72
|
resolve(path: string[]): Promise<unknown>;
|
|
74
73
|
/** Adds a new document to the workspace */
|
|
75
74
|
addDocument(input: WorkspaceDocumentInput): Promise<void>;
|
|
76
|
-
/** Similar to addDocument but requires and in-mem object to be provided and loads the document synchronously */
|
|
77
|
-
addDocumentSync(input: ObjectDoc): void;
|
|
78
75
|
/** Returns the merged configuration for the active document */
|
|
79
76
|
readonly config: typeof defaultConfig;
|
|
80
77
|
/** Downloads the specified document in the requested format */
|
|
@@ -91,6 +88,8 @@ export type WorkspaceStore = {
|
|
|
91
88
|
loadWorkspace(input: string): void;
|
|
92
89
|
/** Imports a workspace from a specification object */
|
|
93
90
|
importWorkspaceFromSpecification(specification: WorkspaceSpecification): Promise<void[]>;
|
|
91
|
+
/** Rebase document with a remote origin */
|
|
92
|
+
rebaseDocument: (documentName: string, newDocumentOrigin: Record<string, unknown>, resolvedConflicts?: Difference[]) => void | ReturnType<typeof merge>['conflicts'];
|
|
94
93
|
};
|
|
95
94
|
/**
|
|
96
95
|
* Creates a reactive workspace store that manages documents and their metadata.
|
package/dist/client.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AAKxD,OAAO,EAAoB,KAAK,uBAAuB,EAAE,MAAM,cAAc,CAAA;AAG7E,OAAO,EAAyB,KAAK,eAAe,EAAE,MAAM,wCAAwC,CAAA;AAEpG,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,0CAA0C,CAAA;AAEtE,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,mCAAmC,CAAA;AAE/E,OAAO,KAAK,EAAE,SAAS,EAAE,qBAAqB,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAG1F,OAAO,EAAe,KAAK,EAAE,KAAK,UAAU,EAAE,MAAM,yBAAyB,CAAA;AAE7E;;;;;GAKG;AACH,KAAK,0BAA0B,GAAG;IAChC,wEAAwE;IACxE,IAAI,CAAC,EAAE,qBAAqB,CAAA;IAC5B,kDAAkD;IAClD,IAAI,EAAE,MAAM,CAAA;IACZ,iEAAiE;IACjE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,uBAAuB,CAAC,CAAA;IAClD,iCAAiC;IACjC,SAAS,CAAC,EAAE,WAAW,CAAC,eAAe,CAAC,CAAA;CACzC,CAAA;AAED;;;GAGG;AACH,MAAM,MAAM,MAAM,GAAG;IACnB,6CAA6C;IAC7C,GAAG,EAAE,MAAM,CAAA;IACX,wIAAwI;IACxI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
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import { upgrade } from "@scalar/openapi-parser";
|
|
4
|
+
import { createMagicProxy, getRaw } from "@scalar/json-magic/magic-proxy";
|
|
5
5
|
import { applySelectiveUpdates } from "./helpers/apply-selective-updates.js";
|
|
6
6
|
import { deepClone, isObject, safeAssign } from "./helpers/general.js";
|
|
7
7
|
import { getValueByPath } from "./helpers/json-path-utils.js";
|
|
8
8
|
import { mergeObjects } from "./helpers/merge-object.js";
|
|
9
|
-
import { createMagicProxy, getRaw } from "./helpers/proxy.js";
|
|
10
9
|
import { createNavigation } from "./navigation/index.js";
|
|
11
10
|
import { extensions } from "./schemas/extensions.js";
|
|
12
11
|
import { coerceValue } from "./schemas/typebox-coerce.js";
|
|
@@ -14,6 +13,9 @@ import { OpenAPIDocumentSchema } from "./schemas/v3.1/strict/openapi-document.js
|
|
|
14
13
|
import { defaultReferenceConfig } from "./schemas/reference-config/index.js";
|
|
15
14
|
import { InMemoryWorkspaceSchema } from "./schemas/inmemory-workspace.js";
|
|
16
15
|
import { createOverridesProxy } from "./helpers/overrides-proxy.js";
|
|
16
|
+
import { bundle } from "@scalar/json-magic/bundle";
|
|
17
|
+
import { fetchUrls } from "@scalar/json-magic/bundle/plugins/browser";
|
|
18
|
+
import { apply, diff, merge } from "@scalar/json-magic/diff";
|
|
17
19
|
const defaultConfig = {
|
|
18
20
|
"x-scalar-reference-config": defaultReferenceConfig
|
|
19
21
|
};
|
|
@@ -55,14 +57,14 @@ const createWorkspaceStore = (workspaceProps) => {
|
|
|
55
57
|
if (!workspaceDocument) {
|
|
56
58
|
return;
|
|
57
59
|
}
|
|
58
|
-
const updatedDocument =
|
|
60
|
+
const updatedDocument = getRaw(workspaceDocument);
|
|
59
61
|
if (!intermediateDocument || !updatedDocument) {
|
|
60
62
|
return;
|
|
61
63
|
}
|
|
62
64
|
const excludedDiffs = applySelectiveUpdates(intermediateDocument, updatedDocument);
|
|
63
65
|
return excludedDiffs;
|
|
64
66
|
}
|
|
65
|
-
function
|
|
67
|
+
async function addInMemoryDocument(input) {
|
|
66
68
|
const { name, meta } = input;
|
|
67
69
|
const document = coerceValue(OpenAPIDocumentSchema, upgrade(input.document).specification);
|
|
68
70
|
originalDocuments[name] = deepClone({ ...document, ...meta });
|
|
@@ -72,8 +74,10 @@ const createWorkspaceStore = (workspaceProps) => {
|
|
|
72
74
|
if (document[extensions.document.navigation] === void 0) {
|
|
73
75
|
document[extensions.document.navigation] = createNavigation(document, input.config ?? {}).entries;
|
|
74
76
|
}
|
|
77
|
+
if (document[extensions.document.navigation] === void 0) {
|
|
78
|
+
await bundle(input.document, { treeShake: false, plugins: [fetchUrls()] });
|
|
79
|
+
}
|
|
75
80
|
workspace.documents[name] = createOverridesProxy(createMagicProxy({ ...document, ...meta }), input.overrides);
|
|
76
|
-
saveDocument(name);
|
|
77
81
|
}
|
|
78
82
|
async function addDocument(input) {
|
|
79
83
|
const { name, meta } = input;
|
|
@@ -102,9 +106,8 @@ const createWorkspaceStore = (workspaceProps) => {
|
|
|
102
106
|
};
|
|
103
107
|
return;
|
|
104
108
|
}
|
|
105
|
-
|
|
109
|
+
await addInMemoryDocument({ ...input, document: resolve.data });
|
|
106
110
|
}
|
|
107
|
-
workspaceProps?.documents?.forEach(addDocumentSync);
|
|
108
111
|
const visitedNodesCache = /* @__PURE__ */ new Set();
|
|
109
112
|
return {
|
|
110
113
|
/**
|
|
@@ -225,25 +228,6 @@ const createWorkspaceStore = (workspaceProps) => {
|
|
|
225
228
|
* })
|
|
226
229
|
*/
|
|
227
230
|
addDocument,
|
|
228
|
-
/**
|
|
229
|
-
* Similar to addDocument but requires and in-mem object to be provided and loads the document synchronously
|
|
230
|
-
* @param document - The document content to add. This should be a valid OpenAPI/Swagger document or other supported format
|
|
231
|
-
* @param meta - Metadata for the document, including its name and other properties defined in WorkspaceDocumentMeta
|
|
232
|
-
* @example
|
|
233
|
-
* // Add a new OpenAPI document to the workspace
|
|
234
|
-
* store.addDocument({
|
|
235
|
-
* name: 'name',
|
|
236
|
-
* document: {
|
|
237
|
-
* openapi: '3.0.0',
|
|
238
|
-
* info: { title: 'title' },
|
|
239
|
-
* },
|
|
240
|
-
* meta: {
|
|
241
|
-
* 'x-scalar-active-auth': 'Bearer',
|
|
242
|
-
* 'x-scalar-active-server': 'production'
|
|
243
|
-
* }
|
|
244
|
-
* })
|
|
245
|
-
*/
|
|
246
|
-
addDocumentSync,
|
|
247
231
|
/**
|
|
248
232
|
* Returns the merged configuration for the active document.
|
|
249
233
|
*
|
|
@@ -333,7 +317,7 @@ const createWorkspaceStore = (workspaceProps) => {
|
|
|
333
317
|
return;
|
|
334
318
|
}
|
|
335
319
|
const intermediateDocument = intermediateDocuments[documentName];
|
|
336
|
-
const updatedDocument =
|
|
320
|
+
const updatedDocument = getRaw(workspaceDocument);
|
|
337
321
|
if (!intermediateDocument || !updatedDocument) {
|
|
338
322
|
return;
|
|
339
323
|
}
|
|
@@ -377,7 +361,8 @@ const createWorkspaceStore = (workspaceProps) => {
|
|
|
377
361
|
meta: workspaceProps?.meta ?? {},
|
|
378
362
|
documentConfigs,
|
|
379
363
|
originalDocuments,
|
|
380
|
-
intermediateDocuments
|
|
364
|
+
intermediateDocuments,
|
|
365
|
+
overrides
|
|
381
366
|
});
|
|
382
367
|
},
|
|
383
368
|
/**
|
|
@@ -398,6 +383,7 @@ const createWorkspaceStore = (workspaceProps) => {
|
|
|
398
383
|
safeAssign(originalDocuments, result.originalDocuments);
|
|
399
384
|
safeAssign(intermediateDocuments, result.intermediateDocuments);
|
|
400
385
|
safeAssign(documentConfigs, result.documentConfigs);
|
|
386
|
+
safeAssign(overrides, result.overrides);
|
|
401
387
|
safeAssign(workspace, result.meta);
|
|
402
388
|
},
|
|
403
389
|
/**
|
|
@@ -432,6 +418,55 @@ const createWorkspaceStore = (workspaceProps) => {
|
|
|
432
418
|
([name, doc]) => addDocument({ url: doc.$ref, name, overrides: overrides2?.[name] })
|
|
433
419
|
)
|
|
434
420
|
);
|
|
421
|
+
},
|
|
422
|
+
/**
|
|
423
|
+
* Rebases a document in the workspace with a new origin, resolving conflicts if provided.
|
|
424
|
+
*
|
|
425
|
+
* This method is used to rebase a document (e.g., after pulling remote changes) by applying the changes
|
|
426
|
+
* from the new origin and merging them with local edits. If there are conflicts, they can be resolved
|
|
427
|
+
* by providing a list of resolved conflicts.
|
|
428
|
+
*
|
|
429
|
+
* @param documentName - The name of the document to rebase.
|
|
430
|
+
* @param newDocumentOrigin - The new origin document (as an object) to rebase onto.
|
|
431
|
+
* @param resolvedConflicts - (Optional) An array of resolved conflicts to apply.
|
|
432
|
+
* @returns If there are unresolved conflicts and no resolution is provided, returns the list of conflicts.
|
|
433
|
+
*
|
|
434
|
+
* @example
|
|
435
|
+
* // Example: Rebase a document with a new origin and resolve conflicts
|
|
436
|
+
* const conflicts = store.rebaseDocument('api', newOriginDoc)
|
|
437
|
+
* if (conflicts && conflicts.length > 0) {
|
|
438
|
+
* // User resolves conflicts here...
|
|
439
|
+
* store.rebaseDocument('api', newOriginDoc, userResolvedConflicts)
|
|
440
|
+
* }
|
|
441
|
+
*/
|
|
442
|
+
rebaseDocument: (documentName, newDocumentOrigin, resolvedConflicts) => {
|
|
443
|
+
const newOrigin = coerceValue(OpenAPIDocumentSchema, upgrade(newDocumentOrigin).specification);
|
|
444
|
+
const originalDocument = originalDocuments[documentName];
|
|
445
|
+
const intermediateDocument = intermediateDocuments[documentName];
|
|
446
|
+
const activeDocument = workspace.documents[documentName] ? getRaw(workspace.documents[documentName]) : void 0;
|
|
447
|
+
if (!originalDocument || !intermediateDocument || !activeDocument) {
|
|
448
|
+
return console.error("[ERROR]: Specified document is missing or internal corrupted workspace state");
|
|
449
|
+
}
|
|
450
|
+
const changelogAA = diff(originalDocument, newOrigin);
|
|
451
|
+
const changelogAB = diff(originalDocument, intermediateDocument);
|
|
452
|
+
const changesA = merge(changelogAA, changelogAB);
|
|
453
|
+
if (resolvedConflicts === void 0) {
|
|
454
|
+
return changesA.conflicts;
|
|
455
|
+
}
|
|
456
|
+
const changesetA = changesA.diffs.concat(resolvedConflicts);
|
|
457
|
+
const newIntermediateDocument = apply(deepClone(originalDocument), changesetA);
|
|
458
|
+
intermediateDocuments[documentName] = newIntermediateDocument;
|
|
459
|
+
originalDocuments[documentName] = newOrigin;
|
|
460
|
+
const changelogBA = diff(intermediateDocument, newIntermediateDocument);
|
|
461
|
+
const changelogBB = diff(intermediateDocument, activeDocument);
|
|
462
|
+
const changesB = merge(changelogBA, changelogBB);
|
|
463
|
+
const changesetB = changesB.diffs.concat(changesB.conflicts.flatMap((it) => it[0]));
|
|
464
|
+
const newActiveDocument = apply(deepClone(newIntermediateDocument), changesetB);
|
|
465
|
+
workspace.documents[documentName] = createOverridesProxy(
|
|
466
|
+
createMagicProxy({ ...newActiveDocument }),
|
|
467
|
+
overrides[documentName]
|
|
468
|
+
);
|
|
469
|
+
return;
|
|
435
470
|
}
|
|
436
471
|
};
|
|
437
472
|
};
|
package/dist/client.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/client.ts"],
|
|
4
|
-
"sourcesContent": ["import YAML from 'yaml'\nimport { reactive } from 'vue'\nimport { bundle, upgrade } from '@scalar/openapi-parser'\nimport { fetchUrls } from '@scalar/openapi-parser/plugins-browser'\nimport type { DeepPartial, DeepRequired } from '@/types'\nimport { applySelectiveUpdates } from '@/helpers/apply-selective-updates'\nimport { deepClone, isObject, safeAssign } from '@/helpers/general'\nimport { getValueByPath } from '@/helpers/json-path-utils'\nimport { mergeObjects } from '@/helpers/merge-object'\nimport { createMagicProxy, getRaw } from '@/helpers/proxy'\nimport { createNavigation, type createNavigationOptions } from '@/navigation'\nimport { extensions } from '@/schemas/extensions'\nimport { coerceValue } from '@/schemas/typebox-coerce'\nimport { OpenAPIDocumentSchema, type OpenApiDocument } from '@/schemas/v3.1/strict/openapi-document'\nimport { defaultReferenceConfig } from '@/schemas/reference-config'\nimport type { Config } from '@/schemas/workspace-specification/config'\nimport { InMemoryWorkspaceSchema, type InMemoryWorkspace } from '@/schemas/inmemory-workspace'\nimport type { WorkspaceSpecification } from '@/schemas/workspace-specification'\nimport { createOverridesProxy } from '@/helpers/overrides-proxy'\nimport type { Workspace, WorkspaceDocumentMeta, WorkspaceMeta } from '@/schemas/workspace'\n\n/**\n * Input type for workspace document metadata and configuration.\n * This type defines the required and optional fields for initializing a document in the workspace.\n *\n * TODO: merge navigation options with the document config\n */\ntype WorkspaceDocumentMetaInput = {\n /** Optional metadata about the document like title, description, etc */\n meta?: WorkspaceDocumentMeta\n /** Required unique identifier for the document */\n name: string\n /** Optional configuration for generating navigation structure */\n config?: Config & Partial<createNavigationOptions>\n /** Overrides for the document */\n overrides?: DeepPartial<OpenApiDocument>\n}\n\n/**\n * Represents a document that is loaded from a URL.\n * This type extends WorkspaceDocumentMetaInput to include URL-specific properties.\n */\nexport type UrlDoc = {\n /** URL to fetch the OpenAPI document from */\n url: string\n /** Optional custom fetch implementation to use when retrieving the document. By default the global fetch implementation will be used */\n fetch?: (input: string | URL | globalThis.Request, init?: RequestInit) => Promise<Response>\n} & WorkspaceDocumentMetaInput\n\n/** Represents a document that is provided directly as an object rather than loaded from a URL */\nexport type ObjectDoc = {\n /** The OpenAPI document object containing the API specification */\n document: Record<string, unknown>\n} & WorkspaceDocumentMetaInput\n\n/**\n * Union type representing the possible input formats for a workspace document:\n * - UrlDoc: Document loaded from a URL with optional fetch configuration\n * - ObjectDoc: Direct document object with metadata\n */\nexport type WorkspaceDocumentInput = UrlDoc | ObjectDoc\n\nconst defaultConfig: DeepRequired<Config> = {\n 'x-scalar-reference-config': defaultReferenceConfig,\n}\n\n/**\n * Resolves a workspace document from various input sources (URL, local file, or direct document object).\n *\n * @param workspaceDocument - The document input to resolve, which can be:\n * - A URL to fetch the document from\n * - A direct document object\n * @returns A promise that resolves to an object containing:\n * - ok: boolean indicating if the resolution was successful\n * - data: The resolved document data\n *\n * @example\n * // Resolve from URL\n * const urlDoc = await loadDocument({ name: 'api', url: 'https://api.example.com/openapi.json' })\n *\n * // Resolve direct document\n * const directDoc = await loadDocument({\n * name: 'inline',\n * document: { openapi: '3.0.0', paths: {} }\n * })\n */\nasync function loadDocument(workspaceDocument: WorkspaceDocumentInput) {\n if ('url' in workspaceDocument) {\n return fetchUrls({ fetch: workspaceDocument.fetch }).exec(workspaceDocument.url)\n }\n\n return {\n ok: true as const,\n data: workspaceDocument.document,\n }\n}\n\n/**\n * Configuration object for initializing a workspace store.\n * Defines the initial state and documents for the workspace.\n */\ntype WorkspaceProps = {\n /** Optional metadata for the workspace including theme, active document, etc */\n meta?: WorkspaceMeta\n /** In-mem open api documents. Async source documents (like URLs) can be loaded after initialization */\n documents?: ObjectDoc[]\n /** Workspace configuration */\n config?: Config\n}\n\n/**\n * Type definition for the workspace store return object.\n * This explicit type is needed to avoid TypeScript inference limits.\n *\n * @see https://github.com/microsoft/TypeScript/issues/43817#issuecomment-827746462\n */\nexport type WorkspaceStore = {\n /** Returns the reactive workspace object with an additional activeDocument getter */\n readonly workspace: Workspace\n /** Updates a specific metadata field in the workspace */\n update<K extends keyof WorkspaceMeta>(key: K, value: WorkspaceMeta[K]): void\n /** Updates a specific metadata field in a document */\n updateDocument<K extends keyof WorkspaceDocumentMeta>(\n name: 'active' | (string & {}),\n key: K,\n value: WorkspaceDocumentMeta[K],\n ): void\n /** Replaces the content of a specific document in the workspace with the provided input */\n replaceDocument(documentName: string, input: Record<string, unknown>): void\n /** Resolves a reference in the active document by following the provided path and resolving any external $ref references */\n resolve(path: string[]): Promise<unknown>\n /** Adds a new document to the workspace */\n addDocument(input: WorkspaceDocumentInput): Promise<void>\n /** Similar to addDocument but requires and in-mem object to be provided and loads the document synchronously */\n addDocumentSync(input: ObjectDoc): void\n /** Returns the merged configuration for the active document */\n readonly config: typeof defaultConfig\n /** Downloads the specified document in the requested format */\n exportDocument(documentName: string, format: 'json' | 'yaml'): string | undefined\n /** Persists the current state of the specified document back to the original documents map */\n saveDocument(documentName: string): unknown[] | undefined\n /** Reverts the specified document to its original state */\n revertDocumentChanges(documentName: string): void\n /** Commits the specified document */\n commitDocument(documentName: string): void\n /** Serializes the current workspace state to a JSON string for backup, persistence, or sharing. */\n exportWorkspace(): string\n /** Imports a workspace from a serialized JSON string. */\n loadWorkspace(input: string): void\n /** Imports a workspace from a specification object */\n importWorkspaceFromSpecification(specification: WorkspaceSpecification): Promise<void[]>\n}\n\n/**\n * Creates a reactive workspace store that manages documents and their metadata.\n * The store provides functionality for accessing, updating, and resolving document references.\n *\n * @param workspaceProps - Configuration object for the workspace\n * @param workspaceProps.meta - Optional metadata for the workspace\n * @param workspaceProps.documents - Optional record of documents to initialize the workspace with\n * Documents that require asynchronous loading must be added using `addDocument` after the store is created\n * this allows atomic awaiting and does not block page load for the store initialization\n * @returns An object containing methods and getters for managing the workspace\n */\nexport const createWorkspaceStore = (workspaceProps?: WorkspaceProps): WorkspaceStore => {\n /**\n * Holds the original, unmodified documents as they were initially loaded into the workspace.\n * These documents are stored in their raw form\u2014prior to any reactive wrapping, dereferencing, or bundling.\n * This map preserves the pristine structure of each document, using deep clones to ensure that\n * subsequent mutations in the workspace do not affect the originals.\n * The originals are retained so that we can restore, compare, or sync with the remote registry as needed.\n */\n const originalDocuments = {} as Workspace['documents']\n /**\n * Stores the intermediate state of documents after local edits but before syncing with the remote registry.\n *\n * This map acts as a local \"saved\" version of the document, reflecting the user's changes after they hit \"save\".\n * The `originalDocuments` map, by contrast, always mirrors the document as it exists in the remote registry.\n *\n * Use this map to stage local changes that are ready to be propagated back to the remote registry.\n * This separation allows us to distinguish between:\n * - The last known remote version (`originalDocuments`)\n * - The latest locally saved version (`intermediateDocuments`)\n * - The current in-memory (possibly unsaved) workspace document (`workspace.documents`)\n */\n const intermediateDocuments = {} as Workspace['documents']\n /**\n * A map of document configurations keyed by document name.\n * This stores the configuration options for each document in the workspace,\n * allowing for document-specific settings like navigation options, appearance,\n * and other reference configuration.\n */\n const documentConfigs: Record<string, Config> = {}\n /**\n * Stores per-document overrides for OpenAPI documents.\n * This object is used to override specific fields of a document\n * when you cannot (or should not) modify the source document directly.\n * For example, this enables UI-driven or temporary changes to be applied\n * on top of the original document, without mutating the source.\n * The key is the document name, and the value is a deep partial\n * OpenAPI document representing the overridden fields.\n */\n const overrides: Record<string, DeepPartial<OpenApiDocument>> = {}\n\n // Create a reactive workspace object with proxied documents\n // Each document is wrapped in a proxy to enable reactive updates and reference resolution\n const workspace = reactive<Workspace>({\n ...workspaceProps?.meta,\n documents: {},\n /**\n * Returns the currently active document from the workspace.\n * The active document is determined by the 'x-scalar-active-document' metadata field,\n * falling back to the first document in the workspace if no active document is specified.\n *\n * @returns The active document or undefined if no document is found\n */\n get activeDocument(): NonNullable<Workspace['activeDocument']> | undefined {\n const activeDocumentKey =\n workspace[extensions.workspace.activeDocument] ?? Object.keys(workspace.documents)[0] ?? ''\n return workspace.documents[activeDocumentKey]\n },\n })\n\n /**\n * Returns the name of the currently active document in the workspace.\n * The active document is determined by the 'x-scalar-active-document' metadata field,\n * falling back to the first document in the workspace if no active document is specified.\n *\n * @returns The name of the active document or an empty string if no document is found\n */\n function getActiveDocumentName() {\n return workspace[extensions.workspace.activeDocument] ?? Object.keys(workspace.documents)[0] ?? ''\n }\n\n // Save the current state of the specified document to the intermediate documents map.\n // This function captures the latest (reactive) state of the document from the workspace and\n // applies its changes to the corresponding entry in the `intermediateDocuments` map.\n // The `intermediateDocuments` map represents the most recently \"saved\" local version of the document,\n // which may include edits not yet synced to the remote registry.\n function saveDocument(documentName: string) {\n const intermediateDocument = intermediateDocuments[documentName]\n const workspaceDocument = workspace.documents[documentName]\n\n if (!workspaceDocument) {\n return\n }\n\n // Obtain the raw state of the current document to ensure accurate diffing\n // Remove the magic proxy while preserving the overrides proxy to ensure accurate updates\n const updatedDocument = createOverridesProxy(getRaw(workspaceDocument), overrides[documentName])\n\n // If either the intermediate or updated document is missing, do nothing\n if (!intermediateDocument || !updatedDocument) {\n return\n }\n\n // Apply changes from the current document to the intermediate document in place\n const excludedDiffs = applySelectiveUpdates(intermediateDocument, updatedDocument)\n return excludedDiffs\n }\n\n // Add a document to the store synchronously from an in-memory OpenAPI document\n function addDocumentSync(input: ObjectDoc) {\n const { name, meta } = input\n\n const document = coerceValue(OpenAPIDocumentSchema, upgrade(input.document).specification)\n\n // Store the original document in the originalDocuments map\n // This is used to track the original state of the document as it was loaded into the workspace\n originalDocuments[name] = deepClone({ ...document, ...meta })\n // Store the intermediate document state for local edits\n // This is used to track the last saved state of the document\n // It allows us to differentiate between the original document and the latest saved version\n // This is important for local edits that are not yet synced with the remote registry\n // The intermediate document is used to store the latest saved state of the document\n // This allows us to track changes and revert to the last saved state if needed\n intermediateDocuments[name] = deepClone({ ...document, ...meta })\n // Add the document config to the documentConfigs map\n documentConfigs[name] = input.config ?? {}\n // Store the overrides for this document, or an empty object if none are provided\n overrides[name] = input.overrides ?? {}\n\n // Skip navigation generation if the document already has a server-side generated navigation structure\n if (document[extensions.document.navigation] === undefined) {\n document[extensions.document.navigation] = createNavigation(document, input.config ?? {}).entries\n }\n\n // Create a proxied document with magic proxy and apply any overrides, then store it in the workspace documents map\n workspace.documents[name] = createOverridesProxy(createMagicProxy({ ...document, ...meta }), input.overrides)\n\n // Write overrides to the intermediate document\n saveDocument(name)\n }\n\n // Asynchronously adds a new document to the workspace by loading and validating the input.\n // If loading fails, a placeholder error document is added instead.\n async function addDocument(input: WorkspaceDocumentInput) {\n const { name, meta } = input\n\n const resolve = await loadDocument(input)\n\n if (!resolve.ok) {\n console.error(`Failed to fetch document '${name}': request was not successful`)\n\n workspace.documents[name] = {\n ...meta,\n openapi: '3.1.0',\n info: {\n title: `Document '${name}' could not be loaded`,\n version: 'unknown',\n },\n }\n\n return\n }\n\n if (!isObject(resolve.data)) {\n console.error(`Failed to load document '${name}': response data is not a valid object`)\n\n workspace.documents[name] = {\n ...meta,\n openapi: '3.1.0',\n info: {\n title: `Document '${name}' could not be loaded`,\n version: 'unknown',\n },\n }\n\n return\n }\n\n addDocumentSync({ ...input, document: resolve.data })\n }\n\n // Add any initial documents to the store\n workspaceProps?.documents?.forEach(addDocumentSync)\n\n // Cache to track visited nodes during reference resolution to prevent bundling the same subtree multiple times\n // This is needed because we are doing partial bundle operations\n const visitedNodesCache = new Set()\n\n return {\n /**\n * Returns the reactive workspace object with an additional activeDocument getter\n */\n get workspace() {\n return workspace\n },\n /**\n * Updates a specific metadata field in the workspace\n * @param key - The metadata field to update\n * @param value - The new value for the field\n * @example\n * // Update the workspace title\n * update('x-scalar-active-document', 'document-name')\n */\n update<K extends keyof WorkspaceMeta>(key: K, value: WorkspaceMeta[K]) {\n // @ts-ignore\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n throw new Error('Invalid key: cannot modify prototype')\n }\n Object.assign(workspace, { [key]: value })\n },\n /**\n * Updates a specific metadata field in a document\n * @param name - The name of the document to update ('active' or a specific document name)\n * @param key - The metadata field to update\n * @param value - The new value for the field\n * @throws Error if the specified document doesn't exist\n * @example\n * // Update the auth of the active document\n * updateDocument('active', 'x-scalar-active-auth', 'Bearer')\n * // Update the auth of a specific document\n * updateDocument('document-name', 'x-scalar-active-auth', 'Bearer')\n */\n updateDocument<K extends keyof WorkspaceDocumentMeta>(\n name: 'active' | (string & {}),\n key: K,\n value: WorkspaceDocumentMeta[K],\n ) {\n const currentDocument = workspace.documents[name === 'active' ? getActiveDocumentName() : name]\n\n if (!currentDocument) {\n throw 'Please select a valid document'\n }\n\n Object.assign(currentDocument, { [key]: value })\n },\n /**\n * Replaces the content of a specific document in the workspace with the provided input.\n * This method computes the difference between the current document and the new input,\n * then applies only the necessary changes in place. The updates are applied atomically,\n * ensuring the document is updated in a single operation.\n *\n * @param documentName - The name of the document to update.\n * @param input - The new content to apply to the document (as a plain object).\n * @example\n * // Replace the content of the 'api' document with new data\n * store.replaceDocument('api', {\n * openapi: '3.1.0',\n * info: { title: 'Updated API', version: '1.0.1' },\n * paths: {},\n * })\n */\n replaceDocument(documentName: string, input: Record<string, unknown>) {\n const currentDocument = workspace.documents[documentName]\n\n if (!currentDocument) {\n return console.error(`Document '${documentName}' does not exist in the workspace.`)\n }\n\n // Normalize the input document to ensure it matches the OpenAPI schema and is upgraded to the latest version.\n const newDocument = coerceValue(OpenAPIDocumentSchema, upgrade(input).specification)\n // Update the current document in place, applying only the necessary changes and omitting any preprocessing fields.\n applySelectiveUpdates(currentDocument, newDocument)\n },\n /**\n * Resolves a reference in the active document by following the provided path and resolving any external $ref references.\n * This method traverses the document structure following the given path and resolves any $ref references it encounters.\n * During resolution, it sets a loading status and updates the reference with the resolved content.\n *\n * @param path - Array of strings representing the path to the reference (e.g. ['paths', '/users', 'get', 'responses', '200'])\n * @throws Error if the path is invalid or empty\n * @example\n * // Resolve a reference in the active document\n * resolve(['paths', '/users', 'get', 'responses', '200'])\n */\n resolve: async (path: string[]) => {\n const activeDocument = workspace.activeDocument\n\n const target = getValueByPath(activeDocument, path)\n\n if (!isObject(target)) {\n console.error(\n `Invalid path provided for resolution. Path: [${path.join(', ')}]. Found value of type: ${typeof target}. Expected an object.`,\n )\n return\n }\n\n // Bundle the target document with the active document as root, resolving any external references\n // and tracking resolution status through hooks\n return bundle(target, {\n root: activeDocument,\n treeShake: false,\n plugins: [fetchUrls()],\n urlMap: false,\n hooks: {\n onResolveStart: (node) => {\n node['$status'] = 'loading'\n },\n onResolveError: (node) => {\n node['$status'] = 'error'\n },\n },\n visitedNodes: visitedNodesCache,\n })\n },\n /**\n * Adds a new document to the workspace\n * @param document - The document content to add. This should be a valid OpenAPI/Swagger document or other supported format\n * @param meta - Metadata for the document, including its name and other properties defined in WorkspaceDocumentMeta\n * @example\n * // Add a new OpenAPI document to the workspace\n * store.addDocument({\n * name: 'name',\n * document: {\n * openapi: '3.0.0',\n * info: { title: 'title' },\n * },\n * meta: {\n * 'x-scalar-active-auth': 'Bearer',\n * 'x-scalar-active-server': 'production'\n * }\n * })\n */\n addDocument,\n /**\n * Similar to addDocument but requires and in-mem object to be provided and loads the document synchronously\n * @param document - The document content to add. This should be a valid OpenAPI/Swagger document or other supported format\n * @param meta - Metadata for the document, including its name and other properties defined in WorkspaceDocumentMeta\n * @example\n * // Add a new OpenAPI document to the workspace\n * store.addDocument({\n * name: 'name',\n * document: {\n * openapi: '3.0.0',\n * info: { title: 'title' },\n * },\n * meta: {\n * 'x-scalar-active-auth': 'Bearer',\n * 'x-scalar-active-server': 'production'\n * }\n * })\n */\n addDocumentSync,\n /**\n * Returns the merged configuration for the active document.\n *\n * This getter merges configurations in the following order of precedence:\n * 1. Document-specific configuration (highest priority)\n * 2. Workspace-level configuration\n * 3. Default configuration (lowest priority)\n *\n * The active document is determined by the workspace's activeDocument extension,\n * falling back to the first document if none is specified.\n */\n get config() {\n return mergeObjects<typeof defaultConfig>(\n mergeObjects(defaultConfig, workspaceProps?.config ?? {}),\n documentConfigs[getActiveDocumentName()] ?? {},\n )\n },\n /**\n * Exports the specified document in the requested format.\n *\n * This method serializes the most recently saved local version of the document (from the intermediateDocuments map)\n * to either JSON or YAML. The exported document reflects the last locally saved state, including any edits\n * that have been saved but not yet synced to a remote registry. Runtime/in-memory changes that have not been saved\n * will not be included.\n *\n * @param documentName - The name of the document to export.\n * @param format - The output format: 'json' for a JSON string, or 'yaml' for a YAML string.\n * @returns The document as a string in the requested format, or undefined if the document does not exist.\n *\n * @example\n * // Export a document as JSON\n * const jsonString = store.exportDocument('api', 'json')\n *\n * // Export a document as YAML\n * const yamlString = store.exportDocument('api', 'yaml')\n */\n exportDocument: (documentName: string, format: 'json' | 'yaml') => {\n const intermediateDocument = intermediateDocuments[documentName]\n\n if (!intermediateDocument) {\n return\n }\n\n if (format === 'json') {\n return JSON.stringify(intermediateDocument)\n }\n\n return YAML.stringify(intermediateDocument)\n },\n /**\n * Saves the current state of the specified document to the intermediate documents map.\n *\n * This function captures the latest (reactive) state of the document from the workspace and\n * applies its changes to the corresponding entry in the `intermediateDocuments` map.\n * The `intermediateDocuments` map represents the most recently \"saved\" local version of the document,\n * which may include edits not yet synced to the remote registry.\n *\n * The update is performed in-place. A deep clone of the current document\n * state is used to avoid mutating the reactive object directly.\n *\n * @param documentName - The name of the document to save.\n * @returns An array of diffs that were excluded from being applied (such as changes to ignored keys),\n * or undefined if the document does not exist or cannot be updated.\n *\n * @example\n * // Save the current state of the document named 'api'\n * const excludedDiffs = store.saveDocument('api')\n */\n saveDocument,\n /**\n * Restores the specified document to its last locally saved state.\n *\n * This method updates the current reactive document (in the workspace) with the contents of the\n * corresponding intermediate document (from the `intermediateDocuments` map), effectively discarding\n * any unsaved in-memory changes and reverting to the last saved version.\n * Vue reactivity is preserved by updating the existing reactive object in place.\n *\n * **Warning:** This operation will discard all unsaved (in-memory) changes to the specified document.\n *\n * @param documentName - The name of the document to restore.\n * @returns void\n *\n * @example\n * // Restore the document named 'api' to its last saved state\n * store.revertDocumentChanges('api')\n */\n revertDocumentChanges(documentName: string) {\n const workspaceDocument = workspace.documents[documentName]\n\n if (!workspaceDocument) {\n return\n }\n\n const intermediateDocument = intermediateDocuments[documentName]\n // Get the raw state of the current document to avoid diffing resolved references.\n // This ensures we update the actual data, not the references.\n // Note: We keep the Vue proxy for reactivity by updating the object in place.\n const updatedDocument = createOverridesProxy(getRaw(workspaceDocument), overrides[documentName])\n\n if (!intermediateDocument || !updatedDocument) {\n return\n }\n\n // Overwrite the current document with the last saved state, discarding unsaved changes.\n applySelectiveUpdates(updatedDocument, intermediateDocument)\n },\n /**\n * Commits the specified document.\n *\n * This method is intended to finalize and persist the current state of the document,\n * potentially syncing it with a remote registry or marking it as the latest committed version.\n *\n * @param documentName - The name of the document to commit.\n * @remarks\n * The actual commit logic is not implemented yet.\n */\n commitDocument(documentName: string) {\n // TODO: Implement commit logic\n console.warn(`Commit operation for document '${documentName}' is not implemented yet.`)\n },\n /**\n * Serializes the current workspace state to a JSON string for backup, persistence, or sharing.\n *\n * This method exports all workspace documents (removing Vue reactivity proxies), workspace metadata,\n * document configurations, and both the original and intermediate document states. The resulting JSON\n * can be imported later to fully restore the workspace to this exact state, including all documents\n * and their configurations.\n *\n * @returns A JSON string representing the complete workspace state.\n */\n exportWorkspace() {\n return JSON.stringify({\n documents: {\n ...Object.fromEntries(\n Object.entries(workspace.documents).map(([name, doc]) => [\n name,\n // Extract the raw document data for export, removing any Vue reactivity wrappers.\n // When importing, the document can be wrapped again in a magic proxy.\n createOverridesProxy(getRaw(doc), overrides[name]),\n ]),\n ),\n },\n meta: workspaceProps?.meta ?? {},\n documentConfigs,\n originalDocuments,\n intermediateDocuments,\n } as InMemoryWorkspace)\n },\n /**\n * Imports a workspace from a serialized JSON string.\n *\n * This method parses the input string using the InMemoryWorkspaceSchema,\n * then updates the current workspace state, including documents, metadata,\n * and configuration, with the imported values.\n *\n * @param input - The serialized workspace JSON string to import.\n */\n loadWorkspace(input: string) {\n const result = coerceValue(InMemoryWorkspaceSchema, JSON.parse(input))\n\n // Assign the magic proxy to the documents\n safeAssign(\n workspace.documents,\n Object.fromEntries(Object.entries(result.documents).map(([name, doc]) => [name, createMagicProxy(doc)])),\n )\n\n safeAssign(originalDocuments, result.originalDocuments)\n safeAssign(intermediateDocuments, result.intermediateDocuments)\n safeAssign(documentConfigs, result.documentConfigs)\n safeAssign(workspace, result.meta)\n },\n /**\n * Imports a workspace from a WorkspaceSpecification object.\n *\n * This method assigns workspace metadata and adds all documents defined in the specification.\n * Each document is added using its $ref and optional overrides.\n *\n * @example\n * ```ts\n * await store.importWorkspaceFromSpecification({\n * documents: {\n * api: { $ref: '/specs/api.yaml' },\n * petstore: { $ref: '/specs/petstore.yaml' }\n * },\n * overrides: {\n * api: { config: { features: { showModels: true } } }\n * },\n * info: { title: 'My Workspace' },\n * workspace: 'v1',\n * \"x-scalar-dark-mode\": true\n * })\n * ```\n *\n * @param specification - The workspace specification to import.\n */\n importWorkspaceFromSpecification: (specification: WorkspaceSpecification) => {\n const { documents, overrides, info, workspace: workspaceVersion, ...meta } = specification\n\n // Assign workspace metadata\n safeAssign(workspace, meta)\n\n // Add workspace documents\n return Promise.all(\n Object.entries(documents ?? {}).map(([name, doc]) =>\n addDocument({ url: doc.$ref, name, overrides: overrides?.[name] }),\n ),\n )\n },\n }\n}\n\n// biome-ignore lint/performance/noBarrelFile: <explanation>\nexport { generateClientMutators } from '@/mutators'\n"],
|
|
5
|
-
"mappings": "AAAA,OAAO,UAAU;AACjB,SAAS,gBAAgB;AACzB,SAAS,
|
|
4
|
+
"sourcesContent": ["import YAML from 'yaml'\nimport { reactive } from 'vue'\nimport { upgrade } from '@scalar/openapi-parser'\nimport { createMagicProxy, getRaw } from '@scalar/json-magic/magic-proxy'\n\nimport type { DeepPartial, DeepRequired } from '@/types'\nimport { applySelectiveUpdates } from '@/helpers/apply-selective-updates'\nimport { deepClone, isObject, safeAssign } from '@/helpers/general'\nimport { getValueByPath } from '@/helpers/json-path-utils'\nimport { mergeObjects } from '@/helpers/merge-object'\nimport { createNavigation, type createNavigationOptions } from '@/navigation'\nimport { extensions } from '@/schemas/extensions'\nimport { coerceValue } from '@/schemas/typebox-coerce'\nimport { OpenAPIDocumentSchema, type OpenApiDocument } from '@/schemas/v3.1/strict/openapi-document'\nimport { defaultReferenceConfig } from '@/schemas/reference-config'\nimport type { Config } from '@/schemas/workspace-specification/config'\nimport { InMemoryWorkspaceSchema, type InMemoryWorkspace } from '@/schemas/inmemory-workspace'\nimport type { WorkspaceSpecification } from '@/schemas/workspace-specification'\nimport { createOverridesProxy } from '@/helpers/overrides-proxy'\nimport type { Workspace, WorkspaceDocumentMeta, WorkspaceMeta } from '@/schemas/workspace'\nimport { bundle } from '@scalar/json-magic/bundle'\nimport { fetchUrls } from '@scalar/json-magic/bundle/plugins/browser'\nimport { apply, diff, merge, type Difference } from '@scalar/json-magic/diff'\n\n/**\n * Input type for workspace document metadata and configuration.\n * This type defines the required and optional fields for initializing a document in the workspace.\n *\n * TODO: merge navigation options with the document config\n */\ntype WorkspaceDocumentMetaInput = {\n /** Optional metadata about the document like title, description, etc */\n meta?: WorkspaceDocumentMeta\n /** Required unique identifier for the document */\n name: string\n /** Optional configuration for generating navigation structure */\n config?: Config & Partial<createNavigationOptions>\n /** Overrides for the document */\n overrides?: DeepPartial<OpenApiDocument>\n}\n\n/**\n * Represents a document that is loaded from a URL.\n * This type extends WorkspaceDocumentMetaInput to include URL-specific properties.\n */\nexport type UrlDoc = {\n /** URL to fetch the OpenAPI document from */\n url: string\n /** Optional custom fetch implementation to use when retrieving the document. By default the global fetch implementation will be used */\n fetch?: (input: string | URL | globalThis.Request, init?: RequestInit) => Promise<Response>\n} & WorkspaceDocumentMetaInput\n\n/** Represents a document that is provided directly as an object rather than loaded from a URL */\nexport type ObjectDoc = {\n /** The OpenAPI document object containing the API specification */\n document: Record<string, unknown>\n} & WorkspaceDocumentMetaInput\n\n/**\n * Union type representing the possible input formats for a workspace document:\n * - UrlDoc: Document loaded from a URL with optional fetch configuration\n * - ObjectDoc: Direct document object with metadata\n */\nexport type WorkspaceDocumentInput = UrlDoc | ObjectDoc\n\nconst defaultConfig: DeepRequired<Config> = {\n 'x-scalar-reference-config': defaultReferenceConfig,\n}\n\n/**\n * Resolves a workspace document from various input sources (URL, local file, or direct document object).\n *\n * @param workspaceDocument - The document input to resolve, which can be:\n * - A URL to fetch the document from\n * - A direct document object\n * @returns A promise that resolves to an object containing:\n * - ok: boolean indicating if the resolution was successful\n * - data: The resolved document data\n *\n * @example\n * // Resolve from URL\n * const urlDoc = await loadDocument({ name: 'api', url: 'https://api.example.com/openapi.json' })\n *\n * // Resolve direct document\n * const directDoc = await loadDocument({\n * name: 'inline',\n * document: { openapi: '3.0.0', paths: {} }\n * })\n */\nasync function loadDocument(workspaceDocument: WorkspaceDocumentInput) {\n if ('url' in workspaceDocument) {\n return fetchUrls({ fetch: workspaceDocument.fetch }).exec(workspaceDocument.url)\n }\n\n return {\n ok: true as const,\n data: workspaceDocument.document,\n }\n}\n\n/**\n * Configuration object for initializing a workspace store.\n * Defines the initial state and documents for the workspace.\n */\ntype WorkspaceProps = {\n /** Optional metadata for the workspace including theme, active document, etc */\n meta?: WorkspaceMeta\n /** Workspace configuration */\n config?: Config\n}\n\n/**\n * Type definition for the workspace store return object.\n * This explicit type is needed to avoid TypeScript inference limits.\n *\n * @see https://github.com/microsoft/TypeScript/issues/43817#issuecomment-827746462\n */\nexport type WorkspaceStore = {\n /** Returns the reactive workspace object with an additional activeDocument getter */\n readonly workspace: Workspace\n /** Updates a specific metadata field in the workspace */\n update<K extends keyof WorkspaceMeta>(key: K, value: WorkspaceMeta[K]): void\n /** Updates a specific metadata field in a document */\n updateDocument<K extends keyof WorkspaceDocumentMeta>(\n name: 'active' | (string & {}),\n key: K,\n value: WorkspaceDocumentMeta[K],\n ): void\n /** Replaces the content of a specific document in the workspace with the provided input */\n replaceDocument(documentName: string, input: Record<string, unknown>): void\n /** Resolves a reference in the active document by following the provided path and resolving any external $ref references */\n resolve(path: string[]): Promise<unknown>\n /** Adds a new document to the workspace */\n addDocument(input: WorkspaceDocumentInput): Promise<void>\n /** Returns the merged configuration for the active document */\n readonly config: typeof defaultConfig\n /** Downloads the specified document in the requested format */\n exportDocument(documentName: string, format: 'json' | 'yaml'): string | undefined\n /** Persists the current state of the specified document back to the original documents map */\n saveDocument(documentName: string): unknown[] | undefined\n /** Reverts the specified document to its original state */\n revertDocumentChanges(documentName: string): void\n /** Commits the specified document */\n commitDocument(documentName: string): void\n /** Serializes the current workspace state to a JSON string for backup, persistence, or sharing. */\n exportWorkspace(): string\n /** Imports a workspace from a serialized JSON string. */\n loadWorkspace(input: string): void\n /** Imports a workspace from a specification object */\n importWorkspaceFromSpecification(specification: WorkspaceSpecification): Promise<void[]>\n /** Rebase document with a remote origin */\n rebaseDocument: (\n documentName: string,\n newDocumentOrigin: Record<string, unknown>,\n resolvedConflicts?: Difference[],\n ) => void | ReturnType<typeof merge>['conflicts']\n}\n\n/**\n * Creates a reactive workspace store that manages documents and their metadata.\n * The store provides functionality for accessing, updating, and resolving document references.\n *\n * @param workspaceProps - Configuration object for the workspace\n * @param workspaceProps.meta - Optional metadata for the workspace\n * @param workspaceProps.documents - Optional record of documents to initialize the workspace with\n * Documents that require asynchronous loading must be added using `addDocument` after the store is created\n * this allows atomic awaiting and does not block page load for the store initialization\n * @returns An object containing methods and getters for managing the workspace\n */\nexport const createWorkspaceStore = (workspaceProps?: WorkspaceProps): WorkspaceStore => {\n /**\n * Holds the original, unmodified documents as they were initially loaded into the workspace.\n * These documents are stored in their raw form\u2014prior to any reactive wrapping, dereferencing, or bundling.\n * This map preserves the pristine structure of each document, using deep clones to ensure that\n * subsequent mutations in the workspace do not affect the originals.\n * The originals are retained so that we can restore, compare, or sync with the remote registry as needed.\n */\n const originalDocuments = {} as Workspace['documents']\n /**\n * Stores the intermediate state of documents after local edits but before syncing with the remote registry.\n *\n * This map acts as a local \"saved\" version of the document, reflecting the user's changes after they hit \"save\".\n * The `originalDocuments` map, by contrast, always mirrors the document as it exists in the remote registry.\n *\n * Use this map to stage local changes that are ready to be propagated back to the remote registry.\n * This separation allows us to distinguish between:\n * - The last known remote version (`originalDocuments`)\n * - The latest locally saved version (`intermediateDocuments`)\n * - The current in-memory (possibly unsaved) workspace document (`workspace.documents`)\n */\n const intermediateDocuments = {} as Workspace['documents']\n /**\n * A map of document configurations keyed by document name.\n * This stores the configuration options for each document in the workspace,\n * allowing for document-specific settings like navigation options, appearance,\n * and other reference configuration.\n */\n const documentConfigs: Record<string, Config> = {}\n /**\n * Stores per-document overrides for OpenAPI documents.\n * This object is used to override specific fields of a document\n * when you cannot (or should not) modify the source document directly.\n * For example, this enables UI-driven or temporary changes to be applied\n * on top of the original document, without mutating the source.\n * The key is the document name, and the value is a deep partial\n * OpenAPI document representing the overridden fields.\n */\n const overrides: Record<string, DeepPartial<OpenApiDocument>> = {}\n\n // Create a reactive workspace object with proxied documents\n // Each document is wrapped in a proxy to enable reactive updates and reference resolution\n const workspace = reactive<Workspace>({\n ...workspaceProps?.meta,\n documents: {},\n /**\n * Returns the currently active document from the workspace.\n * The active document is determined by the 'x-scalar-active-document' metadata field,\n * falling back to the first document in the workspace if no active document is specified.\n *\n * @returns The active document or undefined if no document is found\n */\n get activeDocument(): NonNullable<Workspace['activeDocument']> | undefined {\n const activeDocumentKey =\n workspace[extensions.workspace.activeDocument] ?? Object.keys(workspace.documents)[0] ?? ''\n return workspace.documents[activeDocumentKey]\n },\n })\n\n /**\n * Returns the name of the currently active document in the workspace.\n * The active document is determined by the 'x-scalar-active-document' metadata field,\n * falling back to the first document in the workspace if no active document is specified.\n *\n * @returns The name of the active document or an empty string if no document is found\n */\n function getActiveDocumentName() {\n return workspace[extensions.workspace.activeDocument] ?? Object.keys(workspace.documents)[0] ?? ''\n }\n\n // Save the current state of the specified document to the intermediate documents map.\n // This function captures the latest (reactive) state of the document from the workspace and\n // applies its changes to the corresponding entry in the `intermediateDocuments` map.\n // The `intermediateDocuments` map represents the most recently \"saved\" local version of the document,\n // which may include edits not yet synced to the remote registry.\n function saveDocument(documentName: string) {\n const intermediateDocument = intermediateDocuments[documentName]\n const workspaceDocument = workspace.documents[documentName]\n\n if (!workspaceDocument) {\n return\n }\n\n // Obtain the raw state of the current document to ensure accurate diffing\n const updatedDocument = getRaw(workspaceDocument)\n\n // If either the intermediate or updated document is missing, do nothing\n if (!intermediateDocument || !updatedDocument) {\n return\n }\n\n // Apply changes from the current document to the intermediate document in place\n const excludedDiffs = applySelectiveUpdates(intermediateDocument, updatedDocument)\n return excludedDiffs\n }\n\n // Add a document to the store synchronously from an in-memory OpenAPI document\n async function addInMemoryDocument(input: ObjectDoc) {\n const { name, meta } = input\n\n const document = coerceValue(OpenAPIDocumentSchema, upgrade(input.document).specification)\n\n // Store the original document in the originalDocuments map\n // This is used to track the original state of the document as it was loaded into the workspace\n originalDocuments[name] = deepClone({ ...document, ...meta })\n\n // Store the intermediate document state for local edits\n // This is used to track the last saved state of the document\n // It allows us to differentiate between the original document and the latest saved version\n // This is important for local edits that are not yet synced with the remote registry\n // The intermediate document is used to store the latest saved state of the document\n // This allows us to track changes and revert to the last saved state if needed\n intermediateDocuments[name] = deepClone({ ...document, ...meta })\n // Add the document config to the documentConfigs map\n documentConfigs[name] = input.config ?? {}\n // Store the overrides for this document, or an empty object if none are provided\n overrides[name] = input.overrides ?? {}\n\n // Skip navigation generation if the document already has a server-side generated navigation structure\n if (document[extensions.document.navigation] === undefined) {\n document[extensions.document.navigation] = createNavigation(document, input.config ?? {}).entries\n }\n\n // If the document navigation is not already present, bundle the entire document to resolve all references.\n // This typically applies when the document is not preprocessed by the server and needs local reference resolution.\n if (document[extensions.document.navigation] === undefined) {\n await bundle(input.document, { treeShake: false, plugins: [fetchUrls()] })\n }\n\n // Create a proxied document with magic proxy and apply any overrides, then store it in the workspace documents map\n workspace.documents[name] = createOverridesProxy(createMagicProxy({ ...document, ...meta }), input.overrides)\n }\n\n // Asynchronously adds a new document to the workspace by loading and validating the input.\n // If loading fails, a placeholder error document is added instead.\n async function addDocument(input: WorkspaceDocumentInput) {\n const { name, meta } = input\n\n const resolve = await loadDocument(input)\n\n if (!resolve.ok) {\n console.error(`Failed to fetch document '${name}': request was not successful`)\n\n workspace.documents[name] = {\n ...meta,\n openapi: '3.1.0',\n info: {\n title: `Document '${name}' could not be loaded`,\n version: 'unknown',\n },\n }\n\n return\n }\n\n if (!isObject(resolve.data)) {\n console.error(`Failed to load document '${name}': response data is not a valid object`)\n\n workspace.documents[name] = {\n ...meta,\n openapi: '3.1.0',\n info: {\n title: `Document '${name}' could not be loaded`,\n version: 'unknown',\n },\n }\n\n return\n }\n\n await addInMemoryDocument({ ...input, document: resolve.data })\n }\n\n // Cache to track visited nodes during reference resolution to prevent bundling the same subtree multiple times\n // This is needed because we are doing partial bundle operations\n const visitedNodesCache = new Set()\n\n return {\n /**\n * Returns the reactive workspace object with an additional activeDocument getter\n */\n get workspace() {\n return workspace\n },\n /**\n * Updates a specific metadata field in the workspace\n * @param key - The metadata field to update\n * @param value - The new value for the field\n * @example\n * // Update the workspace title\n * update('x-scalar-active-document', 'document-name')\n */\n update<K extends keyof WorkspaceMeta>(key: K, value: WorkspaceMeta[K]) {\n // @ts-ignore\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n throw new Error('Invalid key: cannot modify prototype')\n }\n Object.assign(workspace, { [key]: value })\n },\n /**\n * Updates a specific metadata field in a document\n * @param name - The name of the document to update ('active' or a specific document name)\n * @param key - The metadata field to update\n * @param value - The new value for the field\n * @throws Error if the specified document doesn't exist\n * @example\n * // Update the auth of the active document\n * updateDocument('active', 'x-scalar-active-auth', 'Bearer')\n * // Update the auth of a specific document\n * updateDocument('document-name', 'x-scalar-active-auth', 'Bearer')\n */\n updateDocument<K extends keyof WorkspaceDocumentMeta>(\n name: 'active' | (string & {}),\n key: K,\n value: WorkspaceDocumentMeta[K],\n ) {\n const currentDocument = workspace.documents[name === 'active' ? getActiveDocumentName() : name]\n\n if (!currentDocument) {\n throw 'Please select a valid document'\n }\n\n Object.assign(currentDocument, { [key]: value })\n },\n /**\n * Replaces the content of a specific document in the workspace with the provided input.\n * This method computes the difference between the current document and the new input,\n * then applies only the necessary changes in place. The updates are applied atomically,\n * ensuring the document is updated in a single operation.\n *\n * @param documentName - The name of the document to update.\n * @param input - The new content to apply to the document (as a plain object).\n * @example\n * // Replace the content of the 'api' document with new data\n * store.replaceDocument('api', {\n * openapi: '3.1.0',\n * info: { title: 'Updated API', version: '1.0.1' },\n * paths: {},\n * })\n */\n replaceDocument(documentName: string, input: Record<string, unknown>) {\n const currentDocument = workspace.documents[documentName]\n\n if (!currentDocument) {\n return console.error(`Document '${documentName}' does not exist in the workspace.`)\n }\n\n // Normalize the input document to ensure it matches the OpenAPI schema and is upgraded to the latest version.\n const newDocument = coerceValue(OpenAPIDocumentSchema, upgrade(input).specification)\n // Update the current document in place, applying only the necessary changes and omitting any preprocessing fields.\n applySelectiveUpdates(currentDocument, newDocument)\n },\n /**\n * Resolves a reference in the active document by following the provided path and resolving any external $ref references.\n * This method traverses the document structure following the given path and resolves any $ref references it encounters.\n * During resolution, it sets a loading status and updates the reference with the resolved content.\n *\n * @param path - Array of strings representing the path to the reference (e.g. ['paths', '/users', 'get', 'responses', '200'])\n * @throws Error if the path is invalid or empty\n * @example\n * // Resolve a reference in the active document\n * resolve(['paths', '/users', 'get', 'responses', '200'])\n */\n resolve: async (path: string[]) => {\n const activeDocument = workspace.activeDocument\n\n const target = getValueByPath(activeDocument, path)\n\n if (!isObject(target)) {\n console.error(\n `Invalid path provided for resolution. Path: [${path.join(', ')}]. Found value of type: ${typeof target}. Expected an object.`,\n )\n return\n }\n\n // Bundle the target document with the active document as root, resolving any external references\n // and tracking resolution status through hooks\n return bundle(target, {\n root: activeDocument,\n treeShake: false,\n plugins: [fetchUrls()],\n urlMap: false,\n hooks: {\n onResolveStart: (node) => {\n node['$status'] = 'loading'\n },\n onResolveError: (node) => {\n node['$status'] = 'error'\n },\n },\n visitedNodes: visitedNodesCache,\n })\n },\n /**\n * Adds a new document to the workspace\n * @param document - The document content to add. This should be a valid OpenAPI/Swagger document or other supported format\n * @param meta - Metadata for the document, including its name and other properties defined in WorkspaceDocumentMeta\n * @example\n * // Add a new OpenAPI document to the workspace\n * store.addDocument({\n * name: 'name',\n * document: {\n * openapi: '3.0.0',\n * info: { title: 'title' },\n * },\n * meta: {\n * 'x-scalar-active-auth': 'Bearer',\n * 'x-scalar-active-server': 'production'\n * }\n * })\n */\n addDocument,\n /**\n * Returns the merged configuration for the active document.\n *\n * This getter merges configurations in the following order of precedence:\n * 1. Document-specific configuration (highest priority)\n * 2. Workspace-level configuration\n * 3. Default configuration (lowest priority)\n *\n * The active document is determined by the workspace's activeDocument extension,\n * falling back to the first document if none is specified.\n */\n get config() {\n return mergeObjects<typeof defaultConfig>(\n mergeObjects(defaultConfig, workspaceProps?.config ?? {}),\n documentConfigs[getActiveDocumentName()] ?? {},\n )\n },\n /**\n * Exports the specified document in the requested format.\n *\n * This method serializes the most recently saved local version of the document (from the intermediateDocuments map)\n * to either JSON or YAML. The exported document reflects the last locally saved state, including any edits\n * that have been saved but not yet synced to a remote registry. Runtime/in-memory changes that have not been saved\n * will not be included.\n *\n * @param documentName - The name of the document to export.\n * @param format - The output format: 'json' for a JSON string, or 'yaml' for a YAML string.\n * @returns The document as a string in the requested format, or undefined if the document does not exist.\n *\n * @example\n * // Export a document as JSON\n * const jsonString = store.exportDocument('api', 'json')\n *\n * // Export a document as YAML\n * const yamlString = store.exportDocument('api', 'yaml')\n */\n exportDocument: (documentName: string, format: 'json' | 'yaml') => {\n const intermediateDocument = intermediateDocuments[documentName]\n\n if (!intermediateDocument) {\n return\n }\n\n if (format === 'json') {\n return JSON.stringify(intermediateDocument)\n }\n\n return YAML.stringify(intermediateDocument)\n },\n /**\n * Saves the current state of the specified document to the intermediate documents map.\n *\n * This function captures the latest (reactive) state of the document from the workspace and\n * applies its changes to the corresponding entry in the `intermediateDocuments` map.\n * The `intermediateDocuments` map represents the most recently \"saved\" local version of the document,\n * which may include edits not yet synced to the remote registry.\n *\n * The update is performed in-place. A deep clone of the current document\n * state is used to avoid mutating the reactive object directly.\n *\n * @param documentName - The name of the document to save.\n * @returns An array of diffs that were excluded from being applied (such as changes to ignored keys),\n * or undefined if the document does not exist or cannot be updated.\n *\n * @example\n * // Save the current state of the document named 'api'\n * const excludedDiffs = store.saveDocument('api')\n */\n saveDocument,\n /**\n * Restores the specified document to its last locally saved state.\n *\n * This method updates the current reactive document (in the workspace) with the contents of the\n * corresponding intermediate document (from the `intermediateDocuments` map), effectively discarding\n * any unsaved in-memory changes and reverting to the last saved version.\n * Vue reactivity is preserved by updating the existing reactive object in place.\n *\n * **Warning:** This operation will discard all unsaved (in-memory) changes to the specified document.\n *\n * @param documentName - The name of the document to restore.\n * @returns void\n *\n * @example\n * // Restore the document named 'api' to its last saved state\n * store.revertDocumentChanges('api')\n */\n revertDocumentChanges(documentName: string) {\n const workspaceDocument = workspace.documents[documentName]\n\n if (!workspaceDocument) {\n return\n }\n\n const intermediateDocument = intermediateDocuments[documentName]\n // Get the raw state of the current document to avoid diffing resolved references.\n const updatedDocument = getRaw(workspaceDocument)\n\n if (!intermediateDocument || !updatedDocument) {\n return\n }\n\n // Overwrite the current document with the last saved state, discarding unsaved changes.\n applySelectiveUpdates(updatedDocument, intermediateDocument)\n },\n /**\n * Commits the specified document.\n *\n * This method is intended to finalize and persist the current state of the document,\n * potentially syncing it with a remote registry or marking it as the latest committed version.\n *\n * @param documentName - The name of the document to commit.\n * @remarks\n * The actual commit logic is not implemented yet.\n */\n commitDocument(documentName: string) {\n // TODO: Implement commit logic\n console.warn(`Commit operation for document '${documentName}' is not implemented yet.`)\n },\n /**\n * Serializes the current workspace state to a JSON string for backup, persistence, or sharing.\n *\n * This method exports all workspace documents (removing Vue reactivity proxies), workspace metadata,\n * document configurations, and both the original and intermediate document states. The resulting JSON\n * can be imported later to fully restore the workspace to this exact state, including all documents\n * and their configurations.\n *\n * @returns A JSON string representing the complete workspace state.\n */\n exportWorkspace() {\n return JSON.stringify({\n documents: {\n ...Object.fromEntries(\n Object.entries(workspace.documents).map(([name, doc]) => [\n name,\n // Extract the raw document data for export, removing any Vue reactivity wrappers.\n // When importing, the document can be wrapped again in a magic proxy.\n createOverridesProxy(getRaw(doc), overrides[name]),\n ]),\n ),\n },\n meta: workspaceProps?.meta ?? {},\n documentConfigs,\n originalDocuments,\n intermediateDocuments,\n overrides,\n } as InMemoryWorkspace)\n },\n /**\n * Imports a workspace from a serialized JSON string.\n *\n * This method parses the input string using the InMemoryWorkspaceSchema,\n * then updates the current workspace state, including documents, metadata,\n * and configuration, with the imported values.\n *\n * @param input - The serialized workspace JSON string to import.\n */\n loadWorkspace(input: string) {\n const result = coerceValue(InMemoryWorkspaceSchema, JSON.parse(input))\n\n // Assign the magic proxy to the documents\n safeAssign(\n workspace.documents,\n Object.fromEntries(Object.entries(result.documents).map(([name, doc]) => [name, createMagicProxy(doc)])),\n )\n\n safeAssign(originalDocuments, result.originalDocuments)\n safeAssign(intermediateDocuments, result.intermediateDocuments)\n safeAssign(documentConfigs, result.documentConfigs)\n safeAssign(overrides, result.overrides)\n safeAssign(workspace, result.meta)\n },\n /**\n * Imports a workspace from a WorkspaceSpecification object.\n *\n * This method assigns workspace metadata and adds all documents defined in the specification.\n * Each document is added using its $ref and optional overrides.\n *\n * @example\n * ```ts\n * await store.importWorkspaceFromSpecification({\n * documents: {\n * api: { $ref: '/specs/api.yaml' },\n * petstore: { $ref: '/specs/petstore.yaml' }\n * },\n * overrides: {\n * api: { config: { features: { showModels: true } } }\n * },\n * info: { title: 'My Workspace' },\n * workspace: 'v1',\n * \"x-scalar-dark-mode\": true\n * })\n * ```\n *\n * @param specification - The workspace specification to import.\n */\n importWorkspaceFromSpecification: (specification: WorkspaceSpecification) => {\n const { documents, overrides, info, workspace: workspaceVersion, ...meta } = specification\n\n // Assign workspace metadata\n safeAssign(workspace, meta)\n\n // Add workspace documents\n return Promise.all(\n Object.entries(documents ?? {}).map(([name, doc]) =>\n addDocument({ url: doc.$ref, name, overrides: overrides?.[name] }),\n ),\n )\n },\n /**\n * Rebases a document in the workspace with a new origin, resolving conflicts if provided.\n *\n * This method is used to rebase a document (e.g., after pulling remote changes) by applying the changes\n * from the new origin and merging them with local edits. If there are conflicts, they can be resolved\n * by providing a list of resolved conflicts.\n *\n * @param documentName - The name of the document to rebase.\n * @param newDocumentOrigin - The new origin document (as an object) to rebase onto.\n * @param resolvedConflicts - (Optional) An array of resolved conflicts to apply.\n * @returns If there are unresolved conflicts and no resolution is provided, returns the list of conflicts.\n *\n * @example\n * // Example: Rebase a document with a new origin and resolve conflicts\n * const conflicts = store.rebaseDocument('api', newOriginDoc)\n * if (conflicts && conflicts.length > 0) {\n * // User resolves conflicts here...\n * store.rebaseDocument('api', newOriginDoc, userResolvedConflicts)\n * }\n */\n rebaseDocument: (\n documentName: string,\n newDocumentOrigin: Record<string, unknown>,\n resolvedConflicts?: Difference[],\n ) => {\n const newOrigin = coerceValue(OpenAPIDocumentSchema, upgrade(newDocumentOrigin).specification)\n\n const originalDocument = originalDocuments[documentName]\n const intermediateDocument = intermediateDocuments[documentName]\n const activeDocument = workspace.documents[documentName] ? getRaw(workspace.documents[documentName]) : undefined // raw version without any overrides\n\n if (!originalDocument || !intermediateDocument || !activeDocument) {\n // If any required document state is missing, do nothing\n return console.error('[ERROR]: Specified document is missing or internal corrupted workspace state')\n }\n\n // ---- Get the new intermediate document\n const changelogAA = diff(originalDocument, newOrigin)\n const changelogAB = diff(originalDocument, intermediateDocument)\n\n const changesA = merge(changelogAA, changelogAB)\n\n if (resolvedConflicts === undefined) {\n // If there are conflicts, return the list of conflicts for user resolution\n return changesA.conflicts\n }\n\n const changesetA = changesA.diffs.concat(resolvedConflicts)\n\n // Apply the changes to the original document to get the new intermediate\n const newIntermediateDocument = apply(deepClone(originalDocument), changesetA) as typeof originalDocument\n intermediateDocuments[documentName] = newIntermediateDocument\n\n // Update the original document\n originalDocuments[documentName] = newOrigin\n\n // ---- Get the new active document\n const changelogBA = diff(intermediateDocument, newIntermediateDocument)\n const changelogBB = diff(intermediateDocument, activeDocument)\n\n const changesB = merge(changelogBA, changelogBB)\n\n // Auto-conflict resolution: pick only the changes from the first changeset\n // TODO: In the future, implement smarter conflict resolution if needed\n const changesetB = changesB.diffs.concat(changesB.conflicts.flatMap((it) => it[0]))\n\n const newActiveDocument = apply(deepClone(newIntermediateDocument), changesetB) as typeof newIntermediateDocument\n\n // Update the active document to the new value\n workspace.documents[documentName] = createOverridesProxy(\n createMagicProxy({ ...newActiveDocument }),\n overrides[documentName],\n )\n return\n },\n }\n}\n\n// biome-ignore lint/performance/noBarrelFile: <explanation>\nexport { generateClientMutators } from '@/mutators'\n"],
|
|
5
|
+
"mappings": "AAAA,OAAO,UAAU;AACjB,SAAS,gBAAgB;AACzB,SAAS,eAAe;AACxB,SAAS,kBAAkB,cAAc;AAGzC,SAAS,6BAA6B;AACtC,SAAS,WAAW,UAAU,kBAAkB;AAChD,SAAS,sBAAsB;AAC/B,SAAS,oBAAoB;AAC7B,SA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
|
+
import { type Difference } from '@scalar/json-magic/diff';
|
|
3
3
|
/**
|
|
4
4
|
* Applies updates from an updated document to an original document, while excluding changes to certain metadata keys.
|
|
5
5
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apply-selective-updates.d.ts","sourceRoot":"","sources":["../../src/helpers/apply-selective-updates.ts"],"names":[],"mappings":"AAAA,OAAO,EAAS,KAAK,aAAa,EAAE,MAAM,mBAAmB,CAAA;AAC7D,OAAO,EAAe,KAAK,UAAU,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"apply-selective-updates.d.ts","sourceRoot":"","sources":["../../src/helpers/apply-selective-updates.ts"],"names":[],"mappings":"AAAA,OAAO,EAAS,KAAK,aAAa,EAAE,MAAM,mBAAmB,CAAA;AAC7D,OAAO,EAAe,KAAK,UAAU,EAAE,MAAM,yBAAyB,CAAA;AAMtE;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,qBAAqB,qBAAsB,aAAa,mBAAmB,aAAa,qCAQpG,CAAA"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { split } from "../helpers/general.js";
|
|
2
|
-
import { apply, diff } from "@scalar/json-diff";
|
|
2
|
+
import { apply, diff } from "@scalar/json-magic/diff";
|
|
3
3
|
const excludeKeys = /* @__PURE__ */ new Set(["x-scalar-navigation", "x-ext", "x-ext-urls", "$ref", "$status"]);
|
|
4
4
|
const applySelectiveUpdates = (originalDocument, updatedDocument) => {
|
|
5
5
|
const diffs = diff(originalDocument, updatedDocument);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/helpers/apply-selective-updates.ts"],
|
|
4
|
-
"sourcesContent": ["import { split, type UnknownObject } from '@/helpers/general'\nimport { apply, diff, type Difference } from '@scalar/json-diff'\n\n// Keys to exclude from the diff - these are metadata fields that should not be persisted\n// when applying updates to the original document\nconst excludeKeys = new Set(['x-scalar-navigation', 'x-ext', 'x-ext-urls', '$ref', '$status'])\n\n/**\n * Applies updates from an updated document to an original document, while excluding changes to certain metadata keys.\n *\n * This function computes the differences between the original and updated documents,\n * filters out any diffs that affect excluded keys (such as navigation, external references, or status fields),\n * and applies only the allowed changes to the original document in place.\n *\n * Note: The originalDocument is mutated directly.\n *\n * @param originalDocument - The document to be updated (mutated in place)\n * @param updatedDocument - The document containing the desired changes\n * @returns A tuple: [the updated original document, array of excluded diffs that were not applied]\n */\nexport const applySelectiveUpdates = (originalDocument: UnknownObject, updatedDocument: UnknownObject) => {\n const diffs: Difference[] = diff(originalDocument, updatedDocument)\n\n const [writableDiffs, excludedDiffs] = split(diffs, (d) => !d.path.some((p) => excludeKeys.has(p)))\n\n apply(originalDocument, writableDiffs)\n\n return [originalDocument, excludedDiffs]\n}\n"],
|
|
4
|
+
"sourcesContent": ["import { split, type UnknownObject } from '@/helpers/general'\nimport { apply, diff, type Difference } from '@scalar/json-magic/diff'\n\n// Keys to exclude from the diff - these are metadata fields that should not be persisted\n// when applying updates to the original document\nconst excludeKeys = new Set(['x-scalar-navigation', 'x-ext', 'x-ext-urls', '$ref', '$status'])\n\n/**\n * Applies updates from an updated document to an original document, while excluding changes to certain metadata keys.\n *\n * This function computes the differences between the original and updated documents,\n * filters out any diffs that affect excluded keys (such as navigation, external references, or status fields),\n * and applies only the allowed changes to the original document in place.\n *\n * Note: The originalDocument is mutated directly.\n *\n * @param originalDocument - The document to be updated (mutated in place)\n * @param updatedDocument - The document containing the desired changes\n * @returns A tuple: [the updated original document, array of excluded diffs that were not applied]\n */\nexport const applySelectiveUpdates = (originalDocument: UnknownObject, updatedDocument: UnknownObject) => {\n const diffs: Difference[] = diff(originalDocument, updatedDocument)\n\n const [writableDiffs, excludedDiffs] = split(diffs, (d) => !d.path.some((p) => excludeKeys.has(p)))\n\n apply(originalDocument, writableDiffs)\n\n return [originalDocument, excludedDiffs]\n}\n"],
|
|
5
5
|
"mappings": "AAAA,SAAS,aAAiC;AAC1C,SAAS,OAAO,YAA6B;AAI7C,MAAM,cAAc,oBAAI,IAAI,CAAC,uBAAuB,SAAS,cAAc,QAAQ,SAAS,CAAC;AAetF,MAAM,wBAAwB,CAAC,kBAAiC,oBAAmC;AACxG,QAAM,QAAsB,KAAK,kBAAkB,eAAe;AAElE,QAAM,CAAC,eAAe,aAAa,IAAI,MAAM,OAAO,CAAC,MAAM,CAAC,EAAE,KAAK,KAAK,CAAC,MAAM,YAAY,IAAI,CAAC,CAAC,CAAC;AAElG,QAAM,kBAAkB,aAAa;AAErC,SAAO,CAAC,kBAAkB,aAAa;AACzC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|