@scalar/workspace-store 0.8.0 → 0.9.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 +15 -0
- package/README.md +15 -0
- package/dist/client.d.ts +10 -3
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +50 -1
- package/dist/client.js.map +2 -2
- package/dist/helpers/general.d.ts +25 -0
- package/dist/helpers/general.d.ts.map +1 -1
- package/dist/helpers/general.js +4 -0
- package/dist/helpers/general.js.map +2 -2
- package/dist/mutators/helpers.d.ts +1243 -1155
- package/dist/mutators/helpers.d.ts.map +1 -1
- package/dist/navigation/helpers/traverse-description.d.ts +2 -1
- package/dist/navigation/helpers/traverse-description.d.ts.map +1 -1
- package/dist/navigation/helpers/traverse-description.js.map +2 -2
- package/dist/navigation/helpers/traverse-document.d.ts +89 -2
- package/dist/navigation/helpers/traverse-document.d.ts.map +1 -1
- package/dist/navigation/helpers/traverse-document.js.map +2 -2
- package/dist/navigation/helpers/traverse-paths.d.ts.map +1 -1
- package/dist/navigation/helpers/traverse-paths.js.map +2 -2
- package/dist/navigation/helpers/traverse-schemas.d.ts +2 -1
- package/dist/navigation/helpers/traverse-schemas.d.ts.map +1 -1
- package/dist/navigation/helpers/traverse-schemas.js.map +2 -2
- package/dist/navigation/helpers/traverse-tags.d.ts +2 -1
- package/dist/navigation/helpers/traverse-tags.d.ts.map +1 -1
- package/dist/navigation/helpers/traverse-tags.js.map +2 -2
- package/dist/navigation/helpers/traverse-webhooks.d.ts +2 -1
- package/dist/navigation/helpers/traverse-webhooks.d.ts.map +1 -1
- package/dist/navigation/helpers/traverse-webhooks.js.map +2 -2
- package/dist/navigation/types.d.ts +1 -39
- package/dist/navigation/types.d.ts.map +1 -1
- package/dist/schemas/inmemory-workspace.d.ts +68 -0
- package/dist/schemas/inmemory-workspace.d.ts.map +1 -0
- package/dist/schemas/inmemory-workspace.js +14 -0
- package/dist/schemas/inmemory-workspace.js.map +7 -0
- package/dist/schemas/navigation.d.ts +148 -0
- package/dist/schemas/navigation.d.ts.map +1 -0
- package/dist/schemas/navigation.js +76 -0
- package/dist/schemas/navigation.js.map +7 -0
- package/dist/schemas/v3.1/strict/openapi-document.d.ts +47 -0
- package/dist/schemas/v3.1/strict/openapi-document.d.ts.map +1 -1
- package/dist/schemas/v3.1/strict/openapi-document.js +4 -1
- package/dist/schemas/v3.1/strict/openapi-document.js.map +2 -2
- package/dist/schemas/workspace-specification/index.d.ts +47 -0
- package/dist/schemas/workspace-specification/index.d.ts.map +1 -1
- package/dist/server.d.ts +141 -141
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js.map +1 -1
- package/package.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# @scalar/workspace-store
|
|
2
2
|
|
|
3
|
+
## 0.9.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- a0cadac: feat(workspace-store) add persistence layer to workspace store
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- 80acf84: feat: add code sample block wrapper with global state
|
|
12
|
+
- Updated dependencies [c10e191]
|
|
13
|
+
- Updated dependencies [903f975]
|
|
14
|
+
- @scalar/types@0.2.8
|
|
15
|
+
- @scalar/code-highlight@0.1.6
|
|
16
|
+
- @scalar/openapi-parser@0.18.1
|
|
17
|
+
|
|
3
18
|
## 0.8.0
|
|
4
19
|
|
|
5
20
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -353,4 +353,19 @@ store.workspace.documents['api'].info.title = 'Updated API Title'
|
|
|
353
353
|
|
|
354
354
|
// This will restore the original title since we did not commit the changes yet
|
|
355
355
|
store.revertDocumentChanges()
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
### Workspace State Persistence
|
|
359
|
+
|
|
360
|
+
The workspace store provides methods to persist and restore the complete workspace state, including all documents, configurations, and metadata. This is useful for saving work between sessions or sharing workspace configurations.
|
|
361
|
+
|
|
362
|
+
```ts
|
|
363
|
+
const client = createWorkspaceStore()
|
|
364
|
+
// Get the current workspace state
|
|
365
|
+
const currentWorkspaceState = client.exportWorkspace()
|
|
366
|
+
|
|
367
|
+
// Persist on some kind of storage
|
|
368
|
+
|
|
369
|
+
// Reload the workspace state
|
|
370
|
+
client.loadWorkspace(currentWorkspaceState)
|
|
356
371
|
```
|
package/dist/client.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type createNavigationOptions } from './navigation/index.js';
|
|
2
|
+
import type { DeepTransform } from './types.js';
|
|
2
3
|
import type { WorkspaceMeta, WorkspaceDocumentMeta, Workspace } from './schemas/workspace.js';
|
|
3
4
|
import type { Config } from './schemas/workspace-specification/config.js';
|
|
4
5
|
/**
|
|
@@ -30,11 +31,13 @@ export type ObjectDoc = {
|
|
|
30
31
|
/** The OpenAPI document object containing the API specification */
|
|
31
32
|
document: Record<string, unknown>;
|
|
32
33
|
} & WorkspaceDocumentMetaInput;
|
|
33
|
-
/**
|
|
34
|
+
/**
|
|
35
|
+
* Union type representing the possible input formats for a workspace document:
|
|
34
36
|
* - UrlDoc: Document loaded from a URL with optional fetch configuration
|
|
35
37
|
* - ObjectDoc: Direct document object with metadata
|
|
36
38
|
*/
|
|
37
|
-
type WorkspaceDocumentInput = UrlDoc | ObjectDoc;
|
|
39
|
+
export type WorkspaceDocumentInput = UrlDoc | ObjectDoc;
|
|
40
|
+
declare const defaultConfig: DeepTransform<Config, 'NonNullable'>;
|
|
38
41
|
/**
|
|
39
42
|
* Configuration object for initializing a workspace store.
|
|
40
43
|
* Defines the initial state and documents for the workspace.
|
|
@@ -67,7 +70,7 @@ export type WorkspaceStore = {
|
|
|
67
70
|
/** Similar to addDocument but requires and in-mem object to be provided and loads the document synchronously */
|
|
68
71
|
addDocumentSync(input: ObjectDoc): void;
|
|
69
72
|
/** Returns the merged configuration for the active document */
|
|
70
|
-
readonly config:
|
|
73
|
+
readonly config: typeof defaultConfig;
|
|
71
74
|
/** Downloads the specified document in the requested format */
|
|
72
75
|
exportDocument(documentName: string, format: 'json' | 'yaml'): string | undefined;
|
|
73
76
|
/** Persists the current state of the specified document back to the original documents map */
|
|
@@ -76,6 +79,10 @@ export type WorkspaceStore = {
|
|
|
76
79
|
revertDocumentChanges(documentName: string): void;
|
|
77
80
|
/** Commits the specified document */
|
|
78
81
|
commitDocument(documentName: string): void;
|
|
82
|
+
/** Serializes the current workspace state to a JSON string for backup, persistence, or sharing. */
|
|
83
|
+
exportWorkspace(): string;
|
|
84
|
+
/** Imports a workspace from a serialized JSON string. */
|
|
85
|
+
loadWorkspace(input: string): void;
|
|
79
86
|
};
|
|
80
87
|
/**
|
|
81
88
|
* 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":"AAKA,OAAO,EAAoB,KAAK,uBAAuB,EAAE,MAAM,cAAc,CAAA;
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAKA,OAAO,EAAoB,KAAK,uBAAuB,EAAE,MAAM,cAAc,CAAA;AAC7E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAM5C,OAAO,KAAK,EAAE,aAAa,EAAE,qBAAqB,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAA;AAK1F,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,0CAA0C,CAAA;AAGtE;;;;;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;CACnD,CAAA;AAED;;;GAG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,4HAA4H;IAC5H,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;IACzC,2CAA2C;IAC3C,WAAW,CAAC,KAAK,EAAE,sBAAsB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IACzD,gHAAgH;IAChH,eAAe,CAAC,KAAK,EAAE,SAAS,GAAG,IAAI,CAAA;IACvC,+DAA+D;IAC/D,QAAQ,CAAC,MAAM,EAAE,OAAO,aAAa,CAAA;IACrC,+DAA+D;IAC/D,cAAc,CAAC,YAAY,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,SAAS,CAAA;IACjF,8FAA8F;IAC9F,YAAY,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,EAAE,GAAG,SAAS,CAAA;IACzD,2DAA2D;IAC3D,qBAAqB,CAAC,YAAY,EAAE,MAAM,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;CACnC,CAAA;AAED;;;;;;;;;;GAUG;AACH,eAAO,MAAM,oBAAoB,oBAAqB,cAAc,KAAG,cAmatE,CAAA;AAGD,OAAO,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAA"}
|
package/dist/client.js
CHANGED
|
@@ -4,7 +4,7 @@ import { bundle, upgrade } from "@scalar/openapi-parser";
|
|
|
4
4
|
import { fetchUrls } from "@scalar/openapi-parser/plugins-browser";
|
|
5
5
|
import { createNavigation } from "./navigation/index.js";
|
|
6
6
|
import { createMagicProxy, getRaw } from "./helpers/proxy.js";
|
|
7
|
-
import { deepClone, isObject } from "./helpers/general.js";
|
|
7
|
+
import { deepClone, isObject, safeAssign } from "./helpers/general.js";
|
|
8
8
|
import { mergeObjects } from "./helpers/merge-object.js";
|
|
9
9
|
import { applySelectiveUpdates } from "./helpers/apply-selective-updates.js";
|
|
10
10
|
import { getValueByPath } from "./helpers/json-path-utils.js";
|
|
@@ -12,6 +12,7 @@ import { extensions } from "./schemas/extensions.js";
|
|
|
12
12
|
import { coerceValue } from "./schemas/typebox-coerce.js";
|
|
13
13
|
import { OpenAPIDocumentSchema } from "./schemas/v3.1/strict/openapi-document.js";
|
|
14
14
|
import { defaultReferenceConfig } from "./schemas/reference-config/index.js";
|
|
15
|
+
import { InMemoryWorkspaceSchema } from "./schemas/inmemory-workspace.js";
|
|
15
16
|
const defaultConfig = {
|
|
16
17
|
"x-scalar-reference-config": defaultReferenceConfig
|
|
17
18
|
};
|
|
@@ -300,6 +301,54 @@ const createWorkspaceStore = (workspaceProps) => {
|
|
|
300
301
|
*/
|
|
301
302
|
commitDocument(documentName) {
|
|
302
303
|
console.warn(`Commit operation for document '${documentName}' is not implemented yet.`);
|
|
304
|
+
},
|
|
305
|
+
/**
|
|
306
|
+
* Serializes the current workspace state to a JSON string for backup, persistence, or sharing.
|
|
307
|
+
*
|
|
308
|
+
* This method exports all workspace documents (removing Vue reactivity proxies), workspace metadata,
|
|
309
|
+
* document configurations, and both the original and intermediate document states. The resulting JSON
|
|
310
|
+
* can be imported later to fully restore the workspace to this exact state, including all documents
|
|
311
|
+
* and their configurations.
|
|
312
|
+
*
|
|
313
|
+
* @returns A JSON string representing the complete workspace state.
|
|
314
|
+
*/
|
|
315
|
+
exportWorkspace() {
|
|
316
|
+
return JSON.stringify({
|
|
317
|
+
documents: {
|
|
318
|
+
...Object.fromEntries(
|
|
319
|
+
Object.entries(workspace.documents).map(([name, doc]) => [
|
|
320
|
+
name,
|
|
321
|
+
// Extract the raw document data for export, removing any Vue reactivity wrappers.
|
|
322
|
+
// When importing, the document can be wrapped again in a magic proxy.
|
|
323
|
+
toRaw(getRaw(doc))
|
|
324
|
+
])
|
|
325
|
+
)
|
|
326
|
+
},
|
|
327
|
+
meta: workspaceProps?.meta ?? {},
|
|
328
|
+
documentConfigs,
|
|
329
|
+
originalDocuments,
|
|
330
|
+
intermediateDocuments
|
|
331
|
+
});
|
|
332
|
+
},
|
|
333
|
+
/**
|
|
334
|
+
* Imports a workspace from a serialized JSON string.
|
|
335
|
+
*
|
|
336
|
+
* This method parses the input string using the InMemoryWorkspaceSchema,
|
|
337
|
+
* then updates the current workspace state, including documents, metadata,
|
|
338
|
+
* and configuration, with the imported values.
|
|
339
|
+
*
|
|
340
|
+
* @param input - The serialized workspace JSON string to import.
|
|
341
|
+
*/
|
|
342
|
+
loadWorkspace(input) {
|
|
343
|
+
const result = coerceValue(InMemoryWorkspaceSchema, JSON.parse(input));
|
|
344
|
+
safeAssign(
|
|
345
|
+
workspace.documents,
|
|
346
|
+
Object.fromEntries(Object.entries(result.documents).map(([name, doc]) => [name, createMagicProxy(doc)]))
|
|
347
|
+
);
|
|
348
|
+
safeAssign(originalDocuments, result.originalDocuments);
|
|
349
|
+
safeAssign(intermediateDocuments, result.intermediateDocuments);
|
|
350
|
+
safeAssign(documentConfigs, result.documentConfigs);
|
|
351
|
+
safeAssign(workspace, result.meta);
|
|
303
352
|
}
|
|
304
353
|
};
|
|
305
354
|
};
|
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, toRaw } from 'vue'\nimport { bundle, upgrade } from '@scalar/openapi-parser'\nimport { fetchUrls } from '@scalar/openapi-parser/plugins-browser'\n\nimport { createNavigation, type createNavigationOptions } from '@/navigation'\nimport type { DeepTransform } from '@/types'\nimport { createMagicProxy, getRaw } from '@/helpers/proxy'\nimport { deepClone, isObject } from '@/helpers/general'\nimport { mergeObjects } from '@/helpers/merge-object'\nimport { applySelectiveUpdates } from '@/helpers/apply-selective-updates'\nimport { getValueByPath } from '@/helpers/json-path-utils'\nimport type { WorkspaceMeta, WorkspaceDocumentMeta, Workspace } from '@/schemas/workspace'\nimport { extensions } from '@/schemas/extensions'\nimport { coerceValue } from '@/schemas/typebox-coerce'\nimport { OpenAPIDocumentSchema } from '@/schemas/v3.1/strict/openapi-document'\nimport { defaultReferenceConfig } from '@/schemas/reference-config'\nimport type { Config } from '@/schemas/workspace-specification/config'\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/** 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 */\ntype 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: Config\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}\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 || !isObject(resolve.data)) {\n console.error(`Can not load the document '${name}'`)\n workspace.documents[name] = {\n ...meta,\n info: {\n title: `Document '${name}' could not be loaded`,\n version: 'unknown',\n },\n openapi: '3.1.0',\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}\n\n// biome-ignore lint/performance/noBarrelFile: <explanation>\nexport { generateClientMutators } from '@/mutators'\n"],
|
|
5
|
-
"mappings": "AAAA,OAAO,UAAU;AACjB,SAAS,UAAU,aAAa;AAChC,SAAS,QAAQ,eAAe;AAChC,SAAS,iBAAiB;AAE1B,SAAS,wBAAsD;AAE/D,SAAS,kBAAkB,cAAc;AACzC,SAAS,WAAW,
|
|
4
|
+
"sourcesContent": ["import YAML from 'yaml'\nimport { reactive, toRaw } from 'vue'\nimport { bundle, upgrade } from '@scalar/openapi-parser'\nimport { fetchUrls } from '@scalar/openapi-parser/plugins-browser'\n\nimport { createNavigation, type createNavigationOptions } from '@/navigation'\nimport type { DeepTransform } from '@/types'\nimport { createMagicProxy, getRaw } from '@/helpers/proxy'\nimport { deepClone, isObject, safeAssign } from '@/helpers/general'\nimport { mergeObjects } from '@/helpers/merge-object'\nimport { applySelectiveUpdates } from '@/helpers/apply-selective-updates'\nimport { getValueByPath } from '@/helpers/json-path-utils'\nimport type { WorkspaceMeta, WorkspaceDocumentMeta, Workspace } from '@/schemas/workspace'\nimport { extensions } from '@/schemas/extensions'\nimport { coerceValue } from '@/schemas/typebox-coerce'\nimport { OpenAPIDocumentSchema } 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'\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 || !isObject(resolve.data)) {\n console.error(`Can not load the document '${name}'`)\n workspace.documents[name] = {\n ...meta,\n info: {\n title: `Document '${name}' could not be loaded`,\n version: 'unknown',\n },\n openapi: '3.1.0',\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,OAAO,UAAU;AACjB,SAAS,UAAU,aAAa;AAChC,SAAS,QAAQ,eAAe;AAChC,SAAS,iBAAiB;AAE1B,SAAS,wBAAsD;AAE/D,SAAS,kBAAkB,cAAc;AACzC,SAAS,WAAW,UAAU,kBAAkB;AAChD,SAAS,oBAAoB;AAC7B,SAAS,6BAA6B;AACtC,SAAS,sBAAsB;AAE/B,SAAS,kBAAkB;AAC3B,SAAS,mBAAmB;AAC5B,SAAS,6BAA6B;AACtC,SAAS,8BAA8B;AAEvC,SAAS,+BAAuD;AAyChE,MAAM,gBAAsD;AAAA,EAC1D,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;AAiEO,MAAM,uBAAuB,CAAC,mBAAoD;AAQvF,QAAM,oBAAoB,CAAC;AAc3B,QAAM,wB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3B,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
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -56,4 +56,29 @@ export declare const deepClone: <T>(value: T) => T;
|
|
|
56
56
|
* ```
|
|
57
57
|
*/
|
|
58
58
|
export declare const split: <T>(array: T[], condition: (element: T) => boolean) => [T[], T[]];
|
|
59
|
+
/**
|
|
60
|
+
* Safely assigns properties from a source object to a target object.
|
|
61
|
+
*
|
|
62
|
+
* This function uses Object.assign to copy enumerable properties from the source object
|
|
63
|
+
* to the target object. It's a type-safe wrapper around Object.assign that ensures
|
|
64
|
+
* the source object is compatible with the target object's type.
|
|
65
|
+
*
|
|
66
|
+
* @param target - The target object to assign properties to
|
|
67
|
+
* @param source - The source object containing properties to assign
|
|
68
|
+
* @template T - The type of the target object
|
|
69
|
+
*
|
|
70
|
+
* @example
|
|
71
|
+
* ```ts
|
|
72
|
+
* const target = { name: 'John', age: 30 }
|
|
73
|
+
* const source = { age: 31, city: 'New York' }
|
|
74
|
+
* safeAssign(target, source)
|
|
75
|
+
* // target is now: { name: 'John', age: 31, city: 'New York' }
|
|
76
|
+
*
|
|
77
|
+
* const config = { theme: 'dark', language: 'en' }
|
|
78
|
+
* const updates = { theme: 'light' }
|
|
79
|
+
* safeAssign(config, updates)
|
|
80
|
+
* // config is now: { theme: 'light', language: 'en' }
|
|
81
|
+
* ```
|
|
82
|
+
*/
|
|
83
|
+
export declare const safeAssign: <T extends Record<string, unknown>>(target: T, source: Partial<T>) => void;
|
|
59
84
|
//# sourceMappingURL=general.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"general.d.ts","sourceRoot":"","sources":["../../src/helpers/general.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;AAEnD;;;;;;;;;GASG;AACH,wBAAgB,QAAQ,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,aAAa,CAE/D;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAEjD;AAED,wBAAgB,KAAK,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,KAAK,EAAE,CAAC,GAClC,CAAC,MAAM,CAAC,CAAC,EAAE,CACzC;AAED;;;;;;GAMG;AACH,eAAO,MAAM,SAAS,GAAI,CAAC,SAAS,CAAC,KAAG,CAEvC,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,eAAO,MAAM,KAAK,GAAI,CAAC,SAAS,CAAC,EAAE,aAAa,CAAC,OAAO,EAAE,CAAC,KAAK,OAAO,eAOtE,CAAA"}
|
|
1
|
+
{"version":3,"file":"general.d.ts","sourceRoot":"","sources":["../../src/helpers/general.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;AAEnD;;;;;;;;;GASG;AACH,wBAAgB,QAAQ,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,aAAa,CAE/D;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAEjD;AAED,wBAAgB,KAAK,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,KAAK,EAAE,CAAC,GAClC,CAAC,MAAM,CAAC,CAAC,EAAE,CACzC;AAED;;;;;;GAMG;AACH,eAAO,MAAM,SAAS,GAAI,CAAC,SAAS,CAAC,KAAG,CAEvC,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,eAAO,MAAM,KAAK,GAAI,CAAC,SAAS,CAAC,EAAE,aAAa,CAAC,OAAO,EAAE,CAAC,KAAK,OAAO,eAOtE,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,eAAO,MAAM,UAAU,GAAI,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,UAAU,CAAC,UAAU,OAAO,CAAC,CAAC,CAAC,SAE1F,CAAA"}
|
package/dist/helpers/general.js
CHANGED
|
@@ -18,11 +18,15 @@ const split = (array, condition) => {
|
|
|
18
18
|
[[], []]
|
|
19
19
|
);
|
|
20
20
|
};
|
|
21
|
+
const safeAssign = (target, source) => {
|
|
22
|
+
Object.assign(target, source);
|
|
23
|
+
};
|
|
21
24
|
export {
|
|
22
25
|
deepClone,
|
|
23
26
|
isLocalRef,
|
|
24
27
|
isObject,
|
|
25
28
|
keyOf,
|
|
29
|
+
safeAssign,
|
|
26
30
|
split
|
|
27
31
|
};
|
|
28
32
|
//# sourceMappingURL=general.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/helpers/general.ts"],
|
|
4
|
-
"sourcesContent": ["export type UnknownObject = Record<string, unknown>\n\n/**\n * Returns true if the value is a non-null object (but not an array).\n *\n * @example\n * ```ts\n * isObject({}) // true\n * isObject([]) // false\n * isObject(null) // false\n * ```\n */\nexport function isObject(value: unknown): value is UnknownObject {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * Checks if a string is a local reference (starts with #)\n * @param value - The reference string to check\n * @returns true if the string is a local reference, false otherwise\n * @example\n * ```ts\n * isLocalRef('#/components/schemas/User') // true\n * isLocalRef('https://example.com/schema.json') // false\n * isLocalRef('./local-schema.json') // false\n * ```\n */\nexport function isLocalRef(value: string): boolean {\n return value.startsWith('#')\n}\n\nexport function keyOf<T extends Record<string, unknown>>(value: T) {\n return Object.keys(value) as (keyof T)[]\n}\n\n/**\n * Deep clones a value using JSON serialization.\n *\n * @param value - The value to deep clone\n * @template T - The type of the value\n * @returns A deep clone of the value\n */\nexport const deepClone = <T>(value: T): T => {\n return JSON.parse(JSON.stringify(value)) as T\n}\n\n/**\n * Splits an array into two arrays based on a condition.\n *\n * This function takes an array and a predicate function, then returns a tuple containing\n * two arrays: the first contains elements that pass the condition, and the second contains\n * elements that fail the condition.\n *\n * @param array - The array to split\n * @param condition - A predicate function that determines which array each element belongs to\n * @returns A tuple of two arrays: [passingElements, failingElements]\n *\n * @example\n * ```ts\n * const numbers = [1, 2, 3, 4, 5, 6]\n * const [evens, odds] = split(numbers, (n) => n % 2 === 0)\n * // evens: [2, 4, 6]\n * // odds: [1, 3, 5]\n *\n * const words = ['apple', 'banana', 'cherry', 'date']\n * const [longWords, shortWords] = split(words, (word) => word.length > 5)\n * // longWords: ['banana', 'cherry']\n * // shortWords: ['apple', 'date']\n * ```\n */\nexport const split = <T>(array: T[], condition: (element: T) => boolean) => {\n return array.reduce<[T[], T[]]>(\n ([pass, fail], item) => {\n return condition(item) ? [[...pass, item], fail] : [pass, [...fail, item]]\n },\n [[], []],\n )\n}\n"],
|
|
5
|
-
"mappings": "AAYO,SAAS,SAAS,OAAwC;AAC/D,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAaO,SAAS,WAAW,OAAwB;AACjD,SAAO,MAAM,WAAW,GAAG;AAC7B;AAEO,SAAS,MAAyC,OAAU;AACjE,SAAO,OAAO,KAAK,KAAK;AAC1B;AASO,MAAM,YAAY,CAAI,UAAgB;AAC3C,SAAO,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AACzC;AA0BO,MAAM,QAAQ,CAAI,OAAY,cAAuC;AAC1E,SAAO,MAAM;AAAA,IACX,CAAC,CAAC,MAAM,IAAI,GAAG,SAAS;AACtB,aAAO,UAAU,IAAI,IAAI,CAAC,CAAC,GAAG,MAAM,IAAI,GAAG,IAAI,IAAI,CAAC,MAAM,CAAC,GAAG,MAAM,IAAI,CAAC;AAAA,IAC3E;AAAA,IACA,CAAC,CAAC,GAAG,CAAC,CAAC;AAAA,EACT;AACF;",
|
|
4
|
+
"sourcesContent": ["export type UnknownObject = Record<string, unknown>\n\n/**\n * Returns true if the value is a non-null object (but not an array).\n *\n * @example\n * ```ts\n * isObject({}) // true\n * isObject([]) // false\n * isObject(null) // false\n * ```\n */\nexport function isObject(value: unknown): value is UnknownObject {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * Checks if a string is a local reference (starts with #)\n * @param value - The reference string to check\n * @returns true if the string is a local reference, false otherwise\n * @example\n * ```ts\n * isLocalRef('#/components/schemas/User') // true\n * isLocalRef('https://example.com/schema.json') // false\n * isLocalRef('./local-schema.json') // false\n * ```\n */\nexport function isLocalRef(value: string): boolean {\n return value.startsWith('#')\n}\n\nexport function keyOf<T extends Record<string, unknown>>(value: T) {\n return Object.keys(value) as (keyof T)[]\n}\n\n/**\n * Deep clones a value using JSON serialization.\n *\n * @param value - The value to deep clone\n * @template T - The type of the value\n * @returns A deep clone of the value\n */\nexport const deepClone = <T>(value: T): T => {\n return JSON.parse(JSON.stringify(value)) as T\n}\n\n/**\n * Splits an array into two arrays based on a condition.\n *\n * This function takes an array and a predicate function, then returns a tuple containing\n * two arrays: the first contains elements that pass the condition, and the second contains\n * elements that fail the condition.\n *\n * @param array - The array to split\n * @param condition - A predicate function that determines which array each element belongs to\n * @returns A tuple of two arrays: [passingElements, failingElements]\n *\n * @example\n * ```ts\n * const numbers = [1, 2, 3, 4, 5, 6]\n * const [evens, odds] = split(numbers, (n) => n % 2 === 0)\n * // evens: [2, 4, 6]\n * // odds: [1, 3, 5]\n *\n * const words = ['apple', 'banana', 'cherry', 'date']\n * const [longWords, shortWords] = split(words, (word) => word.length > 5)\n * // longWords: ['banana', 'cherry']\n * // shortWords: ['apple', 'date']\n * ```\n */\nexport const split = <T>(array: T[], condition: (element: T) => boolean) => {\n return array.reduce<[T[], T[]]>(\n ([pass, fail], item) => {\n return condition(item) ? [[...pass, item], fail] : [pass, [...fail, item]]\n },\n [[], []],\n )\n}\n\n/**\n * Safely assigns properties from a source object to a target object.\n *\n * This function uses Object.assign to copy enumerable properties from the source object\n * to the target object. It's a type-safe wrapper around Object.assign that ensures\n * the source object is compatible with the target object's type.\n *\n * @param target - The target object to assign properties to\n * @param source - The source object containing properties to assign\n * @template T - The type of the target object\n *\n * @example\n * ```ts\n * const target = { name: 'John', age: 30 }\n * const source = { age: 31, city: 'New York' }\n * safeAssign(target, source)\n * // target is now: { name: 'John', age: 31, city: 'New York' }\n *\n * const config = { theme: 'dark', language: 'en' }\n * const updates = { theme: 'light' }\n * safeAssign(config, updates)\n * // config is now: { theme: 'light', language: 'en' }\n * ```\n */\nexport const safeAssign = <T extends Record<string, unknown>>(target: T, source: Partial<T>) => {\n Object.assign(target, source)\n}\n"],
|
|
5
|
+
"mappings": "AAYO,SAAS,SAAS,OAAwC;AAC/D,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAaO,SAAS,WAAW,OAAwB;AACjD,SAAO,MAAM,WAAW,GAAG;AAC7B;AAEO,SAAS,MAAyC,OAAU;AACjE,SAAO,OAAO,KAAK,KAAK;AAC1B;AASO,MAAM,YAAY,CAAI,UAAgB;AAC3C,SAAO,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AACzC;AA0BO,MAAM,QAAQ,CAAI,OAAY,cAAuC;AAC1E,SAAO,MAAM;AAAA,IACX,CAAC,CAAC,MAAM,IAAI,GAAG,SAAS;AACtB,aAAO,UAAU,IAAI,IAAI,CAAC,CAAC,GAAG,MAAM,IAAI,GAAG,IAAI,IAAI,CAAC,MAAM,CAAC,GAAG,MAAM,IAAI,CAAC;AAAA,IAC3E;AAAA,IACA,CAAC,CAAC,GAAG,CAAC,CAAC;AAAA,EACT;AACF;AA0BO,MAAM,aAAa,CAAoC,QAAW,WAAuB;AAC9F,SAAO,OAAO,QAAQ,MAAM;AAC9B;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|