@scalar/workspace-store 0.10.2 → 0.11.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 CHANGED
@@ -1,5 +1,28 @@
1
1
  # @scalar/workspace-store
2
2
 
3
+ ## 0.11.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 9924c47: feat(workspace-store): support replacing the whole document
8
+ - a0c92d9: feat(workspace-store): create store from workspace specification object
9
+
10
+ ### Patch Changes
11
+
12
+ - a5534e6: fix: show path parameters on operation
13
+ - 6b6c72c: fix: hiddenClients: true and move clients to workspace store
14
+ - Updated dependencies [ccf875a]
15
+ - Updated dependencies [d4cb86b]
16
+ - Updated dependencies [94d6d0c]
17
+ - Updated dependencies [c345d2c]
18
+ - Updated dependencies [c0d6793]
19
+ - Updated dependencies [f3d0216]
20
+ - @scalar/openapi-types@0.3.7
21
+ - @scalar/types@0.2.11
22
+ - @scalar/code-highlight@0.1.9
23
+ - @scalar/openapi-parser@0.18.3
24
+ - @scalar/helpers@0.0.7
25
+
3
26
  ## 0.10.2
4
27
 
5
28
  ### Patch Changes
package/README.md CHANGED
@@ -368,4 +368,63 @@ const currentWorkspaceState = client.exportWorkspace()
368
368
 
369
369
  // Reload the workspace state
370
370
  client.loadWorkspace(currentWorkspaceState)
371
+ ```
372
+
373
+ ### Replace the Entire Document
374
+
375
+ When you have a new or updated OpenAPI document and want to overwrite the existing one—regardless of which parts have changed—you can use the `replaceDocument` method. This method efficiently and atomically updates the entire document in place, ensuring that only the necessary changes are applied for optimal performance.
376
+
377
+ ```ts
378
+ const client = createWorkspaceStore({
379
+ documents: [
380
+ {
381
+ name: 'document-name',
382
+ document: {
383
+ openapi: '3.1.0',
384
+ info: {
385
+ title: 'Document Title',
386
+ version: '1.0.0',
387
+ },
388
+ paths: {},
389
+ components: {
390
+ schemas: {},
391
+ },
392
+ servers: [],
393
+ },
394
+ },
395
+ ],
396
+ })
397
+
398
+ // Update the document with the new changes
399
+ client.replaceDocument('document-name', {
400
+ openapi: '3.1.0',
401
+ info: {
402
+ title: 'Updated Document',
403
+ version: '1.0.0',
404
+ },
405
+ paths: {},
406
+ components: {
407
+ schemas: {},
408
+ },
409
+ servers: [],
410
+ })
411
+ ```
412
+
413
+ ### Create workspace from specification
414
+
415
+ Create the workspace from a specification object
416
+
417
+ ```ts
418
+ await store.importWorkspaceFromSpecification({
419
+ workspace: 'v1',
420
+ info: { title: 'My Workspace' },
421
+ documents: {
422
+ api: { $ref: '/examples/api.yaml' },
423
+ petstore: { $ref: '/examples/petstore.yaml' }
424
+ },
425
+ overrides: {
426
+ api: { config: { features: { showModels: true } } }
427
+ },
428
+ "x-scalar-dark-mode": true
429
+ })
371
430
  ```
package/dist/client.d.ts CHANGED
@@ -1,7 +1,9 @@
1
+ import type { DeepPartial, DeepRequired } from './types.js';
1
2
  import { type createNavigationOptions } from './navigation/index.js';
2
- import type { Workspace, WorkspaceDocumentMeta, WorkspaceMeta } from './schemas/workspace.js';
3
+ import { type OpenApiDocument } from './schemas/v3.1/strict/openapi-document.js';
3
4
  import type { Config } from './schemas/workspace-specification/config.js';
4
- import type { DeepTransform } from './types.js';
5
+ import type { WorkspaceSpecification } from './schemas/workspace-specification/index.js';
6
+ import type { Workspace, WorkspaceDocumentMeta, WorkspaceMeta } from './schemas/workspace.js';
5
7
  /**
6
8
  * Input type for workspace document metadata and configuration.
7
9
  * This type defines the required and optional fields for initializing a document in the workspace.
@@ -15,6 +17,8 @@ type WorkspaceDocumentMetaInput = {
15
17
  name: string;
16
18
  /** Optional configuration for generating navigation structure */
17
19
  config?: Config & Partial<createNavigationOptions>;
20
+ /** Overrides for the document */
21
+ overrides?: DeepPartial<OpenApiDocument>;
18
22
  };
19
23
  /**
20
24
  * Represents a document that is loaded from a URL.
@@ -37,7 +41,7 @@ export type ObjectDoc = {
37
41
  * - ObjectDoc: Direct document object with metadata
38
42
  */
39
43
  export type WorkspaceDocumentInput = UrlDoc | ObjectDoc;
40
- declare const defaultConfig: DeepTransform<Config, 'NonNullable'>;
44
+ declare const defaultConfig: DeepRequired<Config>;
41
45
  /**
42
46
  * Configuration object for initializing a workspace store.
43
47
  * Defines the initial state and documents for the workspace.
@@ -63,6 +67,8 @@ export type WorkspaceStore = {
63
67
  update<K extends keyof WorkspaceMeta>(key: K, value: WorkspaceMeta[K]): void;
64
68
  /** Updates a specific metadata field in a document */
65
69
  updateDocument<K extends keyof WorkspaceDocumentMeta>(name: 'active' | (string & {}), key: K, value: WorkspaceDocumentMeta[K]): void;
70
+ /** Replaces the content of a specific document in the workspace with the provided input */
71
+ replaceDocument(documentName: string, input: Record<string, unknown>): void;
66
72
  /** Resolves a reference in the active document by following the provided path and resolving any external $ref references */
67
73
  resolve(path: string[]): Promise<unknown>;
68
74
  /** Adds a new document to the workspace */
@@ -83,6 +89,8 @@ export type WorkspaceStore = {
83
89
  exportWorkspace(): string;
84
90
  /** Imports a workspace from a serialized JSON string. */
85
91
  loadWorkspace(input: string): void;
92
+ /** Imports a workspace from a specification object */
93
+ importWorkspaceFromSpecification(specification: WorkspaceSpecification): Promise<void[]>;
86
94
  };
87
95
  /**
88
96
  * Creates a reactive workspace store that manages documents and their metadata.
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAUA,OAAO,EAAoB,KAAK,uBAAuB,EAAE,MAAM,cAAc,CAAA;AAM7E,OAAO,KAAK,EAAE,SAAS,EAAE,qBAAqB,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAC1F,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,0CAA0C,CAAA;AACtE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAE5C;;;;;GAKG;AACH,KAAK,0BAA0B,GAAG;IAChC,wEAAwE;IACxE,IAAI,CAAC,EAAE,qBAAqB,CAAA;IAC5B,kDAAkD;IAClD,IAAI,EAAE,MAAM,CAAA;IACZ,iEAAi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M,GAAG,IAAI,CAAA;IACjD,qCAAqC;IACrC,cAAc,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI,CAAA;IAC1C,mGAAmG;IACnG,eAAe,IAAI,MAAM,CAAA;IACzB,yDAAyD;IACzD,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;IAClC,sDAAsD;IACtD,gCAAgC,CAAC,aAAa,EAAE,sBAAsB,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC,CAAA;CACzF,CAAA;AAED;;;;;;;;;;GAUG;AACH,eAAO,MAAM,oBAAoB,oBAAqB,cAAc,KAAG,cA4hBtE,CAAA;AAGD,OAAO,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAA"}
package/dist/client.js CHANGED
@@ -1,7 +1,7 @@
1
+ import YAML from "yaml";
2
+ import { reactive } from "vue";
1
3
  import { bundle, upgrade } from "@scalar/openapi-parser";
2
4
  import { fetchUrls } from "@scalar/openapi-parser/plugins-browser";
3
- import { reactive, toRaw } from "vue";
4
- import YAML from "yaml";
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";
@@ -9,10 +9,11 @@ import { mergeObjects } from "./helpers/merge-object.js";
9
9
  import { createMagicProxy, getRaw } from "./helpers/proxy.js";
10
10
  import { createNavigation } from "./navigation/index.js";
11
11
  import { extensions } from "./schemas/extensions.js";
12
- import { InMemoryWorkspaceSchema } from "./schemas/inmemory-workspace.js";
13
- import { defaultReferenceConfig } from "./schemas/reference-config/index.js";
14
12
  import { coerceValue } from "./schemas/typebox-coerce.js";
15
13
  import { OpenAPIDocumentSchema } from "./schemas/v3.1/strict/openapi-document.js";
14
+ import { defaultReferenceConfig } from "./schemas/reference-config/index.js";
15
+ import { InMemoryWorkspaceSchema } from "./schemas/inmemory-workspace.js";
16
+ import { createOverridesProxy } from "./helpers/overrides-proxy.js";
16
17
  const defaultConfig = {
17
18
  "x-scalar-reference-config": defaultReferenceConfig
18
19
  };
@@ -29,6 +30,7 @@ const createWorkspaceStore = (workspaceProps) => {
29
30
  const originalDocuments = {};
30
31
  const intermediateDocuments = {};
31
32
  const documentConfigs = {};
33
+ const overrides = {};
32
34
  const workspace = reactive({
33
35
  ...workspaceProps?.meta,
34
36
  documents: {},
@@ -47,16 +49,60 @@ const createWorkspaceStore = (workspaceProps) => {
47
49
  function getActiveDocumentName() {
48
50
  return workspace[extensions.workspace.activeDocument] ?? Object.keys(workspace.documents)[0] ?? "";
49
51
  }
52
+ function saveDocument(documentName) {
53
+ const intermediateDocument = intermediateDocuments[documentName];
54
+ const workspaceDocument = workspace.documents[documentName];
55
+ if (!workspaceDocument) {
56
+ return;
57
+ }
58
+ const updatedDocument = createOverridesProxy(getRaw(workspaceDocument), overrides[documentName]);
59
+ if (!intermediateDocument || !updatedDocument) {
60
+ return;
61
+ }
62
+ const excludedDiffs = applySelectiveUpdates(intermediateDocument, updatedDocument);
63
+ return excludedDiffs;
64
+ }
50
65
  function addDocumentSync(input) {
51
66
  const { name, meta } = input;
52
67
  const document = coerceValue(OpenAPIDocumentSchema, upgrade(input.document).specification);
53
68
  originalDocuments[name] = deepClone({ ...document, ...meta });
54
69
  intermediateDocuments[name] = deepClone({ ...document, ...meta });
55
70
  documentConfigs[name] = input.config ?? {};
71
+ overrides[name] = input.overrides ?? {};
56
72
  if (document[extensions.document.navigation] === void 0) {
57
73
  document[extensions.document.navigation] = createNavigation(document, input.config ?? {}).entries;
58
74
  }
59
- workspace.documents[name] = createMagicProxy({ ...document, ...meta });
75
+ workspace.documents[name] = createOverridesProxy(createMagicProxy({ ...document, ...meta }), input.overrides);
76
+ saveDocument(name);
77
+ }
78
+ async function addDocument(input) {
79
+ const { name, meta } = input;
80
+ const resolve = await loadDocument(input);
81
+ if (!resolve.ok) {
82
+ console.error(`Failed to fetch document '${name}': request was not successful`);
83
+ workspace.documents[name] = {
84
+ ...meta,
85
+ openapi: "3.1.0",
86
+ info: {
87
+ title: `Document '${name}' could not be loaded`,
88
+ version: "unknown"
89
+ }
90
+ };
91
+ return;
92
+ }
93
+ if (!isObject(resolve.data)) {
94
+ console.error(`Failed to load document '${name}': response data is not a valid object`);
95
+ workspace.documents[name] = {
96
+ ...meta,
97
+ openapi: "3.1.0",
98
+ info: {
99
+ title: `Document '${name}' could not be loaded`,
100
+ version: "unknown"
101
+ }
102
+ };
103
+ return;
104
+ }
105
+ addDocumentSync({ ...input, document: resolve.data });
60
106
  }
61
107
  workspaceProps?.documents?.forEach(addDocumentSync);
62
108
  const visitedNodesCache = /* @__PURE__ */ new Set();
@@ -100,6 +146,30 @@ const createWorkspaceStore = (workspaceProps) => {
100
146
  }
101
147
  Object.assign(currentDocument, { [key]: value });
102
148
  },
149
+ /**
150
+ * Replaces the content of a specific document in the workspace with the provided input.
151
+ * This method computes the difference between the current document and the new input,
152
+ * then applies only the necessary changes in place. The updates are applied atomically,
153
+ * ensuring the document is updated in a single operation.
154
+ *
155
+ * @param documentName - The name of the document to update.
156
+ * @param input - The new content to apply to the document (as a plain object).
157
+ * @example
158
+ * // Replace the content of the 'api' document with new data
159
+ * store.replaceDocument('api', {
160
+ * openapi: '3.1.0',
161
+ * info: { title: 'Updated API', version: '1.0.1' },
162
+ * paths: {},
163
+ * })
164
+ */
165
+ replaceDocument(documentName, input) {
166
+ const currentDocument = workspace.documents[documentName];
167
+ if (!currentDocument) {
168
+ return console.error(`Document '${documentName}' does not exist in the workspace.`);
169
+ }
170
+ const newDocument = coerceValue(OpenAPIDocumentSchema, upgrade(input).specification);
171
+ applySelectiveUpdates(currentDocument, newDocument);
172
+ },
103
173
  /**
104
174
  * Resolves a reference in the active document by following the provided path and resolving any external $ref references.
105
175
  * This method traverses the document structure following the given path and resolves any $ref references it encounters.
@@ -154,35 +224,7 @@ const createWorkspaceStore = (workspaceProps) => {
154
224
  * }
155
225
  * })
156
226
  */
157
- addDocument: async (input) => {
158
- const { name, meta, config } = input;
159
- const resolve = await loadDocument(input);
160
- if (!resolve.ok) {
161
- console.error(`Failed to fetch document '${name}': request was not successful`);
162
- workspace.documents[name] = {
163
- ...meta,
164
- openapi: "3.1.0",
165
- info: {
166
- title: `Document '${name}' could not be loaded`,
167
- version: "unknown"
168
- }
169
- };
170
- return;
171
- }
172
- if (!isObject(resolve.data)) {
173
- console.error(`Failed to load document '${name}': response data is not a valid object`);
174
- workspace.documents[name] = {
175
- ...meta,
176
- openapi: "3.1.0",
177
- info: {
178
- title: `Document '${name}' could not be loaded`,
179
- version: "unknown"
180
- }
181
- };
182
- return;
183
- }
184
- addDocumentSync({ document: resolve.data, name, meta, config });
185
- },
227
+ addDocument,
186
228
  /**
187
229
  * Similar to addDocument but requires and in-mem object to be provided and loads the document synchronously
188
230
  * @param document - The document content to add. This should be a valid OpenAPI/Swagger document or other supported format
@@ -267,15 +309,7 @@ const createWorkspaceStore = (workspaceProps) => {
267
309
  * // Save the current state of the document named 'api'
268
310
  * const excludedDiffs = store.saveDocument('api')
269
311
  */
270
- saveDocument(documentName) {
271
- const intermediateDocument = intermediateDocuments[documentName];
272
- const updatedDocument = toRaw(getRaw(workspace.documents[documentName]));
273
- if (!intermediateDocument || !updatedDocument) {
274
- return;
275
- }
276
- const excludedDiffs = applySelectiveUpdates(intermediateDocument, updatedDocument);
277
- return excludedDiffs;
278
- },
312
+ saveDocument,
279
313
  /**
280
314
  * Restores the specified document to its last locally saved state.
281
315
  *
@@ -294,8 +328,12 @@ const createWorkspaceStore = (workspaceProps) => {
294
328
  * store.revertDocumentChanges('api')
295
329
  */
296
330
  revertDocumentChanges(documentName) {
331
+ const workspaceDocument = workspace.documents[documentName];
332
+ if (!workspaceDocument) {
333
+ return;
334
+ }
297
335
  const intermediateDocument = intermediateDocuments[documentName];
298
- const updatedDocument = getRaw(workspace.documents[documentName]);
336
+ const updatedDocument = createOverridesProxy(getRaw(workspaceDocument), overrides[documentName]);
299
337
  if (!intermediateDocument || !updatedDocument) {
300
338
  return;
301
339
  }
@@ -332,7 +370,7 @@ const createWorkspaceStore = (workspaceProps) => {
332
370
  name,
333
371
  // Extract the raw document data for export, removing any Vue reactivity wrappers.
334
372
  // When importing, the document can be wrapped again in a magic proxy.
335
- toRaw(getRaw(doc))
373
+ createOverridesProxy(getRaw(doc), overrides[name])
336
374
  ])
337
375
  )
338
376
  },
@@ -361,6 +399,39 @@ const createWorkspaceStore = (workspaceProps) => {
361
399
  safeAssign(intermediateDocuments, result.intermediateDocuments);
362
400
  safeAssign(documentConfigs, result.documentConfigs);
363
401
  safeAssign(workspace, result.meta);
402
+ },
403
+ /**
404
+ * Imports a workspace from a WorkspaceSpecification object.
405
+ *
406
+ * This method assigns workspace metadata and adds all documents defined in the specification.
407
+ * Each document is added using its $ref and optional overrides.
408
+ *
409
+ * @example
410
+ * ```ts
411
+ * await store.importWorkspaceFromSpecification({
412
+ * documents: {
413
+ * api: { $ref: '/specs/api.yaml' },
414
+ * petstore: { $ref: '/specs/petstore.yaml' }
415
+ * },
416
+ * overrides: {
417
+ * api: { config: { features: { showModels: true } } }
418
+ * },
419
+ * info: { title: 'My Workspace' },
420
+ * workspace: 'v1',
421
+ * "x-scalar-dark-mode": true
422
+ * })
423
+ * ```
424
+ *
425
+ * @param specification - The workspace specification to import.
426
+ */
427
+ importWorkspaceFromSpecification: (specification) => {
428
+ const { documents, overrides: overrides2, info, workspace: workspaceVersion, ...meta } = specification;
429
+ safeAssign(workspace, meta);
430
+ return Promise.all(
431
+ Object.entries(documents ?? {}).map(
432
+ ([name, doc]) => addDocument({ url: doc.$ref, name, overrides: overrides2?.[name] })
433
+ )
434
+ );
364
435
  }
365
436
  };
366
437
  };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/client.ts"],
4
- "sourcesContent": ["import { bundle, upgrade } from '@scalar/openapi-parser'\nimport { fetchUrls } from '@scalar/openapi-parser/plugins-browser'\nimport { reactive, toRaw } from 'vue'\nimport YAML from 'yaml'\n\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 { type InMemoryWorkspace, InMemoryWorkspaceSchema } from '@/schemas/inmemory-workspace'\nimport { defaultReferenceConfig } from '@/schemas/reference-config'\nimport { coerceValue } from '@/schemas/typebox-coerce'\nimport { OpenAPIDocumentSchema } from '@/schemas/v3.1/strict/openapi-document'\nimport type { Workspace, WorkspaceDocumentMeta, WorkspaceMeta } from '@/schemas/workspace'\nimport type { Config } from '@/schemas/workspace-specification/config'\nimport type { DeepTransform } from '@/types'\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}\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: DeepTransform<Config, 'NonNullable'> = {\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 /** 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}\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 /**\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 // 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 // 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\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 workspace.documents[name] = createMagicProxy({ ...document, ...meta })\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 * 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: async (input: WorkspaceDocumentInput) => {\n const { name, meta, config } = 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({ document: resolve.data, name, meta, config })\n },\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(documentName: string) {\n const intermediateDocument = intermediateDocuments[documentName]\n // Obtain the raw state of the current document to ensure accurate diffing\n const updatedDocument = toRaw(getRaw(workspace.documents[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 * 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 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 = getRaw(workspace.documents[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 toRaw(getRaw(doc)),\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}\n\n// biome-ignore lint/performance/noBarrelFile: <explanation>\nexport { generateClientMutators } from '@/mutators'\n"],
5
- "mappings": "AAAA,SAAS,QAAQ,eAAe;AAChC,SAAS,iBAAiB;AAC1B,SAAS,UAAU,aAAa;AAChC,OAAO,UAAU;AAEjB,SAAS,6BAA6B;AACtC,SAAS,WAAW,UAAU,kBAAkB;AAChD,SAAS,sBAAsB;AAC/B,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB,cAAc;AACzC,SAAS,wBAAsD;AAC/D,SAAS,kBAAkB;AAC3B,SAAiC,+BAA+B;AAChE,SAAS,8BAA8B;AACvC,SAAS,mBAAmB;AAC5B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AAAA;AAAA,IAWA,eAAe,cAAsB;AAEnC,cAAQ,KAAK,kCAAkC,YAAY,2BAA2B;AAAA,IACxF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAWA,kBAAkB;AAChB,aAAO,KAAK,UAAU;AAAA,QACpB,WAAW;AAAA,UACT,GAAG,OAAO;AAAA,YACR,OAAO,QAAQ,UAAU,SAAS,EAAE,IAAI,CAAC,CAAC,MAAM,GAAG,MAAM;AAAA,cACvD;AAAA;AAAA;AAAA,cAGA,MAAM,OAAO,GAAG,CAAC;AAAA,YACnB,CAAC;AAAA,UACH;AAAA,QACF;AAAA,QACA,MAAM,gBAAgB,QAAQ,CAAC;AAAA,QAC/B;AAAA,QACA;AAAA,QACA;AAAA,MACF,CAAsB;AAAA,IACxB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAUA,cAAc,OAAe;AAC3B,YAAM,SAAS,YAAY,yBAAyB,KAAK,MAAM,KAAK,CAAC;AAGrE;AAAA,QACE,UAAU;AAAA,QACV,OAAO,YAAY,OAAO,QAAQ,OAAO,SAAS,EAAE,IAAI,CAAC,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,CAAC,CAAC;AAAA,MACzG;AAEA,iBAAW,mBAAmB,OAAO,iBAAiB;AACtD,iBAAW,uBAAuB,OAAO,qBAAqB;AAC9D,iBAAW,iBAAiB,OAAO,eAAe;AAClD,iBAAW,WAAW,OAAO,IAAI;AAAA,IACnC;AAAA,EACF;AACF;AAGA,SAAS,8BAA8B;",
6
- "names": []
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,QAAQ,eAAe;AAChC,SAAS,iBAAiB;AAE1B,SAAS,6BAA6B;AACtC,SAAS,WAAW,UAAU,kBAAkB;AAChD,SAAS,sBAAsB;AAC/B,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB,cAAc;AACzC,SAAS,wBAAsD;AAC/D,SAAS,kBAAkB;AAC3B,SAAS,mBAAmB;AAC5B,SAAS,6BAAmD;AAC5D,SAAS,8BAA8B;AAEvC,SAAS,+BAAuD;AAEhE,SAAS,4BAA4B;AA4CrC,MAAM,gBAAsC;AAAA,EAC1C,6BAA6B;AAC/B;AAsBA,eAAe,aAAa,mBAA2C;AACrE,MAAI,SAAS,mBAAmB;AAC9B,WAAO,UAAU,EAAE,OAAO,kBAAkB,MAAM,CAAC,EAAE,KAAK,kBAAkB,GAAG;AAAA,EACjF;AAEA,SAAO;AAAA,IACL,IAAI;AAAA,IACJ,MAAM,kBAAkB;AAAA,EAC1B;AACF;AAqEO,MAAM,uBAAuB,CAAC,mBAAoD;AAQvF,QAAM,oBAAoB,CAAC;AAa3B,QAAM,wBAAwB,CAAC;A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Ae;AAClD,iBAAW,WAAW,OAAO,IAAI;AAAA,IACnC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAyBA,kCAAkC,CAAC,kBAA0C;AAC3E,YAAM,EAAE,WAAW,WAAAA,YAAW,MAAM,WAAW,kBAAkB,GAAG,KAAK,IAAI;AAG7E,iBAAW,WAAW,IAAI;AAG1B,aAAO,QAAQ;AAAA,QACb,OAAO,QAAQ,aAAa,CAAC,CAAC,EAAE;AAAA,UAAI,CAAC,CAAC,MAAM,GAAG,MAC7C,YAAY,EAAE,KAAK,IAAI,MAAM,MAAM,WAAWA,aAAY,IAAI,EAAE,CAAC;AAAA,QACnE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAGA,SAAS,8BAA8B;",
6
+ "names": ["overrides"]
7
7
  }
@@ -0,0 +1,5 @@
1
+ import { type UnknownObject } from '../helpers/general.js';
2
+ export declare const createOverridesProxy: <T extends object>(targetObject: T, overrides?: unknown) => T;
3
+ export declare const TARGET_SYMBOL: unique symbol;
4
+ export declare function unpackOverridesProxy<T extends UnknownObject>(obj: T): T;
5
+ //# sourceMappingURL=overrides-proxy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"overrides-proxy.d.ts","sourceRoot":"","sources":["../../src/helpers/overrides-proxy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAY,KAAK,aAAa,EAAE,MAAM,mBAAmB,CAAA;AAIhE,eAAO,MAAM,oBAAoB,GAAI,CAAC,SAAS,MAAM,gBAAgB,CAAC,cAAc,OAAO,KAAG,CAkD7F,CAAA;AAED,eAAO,MAAM,aAAa,eAAiC,CAAA;AAC3D,wBAAgB,oBAAoB,CAAC,CAAC,SAAS,aAAa,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAMvE"}
@@ -0,0 +1,48 @@
1
+ import { isObject } from "../helpers/general.js";
2
+ const isOverridesProxy = Symbol("isOverridesProxy");
3
+ const createOverridesProxy = (targetObject, overrides) => {
4
+ if (!targetObject || typeof targetObject !== "object") {
5
+ return targetObject;
6
+ }
7
+ const handler = {
8
+ get(target, prop, receiver) {
9
+ if (prop === isOverridesProxy) {
10
+ return true;
11
+ }
12
+ if (prop === TARGET_SYMBOL) {
13
+ return target;
14
+ }
15
+ const value = Reflect.get(target, prop, receiver);
16
+ if (!isObject(value)) {
17
+ return Reflect.get(overrides ?? {}, prop, receiver) ?? value;
18
+ }
19
+ return createOverridesProxy(value, overrides?.[prop]);
20
+ },
21
+ set(target, prop, value, receiver) {
22
+ if (prop === isOverridesProxy || prop === TARGET_SYMBOL) {
23
+ return false;
24
+ }
25
+ const hasOverride = overrides && Reflect.has(overrides, prop);
26
+ if (hasOverride && overrides && typeof overrides === "object") {
27
+ ;
28
+ overrides[prop] = value;
29
+ return true;
30
+ }
31
+ return Reflect.set(target, prop, value, receiver);
32
+ }
33
+ };
34
+ return new Proxy(targetObject, handler);
35
+ };
36
+ const TARGET_SYMBOL = Symbol("overridesProxyTarget");
37
+ function unpackOverridesProxy(obj) {
38
+ if (obj[isOverridesProxy]) {
39
+ return obj[TARGET_SYMBOL];
40
+ }
41
+ return obj;
42
+ }
43
+ export {
44
+ TARGET_SYMBOL,
45
+ createOverridesProxy,
46
+ unpackOverridesProxy
47
+ };
48
+ //# sourceMappingURL=overrides-proxy.js.map