Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
feat: Store Content Block content in MDX assets
Oleg Isonen86b6310fff4a
diff --git a/apps/builder/app/builder/builder.tsx b/apps/builder/app/builder/builder.tsxindex 6ba4b93011..409a46bb18 100644--- a/apps/builder/app/builder/builder.tsx+++ b/apps/builder/app/builder/builder.tsx@@ -58,7 +58,10 @@ import { CloneProjectDialog } from "~/shared/clone-project";import type { TokenPermissions } from "@webstudio-is/authorization-token";import { useToastErrors } from "~/shared/error/toast-error";import { initBuilderApi } from "~/shared/builder-api";-import { migrateLoadedWebstudioData } from "~/shared/instance-utils/data";+import {+ abortPendingTemplateNameConfirmation,+ migrateLoadedWebstudioData,+} from "~/shared/instance-utils/data";import { Loading, LoadingBackground } from "./shared/loading";import { mergeRefs } from "@react-aria/utils";import { CommandPanel } from "./features/command-panel";@@ -71,6 +74,7 @@ import { TokenConflictDialog } from "~/shared/token-conflict-dialog";import { RootStyleConflictDialog } from "~/shared/root-style-conflict-dialog";import { DesignTokenImportDialog } from "~/shared/design-token-import-dialog";import type { User } from "~/shared/db/user.server";+import { TemplateNameConfirmationDialog } from "./features/template-name-confirmation-dialog";import {initCopyPaste,@@ -324,6 +328,7 @@ export const Builder = (props: BuilderProps) => {useUnmount(() => {$pages.set(undefined);+ abortPendingTemplateNameConfirmation();});const dataLoadingState = useStore($dataLoadingState);@@ -529,6 +534,7 @@ export const Builder = (props: BuilderProps) => {<DesignTokenImportDialog /><TokenConflictDialog /><RootStyleConflictDialog />+ <TemplateNameConfirmationDialog /><RemoteDialog /><Toaster /></div>diff --git a/apps/builder/app/builder/features/navigator/navigator-tree.tsx b/apps/builder/app/builder/features/navigator/navigator-tree.tsxindex fed26bb58a..6ef210b830 100644--- a/apps/builder/app/builder/features/navigator/navigator-tree.tsx+++ b/apps/builder/app/builder/features/navigator/navigator-tree.tsx@@ -2,7 +2,7 @@ import {reparentInstance,toggleInstanceShow,} from "~/shared/instance-utils/mutation";-import { useEffect, useMemo, useRef } from "react";+import { useEffect, useId, useMemo, useRef, useState } from "react";import { atom, computed } from "nanostores";import { mergeRefs } from "@react-aria/utils";import { useStore } from "@nanostores/react";@@ -64,7 +64,12 @@ import {getContextMenuSelectedInstanceSelectors,getInstanceSelectionUpdate,} from "~/shared/instance-utils/selection";-import { $instances, $props } from "~/shared/sync/data-stores";+import {+ $runtimeInstances as $instances,+ $runtimeProps as $props,+ getRuntimeInstanceChildren,+ contentBlockPresentationComponent,+} from "~/shared/content-block-content";import { suppressCommandsForEvent } from "~/shared/commands-emitter";import {areInstanceSelectorsEqual,@@ -74,7 +79,10 @@ import {} from "@webstudio-is/project-build/runtime";import { emitCommand } from "~/builder/shared/commands";import { useContentEditable } from "~/shared/dom-hooks";-import { executeRuntimeMutation } from "~/shared/instance-utils/data";+import {+ executeRuntimeMutation,+ getDuplicateTemplateNameMessage,+} from "~/shared/instance-utils/data";import { isRichTextContent } from "@webstudio-is/project-build/runtime";import {getInstanceLabel,@@ -302,7 +310,8 @@ export const $flatTree = computed(flatTree.push(treeItem);}const level = treeItem.visibleAncestors.length - 1;- if (level > 0 && instance.children.some((child) => child.type === "id")) {+ const children = getRuntimeInstanceChildren(instance, selector);+ if (level > 0 && children.some((child) => child.type === "id")) {treeItem.isExpanded = expandedItems.has(getSelectorKey(selector));}// always expand invisible items@@ -347,10 +356,10 @@ export const $flatTree = computed(}}} else if (level === 0 || treeItem.isExpanded) {- for (let index = 0; index < instance.children.length; index += 1) {- const child = instance.children[index];+ for (let index = 0; index < children.length; index += 1) {+ const child = children[index];if (child.type === "id") {- const isLastChild = index === instance.children.length - 1;+ const isLastChild = index === children.length - 1;const lastDescendentItem = traverse(child.value,[child.value, ...selector],@@ -406,8 +415,10 @@ const handleExpand = (item: TreeItem, isExpanded: boolean, all: boolean) => {const instance = instances.get(instanceId);// expand all descendants as well when alt is pressedif (all && instance) {- for (const child of instance.children) {- traverse(child.value, [child.value, ...selector]);+ for (const child of getRuntimeInstanceChildren(instance, selector)) {+ if (child.type === "id") {+ traverse(child.value, [child.value, ...selector]);+ }}}};@@ -490,6 +501,11 @@ const ShowToggle = ({const EditableTreeNodeLabel = styled("div", {variants: {+ hasError: {+ true: {+ outline: `1px solid ${theme.colors.borderDestructiveMain}`,+ },+ },isEditing: {true: {background: theme.colors.backgroundControls,@@ -515,31 +531,57 @@ const TreeNodeContent = ({onIsEditingChange: (isEditing: boolean) => void;}) => {const editableRef = useRef<HTMLDivElement | null>(null);+ const errorId = useId();+ const [error, setError] = useState<string>();const label = getInstanceLabel(instance);const { ref, handlers } = useContentEditable({value: label,- isEditable: true,+ isEditable: instance.component !== contentBlockPresentationComponent,isEditing,onChangeValue: (value: string) => {- executeRuntimeMutation({- id: "instances.setLabel",- input: { instanceId: instance.id, label: value },- });+ try {+ executeRuntimeMutation({+ id: "instances.setLabel",+ input: { instanceId: instance.id, label: value },+ });+ } catch (caught) {+ const message = getDuplicateTemplateNameMessage(caught);+ if (message !== undefined) {+ setError(message);+ requestAnimationFrame(() => editableRef.current?.focus());+ return false;+ }+ throw caught;+ }+ setError(undefined);editableRef.current?.closest("button")?.focus();},- onChangeEditing: onIsEditingChange,+ onChangeEditing: (editing) => {+ if (editing) {+ setError(undefined);+ }+ onIsEditingChange(editing);+ },});return (<TreeNodeLabel prefix={<InstanceIcon instance={instance} />}>- <EditableTreeNodeLabel- ref={mergeRefs(editableRef, ref)}- {...handlers}- isEditing={isEditing}+ <Tooltip+ open={error !== undefined}+ content={<Text id={errorId}>{error}</Text>}>- {label}- </EditableTreeNodeLabel>+ <EditableTreeNodeLabel+ ref={mergeRefs(editableRef, ref)}+ {...handlers}+ isEditing={isEditing}+ hasError={error !== undefined}+ aria-invalid={error !== undefined}+ aria-errormessage={error === undefined ? undefined : errorId}+ >+ {label}+ </EditableTreeNodeLabel>+ </Tooltip></TreeNodeLabel>);};diff --git a/apps/builder/app/builder/features/publish/publish.tsx b/apps/builder/app/builder/features/publish/publish.tsxindex 97508b4685..b6d4fc1cf1 100644--- a/apps/builder/app/builder/features/publish/publish.tsx+++ b/apps/builder/app/builder/features/publish/publish.tsx@@ -80,6 +80,7 @@ import { DomainCheckbox, domainToPublishName } from "./domain-checkbox";import { CopyToClipboard } from "~/shared/copy-to-clipboard";import { $openProjectSettings } from "~/shared/nano-states/project-settings";import {+ $assets,$dataSources,$instances,$pages,@@ -173,6 +174,7 @@ const getPrePublishAuditMessages = () => {props: $props.get(),dataSources: $dataSources.get(),resources: $resources.get(),+ assets: $assets.get(),metas: $registeredComponentMetas.get(),});const getMessage = (severity: PrePublishAuditFinding["severity"]) => {diff --git a/apps/builder/app/builder/features/settings-panel/controls/content-block-source-controller.test.ts b/apps/builder/app/builder/features/settings-panel/controls/content-block-source-controller.test.tsnew file mode 100644index 0000000000..917c7b7f33--- /dev/null+++ b/apps/builder/app/builder/features/settings-panel/controls/content-block-source-controller.test.ts@@ -0,0 +1,655 @@+import { expect, test, vi } from "vitest";+import { createMdxAssetEditingSession } from "@webstudio-is/project-build/runtime";+import {+ blockComponent,+ blockTemplateComponent,+ elementComponent,+ type ContentBlockSource,+} from "@webstudio-is/sdk";+import { createContentBlockSourceController } from "./content-block-source-controller";++const encoder = new TextEncoder();++const createRepository = (source: string, updateError?: Error) => {+ let reads = 0;+ let currentSource = source;+ let revision = 0;+ const updateContent = vi.fn(+ async ({+ assetId,+ data,+ }: {+ assetId: string;+ data: ReadableStream<Uint8Array>;+ }) => {+ if (updateError !== undefined) {+ throw updateError;+ }+ currentSource = await new Response(data).text();+ revision += 1;+ return {+ id: assetId,+ projectId: "project",+ name: `${assetId}_revision_${revision}.mdx`,+ type: "file" as const,+ format: "mdx",+ size: encoder.encode(currentSource).byteLength,+ createdAt: "2026-08-15T00:00:00.000Z",+ };+ }+ );+ return {+ get reads() {+ return reads;+ },+ updateContent,+ setSource: (source: string) => {+ currentSource = source;+ },+ repository: {+ readContent: async ({ assetId }: { assetId: string }) => {+ reads += 1;+ const bytes = encoder.encode(currentSource);+ return {+ asset: {+ id: assetId,+ projectId: "project",+ name: `${assetId}_revision.mdx`,+ type: "file" as const,+ format: "mdx",+ size: bytes.byteLength,+ createdAt: "2026-08-15T00:00:00.000Z",+ },+ data: {+ async *[Symbol.asyncIterator]() {+ yield bytes;+ },+ },+ };+ },+ updateContent,+ },+ };+};++const createState = ({+ body = true,+ source,+}: {+ body?: boolean;+ source?: ContentBlockSource;+} = {}) => ({+ pages: {+ pages: new Map([+ [+ "page",+ {+ id: "page",+ name: "Page",+ path: "",+ title: "Page",+ meta: {},+ rootInstanceId: "block",+ },+ ],+ ]),+ pageTemplates: new Map(),+ },+ assets: new Map(),+ assetFolders: new Map(),+ instances: new Map([+ [+ "block",+ {+ type: "instance" as const,+ id: "block",+ component: blockComponent,+ children: [+ { type: "id" as const, value: "templates" },+ ...(body ? [{ type: "id" as const, value: "body" }] : []),+ ],+ },+ ],+ [+ "templates",+ {+ type: "instance" as const,+ id: "templates",+ component: blockTemplateComponent,+ children: [],+ },+ ],+ [+ "body",+ {+ type: "instance" as const,+ id: "body",+ component: elementComponent,+ tag: "p",+ children: [{ type: "text" as const, value: "Block body" }],+ },+ ],+ ]),+ props: new Map(+ source === undefined+ ? []+ : [+ [+ "src",+ source.type === "asset"+ ? {+ id: "src",+ instanceId: "block",+ name: "src",+ type: "asset" as const,+ value: source.assetId,+ }+ : {+ id: "src",+ instanceId: "block",+ name: "src",+ type: "expression" as const,+ value: source.value,+ },+ ],+ ]+ ),+ dataSources: new Map(),+ resources: new Map(),+ breakpoints: new Map(),+ styleSources: new Map(),+ styleSourceSelections: new Map(),+ styles: new Map(),+ marketplaceProduct: undefined,+ projectSettings: undefined,+});++const createController = ({+ state,+ fileSource = "# File body",+ authorizeAsset = () => true,+ updateError,+}: {+ state: ReturnType<typeof createState>;+ fileSource?: string;+ authorizeAsset?: () => boolean;+ updateError?: Error;+}) => {+ const storage = createRepository(fileSource, updateError);+ const session = createMdxAssetEditingSession({+ repository: storage.repository,+ authorizeAsset,+ });+ const commitProjectPayload = vi.fn();+ const invalidateAssets = vi.fn();+ const publishSessionState = vi.fn();+ const controller = createContentBlockSourceController({+ blockInstanceId: "block",+ renderScope: "scope",+ projectId: "project",+ session,+ getState: () => ({ ...state }) as never,+ commitProjectPayload,+ invalidateAssets,+ publishSessionState,+ });+ return {+ controller,+ commitProjectPayload,+ invalidateAssets,+ publishSessionState,+ session,+ storage,+ };+};++test("connects using file content through one Builder project transaction", async () => {+ const setup = createController({ state: createState() });+ const source = { type: "asset" as const, assetId: "post" };++ await expect(setup.controller.requestSource({ source })).resolves.toEqual({+ status: "requires-authority",+ });+ await expect(+ setup.controller.requestSource({ source, authority: "use-file-content" })+ ).resolves.toMatchObject({ status: "applied" });++ expect(setup.commitProjectPayload).toHaveBeenCalledTimes(1);+ expect(setup.commitProjectPayload.mock.calls[0]?.[0]).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ namespace: "instances" }),+ expect.objectContaining({ namespace: "props" }),+ ])+ );+ expect(setup.storage.updateContent).not.toHaveBeenCalled();+});++test("replaces the Asset before committing the project connection", async () => {+ const setup = createController({ state: createState() });++ const result = await setup.controller.requestSource({+ source: { type: "asset", assetId: "post" },+ authority: "replace-file-body-with-block-content",+ });++ expect(result).toMatchObject({ status: "applied" });+ expect(setup.commitProjectPayload).toHaveBeenCalledOnce();+ expect(setup.storage.updateContent).toHaveBeenCalledOnce();+ expect(setup.storage.updateContent.mock.invocationCallOrder[0]).toBeLessThan(+ setup.commitProjectPayload.mock.invocationCallOrder[0]+ );+ expect(setup.storage.reads).toBe(1);+ expect(setup.publishSessionState).toHaveBeenLastCalledWith(+ expect.objectContaining({ status: "saved" })+ );+});++test("keeps the previous view when the Asset saves but project connection fails", async () => {+ const setup = createController({ state: createState() });+ setup.commitProjectPayload.mockRejectedValueOnce(+ new Error("Project connection failed")+ );++ await expect(+ setup.controller.requestSource({+ source: { type: "asset", assetId: "post" },+ authority: "replace-file-body-with-block-content",+ })+ ).resolves.toMatchObject({+ status: "partial",+ persistence: {+ status: "partial",+ steps: [+ { type: "asset", status: "saved" },+ { type: "project", status: "failed" },+ ],+ retry: { replan: true, roots: [], project: true },+ },+ });+ expect(setup.storage.updateContent).toHaveBeenCalledOnce();+ expect(setup.publishSessionState).not.toHaveBeenCalled();+ expect(setup.invalidateAssets).toHaveBeenCalledOnce();+});++test("does not start lifecycle persistence after disposal", async () => {+ const setup = createController({ state: createState() });+ const request = setup.controller.requestSource({+ source: { type: "asset", assetId: "post" },+ authority: "replace-file-body-with-block-content",+ });+ setup.controller.dispose();++ await expect(request).resolves.toMatchObject({+ status: "blocked",+ message: "The MDX Asset session is closed.",+ });+ expect(setup.storage.updateContent).not.toHaveBeenCalled();+ expect(setup.session.list()).toEqual([+ expect.objectContaining({ status: "saved", source: "# File body" }),+ ]);+});++test("disconnects by copying loaded file content into one project transaction", async () => {+ const source = { type: "asset" as const, assetId: "post" };+ const setup = createController({+ state: createState({ body: false, source }),+ });+ await setup.controller.open(source);++ await expect(setup.controller.disconnect()).resolves.toMatchObject({+ status: "applied",+ });++ expect(setup.commitProjectPayload).toHaveBeenCalledTimes(1);+ expect(setup.commitProjectPayload.mock.calls[0]?.[0]).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ namespace: "instances" }),+ expect.objectContaining({ namespace: "props" }),+ ])+ );+ expect(setup.storage.updateContent).not.toHaveBeenCalled();+});++test("rejects stale project preparation before committing a patch", async () => {+ const state = createState();+ const setup = createController({ state });+ const pending = setup.controller.requestSource({+ source: { type: "asset", assetId: "post" },+ authority: "use-file-content",+ });+ state.props = new Map(state.props);++ await expect(pending).resolves.toEqual({+ status: "blocked",+ code: "content-source-session-failed",+ message: "The project changed while preparing this source update.",+ });+ expect(setup.commitProjectPayload).not.toHaveBeenCalled();+});++test("surfaces exact Asset authorization failure without a project mutation", async () => {+ const setup = createController({+ state: createState({ body: false }),+ authorizeAsset: () => false,+ });++ const state = await setup.controller.open({+ type: "asset",+ assetId: "post",+ });++ expect(state).toMatchObject({ status: "failed" });+ expect(setup.publishSessionState).toHaveBeenCalledWith(+ expect.objectContaining({ status: "failed" })+ );+ expect(setup.commitProjectPayload).not.toHaveBeenCalled();+});++test("retries a recoverable parse failure by reopening the pinned source", async () => {+ const source = { type: "asset" as const, assetId: "post" };+ const setup = createController({+ state: createState({ body: false, source }),+ fileSource: '{alert("unsafe")}',+ });+ await expect(setup.controller.open(source)).resolves.toMatchObject({+ status: "recoverable",+ });+ setup.storage.setSource("# Repaired");++ await expect(setup.controller.retry()).resolves.toMatchObject({+ status: "applied",+ state: { status: "saved" },+ });+ expect(setup.publishSessionState).toHaveBeenLastCalledWith(+ expect.objectContaining({ status: "saved" })+ );+});++test("requires explicit remote reload instead of blindly retrying a conflict", async () => {+ const conflicting = {+ status: "conflicting" as const,+ key: "post",+ identity: { assetId: "post" },+ diagnostics: [],+ };+ const retry = vi.fn();+ const session = {+ open: vi.fn(async () => conflicting),+ get: vi.fn(() => conflicting),+ retry,+ list: () => [],+ };+ const controller = createContentBlockSourceController({+ blockInstanceId: "block",+ renderScope: "scope",+ projectId: "project",+ session: session as never,+ getState: () =>+ createState({+ body: false,+ source: { type: "asset", assetId: "post" },+ }) as never,+ commitProjectPayload: vi.fn(),+ invalidateAssets: vi.fn(),+ });+ await controller.open({ type: "asset", assetId: "post" });++ await expect(controller.retry()).resolves.toEqual({+ status: "blocked",+ code: "content-source-session-failed",+ message:+ "Retry is not available while the MDX Asset session is conflicting",+ });+ expect(retry).not.toHaveBeenCalled();+});++test("does not publish a retry that finishes after the source changes", async () => {+ const failed = {+ status: "failed" as const,+ key: "first",+ identity: { assetId: "first" },+ diagnostics: [],+ localSource: "Unsaved",+ };+ const saved = (assetId: string) => ({+ status: "saved" as const,+ key: assetId,+ identity: { assetId },+ root: {},+ diagnostics: [],+ });+ let finishRetry: ((state: ReturnType<typeof saved>) => void) | undefined;+ const session = {+ open: vi.fn(({ source }: { source: ContentBlockSource }) =>+ Promise.resolve(+ source.type === "asset" && source.assetId === "first"+ ? failed+ : saved("second")+ )+ ),+ get: vi.fn(() => failed),+ retry: vi.fn(+ () =>+ new Promise<ReturnType<typeof saved>>((resolve) => {+ finishRetry = resolve;+ })+ ),+ list: () => [],+ };+ const publishSessionState = vi.fn();+ const controller = createContentBlockSourceController({+ blockInstanceId: "block",+ renderScope: "scope",+ projectId: "project",+ session: session as never,+ getState: () => createState() as never,+ commitProjectPayload: vi.fn(),+ invalidateAssets: vi.fn(),+ publishSessionState,+ });+ await controller.open({ type: "asset", assetId: "first" });+ const retrying = controller.retry();+ await controller.open({ type: "asset", assetId: "second" });+ finishRetry?.(saved("first-retried"));++ await expect(retrying).resolves.toEqual({+ status: "blocked",+ message: "The MDX Asset session changed.",+ });+ expect(publishSessionState).toHaveBeenCalledTimes(2);+ expect(publishSessionState).toHaveBeenLastCalledWith(saved("second"));+});++test("persists a single-Asset content edit and invalidates Asset resources", async () => {+ const setup = createController({+ state: createState({ body: false }),+ fileSource: "Before",+ });+ const loaded = await setup.controller.open({+ type: "asset",+ assetId: "post",+ });+ if (loaded.status !== "saved") {+ throw new Error(`Expected saved state, received ${loaded.status}`);+ }+ expect(setup.controller.isCurrent(loaded.root)).toBe(true);++ const saveResult = await setup.controller.saveStorageChanges([+ {+ root: { type: "external", identity: loaded.identity },+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: [+ loaded.root.fragment.instances[0].id,+ "children",+ 0,+ "value",+ ],+ value: "After",+ },+ ],+ },+ ],+ },+ ]);+ expect(saveResult).toMatchObject({ status: "applied" });+ if (saveResult.status !== "applied" || saveResult.state?.status !== "saved") {+ throw new Error("Expected the MDX edit to be saved");+ }+ expect(setup.controller.isCurrent(loaded.root)).toBe(false);+ expect(setup.controller.isCurrent(saveResult.state.root)).toBe(true);++ expect(setup.storage.updateContent).toHaveBeenCalledTimes(1);+ expect(setup.invalidateAssets).toHaveBeenCalledTimes(1);+ expect(setup.commitProjectPayload).not.toHaveBeenCalled();+});++test("preserves the failed source for recovery when an Asset save fails", async () => {+ const setup = createController({+ state: createState({ body: false }),+ fileSource: "Before",+ updateError: new Error("write failed"),+ });+ const loaded = await setup.controller.open({+ type: "asset",+ assetId: "post",+ });+ if (loaded.status !== "saved") {+ throw new Error("Expected saved state");+ }++ expect(+ await setup.controller.saveStorageChanges([+ {+ root: { type: "external", identity: loaded.identity },+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: [+ loaded.root.fragment.instances[0].id,+ "children",+ 0,+ "value",+ ],+ value: "After",+ },+ ],+ },+ ],+ },+ ])+ ).toMatchObject({ status: "blocked" });+ expect(setup.invalidateAssets).not.toHaveBeenCalled();+ expect(setup.commitProjectPayload).not.toHaveBeenCalled();+});++test("keeps the newest source when an older load finishes last", async () => {+ const createLoadedState = (assetId: string) => ({+ status: "saved" as const,+ key: assetId,+ identity: { assetId },+ root: {},+ diagnostics: [],+ source: assetId,+ });+ let finishFirstLoad:+ | ((state: ReturnType<typeof createLoadedState>) => void)+ | undefined;+ const session = {+ open: vi.fn(({ source }: { source: ContentBlockSource }) =>+ source.type === "asset" && source.assetId === "first"+ ? new Promise<ReturnType<typeof createLoadedState>>((resolve) => {+ finishFirstLoad = resolve;+ })+ : Promise.resolve(createLoadedState("second"))+ ),+ queueSave: vi.fn(({ key }: { key: string }) =>+ Promise.resolve(createLoadedState(key))+ ),+ get: (key: string) => createLoadedState(key),+ list: () => [],+ };+ const controller = createContentBlockSourceController({+ blockInstanceId: "block",+ renderScope: "scope",+ projectId: "project",+ session: session as never,+ getState: () => createState() as never,+ commitProjectPayload: vi.fn(),+ invalidateAssets: vi.fn(),+ });++ const firstLoad = controller.open({ type: "asset", assetId: "first" });+ await controller.open({ type: "asset", assetId: "second" });+ finishFirstLoad?.(createLoadedState("first"));+ await firstLoad;+ await controller.saveStorageChanges([]);++ expect(session.queueSave).toHaveBeenCalledWith({+ key: "second",+ changes: [],+ });+});++test("finishes an in-flight save against its pinned source after switching", async () => {+ const createLoadedState = (assetId: string) => ({+ status: "saved" as const,+ key: assetId,+ identity: { assetId },+ root: {},+ diagnostics: [],+ source: assetId,+ });+ let finishQueue: ((state: unknown) => void) | undefined;+ const queueSave = vi+ .fn()+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finishQueue = resolve;+ })+ )+ .mockImplementation(({ key }: { key: string }) =>+ Promise.resolve(createLoadedState(key))+ );+ const flush = vi.fn((key: string) =>+ Promise.resolve(createLoadedState(`${key}-saved`))+ );+ const session = {+ open: vi.fn(({ source }: { source: ContentBlockSource }) =>+ Promise.resolve(+ createLoadedState(source.type === "asset" ? source.assetId : "dynamic")+ )+ ),+ queueSave,+ flush,+ get: (key: string) => createLoadedState(key),+ list: () => [],+ };+ const controller = createContentBlockSourceController({+ blockInstanceId: "block",+ renderScope: "scope",+ projectId: "project",+ session: session as never,+ getState: () => createState() as never,+ commitProjectPayload: vi.fn(),+ invalidateAssets: vi.fn(),+ });++ await controller.open({ type: "asset", assetId: "first" });+ const saving = controller.saveStorageChanges([]);+ await controller.open({ type: "asset", assetId: "second" });+ finishQueue?.({ ...createLoadedState("first"), status: "pending" });+ await saving;+ await controller.saveStorageChanges([]);++ expect(flush).toHaveBeenCalledWith("first");+ expect(queueSave).toHaveBeenLastCalledWith({ key: "second", changes: [] });+});diff --git a/apps/builder/app/builder/features/settings-panel/controls/content-block-source-controller.ts b/apps/builder/app/builder/features/settings-panel/controls/content-block-source-controller.tsnew file mode 100644index 0000000000..5366eb89a8--- /dev/null+++ b/apps/builder/app/builder/features/settings-panel/controls/content-block-source-controller.ts@@ -0,0 +1,718 @@+import {+ ContentBlockSourceAuthorityRequiredError,+ builderRuntimeContext,+ computeExpression,+ createMdxAssetEditingSession,+ getContentBlockSessionErrorCode,+ getContentBlockSessionMessage,+ getContentBlockSessionSource,+ getContentStorageIdentityKey,+ persistPreparedContentBlockLifecycle,+ prepareContentBlockConnect,+ prepareContentBlockDisconnect,+ prepareContentBlockSwitch,+ recoverContentBlockSession,+ isContentBlockSessionSourceCommitted,+ type ContentBlockSourceAuthority,+ type ContentBlockPersistenceResult,+ type ContentStorageChange,+ type MaterializedContentRoot,+ type MdxAssetEditingSessionState,+} from "@webstudio-is/project-build/runtime";+import {+ getContentBlockSource,+ type ContentBlockSource,+} from "@webstudio-is/sdk";+import { createBuilderHttpAssetContentRepository } from "~/builder/shared/assets/builder-mdx-content-repository.client";+import {+ $variableValuesByInstanceSelector,+ getInstanceKeyWithRoot,+} from "~/shared/nano-states";+import {+ $project,+ hasSameBuilderStateStoreReferences,+ readBuilderStateStores,+} from "~/shared/sync/data-stores";+import { getAssetContentBridge } from "~/shared/asset-content-bridge.client";+import { createTransactionFromBuilderPatchPayload } from "~/shared/sync/builder-patch";+import { getWebstudioData } from "~/shared/instance-utils/data";+import { invalidateAssets } from "~/shared/resources";+import {+ publishMaterializedContentSessionState,+ registerContentStorageSaver,+ removeMaterializedContentRoot,+ registerContentBlockPresentationActions,+} from "~/shared/content-block-content";++export type ContentBlockSourceControllerResult =+ | Readonly<{+ status: "applied";+ state?: MdxAssetEditingSessionState;+ }>+ | Readonly<{ status: "requires-authority" }>+ | Readonly<{+ status: "partial";+ code: "content-source-partial-persistence";+ message: string;+ persistence: ContentBlockPersistenceResult;+ }>+ | Readonly<{ status: "blocked"; code?: string; message: string }>;++type ContentBlockSourceControllerDependencies = Readonly<{+ blockInstanceId: string;+ renderScope: string;+ projectId: string;+ session: ReturnType<typeof createMdxAssetEditingSession>;+ getState: typeof readBuilderStateStores;+ commitProjectPayload: (+ payload: Parameters<+ typeof createTransactionFromBuilderPatchPayload+ >[0]["payload"]+ ) => void;+ invalidateAssets: () => void;+ publishMaterializedRoot?: (root: MaterializedContentRoot) => void;+ publishSessionState?: (state: MdxAssetEditingSessionState) => void;+ removeMaterializedRoot?: () => void;+}>;++const getConfiguredSource = ({+ state,+ blockInstanceId,+}: {+ state: ReturnType<typeof readBuilderStateStores>;+ blockInstanceId: string;+}) => {+ return getContentBlockSource({+ blockInstanceId,+ props: state.props.values(),+ });+};++// Builder retains a long-lived session for canvas projection.+// Lifecycle persistence and recovery policy stay in project-build so the+// generated application operations and this stateful adapter make the same+// authorization, conflict, and serial persistence decisions.+export const createContentBlockSourceController = ({+ blockInstanceId,+ renderScope,+ projectId,+ session,+ getState,+ commitProjectPayload,+ invalidateAssets: invalidate,+ publishMaterializedRoot,+ publishSessionState,+ removeMaterializedRoot,+}: ContentBlockSourceControllerDependencies) => {+ let currentSessionKey: string | undefined;+ let openVersion = 0;+ let disposed = false;+ const open = async (source: ContentBlockSource) => {+ const version = ++openVersion;+ const state = await session.open({+ blockInstanceId,+ source,+ renderScope,+ state: getState(),+ projectId,+ });+ if (disposed === false && version === openVersion) {+ if ("key" in state) {+ currentSessionKey = state.key;+ }+ publishSessionState?.(state);+ if ("root" in state && state.status === "saved") {+ publishMaterializedRoot?.(state.root);+ }+ }+ return state;+ };++ const applyPrepared = async (+ prepared: Awaited<+ ReturnType<+ | typeof prepareContentBlockConnect+ | typeof prepareContentBlockDisconnect+ | typeof prepareContentBlockSwitch+ >+ >,+ expectedState: ReturnType<typeof readBuilderStateStores>+ ): Promise<ContentBlockSourceControllerResult> => {+ if (disposed) {+ return {+ status: "blocked",+ message: "The MDX Asset session is closed.",+ };+ }+ const persisted = await persistPreparedContentBlockLifecycle({+ prepared,+ session,+ commitProjectPayload: (payload) => commitProjectPayload([...payload]),+ canCommitProjectPayload: () =>+ hasSameBuilderStateStoreReferences(expectedState, getState()),+ });+ if (persisted.status !== "complete") {+ const failedStep = persisted.persistence.steps.find(+ ({ status }) => status === "failed"+ );+ if (persisted.state !== undefined && failedStep?.type === "asset") {+ publishSessionState?.(persisted.state);+ }+ if (+ persisted.persistence.steps.some(+ ({ type, status }) => type === "asset" && status === "saved"+ )+ ) {+ invalidate();+ }+ if (persisted.status === "partial") {+ return {+ status: "partial",+ code: "content-source-partial-persistence",+ message:+ "Some content changes were saved. Retry the unfinished steps.",+ persistence: persisted.persistence,+ };+ }+ return {+ status: "blocked",+ code: failedStep?.code,+ message:+ failedStep?.message ?? "The content changes could not be saved.",+ };+ }+ if (disposed) {+ return { status: "applied", state: persisted.state };+ }+ if (persisted.state !== undefined) {+ publishSessionState?.(persisted.state);+ if ("key" in persisted.state) {+ currentSessionKey = persisted.state.key;+ }+ if (persisted.state.status === "saved") {+ publishMaterializedRoot?.(persisted.state.root);+ }+ }+ if (prepared.storageWrites.length > 0) {+ invalidate();+ }+ if (prepared.action === "disconnect") {+ currentSessionKey = undefined;+ removeMaterializedRoot?.();+ }+ return { status: "applied", state: persisted.state };+ };++ const requestSource = async ({+ source,+ authority,+ }: {+ source: ContentBlockSource;+ authority?: ContentBlockSourceAuthority;+ }): Promise<ContentBlockSourceControllerResult> => {+ if (disposed) {+ return { status: "blocked", message: "The MDX Asset session is closed." };+ }+ const state = getState();+ const configuredSource = getConfiguredSource({ state, blockInstanceId });+ try {+ if (configuredSource === undefined) {+ return await applyPrepared(+ await prepareContentBlockConnect({+ state,+ blockInstanceId,+ source,+ renderScope,+ projectId,+ authority,+ session,+ context: builderRuntimeContext,+ }),+ state+ );+ }+ if (currentSessionKey === undefined) {+ const current = await open(configuredSource);+ if (!("key" in current) || !("root" in current)) {+ return {+ status: "blocked",+ message: "The current MDX file could not be loaded.",+ };+ }+ }+ const currentKey = currentSessionKey;+ if (currentKey === undefined) {+ return { status: "blocked", message: "The MDX Asset is not loaded." };+ }+ return await applyPrepared(+ await prepareContentBlockSwitch({+ state,+ blockInstanceId,+ currentSessionKey: currentKey,+ source,+ renderScope,+ projectId,+ authority,+ session,+ context: builderRuntimeContext,+ }),+ state+ );+ } catch (error) {+ if (error instanceof ContentBlockSourceAuthorityRequiredError) {+ return { status: "requires-authority" };+ }+ throw error;+ }+ };++ const disconnect = async (): Promise<ContentBlockSourceControllerResult> => {+ if (disposed) {+ return { status: "blocked", message: "The MDX Asset session is closed." };+ }+ const state = getState();+ const source = getConfiguredSource({ state, blockInstanceId });+ if (source !== undefined && currentSessionKey === undefined) {+ const current = await open(source);+ if (!("key" in current) || !("root" in current)) {+ return {+ status: "blocked",+ message: "The current MDX file could not be loaded.",+ };+ }+ }+ return await applyPrepared(+ await prepareContentBlockDisconnect({+ state,+ blockInstanceId,+ currentSessionKey,+ renderScope,+ session,+ context: builderRuntimeContext,+ }),+ state+ );+ };++ const saveStorageChanges = async (+ changes: readonly ContentStorageChange[]+ ): Promise<ContentBlockSourceControllerResult> => {+ if (disposed || currentSessionKey === undefined) {+ return { status: "blocked", message: "The MDX Asset is not loaded." };+ }+ const key = currentSessionKey;+ const pending = await session.queueSave({ key, changes });+ if (disposed === false && currentSessionKey === key) {+ publishSessionState?.(pending);+ }+ if (pending.status !== "pending" && pending.status !== "saved") {+ return {+ status: "blocked",+ code: getContentBlockSessionErrorCode(pending),+ message: getContentBlockSessionMessage(pending),+ };+ }+ if (disposed) {+ if (pending.status === "pending") {+ session.cancel(key);+ }+ return {+ status: "blocked",+ message: "The MDX Asset editing session was closed.",+ };+ }+ const expectedSource = getContentBlockSessionSource(pending);+ if (expectedSource === undefined) {+ return {+ status: "blocked",+ message: "The updated MDX source is unavailable.",+ };+ }+ const saved =+ pending.status === "pending" ? await session.flush(key) : pending;+ if (disposed === false && currentSessionKey === key) {+ publishSessionState?.(saved);+ }+ const committed = isContentBlockSessionSourceCommitted({+ state: saved,+ source: expectedSource,+ });+ const committedWithProjectionError =+ committed && saved.status === "recoverable";+ if (committed === false) {+ return {+ status: "blocked",+ code: getContentBlockSessionErrorCode(saved),+ message: getContentBlockSessionMessage(saved),+ };+ }+ if (disposed) {+ return {+ status: "blocked",+ message: "The MDX Asset editing session was closed.",+ };+ }+ const savedCurrentSource = currentSessionKey === key;+ if (savedCurrentSource && "key" in saved) {+ currentSessionKey = saved.key;+ }+ if (saved.status === "saved" && savedCurrentSource) {+ publishMaterializedRoot?.(saved.root);+ }+ if (+ (saved.status === "saved" && currentSessionKey === saved.key) ||+ committedWithProjectionError+ ) {+ invalidate();+ }+ return { status: "applied", state: saved };+ };++ const preflightStorageChanges = async (+ changes: readonly ContentStorageChange[]+ ): Promise<ContentBlockSourceControllerResult> => {+ if (disposed || currentSessionKey === undefined) {+ return { status: "blocked", message: "The MDX Asset is not loaded." };+ }+ const preflight = await session.preflightSave({+ key: currentSessionKey,+ changes,+ });+ return preflight.status === "ready"+ ? { status: "applied" }+ : { status: "blocked", message: preflight.reason };+ };++ const retry = async (): Promise<ContentBlockSourceControllerResult> => {+ if (disposed) {+ return { status: "blocked", message: "The MDX Asset session is closed." };+ }+ const current =+ currentSessionKey === undefined+ ? undefined+ : session.get(currentSessionKey);+ if (current === undefined || currentSessionKey === undefined) {+ const source = getConfiguredSource({+ state: getState(),+ blockInstanceId,+ });+ if (source === undefined) {+ return {+ status: "blocked",+ message: "The MDX source is disconnected.",+ };+ }+ const state = await open(source);+ return state.status === "saved" || state.status === "pending"+ ? { status: "applied", state }+ : {+ status: "blocked",+ message: getContentBlockSessionMessage(state),+ };+ }+ const key = currentSessionKey;+ const source = getConfiguredSource({ state: getState(), blockInstanceId });+ const recovered = await recoverContentBlockSession({+ session,+ state: current,+ action: "retry",+ reopen:+ source === undefined+ ? undefined+ : () =>+ session.open({+ blockInstanceId,+ source,+ renderScope,+ state: getState(),+ projectId,+ }),+ });+ if (disposed || currentSessionKey !== key) {+ return { status: "blocked", message: "The MDX Asset session changed." };+ }+ publishSessionState?.(recovered.state);+ if (recovered.status === "blocked") {+ return {+ status: "blocked",+ code: recovered.code,+ message: recovered.message,+ };+ }+ if (recovered.state.status === "saved") {+ currentSessionKey = recovered.state.key;+ publishMaterializedRoot?.(recovered.state.root);+ }+ if (recovered.changedAsset) {+ invalidate();+ }+ return { status: "applied", state: recovered.state };+ };++ const reloadRemote =+ async (): Promise<ContentBlockSourceControllerResult> => {+ if (disposed || currentSessionKey === undefined) {+ return { status: "blocked", message: "The MDX Asset is not loaded." };+ }+ const key = currentSessionKey;+ const current = session.get(key);+ if (current === undefined) {+ return { status: "blocked", message: "The MDX Asset is not loaded." };+ }+ const recovered = await recoverContentBlockSession({+ session,+ state: current,+ action: "reload-remote",+ });+ if (disposed || currentSessionKey !== key) {+ return { status: "blocked", message: "The MDX Asset session changed." };+ }+ const state = recovered.state;+ if ("key" in state) {+ currentSessionKey = state.key;+ }+ publishSessionState?.(state);+ if (recovered.status === "complete" && state.status === "saved") {+ publishMaterializedRoot?.(state.root);+ invalidate();+ }+ return recovered.status === "complete"+ ? { status: "applied", state }+ : {+ status: "blocked",+ code: recovered.code,+ message: recovered.message,+ };+ };++ const copyUnsavedSource = () =>+ currentSessionKey === undefined+ ? undefined+ : session.copyUnsavedSource(currentSessionKey);++ const isCurrent = ({ identity }: MaterializedContentRoot) => {+ const state =+ currentSessionKey === undefined+ ? undefined+ : session.get(currentSessionKey);+ return (+ state !== undefined &&+ "identity" in state &&+ getContentStorageIdentityKey(state.identity) ===+ getContentStorageIdentityKey(identity)+ );+ };++ const dispose = () => {+ if (disposed) {+ return;+ }+ disposed = true;+ openVersion += 1;+ currentSessionKey = undefined;+ for (const state of session.list()) {+ if (state.status === "pending") {+ session.cancel(state.key);+ }+ }+ };++ return {+ open,+ requestSource,+ disconnect,+ preflightStorageChanges,+ saveStorageChanges,+ retry,+ reloadRemote,+ copyUnsavedSource,+ isCurrent,+ dispose,+ };+};++type BuilderContentBlockSourceController = ReturnType<+ typeof createContentBlockSourceController+>;++type BuilderControllerEntry = {+ controller: BuilderContentBlockSourceController;+ unregisterSaver: () => void;+ unregisterPresentationActions: () => void;+ references: number;+};++const builderControllers = new Map<string, BuilderControllerEntry>();++const acquireBuilderController = ({+ controllerKey,+ entry,+ blockInstanceId,+ renderScope,+}: {+ controllerKey: string;+ entry: BuilderControllerEntry;+ blockInstanceId: string;+ renderScope: string;+}) => {+ let released = false;+ return {+ ...entry.controller,+ dispose: () => {+ if (released) {+ return;+ }+ released = true;+ entry.references -= 1;+ if (entry.references !== 0) {+ return;+ }+ builderControllers.delete(controllerKey);+ entry.unregisterSaver();+ entry.unregisterPresentationActions();+ entry.controller.dispose();+ removeMaterializedContentRoot({ blockInstanceId, renderScope });+ },+ };+};++export const createBuilderContentBlockSourceController = ({+ blockInstanceId,+ renderScope,+ projectId,+}: {+ blockInstanceId: string;+ renderScope: string;+ projectId: string;+}) => {+ const controllerKey = JSON.stringify([+ projectId,+ blockInstanceId,+ renderScope,+ ]);+ const existing = builderControllers.get(controllerKey);+ if (existing !== undefined) {+ existing.references += 1;+ return acquireBuilderController({+ controllerKey,+ entry: existing,+ blockInstanceId,+ renderScope,+ });+ }+ const repository = createBuilderHttpAssetContentRepository({ projectId });+ const session = createMdxAssetEditingSession({+ repository,+ authorizeAsset: ({ assetId, operation, identity }) =>+ getAssetContentBridge().authorize({+ projectId,+ assetId,+ identityAssetId: identity?.assetId,+ operation,+ }),+ resolveExpressionAssetId: ({ expression, renderScope: scope }) => {+ const values = $variableValuesByInstanceSelector.get();+ let selector: unknown;+ try {+ selector = JSON.parse(scope);+ } catch {+ selector = undefined;+ }+ const variables =+ values.get(scope) ??+ (Array.isArray(selector) &&+ selector.every((instanceId) => typeof instanceId === "string")+ ? values.get(getInstanceKeyWithRoot(selector))+ : undefined);+ const value = computeExpression(expression, variables ?? new Map());+ return typeof value === "string" && value !== "" ? value : undefined;+ },+ });+ const controller = createContentBlockSourceController({+ blockInstanceId,+ renderScope,+ projectId,+ session,+ getState: readBuilderStateStores,+ commitProjectPayload: (payload) =>+ createTransactionFromBuilderPatchPayload({+ data: getWebstudioData(),+ payload,+ }),+ invalidateAssets,+ publishSessionState: (state) => {+ if ($project.get()?.id === projectId) {+ publishMaterializedContentSessionState({+ blockInstanceId,+ renderScope,+ state,+ });+ }+ },+ removeMaterializedRoot: () =>+ removeMaterializedContentRoot({ blockInstanceId, renderScope }),+ });+ const unregisterSaver = registerContentStorageSaver({+ blockInstanceId,+ renderScope,+ preflight: async (changes) => {+ const result = await controller.preflightStorageChanges(changes);+ return result.status === "applied"+ ? result+ : {+ status: "blocked",+ message:+ result.status === "requires-authority"+ ? "Saving MDX content cannot require content authority."+ : result.message,+ };+ },+ isCurrent: controller.isCurrent,+ save: async (changes) => {+ const result = await controller.saveStorageChanges(changes);+ const saveResult =+ result.status === "requires-authority"+ ? {+ status: "blocked" as const,+ message: "Saving MDX content cannot require content authority.",+ }+ : result;+ return saveResult;+ },+ });+ const toStorageResult = (result: ContentBlockSourceControllerResult) =>+ result.status === "applied"+ ? ({ status: "applied" } as const)+ : {+ status: "blocked" as const,+ message:+ result.status === "blocked"+ ? result.message+ : "The MDX operation requires content authority.",+ };+ const unregisterPresentationActions = registerContentBlockPresentationActions(+ {+ blockInstanceId,+ renderScope,+ actions: {+ retry: async () => toStorageResult(await controller.retry()),+ reloadRemote: async () =>+ toStorageResult(await controller.reloadRemote()),+ copyUnsavedSource: controller.copyUnsavedSource,+ },+ }+ );+ const entry = {+ controller,+ unregisterSaver,+ unregisterPresentationActions,+ references: 1,+ };+ builderControllers.set(controllerKey, entry);+ return acquireBuilderController({+ controllerKey,+ entry,+ blockInstanceId,+ renderScope,+ });+};diff --git a/apps/builder/app/builder/features/settings-panel/controls/content-block-source-section.tsx b/apps/builder/app/builder/features/settings-panel/controls/content-block-source-section.tsxnew file mode 100644index 0000000000..530331c104--- /dev/null+++ b/apps/builder/app/builder/features/settings-panel/controls/content-block-source-section.tsx@@ -0,0 +1,280 @@+import { useEffect, useMemo, useState } from "react";+import { useStore } from "@nanostores/react";+import {+ decodeUtf8,+ readBoundedBytes,+} from "@webstudio-is/content-engine/compiler";+import { contentEngineLimits } from "@webstudio-is/content-engine/limits";+import { previewMarkdownToMdxConversion } from "@webstudio-is/content-engine/mdx-conversion";+import { getContentBlockRenderScopeKey } from "@webstudio-is/project-build/runtime";+import {+ formatAssetName,+ formatContentBlockSourceIntegrityIssue,+ getFileNameParts,+ getContentBlockSourceIntegrityIssues,+ getContentBlockSource,+ type ContentBlockSource,+} from "@webstudio-is/sdk";+import { TextFileEditor } from "~/builder/features/text-file-editor/text-file-editor";+import { createBuilderHttpAssetContentRepository } from "~/builder/shared/assets/builder-mdx-content-repository.client";+import { uploadSingleAsset } from "~/builder/shared/assets/upload-assets";+import { $authPermit } from "~/shared/nano-states";+import {+ $assets,+ $instances,+ $project,+ $props,+} from "~/shared/sync/data-stores";+import { ContentBlockSourceControl } from "./content-block-source";+import { createBuilderContentBlockSourceController } from "./content-block-source-controller";+import {+ $materializedContentViewStates,+ formatContentBlockDiagnostic,+} from "~/shared/content-block-content";+import { $publisher } from "~/shared/pubsub";++const getSource = (+ blockInstanceId: string,+ props: ReturnType<typeof $props.get>+) => {+ return getContentBlockSource({ blockInstanceId, props: props.values() });+};++const getStateError = (+ state: Awaited<+ ReturnType<+ ReturnType<typeof createBuilderContentBlockSourceController>["open"]+ >+ >+) => {+ if (state.status === "failed" || state.status === "recoverable") {+ return state.diagnostics[0] === undefined+ ? "The MDX file could not be loaded."+ : formatContentBlockDiagnostic(state.diagnostics[0]);+ }+ if (state.status === "conflicting") {+ return "The MDX file changed remotely. Reload it before editing.";+ }+};++export const ContentBlockSourceSection = ({+ blockInstanceId,+ renderScope,+}: {+ blockInstanceId: string;+ renderScope: string;+}) => {+ const project = useStore($project);+ const props = useStore($props);+ const assets = useStore($assets);+ const instances = useStore($instances);+ const authPermit = useStore($authPermit);+ const materializedViewStates = useStore($materializedContentViewStates);+ const viewState = materializedViewStates.get(+ getContentBlockRenderScopeKey(blockInstanceId, renderScope)+ );+ const source = useMemo(+ () => getSource(blockInstanceId, props),+ [blockInstanceId, props]+ );+ const resolvedAssetId =+ source?.type === "asset"+ ? source.assetId+ : (viewState?.identity?.assetId ?? viewState?.assetId);+ const resolvedAsset =+ resolvedAssetId === undefined ? undefined : assets.get(resolvedAssetId);+ const blockInstance = instances.get(blockInstanceId);+ const sourceIntegrityIssue =+ blockInstance === undefined+ ? undefined+ : getContentBlockSourceIntegrityIssues({+ instances: [blockInstance],+ props: props.values(),+ assets: assets.values(),+ })[0];+ const sourceIntegrityError =+ sourceIntegrityIssue === undefined+ ? undefined+ : formatContentBlockSourceIntegrityIssue(sourceIntegrityIssue);+ const [loading, setLoading] = useState(source !== undefined);+ const [error, setError] = useState<string>();+ const [openedAssetId, setOpenedAssetId] = useState<string>();+ const controller = useMemo(+ () =>+ project === undefined+ ? undefined+ : createBuilderContentBlockSourceController({+ blockInstanceId,+ renderScope,+ projectId: project.id,+ }),+ [blockInstanceId, project, renderScope]+ );+ const repository = useMemo(+ () =>+ project === undefined+ ? undefined+ : createBuilderHttpAssetContentRepository({ projectId: project.id }),+ [project]+ );++ useEffect(() => {+ let active = true;+ if (source === undefined || controller === undefined) {+ setLoading(false);+ setError(undefined);+ return;+ }+ setLoading(true);+ void controller+ .open(source)+ .then((state) => {+ if (active) {+ setError(getStateError(state));+ }+ })+ .catch(() => {+ if (active) {+ setError("Unable to load MDX");+ }+ })+ .finally(() => {+ if (active) {+ setLoading(false);+ }+ });+ return () => {+ active = false;+ };+ }, [+ controller,+ resolvedAsset?.name,+ resolvedAsset?.size,+ resolvedAsset?.updatedAt,+ resolvedAssetId,+ source,+ ]);++ useEffect(+ () => () => {+ controller?.dispose();+ },+ [controller]+ );++ if (+ project === undefined ||+ controller === undefined ||+ repository === undefined+ ) {+ return;+ }++ const requestSource = async (input: {+ source: ContentBlockSource;+ authority?: Parameters<typeof controller.requestSource>[0]["authority"];+ }) => {+ const isSwitch = source !== undefined;+ const sourceChanged =+ source === undefined ||+ (source.type === "asset"+ ? input.source.type !== "asset" ||+ source.assetId !== input.source.assetId+ : input.source.type !== "expression" ||+ source.value !== input.source.value);+ const publishStatus = (status: "loading" | "ready") => {+ if (isSwitch) {+ $publisher.get().publish?.({+ type: "contentBlockSourceStatus",+ payload: {+ projectId: project.id,+ blockInstanceId,+ renderScope,+ status,+ },+ });+ }+ };+ publishStatus("loading");+ try {+ const result = await controller.requestSource(input);+ if (result.status === "applied") {+ setError(+ result.state === undefined ? undefined : getStateError(result.state)+ );+ if (sourceChanged === false) {+ publishStatus("ready");+ }+ } else {+ publishStatus("ready");+ }+ return result;+ } catch (error) {+ publishStatus("ready");+ throw error;+ }+ };++ return (+ <>+ <ContentBlockSourceControl+ source={source}+ resolvedAsset={resolvedAsset}+ disabled={authPermit === "view"}+ loading={loading}+ error={error ?? sourceIntegrityError}+ diagnostics={viewState?.diagnostics}+ onRequestSource={requestSource}+ onDisconnect={async () => {+ const result = await controller.disconnect();+ return result.status === "requires-authority"+ ? {+ status: "blocked",+ message: "Disconnect does not accept a content authority.",+ }+ : result;+ }}+ onOpen={setOpenedAssetId}+ onPreviewMarkdown={async (assetId) => {+ const content = await repository.readContent({ assetId });+ const bytes = await readBoundedBytes(+ content.data,+ contentEngineLimits.hydratedFileBytes+ );+ if (bytes.byteLength !== content.asset.size) {+ throw new Error("Markdown Asset content does not match its size");+ }+ return await previewMarkdownToMdxConversion({+ source: decodeUtf8(bytes),+ });+ }}+ onCreateConvertedMdx={async ({ assetId, preview }) => {+ const markdownAsset = assets.get(assetId);+ if (markdownAsset === undefined) {+ throw new Error("Markdown Asset not found");+ }+ const { basename } = getFileNameParts(formatAssetName(markdownAsset));+ const created = await uploadSingleAsset(+ "file",+ new File([preview.source], `${basename}.mdx`, {+ type: "text/mdx",+ }),+ { folderId: markdownAsset.folderId }+ );+ return created?.id;+ }}+ />+ {openedAssetId !== undefined && (+ <TextFileEditor+ key={openedAssetId}+ assetId={openedAssetId}+ onOpenChange={(open) => {+ if (open === false) {+ setOpenedAssetId(undefined);+ }+ }}+ />+ )}+ </>+ );+};diff --git a/apps/builder/app/builder/features/settings-panel/controls/content-block-source.test.tsx b/apps/builder/app/builder/features/settings-panel/controls/content-block-source.test.tsxnew file mode 100644index 0000000000..1eb3ad4231--- /dev/null+++ b/apps/builder/app/builder/features/settings-panel/controls/content-block-source.test.tsx@@ -0,0 +1,388 @@+/**+ * @vitest-environment jsdom+ */+import { act } from "react-dom/test-utils";+import { createRoot, type Root } from "react-dom/client";+import type { ComponentProps } from "react";+import { afterEach, beforeEach, expect, test, vi } from "vitest";+import { TooltipProvider } from "@webstudio-is/design-system";+import type { Asset } from "@webstudio-is/sdk";+import { $assets } from "~/shared/sync/data-stores";+import { ContentBlockSourceControl } from "./content-block-source";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const asset: Asset = {+ id: "post",+ projectId: "project",+ name: "post.mdx",+ format: "mdx",+ size: 10,+ type: "file",+ meta: {},+ createdAt: "2026-01-01T00:00:00.000Z",+};+const targetAsset: Asset = { ...asset, id: "other", name: "other.mdx" };+const markdownAsset: Asset = {+ ...asset,+ id: "legacy",+ name: "legacy.md",+ format: "md",+};++let container: HTMLDivElement;+let root: Root;+const scrollIntoView = Object.getOwnPropertyDescriptor(+ HTMLElement.prototype,+ "scrollIntoView"+);++beforeEach(() => {+ vi.stubGlobal(+ "ResizeObserver",+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ );+ Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {+ configurable: true,+ value: vi.fn(),+ });+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ $assets.set(+ new Map([asset, targetAsset, markdownAsset].map((item) => [item.id, item]))+ );+});++afterEach(() => {+ act(() => root.unmount());+ document.body.innerHTML = "";+ vi.unstubAllGlobals();+ $assets.set(new Map());+ if (scrollIntoView === undefined) {+ delete (HTMLElement.prototype as { scrollIntoView?: unknown })+ .scrollIntoView;+ } else {+ Object.defineProperty(+ HTMLElement.prototype,+ "scrollIntoView",+ scrollIntoView+ );+ }+});++const findButton = (label: string) => {+ const button = Array.from(+ document.body.querySelectorAll<HTMLButtonElement>("button")+ ).find((candidate) => candidate.textContent?.trim() === label);+ if (button === undefined) {+ throw new Error(`Expected button "${label}"`);+ }+ return button;+};++const renderControl = ({+ onDisconnect = async () => ({ status: "applied" as const }),+ source = { type: "asset" as const, assetId: asset.id },+ loading = false,+ diagnostics,+}: {+ onDisconnect?: ComponentProps<+ typeof ContentBlockSourceControl+ >["onDisconnect"];+ source?:+ | { type: "asset"; assetId: string }+ | { type: "expression"; value: string };+ loading?: boolean;+ diagnostics?: ComponentProps<typeof ContentBlockSourceControl>["diagnostics"];+} = {}) => {+ act(() => {+ root.render(+ <TooltipProvider>+ <ContentBlockSourceControl+ source={source}+ resolvedAsset={asset}+ loading={loading}+ diagnostics={diagnostics}+ onRequestSource={async () => ({ status: "applied" })}+ onDisconnect={onDisconnect}+ onOpen={() => {}}+ onPreviewMarkdown={async () => {+ throw new Error("Not used");+ }}+ onCreateConvertedMdx={async () => undefined}+ />+ </TooltipProvider>+ );+ });+};++test("shows persistent actionable diagnostics with file, location, and render scope", () => {+ const diagnostic = {+ code: "ignored-template-prop" as const,+ severity: "warning" as const,+ blockInstanceId: "block",+ assetId: "post",+ contentRef: "post.mdx",+ renderScope: "collection:item-2",+ templateName: "Hero",+ propName: "tone",+ reason: "design-only" as const,+ sourceRange: {+ start: { line: 7, column: 4 },+ end: { line: 7, column: 12 },+ },+ };+ renderControl({+ diagnostics: [diagnostic, diagnostic],+ });++ expect(+ container.querySelector('[aria-label="MDX diagnostics"]')?.textContent+ ).toContain(+ 'post.mdx: Property "tone" on template "Hero" was ignored because it is design only. Line 7, column 4.'+ );+ expect(container.textContent).toContain("Render scope: collection:item-2");+ expect(+ container.querySelectorAll('[aria-label="MDX diagnostics"] > li')+ ).toHaveLength(1);+ expect(findButton("Open file to repair")).not.toBeNull();+});++test("keeps the resolved filename visible while refreshed content loads", () => {+ renderControl({ loading: true });++ expect(document.body.textContent).toContain("post.mdx");+ expect(findButton("Open").matches(":disabled")).toBe(true);+});++test("requires copying loaded file content before disconnecting", async () => {+ const onDisconnect = vi.fn(async () => ({ status: "applied" as const }));+ renderControl({ onDisconnect });++ act(() => findButton("Disconnect").click());+ expect(document.body.textContent).toContain(+ "The current file content will be copied into the Content Block."+ );+ expect(onDisconnect).not.toHaveBeenCalled();++ await act(async () => {+ findButton("Copy file content and disconnect").click();+ });+ expect(onDisconnect).toHaveBeenCalledOnce();+ expect(document.body.textContent).not.toContain(+ "The current file content will be copied into the Content Block."+ );+});++test("keeps a partial lifecycle result visible without claiming complete success", async () => {+ renderControl({+ onDisconnect: async () => ({+ status: "partial",+ message: "The file was saved, but the Content Block was not connected.",+ }),+ });++ act(() => findButton("Disconnect").click());+ await act(async () => {+ findButton("Copy file content and disconnect").click();+ });++ expect(document.querySelector('[role="alert"]')?.textContent).toBe(+ "The file was saved, but the Content Block was not connected."+ );+ expect(document.body.textContent).toContain("Disconnect content source");+});++test("submits a disconnect only once while it is pending", async () => {+ let resolveDisconnect: (result: { status: "applied" }) => void = () => {};+ const onDisconnect = vi.fn(+ () =>+ new Promise<{ status: "applied" }>((resolve) => {+ resolveDisconnect = resolve;+ })+ );+ renderControl({ onDisconnect });++ act(() => findButton("Disconnect").click());+ const confirm = findButton("Copy file content and disconnect");+ act(() => {+ confirm.click();+ confirm.click();+ });++ expect(onDisconnect).toHaveBeenCalledOnce();+ await act(async () => resolveDisconnect({ status: "applied" }));+});++test("shows the resolved filename while retaining a dynamic binding", () => {+ renderControl({ source: { type: "expression", value: "post.body" } });++ expect(container.textContent).toContain("post.mdx");+ expect(container.querySelector('[data-variant="bound"]')).not.toBeNull();+});++test("creates only a new MDX Asset from the source control", () => {+ renderControl();++ act(() => findButton("Create MDX file").click());++ expect(document.body.textContent).toContain("New MDX file");+ expect(+ document.querySelector<HTMLInputElement>("#asset-text-file-name")?.value+ ).toBe("untitled.mdx");+});++test("asks which body to keep before switching non-empty content", async () => {+ const onRequestSource = vi+ .fn()+ .mockResolvedValueOnce({ status: "requires-authority" })+ .mockResolvedValueOnce({ status: "applied" });+ act(() => {+ root.render(+ <TooltipProvider>+ <ContentBlockSourceControl+ source={{ type: "asset", assetId: asset.id }}+ resolvedAsset={asset}+ onRequestSource={onRequestSource}+ onDisconnect={async () => ({ status: "applied" })}+ onOpen={() => {}}+ onPreviewMarkdown={async () => {+ throw new Error("Not used");+ }}+ onCreateConvertedMdx={async () => undefined}+ />+ </TooltipProvider>+ );+ });++ await act(async () => {+ findButton("Replace or switch").click();+ await new Promise<void>((resolve) =>+ requestAnimationFrame(() => resolve())+ );+ });+ const targetOption = Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="option"]')+ ).find((button) => button.textContent?.includes("other.mdx"));+ const target = targetOption?.querySelector<HTMLElement>(+ "[data-asset-thumbnail] > div"+ );+ if (target === undefined || target === null) {+ throw new Error("Expected compatible MDX Asset");+ }+ await act(async () => {+ target.click();+ await Promise.resolve();+ });++ expect(document.body.textContent).toContain("Switch content source");+ expect(document.body.textContent).not.toContain("Switch MDX file");+ expect(onRequestSource).toHaveBeenNthCalledWith(1, {+ source: { type: "asset", assetId: targetAsset.id },+ authority: undefined,+ });++ await act(async () => findButton("Use file content").click());+ expect(onRequestSource).toHaveBeenNthCalledWith(2, {+ source: { type: "asset", assetId: targetAsset.id },+ authority: "use-file-content",+ });+});++test("previews converted MDX and explains skipped Markdown before creation", async () => {+ const preview = {+ source: "# Converted\n",+ document: { frontmatter: { properties: {} }, children: [] },+ omissions: [+ {+ nodeType: "html",+ reason: "Unsupported HTML",+ sourceRange: {+ start: { line: 2, column: 1, offset: 12 },+ end: { line: 2, column: 8, offset: 19 },+ },+ },+ ],+ };+ const onPreviewMarkdown = vi.fn(async () => preview);+ const onCreateConvertedMdx = vi.fn(async () => "converted");+ const onRequestSource = vi.fn(async () => ({ status: "applied" as const }));+ act(() => {+ root.render(+ <TooltipProvider>+ <ContentBlockSourceControl+ source={{ type: "asset", assetId: asset.id }}+ resolvedAsset={asset}+ onRequestSource={onRequestSource}+ onDisconnect={async () => ({ status: "applied" })}+ onOpen={() => {}}+ onPreviewMarkdown={onPreviewMarkdown}+ onCreateConvertedMdx={onCreateConvertedMdx}+ />+ </TooltipProvider>+ );+ });++ await act(async () => {+ findButton("Convert Markdown").click();+ await new Promise<void>((resolve) =>+ requestAnimationFrame(() => resolve())+ );+ });+ const markdownOption = Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="option"]')+ ).find((option) => option.textContent?.includes("legacy.md"));+ expect(markdownOption).toBeDefined();+ expect(+ Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="option"]')+ ).some((option) => option.textContent?.includes("other.mdx"))+ ).toBe(false);+ const markdownPreview = markdownOption?.querySelector<HTMLElement>(+ "[data-asset-thumbnail] > div"+ );+ if (markdownPreview === undefined || markdownPreview === null) {+ throw new Error("Expected Markdown Asset preview");+ }+ await act(async () => {+ markdownPreview.click();+ await Promise.resolve();+ });++ expect(document.body.textContent).toContain(+ "1 unsupported part will be skipped"+ );+ expect(document.body.textContent).toContain("html: Unsupported HTML");+ expect(document.querySelector<HTMLTextAreaElement>("textarea")?.value).toBe(+ preview.source+ );++ const conversionDialog = Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="dialog"]')+ ).find((dialog) => dialog.textContent?.includes("Convert Markdown to MDX"));+ const createConverted = Array.from(+ conversionDialog?.querySelectorAll<HTMLButtonElement>("button") ?? []+ ).find((button) => button.textContent?.trim() === "Create MDX file");+ if (createConverted === undefined) {+ throw new Error("Expected conversion action");+ }+ await act(async () => {+ createConverted.click();+ await Promise.resolve();+ });+ expect(onCreateConvertedMdx).toHaveBeenCalledWith({+ assetId: "legacy",+ preview,+ });+ expect(onRequestSource).toHaveBeenCalledWith({+ source: { type: "asset", assetId: "converted" },+ authority: undefined,+ });+});diff --git a/apps/builder/app/builder/features/settings-panel/controls/content-block-source.tsx b/apps/builder/app/builder/features/settings-panel/controls/content-block-source.tsxnew file mode 100644index 0000000000..224e0fd890--- /dev/null+++ b/apps/builder/app/builder/features/settings-panel/controls/content-block-source.tsx@@ -0,0 +1,591 @@+import { useId, useRef, useState } from "react";+import {+ Button,+ Dialog,+ DialogActions,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogTitle,+ Flex,+ FloatingPanel,+ Grid,+ Label,+ Text,+ TextArea,+ theme,+} from "@webstudio-is/design-system";+import type { MarkdownToMdxConversionPreview } from "@webstudio-is/content-engine/mdx-conversion";+import type { ContentBlockSourceAuthority } from "@webstudio-is/project-build/runtime";+import {+ formatAssetName,+ type Asset,+ type ContentBlockDiagnostic,+ type ContentBlockSource,+} from "@webstudio-is/sdk";+import { AssetManager } from "~/builder/shared/asset-manager";+import { BindableExpressionControl } from "~/builder/shared/bindable-expression";+import { CreateTextFileDialog } from "~/builder/features/text-file-editor/create-text-file-dialog";+import { useBindableControl } from "./use-bindable-control";+import {+ deduplicateContentBlockDiagnostics,+ formatContentBlockDiagnostic,+} from "~/shared/content-block-content";++export type ContentBlockSourceMutationResult =+ | Readonly<{ status: "applied" }>+ | Readonly<{ status: "partial"; message: string }>+ | Readonly<{ status: "blocked"; message: string }>;++export type ContentBlockSourceActionResult =+ | ContentBlockSourceMutationResult+ | Readonly<{ status: "requires-authority" }>;++type PendingSource = Readonly<{+ source: ContentBlockSource;+ action: "connect" | "switch";+}>;++type PendingConversion = Readonly<{+ assetId: string;+ preview: MarkdownToMdxConversionPreview;+}>;++const SourceAuthorityDialog = ({+ pending,+ disabled,+ error,+ onClose,+ onSelect,+}: {+ pending: PendingSource;+ disabled: boolean;+ error?: string;+ onClose: () => void;+ onSelect: (authority: ContentBlockSourceAuthority) => void;+}) => (+ <Dialog open onOpenChange={(open) => open === false && onClose()}>+ <DialogContent>+ <DialogTitle>+ {pending.action === "connect"+ ? "Connect content source"+ : "Switch content source"}+ </DialogTitle>+ <Grid gap="3" css={{ padding: theme.panel.padding }}>+ <DialogDescription>+ Both the Content Block and file contain content. Choose which body to+ keep. File frontmatter is always preserved.+ </DialogDescription>+ {error !== undefined && (+ <Text role="alert" color="destructive" variant="tiny">+ {error}+ </Text>+ )}+ </Grid>+ <DialogActions>+ <Button+ autoFocus+ disabled={disabled}+ onClick={() => onSelect("use-file-content")}+ >+ Use file content+ </Button>+ <Button+ color="neutral"+ disabled={disabled}+ onClick={() => onSelect("replace-file-body-with-block-content")}+ >+ Replace file body with block content+ </Button>+ <DialogClose>+ <Button color="ghost" disabled={disabled}>+ Cancel+ </Button>+ </DialogClose>+ </DialogActions>+ </DialogContent>+ </Dialog>+);++const DisconnectDialog = ({+ disabled,+ error,+ onClose,+ onConfirm,+}: {+ disabled: boolean;+ error?: string;+ onClose: () => void;+ onConfirm: () => void;+}) => (+ <Dialog open onOpenChange={(open) => open === false && onClose()}>+ <DialogContent>+ <DialogTitle>Disconnect content source</DialogTitle>+ <Grid gap="3" css={{ padding: theme.panel.padding }}>+ <DialogDescription>+ The current file content will be copied into the Content Block. The+ file will not be changed.+ </DialogDescription>+ {error !== undefined && (+ <Text role="alert" color="destructive" variant="tiny">+ {error}+ </Text>+ )}+ </Grid>+ <DialogActions>+ <Button autoFocus disabled={disabled} onClick={onConfirm}>+ Copy file content and disconnect+ </Button>+ <DialogClose>+ <Button color="ghost" disabled={disabled}>+ Cancel+ </Button>+ </DialogClose>+ </DialogActions>+ </DialogContent>+ </Dialog>+);++const SourcePicker = ({+ title,+ accept,+ disabled,+ triggerLabel,+ onSelect,+}: {+ title: string;+ accept: string;+ disabled: boolean;+ triggerLabel: string;+ onSelect: (assetId: string) => void;+}) => {+ const [open, setOpen] = useState(false);+ return (+ <FloatingPanel+ title={title}+ open={open}+ onOpenChange={setOpen}+ content={+ <AssetManager+ accept={accept}+ onChange={(assetId) => {+ setOpen(false);+ onSelect(assetId);+ }}+ />+ }+ >+ <Button color="neutral" disabled={disabled}>+ {triggerLabel}+ </Button>+ </FloatingPanel>+ );+};++/**+ * Presentation and interaction boundary for Content Block source lifecycle.+ * The caller owns loading, exact-Asset authorization, lifecycle preparation,+ * and persistence. This component never updates the src prop directly.+ */+export const ContentBlockSourceControl = ({+ source,+ resolvedAsset,+ disabled = false,+ loading = false,+ error,+ diagnostics = [],+ onRequestSource,+ onDisconnect,+ onOpen,+ onPreviewMarkdown,+ onCreateConvertedMdx,+}: {+ source?: ContentBlockSource;+ resolvedAsset?: Asset;+ disabled?: boolean;+ loading?: boolean;+ error?: string;+ diagnostics?: readonly ContentBlockDiagnostic[];+ onRequestSource: (input: {+ source: ContentBlockSource;+ authority?: ContentBlockSourceAuthority;+ }) => Promise<ContentBlockSourceActionResult>;+ onDisconnect: () => Promise<ContentBlockSourceMutationResult>;+ onOpen: (assetId: string) => void;+ onPreviewMarkdown: (+ assetId: string+ ) => Promise<MarkdownToMdxConversionPreview>;+ onCreateConvertedMdx: (+ input: PendingConversion+ ) => Promise<string | undefined>;+}) => {+ const conversionPreviewId = useId();+ const [pendingSource, setPendingSource] = useState<PendingSource>();+ const [disconnecting, setDisconnecting] = useState(false);+ const [busy, setBusy] = useState(false);+ const busyRef = useRef(false);+ const [localError, setLocalError] = useState<string>();+ const [conversion, setConversion] = useState<PendingConversion>();+ const [creatingMdx, setCreatingMdx] = useState(false);+ const isDisabled = disabled || loading || busy;+ const connected = source !== undefined;+ const binding = useBindableControl({+ boundExpression: source?.type === "expression" ? source.value : undefined,+ fallbackExpression: JSON.stringify(resolvedAsset?.id ?? ""),+ });+ const uniqueDiagnostics = deduplicateContentBlockDiagnostics(diagnostics);++ const beginOperation = () => {+ if (disabled || loading || busyRef.current) {+ return false;+ }+ busyRef.current = true;+ setBusy(true);+ setLocalError(undefined);+ return true;+ };++ const finishOperation = () => {+ busyRef.current = false;+ setBusy(false);+ };++ const requestSource = async (+ requestedSource: ContentBlockSource,+ authority?: ContentBlockSourceAuthority+ ) => {+ if (beginOperation() === false) {+ return;+ }+ try {+ const result = await onRequestSource({+ source: requestedSource,+ authority,+ });+ if (result.status === "requires-authority") {+ setPendingSource({+ source: requestedSource,+ action: connected ? "switch" : "connect",+ });+ return;+ }+ if (result.status === "blocked" || result.status === "partial") {+ setLocalError(result.message);+ return;+ }+ setPendingSource(undefined);+ } catch (error) {+ setLocalError(+ error instanceof Error ? error.message : "Unable to change source"+ );+ } finally {+ finishOperation();+ }+ };++ return (+ <fieldset disabled={isDisabled} style={{ display: "contents" }}>+ <Text as="legend" variant="labels">+ Content source+ </Text>+ <Grid gap="2">+ <BindableExpressionControl+ {...binding}+ value={resolvedAsset?.id}+ validate={(value) =>+ typeof value === "string" && value !== ""+ ? undefined+ : "Content source must resolve to an Asset ID"+ }+ onChangeValue={(value) => {+ if (typeof value === "string" && value !== "") {+ void requestSource({ type: "asset", assetId: value });+ }+ }}+ onChangeExpression={(value) => {+ void requestSource({ type: "expression", value });+ }}+ onRemove={(value) => {+ if (typeof value === "string" && value !== "") {+ void requestSource({ type: "asset", assetId: value });+ }+ }}+ renderControl={() => (+ <Flex gap="2" align="center" wrap="wrap">+ <Text>+ {resolvedAsset+ ? formatAssetName(resolvedAsset)+ : loading+ ? "Loading content source…"+ : source?.type === "expression"+ ? "Dynamic content source"+ : source?.type === "asset"+ ? "Missing MDX Asset"+ : "No content source"}+ </Text>+ {resolvedAsset !== undefined && (+ <Button+ color="ghost"+ disabled={isDisabled}+ onClick={() => onOpen(resolvedAsset.id)}+ >+ Open+ </Button>+ )}+ </Flex>+ )}+ />++ <Flex gap="2" wrap="wrap">+ <SourcePicker+ title={connected ? "Switch MDX file" : "Choose MDX file"}+ accept=".mdx"+ disabled={isDisabled}+ triggerLabel={connected ? "Replace or switch" : "Choose file"}+ onSelect={(assetId) =>+ void requestSource({ type: "asset", assetId })+ }+ />+ <Button+ color="neutral"+ disabled={isDisabled}+ onClick={() => setCreatingMdx(true)}+ >+ Create MDX file+ </Button>+ <SourcePicker+ title="Convert Markdown file"+ accept=".md"+ disabled={isDisabled}+ triggerLabel="Convert Markdown"+ onSelect={(assetId) => {+ if (beginOperation() === false) {+ return;+ }+ void onPreviewMarkdown(assetId)+ .then((preview) => setConversion({ assetId, preview }))+ .catch((error) =>+ setLocalError(+ error instanceof Error+ ? error.message+ : "Unable to preview conversion"+ )+ )+ .finally(finishOperation);+ }}+ />+ {connected && (+ <Button+ color="ghost"+ disabled={isDisabled}+ onClick={() => setDisconnecting(true)}+ >+ Disconnect+ </Button>+ )}+ </Flex>++ {(localError ?? error) !== undefined &&+ pendingSource === undefined &&+ disconnecting === false &&+ conversion === undefined && (+ <Text role="alert" color="destructive" variant="tiny">+ {localError ?? error}+ </Text>+ )}++ {busy && (+ <Text role="status" variant="tiny">+ Updating content source…+ </Text>+ )}++ {uniqueDiagnostics.length > 0 && (+ <Grid as="ul" gap="2" aria-label="MDX diagnostics">+ {uniqueDiagnostics.map((diagnostic) => (+ <Flex+ as="li"+ key={JSON.stringify(diagnostic)}+ direction="column"+ gap="1"+ >+ <Text+ color={+ diagnostic.severity === "error" ? "destructive" : "subtle"+ }+ variant="tiny"+ >+ {diagnostic.contentRef ?? resolvedAsset?.name ?? "MDX file"}+ {": "}+ {formatContentBlockDiagnostic(diagnostic)}+ </Text>+ <Text color="subtle" variant="tiny">+ Render scope: {diagnostic.renderScope ?? "current block"}+ </Text>+ {resolvedAsset !== undefined && (+ <Button+ color="ghost"+ disabled={isDisabled}+ onClick={() => onOpen(resolvedAsset.id)}+ >+ Open file to repair+ </Button>+ )}+ </Flex>+ ))}+ </Grid>+ )}++ {pendingSource !== undefined && (+ <SourceAuthorityDialog+ pending={pendingSource}+ disabled={isDisabled}+ error={localError ?? error}+ onClose={() => setPendingSource(undefined)}+ onSelect={(authority) =>+ void requestSource(pendingSource.source, authority)+ }+ />+ )}++ {disconnecting && (+ <DisconnectDialog+ disabled={isDisabled}+ error={localError ?? error}+ onClose={() => setDisconnecting(false)}+ onConfirm={() => {+ if (beginOperation() === false) {+ return;+ }+ void onDisconnect()+ .then((result) => {+ if (+ result.status === "blocked" ||+ result.status === "partial"+ ) {+ setLocalError(result.message);+ return;+ }+ if (result.status === "applied") {+ setDisconnecting(false);+ }+ })+ .catch((error) =>+ setLocalError(+ error instanceof Error+ ? error.message+ : "Unable to disconnect source"+ )+ )+ .finally(finishOperation);+ }}+ />+ )}++ {conversion !== undefined && (+ <Dialog+ open+ onOpenChange={(open) => open === false && setConversion(undefined)}+ >+ <DialogContent>+ <DialogTitle>Convert Markdown to MDX</DialogTitle>+ <Grid gap="3" css={{ padding: theme.panel.padding }}>+ <DialogDescription>+ {conversion.preview.omissions.length === 0+ ? "All content can be converted. The original Markdown file will not be changed."+ : `${conversion.preview.omissions.length} unsupported ${+ conversion.preview.omissions.length === 1+ ? "part"+ : "parts"+ } will be skipped. The original Markdown file will not be changed.`}+ </DialogDescription>+ {conversion.preview.omissions.length > 0 && (+ <ul>+ {conversion.preview.omissions+ .slice(0, 10)+ .map((omission) => (+ <li+ key={`${omission.nodeType}:${omission.sourceRange.start.line}:${omission.sourceRange.start.column}`}+ >+ <Text variant="tiny">+ {omission.nodeType}: {omission.reason}+ </Text>+ </li>+ ))}+ {conversion.preview.omissions.length > 10 && (+ <li>+ <Text variant="tiny">+ {conversion.preview.omissions.length - 10} more+ skipped parts+ </Text>+ </li>+ )}+ </ul>+ )}+ <Grid gap="1">+ <Label htmlFor={conversionPreviewId}>Converted MDX</Label>+ <TextArea+ id={conversionPreviewId}+ readOnly+ rows={10}+ value={conversion.preview.source}+ />+ </Grid>+ {(localError ?? error) !== undefined && (+ <Text role="alert" color="destructive" variant="tiny">+ {localError ?? error}+ </Text>+ )}+ </Grid>+ <DialogActions>+ <Button+ autoFocus+ disabled={isDisabled}+ onClick={() => {+ if (beginOperation() === false) {+ return;+ }+ void onCreateConvertedMdx(conversion)+ .then(async (assetId) => {+ if (assetId !== undefined) {+ setConversion(undefined);+ finishOperation();+ await requestSource({ type: "asset", assetId });+ }+ })+ .catch((error) =>+ setLocalError(+ error instanceof Error+ ? error.message+ : "Unable to create converted MDX file"+ )+ )+ .finally(finishOperation);+ }}+ >+ Create MDX file+ </Button>+ <DialogClose>+ <Button color="ghost" disabled={isDisabled}>+ Cancel+ </Button>+ </DialogClose>+ </DialogActions>+ </DialogContent>+ </Dialog>+ )}+ <CreateTextFileDialog+ open={creatingMdx}+ defaultName="untitled.mdx"+ allowedExtensions={["mdx"]}+ title="New MDX file"+ disabled={isDisabled}+ onOpenChange={setCreatingMdx}+ onCreated={(assetId) =>+ void requestSource({ type: "asset", assetId })+ }+ />+ </Grid>+ </fieldset>+ );+};diff --git a/apps/builder/app/builder/features/settings-panel/props-section/props-section.test.ts b/apps/builder/app/builder/features/settings-panel/props-section/props-section.test.tsindex bc1e011414..b2afc52cc4 100644--- a/apps/builder/app/builder/features/settings-panel/props-section/props-section.test.ts+++ b/apps/builder/app/builder/features/settings-panel/props-section/props-section.test.ts@@ -1,5 +1,5 @@import { describe, expect, test } from "vitest";-import { rootComponent } from "@webstudio-is/sdk";+import { blockComponent, rootComponent } from "@webstudio-is/sdk";import { __testing__ } from "./props-section";const {@@ -70,6 +70,17 @@ describe("shouldRenderPropsSectionContainer", () => {).toBe(true);});+ test("renders Content Block source controls without component prop metadata", () => {+ expect(+ shouldRenderPropsSectionContainer({+ component: blockComponent,+ propsMetasSize: 0,+ hasVisibleProps: false,+ isContentMode: false,+ })+ ).toBe(true);+ });+test("hides root and empty metadata without content-visible props", () => {expect(shouldRenderPropsSectionContainer({diff --git a/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsx b/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsxindex f70c76c452..857e9b9cfd 100644--- a/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsx+++ b/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsx@@ -6,6 +6,8 @@ import { matchSorter } from "match-sorter";import {type Instance,type Props,+ blockComponent,+ contentBlockSourceProp,descendantComponent,rootComponent,} from "@webstudio-is/sdk";@@ -48,6 +50,7 @@ import {$selectedInstancePropsMetas,} from "../shared";import { executeRuntimeMutation } from "~/shared/instance-utils/data";+import { ContentBlockSourceSection } from "../controls/content-block-source-section";type Item = {name: string;@@ -106,6 +109,9 @@ const shouldRenderPropsSectionContainer = ({if (component === rootComponent) {return false;}+ if (component === blockComponent) {+ return true;+ }return propsMetasSize > 0 || (isContentMode && hasVisibleProps);};@@ -274,8 +280,17 @@ export const PropsSection = (props: PropsSectionProps) => {const matchMediaValue = matchMediaBreakpoints(matchingBreakpoints);- const hasProperties =- logic.addedProps.length > 0 || logic.initialProps.length > 0;+ const addedProps = logic.addedProps.filter(+ (item) =>+ props.component !== blockComponent ||+ item.propName !== contentBlockSourceProp+ );+ const initialProps = logic.initialProps.filter(+ (item) =>+ props.component !== blockComponent ||+ item.propName !== contentBlockSourceProp+ );+ const hasProperties = addedProps.length > 0 || initialProps.length > 0;const hasItems = hasProperties || (isDesignMode && addingProp);const animationAction = logic.initialProps.find(@@ -368,8 +383,8 @@ export const PropsSection = (props: PropsSectionProps) => {}}/>)}- {logic.addedProps.map((item) => renderProperty(props, item))}- {logic.initialProps.map((item) => renderProperty(props, item))}+ {addedProps.map((item) => renderProperty(props, item))}+ {initialProps.map((item) => renderProperty(props, item))}</Flex></CollapsibleSectionWithAddButton>)}@@ -436,6 +451,17 @@ export const PropsSectionContainer = ({style={{ display: "contents" }}disabled={instance.component === descendantComponent}>+ {instance.component === blockComponent && (+ <>+ <Box css={{ padding: theme.panel.padding }}>+ <ContentBlockSourceSection+ blockInstanceId={instance.id}+ renderScope={selectedInstanceKey}+ />+ </Box>+ <Separator />+ </>+ )}<PropsSectionpropsLogic={logic}propValues={propValues ?? new Map()}diff --git a/apps/builder/app/builder/features/settings-panel/settings-section.tsx b/apps/builder/app/builder/features/settings-panel/settings-section.tsxindex 6cc8670510..7deaf4c6ce 100644--- a/apps/builder/app/builder/features/settings-panel/settings-section.tsx+++ b/apps/builder/app/builder/features/settings-panel/settings-section.tsx@@ -1,27 +1,63 @@-import { useId } from "react";+import { useEffect, useId, useRef, useState } from "react";import { useStore } from "@nanostores/react";-import { InputField } from "@webstudio-is/design-system";+import { InputField, Text, Tooltip } from "@webstudio-is/design-system";import { useDraftValue } from "~/builder/shared/use-draft-value";import { HorizontalLayout, Label, Row } from "./shared";import { $selectedInstance } from "~/shared/nano-states";import { getInstanceLabel } from "~/builder/shared/instance-label";-import { executeRuntimeMutation } from "~/shared/instance-utils/data";--const saveLabel = (label: string, instanceId: string) => {- executeRuntimeMutation({- id: "instances.setLabel",- input: { instanceId, label },- });-};+import {+ executeRuntimeMutation,+ getDuplicateTemplateNameMessage,+ $pendingTemplateNameConfirmation,+} from "~/shared/instance-utils/data";export const SettingsSection = () => {const selectedInstance = useStore($selectedInstance);+ const pendingConfirmation = useStore($pendingTemplateNameConfirmation);const id = useId();+ const errorId = useId();+ const inputRef = useRef<HTMLInputElement>(null);+ const [error, setError] = useState<string>();+ const hadPendingConfirmation = useRef(false);+ useEffect(() => setError(undefined), [selectedInstance?.id]);const localValue = useDraftValue(selectedInstance?.label ?? "",- (value) => selectedInstance && saveLabel(value, selectedInstance.id),+ (value) => {+ if (selectedInstance === undefined) {+ return;+ }+ try {+ executeRuntimeMutation({+ id: "instances.setLabel",+ input: { instanceId: selectedInstance.id, label: value },+ });+ setError(undefined);+ } catch (caught) {+ const message = getDuplicateTemplateNameMessage(caught);+ if (message === undefined) {+ throw caught;+ }+ setError(message);+ requestAnimationFrame(() => inputRef.current?.focus());+ return false;+ }+ },{ autoSave: false });+ const resetLocalValue = localValue.reset;+ useEffect(() => {+ const isPendingForInstance =+ pendingConfirmation?.operation.id === "instances.setLabel" &&+ pendingConfirmation.operation.input.instanceId === selectedInstance?.id;+ if (isPendingForInstance) {+ hadPendingConfirmation.current = true;+ return;+ }+ if (hadPendingConfirmation.current) {+ hadPendingConfirmation.current = false;+ resetLocalValue();+ }+ }, [pendingConfirmation, resetLocalValue, selectedInstance?.id]);if (selectedInstance === undefined) {return;@@ -32,15 +68,27 @@ export const SettingsSection = () => {return (<Row><HorizontalLayout label={<Label htmlFor={id}>Name</Label>}>- <InputField- id={id}- /* Key is required, otherwise when label is undefined, previous value stayed */- key={selectedInstance.id}- placeholder={placeholder}- value={localValue.value}- onChange={(event) => localValue.set(event.target.value)}- onBlur={localValue.save}- />+ <Tooltip+ open={error !== undefined}+ content={<Text id={errorId}>{error}</Text>}+ >+ <InputField+ id={id}+ /* Key is required, otherwise when label is undefined, previous value stayed */+ key={selectedInstance.id}+ inputRef={inputRef}+ placeholder={placeholder}+ value={localValue.value}+ color={error === undefined ? undefined : "error"}+ aria-invalid={error !== undefined}+ aria-errormessage={error === undefined ? undefined : errorId}+ onChange={(event) => {+ setError(undefined);+ localValue.set(event.target.value);+ }}+ onBlur={localValue.save}+ />+ </Tooltip></HorizontalLayout></Row>);diff --git a/apps/builder/app/builder/features/template-name-confirmation-dialog.test.tsx b/apps/builder/app/builder/features/template-name-confirmation-dialog.test.tsxnew file mode 100644index 0000000000..c8393251a1--- /dev/null+++ b/apps/builder/app/builder/features/template-name-confirmation-dialog.test.tsx@@ -0,0 +1,81 @@+/**+ * @vitest-environment jsdom+ */+import { act } from "react-dom/test-utils";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, test, vi } from "vitest";+import { $pendingTemplateNameConfirmation } from "~/shared/instance-utils/data";+import { TemplateNameConfirmationDialog } from "./template-name-confirmation-dialog";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ vi.stubGlobal(+ "ResizeObserver",+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ );+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ document.body.innerHTML = "";+ $pendingTemplateNameConfirmation.set(undefined);+ vi.unstubAllGlobals();+});++const showDialog = (action: "rename" | "delete") => {+ act(() => {+ $pendingTemplateNameConfirmation.set({+ operation:+ action === "rename"+ ? {+ id: "instances.setLabel",+ input: { instanceId: "card", label: "Hero Card" },+ }+ : {+ id: "instances.delete",+ input: { instanceIds: ["card"] },+ },+ confirmation: {+ action,+ templates: [{ instanceId: "card", oldName: "Card" }],+ },+ });+ root.render(<TemplateNameConfirmationDialog />);+ });+};++test.each([+ { action: "rename" as const, title: "Rename template", confirm: "Rename" },+ { action: "delete" as const, title: "Delete template", confirm: "Delete" },+])("shows exact $action actions and aborts accessibly", (expected) => {+ showDialog(expected.action);+ const dialog = document.body.querySelector('[role="dialog"]');+ expect(dialog?.getAttribute("aria-labelledby")).toBeTruthy();+ expect(dialog?.textContent).toContain(expected.title);+ const buttons = Array.from(+ dialog?.querySelectorAll("button") ?? [],+ (button) => button.textContent+ ).filter(Boolean);+ expect(buttons).toEqual(["Abort", expected.confirm]);++ act(() => {+ const abort = Array.from(dialog?.querySelectorAll("button") ?? []).find(+ (button) => button.textContent === "Abort"+ );+ abort?.click();+ });+ expect($pendingTemplateNameConfirmation.get()).toBeUndefined();+});diff --git a/apps/builder/app/builder/features/template-name-confirmation-dialog.tsx b/apps/builder/app/builder/features/template-name-confirmation-dialog.tsxnew file mode 100644index 0000000000..6843183711--- /dev/null+++ b/apps/builder/app/builder/features/template-name-confirmation-dialog.tsx@@ -0,0 +1,59 @@+import { useStore } from "@nanostores/react";+import {+ Button,+ Dialog,+ DialogActions,+ DialogContent,+ DialogDescription,+ DialogTitle,+ Text,+ theme,+} from "@webstudio-is/design-system";+import {+ $pendingTemplateNameConfirmation,+ abortPendingTemplateNameConfirmation,+ confirmPendingTemplateNameChange,+} from "~/shared/instance-utils/data";++export const TemplateNameConfirmationDialog = () => {+ const pending = useStore($pendingTemplateNameConfirmation);+ const action = pending?.confirmation.action;+ return (+ <Dialog+ open={pending !== undefined}+ onOpenChange={(open) => {+ if (open === false) {+ abortPendingTemplateNameConfirmation();+ }+ }}+ >+ <DialogContent>+ <DialogTitle suffix={false}>+ {action === "delete" ? "Delete template" : "Rename template"}+ </DialogTitle>+ <DialogDescription asChild>+ <Text css={{ padding: theme.spacing[5] }}>+ {action === "delete"+ ? "Deleting this template may disconnect references in connected MDX files. The files will not be changed."+ : "Renaming this template may disconnect references in connected MDX files. The files will not be changed."}+ </Text>+ </DialogDescription>+ <DialogActions>+ <Button+ autoFocus+ color="neutral"+ onClick={abortPendingTemplateNameConfirmation}+ >+ Abort+ </Button>+ <Button+ color={action === "delete" ? "destructive" : "primary"}+ onClick={confirmPendingTemplateNameChange}+ >+ {action === "delete" ? "Delete" : "Rename"}+ </Button>+ </DialogActions>+ </DialogContent>+ </Dialog>+ );+};diff --git a/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.test.ts b/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.test.tsindex 3973de9fda..886a2b64c5 100644--- a/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.test.ts+++ b/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.test.ts@@ -18,6 +18,9 @@ test("accepts supported text names and rejects invalid or duplicate names", () =expect(getTextFileNameError({ name: "data.json", assets: [existing] })).toBeUndefined();+ expect(+ getTextFileNameError({ name: "component.mdx", assets: [] })+ ).toBeUndefined();expect(getTextFileNameError({ name: "image.png", assets: [] })).toBe("Use a supported editable text extension.");@@ -43,3 +46,34 @@ test("compares global complete display names after an asset is renamed", () => {})).toBe("A file with this name already exists.");});++test("can restrict creation to the requested text format", () => {+ expect(+ getTextFileNameError({+ name: "post.mdx",+ assets: [],+ allowedExtensions: ["mdx"],+ })+ ).toBeUndefined();+ expect(+ getTextFileNameError({+ name: "post.md",+ assets: [],+ allowedExtensions: ["mdx"],+ })+ ).toBe("Use a supported editable text extension.");+ expect(+ getTextFileNameError({+ name: "post.MDX",+ assets: [],+ allowedExtensions: ["MDX"],+ })+ ).toBeUndefined();+ expect(+ getTextFileNameError({+ name: "post.mdx.txt",+ assets: [],+ allowedExtensions: ["mdx"],+ })+ ).toBe("Use a supported editable text extension.");+});diff --git a/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.tsx b/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.tsxindex a91868ca6f..61839cd890 100644--- a/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.tsx+++ b/apps/builder/app/builder/features/text-file-editor/create-text-file-dialog.tsx@@ -25,16 +25,22 @@ import { uploadSingleAsset } from "~/builder/shared/assets/upload-assets";export const getTextFileNameError = ({name,assets,+ allowedExtensions,}: {name: string;assets: Iterable<Asset>;+ allowedExtensions?: readonly string[];}) => {if (isValidFilename(name) === false) {return "Enter a valid file name.";}+ const extension = getFileExtension(name)?.toLowerCase() ?? "";if (- isTextFileAsset({ format: getFileExtension(name)?.toLowerCase() ?? "" }) ===- false+ isTextFileAsset({ format: extension }) === false ||+ (allowedExtensions !== undefined &&+ allowedExtensions.some(+ (allowedExtension) => allowedExtension.toLowerCase() === extension+ ) === false)) {return "Use a supported editable text extension.";}@@ -71,34 +77,43 @@ const stopEscapePropagation = (event: KeyboardEvent) => {export const CreateTextFileDialog = ({open,folderId,+ defaultName = "untitled.md",+ allowedExtensions,+ title = "New text file",+ disabled = false,onOpenChange,onCreated,}: {open: boolean;folderId?: string;+ defaultName?: string;+ allowedExtensions?: readonly string[];+ title?: string;+ disabled?: boolean;onOpenChange: (open: boolean) => void;onCreated: (assetId: string) => void;}) => {- const [name, setName] = useState("untitled.md");+ const [name, setName] = useState(defaultName);const [error, setError] = useState<string>();const [creating, setCreating] = useState(false);useLayoutEffect(() => {if (open) {- setName("untitled.md");+ setName(defaultName);setError(undefined);setCreating(false);}- }, [open]);+ }, [defaultName, open]);const normalizedName = name.trim();const submit = async () => {- if (creating) {+ if (creating || disabled) {return;}const validationError = getTextFileNameError({name: normalizedName,assets: $assets.get().values(),+ allowedExtensions,});setError(validationError);if (validationError !== undefined) {@@ -131,14 +146,14 @@ export const CreateTextFileDialog = ({aria-describedby={undefined}onKeyDown={stopEscapePropagation}>- <DialogTitle>New text file</DialogTitle>+ <DialogTitle>{title}</DialogTitle><Grid gap={3} css={{ padding: theme.panel.padding }}><Grid gap={1}><Label htmlFor="asset-text-file-name">File name</Label><InputFieldid="asset-text-file-name"autoFocus- disabled={creating}+ disabled={creating || disabled}value={name}color={error === undefined ? undefined : "error"}onChange={(event) => {@@ -158,7 +173,10 @@ export const CreateTextFileDialog = ({)}</Grid><Flex justify="end">- <Button disabled={creating} onClick={() => void submit()}>+ <Button+ disabled={creating || disabled}+ onClick={() => void submit()}+ >{creating ? "Creating…" : "Create file"}</Button></Flex>diff --git a/apps/builder/app/builder/features/text-file-editor/text-file-editor.tsx b/apps/builder/app/builder/features/text-file-editor/text-file-editor.tsxindex 6ca711a08a..38b858e378 100644--- a/apps/builder/app/builder/features/text-file-editor/text-file-editor.tsx+++ b/apps/builder/app/builder/features/text-file-editor/text-file-editor.tsx@@ -61,7 +61,8 @@ import {} from "~/builder/features/settings-panel/controls/url";import {getTextFileEditorExtensions,- isMarkdownAsset,+ isMarkdownPreviewAsset,+ isMarkdownSyntaxAsset,} from "./text-file-utils";import { MarkdownSplitView } from "./markdown-preview";@@ -355,11 +356,13 @@ const MarkdownLinkPicker = ({const MarkdownToolbar = ({editorApiRef,disabled,+ showPreview,previewOpen,onPreviewOpenChange,}: {editorApiRef: RefObject<EditorApi | undefined>;disabled: boolean;+ showPreview: boolean;previewOpen: boolean;onPreviewOpenChange: (open: boolean) => void;}) => (@@ -404,18 +407,20 @@ const MarkdownToolbar = ({<MarkdownLinkPicker editorApiRef={editorApiRef} disabled={disabled} /><MarkdownImagePicker editorApiRef={editorApiRef} disabled={disabled} /></Flex>- <Tooltip content={previewOpen ? "Hide preview" : "Show preview"}>- <IconButton- type="button"- aria-label={previewOpen ? "Hide preview" : "Show preview"}- aria-pressed={previewOpen}- variant={previewOpen ? "local" : "default"}- onMouseDown={(event) => event.preventDefault()}- onClick={() => onPreviewOpenChange(previewOpen === false)}- >- <MarkdownEmbedIcon />- </IconButton>- </Tooltip>+ {showPreview && (+ <Tooltip content={previewOpen ? "Hide preview" : "Show preview"}>+ <IconButton+ type="button"+ aria-label={previewOpen ? "Hide preview" : "Show preview"}+ aria-pressed={previewOpen}+ variant={previewOpen ? "local" : "default"}+ onMouseDown={(event) => event.preventDefault()}+ onClick={() => onPreviewOpenChange(previewOpen === false)}+ >+ <MarkdownEmbedIcon />+ </IconButton>+ </Tooltip>+ )}</Flex>);@@ -512,7 +517,9 @@ export const TextFileEditor = ({};const title = asset === undefined ? "Text file" : formatAssetName(asset);- const isMarkdown = asset !== undefined && isMarkdownAsset(asset);+ const isMarkdown = asset !== undefined && isMarkdownSyntaxAsset(asset);+ const hasMarkdownPreview =+ asset !== undefined && isMarkdownPreviewAsset(asset);let editor: ReactNode;if (state.status === "loaded" && asset !== undefined) {editor = (@@ -572,11 +579,12 @@ export const TextFileEditor = ({<MarkdownToolbareditorApiRef={editorApiRef}disabled={canEdit === false}+ showPreview={hasMarkdownPreview}previewOpen={previewOpen}onPreviewOpenChange={setPreviewOpen}/>)}- {isMarkdown ? (+ {hasMarkdownPreview ? (<MarkdownSplitViewopen={previewOpen}source={state.content}diff --git a/apps/builder/app/builder/features/text-file-editor/text-file-utils.test.ts b/apps/builder/app/builder/features/text-file-editor/text-file-utils.test.tsindex b82b78268b..b8cd005fda 100644--- a/apps/builder/app/builder/features/text-file-editor/text-file-utils.test.ts+++ b/apps/builder/app/builder/features/text-file-editor/text-file-utils.test.ts@@ -6,7 +6,8 @@ import {} from "@webstudio-is/sdk";import {getTextFileEditorExtensions,- isMarkdownAsset,+ isMarkdownPreviewAsset,+ isMarkdownSyntaxAsset,} from "./text-file-utils";describe("text file assets", () => {@@ -19,7 +20,7 @@ describe("text file assets", () => {expect(isTextFileAsset({ format: "pdf" })).toBe(false);});- test.each(["md", "js", "css", "json", "html", "xml", "svg"])(+ test.each(["md", "mdx", "js", "css", "json", "html", "xml", "svg"])("uses the available CodeMirror language for %s",(format) => {expect(getTextFileEditorExtensions({ format })).toHaveLength(1);@@ -41,8 +42,14 @@ describe("text file assets", () => {});- test("identifies Markdown files case-insensitively", () => {- expect(isMarkdownAsset({ format: "MD" })).toBe(true);- expect(isMarkdownAsset({ format: "txt" })).toBe(false);+ test("identifies files that use Markdown syntax", () => {+ expect(isMarkdownSyntaxAsset({ format: "MD" })).toBe(true);+ expect(isMarkdownSyntaxAsset({ format: "mdx" })).toBe(true);+ expect(isMarkdownSyntaxAsset({ format: "txt" })).toBe(false);+ });++ test("limits the Markdown preview to .md files", () => {+ expect(isMarkdownPreviewAsset({ format: "MD" })).toBe(true);+ expect(isMarkdownPreviewAsset({ format: "mdx" })).toBe(false);});});diff --git a/apps/builder/app/builder/features/text-file-editor/text-file-utils.ts b/apps/builder/app/builder/features/text-file-editor/text-file-utils.tsindex f1551de101..b183b5a1a5 100644--- a/apps/builder/app/builder/features/text-file-editor/text-file-utils.ts+++ b/apps/builder/app/builder/features/text-file-editor/text-file-utils.ts@@ -29,5 +29,8 @@ export const getTextFileEditorExtensions = (return languageExtensions[language];};-export const isMarkdownAsset = (asset: Pick<Asset, "format">) =>+export const isMarkdownSyntaxAsset = (asset: Pick<Asset, "format">) =>getAssetTextEditorLanguage(asset) === "markdown";++export const isMarkdownPreviewAsset = (asset: Pick<Asset, "format">) =>+ asset.format.toLowerCase() === "md";diff --git a/apps/builder/app/builder/shared/asset-manager/asset-filters.tsx b/apps/builder/app/builder/shared/asset-manager/asset-filters.tsxindex 84c08d5a96..a763b921a5 100644--- a/apps/builder/app/builder/shared/asset-manager/asset-filters.tsx+++ b/apps/builder/app/builder/shared/asset-manager/asset-filters.tsx@@ -49,6 +49,7 @@ const EXTENSION_TO_DISPLAY_CATEGORY: Record<// Codetxt: "Code",md: "Code",+ mdx: "Code",js: "Code",css: "Code",json: "Code",diff --git a/apps/builder/app/builder/shared/assets/builder-mdx-content-repository.client.ts b/apps/builder/app/builder/shared/assets/builder-mdx-content-repository.client.tsnew file mode 100644index 0000000000..9ac5f48032--- /dev/null+++ b/apps/builder/app/builder/shared/assets/builder-mdx-content-repository.client.ts@@ -0,0 +1,30 @@+import type { AssetContentRepository } from "@webstudio-is/asset-uploader/content-repository";+import { getAssetContentBridge } from "~/shared/asset-content-bridge.client";+import { $authToken } from "~/shared/nano-states";+import { createHttpAssetContentRepository } from "./mdx-content-repository";++export const createBuilderHttpAssetContentRepository = ({+ projectId,+ origin,+}: {+ projectId: string;+ origin?: string;+}): AssetContentRepository => {+ const getRepository = () => {+ const requestOrigin = origin ?? globalThis.location?.origin;+ if (requestOrigin === undefined) {+ throw new Error("Asset content requests require a browser origin");+ }+ return createHttpAssetContentRepository({+ projectId,+ origin: requestOrigin,+ authToken: () => $authToken.get(),+ request: (input, init) =>+ getAssetContentBridge().request(String(input), init),+ });+ };+ return {+ readContent: (input) => getRepository().readContent(input),+ updateContent: (input) => getRepository().updateContent(input),+ };+};diff --git a/apps/builder/app/builder/shared/assets/mdx-content-repository.test.ts b/apps/builder/app/builder/shared/assets/mdx-content-repository.test.tsnew file mode 100644index 0000000000..aed1ca7064--- /dev/null+++ b/apps/builder/app/builder/shared/assets/mdx-content-repository.test.ts@@ -0,0 +1,259 @@+import { describe, expect, test, vi } from "vitest";+import {+ AssetContentAuthorizationError,+ AssetRevisionConflictError,+} from "@webstudio-is/asset-uploader/content-repository";+import {+ assetContentDescriptorHeader,+ serializeAssetContentDescriptor,+} from "@webstudio-is/protocol/asset-resource-api";+import { contentEngineLimits } from "@webstudio-is/content-engine/limits";+import { createHttpAssetContentRepository } from "./mdx-content-repository";+import { createBuilderHttpAssetContentRepository } from "./builder-mdx-content-repository.client";++const asset = {+ id: "asset-1",+ projectId: "project-1",+ name: "article_revision.mdx",+ type: "file" as const,+ format: "mdx",+ size: 7,+ createdAt: "2026-08-15T00:00:00.000Z",+};++const collect = async (data: AsyncIterable<Uint8Array>) => {+ const chunks: Uint8Array[] = [];+ for await (const chunk of data) {+ chunks.push(chunk);+ }+ return new Uint8Array(chunks.flatMap((chunk) => Array.from(chunk.values())));+};++describe("HTTP MDX content repository", () => {+ test("can be created during server rendering without reading browser globals", () => {+ const browserWindow = globalThis.window;+ vi.stubGlobal("window", undefined);+ try {+ expect(() =>+ createBuilderHttpAssetContentRepository({ projectId: asset.projectId })+ ).not.toThrow();+ } finally {+ vi.stubGlobal("window", browserWindow);+ }+ });++ test("returns content and exact revision identity from one response", async () => {+ const request = vi.fn<typeof fetch>(async () =>+ Promise.resolve(+ new Response("# Hello", {+ headers: {+ "content-length": "7",+ [assetContentDescriptorHeader]:+ serializeAssetContentDescriptor(asset),+ },+ })+ )+ );+ const repository = createHttpAssetContentRepository({+ projectId: asset.projectId,+ origin: "https://webstudio.is",+ authToken: () => "token",+ request,+ });++ const content = await repository.readContent({ assetId: asset.id });++ expect(content.asset).toEqual(asset);+ expect(content.contentLength).toBe(7);+ expect(new TextDecoder().decode(await collect(content.data))).toBe(+ "# Hello"+ );+ expect(request).toHaveBeenCalledTimes(1);+ expect(+ new Headers(request.mock.calls[0]?.[1]?.headers).get("x-auth-token")+ ).toBe("token");+ });++ test("rejects content without the identity of the streamed revision", async () => {+ const repository = createHttpAssetContentRepository({+ projectId: asset.projectId,+ origin: "https://webstudio.is",+ request: async () => new Response("# Hello"),+ });++ await expect(repository.readContent({ assetId: asset.id })).rejects.toThrow(+ "missing its revision identity"+ );+ });++ test.each([+ [{ ...asset, id: "other" }, "requested Asset"],+ [{ ...asset, projectId: "other" }, "requested Asset"],+ ])("rejects substituted content identity %#", async (descriptor, message) => {+ const repository = createHttpAssetContentRepository({+ projectId: asset.projectId,+ origin: "https://webstudio.is",+ request: async () =>+ new Response("# Hello", {+ headers: {+ [assetContentDescriptorHeader]:+ serializeAssetContentDescriptor(descriptor),+ },+ }),+ });++ await expect(repository.readContent({ assetId: asset.id })).rejects.toThrow(+ message+ );+ });++ test("requires a partial response for a ranged read", async () => {+ const repository = createHttpAssetContentRepository({+ projectId: asset.projectId,+ origin: "https://webstudio.is",+ request: async () =>+ new Response("Hell", {+ headers: {+ [assetContentDescriptorHeader]:+ serializeAssetContentDescriptor(asset),+ },+ }),+ });++ await expect(+ repository.readContent({+ assetId: asset.id,+ range: { offset: 2, length: 4 },+ })+ ).rejects.toThrow("unexpected status 200");+ });++ test("rejects an oversized full-file descriptor before exposing its body", async () => {+ const repository = createHttpAssetContentRepository({+ projectId: asset.projectId,+ origin: "https://webstudio.is",+ request: async () =>+ new Response("body", {+ headers: {+ [assetContentDescriptorHeader]: serializeAssetContentDescriptor({+ ...asset,+ size: contentEngineLimits.hydratedFileBytes + 1,+ }),+ },+ }),+ });++ await expect(repository.readContent({ assetId: asset.id })).rejects.toThrow(+ "exceeds the MDX editing limit"+ );+ });++ test.each([+ [403, AssetContentAuthorizationError],+ [409, AssetRevisionConflictError],+ ])(+ "maps HTTP %s to the shared repository error",+ async (status, ErrorType) => {+ const repository = createHttpAssetContentRepository({+ projectId: asset.projectId,+ origin: "https://webstudio.is",+ request: async () =>+ new Response(JSON.stringify({ errors: "Denied" }), {+ status,+ headers: { "content-type": "application/json" },+ }),+ });++ await expect(+ repository.readContent({ assetId: asset.id })+ ).rejects.toThrow(ErrorType);+ }+ );++ test("updates with the pinned storage name and returns the next identity", async () => {+ const next = { ...asset, name: "article_next.mdx", size: 4 };+ const request = vi.fn<typeof fetch>(async (_url, init) => {+ expect(init?.method).toBe("PUT");+ expect(await new Response(init?.body).text()).toBe("next");+ return new Response(JSON.stringify({ asset: next }), {+ headers: { "content-type": "application/json" },+ });+ });+ const repository = createHttpAssetContentRepository({+ projectId: asset.projectId,+ origin: "https://webstudio.is",+ request,+ });++ await expect(+ repository.updateContent({+ assetId: asset.id,+ expectedName: asset.name,+ data: new ReadableStream({+ start(controller) {+ controller.enqueue(new TextEncoder().encode("next"));+ controller.close();+ },+ }),+ })+ ).resolves.toEqual(next);++ const url = request.mock.calls[0]?.[0];+ expect(new URL(String(url)).searchParams.get("expectedName")).toBe(+ asset.name+ );+ });++ test("bounds update buffering before making a request", async () => {+ const request = vi.fn<typeof fetch>();+ let cancelled = false;+ const repository = createHttpAssetContentRepository({+ projectId: asset.projectId,+ origin: "https://webstudio.is",+ request,+ });++ await expect(+ repository.updateContent({+ assetId: asset.id,+ expectedName: asset.name,+ data: new ReadableStream({+ start(controller) {+ controller.enqueue(+ new Uint8Array(contentEngineLimits.hydratedFileBytes + 1)+ );+ },+ cancel() {+ cancelled = true;+ },+ }),+ })+ ).rejects.toThrow();+ expect(request).not.toHaveBeenCalled();+ expect(cancelled).toBe(true);+ });++ test("rejects a substituted identity after update", async () => {+ const repository = createHttpAssetContentRepository({+ projectId: asset.projectId,+ origin: "https://webstudio.is",+ request: async () =>+ new Response(JSON.stringify({ asset: { ...asset, id: "other" } }), {+ headers: { "content-type": "application/json" },+ }),+ });++ await expect(+ repository.updateContent({+ assetId: asset.id,+ expectedName: asset.name,+ data: new ReadableStream({+ start(controller) {+ controller.enqueue(new TextEncoder().encode("next"));+ controller.close();+ },+ }),+ })+ ).rejects.toThrow("requested Asset");+ });+});diff --git a/apps/builder/app/builder/shared/assets/mdx-content-repository.ts b/apps/builder/app/builder/shared/assets/mdx-content-repository.tsnew file mode 100644index 0000000000..6e53f8179b--- /dev/null+++ b/apps/builder/app/builder/shared/assets/mdx-content-repository.ts@@ -0,0 +1,58 @@+import {+ createHttpAssetContentRepository as createSharedRepository,+ type AssetContentRepository,+} from "@webstudio-is/asset-uploader/content-repository";+import {+ readProjectAssetContent,+ updateProjectAssetContent,+} from "@webstudio-is/http-client";+import {+ assetContentDescriptor,+ assetContentDescriptorHeader,+ parseAssetContentDescriptor,+} from "@webstudio-is/protocol/asset-resource-api";++type HttpAssetContentRepositoryDependencies = Readonly<{+ projectId: string;+ origin: string;+ authToken?: () => string | undefined;+ request?: typeof fetch;+}>;++export const createHttpAssetContentRepository = ({+ projectId,+ origin,+ authToken = () => undefined,+ request = fetch,+}: HttpAssetContentRepositoryDependencies): AssetContentRepository =>+ createSharedRepository({+ projectId,+ read: ({ assetId, range }) =>+ readProjectAssetContent({+ projectId,+ origin,+ requestOrigin: origin,+ authToken: authToken(),+ request,+ assetId,+ range,+ }),+ update: async ({ assetId, expectedName, data }) => {+ const bytes = Uint8Array.from(data);+ const { asset } = await updateProjectAssetContent({+ projectId,+ origin,+ requestOrigin: origin,+ authToken: authToken(),+ request,+ assetId,+ expectedName,+ readAssetData: async () => bytes,+ });+ return assetContentDescriptor.parse(asset);+ },+ parseAsset: (response) =>+ parseAssetContentDescriptor(+ response.headers.get(assetContentDescriptorHeader)+ ),+ });diff --git a/apps/builder/app/builder/shared/commands.test.ts b/apps/builder/app/builder/shared/commands.test.tsindex 3d18359804..8072e97c57 100644--- a/apps/builder/app/builder/shared/commands.test.ts+++ b/apps/builder/app/builder/shared/commands.test.ts@@ -91,6 +91,38 @@ const resetDataStores = () => {$builderMode.set("design");};+test("keeps ordinary project undo and redo commands working", async () => {+ resetDataStores();+ const unsubscribe = subscribeCommands();+ $instances.set(+ new Map([+ [+ "box",+ {+ type: "instance" as const,+ id: "box",+ component: "Box",+ children: [],+ },+ ],+ ])+ );+ serverSyncStore.createTransaction([$instances], (instances) => {+ instances.get("box")!.label = "Changed";+ });++ emitCommand("undo");+ await vi.waitFor(() =>+ expect($instances.get().get("box")?.label).toBeUndefined()+ );+ emitCommand("redo");+ await vi.waitFor(() =>+ expect($instances.get().get("box")?.label).toBe("Changed")+ );++ unsubscribe();+});+const setupMoveInstanceProject = () => {resetDataStores();const instances = new Map<Instance["id"], Instance>([diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.tsindex 1e7a41faa2..a43f20eaf6 100644--- a/apps/builder/app/builder/shared/commands.ts+++ b/apps/builder/app/builder/shared/commands.ts@@ -96,7 +96,7 @@ import {import { getDirectSharedSlotChildBoundary } from "~/shared/instance-utils/slot";import type { InstanceSelector } from "@webstudio-is/project-build/runtime";import { areInstanceSelectorsEqual } from "@webstudio-is/project-build/runtime";-import { findChildReferenceIndex } from "@webstudio-is/project-build/runtime";+import { findChildReferenceIndex } from "@webstudio-is/sdk";const makeBreakpointCommand = <CommandName extends string>(name: CommandName,@@ -442,7 +442,7 @@ const deleteSelectedInstances = () => {reportSkippedSelectedInstances("deleted");}- executeRuntimeMutation({+ const result = executeRuntimeMutation({id: "instances.delete",input: {instanceIds: sortInstancePathsForChildMutation(@@ -450,7 +450,9 @@ const deleteSelectedInstances = () => {).map(({ instancePath }) => instancePath[0].instance.id),},});- clearInstanceSelection();+ if (result !== undefined) {+ clearInstanceSelection();+ }return true;};@@ -1126,9 +1128,7 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({// safari use meta+z to reopen closed tabs, here added ctrl as alternativedefaultHotkeys: ["meta+z", "ctrl+z"],disableOnInputLikeControls: true,- handler: () => {- serverSyncStore.undo();- },+ handler: () => serverSyncStore.undo(),},{name: "redo",@@ -1137,9 +1137,7 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({// safari use meta+z to reopen closed tabs, here added ctrl as alternativedefaultHotkeys: ["meta+shift+z", "ctrl+shift+z"],disableOnInputLikeControls: true,- handler: () => {- serverSyncStore.redo();- },+ handler: () => serverSyncStore.redo(),},{diff --git a/apps/builder/app/builder/shared/instance-label.tsx b/apps/builder/app/builder/shared/instance-label.tsxindex bf314577ef..089876220d 100644--- a/apps/builder/app/builder/shared/instance-label.tsx+++ b/apps/builder/app/builder/shared/instance-label.tsx@@ -27,6 +27,7 @@ import {} from "@webstudio-is/icons/svg";import {elementComponent,+ getInstanceName,parseComponentName,ROOT_INSTANCE_ID,type Instance,@@ -120,19 +121,9 @@ export const getInstanceLabel = (return "Unknown";}- if (instanceOrInstanceId.label) {- return instanceOrInstanceId.label;- }- if (- instanceOrInstanceId.component === elementComponent &&- instanceOrInstanceId.tag- ) {- return `<${instanceOrInstanceId.tag}>`;- }- const meta = $registeredComponentMetas- .get()- .get(instanceOrInstanceId.component);- return (- meta?.label || getLabelFromComponentName(instanceOrInstanceId.component)- );+ return getInstanceName({+ instance: instanceOrInstanceId,+ metas: $registeredComponentMetas.get(),+ fallbackName: getLabelFromComponentName(instanceOrInstanceId.component),+ });};diff --git a/apps/builder/app/builder/shared/use-draft-value.test.tsx b/apps/builder/app/builder/shared/use-draft-value.test.tsxindex c6df0cb9ee..7342383dca 100644--- a/apps/builder/app/builder/shared/use-draft-value.test.tsx+++ b/apps/builder/app/builder/shared/use-draft-value.test.tsx@@ -28,7 +28,7 @@ const renderDraftValue = <Type,>({onRender,}: {savedValue: Type;- onSave: (value: Type) => void;+ onSave: (value: Type) => void | boolean;options?: Parameters<typeof useDraftValue<Type>>[2];onRender?: (draftValue: DraftValueApi<Type>) => void;}) => {@@ -156,4 +156,30 @@ describe("useDraftValue", () => {draftValue.rerender({ count: 2 });expect(draftValue.current.value).toEqual({ count: 2 });});++ test("keeps a rejected draft open across rerenders", () => {+ const draftValue = renderDraftValue({+ savedValue: "saved",+ onSave: () => false,+ });+ act(() => {+ draftValue.current.set("duplicate");+ draftValue.current.save();+ });+ draftValue.rerender("remote");++ expect(draftValue.current.value).toBe("duplicate");+ });++ test("resets a draft to the latest saved value", () => {+ const draftValue = renderDraftValue({+ savedValue: "saved",+ onSave: vi.fn(),+ });+ act(() => draftValue.current.set("draft"));+ draftValue.rerender("remote");+ act(() => draftValue.current.reset());++ expect(draftValue.current.value).toBe("remote");+ });});diff --git a/apps/builder/app/builder/shared/use-draft-value.ts b/apps/builder/app/builder/shared/use-draft-value.tsindex 0a403f9977..7a2ec90615 100644--- a/apps/builder/app/builder/shared/use-draft-value.ts+++ b/apps/builder/app/builder/shared/use-draft-value.ts@@ -6,7 +6,7 @@ type ValueUpdater<Type> = Type | ((value: Type) => Type);export const useDraftValue = <Type>(savedValue: Type,- onSave: (value: Type) => void,+ onSave: (value: Type) => void | boolean,{autoSave = true,resetOnSave = false,@@ -35,13 +35,14 @@ export const useDraftValue = <Type>(};const saveDraft = ({ refreshOnReset = true } = {}) => {- isEditingRef.current = false;if (equal(localValueRef.current, savedValueRef.current) === false &&shouldSaveRef.current(localValueRef.current)) {// To synchronize with setState immediately followed by save- onSaveRef.current(localValueRef.current);+ if (onSaveRef.current(localValueRef.current) === false) {+ return false;+ }if (resetOnSave) {localValueRef.current = savedValueRef.current;if (refreshOnReset) {@@ -49,6 +50,8 @@ export const useDraftValue = <Type>(}}}+ isEditingRef.current = false;+ return true;};const save = () => {@@ -69,6 +72,12 @@ export const useDraftValue = <Type>(}};+ const reset = () => {+ isEditingRef.current = false;+ localValueRef.current = savedValueRef.current;+ refresh();+ };+// onBlur will not trigger if control is unmounted when props panel is closed or similar.// So we're saving at the unmount// store save in ref to access latest saved value from render@@ -110,6 +119,7 @@ export const useDraftValue = <Type>(* Should be called on onBlur or similar event*/save,+ reset,flush: saveDebounced.flush,};};diff --git a/apps/builder/app/canvas/canvas.tsx b/apps/builder/app/canvas/canvas.tsxindex 2b89cae275..37d0444ed2 100644--- a/apps/builder/app/canvas/canvas.tsx+++ b/apps/builder/app/canvas/canvas.tsx@@ -41,8 +41,12 @@ import {subscribeModifierKeys,assetBaseUrl,} from "~/shared/nano-states";-import { $assets } from "~/shared/sync/data-stores";-import { $pages, $instances, $breakpoints } from "~/shared/sync/data-stores";+import { $pages } from "~/shared/sync/data-stores";+import {+ $runtimeAssets as $assets,+ $runtimeBreakpoints as $breakpoints,+ $runtimeInstances as $instances,+} from "~/shared/content-block-content";import { useDragAndDrop } from "./shared/use-drag-drop";import {initCopyPaste,diff --git a/apps/builder/app/canvas/features/build-mode/block.test.tsx b/apps/builder/app/canvas/features/build-mode/block.test.tsxnew file mode 100644index 0000000000..95eb35af7f--- /dev/null+++ b/apps/builder/app/canvas/features/build-mode/block.test.tsx@@ -0,0 +1,164 @@+/**+ * @vitest-environment jsdom+ */+import { act } from "react-dom/test-utils";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, test, vi } from "vitest";+import {+ registerContentBlockPresentationActions,+ resetMaterializedContent,+ type ContentBlockPresentationItem,+} from "~/shared/content-block-content";+import { ContentBlockPresentation } from "./block";+import {+ componentAttribute,+ idAttribute,+ selectorIdAttribute,+} from "@webstudio-is/react-sdk";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+ resetMaterializedContent();+});++const item = (values: Partial<ContentBlockPresentationItem> = {}) => ({+ id: "notice",+ blockInstanceId: "block",+ renderScope: "scope:item-1",+ kind: "error" as const,+ status: "recoverable" as const,+ label: "Repair MDX file",+ message: "The MDX file could not be rendered.",+ assetId: "article",+ ...values,+});++const systemProps = {+ [componentAttribute]: "ws:content-presentation",+ [idAttribute]: "notice",+ [selectorIdAttribute]: "notice,block",+};++test("renders an accessible selectable recovery notice and retries its exact scope", async () => {+ const retry = vi.fn(async () => ({ status: "applied" as const }));+ registerContentBlockPresentationActions({+ blockInstanceId: "block",+ renderScope: "scope:item-1",+ actions: {+ retry,+ reloadRemote: async () => ({ status: "applied" }),+ copyUnsavedSource: () => undefined,+ },+ });+ act(() => {+ root.render(<ContentBlockPresentation item={item()} {...systemProps} />);+ });++ const notice = container.querySelector<HTMLElement>('[role="alert"]');+ expect(notice?.tabIndex).toBe(0);+ expect(notice?.textContent).toContain("Repair MDX file");+ const retryButton = container.querySelector<HTMLButtonElement>(+ '[aria-label="Retry loading MDX content"]'+ );+ await act(async () => retryButton?.click());+ expect(retry).toHaveBeenCalledOnce();+});++test("offers explicit conflict recovery without a blind retry", () => {+ const reloadRemote = vi.fn(async () => ({ status: "applied" as const }));+ registerContentBlockPresentationActions({+ blockInstanceId: "block",+ renderScope: "scope:item-1",+ actions: {+ retry: async () => ({ status: "applied" }),+ reloadRemote,+ copyUnsavedSource: () => "unsaved",+ },+ });+ Object.assign(navigator, {+ clipboard: { writeText: vi.fn(async () => undefined) },+ });+ act(() => {+ root.render(+ <ContentBlockPresentation+ item={item({ status: "conflicting", label: "MDX conflict" })}+ {...systemProps}+ />+ );+ });++ expect(container.textContent).not.toContain("Retry");+ expect(container.textContent).toContain("Reload remote file");+ expect(container.textContent).toContain("Copy unsaved MDX");+});++test("announces unresolved templates as warnings without recovery controls", () => {+ act(() => {+ root.render(+ <ContentBlockPresentation+ item={item({+ kind: "warning",+ status: "ready",+ label: "Missing template: Hero",+ message: "Template Hero is unavailable.",+ assetId: undefined,+ })}+ {...systemProps}+ />+ );+ });++ const warning = container.querySelector('[role="status"]');+ expect(warning?.textContent).toContain("Missing template: Hero");+ expect(warning?.getAttribute("aria-live")).toBe("off");+ expect(container.querySelector("button")).toBeNull();+});++test.each([+ {+ kind: "loading" as const,+ status: "loading" as const,+ label: "Loading MDX",+ busy: "true",+ },+ {+ kind: "loading" as const,+ status: "pending" as const,+ label: "Saving MDX",+ busy: "true",+ },+ {+ kind: "empty" as const,+ status: "empty" as const,+ label: "Empty MDX file",+ busy: null,+ },+])("announces $status content without recovery controls", (state) => {+ act(() => {+ root.render(+ <ContentBlockPresentation+ item={item({ ...state, message: state.label, assetId: undefined })}+ {...systemProps}+ />+ );+ });++ const notice = container.querySelector('[role="status"]');+ expect(notice?.textContent).toContain(state.label);+ expect(notice?.getAttribute("aria-busy")).toBe(state.busy);+ expect(container.querySelector("button")).toBeNull();+});diff --git a/apps/builder/app/canvas/features/build-mode/block.tsx b/apps/builder/app/canvas/features/build-mode/block.tsxindex af7085ce11..60aefae3da 100644--- a/apps/builder/app/canvas/features/build-mode/block.tsx+++ b/apps/builder/app/canvas/features/build-mode/block.tsx@@ -8,9 +8,157 @@ import {} from "@webstudio-is/react-sdk";import * as React from "react";+import { useState } from "react";+import { Button, rawTheme } from "@webstudio-is/design-system";+import { TextFileEditor } from "~/builder/features/text-file-editor/text-file-editor";import { $isDesignMode, $isPreviewMode } from "~/shared/nano-states";import { $selectedInstanceSelector } from "~/shared/nano-states";-import { $instances } from "~/shared/sync/data-stores";+import {+ $runtimeInstances as $instances,+ getContentBlockPresentationActions,+ type ContentBlockPresentationItem,+} from "~/shared/content-block-content";++export const ContentBlockPresentation = React.forwardRef<+ HTMLElement,+ {+ item: ContentBlockPresentationItem;+ } & WebstudioComponentSystemProps+>(({ item, ...props }, ref) => {+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string>();+ const [openedAssetId, setOpenedAssetId] = useState<string>();+ const actions = getContentBlockPresentationActions(item);+ const run = async (action: "retry" | "reloadRemote") => {+ if (busy || actions === undefined) {+ return;+ }+ setBusy(true);+ setError(undefined);+ try {+ const result = await actions[action]();+ if (result.status === "blocked") {+ setError(result.message);+ }+ } catch (error) {+ setError(error instanceof Error ? error.message : "Unable to update MDX");+ } finally {+ setBusy(false);+ }+ };+ const stopCanvasSelection = (event: React.SyntheticEvent) =>+ event.stopPropagation();+ const isError = item.kind === "error";+ const isWarning = item.kind === "warning";+ return (+ <>+ <section+ {...props}+ ref={ref}+ role={isError ? "alert" : "status"}+ aria-live={isError ? "assertive" : isWarning ? "off" : "polite"}+ aria-busy={item.kind === "loading" || busy || undefined}+ tabIndex={0}+ style={{+ display: "grid",+ gap: rawTheme.spacing[3],+ padding: rawTheme.spacing[5],+ border: `1px solid ${+ isError+ ? rawTheme.colors.borderDestructiveMain+ : rawTheme.colors.borderMain+ }`,+ borderRadius: rawTheme.spacing[3],+ backgroundColor: rawTheme.colors.backgroundMenu,+ color: isError+ ? rawTheme.colors.foregroundDestructive+ : rawTheme.colors.foregroundMain,+ }}+ >+ <strong>{item.label}</strong>+ <span>{item.message}</span>+ {error !== undefined && <span>{error}</span>}+ <span style={{ display: "flex", gap: rawTheme.spacing[3] }}>+ {isError && item.status !== "conflicting" && (+ <Button+ type="button"+ color="neutral"+ disabled={busy || actions === undefined}+ aria-label="Retry loading MDX content"+ onPointerDown={stopCanvasSelection}+ onClick={(event) => {+ stopCanvasSelection(event);+ void run("retry");+ }}+ >+ Retry+ </Button>+ )}+ {item.status === "conflicting" && (+ <>+ <Button+ type="button"+ color="neutral"+ disabled={busy || actions === undefined}+ onPointerDown={stopCanvasSelection}+ onClick={(event) => {+ stopCanvasSelection(event);+ void run("reloadRemote");+ }}+ >+ Reload remote file+ </Button>+ <Button+ type="button"+ color="neutral"+ disabled={busy || actions?.copyUnsavedSource() === undefined}+ onPointerDown={stopCanvasSelection}+ onClick={(event) => {+ stopCanvasSelection(event);+ const source = actions?.copyUnsavedSource();+ if (source !== undefined) {+ if (navigator.clipboard === undefined) {+ setError("Clipboard access is unavailable.");+ } else {+ void navigator.clipboard.writeText(source).catch(() => {+ setError("The unsaved MDX could not be copied.");+ });+ }+ }+ }}+ >+ Copy unsaved MDX+ </Button>+ </>+ )}+ {item.assetId !== undefined && (+ <Button+ type="button"+ color="neutral"+ onPointerDown={stopCanvasSelection}+ onClick={(event) => {+ stopCanvasSelection(event);+ setOpenedAssetId(item.assetId);+ }}+ >+ Open file+ </Button>+ )}+ </span>+ </section>+ {openedAssetId !== undefined && (+ <TextFileEditor+ assetId={openedAssetId}+ onOpenChange={(open) => {+ if (open === false) {+ setOpenedAssetId(undefined);+ }+ }}+ />+ )}+ </>+ );+});export const Block = React.forwardRef<HTMLDivElement,diff --git a/apps/builder/app/canvas/features/text-editor/text-editor.tsx b/apps/builder/app/canvas/features/text-editor/text-editor.tsxindex 9e251c5879..b87e044aba 100644--- a/apps/builder/app/canvas/features/text-editor/text-editor.tsx+++ b/apps/builder/app/canvas/features/text-editor/text-editor.tsx@@ -76,7 +76,7 @@ import {$textEditorContextMenu,execTextEditorContextMenuCommand,} from "~/shared/nano-states";-import { $instances } from "~/shared/sync/data-stores";+import { $runtimeInstances as $instances } from "~/shared/content-block-content";import {findBlockChildSelector,findBlockTemplates,diff --git a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsxindex c1e1f46a28..cc731d84b4 100644--- a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx+++ b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx@@ -25,6 +25,7 @@ import {descendantComponent,blockComponent,blockTemplateComponent,+ getContentBlockSource,getIndexesWithinAncestors,elementComponent,} from "@webstudio-is/sdk";@@ -53,19 +54,33 @@ import {$registeredComponentMetas,$selectedInstanceRenderState,$selectedPageHash,+ $variableValuesByInstanceSelector,} from "~/shared/nano-states";-import { $props } from "~/shared/sync/data-stores";+import {+ $runtimeInstances as $instances,+ $runtimeProps as $props,+ $runtimeAssets as $assets,+ $materializedContentStatuses,+ getRuntimeInstanceChildren,+ isMaterializedInstanceEditable,+ $contentBlockPresentationItems,+ contentBlockPresentationComponent,+} from "~/shared/content-block-content";import { $textEditingInstanceSelector } from "~/shared/nano-states";-import { $instances } from "~/shared/sync/data-stores";import {type InstanceSelector,areInstanceSelectorsEqual,+ computeExpression,} from "@webstudio-is/project-build/runtime";import { findBlockSelector } from "@webstudio-is/project-build/runtime";import { inflateInstance } from "~/canvas/inflator";import { getIsVisuallyHidden } from "~/shared/visually-hidden";import { TextEditor } from "../text-editor";-import { $selectedPage, getInstanceKey } from "~/shared/nano-states";+import {+ $selectedPage,+ getInstanceKey,+ getInstanceKeyWithRoot,+} from "~/shared/nano-states";import { selectInstance } from "~/shared/nano-states";import { $currentSystem } from "~/shared/system";import { executeRuntimeMutation } from "~/shared/instance-utils/data";@@ -73,13 +88,20 @@ import {createInstanceChildrenElements,type WebstudioComponentProps,} from "~/canvas/elements";-import { Block } from "../build-mode/block";+import { Block, ContentBlockPresentation } from "../build-mode/block";import { BlockTemplate } from "../build-mode/block-template";import {editablePlaceholderAttribute,editingPlaceholderVariable,} from "~/canvas/shared/styles";import { richTextPlaceholders } from "@webstudio-is/project-build/runtime";+import { $project } from "~/shared/sync/data-stores";+import { createBuilderContentBlockSourceController } from "~/builder/features/settings-panel/controls/content-block-source-controller";+import {+ setContentBlockSourceSwitching,+ setMaterializedContentStatus,+} from "~/shared/content-block-content";+import { subscribe } from "~/shared/pubsub";const computeComponentKey = (props: Record<string, unknown>) => {const assetId = props.$webstudio$canvasOnly$assetId;@@ -387,11 +409,156 @@ const useInstanceProps = (instanceSelector: InstanceSelector) => {const existingElements = new Set<string>();+const useContentBlockMaterialization = ({+ instance,+ instanceSelector,+ props,+}: {+ instance: Instance;+ instanceSelector: InstanceSelector;+ props: ReadonlyMap<string, Prop>;+}) => {+ const project = useStore($project);+ const assets = useStore($assets);+ const variableValues = useStore($variableValuesByInstanceSelector);+ const renderScope = getInstanceKey(instanceSelector);+ const rootedRenderScope = getInstanceKeyWithRoot(instanceSelector);+ useEffect(() => {+ if (instance.component !== blockComponent || project === undefined) {+ return;+ }+ const unsubscribe = subscribe("contentBlockSourceStatus", (message) => {+ if (+ message.projectId === project.id &&+ message.blockInstanceId === instance.id &&+ message.renderScope === renderScope+ ) {+ setContentBlockSourceSwitching({+ blockInstanceId: instance.id,+ renderScope,+ switching: message.status === "loading",+ });+ }+ });+ return () => {+ unsubscribe();+ setContentBlockSourceSwitching({+ blockInstanceId: instance.id,+ renderScope,+ switching: false,+ });+ };+ }, [instance.component, instance.id, project, renderScope]);+ const source = useMemo(() => {+ if (instance.component !== blockComponent) {+ return;+ }+ return getContentBlockSource({+ blockInstanceId: instance.id,+ props: props.values(),+ });+ }, [instance.component, instance.id, props]);+ const sourceKey = source === undefined ? undefined : JSON.stringify(source);+ const resolvedAssetId = useMemo(() => {+ if (source?.type === "asset") {+ return source.assetId;+ }+ if (source?.type !== "expression") {+ return;+ }+ try {+ const value = computeExpression(+ source.value,+ variableValues.get(rootedRenderScope) ?? new Map()+ );+ return typeof value === "string" ? value : undefined;+ } catch {+ return;+ }+ }, [rootedRenderScope, source, variableValues]);+ const resolvedAsset =+ resolvedAssetId === undefined ? undefined : assets.get(resolvedAssetId);+ const resolvedAssetVersion =+ resolvedAsset === undefined+ ? undefined+ : JSON.stringify([+ resolvedAsset.id,+ resolvedAsset.name,+ resolvedAsset.size,+ resolvedAsset.updatedAt,+ ]);+ const controller = useMemo(+ () =>+ project === undefined || sourceKey === undefined+ ? undefined+ : createBuilderContentBlockSourceController({+ blockInstanceId: instance.id,+ renderScope,+ projectId: project.id,+ }),+ [instance.id, project, renderScope, sourceKey]+ );++ useEffect(+ () => () => {+ controller?.dispose();+ },+ [controller]+ );++ useEffect(() => {+ if (+ controller === undefined ||+ sourceKey === undefined ||+ $project.get()?.id !== project?.id+ ) {+ return;+ }+ let active = true;+ setContentBlockSourceSwitching({+ blockInstanceId: instance.id,+ renderScope,+ switching: false,+ });+ setMaterializedContentStatus({+ blockInstanceId: instance.id,+ renderScope,+ status: "loading",+ assetId: resolvedAssetId,+ });+ const markFailed = () => {+ if (active && $project.get()?.id === project?.id) {+ setMaterializedContentStatus({+ blockInstanceId: instance.id,+ renderScope,+ status: "failed",+ assetId: resolvedAssetId,+ });+ }+ };+ void controller.open(JSON.parse(sourceKey)).catch(markFailed);+ return () => {+ active = false;+ };+ }, [+ controller,+ instance.id,+ project,+ renderScope,+ resolvedAssetId,+ resolvedAssetVersion,+ sourceKey,+ ]);+};+/*** We are identifying newly created instances like Tooltips and ensuring the calculation of 'inflated' elements.*/-const useInflateOnNewElement = (instanceId: Instance["id"]) => {+const useInflateOnNewElement = (instanceId: Instance["id"], enabled = true) => {useEffect(() => {+ if (enabled === false) {+ return;+ }if (existingElements.has(instanceId) === false) {inflateInstance(instanceId);}@@ -400,7 +567,7 @@ const useInflateOnNewElement = (instanceId: Instance["id"]) => {return () => {existingElements.delete(instanceId);};- }, [instanceId]);+ }, [enabled, instanceId]);};/**@@ -483,6 +650,13 @@ export const WebstudioComponentCanvas = forwardRef<const instanceId = instance.id;const instances = useStore($instances);const allProps = useStore($props);+ const presentationItems = useStore($contentBlockPresentationItems);+ useStore($materializedContentStatuses);+ useContentBlockMaterialization({+ instance,+ instanceSelector,+ props: allProps,+ });const metas = useStore($registeredComponentMetas);const textEditingInstanceSelector = useStore($textEditingInstanceSelector);@@ -495,7 +669,7 @@ export const WebstudioComponentCanvas = forwardRef<createInstanceChildrenElements({instances,instanceSelector,- children: instance.children,+ children: getRuntimeInstanceChildren(instance, instanceSelector),Component: WebstudioComponentCanvas,components,});@@ -506,7 +680,10 @@ export const WebstudioComponentCanvas = forwardRef<*/const initialContentEditableContent = useRef(children);- useInflateOnNewElement(instanceId);+ useInflateOnNewElement(+ instanceId,+ instance.component !== contentBlockPresentationComponent+ );// this assumes presence of `useStore($selectedInstanceSelector)` above// we rely on root re-rendering after selected instance changes@@ -546,7 +723,11 @@ export const WebstudioComponentCanvas = forwardRef<if (instance.component === collectionComponent) {const originalData = instanceProps.data;- if (originalData && instance.children.length > 0) {+ const collectionChildren = getRuntimeInstanceChildren(+ instance,+ instanceSelector+ );+ if (originalData && collectionChildren.length > 0) {const entries = getCollectionEntries(originalData);if (entries.length > 0) {return entries.map(([key]) => (@@ -557,7 +738,7 @@ export const WebstudioComponentCanvas = forwardRef<getIndexedInstanceId(instance.id, key),...instanceSelector,],- children: instance.children,+ children: collectionChildren,Component: WebstudioComponentCanvas,components,})}@@ -609,6 +790,13 @@ export const WebstudioComponentCanvas = forwardRef<// For expressions that resolve to asset URLs (via assets resource), use the src value itselfconst key = computeComponentKey(props);+ if (instance.component === contentBlockPresentationComponent) {+ const item = presentationItems.get(instance.id);+ return item === undefined ? null : (+ <ContentBlockPresentation item={item} {...props} ref={ref} />+ );+ }+const instanceElement = (<><Component key={key} {...props} ref={ref}>@@ -618,6 +806,7 @@ export const WebstudioComponentCanvas = forwardRef<);if (+ isMaterializedInstanceEditable({ instanceSelector, instances }) === false ||areInstanceSelectorsEqual(textEditingInstanceSelector?.selector,instanceSelector@@ -677,8 +866,19 @@ export const WebstudioComponentPreview = forwardRef<WebstudioComponentProps>(({ instance, instanceSelector, components, ...restProps }, ref) => {const instances = useStore($instances);+ const allProps = useStore($props);+ useStore($contentBlockPresentationItems);+ useContentBlockMaterialization({+ instance,+ instanceSelector,+ props: allProps,+ });const { [showAttribute]: show = true, ...instanceProps } =useInstanceProps(instanceSelector);++ if (instance.component === contentBlockPresentationComponent) {+ return null;+ }const props: {[componentAttribute]: string;[idAttribute]: string;@@ -695,7 +895,11 @@ export const WebstudioComponentPreview = forwardRef<if (instance.component === collectionComponent) {const originalData = instanceProps.data;- if (originalData && instance.children.length > 0) {+ const collectionChildren = getRuntimeInstanceChildren(+ instance,+ instanceSelector+ );+ if (originalData && collectionChildren.length > 0) {const entries = getCollectionEntries(originalData);if (entries.length > 0) {return entries.map(([key]) => (@@ -706,7 +910,7 @@ export const WebstudioComponentPreview = forwardRef<getIndexedInstanceId(instance.id, key),...instanceSelector,],- children: instance.children,+ children: collectionChildren,Component: WebstudioComponentPreview,components,})}@@ -759,7 +963,7 @@ export const WebstudioComponentPreview = forwardRef<createInstanceChildrenElements({instances,instanceSelector,- children: instance.children,+ children: getRuntimeInstanceChildren(instance, instanceSelector),Component: WebstudioComponentPreview,components,})}diff --git a/apps/builder/app/canvas/grid-guide-utils.ts b/apps/builder/app/canvas/grid-guide-utils.tsindex 98e56b8cd8..c5c8e65943 100644--- a/apps/builder/app/canvas/grid-guide-utils.ts+++ b/apps/builder/app/canvas/grid-guide-utils.ts@@ -3,7 +3,7 @@ import {$stylesIndex,$propValuesByInstanceSelectorWithMemoryProps,} from "~/shared/nano-states";-import { $instances } from "~/shared/sync/data-stores";+import { $runtimeInstances as $instances } from "~/shared/content-block-content";import { $gridCellData, type GridCellData } from "~/shared/nano-states";import { subscribeScrollState } from "~/canvas/shared/scroll-state";import { subscribeWindowResize } from "~/shared/dom-hooks";diff --git a/apps/builder/app/canvas/inflator.ts b/apps/builder/app/canvas/inflator.tsindex 74dcf03215..1f16def92e 100644--- a/apps/builder/app/canvas/inflator.ts+++ b/apps/builder/app/canvas/inflator.ts@@ -4,8 +4,10 @@ import { compareMedia, type StyleValue } from "@webstudio-is/css-engine";import { parseGridTemplateTrackList } from "@webstudio-is/css-data";import type { Breakpoint, StyleDecl, WsComponentMeta } from "@webstudio-is/sdk";import { $registeredComponentMetas, $stylesIndex } from "~/shared/nano-states";-import { $breakpoints } from "~/shared/sync/data-stores";-import { $instances } from "~/shared/sync/data-stores";+import {+ $runtimeBreakpoints as $breakpoints,+ $runtimeInstances as $instances,+} from "~/shared/content-block-content";import { $selectedBreakpoint } from "~/shared/nano-states";import { $selectedPage } from "~/shared/nano-states";import { serverSyncStore } from "~/shared/sync/sync-stores";diff --git a/apps/builder/app/canvas/instance-hovering.ts b/apps/builder/app/canvas/instance-hovering.tsindex bfd63c7050..97b0721afc 100644--- a/apps/builder/app/canvas/instance-hovering.ts+++ b/apps/builder/app/canvas/instance-hovering.ts@@ -4,7 +4,7 @@ import {$hoveredInstanceSelector,$textEditingInstanceSelector,} from "~/shared/nano-states";-import { $instances } from "~/shared/sync/data-stores";+import { $runtimeInstances as $instances } from "~/shared/content-block-content";import { $hoveredInstanceOutline } from "~/shared/nano-states";import {getAllElementsBoundingBox,diff --git a/apps/builder/app/canvas/instance-selection-events.ts b/apps/builder/app/canvas/instance-selection-events.tsindex 8f549c1094..2bb683b068 100644--- a/apps/builder/app/canvas/instance-selection-events.ts+++ b/apps/builder/app/canvas/instance-selection-events.ts@@ -13,8 +13,10 @@ import {selectInstances,} from "~/shared/nano-states";import { getInstanceSelectionUpdate } from "~/shared/instance-utils/selection";-import { $props } from "~/shared/sync/data-stores";-import { $instances } from "~/shared/sync/data-stores";+import {+ $runtimeInstances as $instances,+ $runtimeProps as $props,+} from "~/shared/content-block-content";import { $ephemeralStyles } from "~/canvas/stores";import { emitCommand } from "./shared/commands";import { shallowEqual } from "shallow-equal";diff --git a/apps/builder/app/canvas/selected-instance-effects.ts b/apps/builder/app/canvas/selected-instance-effects.tsindex aa6cf0dc97..b525ef5084 100644--- a/apps/builder/app/canvas/selected-instance-effects.ts+++ b/apps/builder/app/canvas/selected-instance-effects.ts@@ -16,7 +16,11 @@ import {type UnitSizes,type PropertySizes,} from "~/shared/nano-states";-import { $styleSourceSelections } from "~/shared/sync/data-stores";+import {+ $runtimeInstances as $instances,+ $runtimeStyleSourceSelections as $styleSourceSelections,+ $runtimeStyles as $styles,+} from "~/shared/content-block-content";import {getAllElementsBoundingBox,getVisibleElementsByInstanceSelector,@@ -29,7 +33,6 @@ import {$selectedInstanceOutline,$selectedInstanceOutlines,} from "~/shared/nano-states";-import { $instances, $styles } from "~/shared/sync/data-stores";import { inflateInstance } from "~/canvas/inflator";import {areInstanceSelectorsEqual,diff --git a/apps/builder/app/canvas/shared/commands.ts b/apps/builder/app/canvas/shared/commands.tsindex 345051d3bc..b9fcebb2c4 100644--- a/apps/builder/app/canvas/shared/commands.ts+++ b/apps/builder/app/canvas/shared/commands.ts@@ -14,7 +14,10 @@ import {clearInstanceSelection,selectInstance,} from "~/shared/nano-states";-import { $instances, $props } from "~/shared/sync/data-stores";+import {+ $runtimeInstances as $instances,+ $runtimeProps as $props,+} from "~/shared/content-block-content";import {CLEAR_FORMAT_COMMAND,TOGGLE_SPAN_COMMAND,diff --git a/apps/builder/app/canvas/shared/content-mode.ts b/apps/builder/app/canvas/shared/content-mode.tsindex ced62d01a0..6b5f64fa75 100644--- a/apps/builder/app/canvas/shared/content-mode.ts+++ b/apps/builder/app/canvas/shared/content-mode.ts@@ -1,6 +1,7 @@import { getContentModeEditableInstanceIds } from "@webstudio-is/project-build/runtime";import type { InstanceSelector } from "@webstudio-is/project-build/runtime";import type { Instances } from "@webstudio-is/sdk";+import { getMaterializedInstanceEditability } from "~/shared/content-block-content";export const isTextEditableInContentMode = ({isContentMode,@@ -14,6 +15,13 @@ export const isTextEditableInContentMode = ({if (isContentMode === false) {return true;}+ const materializedEditability = getMaterializedInstanceEditability({+ instanceSelector,+ instances,+ });+ if (materializedEditability !== undefined) {+ return materializedEditability;+ }return getContentModeEditableInstanceIds({ instances }).has(instanceSelector[0]);diff --git a/apps/builder/app/canvas/shared/scroll-new-instance-into-view.ts b/apps/builder/app/canvas/shared/scroll-new-instance-into-view.tsindex 1870e99ee9..a0707dfdb3 100644--- a/apps/builder/app/canvas/shared/scroll-new-instance-into-view.ts+++ b/apps/builder/app/canvas/shared/scroll-new-instance-into-view.ts@@ -1,6 +1,6 @@import { idAttribute } from "@webstudio-is/react-sdk";import type { Instances } from "@webstudio-is/sdk";-import { $instances } from "~/shared/sync/data-stores";+import { $runtimeInstances as $instances } from "~/shared/content-block-content";/*** When a new instance is added to the canvas, scroll it into view.diff --git a/apps/builder/app/canvas/shared/styles.test.ts b/apps/builder/app/canvas/shared/styles.test.tsindex 19ad26e27b..a5d6f3d5df 100644--- a/apps/builder/app/canvas/shared/styles.test.ts+++ b/apps/builder/app/canvas/shared/styles.test.ts@@ -330,6 +330,51 @@ describe("computeDescendantSelectors", () => {expect(result.get("descendant")).toBe('[data-ws-id="parent"] > div');});+ test("computes a selector for a descendant at an MDX storage root", () => {+ const instances = new Map([+ ["block", createInstance("block", "ws:block")],+ ["descendant", createInstance("descendant", descendantComponent)],+ ]);+ const props = new Map([+ ["prop-1", createProp("prop-1", "descendant", "selector", " > div")],+ ]);+ const materializedRoots = new Map([+ [+ "root",+ {+ identity: {+ blockInstanceId: "block",+ assetId: "article",+ revision: "sha256:one",+ contentRef: "article.mdx",+ format: "mdx" as const,+ renderScope: "page:/",+ },+ fragment: {+ children: [{ type: "id" as const, value: "descendant" }],+ instances: [],+ props: [],+ assets: [],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ },+ },+ ],+ ]);++ const result = computeDescendantSelectors(+ instances,+ props,+ materializedRoots+ );++ expect(result.get("descendant")).toBe('[data-ws-id="block"] > div');+ });+test("ignores descendant without selector prop", () => {const instances = new Map([[diff --git a/apps/builder/app/canvas/shared/styles.ts b/apps/builder/app/canvas/shared/styles.tsindex 3786e663cf..c54df3cfb8 100644--- a/apps/builder/app/canvas/shared/styles.ts+++ b/apps/builder/app/canvas/shared/styles.ts@@ -33,14 +33,15 @@ import {$selectedStyleState,assetBaseUrl,} from "~/shared/nano-states";-import { $assets } from "~/shared/sync/data-stores";import {- $breakpoints,- $instances,- $props,- $styleSourceSelections,- $styles,-} from "~/shared/sync/data-stores";+ $runtimeAssets as $assets,+ $runtimeBreakpoints as $breakpoints,+ $runtimeInstances as $instances,+ $runtimeProps as $props,+ $runtimeStyleSourceSelections as $styleSourceSelections,+ $runtimeStyles as $styles,+ $activeMaterializedContentRoots,+} from "~/shared/content-block-content";import { setDifference } from "~/shared/shim";import { $ephemeralStyles } from "../stores";import { canvasApi } from "~/shared/canvas-api";@@ -53,6 +54,7 @@ import {findAllNavigableTextInstanceSelectors,type InstanceSelector,} from "@webstudio-is/project-build/runtime";+import type { MaterializedContentRoot } from "@webstudio-is/project-build/runtime";import { getAllElementsByInstanceSelector } from "~/shared/dom-utils";import { createComputedStyleDeclStore } from "~/builder/features/style-panel/shared/model";@@ -314,7 +316,8 @@ const computeDescendantSelectors = <P extends { instanceId: string; name: string; type: string; value?: unknown },>(instances: Map<Instance["id"], Instance>,- props: Map<string, P>+ props: Map<string, P>,+ materializedRoots: ReadonlyMap<string, MaterializedContentRoot> = new Map()) => {const parentIdByInstanceId = new Map<Instance["id"], Instance["id"]>();const descendantInstanceIds: Instance["id"][] = [];@@ -328,6 +331,13 @@ const computeDescendantSelectors = <}}}+ for (const { identity, fragment } of materializedRoots.values()) {+ for (const child of fragment.children) {+ if (child.type === "id") {+ parentIdByInstanceId.set(child.value, identity.blockInstanceId);+ }+ }+ }const descendantSelectorByInstanceId = new Map<Instance["id"], string>();for (const prop of props.values()) {if (prop.name === "selector" && prop.type === "string") {@@ -402,7 +412,7 @@ const getPresetStyleSelector = (component: string, tag: string) =>: `${tag}:where([data-ws-component="${component}"])`;const $descendantSelectors = computed(- [$instances, $props],+ [$instances, $props, $activeMaterializedContentRoots],computeDescendantSelectors);diff --git a/apps/builder/app/canvas/shared/use-drag-drop.ts b/apps/builder/app/canvas/shared/use-drag-drop.tsindex d830fe07dc..f9a62671bc 100644--- a/apps/builder/app/canvas/shared/use-drag-drop.ts+++ b/apps/builder/app/canvas/shared/use-drag-drop.ts@@ -20,7 +20,10 @@ import {$registeredComponentMetas,type ItemDropTarget,} from "~/shared/nano-states";-import { $instances, $props } from "~/shared/sync/data-stores";+import {+ $runtimeInstances as $instances,+ $runtimeProps as $props,+} from "~/shared/content-block-content";import { publish, useSubscribe } from "~/shared/pubsub";import {getElementByInstanceSelector,diff --git a/apps/builder/app/services/api-router.server.ts b/apps/builder/app/services/api-router.server.tsindex 50ce4c5c8b..c2340b0897 100644--- a/apps/builder/app/services/api-router.server.ts+++ b/apps/builder/app/services/api-router.server.ts@@ -40,6 +40,7 @@ import {loadBuilderAssetFieldCatalog,loadAssetDataByProject,loadAssetFoldersByProject,+ PostgresAssetRepository,} from "@webstudio-is/asset-uploader/server";import { buildPatchTransaction } from "@webstudio-is/protocol/schema";import {@@ -57,9 +58,16 @@ import { componentMetas } from "~/shared/component-metas.server";import { type Asset, type AssetFolder } from "@webstudio-is/sdk";import {applyContentModeTransaction,+ computeExpression,+ createContentBlockApplicationOperations,+ createMdxAssetEditingSession,getContentModeCapabilities,} from "@webstudio-is/project-build/runtime";-import type { CompactBuild } from "@webstudio-is/project-build";+import {+ createBuildContentCompilationPlan,+ type CompactBuild,+} from "@webstudio-is/project-build";+import { applyBuilderPatchTransactions } from "@webstudio-is/project-build/state";import {runtimeOperationContracts,type RuntimeOperationId,@@ -464,18 +472,95 @@ const loadRuntimeAssetData = async (ctx: AppContext, projectId: string) => {});};+const createServerContentStorageApplication = async ({+ ctx,+ projectId,+ build,+ assets,+ assetFolders,+ includeMigrationCandidates = false,+}: {+ ctx: AppContext;+ projectId: string;+ build: CompactBuild;+ assets: Asset[];+ assetFolders: AssetFolder[];+ includeMigrationCandidates?: boolean;+}) => {+ let state = createBuilderRuntimeState(build, assets, assetFolders);+ const repository = new PostgresAssetRepository({+ projectId,+ context: ctx,+ assetStore: createAssetClient(),+ });+ const migrationContentArtifact = includeMigrationCandidates+ ? await repository.prepareIndex(createBuildContentCompilationPlan(build))+ : undefined;+ const application = createContentBlockApplicationOperations({+ projectId,+ session: createMdxAssetEditingSession({+ repository,+ authorizeAsset: ({ assetId }) => state.assets?.has(assetId) === true,+ resolveExpressionAssetId: ({ expression, variables: scoped }) => {+ const variables = new Map<string, unknown>();+ for (const dataSource of state.dataSources?.values() ?? []) {+ if (dataSource.type === "variable") {+ variables.set(dataSource.name, dataSource.value.value);+ }+ }+ for (const [name, value] of Object.entries(scoped ?? {})) {+ variables.set(name, value);+ }+ const value = computeExpression(expression, variables);+ return typeof value === "string" && value !== "" ? value : undefined;+ },+ }),+ getState: () => state,+ getProjectVersion: () => build.version,+ migrationContentArtifact,+ context: {+ createId: () => crypto.randomUUID(),+ projectId,+ projectVersion: build.version,+ },+ });+ return {+ application,+ applyProjectPayload: (+ payload: z.infer<typeof buildPatchTransaction>["payload"]+ ) => {+ state = applyBuilderPatchTransactions(state, [+ { id: crypto.randomUUID(), payload },+ ]).state;+ },+ };+};+const runtimeAssetsQuery = <Result = unknown>(id: RuntimeOperationId) =>projectQuery(runtimeProjectInput(id), "view", async ({ ctx, input }) => {const [{ assets, assetFolders }, build] = await Promise.all([loadRuntimeAssetData(ctx, input.projectId),loadDevBuildByProjectId(ctx, input.projectId),]);+ const contentStorageApplication =+ id === "contentBlocks.inspectSource"+ ? (+ await createServerContentStorageApplication({+ ctx,+ projectId: input.projectId,+ build,+ assets,+ assetFolders,+ })+ ).application+ : undefined;return executeApiRuntimeOperation<Result>({id,build,assets,assetFolders,input,+ context: { contentStorageApplication },});});@@ -500,6 +585,52 @@ const runtimeAssetsMutation = <Result extends Record<string, unknown> = {}>(});+const runtimeAssetsApplication = <Result extends Record<string, unknown> = {}>(+ id: RuntimeOperationId+) =>+ contentOrBuildMutation(+ runtimeMutationInput(id, false),+ async ({ ctx, input, build, commit }) => {+ const { assets, assetFolders } = await loadRuntimeAssetData(+ ctx,+ input.projectId+ );+ const storage = await createServerContentStorageApplication({+ ctx,+ projectId: input.projectId,+ build,+ assets,+ assetFolders,+ includeMigrationCandidates:+ id === "contentBlocks.migrateTemplateReferences",+ });+ let version = build.version;+ const result = await executeApiRuntimeOperation<Result>({+ id,+ build,+ assets,+ assetFolders,+ input,+ context: {+ contentStorageApplication: storage.application,+ commitApplicationProjectPayload: async ({+ payload,+ expectedVersion,+ }) => {+ if (expectedVersion !== build.version) {+ throwApiError("CONFLICT", "Project changed after preparation");+ }+ const committed = await commit([...payload]);+ storage.applyProjectPayload([...payload]);+ version = committed.version;+ return { version };+ },+ },+ });+ return { version, ...result };+ }+ );+type RuntimeOperationRouteTree = Record<string, unknown>;type RouterRecord = Parameters<typeof router>[0];type RuntimeOperation = (typeof runtimeOperationContracts)[number];@@ -530,8 +661,11 @@ const addRuntimeOperationRoute = (const createRuntimeOperationProcedure = (operation: RuntimeOperation) => {const { id } = operation;if (operation.requiresAssets) {- return operation.kind === "read"- ? runtimeAssetsQuery(id)+ if (operation.kind === "read") {+ return runtimeAssetsQuery(id);+ }+ return operation.kind === "application"+ ? runtimeAssetsApplication(id): runtimeAssetsMutation(id);}if (operation.kind === "read") {diff --git a/apps/builder/app/services/api-runtime.server.test.ts b/apps/builder/app/services/api-runtime.server.test.tsindex 5e1e043f75..8c8ddfe53f 100644--- a/apps/builder/app/services/api-runtime.server.test.ts+++ b/apps/builder/app/services/api-runtime.server.test.ts@@ -70,6 +70,122 @@ describe("api runtime adapter", () => {).rejects.toThrow("Page not found");});+ test("uses the shared Content Block source application for API inspection", async () => {+ await expect(+ executeApiRuntimeOperation({+ id: "contentBlocks.inspectSource",+ build: createBuild(),+ input: { blockInstanceId: "root-1", renderScope: "page:/" },+ context: {+ contentStorageApplication: {+ getMaterializedContent: () => [],+ preflightStorageChanges: async () => ({ status: "ready" }),+ saveStorageChanges: async () => ({+ status: "complete",+ persistence: {+ status: "complete",+ steps: [],+ retry: { replan: true, roots: [], project: false },+ },+ }),+ inspectSource: async (input) => ({+ ...input,+ sessionStatus: "disconnected",+ pending: false,+ diagnostics: [],+ capabilities: {+ canConnect: true,+ canSwitch: false,+ canDisconnectWithCopy: false,+ canEdit: false,+ canRetry: false,+ canReloadRemote: false,+ canCopyUnsavedSource: false,+ },+ repairRoutes: [],+ }),+ },+ },+ })+ ).resolves.toMatchObject({+ blockInstanceId: "root-1",+ renderScope: "page:/",+ sessionStatus: "disconnected",+ capabilities: { canConnect: true },+ });+ });++ test("uses the per-request API project commit capability for Content Block lifecycle", async () => {+ let committed = false;+ const inspection = {+ blockInstanceId: "root-1",+ renderScope: "page:/",+ sessionStatus: "saved" as const,+ pending: false,+ diagnostics: [],+ capabilities: {+ canConnect: false,+ canSwitch: true,+ canDisconnectWithCopy: true,+ canEdit: true,+ canRetry: false,+ canReloadRemote: false,+ canCopyUnsavedSource: false,+ },+ repairRoutes: ["disconnect-with-copy" as const],+ };+ await expect(+ executeApiRuntimeOperation({+ id: "contentBlocks.connectSource",+ build: createBuild(),+ input: {+ blockInstanceId: "root-1",+ renderScope: "page:/",+ source: { type: "asset", assetId: "article" },+ authority: "use-file-content",+ },+ context: {+ commitApplicationProjectPayload: async ({ expectedVersion }) => {+ expect(expectedVersion).toBe(1);+ committed = true;+ return { version: 2 };+ },+ contentStorageApplication: {+ getMaterializedContent: () => [],+ preflightStorageChanges: async () => ({ status: "ready" }),+ saveStorageChanges: async () => ({+ status: "complete",+ persistence: {+ status: "complete",+ steps: [],+ retry: { replan: true, roots: [], project: false },+ },+ }),+ inspectSource: async () => inspection,+ applyLifecycle: async (_input, execution) => {+ await execution?.commitProjectPayload?.([]);+ return {+ status: "complete",+ result: {+ action: "connect",+ changesProject: true,+ storageWrites: [],+ diagnostics: [],+ persistenceOrder: "none",+ },+ };+ },+ },+ },+ })+ ).resolves.toMatchObject({+ status: "complete",+ source: { renderScope: "page:/" },+ plan: { action: "connect", changesProject: true },+ });+ expect(committed).toBe(true);+ });+test("preserves canonical mutation payloads across the API adapter", async () => {const build = createBuild();const pageId = build.pages.homePageId;diff --git a/apps/builder/app/services/api-runtime.server.ts b/apps/builder/app/services/api-runtime.server.tsindex 9c6602a185..eea4573636 100644--- a/apps/builder/app/services/api-runtime.server.ts+++ b/apps/builder/app/services/api-runtime.server.ts@@ -3,6 +3,7 @@ import type { RuntimeOperationId } from "@webstudio-is/project-build/contracts";import { executeBuilderRuntimeOperation } from "@webstudio-is/project-build/runtime";import { BuilderRuntimeError } from "@webstudio-is/project-build/runtime";import { builderRuntimeContext } from "@webstudio-is/project-build/runtime";+import type { BuilderRuntimeContext } from "@webstudio-is/project-build/runtime";import { type BuilderRuntimeMutation } from "@webstudio-is/project-build/runtime";import type { BuilderState } from "@webstudio-is/project-build/state";import { createBuilderStateFromCompactBuild } from "@webstudio-is/project-build/state";@@ -26,12 +27,14 @@ export const executeApiRuntimeOperation = async <Result>({assets,assetFolders,input,+ context,}: {id: RuntimeOperationId;build: CompactBuild;assets?: Asset[];assetFolders?: AssetFolder[];input: unknown;+ context?: Partial<BuilderRuntimeContext>;}): Promise<Result> => {try {return await executeBuilderRuntimeOperation<Result>({@@ -42,6 +45,7 @@ export const executeApiRuntimeOperation = async <Result>({createId: builderRuntimeContext.createId,projectId: build.projectId,projectVersion: build.version,+ ...context,},});} catch (error) {diff --git a/apps/builder/app/services/asset-rest-content.server.test.ts b/apps/builder/app/services/asset-rest-content.server.test.tsindex cd28a87f6d..f4c51953e0 100644--- a/apps/builder/app/services/asset-rest-content.server.test.ts+++ b/apps/builder/app/services/asset-rest-content.server.test.ts@@ -1,9 +1,14 @@import { describe, expect, test, vi } from "vitest";import type { Asset } from "@webstudio-is/sdk";+import {+ assetContentDescriptorHeader,+ parseAssetContentDescriptor,+} from "@webstudio-is/protocol/asset-resource-api";import {createAssetContentLoader,parseRequestRange,} from "./asset-rest-route-handlers.server";+import { createHttpAssetContentRepository } from "~/builder/shared/assets/mdx-content-repository";const asset: Asset = {id: "asset-1",@@ -59,6 +64,19 @@ describe("Assets REST content download", () => {expect(response.status).toBe(206);expect(response.headers.get("content-range")).toBe("bytes 2-5/10");expect(response.headers.get("content-length")).toBe("4");+ expect(+ parseAssetContentDescriptor(+ response.headers.get(assetContentDescriptorHeader)+ )+ ).toEqual({+ id: asset.id,+ projectId: asset.projectId,+ name: asset.name,+ type: asset.type,+ format: asset.format,+ size: asset.size,+ createdAt: asset.createdAt,+ });expect(await response.text()).toBe("post");expect(readContent).toHaveBeenCalledWith({assetId: "asset-1",@@ -66,4 +84,53 @@ describe("Assets REST content download", () => {asset,});});++ test("provides the same content contract to the browser repository", async () => {+ const bytes = new TextEncoder().encode("# Hello");+ const serverRead = {+ asset: { ...asset, name: "post_revision.mdx", format: "mdx", size: 7 },+ data: {+ async *[Symbol.asyncIterator]() {+ yield bytes;+ },+ },+ contentLength: bytes.byteLength,+ };+ const loader = createAssetContentLoader({+ preventCrossOriginCookie: vi.fn(),+ createRepository: vi.fn(async () => ({+ get: vi.fn(async () => serverRead.asset),+ readContent: vi.fn(async () => serverRead),+ })) as never,+ });+ const browserRepository = createHttpAssetContentRepository({+ projectId: asset.projectId,+ origin: "https://webstudio.is",+ request: async (input, init) =>+ loader({+ request: new Request(input, init),+ params: { assetId: asset.id },+ } as never),+ });++ const browserRead = await browserRepository.readContent({+ assetId: asset.id,+ });+ const chunks = [];+ for await (const chunk of browserRead.data) {+ chunks.push(...chunk);+ }++ expect(browserRead.asset).toEqual({+ id: serverRead.asset.id,+ projectId: serverRead.asset.projectId,+ name: serverRead.asset.name,+ type: serverRead.asset.type,+ format: serverRead.asset.format,+ size: serverRead.asset.size,+ createdAt: serverRead.asset.createdAt,+ });+ expect(new Uint8Array(chunks)).toEqual(bytes);+ expect(browserRead.contentLength).toBe(serverRead.contentLength);+ });});diff --git a/apps/builder/app/services/asset-rest-route-handlers.server.ts b/apps/builder/app/services/asset-rest-route-handlers.server.tsindex 8b0f98031d..863d7a07ab 100644--- a/apps/builder/app/services/asset-rest-route-handlers.server.ts+++ b/apps/builder/app/services/asset-rest-route-handlers.server.ts@@ -7,8 +7,10 @@ import { Readable } from "node:stream";import parseRange from "range-parser";import { getAssetMime } from "@webstudio-is/sdk";import {+ assetContentDescriptorHeader,assetMetadataUpdate,assetResourceApiOperations,+ serializeAssetContentDescriptor,} from "@webstudio-is/protocol/asset-resource-api";import { privateNoStoreResponseHeaders } from "./cache-control.server";import { ensureApiCsrf } from "./api-auth.server";@@ -69,9 +71,13 @@ export const createAssetContentLoader =const range = parseRequestRange(request.headers.get("range"), asset.size);const content = await repository.readContent({ assetId, range, asset });const headers = new Headers(privateNoStoreResponseHeaders);+ headers.set(+ assetContentDescriptorHeader,+ serializeAssetContentDescriptor(content.asset)+ );headers.set("content-type",- getAssetMime(asset) ?? "application/octet-stream"+ getAssetMime(content.asset) ?? "application/octet-stream");headers.set("accept-ranges", "bytes");headers.set(diff --git a/apps/builder/app/services/project-import.server.test.ts b/apps/builder/app/services/project-import.server.test.tsindex eb72ebdc9f..dad288b87d 100644--- a/apps/builder/app/services/project-import.server.test.ts+++ b/apps/builder/app/services/project-import.server.test.ts@@ -4,6 +4,7 @@ import {createPageFixture,createPublishedProjectBundleFixture,} from "@webstudio-is/protocol/fixtures";+import { blockComponent } from "@webstudio-is/sdk";import { type PublishedProjectBundle } from "@webstudio-is/protocol";import { createAssetRows } from "@webstudio-is/asset-uploader/server";import {@@ -218,6 +219,50 @@ describe("build import helpers", () => {);});+ test("rejects imported Content Blocks with missing source Assets", async () => {+ const data = createData({ assets: [] });+ data.build.instances = [+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [],+ },+ ],+ ];+ data.build.props = [+ [+ "source",+ {+ id: "source",+ instanceId: "block",+ name: "src",+ type: "asset",+ value: "missing-post",+ },+ ],+ ];+ const calls: string[] = [];++ await expect(+ importPublishedProjectBundle(+ {+ ctx: {+ postgrest: { client: createPostgrestClient(calls) },+ } as never,+ data,+ projectId: "target-project",+ },+ { hasProjectPermit, loadDevBuildByProjectId }+ )+ ).rejects.toThrow(+ 'Cannot import: Content Block source prop "source" references missing Asset "missing-post".'+ );+ expect(calls).toEqual([]);+ });+test("serializes imported build data into compact build columns", () => {const update = createBuildImportUpdate({data: createData(),diff --git a/apps/builder/app/services/project-import.server.ts b/apps/builder/app/services/project-import.server.tsindex 1fb0579261..956631f2bf 100644--- a/apps/builder/app/services/project-import.server.ts+++ b/apps/builder/app/services/project-import.server.ts@@ -22,6 +22,7 @@ import {createProjectSettingsFromPages,removeLegacyProjectSettingsFromPages,} from "@webstudio-is/project-build";+import { assertContentBlockSourceIntegrity } from "@webstudio-is/project-build/runtime";import {isAssetFileName,getMissingImportedAssetFilesMessage,@@ -332,6 +333,15 @@ export const importPublishedProjectBundle = async (const { assets: importedAssets, folders: importedAssetFolders } =normalizeImportedAssetFolderData(data.assetFolders ?? [], data.assets);+ assertContentBlockSourceIntegrity(+ {+ props: data.build.props.map(([, value]) => value),+ instances: data.build.instances.map(([, value]) => value),+ assets: importedAssets,+ },+ { messagePrefix: "Cannot import" }+ );+await assertImportedAssetFilesUploaded({assets: importedAssets,ctx,diff --git a/apps/builder/app/shared/asset-content-bridge.client.test.ts b/apps/builder/app/shared/asset-content-bridge.client.test.tsnew file mode 100644index 0000000000..8370611da5--- /dev/null+++ b/apps/builder/app/shared/asset-content-bridge.client.test.ts@@ -0,0 +1,103 @@+import { expect, test, vi } from "vitest";+import { contentEngineLimits } from "@webstudio-is/content-engine/limits";+import { createAssetContentBridge } from "./asset-content-bridge.client";++const origin = "https://builder.example";+const contentUrl = `${origin}/rest/assets/asset-1/content?projectId=project-1`;++const createBridge = ({+ authorized = true,+}: {+ authorized?: boolean;+} = {}) => {+ const request = vi.fn(async () => new Response("ok"));+ const authorize = vi.fn(() => authorized);+ return {+ bridge: createAssetContentBridge({ origin, request, authorize }),+ request,+ authorize,+ };+};++test("forwards only an authorized Asset content request", async () => {+ const { bridge, request, authorize } = createBridge();++ await expect(bridge.request(contentUrl)).resolves.toBeInstanceOf(Response);++ expect(authorize).toHaveBeenCalledWith({+ projectId: "project-1",+ assetId: "asset-1",+ operation: "read",+ });+ expect(request).toHaveBeenCalledTimes(1);+});++test("forwards a bounded authorized write", async () => {+ const { bridge, request, authorize } = createBridge();++ await expect(+ bridge.request(`${contentUrl}&expectedName=article.mdx`, {+ method: "PUT",+ headers: { "content-type": "application/octet-stream" },+ body: new TextEncoder().encode("# Updated"),+ })+ ).resolves.toBeInstanceOf(Response);++ expect(authorize).toHaveBeenCalledWith({+ projectId: "project-1",+ assetId: "asset-1",+ operation: "write",+ });+ expect(request).toHaveBeenCalledTimes(1);+});++const rejectedRequests: ReadonlyArray<{+ name: string;+ url: string;+ init?: RequestInit;+}> = [+ {+ name: "another origin",+ url: "https://attacker.example/rest/assets/asset-1/content?projectId=project-1",+ },+ {+ name: "another route",+ url: `${origin}/rest/assets/asset-1?projectId=project-1`,+ },+ {+ name: "an unsupported method",+ url: contentUrl,+ init: { method: "DELETE" },+ },+ {+ name: "an unknown query",+ url: `${contentUrl}&redirect=https://attacker.example`,+ },+];++test.each(rejectedRequests)("rejects $name", async ({ url, init }) => {+ const { bridge, request } = createBridge();++ await expect(bridge.request(url, init)).rejects.toThrow();+ expect(request).not.toHaveBeenCalled();+});++test("enforces project and Asset authorization inside the request path", async () => {+ const { bridge, request } = createBridge({ authorized: false });++ await expect(bridge.request(contentUrl)).rejects.toThrow("not authorized");+ expect(request).not.toHaveBeenCalled();+});++test("bounds Asset content writes before forwarding them", async () => {+ const { bridge, request } = createBridge();++ await expect(+ bridge.request(`${contentUrl}&expectedName=article.mdx`, {+ method: "PUT",+ headers: { "content-type": "application/octet-stream" },+ body: new Uint8Array(contentEngineLimits.hydratedFileBytes + 1),+ })+ ).rejects.toThrow("exceeds");+ expect(request).not.toHaveBeenCalled();+});diff --git a/apps/builder/app/shared/asset-content-bridge.client.ts b/apps/builder/app/shared/asset-content-bridge.client.tsnew file mode 100644index 0000000000..702dfcef68--- /dev/null+++ b/apps/builder/app/shared/asset-content-bridge.client.ts@@ -0,0 +1,125 @@+import { contentEngineLimits } from "@webstudio-is/content-engine/limits";++export type AssetContentAuthorization = Readonly<{+ projectId: string;+ assetId: string;+ identityAssetId?: string;+ operation: "read" | "write";+}>;++export type AssetContentBridge = Readonly<{+ request: (input: string, init?: RequestInit) => Promise<Response>;+ authorize: (input: AssetContentAuthorization) => boolean;+}>;++const namespace = "__webstudio__$__assetContentBridge";++export const createAssetContentBridge = ({+ origin,+ request,+ authorize,+}: {+ origin: string;+ request: (input: string, init?: RequestInit) => Promise<Response>;+ authorize: (input: AssetContentAuthorization) => boolean;+}): AssetContentBridge => ({+ authorize,+ request: async (input, init) => {+ const url = new URL(input, origin);+ const method = init?.method?.toUpperCase() ?? "GET";+ const [, rest, assets, encodedAssetId, content, ...extraPath] =+ url.pathname.split("/");+ if (+ url.origin !== origin ||+ rest !== "rest" ||+ assets !== "assets" ||+ encodedAssetId === undefined ||+ encodedAssetId === "" ||+ content !== "content" ||+ extraPath.length !== 0 ||+ (method !== "GET" && method !== "PUT")+ ) {+ throw new Error("Only same-origin Asset content requests are allowed");+ }+ let assetId: string;+ try {+ assetId = decodeURIComponent(encodedAssetId);+ } catch {+ throw new Error("Asset content request has an invalid Asset id");+ }+ const projectIds = url.searchParams.getAll("projectId");+ const expectedNames = url.searchParams.getAll("expectedName");+ const allowedQueryNames =+ method === "GET"+ ? new Set(["projectId"])+ : new Set(["projectId", "expectedName"]);+ if (+ projectIds.length !== 1 ||+ projectIds[0] === "" ||+ expectedNames.length !== (method === "PUT" ? 1 : 0) ||+ (method === "PUT" && expectedNames[0] === "") ||+ [...url.searchParams.keys()].some(+ (name) => allowedQueryNames.has(name) === false+ )+ ) {+ throw new Error("Asset content request has invalid parameters");+ }+ const operation = method === "PUT" ? "write" : "read";+ if (+ authorize({+ projectId: projectIds[0],+ assetId,+ operation,+ }) === false+ ) {+ throw new Error("Asset content request is not authorized");+ }+ if (method === "GET") {+ if (init?.body != null) {+ throw new Error("Asset content reads cannot include a body");+ }+ return await request(url.href, init);+ }+ const headers = new Headers(init?.headers);+ if (headers.get("content-type") !== "application/octet-stream") {+ throw new Error("Asset content writes require binary content");+ }+ const body = init?.body;+ const byteLength =+ typeof body === "string"+ ? new TextEncoder().encode(body).byteLength+ : body instanceof Blob+ ? body.size+ : body instanceof ArrayBuffer+ ? body.byteLength+ : ArrayBuffer.isView(body)+ ? body.byteLength+ : undefined;+ if (byteLength === undefined) {+ throw new Error("Asset content writes require a bounded body");+ }+ if (byteLength > contentEngineLimits.hydratedFileBytes) {+ throw new Error("Asset content write exceeds the MDX editing limit");+ }+ return await request(url.href, init);+ },+});++declare global {+ interface Window {+ [namespace]?: AssetContentBridge;+ }+}++export const initAssetContentBridge = (bridge: AssetContentBridge) => {+ window[namespace] = bridge;+};++export const getAssetContentBridge = () => {+ const owner = window.self === window.top ? window : window.top;+ const bridge = owner?.[namespace];+ if (bridge === undefined) {+ throw new Error("Builder Asset content bridge is not available");+ }+ return bridge;+};diff --git a/apps/builder/app/shared/builder-api.ts b/apps/builder/app/shared/builder-api.tsindex f5fde02d4e..a6502a64cc 100644--- a/apps/builder/app/shared/builder-api.ts+++ b/apps/builder/app/shared/builder-api.ts@@ -5,6 +5,13 @@ import { uploadAssets } from "~/builder/shared/assets/upload-assets";import { showTokenConflictDialog } from "./token-conflict-dialog";import { showRootStyleConflictDialog } from "./root-style-conflict-dialog";import { showDesignTokenImportDialog } from "./design-token-import-dialog";+import { fetch as builderFetch } from "./fetch.client";+import { $assets, $project } from "./sync/data-stores";+import { $authPermit } from "./nano-states";+import {+ createAssetContentBridge,+ initAssetContentBridge,+} from "./asset-content-bridge.client";const apiWindowNamespace = "__webstudio__$__builderApi";@@ -17,6 +24,27 @@ const isSafeMode = (() => {return new URLSearchParams(window.location.search).get("safemode") === "true";})();+const authorizeAssetContent = ({+ projectId,+ assetId,+ identityAssetId,+ operation,+}: {+ projectId: string;+ assetId: string;+ identityAssetId?: string;+ operation: "read" | "write";+}) => {+ const asset = $assets.get().get(assetId);+ return (+ $project.get()?.id === projectId &&+ asset?.projectId === projectId &&+ asset.format === "mdx" &&+ (identityAssetId === undefined || identityAssetId === assetId) &&+ (operation === "read" || $authPermit.get() !== "view")+ );+};+const _builderApi = {isInitialized: () => true,isSafeMode: () => isSafeMode,@@ -117,6 +145,13 @@ export const builderApi = createRecursiveProxy((options) => {export const initBuilderApi = () => {if (isInTop()) {window[apiWindowNamespace] = _builderApi;+ initAssetContentBridge(+ createAssetContentBridge({+ origin: window.location.origin,+ request: (input, init) => builderFetch(input, init),+ authorize: authorizeAssetContent,+ })+ );}return () => {};};diff --git a/apps/builder/app/shared/commands-emitter.test.ts b/apps/builder/app/shared/commands-emitter.test.tsindex 3773ed7be4..4e09f597b5 100644--- a/apps/builder/app/shared/commands-emitter.test.ts+++ b/apps/builder/app/shared/commands-emitter.test.ts@@ -122,4 +122,55 @@ describe("createCommandsEmitter", () => {expect(calls).toEqual(["canvas"]);});++ test("leaves undo shortcuts inside editable controls to the editor", () => {+ const handler = vi.fn();+ const { subscribeCommands } = createCommandsEmitter({+ source: "builder",+ commands: [+ {+ name: "undo",+ handler,+ defaultHotkeys: ["ctrl+z"],+ disableOnInputLikeControls: true,+ },+ ],+ });+ const unsubscribe = subscribeCommands();+ const editable = document.createElement("div");+ editable.contentEditable = "true";+ Object.defineProperty(editable, "isContentEditable", { value: true });+ const input = document.createElement("input");+ const textarea = document.createElement("textarea");+ for (const control of [editable, input, textarea]) {+ document.body.appendChild(control);+ const editorEvent = new KeyboardEvent("keydown", {+ key: "z",+ ctrlKey: true,+ bubbles: true,+ cancelable: true,+ });+ control.dispatchEvent(editorEvent);+ expect(handler).not.toHaveBeenCalled();+ expect(editorEvent.defaultPrevented).toBe(false);+ }++ const regular = document.createElement("div");+ document.body.appendChild(regular);+ const appEvent = new KeyboardEvent("keydown", {+ key: "z",+ ctrlKey: true,+ bubbles: true,+ cancelable: true,+ });+ regular.dispatchEvent(appEvent);++ expect(handler).toHaveBeenCalledOnce();+ expect(appEvent.defaultPrevented).toBe(true);+ unsubscribe();+ editable.remove();+ input.remove();+ textarea.remove();+ regular.remove();+ });});diff --git a/apps/builder/app/shared/content-block-content.test.ts b/apps/builder/app/shared/content-block-content.test.tsnew file mode 100644index 0000000000..733ecb4942--- /dev/null+++ b/apps/builder/app/shared/content-block-content.test.ts@@ -0,0 +1,678 @@+import { afterEach, expect, test } from "vitest";+import type { Project } from "@webstudio-is/project";+import type { MaterializedMdxAuthoredContentRoot } from "@webstudio-is/project-build/runtime";+import {+ blockComponent,+ blockTemplateComponent,+ elementComponent,+ type ContentBlockExternalContentIdentity,+ type WebstudioFragment,+} from "@webstudio-is/sdk";+import {+ $instances,+ $project,+ $props,+ $assets,+ $breakpoints,+ $dataSources,+ $resources,+ $styleSourceSelections,+ $styleSources,+ $styles,+ resetDataStores,+} from "./sync/data-stores";+import {+ $contentBlockPresentationItems,+ $materializedContentViewStates,+ $runtimeInstances,+ formatContentBlockDiagnostic,+ getMaterializedInstanceEditability,+ getMaterializedContentViewStateFromSession,+ getRuntimeInstanceChildren,+ publishMaterializedContentRoot,+ publishMaterializedContentSessionState,+ $materializedContentRoots,+ resetMaterializedContent,+ setMaterializedContentStatus,+ setContentBlockSourceSwitching,+ takeNewContentBlockDiagnostics,+} from "./content-block-content";++const identity = (+ renderScope: string+): ContentBlockExternalContentIdentity => ({+ blockInstanceId: "block",+ assetId: renderScope,+ revision: `sha256:${renderScope}`,+ contentRef: `${renderScope}.mdx`,+ format: "mdx",+ renderScope,+});++const fragment = (id: string): WebstudioFragment => ({+ children: [{ type: "id", value: id }],+ instances: [+ {+ type: "instance",+ id,+ component: elementComponent,+ tag: "p",+ children: [{ type: "text", value: id }],+ },+ ],+ props: [],+ assets: [],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+});++afterEach(() => {+ resetMaterializedContent();+ resetDataStores();+ $project.set(undefined);+});++test("projects repeated MDX roots by selector without changing persisted instances", () => {+ $project.set({ id: "project" } as Project);+ const persistedBlock = {+ type: "instance" as const,+ id: "block",+ component: blockComponent,+ children: [{ type: "id" as const, value: "templates" }],+ };+ $instances.set(+ new Map([+ [persistedBlock.id, persistedBlock],+ [+ "templates",+ {+ type: "instance" as const,+ id: "templates",+ component: blockTemplateComponent,+ children: [],+ },+ ],+ ])+ );+ $props.set(+ new Map([+ [+ "source",+ {+ id: "source",+ instanceId: "block",+ name: "src",+ type: "expression" as const,+ value: "article",+ },+ ],+ ])+ );+ $assets.set(new Map());+ $breakpoints.set(new Map());+ $dataSources.set(new Map());+ $resources.set(new Map());+ $styleSourceSelections.set(new Map());+ $styleSources.set(new Map());+ $styles.set(new Map());+ const firstScope = JSON.stringify(["block", "collection[0]"]);+ const secondScope = JSON.stringify(["block", "collection[1]"]);+ publishMaterializedContentRoot({+ identity: identity(firstScope),+ fragment: fragment("first-content"),+ });+ publishMaterializedContentRoot({+ identity: identity(secondScope),+ fragment: fragment("second-content"),+ });++ const runtimeBlock = $runtimeInstances.get().get("block");+ if (runtimeBlock === undefined) {+ throw new Error("Expected projected Content Block");+ }+ expect($runtimeInstances.get().has("first-content")).toBe(true);+ expect($runtimeInstances.get().has("second-content")).toBe(true);+ expect(+ getRuntimeInstanceChildren(runtimeBlock, ["block", "collection[0]"])+ ).toEqual([+ { type: "id", value: "templates" },+ { type: "id", value: "first-content" },+ ]);+ expect(+ getRuntimeInstanceChildren(runtimeBlock, ["block", "collection[1]"])+ ).toEqual([+ { type: "id", value: "templates" },+ { type: "id", value: "second-content" },+ ]);+ expect($instances.get()).toEqual(+ new Map([+ [persistedBlock.id, persistedBlock],+ [+ "templates",+ {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [],+ },+ ],+ ])+ );++ $props.set(+ new Map([+ [+ "source",+ {+ id: "source",+ instanceId: "block",+ name: "src",+ type: "asset",+ value: "replacement",+ },+ ],+ ])+ );+ expect($runtimeInstances.get().has("first-content")).toBe(true);++ $props.set(new Map());+ expect($runtimeInstances.get().has("first-content")).toBe(false);+ expect($runtimeInstances.get().get("block")?.children).toEqual([+ { type: "id", value: "templates" },+ ]);++ $props.set(+ new Map([+ [+ "source",+ {+ id: "source",+ instanceId: "block",+ name: "src",+ type: "expression",+ value: "article",+ },+ ],+ ])+ );+ publishMaterializedContentRoot({+ identity: identity(firstScope),+ fragment: fragment("first-content"),+ });+ expect($runtimeInstances.get().has("first-content")).toBe(true);++ $project.set({ id: "other-project" } as Project);+ expect($runtimeInstances.get().has("first-content")).toBe(false);+});++test("keeps previous materialized content read-only while its source switches", () => {+ $project.set({ id: "project" } as Project);+ const renderScope = JSON.stringify(["block"]);+ const block = {+ type: "instance" as const,+ id: "block",+ component: blockComponent,+ children: [{ type: "id" as const, value: "templates" }],+ };+ $instances.set(+ new Map([+ [block.id, block],+ [+ "templates",+ {+ type: "instance" as const,+ id: "templates",+ component: blockTemplateComponent,+ children: [],+ },+ ],+ ])+ );+ $props.set(+ new Map([+ [+ "source",+ {+ id: "source",+ instanceId: block.id,+ name: "src",+ type: "asset" as const,+ value: "source",+ },+ ],+ ])+ );+ publishMaterializedContentRoot({+ identity: identity(renderScope),+ fragment: fragment("content"),+ });+ const input = {+ instanceSelector: ["content", "block"],+ instances: $runtimeInstances.get(),+ };++ expect(getMaterializedInstanceEditability(input)).toBe(true);+ setContentBlockSourceSwitching({+ blockInstanceId: block.id,+ renderScope,+ switching: true,+ });+ expect(getMaterializedInstanceEditability(input)).toBe(false);+ setContentBlockSourceSwitching({+ blockInstanceId: block.id,+ renderScope,+ switching: false,+ });+ expect(getMaterializedInstanceEditability(input)).toBe(true);+});++test("projects selectable Builder-only loading and unresolved-template notices per exact scope", () => {+ $project.set({ id: "project" } as Project);+ const block = {+ type: "instance" as const,+ id: "block",+ component: blockComponent,+ children: [{ type: "id" as const, value: "templates" }],+ };+ $instances.set(+ new Map([+ [block.id, block],+ [+ "templates",+ {+ type: "instance" as const,+ id: "templates",+ component: blockTemplateComponent,+ children: [],+ },+ ],+ ])+ );+ $props.set(+ new Map([+ [+ "source",+ {+ id: "source",+ instanceId: "block",+ name: "src",+ type: "asset" as const,+ value: "article",+ },+ ],+ ])+ );+ const renderScope = JSON.stringify(["block", "collection[1]"]);+ setMaterializedContentStatus({+ blockInstanceId: "block",+ renderScope,+ status: "loading",+ });++ const loadingChildren = getRuntimeInstanceChildren(block, [+ "block",+ "collection[1]",+ ]);+ const loadingId = loadingChildren.at(-1)?.value;+ expect(+ $contentBlockPresentationItems.get().get(loadingId ?? "")+ ).toMatchObject({+ blockInstanceId: "block",+ renderScope,+ kind: "loading",+ label: "Loading MDX",+ });+ expect($instances.get().has(loadingId ?? "")).toBe(false);+ $instances.set(+ new Map($instances.get()).set(loadingId ?? "", {+ type: "instance",+ id: loadingId ?? "",+ component: elementComponent,+ tag: "div",+ children: [],+ })+ );+ const collisionSafeLoadingId = getRuntimeInstanceChildren(block, [+ "block",+ "collection[1]",+ ]).at(-1)?.value;+ expect(collisionSafeLoadingId).toBe(`${loadingId}-1`);+ expect(+ $contentBlockPresentationItems.get().get(collisionSafeLoadingId ?? "")+ ).toMatchObject({ kind: "loading" });+ const otherRenderScope = JSON.stringify(["block", "collection[2]"]);+ setMaterializedContentStatus({+ blockInstanceId: "block",+ renderScope: otherRenderScope,+ status: "loading",+ });+ const otherLoadingId = getRuntimeInstanceChildren(block, [+ "block",+ "collection[2]",+ ]).at(-1)?.value;+ expect(otherLoadingId).not.toBe(loadingId);+ expect(+ getRuntimeInstanceChildren(block, ["block", "collection[1]"])+ ).not.toContainEqual({ type: "id", value: otherLoadingId });++ const diagnostic = {+ code: "unresolved-template" as const,+ severity: "warning" as const,+ blockInstanceId: "block",+ assetId: "article",+ contentRef: "article.mdx",+ renderScope,+ templateName: "Hero Card",+ sourceRange: {+ start: { line: 4, column: 2 },+ end: { line: 4, column: 35 },+ },+ };+ publishMaterializedContentRoot(+ { identity: identity(renderScope), fragment: fragment("content") },+ [diagnostic]+ );+ const warningChildren = getRuntimeInstanceChildren(block, [+ "block",+ "collection[1]",+ ]);+ const warningId = warningChildren.at(-1)?.value;+ expect(+ $contentBlockPresentationItems.get().get(warningId ?? "")+ ).toMatchObject({+ kind: "warning",+ label: "Missing template: Hero Card",+ message:+ 'Template "Hero Card" is not available and was skipped. Line 4, column 2.',+ });+ expect(+ $materializedContentViewStates+ .get()+ .get(JSON.stringify(["block", renderScope]))+ ).toMatchObject({ status: "ready", diagnostics: [diagnostic] });+ expect($instances.get()).not.toBe($runtimeInstances.get());+ expect($instances.get().has(warningId ?? "")).toBe(false);+});++test("projects duplicate unresolved templates at their exact nested authored positions", () => {+ $project.set({ id: "project" } as Project);+ const block = {+ type: "instance" as const,+ id: "block",+ component: blockComponent,+ children: [{ type: "id" as const, value: "templates" }],+ };+ const wrapper = {+ type: "instance" as const,+ id: "wrapper",+ component: elementComponent,+ tag: "div",+ children: [+ { type: "text" as const, value: "Before" },+ { type: "text" as const, value: "After" },+ ],+ };+ $instances.set(+ new Map([+ [block.id, block],+ [+ "templates",+ {+ type: "instance" as const,+ id: "templates",+ component: blockTemplateComponent,+ children: [],+ },+ ],+ ])+ );+ $props.set(+ new Map([+ [+ "source",+ {+ id: "source",+ instanceId: "block",+ name: "src",+ type: "asset" as const,+ value: "article",+ },+ ],+ ])+ );+ const renderScope = JSON.stringify(["block"]);+ const makeDiagnostic = (line: number) => ({+ code: "unresolved-template" as const,+ severity: "warning" as const,+ blockInstanceId: "block",+ assetId: "article",+ contentRef: "article.mdx",+ renderScope,+ templateName: "Card",+ sourceRange: {+ start: { line, column: 1 },+ end: { line, column: 20 },+ },+ });+ const root: MaterializedMdxAuthoredContentRoot = {+ identity: identity(renderScope),+ fragment: {+ ...fragment("unused"),+ children: [{ type: "id", value: wrapper.id }],+ instances: [wrapper],+ },+ document: {+ frontmatter: { properties: {} },+ children: [+ {+ type: "element",+ syntax: "mdx",+ tag: "div",+ props: [],+ mdxMode: "flow",+ children: [+ { type: "text", value: "Before" },+ {+ type: "template",+ name: "Card",+ props: [],+ children: [],+ mdxMode: "flow",+ },+ {+ type: "template",+ name: "Card",+ props: [],+ children: [],+ mdxMode: "flow",+ },+ { type: "text", value: "After" },+ ],+ },+ ],+ },+ provenance: {+ nodes: [+ {+ type: "element",+ path: [0],+ instanceId: wrapper.id,+ assetProps: [],+ },+ ],+ unresolvedTemplates: [+ {+ path: [0, 1],+ markerId: "first-card",+ templateName: "Card",+ },+ {+ path: [0, 2],+ markerId: "second-card",+ templateName: "Card",+ },+ ],+ },+ };+ publishMaterializedContentRoot(root, [makeDiagnostic(2), makeDiagnostic(3)]);++ const children = getRuntimeInstanceChildren(wrapper, ["block"]);+ const firstWarningId = children[1]?.type === "id" ? children[1].value : "";+ const secondWarningId = children[2]?.type === "id" ? children[2].value : "";+ expect(children).toEqual([+ { type: "text", value: "Before" },+ { type: "id", value: firstWarningId },+ { type: "id", value: secondWarningId },+ { type: "text", value: "After" },+ ]);+ expect(firstWarningId).not.toBe(secondWarningId);+ expect(+ $contentBlockPresentationItems.get().get(firstWarningId ?? "")+ ).toMatchObject({ diagnostic: { sourceRange: { start: { line: 2 } } } });+ expect(+ $contentBlockPresentationItems.get().get(secondWarningId ?? "")+ ).toMatchObject({ diagnostic: { sourceRange: { start: { line: 3 } } } });+ expect($instances.get().has(firstWarningId ?? "")).toBe(false);+ expect($instances.get().has(secondWarningId ?? "")).toBe(false);+});++test("formats and deduplicates diagnostics by revision without losing detail", () => {+ const diagnostic = {+ code: "ignored-template-prop" as const,+ severity: "warning" as const,+ blockInstanceId: "block",+ assetId: "article",+ contentRef: "article.mdx",+ renderScope: "scope",+ templateName: "Hero",+ propName: "tone",+ reason: "design-only" as const,+ sourceRange: {+ start: { line: 2, column: 3 },+ end: { line: 2, column: 12 },+ },+ };+ expect(formatContentBlockDiagnostic(diagnostic)).toBe(+ 'Property "tone" on template "Hero" was ignored because it is design only. Line 2, column 3.'+ );+ expect(takeNewContentBlockDiagnostics([diagnostic], "sha256:one")).toEqual([+ diagnostic,+ ]);+ expect(takeNewContentBlockDiagnostics([diagnostic], "sha256:one")).toEqual(+ []+ );+ expect(takeNewContentBlockDiagnostics([diagnostic], "sha256:two")).toEqual([+ diagnostic,+ ]);+});++test("maps empty, unsafe, conflict, and recoverable session states without storing errors", () => {+ const root = {+ identity: identity("scope"),+ fragment: { ...fragment("content"), children: [] },+ document: { frontmatter: { properties: {} }, children: [] },+ provenance: { nodes: [], unresolvedTemplates: [] },+ };+ expect(+ getMaterializedContentViewStateFromSession({+ status: "saved",+ key: "saved",+ identity: root.identity,+ root,+ source: "",+ diagnostics: [],+ })+ ).toMatchObject({ status: "empty", diagnostics: [] });+ const unsafe = {+ code: "unsafe-mdx" as const,+ severity: "error" as const,+ blockInstanceId: "block",+ assetId: "article",+ contentRef: "article.mdx",+ renderScope: "scope",+ nodeType: "mdxFlowExpression",+ reason: "Executable expressions are not allowed",+ };+ expect(+ getMaterializedContentViewStateFromSession({+ status: "recoverable",+ key: "recoverable",+ identity: root.identity,+ diagnostics: [unsafe],+ error: new Error("private parser detail"),+ })+ ).toEqual({+ status: "recoverable",+ identity: root.identity,+ assetId: root.identity.assetId,+ diagnostics: [unsafe],+ hasUnsavedSource: false,+ message:+ "The MDX file could not be rendered. Open the file to repair it, then retry.",+ });+ expect(+ getMaterializedContentViewStateFromSession({+ status: "conflicting",+ key: "conflict",+ identity: root.identity,+ diagnostics: [],+ })+ ).toMatchObject({+ status: "conflicting",+ hasUnsavedSource: false,+ });+});++test("keeps pending and conflicting local MDX visible without marking it editable", () => {+ const renderScope = "scope";+ const root = {+ identity: identity(renderScope),+ fragment: fragment("pending-content"),+ document: { frontmatter: { properties: {} }, children: [] },+ provenance: { nodes: [], unresolvedTemplates: [] },+ };+ const sessionBase = {+ key: "pending",+ identity: root.identity,+ root,+ source: "Before",+ localSource: "After",+ writes: [],+ diagnostics: [],+ };+ publishMaterializedContentSessionState({+ blockInstanceId: "block",+ renderScope,+ state: { ...sessionBase, status: "pending" },+ });+ expect(+ $materializedContentRoots.get().get(JSON.stringify(["block", renderScope]))+ ).toBe(root);+ expect(+ $materializedContentViewStates+ .get()+ .get(JSON.stringify(["block", renderScope]))+ ).toMatchObject({ status: "pending", hasUnsavedSource: true });++ publishMaterializedContentSessionState({+ blockInstanceId: "block",+ renderScope,+ state: {+ ...sessionBase,+ status: "conflicting",+ error: new Error("remote conflict"),+ },+ });+ expect(+ $materializedContentRoots.get().get(JSON.stringify(["block", renderScope]))+ ).toBe(root);+ expect(+ $materializedContentViewStates+ .get()+ .get(JSON.stringify(["block", renderScope]))+ ).toMatchObject({ status: "conflicting", hasUnsavedSource: true });+});diff --git a/apps/builder/app/shared/content-block-content.ts b/apps/builder/app/shared/content-block-content.tsnew file mode 100644index 0000000000..bc9d2ad175--- /dev/null+++ b/apps/builder/app/shared/content-block-content.ts@@ -0,0 +1,1227 @@+import { atom, computed } from "nanostores";+import hash from "@emotion/hash";+import { toast } from "@webstudio-is/design-system";+import type { MdxAuthoredNode } from "@webstudio-is/content-engine/mdx";+import {+ createContentStorageSelectorProjection,+ applyMdxContentStorageChanges,+ executeContentBlockPersistencePlan,+ findBlockSelector,+ getContentBlockRenderScopeKey,+ getContentStorageIdentityKey,+ type ContentStorageChange,+ type ContentBlockPersistenceResult,+ type InstanceSelector,+ type MaterializedContentRoot,+ type MaterializedMdxAuthoredContentRoot,+ type MdxAssetEditingSessionState,+} from "@webstudio-is/project-build/runtime";+import type {+ Asset,+ Breakpoint,+ ContentBlockDiagnostic,+ ContentBlockExternalContentIdentity,+ DataSource,+ Instance,+ Instances,+ Prop,+ Resource,+ StyleDecl,+ StyleSource,+ StyleSourceSelection,+} from "@webstudio-is/sdk";+import {+ blockTemplateComponent,+ getContentBlockSource,+} from "@webstudio-is/sdk";+import {+ $assets,+ $breakpoints,+ $dataSources,+ $instances,+ $project,+ $props,+ $resources,+ $styleSourceSelections,+ $styleSources,+ $styles,+ readBuilderStateStores,+} from "./sync/data-stores";++type StorageSaveResult =+ | Readonly<{+ status: "applied";+ persistence?: ContentBlockPersistenceResult;+ }>+ | Readonly<{+ status: "blocked" | "partial";+ message: string;+ persistence?: ContentBlockPersistenceResult;+ }>;++type StorageSaver = (+ changes: readonly ContentStorageChange[]+) => Promise<StorageSaveResult>;++type StorageSaverEntry = {+ preflight: StorageSaver;+ save: StorageSaver;+ isCurrent: (root: MaterializedContentRoot) => boolean;+};++type ContentBlockPresentationActions = Readonly<{+ retry: () => Promise<StorageSaveResult>;+ reloadRemote: () => Promise<StorageSaveResult>;+ copyUnsavedSource: () => string | undefined;+}>;++export type MaterializedContentViewState = Readonly<{+ status:+ | "loading"+ | "ready"+ | "empty"+ | "pending"+ | "failed"+ | "recoverable"+ | "conflicting"+ | "cancelled";+ diagnostics: readonly ContentBlockDiagnostic[];+ identity?: ContentBlockExternalContentIdentity;+ assetId?: Asset["id"];+ message?: string;+ hasUnsavedSource?: boolean;+}>;++export const contentBlockPresentationComponent = "ws:content-presentation";++export type ContentBlockPresentationItem = Readonly<{+ id: Instance["id"];+ blockInstanceId: Instance["id"];+ renderScope: string;+ kind: "loading" | "empty" | "error" | "warning";+ status: MaterializedContentViewState["status"];+ label: string;+ message: string;+ diagnostic?: ContentBlockDiagnostic;+ assetId?: Asset["id"];+}>;++export const $materializedContentRoots = atom<+ ReadonlyMap<string, MaterializedContentRoot>+>(new Map());+export const $materializedContentViewStates = atom<+ ReadonlyMap<string, MaterializedContentViewState>+>(new Map());+const $switchingContentScopes = atom<ReadonlySet<string>>(new Set());+export const $materializedContentStatuses = computed(+ [$materializedContentViewStates, $switchingContentScopes],+ (states, switchingScopes) =>+ new Map(+ Array.from(states, ([key, state]) => [+ key,+ switchingScopes.has(key)+ ? ("loading" as const)+ : state.status === "ready" || state.status === "empty"+ ? ("ready" as const)+ : state.status === "loading" || state.status === "pending"+ ? ("loading" as const)+ : ("failed" as const),+ ])+ )+);++export const $activeMaterializedContentRoots = computed(+ [$materializedContentRoots, $instances, $props],+ (materializedRoots, instances, props) => {+ const attachedBlocks = new Map<string, boolean>();+ return new Map(+ Array.from(materializedRoots).filter(([, { identity }]) => {+ const cached = attachedBlocks.get(identity.blockInstanceId);+ if (cached !== undefined) {+ return cached;+ }+ const block = instances.get(identity.blockInstanceId);+ if (block === undefined) {+ attachedBlocks.set(identity.blockInstanceId, false);+ return false;+ }+ if (+ getContentBlockSource({+ blockInstanceId: block.id,+ props: props.values(),+ }) === undefined+ ) {+ attachedBlocks.set(identity.blockInstanceId, false);+ return false;+ }+ const templateChildren = block.children.filter(+ (child) =>+ child.type === "id" &&+ instances.get(child.value)?.component === blockTemplateComponent+ );+ const isAttached =+ templateChildren.length === 1 &&+ templateChildren.length === block.children.length;+ attachedBlocks.set(identity.blockInstanceId, isAttached);+ return isAttached;+ })+ );+ }+);++const formatSourceLocation = (diagnostic: ContentBlockDiagnostic) => {+ const point = diagnostic.sourceRange?.start;+ return point === undefined+ ? ""+ : ` Line ${point.line}, column ${point.column}.`;+};++export const formatContentBlockDiagnostic = (+ diagnostic: ContentBlockDiagnostic+) => {+ let message: string;+ if (diagnostic.code === "invalid-mdx") {+ message = diagnostic.message;+ } else if (diagnostic.code === "unsafe-mdx") {+ message = diagnostic.reason;+ } else if (diagnostic.code === "unresolved-template") {+ message = `Template "${diagnostic.templateName}" is not available and was skipped.`;+ } else if (diagnostic.code === "ignored-template-prop") {+ message = `Property "${diagnostic.propName}" on template "${+ diagnostic.templateName+ }" was ignored because it is ${diagnostic.reason.replace("-", " ")}.`;+ } else if (diagnostic.code === "stale-revision") {+ message = "The MDX file changed after it was loaded.";+ } else if (diagnostic.code === "changed-binding") {+ message = "The dynamic content source resolved to a different MDX file.";+ } else if (diagnostic.code === "pending-writes") {+ message = `${diagnostic.pendingMutationCount} MDX ${+ diagnostic.pendingMutationCount === 1 ? "change is" : "changes are"+ } still pending.`;+ } else if (diagnostic.code === "authorization-failed") {+ message = `The MDX file could not be ${+ diagnostic.operation === "read" ? "opened" : "saved"+ } with the current permissions.`;+ } else {+ message = "Some MDX changes could not be saved and require recovery.";+ }+ return `${message}${formatSourceLocation(diagnostic)}`;+};++const notifiedDiagnosticKeys = new Set<string>();+const notifiedStateKeys = new Set<string>();++export const deduplicateContentBlockDiagnostics = (+ diagnostics: readonly ContentBlockDiagnostic[]+) => {+ const keys = new Set<string>();+ return diagnostics.filter((diagnostic) => {+ const key = JSON.stringify(diagnostic);+ if (keys.has(key)) {+ return false;+ }+ keys.add(key);+ return true;+ });+};++export const takeNewContentBlockDiagnostics = (+ diagnostics: readonly ContentBlockDiagnostic[],+ revision?: string+) => {+ const fresh: ContentBlockDiagnostic[] = [];+ for (const diagnostic of deduplicateContentBlockDiagnostics(diagnostics)) {+ const key = JSON.stringify([revision, diagnostic]);+ if (notifiedDiagnosticKeys.has(key)) {+ continue;+ }+ notifiedDiagnosticKeys.add(key);+ fresh.push(diagnostic);+ }+ return fresh;+};++const getSessionMessage = (state: MdxAssetEditingSessionState) => {+ if (state.status === "conflicting") {+ return "The MDX file changed remotely. Reload the remote file or copy your unsaved MDX before continuing.";+ }+ if (state.status === "recoverable") {+ return "The MDX file could not be rendered. Open the file to repair it, then retry.";+ }+ if (state.status === "cancelled") {+ return "MDX editing was cancelled.";+ }+ if (state.status === "failed") {+ return "The MDX file could not be loaded or saved.";+ }+};++export const getMaterializedContentViewStateFromSession = (+ state: MdxAssetEditingSessionState+): MaterializedContentViewState => {+ const identity = "identity" in state ? state.identity : undefined;+ const diagnostics = state.diagnostics;+ if (state.status === "saved") {+ return {+ status: state.root.fragment.children.length === 0 ? "empty" : "ready",+ identity,+ assetId: identity?.assetId,+ diagnostics,+ };+ }+ if (state.status === "pending") {+ return {+ status: "pending",+ identity,+ assetId: identity?.assetId,+ diagnostics,+ hasUnsavedSource: true,+ message: "Saving MDX content…",+ };+ }+ return {+ status: state.status,+ identity,+ assetId: identity?.assetId,+ diagnostics,+ hasUnsavedSource: "localSource" in state,+ message: getSessionMessage(state),+ };+};++const $contentStorageBaseProjection = computed(+ [+ $activeMaterializedContentRoots,+ $assets,+ $breakpoints,+ $dataSources,+ $instances,+ $props,+ $resources,+ $styleSourceSelections,+ $styleSources,+ $styles,+ ],+ (materializedRoots) => {+ const state = readBuilderStateStores();+ return createContentStorageSelectorProjection({+ state,+ materializedRoots: Array.from(materializedRoots.values()),+ allowStaleSource: true,+ });+ }+);++const isAuthoredRoot = (+ root: MaterializedContentRoot+): root is MaterializedMdxAuthoredContentRoot =>+ "provenance" in root && "document" in root;++const createPresentationItem = ({+ blockInstanceId,+ renderScope,+ kind,+ status,+ label,+ message,+ diagnostic,+ assetId,+ discriminator,+}: Omit<ContentBlockPresentationItem, "id"> & {+ discriminator: unknown;+}): ContentBlockPresentationItem => ({+ id: `mdx-builder-${hash(+ JSON.stringify([blockInstanceId, renderScope, discriminator])+ )}`,+ blockInstanceId,+ renderScope,+ kind,+ status,+ label,+ message,+ diagnostic,+ assetId,+});++const getAuthoredChildren = (+ root: MaterializedMdxAuthoredContentRoot,+ parentPath: readonly number[]+): readonly MdxAuthoredNode[] | undefined => {+ let children = root.document.children;+ for (const index of parentPath) {+ const node = children[index];+ if (+ node === undefined ||+ (node.type !== "element" && node.type !== "template")+ ) {+ return;+ }+ children = node.children;+ }+ return children;+};++const getPathKey = (path: readonly number[]) => path.join(".");++const $contentStorageProjection = computed(+ [+ $contentStorageBaseProjection,+ $activeMaterializedContentRoots,+ $materializedContentViewStates,+ ],+ (projection, materializedRoots, viewStates) => {+ const instances = new Map(projection.state.instances);+ const items = new Map<Instance["id"], ContentBlockPresentationItem>();+ const reservedInstanceIds = new Set(instances.keys());+ const createItem = (+ input: Parameters<typeof createPresentationItem>[0]+ ): ContentBlockPresentationItem => {+ const item = createPresentationItem(input);+ let id = item.id;+ let collisionIndex = 0;+ while (reservedInstanceIds.has(id)) {+ collisionIndex += 1;+ id = `${item.id}-${collisionIndex}`;+ }+ reservedInstanceIds.add(id);+ return id === item.id ? item : { ...item, id };+ };+ const childrenByScope = new Map<string, Instance["children"]>();+ for (const [scopeKey, viewState] of viewStates) {+ const root = materializedRoots.get(scopeKey);+ const identity = viewState.identity ?? root?.identity;+ const parsedScope = JSON.parse(scopeKey) as [string, string];+ const [blockInstanceId, renderScope] = parsedScope;+ if (+ instances.has(blockInstanceId) === false ||+ getContentBlockSource({+ blockInstanceId,+ props: projection.state.props?.values() ?? [],+ }) === undefined+ ) {+ continue;+ }+ const blockPresentationItems: ContentBlockPresentationItem[] = [];+ if (viewState.status === "loading" || viewState.status === "pending") {+ blockPresentationItems.push(+ createItem({+ blockInstanceId,+ renderScope,+ kind: "loading",+ status: viewState.status,+ label:+ viewState.status === "pending" ? "Saving MDX" : "Loading MDX",+ message:+ viewState.message ??+ (viewState.status === "pending"+ ? "Saving MDX content…"+ : "Loading MDX content…"),+ assetId: identity?.assetId ?? viewState.assetId,+ discriminator: viewState.status,+ })+ );+ } else if (viewState.status === "empty") {+ blockPresentationItems.push(+ createItem({+ blockInstanceId,+ renderScope,+ kind: "empty",+ status: viewState.status,+ label: "Empty MDX file",+ message: "The connected MDX file has no body content.",+ assetId: identity?.assetId ?? viewState.assetId,+ discriminator: "empty",+ })+ );+ } else if (viewState.status !== "ready") {+ blockPresentationItems.push(+ createItem({+ blockInstanceId,+ renderScope,+ kind: "error",+ status: viewState.status,+ label:+ viewState.status === "conflicting"+ ? "MDX conflict"+ : viewState.status === "recoverable"+ ? "Repair MDX file"+ : "MDX unavailable",+ message:+ viewState.message ?? "The connected MDX file is unavailable.",+ assetId: identity?.assetId ?? viewState.assetId,+ discriminator: [viewState.status, viewState.message],+ })+ );+ }+ const unresolvedDiagnostics = viewState.diagnostics.filter(+ (diagnostic) => diagnostic.code === "unresolved-template"+ );+ const diagnosticsByTemplate = new Map<+ string,+ Extract<ContentBlockDiagnostic, { code: "unresolved-template" }>[]+ >();+ for (const diagnostic of unresolvedDiagnostics) {+ const diagnostics = diagnosticsByTemplate.get(diagnostic.templateName);+ if (diagnostics === undefined) {+ diagnosticsByTemplate.set(diagnostic.templateName, [diagnostic]);+ } else {+ diagnostics.push(diagnostic);+ }+ }+ const warningItemsByParent = new Map<+ Instance["id"],+ Map<number, ContentBlockPresentationItem>+ >();+ if (root !== undefined && isAuthoredRoot(root)) {+ const authoredInstanceByPath = new Map(+ root.provenance.nodes.map((node) => [getPathKey(node.path), node])+ );+ for (const marker of root.provenance.unresolvedTemplates) {+ const diagnostic = diagnosticsByTemplate+ .get(marker.templateName)+ ?.shift();+ if (diagnostic === undefined) {+ continue;+ }+ const item = createItem({+ blockInstanceId,+ renderScope,+ kind: "warning",+ status: viewState.status,+ label: `Missing template: ${diagnostic.templateName}`,+ message: formatContentBlockDiagnostic(diagnostic),+ diagnostic,+ assetId: identity?.assetId ?? viewState.assetId,+ discriminator: marker.markerId,+ });+ const parentPath = marker.path.slice(0, -1);+ const parentNode = authoredInstanceByPath.get(getPathKey(parentPath));+ if (parentPath.length > 0 && parentNode?.type !== "element") {+ blockPresentationItems.push(item);+ continue;+ }+ const parentId =+ parentNode?.type === "element"+ ? parentNode.instanceId+ : blockInstanceId;+ const warningItems =+ warningItemsByParent.get(parentId) ??+ new Map<number, ContentBlockPresentationItem>();+ warningItems.set(marker.path.at(-1) ?? 0, item);+ warningItemsByParent.set(parentId, warningItems);+ }+ }+ for (const diagnostics of diagnosticsByTemplate.values()) {+ for (const diagnostic of diagnostics) {+ blockPresentationItems.push(+ createItem({+ blockInstanceId,+ renderScope,+ kind: "warning",+ status: viewState.status,+ label: `Missing template: ${diagnostic.templateName}`,+ message: formatContentBlockDiagnostic(diagnostic),+ diagnostic,+ assetId: identity?.assetId ?? viewState.assetId,+ discriminator: diagnostic,+ })+ );+ }+ }+ const presentationItems = [+ ...blockPresentationItems,+ ...Array.from(warningItemsByParent.values()).flatMap((warningItems) =>+ Array.from(warningItems.values())+ ),+ ];+ if (presentationItems.length === 0) {+ continue;+ }+ for (const item of presentationItems) {+ if (instances.has(item.id)) {+ throw new Error(`Builder MDX presentation id "${item.id}" collides`);+ }+ items.set(item.id, item);+ instances.set(item.id, {+ type: "instance",+ id: item.id,+ component: contentBlockPresentationComponent,+ label: item.label,+ children: [],+ });+ }+ if (root !== undefined && isAuthoredRoot(root)) {+ const resolvedPathKeys = new Set(+ root.provenance.nodes.map((node) => getPathKey(node.path))+ );+ for (const [parentId, warningItems] of warningItemsByParent) {+ const parentPath =+ parentId === blockInstanceId+ ? []+ : (root.provenance.nodes.find(+ (node) => node.instanceId === parentId+ )?.path ?? []);+ const authoredChildren = getAuthoredChildren(root, parentPath);+ const parent = instances.get(parentId);+ if (authoredChildren === undefined || parent === undefined) {+ continue;+ }+ const projectedChildren = projection.getInstanceChildren(+ parent,+ renderScope+ );+ const projectOwnedChildren =+ parentId === blockInstanceId ? parent.children : [];+ const materializedChildren = projectedChildren.slice(+ projectOwnedChildren.length+ );+ let materializedIndex = 0;+ const authoredProjectedChildren: Instance["children"] = [];+ authoredChildren.forEach((node, index) => {+ const warningItem = warningItems.get(index);+ if (warningItem !== undefined) {+ authoredProjectedChildren.push({+ type: "id",+ value: warningItem.id,+ });+ return;+ }+ if (node.type === "comment") {+ return;+ }+ const nodePathKey = getPathKey([...parentPath, index]);+ if (+ node.type === "template" &&+ resolvedPathKeys.has(nodePathKey) === false+ ) {+ return;+ }+ const child = materializedChildren[materializedIndex];+ if (child !== undefined) {+ authoredProjectedChildren.push(child);+ materializedIndex += 1;+ }+ });+ authoredProjectedChildren.push(+ ...materializedChildren.slice(materializedIndex)+ );+ childrenByScope.set(+ getContentBlockRenderScopeKey(parentId, renderScope),+ [...projectOwnedChildren, ...authoredProjectedChildren]+ );+ }+ }+ const blockChildrenKey = getContentBlockRenderScopeKey(+ blockInstanceId,+ renderScope+ );+ const blockChildren =+ childrenByScope.get(blockChildrenKey) ??+ projection.getInstanceChildren(+ instances.get(blockInstanceId) as Instance,+ renderScope+ );+ childrenByScope.set(blockChildrenKey, [+ ...blockChildren,+ ...blockPresentationItems.map(({ id }) => ({+ type: "id" as const,+ value: id,+ })),+ ]);+ }+ return {+ state: { ...projection.state, instances },+ items,+ getInstanceChildren: (instance: Instance, renderScope: string) =>+ childrenByScope.get(+ getContentBlockRenderScopeKey(instance.id, renderScope)+ ) ?? projection.getInstanceChildren(instance, renderScope),+ };+ }+);++export const $contentBlockPresentationItems = computed(+ $contentStorageProjection,+ ({ items }) => items+);++export const $runtimeInstances = computed(+ $contentStorageProjection,+ ({ state }) => state.instances ?? new Map<Instance["id"], Instance>()+);+export const $runtimeProps = computed(+ $contentStorageProjection,+ ({ state }) => state.props ?? new Map<Prop["id"], Prop>()+);+export const $runtimeAssets = computed(+ $contentStorageProjection,+ ({ state }) => state.assets ?? new Map<Asset["id"], Asset>()+);+export const $runtimeDataSources = computed(+ $contentStorageProjection,+ ({ state }) => state.dataSources ?? new Map<DataSource["id"], DataSource>()+);+export const $runtimeBreakpoints = computed(+ $contentStorageProjection,+ ({ state }) => state.breakpoints ?? new Map<Breakpoint["id"], Breakpoint>()+);+export const $runtimeResources = computed(+ $contentStorageProjection,+ ({ state }) => state.resources ?? new Map<Resource["id"], Resource>()+);+export const $runtimeStyleSources = computed(+ $contentStorageProjection,+ ({ state }) => state.styleSources ?? new Map<StyleSource["id"], StyleSource>()+);+export const $runtimeStyleSourceSelections = computed(+ $contentStorageProjection,+ ({ state }) =>+ state.styleSourceSelections ??+ new Map<StyleSourceSelection["instanceId"], StyleSourceSelection>()+);+export const $runtimeStyles = computed(+ $contentStorageProjection,+ ({ state }) => state.styles ?? new Map<string, StyleDecl>()+);++export const getRuntimeInstanceChildren = (+ instance: Instance,+ instanceSelector: InstanceSelector+) =>+ $contentStorageProjection+ .get()+ .getInstanceChildren(instance, JSON.stringify(instanceSelector));++export const getMaterializedContentStatus = ({+ blockInstanceId,+ renderScope,+}: {+ blockInstanceId: string;+ renderScope: string;+}) =>+ $materializedContentViewStates+ .get()+ .get(getContentBlockRenderScopeKey(blockInstanceId, renderScope))?.status;++export const getMaterializedContentViewState = ({+ blockInstanceId,+ renderScope,+}: {+ blockInstanceId: string;+ renderScope: string;+}) =>+ $materializedContentViewStates+ .get()+ .get(getContentBlockRenderScopeKey(blockInstanceId, renderScope));++export const getMaterializedInstanceEditability = ({+ instanceSelector,+ instances,+}: {+ instanceSelector: InstanceSelector;+ instances: Instances;+}) => {+ if ($contentBlockPresentationItems.get().has(instanceSelector[0])) {+ return false;+ }+ const blockSelector = findBlockSelector({+ anchor: instanceSelector,+ instances,+ });+ if (blockSelector === undefined) {+ return;+ }+ const root = $activeMaterializedContentRoots+ .get()+ .get(+ getContentBlockRenderScopeKey(+ blockSelector[0],+ JSON.stringify(blockSelector)+ )+ );+ if (+ root === undefined ||+ root.fragment.instances.some(({ id }) => id === instanceSelector[0]) ===+ false+ ) {+ return;+ }+ const scopeKey = getContentBlockRenderScopeKey(+ root.identity.blockInstanceId,+ root.identity.renderScope+ );+ if ($switchingContentScopes.get().has(scopeKey)) {+ return false;+ }+ const status = getMaterializedContentStatus({+ blockInstanceId: root.identity.blockInstanceId,+ renderScope: root.identity.renderScope,+ });+ return status === "ready" || status === "empty" || status === "pending";+};++export const setContentBlockSourceSwitching = ({+ blockInstanceId,+ renderScope,+ switching,+}: {+ blockInstanceId: string;+ renderScope: string;+ switching: boolean;+}) => {+ const key = getContentBlockRenderScopeKey(blockInstanceId, renderScope);+ const scopes = new Set($switchingContentScopes.get());+ if (switching) {+ scopes.add(key);+ } else {+ scopes.delete(key);+ }+ $switchingContentScopes.set(scopes);+};++export const isMaterializedInstanceEditable = (input: {+ instanceSelector: InstanceSelector;+ instances: Instances;+}) => getMaterializedInstanceEditability(input) ?? true;++const storageSavers = new Map<string, StorageSaverEntry>();+const presentationActions = new Map<string, ContentBlockPresentationActions>();++export const registerContentBlockPresentationActions = ({+ blockInstanceId,+ renderScope,+ actions,+}: {+ blockInstanceId: string;+ renderScope: string;+ actions: ContentBlockPresentationActions;+}) => {+ const key = getContentBlockRenderScopeKey(blockInstanceId, renderScope);+ presentationActions.set(key, actions);+ return () => {+ if (presentationActions.get(key) === actions) {+ presentationActions.delete(key);+ }+ };+};++export const getContentBlockPresentationActions = ({+ blockInstanceId,+ renderScope,+}: {+ blockInstanceId: string;+ renderScope: string;+}) =>+ presentationActions.get(+ getContentBlockRenderScopeKey(blockInstanceId, renderScope)+ );++export const publishMaterializedContentRoot = (+ root: MaterializedContentRoot,+ diagnostics: readonly ContentBlockDiagnostic[] = []+) => {+ const roots = new Map($materializedContentRoots.get());+ const scopeKey = getContentBlockRenderScopeKey(+ root.identity.blockInstanceId,+ root.identity.renderScope+ );+ roots.set(scopeKey, root);+ $materializedContentRoots.set(roots);+ const states = new Map($materializedContentViewStates.get());+ states.set(scopeKey, {+ status: root.fragment.children.length === 0 ? "empty" : "ready",+ identity: root.identity,+ diagnostics,+ });+ $materializedContentViewStates.set(states);+};++export const setMaterializedContentStatus = ({+ blockInstanceId,+ renderScope,+ status,+ assetId,+}: {+ blockInstanceId: string;+ renderScope: string;+ status: "loading" | "failed";+ assetId?: Asset["id"];+}) => {+ const states = new Map($materializedContentViewStates.get());+ const key = getContentBlockRenderScopeKey(blockInstanceId, renderScope);+ const current = states.get(key);+ const sourceChanged =+ assetId !== undefined &&+ current?.identity !== undefined &&+ current.identity.assetId !== assetId;+ states.set(key, {+ status,+ identity: sourceChanged ? undefined : current?.identity,+ assetId: assetId ?? current?.assetId,+ diagnostics: sourceChanged ? [] : (current?.diagnostics ?? []),+ message:+ status === "failed"+ ? "The connected MDX file could not be loaded."+ : undefined,+ });+ $materializedContentViewStates.set(states);+};++export const publishMaterializedContentSessionState = ({+ blockInstanceId,+ renderScope,+ state,+}: {+ blockInstanceId: string;+ renderScope: string;+ state: MdxAssetEditingSessionState;+}) => {+ const revision = "identity" in state ? state.identity.revision : undefined;+ for (const diagnostic of takeNewContentBlockDiagnostics(+ state.diagnostics,+ revision+ )) {+ const filename =+ diagnostic.contentRef ??+ (diagnostic.assetId === undefined+ ? undefined+ : $assets.get().get(diagnostic.assetId)?.name) ??+ "MDX file";+ const message = `${filename}: ${formatContentBlockDiagnostic(+ diagnostic+ )} Render scope: ${diagnostic.renderScope ?? renderScope}.`;+ if (diagnostic.severity === "error") {+ toast.error(message);+ } else {+ toast.warn(message);+ }+ }+ if (+ state.diagnostics.length === 0 &&+ (state.status === "failed" ||+ state.status === "recoverable" ||+ state.status === "conflicting")+ ) {+ const viewState = getMaterializedContentViewStateFromSession(state);+ const key = JSON.stringify([+ state.status,+ revision,+ blockInstanceId,+ renderScope,+ viewState.message,+ ]);+ if (notifiedStateKeys.has(key) === false) {+ notifiedStateKeys.add(key);+ toast.error(+ `${+ viewState.message ?? "The MDX file is unavailable."+ } Render scope: ${renderScope}.`+ );+ }+ }+ if (state.status === "saved") {+ publishMaterializedContentRoot(state.root, state.diagnostics);+ return;+ }+ if ("root" in state) {+ const roots = new Map($materializedContentRoots.get());+ roots.set(+ getContentBlockRenderScopeKey(blockInstanceId, renderScope),+ state.root+ );+ $materializedContentRoots.set(roots);+ }+ const states = new Map($materializedContentViewStates.get());+ states.set(+ getContentBlockRenderScopeKey(blockInstanceId, renderScope),+ getMaterializedContentViewStateFromSession(state)+ );+ $materializedContentViewStates.set(states);+};++export const publishPendingMaterializedContentChanges = (+ changes: readonly ContentStorageChange[]+) => {+ const changesByScope = new Map<string, ContentStorageChange[]>();+ for (const change of changes) {+ const scopeKey = getContentBlockRenderScopeKey(+ change.root.identity.blockInstanceId,+ change.root.identity.renderScope+ );+ const scopeChanges = changesByScope.get(scopeKey) ?? [];+ scopeChanges.push(change);+ changesByScope.set(scopeKey, scopeChanges);+ }+ for (const [scopeKey, scopeChanges] of changesByScope) {+ const root = $activeMaterializedContentRoots.get().get(scopeKey);+ if (root === undefined || isAuthoredRoot(root) === false) {+ throw new Error("The MDX authored content is not loaded.");+ }+ const roots = new Map($materializedContentRoots.get());+ roots.set(scopeKey, {+ ...root,+ fragment: applyMdxContentStorageChanges({ root, changes: scopeChanges }),+ });+ $materializedContentRoots.set(roots);+ const states = new Map($materializedContentViewStates.get());+ const current = states.get(scopeKey);+ states.set(scopeKey, {+ status: "pending",+ identity: root.identity,+ assetId: root.identity.assetId,+ diagnostics: current?.diagnostics ?? [],+ hasUnsavedSource: true,+ message: "Saving MDX content…",+ });+ $materializedContentViewStates.set(states);+ }+};++export const failPendingMaterializedContentChanges = (+ changes: readonly ContentStorageChange[],+ message: string+) => {+ const states = new Map($materializedContentViewStates.get());+ let changed = false;+ for (const change of changes) {+ const scopeKey = getContentBlockRenderScopeKey(+ change.root.identity.blockInstanceId,+ change.root.identity.renderScope+ );+ const current = states.get(scopeKey);+ if (current?.status !== "pending") {+ continue;+ }+ states.set(scopeKey, { ...current, status: "failed", message });+ changed = true;+ }+ if (changed) {+ $materializedContentViewStates.set(states);+ }+};++export const removeMaterializedContentRoot = ({+ blockInstanceId,+ renderScope,+}: {+ blockInstanceId: string;+ renderScope: string;+}) => {+ const roots = new Map($materializedContentRoots.get());+ const scopeKey = getContentBlockRenderScopeKey(blockInstanceId, renderScope);+ roots.delete(scopeKey);+ $materializedContentRoots.set(roots);+ const states = new Map($materializedContentViewStates.get());+ states.delete(scopeKey);+ $materializedContentViewStates.set(states);+ setContentBlockSourceSwitching({+ blockInstanceId,+ renderScope,+ switching: false,+ });+};++export const registerContentStorageSaver = ({+ blockInstanceId,+ renderScope,+ preflight,+ save,+ isCurrent,+}: {+ blockInstanceId: string;+ renderScope: string;+ preflight: StorageSaver;+ save: StorageSaver;+ isCurrent: StorageSaverEntry["isCurrent"];+}) => {+ const key = getContentBlockRenderScopeKey(blockInstanceId, renderScope);+ const entry = { preflight, save, isCurrent };+ storageSavers.set(key, entry);+ return () => {+ if (storageSavers.get(key) === entry) {+ storageSavers.delete(key);+ }+ };+};++export const saveMaterializedContentChanges = async (+ changes: readonly ContentStorageChange[],+ {+ projectStep,+ }: {+ projectStep?: Readonly<{+ order: "before" | "after";+ preflight: () => Promise<StorageSaveResult> | StorageSaveResult;+ save: () => Promise<StorageSaveResult> | StorageSaveResult;+ }>;+ } = {}+): Promise<StorageSaveResult> => {+ const blocker = getMaterializedContentSaveBlocker(changes);+ if (blocker !== undefined) {+ return blocker;+ }+ if (changes.length === 0 && projectStep === undefined) {+ return { status: "applied" };+ }+ const groupedChanges = new Map<+ string,+ {+ identity: ContentBlockExternalContentIdentity;+ changes: ContentStorageChange[];+ }+ >();+ for (const change of changes) {+ const key = getContentStorageIdentityKey(change.root.identity);+ const group = groupedChanges.get(key) ?? {+ identity: change.root.identity,+ changes: [],+ };+ group.changes.push(change);+ groupedChanges.set(key, group);+ }+ const assetSteps = [...groupedChanges.values()].map((group) => {+ const scopeKey = getContentBlockRenderScopeKey(+ group.identity.blockInstanceId,+ group.identity.renderScope+ );+ const saver = storageSavers.get(scopeKey)!;+ return {+ type: "asset" as const,+ root: group.identity,+ preflight: async () => {+ const result = await saver.preflight(group.changes);+ return result.status === "applied"+ ? { status: "ready" as const }+ : {+ status: "failed" as const,+ code: "content-source-session-failed",+ message: result.message,+ };+ },+ persist: async () => {+ publishPendingMaterializedContentChanges(group.changes);+ const result = await saver.save(group.changes);+ return result.status === "applied"+ ? { status: "saved" as const }+ : {+ status: "failed" as const,+ code: "content-source-session-failed",+ message: result.message,+ };+ },+ };+ });+ const projectPlan =+ projectStep === undefined+ ? []+ : [+ {+ type: "project" as const,+ preflight: async () => {+ const result = await projectStep.preflight();+ return result.status === "applied"+ ? { status: "ready" as const }+ : {+ status: "failed" as const,+ code: "content-source-session-failed",+ message: result.message,+ };+ },+ persist: async () => {+ const result = await projectStep.save();+ return result.status === "applied"+ ? { status: "saved" as const }+ : {+ status: "failed" as const,+ code: "content-source-session-failed",+ message: result.message,+ };+ },+ },+ ];+ const persistence = await executeContentBlockPersistencePlan(+ projectStep?.order === "before"+ ? [...projectPlan, ...assetSteps]+ : [...assetSteps, ...projectPlan]+ );+ if (persistence.status === "complete") {+ return { status: "applied", persistence };+ }+ const failure = persistence.steps.find(({ status }) => status === "failed");+ return {+ status: persistence.status === "partial" ? "partial" : "blocked",+ message:+ failure?.message ??+ (persistence.status === "partial"+ ? "Some content changes were saved. Retry the unfinished steps."+ : "The content changes could not be saved."),+ persistence,+ };+};++export const getMaterializedContentSaveBlocker = (+ changes: readonly ContentStorageChange[]+): Readonly<{ status: "blocked"; message: string }> | undefined => {+ if (changes.length === 0) {+ return;+ }+ for (const change of changes) {+ const scopeKey = getContentBlockRenderScopeKey(+ change.root.identity.blockInstanceId,+ change.root.identity.renderScope+ );+ const status = getMaterializedContentStatus({+ blockInstanceId: change.root.identity.blockInstanceId,+ renderScope: change.root.identity.renderScope,+ });+ if (status !== "ready" && status !== "empty" && status !== "pending") {+ return {+ status: "blocked",+ message: "The MDX content source is not ready for editing.",+ };+ }+ const currentRoot = $activeMaterializedContentRoots.get().get(scopeKey);+ if (+ currentRoot === undefined ||+ getContentStorageIdentityKey(currentRoot.identity) !==+ getContentStorageIdentityKey(change.root.identity)+ ) {+ return {+ status: "blocked",+ message: "The MDX content source changed before the edit was saved.",+ };+ }+ const saver = storageSavers.get(scopeKey);+ if (saver === undefined) {+ return {+ status: "blocked",+ message: "The MDX content source is not ready for editing.",+ };+ }+ if (saver.isCurrent(currentRoot) === false) {+ return {+ status: "blocked",+ message: "The MDX content source changed before the edit was saved.",+ };+ }+ }+};++export const resetMaterializedContent = () => {+ $materializedContentRoots.set(new Map());+ $materializedContentViewStates.set(new Map());+ $switchingContentScopes.set(new Set());+ storageSavers.clear();+ presentationActions.clear();+ notifiedDiagnosticKeys.clear();+ notifiedStateKeys.clear();+};++let materializedProjectId = $project.get()?.id;+$project.listen((project) => {+ if (project?.id === materializedProjectId) {+ return;+ }+ materializedProjectId = project?.id;+ resetMaterializedContent();+});diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.ts b/apps/builder/app/shared/copy-paste/plugin-instance.tsindex d06a6ee903..0eae1bd7ab 100644--- a/apps/builder/app/shared/copy-paste/plugin-instance.ts+++ b/apps/builder/app/shared/copy-paste/plugin-instance.ts@@ -24,6 +24,7 @@ import { toast } from "@webstudio-is/design-system";import {type Instance,type WebstudioFragment,+ findChildReferenceIndex,isComponentDetachable,} from "@webstudio-is/sdk";import { $instances } from "~/shared/sync/data-stores";@@ -31,7 +32,6 @@ import {type InstanceSelector,sortInstancePathsForChildMutation,} from "@webstudio-is/project-build/runtime";-import { findChildReferenceIndex } from "@webstudio-is/project-build/runtime";import { deleteInstanceBySelector } from "../instance-utils/mutation";import {$allSelectedInstanceSelectors,diff --git a/apps/builder/app/shared/db/canvas.server.ts b/apps/builder/app/shared/db/canvas.server.tsindex f2f27f8b22..862e4dbe5e 100644--- a/apps/builder/app/shared/db/canvas.server.ts+++ b/apps/builder/app/shared/db/canvas.server.ts@@ -7,7 +7,14 @@ import {loadBuildById,loadDevBuildByProjectId,} from "@webstudio-is/project-build/server";-import { createBuildContentCompilationPlan } from "@webstudio-is/project-build";+import {+ createBuildContentCompilationPlan,+ createPublishedBuildContentCompilationPlan,+ getDynamicPublishedMdxSourceBlockIds,+ getPublishedMdxContentDatabaseMaxBytes,+ resolvePublishedMdxDependencyClosure,+ resolvePublishedMdxAssetCandidates,+} from "@webstudio-is/project-build";import { collectFontFamiliesFromStyleDecls } from "@webstudio-is/project-build/runtime";import {loadAssetDataByProject,@@ -21,7 +28,10 @@ import {type Asset,type AssetFolder,} from "@webstudio-is/sdk";-import { serializePages } from "@webstudio-is/project-migrations/pages";+import {+ migratePages,+ serializePages,+} from "@webstudio-is/project-migrations/pages";import { loadById } from "@webstudio-is/project/index.server";import { getUserById } from "./user.server";import { createAssetClient } from "../asset-client";@@ -159,7 +169,30 @@ const addProjectMetadata = async (? undefined: await getUserById(context, project.userId);- const assetRequirements = createBuildContentCompilationPlan(data.build);+ const publicationBuild = {+ ...data.build,+ pages: migratePages(data.build.pages),+ };+ const dynamicBlockIds =+ getDynamicPublishedMdxSourceBlockIds(publicationBuild);+ const projectCandidates = resolvePublishedMdxAssetCandidates({+ build: publicationBuild,+ allowUnresolved: true,+ });+ const needsCandidateDiscovery = dynamicBlockIds.some(+ (blockId) => projectCandidates.has(blockId) === false+ );+ const assetRequirements = needsCandidateDiscovery+ ? createBuildContentCompilationPlan(data.build)+ : createPublishedBuildContentCompilationPlan(+ publicationBuild,+ projectCandidates+ );+ if (needsCandidateDiscovery && assetRequirements === undefined) {+ throw new Error(+ "Dynamic MDX publication requires a finite Assets query dependency"+ );+ }let assetIndex: PublishedProjectBundle["assetIndex"];let publishedAssets = data.assets;let publishedAssetFolders = data.assetFolders;@@ -168,11 +201,27 @@ const addProjectMetadata = async (projectId: project.id,context,assetStore: createAssetClient(),- contentDatabaseMaxBytes: getContentDatabaseMaxBytes(),+ contentDatabaseMaxBytes: getPublishedMdxContentDatabaseMaxBytes({+ baseBytes: getContentDatabaseMaxBytes(),+ assets: data.assets,+ }),plan: assetRequirements,retainedAssetIds: data.assets.filter((asset) => asset.type === "font").map((asset) => asset.id),+ ...(assetRequirements.queries.some(({ id }) =>+ id.startsWith("__content-block-mdx__:")+ ) || needsCandidateDiscovery+ ? {+ resolvePlan: async (+ artifact: NonNullable<PublishedProjectBundle["assetIndex"]>+ ) =>+ (await resolvePublishedMdxDependencyClosure({+ build: publicationBuild,+ artifact,+ }))!,+ }+ : {}),});assetIndex = publishedAssetData.artifact;publishedAssets = publishedAssetData.assets;diff --git a/apps/builder/app/shared/dom-hooks/use-content-editable.test.tsx b/apps/builder/app/shared/dom-hooks/use-content-editable.test.tsxnew file mode 100644index 0000000000..868167284e--- /dev/null+++ b/apps/builder/app/shared/dom-hooks/use-content-editable.test.tsx@@ -0,0 +1,61 @@+/**+ * @vitest-environment jsdom+ */+import { act } from "react-dom/test-utils";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, test, vi } from "vitest";+import { useContentEditable } from "./use-content-editable";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {+ callback(0);+ return 0;+ });+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+ vi.unstubAllGlobals();+});++test("keeps the editor open when completion is rejected", () => {+ const onChangeEditing = vi.fn();+ const onChangeValue = vi.fn(() => false);+ const Editor = () => {+ const { ref, handlers } = useContentEditable({+ isEditable: true,+ isEditing: true,+ onChangeEditing,+ onChangeValue,+ value: "Card",+ });+ return (+ <div ref={ref} {...handlers}>+ Duplicate+ </div>+ );+ };+ act(() => root.render(<Editor />));+ const editor = container.querySelector("div")!;++ act(() => {+ editor.dispatchEvent(+ new KeyboardEvent("keydown", { key: "Enter", bubbles: true })+ );+ });++ expect(onChangeValue).toHaveBeenCalledWith("Duplicate");+ expect(onChangeEditing).not.toHaveBeenCalled();+ expect(editor.getAttribute("contenteditable")).toBe("plaintext-only");+});diff --git a/apps/builder/app/shared/dom-hooks/use-content-editable.ts b/apps/builder/app/shared/dom-hooks/use-content-editable.tsindex 9e4ea08c61..ac7b92a759 100644--- a/apps/builder/app/shared/dom-hooks/use-content-editable.ts+++ b/apps/builder/app/shared/dom-hooks/use-content-editable.ts@@ -16,7 +16,7 @@ export const useContentEditable = ({isEditable: boolean;isEditing: boolean;onChangeEditing: (isEditing: boolean) => void;- onChangeValue: (value: string) => void;+ onChangeValue: (value: string) => void | boolean;value: string;}) => {const elementRef = useRef<HTMLDivElement | null>(null);@@ -62,8 +62,9 @@ export const useContentEditable = ({return;}const nextValue = getValue();- handleEnd(event);- onChangeValue(nextValue);+ if (onChangeValue(nextValue) !== false) {+ handleEnd(event);+ }};const handleKeyDown: KeyboardEventHandler = (event) => {diff --git a/apps/builder/app/shared/instance-utils/data.test.tsx b/apps/builder/app/shared/instance-utils/data.test.tsxindex 693a738e40..7a392613b3 100644--- a/apps/builder/app/shared/instance-utils/data.test.tsx+++ b/apps/builder/app/shared/instance-utils/data.test.tsx@@ -1,12 +1,25 @@-import { describe, expect, expectTypeOf, test } from "vitest";-import type { Asset, Instance, PageTemplate } from "@webstudio-is/sdk";+import { describe, expect, expectTypeOf, test, vi } from "vitest";+import {+ blockComponent,+ blockTemplateComponent,+ contentBlockSourceProp,+ type Asset,+ type Instance,+ type PageTemplate,+} from "@webstudio-is/sdk";import { createDefaultPages } from "@webstudio-is/project-build";-import { findCycles } from "@webstudio-is/project-build/runtime";+import {+ findCycles,+ type MaterializedMdxAuthoredContentRoot,+} from "@webstudio-is/project-build/runtime";import type { BuilderRuntimeOperationInput } from "@webstudio-is/project-build/runtime";import {executeRuntimeMutation,executeRuntimeMutationAsync,executeRuntimeMutationSequence,+ $pendingTemplateNameConfirmation,+ abortPendingTemplateNameConfirmation,+ confirmPendingTemplateNameChange,getWebstudioData,migrateLoadedWebstudioData,type RuntimeMutationOperation,@@ -27,6 +40,15 @@ import {} from "../sync/data-stores";import { $selectedPageId } from "../nano-states/pages";import { $authPermit, $builderMode } from "../nano-states/misc";+import { selectInstance } from "../nano-states/instances";+import {+ publishMaterializedContentRoot,+ registerContentStorageSaver,+ resetMaterializedContent,+ $runtimeInstances,+ $materializedContentRoots,+ getMaterializedContentStatus,+} from "../content-block-content";const createInstance = (id: Instance["id"],@@ -48,6 +70,7 @@ test("accepts only mutation operation ids in the Builder commit helpers", () =>});const setBaseStores = () => {+ abortPendingTemplateNameConfirmation();serverSyncStore.transactionManager.currentStack = [];serverSyncStore.transactionManager.undoneStack = [];serverSyncStore.popAll();@@ -139,6 +162,91 @@ describe("data store helpers", () => {]);});+ test("requires and revalidates confirmation for a source-backed template rename", () => {+ setBaseStores();+ $instances.set(+ new Map([+ [+ "body",+ createInstance("body", "Body", [{ type: "id", value: "block" }]),+ ],+ [+ "block",+ createInstance("block", blockComponent, [+ { type: "id", value: "templates" },+ ]),+ ],+ [+ "templates",+ createInstance("templates", blockTemplateComponent, [+ { type: "id", value: "card" },+ ]),+ ],+ ["card", createInstance("card", "Box", [])],+ ])+ );+ $props.set(+ new Map([+ [+ "src",+ {+ id: "src",+ instanceId: "block",+ name: contentBlockSourceProp,+ type: "asset" as const,+ value: "article.mdx",+ },+ ],+ ])+ );++ expect(+ executeRuntimeMutation({+ id: "instances.setLabel",+ input: { instanceId: "card", label: "Hero Card" },+ })+ ).toBeUndefined();+ expect($instances.get().get("card")?.label).toBeUndefined();+ expect($pendingTemplateNameConfirmation.get()?.confirmation).toEqual({+ action: "rename",+ templates: [{ instanceId: "card", oldName: "Box", newName: "Hero Card" }],+ });++ abortPendingTemplateNameConfirmation();+ expect($instances.get().get("card")?.label).toBeUndefined();++ executeRuntimeMutation({+ id: "instances.setLabel",+ input: { instanceId: "card", label: "Hero Card" },+ });+ const current = $instances.get();+ current.set("card", { ...current.get("card")!, label: "Current Card" });+ $instances.set(new Map(current));+ confirmPendingTemplateNameChange();+ expect($instances.get().get("card")?.label).toBe("Current Card");+ expect(+ $pendingTemplateNameConfirmation.get()?.confirmation.templates[0]?.oldName+ ).toBe("Current Card");++ confirmPendingTemplateNameChange();+ expect($instances.get().get("card")?.label).toBe("Hero Card");+ expect($pendingTemplateNameConfirmation.get()).toBeUndefined();++ expect(+ executeRuntimeMutation({+ id: "instances.delete",+ input: { instanceIds: ["card"] },+ })+ ).toBeUndefined();+ expect($pendingTemplateNameConfirmation.get()?.confirmation).toEqual({+ action: "delete",+ templates: [{ instanceId: "card", oldName: "Hero Card" }],+ });+ expect($instances.get().has("card")).toBe(true);+ confirmPendingTemplateNameChange();+ expect($instances.get().has("card")).toBe(false);+ });+test("commits runtime patch payloads with sync undo and redo support", () => {setBaseStores();@@ -516,6 +624,244 @@ describe("data store helpers", () => {]);});+ test("routes projected text edits to MDX storage without persisting projected instances", async () => {+ setBaseStores();+ $instances.set(+ new Map([+ [+ "body",+ createInstance("body", "Body", [{ type: "id", value: "block" }]),+ ],+ [+ "block",+ createInstance("block", "ws:block", [+ { type: "id", value: "templates" },+ ]),+ ],+ ["templates", createInstance("templates", "ws:block-template", [])],+ ])+ );+ $props.set(+ new Map([+ [+ "source",+ {+ id: "source",+ instanceId: "block",+ name: "src",+ type: "asset" as const,+ value: "article",+ },+ ],+ ])+ );+ const identity = {+ blockInstanceId: "block",+ assetId: "article",+ revision: "sha256:one",+ contentRef: "article.mdx",+ format: "mdx" as const,+ renderScope: JSON.stringify(["block", "body"]),+ };+ const authoredRoot: MaterializedMdxAuthoredContentRoot = {+ identity,+ fragment: {+ children: [{ type: "id", value: "external" }],+ instances: [+ {+ type: "instance",+ id: "external",+ component: "ws:element",+ tag: "p",+ children: [{ type: "text", value: "Before" }],+ },+ ],+ props: [],+ assets: [],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ },+ document: {+ frontmatter: { properties: {} },+ children: [+ {+ type: "element",+ syntax: "markdown",+ tag: "p",+ props: [],+ children: [{ type: "text", value: "Before" }],+ },+ ],+ },+ provenance: {+ nodes: [+ {+ type: "element",+ path: [0],+ instanceId: "external",+ assetProps: [],+ },+ ],+ unresolvedTemplates: [],+ },+ };+ publishMaterializedContentRoot(authoredRoot);+ const save = vi.fn(async () => ({ status: "applied" as const }));+ const unregister = registerContentStorageSaver({+ blockInstanceId: "block",+ renderScope: identity.renderScope,+ preflight: async () => ({ status: "applied" }),+ isCurrent: () => true,+ save,+ });+ selectInstance(["external", "block", "body"]);++ const result = executeRuntimeMutation({+ id: "instances.setTextContent",+ input: {+ operation: "set",+ instanceId: "external",+ mode: "text",+ text: "After",+ },+ });+ await vi.waitFor(() =>+ expect($runtimeInstances.get().get("external")?.children).toEqual([+ { type: "text", value: "After" },+ ])+ );+ expect(+ getMaterializedContentStatus({+ blockInstanceId: "block",+ renderScope: identity.renderScope,+ })+ ).toBe("pending");+ const accumulated = executeRuntimeMutation({+ id: "instances.setTextContent",+ input: {+ operation: "set",+ instanceId: "external",+ mode: "text",+ text: "Again",+ },+ });+ expect(accumulated).toBeUndefined();+ await vi.waitFor(() =>+ expect($runtimeInstances.get().get("external")?.children).toEqual([+ { type: "text", value: "Again" },+ ])+ );+ await Promise.resolve();+ const savedRoot = $materializedContentRoots+ .get()+ .get(JSON.stringify(["block", identity.renderScope]));+ if (savedRoot === undefined) {+ throw new Error("Expected pending materialized content");+ }+ publishMaterializedContentRoot(savedRoot);++ expect(result).toBeUndefined();+ expect(save).toHaveBeenCalledTimes(2);+ expect($instances.get().has("external")).toBe(false);+ expect($instances.get().get("block")?.children).toEqual([+ { type: "id", value: "templates" },+ ]);+ unregister();+ const unregisterStale = registerContentStorageSaver({+ blockInstanceId: "block",+ renderScope: identity.renderScope,+ preflight: async () => ({ status: "applied" }),+ isCurrent: () => false,+ save,+ });+ expect(+ executeRuntimeMutation({+ id: "instances.setTextContent",+ input: {+ operation: "set",+ instanceId: "external",+ mode: "text",+ text: "Stale",+ },+ })+ ).toBeUndefined();+ await Promise.resolve();+ expect(save).toHaveBeenCalledTimes(2);+ unregisterStale();++ let finishSave: ((result: { status: "applied" }) => void) | undefined;+ const deferredSave = vi.fn(+ () =>+ new Promise<{ status: "applied" }>((resolve) => {+ finishSave = resolve;+ })+ );+ const unregisterDeferred = registerContentStorageSaver({+ blockInstanceId: "block",+ renderScope: identity.renderScope,+ preflight: async () => ({ status: "applied" }),+ isCurrent: () => true,+ save: deferredSave,+ });+ let asyncMutationSettled = false;+ const asyncMutation = executeRuntimeMutationAsync({+ id: "instances.setTextContent",+ input: {+ operation: "set",+ instanceId: "external",+ mode: "text",+ text: "Async",+ },+ }).then((mutation) => {+ asyncMutationSettled = true;+ return mutation;+ });+ await vi.waitFor(() => expect(deferredSave).toHaveBeenCalledOnce());+ expect(asyncMutationSettled).toBe(false);+ finishSave?.({ status: "applied" });+ expect((await asyncMutation)?.storageChanges).toHaveLength(1);+ unregisterDeferred();+ const latestRoot = $materializedContentRoots+ .get()+ .get(JSON.stringify(["block", identity.renderScope]));+ if (latestRoot === undefined) {+ throw new Error("Expected accumulated materialized content");+ }+ publishMaterializedContentRoot(latestRoot);+ const unregisterRejected = registerContentStorageSaver({+ blockInstanceId: "block",+ renderScope: identity.renderScope,+ preflight: async () => ({ status: "applied" }),+ isCurrent: () => true,+ save: async () => {+ throw new Error("private transport details");+ },+ });+ await expect(+ executeRuntimeMutationAsync({+ id: "instances.setTextContent",+ input: {+ operation: "set",+ instanceId: "external",+ mode: "text",+ text: "Rejected",+ },+ })+ ).resolves.toBeUndefined();+ expect(+ getMaterializedContentStatus({+ blockInstanceId: "block",+ renderScope: identity.renderScope,+ })+ ).toBe("failed");+ unregisterRejected();+ resetMaterializedContent();+ });+test("uses text content runtime validation before updating stores", () => {setBaseStores();diff --git a/apps/builder/app/shared/instance-utils/data.ts b/apps/builder/app/shared/instance-utils/data.tsindex eea941bb8a..54dc450366 100644--- a/apps/builder/app/shared/instance-utils/data.ts+++ b/apps/builder/app/shared/instance-utils/data.ts@@ -4,12 +4,16 @@import { toast } from "@webstudio-is/design-system";import { type WebstudioData, isPageTemplate } from "@webstudio-is/sdk";import {+ BuilderRuntimeError,+ blockTemplateNameConfirmationInput,executeBuilderRuntimeOperation,createRuntimeMutationAccumulator,+ getRuntimeMutationPersistenceOrder,type BuilderRuntimeOperationInput,type BuilderRuntimeMutationOperationId,type BuilderRuntimeOperationResult,} from "@webstudio-is/project-build/runtime";+import { atom } from "nanostores";import {builderRuntimeContext,type BuilderRuntimeContext,@@ -17,7 +21,24 @@ import {import { type BuilderRuntimeMutation } from "@webstudio-is/project-build/runtime";import { $canOpenPageTemplates, $selectedPage } from "../nano-states";import { createTransactionFromBuilderPatchPayload } from "../sync/builder-patch";-import { $project, readBuilderStateStores } from "../sync/data-stores";+import {+ $project,+ hasSameBuilderStateStoreReferences,+ readBuilderStateStores,+} from "../sync/data-stores";+import {+ $allSelectedInstanceSelectors,+ clearInstanceSelection,+ selectInstance,+} from "../nano-states";+import {+ getMaterializedContentStatus,+ getMaterializedContentSaveBlocker,+ $activeMaterializedContentRoots,+ saveMaterializedContentChanges,+ $contentBlockPresentationItems,+ failPendingMaterializedContentChanges,+} from "../content-block-content";type RuntimeMutationResult<Id extends BuilderRuntimeMutationOperationId> =Extract<BuilderRuntimeOperationResult<Id>, BuilderRuntimeMutation>;@@ -29,6 +50,38 @@ export type RuntimeMutationOperation = {};}[BuilderRuntimeMutationOperationId];+type TemplateNameConfirmation = ReturnType<+ typeof blockTemplateNameConfirmationInput.parse+>;++type PendingTemplateNameConfirmation = {+ operation: RuntimeMutationOperation;+ confirmation: TemplateNameConfirmation;+};++export const $pendingTemplateNameConfirmation = atom<+ PendingTemplateNameConfirmation | undefined+>(undefined);++const getTemplateNameConfirmation = (error: unknown) => {+ if (error instanceof BuilderRuntimeError === false) {+ return;+ }+ const issue = error.issues?.find(+ ({ code }) => code === "template_name_change_requires_confirmation"+ );+ const result = blockTemplateNameConfirmationInput.safeParse(issue?.example);+ return result.success ? result.data : undefined;+};++export const getDuplicateTemplateNameMessage = (error: unknown) => {+ if (error instanceof BuilderRuntimeError === false) {+ return;+ }+ return error.issues?.find(({ code }) => code === "duplicate_template_name")+ ?.message;+};+export type WebstudioInstanceData = Pick<WebstudioData,| "instances"@@ -58,11 +111,67 @@ export const migrateLoadedWebstudioData = () => {}};+const isScopeSelected = (renderScope: string) => {+ const selectedSelectors = $allSelectedInstanceSelectors.get();+ if (selectedSelectors.length === 0) {+ return false;+ }+ let scope: unknown;+ try {+ scope = JSON.parse(renderScope);+ } catch {+ return false;+ }+ if (Array.isArray(scope) === false) {+ return false;+ }+ return selectedSelectors.some(+ (selected) =>+ scope.length <= selected.length &&+ scope.every(+ (instanceId, index) =>+ instanceId === selected[selected.length - scope.length + index]+ )+ );+};++const getSelectedMaterializedContent = () =>+ Array.from($activeMaterializedContentRoots.get().values()).filter(+ ({ identity }) => isScopeSelected(identity.renderScope)+ );+const getRuntimeMutationContext = () => ({createId: builderRuntimeContext.createId,projectId: $project.get()?.id,+ materializedContent: getSelectedMaterializedContent(),+ returnStorageChanges: true,});+const canEditSelectedMaterializedContent = () => {+ if (+ $allSelectedInstanceSelectors+ .get()+ .some(([instanceId]) =>+ $contentBlockPresentationItems.get().has(instanceId)+ )+ ) {+ toast.error("MDX diagnostic notices cannot be edited.");+ return false;+ }+ const roots = getSelectedMaterializedContent();+ for (const { identity } of roots) {+ const status = getMaterializedContentStatus({+ blockInstanceId: identity.blockInstanceId,+ renderScope: identity.renderScope,+ });+ if (status !== "ready" && status !== "empty" && status !== "pending") {+ toast.error("The MDX content source is not ready for editing.");+ return false;+ }+ }+ return true;+};+type RuntimeMutationContext = Pick<BuilderRuntimeContext,"allowLegacyContentModelWarnings"@@ -95,14 +204,104 @@ const createRuntimeMutationArgs = <context: { ...getRuntimeMutationContext(), ...context },});+const persistRuntimeMutation = async <Mutation extends BuilderRuntimeMutation>(+ result: Mutation,+ plannedData: ReturnType<typeof getWebstudioData>+): Promise<Mutation | undefined> => {+ const storageChanges = result.storageChanges ?? [];+ const projectFirst =+ result.payload.length > 0 &&+ getRuntimeMutationPersistenceOrder(result) === "project-first";+ try {+ const saveResult = await saveMaterializedContentChanges(storageChanges, {+ projectStep:+ result.payload.length === 0+ ? undefined+ : {+ order: projectFirst ? ("before" as const) : ("after" as const),+ preflight: () =>+ hasSameBuilderStateStoreReferences(+ plannedData,+ getWebstudioData()+ )+ ? { status: "applied" as const }+ : {+ status: "blocked" as const,+ message:+ "The project changed before the content edit was saved.",+ },+ save: () => {+ if (+ hasSameBuilderStateStoreReferences(+ plannedData,+ getWebstudioData()+ ) === false+ ) {+ return {+ status: "blocked" as const,+ message:+ projectFirst === false+ ? "The MDX files were saved, but the project changed before its step."+ : "The project changed before the content edit was saved.",+ };+ }+ createTransactionFromBuilderPatchPayload({+ data: plannedData,+ payload: result.payload,+ });+ return { status: "applied" as const };+ },+ },+ });+ if (saveResult.status !== "applied") {+ failPendingMaterializedContentChanges(storageChanges, saveResult.message);+ toast.error(saveResult.message);+ return;+ }+ return result;+ } catch (error) {+ const message = "The MDX file could not be saved.";+ failPendingMaterializedContentChanges(storageChanges, message);+ toast.error(message);+ throw new Error(message, { cause: error });+ }+};+const commitRuntimeMutation = <Mutation extends BuilderRuntimeMutation>(+ result: Mutation,+ { returnPendingResult = false }: { returnPendingResult?: boolean } = {}+): Mutation | undefined => {+ const plannedData = getWebstudioData();+ if (!result.storageChanges?.length) {+ createTransactionFromBuilderPatchPayload({+ data: plannedData,+ payload: result.payload,+ });+ return result;+ }+ const blocker = getMaterializedContentSaveBlocker(result.storageChanges);+ if (blocker !== undefined) {+ toast.error(blocker.message);+ return;+ }+ void persistRuntimeMutation(result, plannedData).catch(() => undefined);+ return returnPendingResult ? result : undefined;+};++const commitRuntimeMutationAsync = async <+ Mutation extends BuilderRuntimeMutation,+>(result: Mutation-): Mutation => {- createTransactionFromBuilderPatchPayload({- data: getWebstudioData(),- payload: result.payload,- });- return result;+): Promise<Mutation | undefined> => {+ if (!result.storageChanges?.length) {+ return commitRuntimeMutation(result);+ }+ const blocker = getMaterializedContentSaveBlocker(result.storageChanges);+ if (blocker !== undefined) {+ toast.error(blocker.message);+ return;+ }+ return persistRuntimeMutation(result, getWebstudioData());};export const executeRuntimeMutation = <@@ -119,14 +318,76 @@ export const executeRuntimeMutation = <if (canCommitWebstudioData() === false) {return;}- return commitRuntimeMutation(- requireSynchronousResult(- id,- executeBuilderRuntimeOperation<RuntimeMutationResult<Id>>(- createRuntimeMutationArgs({ id, input, context })- )+ if (canEditSelectedMaterializedContent() === false) {+ return;+ }+ try {+ return commitRuntimeMutation(+ requireSynchronousResult(+ id,+ executeBuilderRuntimeOperation<RuntimeMutationResult<Id>>(+ createRuntimeMutationArgs({ id, input, context })+ )+ ),+ { returnPendingResult: id === "instances.updateTextTree" }+ );+ } catch (error) {+ const confirmation = getTemplateNameConfirmation(error);+ if (confirmation === undefined) {+ throw error;+ }+ $pendingTemplateNameConfirmation.set({+ operation: { id, input } as RuntimeMutationOperation,+ confirmation,+ });+ return;+ }+};++export const abortPendingTemplateNameConfirmation = () => {+ $pendingTemplateNameConfirmation.set(undefined);+};++export const confirmPendingTemplateNameChange = () => {+ const pending = $pendingTemplateNameConfirmation.get();+ if (pending === undefined) {+ return;+ }+ $pendingTemplateNameConfirmation.set(undefined);+ const operation = {+ ...pending.operation,+ input: {+ ...pending.operation.input,+ templateNameConfirmation: pending.confirmation,+ },+ } as RuntimeMutationOperation;+ let result: BuilderRuntimeMutation | undefined;+ try {+ result = executeRuntimeMutation(operation);+ } catch (error) {+ toast.error(+ error instanceof Error+ ? error.message+ : "The template change could not be applied."+ );+ return;+ }+ if (result === undefined) {+ return;+ }+ if (operation.id === "instances.delete") {+ clearInstanceSelection();+ }+ if (+ operation.id === "instances.deleteBySelector" &&+ "instanceSelector" in result.result &&+ Array.isArray(result.result.instanceSelector) &&+ result.result.instanceSelector.every(+ (instanceId) => typeof instanceId === "string")- );+ ) {+ selectInstance(result.result.instanceSelector);+ }};export const executeRuntimeMutationSequence = (@@ -135,6 +396,9 @@ export const executeRuntimeMutationSequence = (if (canCommitWebstudioData() === false) {return;}+ if (canEditSelectedMaterializedContent() === false) {+ return;+ }const accumulator = createRuntimeMutationAccumulator(getWebstudioData());const results = operations.map(({ id, input }) => {return accumulator.stage(@@ -166,19 +430,24 @@ export const executeRuntimeMutationAsync = async <if (canCommitWebstudioData() === false) {return;}+ if (canEditSelectedMaterializedContent() === false) {+ return;+ }const result = await executeBuilderRuntimeOperation<RuntimeMutationResult<Id>>(createRuntimeMutationArgs({ id, input, context }));- return commitRuntimeMutation(result);+ return commitRuntimeMutationAsync(result);};+const defaultProjectSettings = { meta: {}, compiler: {} };+export const getWebstudioData = () => {const data = readBuilderStateStores();const { pages } = data;if (pages === undefined) {throw Error(`Cannot get webstudio data with empty pages`);}- const projectSettings = data.projectSettings ?? { meta: {}, compiler: {} };+ const projectSettings = data.projectSettings ?? defaultProjectSettings;return {...data,pages,diff --git a/apps/builder/app/shared/instance-utils/insert.ts b/apps/builder/app/shared/instance-utils/insert.tsindex e65cdb4a7c..2965bfc968 100644--- a/apps/builder/app/shared/instance-utils/insert.ts+++ b/apps/builder/app/shared/instance-utils/insert.ts@@ -26,7 +26,11 @@ import {$selectedPage,selectInstance,} from "../nano-states";-import { $instances, $project, $props } from "../sync/data-stores";+import { $project } from "../sync/data-stores";+import {+ $runtimeInstances as $instances,+ $runtimeProps as $props,+} from "../content-block-content";import { getInstanceLabel } from "~/builder/shared/instance-label";import { executeRuntimeMutation } from "./data";diff --git a/apps/builder/app/shared/instance-utils/mutation.ts b/apps/builder/app/shared/instance-utils/mutation.tsindex 5458d37841..55f985804c 100644--- a/apps/builder/app/shared/instance-utils/mutation.ts+++ b/apps/builder/app/shared/instance-utils/mutation.ts@@ -16,7 +16,10 @@ import {selectInstance,} from "../nano-states";import type { InstancePath } from "@webstudio-is/project-build/runtime";-import { $instances, $props } from "../sync/data-stores";+import {+ $runtimeInstances as $instances,+ $runtimeProps as $props,+} from "../content-block-content";import { $instanceTags } from "~/builder/features/style-panel/shared/model";import {type DroppableTarget,diff --git a/apps/builder/app/shared/instance-utils/selection.ts b/apps/builder/app/shared/instance-utils/selection.tsindex 71e91eecf9..bc6eec0ae3 100644--- a/apps/builder/app/shared/instance-utils/selection.ts+++ b/apps/builder/app/shared/instance-utils/selection.ts@@ -1,4 +1,8 @@-import { ROOT_INSTANCE_ID, type Instances } from "@webstudio-is/sdk";+import {+ ROOT_INSTANCE_ID,+ type Instance,+ type Instances,+} from "@webstudio-is/sdk";import {areInstanceSelectorsEqual,isDescendantOrSelf,@@ -170,7 +174,11 @@ const isKnownSelectorSegment = (export const canResolveInstanceSelector = (instanceSelector: InstanceSelector,- instances: Instances+ instances: Instances,+ getChildren: (+ instance: Instance,+ selector: InstanceSelector+ ) => Instance["children"] = (instance) => instance.children) => {for (let index = 0; index < instanceSelector.length; index += 1) {if (isKnownSelectorSegment(instanceSelector, index, instances) === false) {@@ -188,9 +196,12 @@ export const canResolveInstanceSelector = (continue;}- const parentInstance = instances.get(parentId);+ const parentInstance =+ instances.get(parentId) ??+ instances.get(getIndexedBaseInstanceId(parentId) ?? "");if (- parentInstance?.children.some(+ parentInstance === undefined ||+ getChildren(parentInstance, instanceSelector.slice(index + 1)).some((child) => child.type === "id" && child.value === instanceId) !== true) {diff --git a/apps/builder/app/shared/nano-states/canvas.ts b/apps/builder/app/shared/nano-states/canvas.tsindex 57b005b136..1bc831923e 100644--- a/apps/builder/app/shared/nano-states/canvas.ts+++ b/apps/builder/app/shared/nano-states/canvas.ts@@ -2,7 +2,7 @@ import { atom, computed } from "nanostores";import type { Instance, Instances } from "@webstudio-is/sdk";import type { FontWeight } from "@webstudio-is/fonts";import type { Rect } from "@webstudio-is/design-system";-import { $instances } from "../sync/data-stores";+import { $runtimeInstances as $instances } from "../content-block-content";import type { InstanceSelector } from "@webstudio-is/project-build/runtime";export type TextToolbarState = {diff --git a/apps/builder/app/shared/nano-states/components.ts b/apps/builder/app/shared/nano-states/components.tsindex caa3c07fe7..6ff68e4bc4 100644--- a/apps/builder/app/shared/nano-states/components.ts+++ b/apps/builder/app/shared/nano-states/components.ts@@ -14,7 +14,10 @@ import {type WsComponentMeta,} from "@webstudio-is/sdk";import type { InstanceSelector } from "@webstudio-is/project-build/runtime";-import { $props, $instances } from "../sync/data-stores";+import {+ $runtimeInstances as $instances,+ $runtimeProps as $props,+} from "../content-block-content";import { $memoryProps } from "./misc";import { $selectedPage } from "./pages";import { $selectedInstanceSelector, getInstanceKey } from "./instances";diff --git a/apps/builder/app/shared/nano-states/instance-selection.test.ts b/apps/builder/app/shared/nano-states/instance-selection.test.tsindex 91f5052395..550073f65a 100644--- a/apps/builder/app/shared/nano-states/instance-selection.test.ts+++ b/apps/builder/app/shared/nano-states/instance-selection.test.ts@@ -1,6 +1,16 @@import { beforeEach, describe, expect, test } from "vitest";-import type { Instance } from "@webstudio-is/sdk";-import { $instances, $pages } from "../sync/data-stores";+import {+ blockComponent,+ blockTemplateComponent,+ elementComponent,+ type Instance,+} from "@webstudio-is/sdk";+import { $instances, $pages, $props } from "../sync/data-stores";+import {+ publishMaterializedContentRoot,+ resetMaterializedContent,+ getRuntimeInstanceChildren,+} from "../content-block-content";import {$allSelectedInstanceSelectors,$selectedInstance,@@ -25,13 +35,134 @@ const createInstance = (});beforeEach(() => {+ resetMaterializedContent();$instances.set(new Map());+ $props.set(new Map());$pages.set(undefined);$selectedPageId.set(undefined);selectInstance(undefined);});describe("selectInstance", () => {+ test("keeps a repeated MDX child selected through projected store updates", () => {+ const renderScope = JSON.stringify([+ "block",+ "collection[1]",+ "collection",+ "body",+ ]);+ $instances.set(+ new Map([+ ["body", createInstance("body", [{ type: "id", value: "collection" }])],+ [+ "collection",+ createInstance("collection", [{ type: "id", value: "block" }]),+ ],+ [+ "block",+ {+ ...createInstance("block", [{ type: "id", value: "templates" }]),+ component: blockComponent,+ },+ ],+ [+ "templates",+ { ...createInstance("templates"), component: blockTemplateComponent },+ ],+ ])+ );+ $props.set(+ new Map([+ [+ "src",+ {+ id: "src",+ instanceId: "block",+ name: "src",+ type: "expression",+ value: "article",+ },+ ],+ ])+ );+ const identity = {+ blockInstanceId: "block",+ assetId: "article",+ revision: "sha256:one",+ contentRef: "article.mdx",+ format: "mdx",+ renderScope,+ } as const;+ publishMaterializedContentRoot(+ {+ identity,+ fragment: {+ children: [{ type: "id", value: "external" }],+ instances: [+ {+ ...createInstance("external"),+ component: elementComponent,+ tag: "p",+ },+ ],+ props: [],+ assets: [],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ },+ },+ [+ {+ code: "unresolved-template",+ severity: "warning",+ blockInstanceId: "block",+ assetId: "article",+ contentRef: "article.mdx",+ renderScope,+ templateName: "Missing",+ },+ ]+ );++ selectInstance([+ "external",+ "block",+ "collection[1]",+ "collection",+ "body",+ ]);+ $instances.set(new Map($instances.get()));++ expect($selectedInstanceSelector.get()).toEqual([+ "external",+ "block",+ "collection[1]",+ "collection",+ "body",+ ]);++ const block = $instances.get().get("block");+ if (block === undefined) {+ throw new Error("Expected Content Block");+ }+ const warningId = getRuntimeInstanceChildren(block, [+ "block",+ "collection[1]",+ "collection",+ "body",+ ]).at(-1)?.value;+ if (warningId === undefined) {+ throw new Error("Expected unresolved-template notice");+ }+ selectInstance([warningId, "block", "collection[1]", "collection", "body"]);+ $instances.set(new Map($instances.get()));+ expect($selectedInstanceSelector.get()?.[0]).toBe(warningId);+ });+test("selects and clears the selected instance selector through canonical state", () => {selectInstance(["box", "body"]);expect($allSelectedInstanceSelectors.get()).toEqual([["box", "body"]]);diff --git a/apps/builder/app/shared/nano-states/instance-selection.ts b/apps/builder/app/shared/nano-states/instance-selection.tsindex fca5ad7396..5dc554ca4e 100644--- a/apps/builder/app/shared/nano-states/instance-selection.ts+++ b/apps/builder/app/shared/nano-states/instance-selection.ts@@ -8,7 +8,10 @@ import {canResolveInstanceSelector,normalizeInstanceSelectors,} from "../instance-utils/selection";-import { $instances } from "../sync/data-stores";+import {+ $runtimeInstances as $instances,+ getRuntimeInstanceChildren,+} from "../content-block-content";export const $allSelectedInstanceSelectors = atom<InstanceSelector[]>([]);// Instance pruning is derived from tree updates and must not be synchronized@@ -82,7 +85,11 @@ $instances.listen((instances) => {}setSelectedInstances(selectedSelectors.filter((instanceSelector) =>- canResolveInstanceSelector(instanceSelector, instances)+ canResolveInstanceSelector(+ instanceSelector,+ instances,+ getRuntimeInstanceChildren+ )),"instance-pruning");diff --git a/apps/builder/app/shared/nano-states/instances.ts b/apps/builder/app/shared/nano-states/instances.tsindex 4f08447ef4..c428ecba20 100644--- a/apps/builder/app/shared/nano-states/instances.ts+++ b/apps/builder/app/shared/nano-states/instances.ts@@ -5,7 +5,7 @@ import {ROOT_INSTANCE_ID,rootComponent,} from "@webstudio-is/sdk";-import { $instances } from "../sync/data-stores";+import { $runtimeInstances as $instances } from "../content-block-content";import type { InstanceSelector } from "@webstudio-is/project-build/runtime";import { getInstancePath } from "@webstudio-is/project-build/runtime";import { $selectedPage } from "./pages";@@ -119,14 +119,18 @@ export const getInstanceKey = <): (InstanceSelector extends undefined ? undefined : never) | string =>JSON.stringify(instanceSelector);+export const getInstanceKeyWithRoot = (instanceSelector: InstanceSelector) =>+ getInstanceKey(+ instanceSelector[0] === ROOT_INSTANCE_ID+ ? instanceSelector+ : [...instanceSelector, ROOT_INSTANCE_ID]+ );+export const $selectedInstanceKeyWithRoot = computed($selectedInstanceSelector,(instanceSelector) => {if (instanceSelector) {- if (instanceSelector[0] === ROOT_INSTANCE_ID) {- return getInstanceKey(instanceSelector);- }- return getInstanceKey([...instanceSelector, ROOT_INSTANCE_ID]);+ return getInstanceKeyWithRoot(instanceSelector);}});diff --git a/apps/builder/app/shared/nano-states/misc.ts b/apps/builder/app/shared/nano-states/misc.tsindex be9b0c5f20..bfb1ec6a51 100644--- a/apps/builder/app/shared/nano-states/misc.ts+++ b/apps/builder/app/shared/nano-states/misc.ts@@ -29,14 +29,13 @@ import { type InstanceSelector } from "@webstudio-is/project-build/runtime";import type { ChildrenOrientation } from "@webstudio-is/design-system";import { $selectedInstance, $selectedInstanceSelector } from "./instances";import { getPermissions } from "../permissions";+import { $project, $publisherHost } from "../sync/data-stores";import {- $project,- $publisherHost,- $props,- $styles,- $styleSources,- $styleSourceSelections,-} from "../sync/data-stores";+ $runtimeProps as $props,+ $runtimeStyles as $styles,+ $runtimeStyleSources as $styleSources,+ $runtimeStyleSourceSelections as $styleSourceSelections,+} from "../content-block-content";export const $publishedOrigin = computed([$project, $publisherHost],diff --git a/apps/builder/app/shared/nano-states/props.ts b/apps/builder/app/shared/nano-states/props.tsindex 3dfa9e48ef..2046f58978 100644--- a/apps/builder/app/shared/nano-states/props.ts+++ b/apps/builder/app/shared/nano-states/props.ts@@ -22,8 +22,14 @@ import {getCollectionEntries,} from "@webstudio-is/react-sdk";import { mapGroupBy } from "~/shared/shim";-import { $instances } from "../sync/data-stores";-import { $dataSources, $props, $assets, $resources } from "../sync/data-stores";+import {+ $runtimeAssets as $assets,+ $runtimeDataSources as $dataSources,+ $runtimeInstances as $instances,+ $runtimeProps as $props,+ $runtimeResources as $resources,+ getRuntimeInstanceChildren,+} from "../content-block-content";import { $uploadingFilesDataStore, $memoryProps, $isPreviewMode } from "./misc";import { $pages } from "../sync/data-stores";import type { InstanceSelector } from "@webstudio-is/project-build/runtime";@@ -334,7 +340,10 @@ export const $propValuesByInstanceSelector = computed(}return;}- for (const child of instance.children) {+ for (const child of getRuntimeInstanceChildren(+ instance,+ instanceSelector+ )) {// plain text can be edited from props panelif (child.type === "text" && instance.children.length === 1) {propValues.set(textContentAttribute, child.value);@@ -557,7 +566,10 @@ export const $variableValuesByInstanceSelector = computed(variableValues = globalVariableValues;variableNames = globalVariableNames;}- for (const child of instance.children) {+ for (const child of getRuntimeInstanceChildren(+ instance,+ instanceSelector+ )) {if (child.type === "id") {traverseInstances([child.value, ...instanceSelector],diff --git a/apps/builder/app/shared/pubsub/index.ts b/apps/builder/app/shared/pubsub/index.tsindex 55cdcc3c38..60cb9c410c 100644--- a/apps/builder/app/shared/pubsub/index.ts+++ b/apps/builder/app/shared/pubsub/index.ts@@ -16,6 +16,12 @@ export interface PubsubMap extends NamespacedCommands {name: string;[key: string]: unknown;};+ contentBlockSourceStatus: {+ projectId: string;+ blockInstanceId: string;+ renderScope: string;+ status: "loading" | "ready";+ };}export const { publish, usePublish, useSubscribe, subscribe } =diff --git a/apps/builder/app/shared/sync/data-stores.ts b/apps/builder/app/shared/sync/data-stores.tsindex 1817227cb1..a2449b047c 100644--- a/apps/builder/app/shared/sync/data-stores.ts+++ b/apps/builder/app/shared/sync/data-stores.ts@@ -83,6 +83,16 @@ export const readBuilderStateStores = () => ({projectSettings: $projectSettings.get(),});+export const hasSameBuilderStateStoreReferences = (+ left: ReturnType<typeof readBuilderStateStores>,+ right: ReturnType<typeof readBuilderStateStores>+) =>+ Object.keys(left).every(+ (namespace) =>+ left[namespace as keyof typeof left] ===+ right[namespace as keyof typeof right]+ );+/*** Get initial values for all data stores.* Used for resetting stores when switching between projects.diff --git a/apps/builder/e2e/fixtures/assets/alternate-source.mdx b/apps/builder/e2e/fixtures/assets/alternate-source.mdxnew file mode 100644index 0000000000..2c8f4c00d9--- /dev/null+++ b/apps/builder/e2e/fixtures/assets/alternate-source.mdx@@ -0,0 +1,3 @@+# Alternate MDX heading++Alternate MDX source text.diff --git a/apps/builder/e2e/fixtures/assets/content-source.mdx b/apps/builder/e2e/fixtures/assets/content-source.mdxnew file mode 100644index 0000000000..74c603068f--- /dev/null+++ b/apps/builder/e2e/fixtures/assets/content-source.mdx@@ -0,0 +1,7 @@+---+title: Content source fixture+---++# MDX source heading++Editable MDX source text.diff --git a/apps/builder/e2e/fixtures/assets/unresolved-source.mdx b/apps/builder/e2e/fixtures/assets/unresolved-source.mdxnew file mode 100644index 0000000000..031b134814--- /dev/null+++ b/apps/builder/e2e/fixtures/assets/unresolved-source.mdx@@ -0,0 +1,5 @@+# Valid MDX sibling++<ws.element ws:name="Missing E2E Template" />++Valid content after the missing template.diff --git a/apps/builder/e2e/fixtures/mdx-content-block-project.ts b/apps/builder/e2e/fixtures/mdx-content-block-project.tsnew file mode 100644index 0000000000..261d9d9834--- /dev/null+++ b/apps/builder/e2e/fixtures/mdx-content-block-project.ts@@ -0,0 +1,222 @@+import { encodeDataSourceVariable } from "@webstudio-is/sdk";+import { loadDevBuild, updateBuild } from "../db";++type InstanceData = {+ type: "instance";+ id: string;+ component: string;+ children: Array<{ type: string; value: string }>;+};++type PropData = {+ id: string;+ instanceId: string;+ name: string;+ type: string;+ value: unknown;+};++type DataSourceData = {+ id: string;+ type: string;+ name: string;+ scopeInstanceId: string;+ value?: unknown;+};++const blockId = "content-block";+const templateId = "content-block-template";++const getBuildData = async (projectId: string) => {+ const build = await loadDevBuild({ projectId });+ return {+ build,+ instances: JSON.parse(build.instances) as InstanceData[],+ props: JSON.parse(build.props) as PropData[],+ dataSources: JSON.parse(build.dataSources) as DataSourceData[],+ };+};++export const configureRepresentableContentBlockBody = async (+ projectId: string+) => {+ const { build, instances } = await getBuildData(projectId);+ const block = instances.find((instance) => instance.id === blockId);+ if (block === undefined) {+ throw new Error("Expected the Content Block fixture instance");+ }+ block.children = [+ { type: "id", value: "list-item" },+ { type: "id", value: templateId },+ ];+ await updateBuild(build.id, { instances: JSON.stringify(instances) });+};++const configureSourceBlock = ({+ instances,+ props,+ expression,+}: {+ instances: InstanceData[];+ props: PropData[];+ expression: string;+}) => {+ const block = instances.find((instance) => instance.id === blockId);+ if (block === undefined) {+ throw new Error("Expected the Content Block fixture instance");+ }+ block.children = [{ type: "id", value: templateId }];+ props.push({+ id: "content-block-source",+ instanceId: blockId,+ name: "src",+ type: "expression",+ value: expression,+ });+};++export const configureDynamicDetailContentBlock = async ({+ projectId,+ initialAssetId,+}: {+ projectId: string;+ initialAssetId: string;+}) => {+ const { build, instances, props, dataSources } =+ await getBuildData(projectId);+ configureSourceBlock({+ instances,+ props,+ expression: "$ws$system.params.assetid",+ });+ const pages = JSON.parse(build.pages) as {+ homePageId: string;+ rootFolderId: string;+ pages: Array<{+ id: string;+ name: string;+ title: string;+ path: string;+ history?: string[];+ rootInstanceId: string;+ }>;+ folders: Array<{ id: string; children: string[] }>;+ };+ const homePage = pages.pages.find((page) => page.id === pages.homePageId);+ if (homePage === undefined) {+ throw new Error("Expected the Content Block fixture home page");+ }+ const dynamicPageId = homePage.id;+ const homeRootId = "mdx-detail-home-root";+ const body = instances.find(+ (instance) => instance.id === homePage.rootInstanceId+ );+ if (body === undefined) {+ throw new Error("Expected the Content Block fixture page root");+ }+ instances.push({ ...body, id: homeRootId, children: [] });+ pages.pages.push({+ ...homePage,+ id: "mdx-detail-home-page",+ name: "MDX detail home",+ title: JSON.stringify("MDX detail home"),+ path: "",+ history: [],+ rootInstanceId: homeRootId,+ });+ pages.homePageId = "mdx-detail-home-page";+ const rootFolder = pages.folders.find(+ (folder) => folder.id === pages.rootFolderId+ );+ if (rootFolder === undefined) {+ throw new Error("Expected the Content Block fixture root folder");+ }+ rootFolder.children = [+ pages.homePageId,+ dynamicPageId,+ ...rootFolder.children.filter((id) => id !== dynamicPageId),+ ];+ homePage.name = "Dynamic MDX detail";+ homePage.title = JSON.stringify("Dynamic MDX detail");+ homePage.path = "/:assetid";+ homePage.history = [`/${initialAssetId}`];+ await updateBuild(build.id, {+ instances: JSON.stringify(instances),+ props: JSON.stringify(props),+ dataSources: JSON.stringify(dataSources),+ pages: JSON.stringify(pages),+ });+ return dynamicPageId;+};++export const configureRepeatedContentBlock = async ({+ projectId,+ assetIds,+}: {+ projectId: string;+ assetIds: [string, string];+}) => {+ const { build, instances, props, dataSources } =+ await getBuildData(projectId);+ const collectionId = "mdx-content-collection";+ const itemParameterId = "mdx-content-collection-item";+ const itemKeyParameterId = "mdx-content-collection-item-key";+ configureSourceBlock({+ instances,+ props,+ expression: `${encodeDataSourceVariable(itemParameterId)}?.assetId`,+ });+ const body = instances.find((instance) => instance.id === "body");+ if (body === undefined) {+ throw new Error("Expected the Content Block fixture body");+ }+ body.children = [{ type: "id", value: collectionId }];+ instances.push({+ type: "instance",+ id: collectionId,+ component: "ws:collection",+ children: [{ type: "id", value: blockId }],+ });+ props.push(+ {+ id: "mdx-content-collection-data",+ instanceId: collectionId,+ name: "data",+ type: "json",+ value: assetIds.map((assetId) => ({ assetId })),+ },+ {+ id: "mdx-content-collection-item-prop",+ instanceId: collectionId,+ name: "item",+ type: "parameter",+ value: itemParameterId,+ },+ {+ id: "mdx-content-collection-item-key-prop",+ instanceId: collectionId,+ name: "itemKey",+ type: "parameter",+ value: itemKeyParameterId,+ }+ );+ dataSources.push(+ {+ id: itemParameterId,+ type: "parameter",+ name: "collectionItem",+ scopeInstanceId: collectionId,+ },+ {+ id: itemKeyParameterId,+ type: "parameter",+ name: "collectionItemKey",+ scopeInstanceId: collectionId,+ }+ );+ await updateBuild(build.id, {+ instances: JSON.stringify(instances),+ props: JSON.stringify(props),+ dataSources: JSON.stringify(dataSources),+ });+};diff --git a/apps/builder/e2e/flows/assets-panel.ts b/apps/builder/e2e/flows/assets-panel.tsindex 1c4dd06889..c96f6d3fd3 100644--- a/apps/builder/e2e/flows/assets-panel.ts+++ b/apps/builder/e2e/flows/assets-panel.ts@@ -174,6 +174,24 @@ export const chooseAssetByFilename = async ({filename: string;}) => {const title = await waitForAsset({ page, filename });- await page.getByAltText(title, { exact: true }).last().click();+ await page.getByTitle(title, { exact: true }).last().click();return title;};++export const getAssetIdByFilename = async ({+ page,+ filename,+}: {+ page: Page;+ filename: string;+}) => {+ const title = await waitForAsset({ page, filename });+ const dragKey = await page+ .getByTitle(title)+ .locator("xpath=ancestor-or-self::*[@data-asset-manager-drag-key][1]")+ .getAttribute("data-asset-manager-drag-key");+ if (dragKey?.startsWith("asset:") !== true) {+ throw new Error(`Expected uploaded asset ${filename} to expose its id`);+ }+ return dragKey.slice("asset:".length);+};diff --git a/apps/builder/e2e/flows/builder.ts b/apps/builder/e2e/flows/builder.tsindex cf3c1bcd5a..84f5e7f986 100644--- a/apps/builder/e2e/flows/builder.ts+++ b/apps/builder/e2e/flows/builder.ts@@ -128,16 +128,22 @@ export const openProjectBuilder = async ({authToken,mode,features,+ pageId,}: {page: Page;projectId: string;authToken?: string;mode?: "content" | "preview";features?: string[];+ pageId?: string;}): Promise<Frame> => {- await page.goto(+ const url = new URL(getProjectBuilderUrl({ projectId, authToken, mode, features }));+ if (pageId !== undefined) {+ url.searchParams.set("pageId", pageId);+ }+ await page.goto(url.href);await page.waitForLoadState("networkidle", { timeout: builderNetworkIdleTimeout }).catch(() => undefined);diff --git a/apps/builder/e2e/flows/content-block-source.ts b/apps/builder/e2e/flows/content-block-source.tsnew file mode 100644index 0000000000..6dcf5d8a95--- /dev/null+++ b/apps/builder/e2e/flows/content-block-source.ts@@ -0,0 +1,47 @@+import type { Page } from "playwright";+import { chooseAssetByFilename } from "./assets-panel";+import { selectNavigatorItem } from "./navigator";++export const selectContentBlock = async ({ page }: { page: Page }) => {+ await selectNavigatorItem({ page, name: "Content Block" });+ await page.getByText("Content source", { exact: true }).waitFor({+ state: "visible",+ timeout: 10_000,+ });+};++export const chooseContentBlockSource = async ({+ page,+ filename,+ action = "Choose file",+}: {+ page: Page;+ filename: string;+ action?: "Choose file" | "Replace or switch";+}) => {+ await page.getByRole("button", { name: action, exact: true }).click();+ await chooseAssetByFilename({ page, filename });+};++export const useFileContent = async ({ page }: { page: Page }) => {+ const dialog = page.getByRole("dialog", { name: /content source$/i });+ await dialog.waitFor({ state: "visible" });+ await dialog.getByRole("button", { name: "Use file content" }).click();+ await dialog.waitFor({ state: "hidden" });+};++export const disconnectContentBlockSource = async ({+ page,+}: {+ page: Page;+}) => {+ await page.getByRole("button", { name: "Disconnect", exact: true }).click();+ const dialog = page.getByRole("dialog", {+ name: "Disconnect content source",+ });+ await dialog.waitFor({ state: "visible" });+ await dialog+ .getByRole("button", { name: "Copy file content and disconnect" })+ .click();+ await dialog.waitFor({ state: "hidden" });+};diff --git a/apps/builder/e2e/flows/content-editing.ts b/apps/builder/e2e/flows/content-editing.tsindex 837d409b0e..cd55625a1c 100644--- a/apps/builder/e2e/flows/content-editing.ts+++ b/apps/builder/e2e/flows/content-editing.ts@@ -96,17 +96,21 @@ export const replaceCanvasText = async ({page,currentText,text,+ waitForProjectSync = true,}: {page: Page;currentText: string;text: string;+ waitForProjectSync?: boolean;}) => {const { canvas, editable } = await startCanvasTextEditingByText({page,currentText,});await page.keyboard.press("ControlOrMeta+A");- const save = waitForChangeToBeSaved({ page });+ const save = waitForProjectSync+ ? waitForChangeToBeSaved({ page })+ : Promise.resolve();try {await page.keyboard.type(text);await canvas.locator("body").click({ position: { x: 1, y: 1 } });diff --git a/apps/builder/e2e/flows/navigator.ts b/apps/builder/e2e/flows/navigator.tsindex 7e6ab82c26..10ee83c884 100644--- a/apps/builder/e2e/flows/navigator.ts+++ b/apps/builder/e2e/flows/navigator.ts@@ -10,3 +10,20 @@ export const openNavigatorPanel = async ({ page }: { page: Page }) => {timeout: 10_000,});};++export const selectNavigatorItem = async ({+ page,+ name,+}: {+ page: Page;+ name: string;+}) => {+ await openNavigatorPanel({ page });+ const item = page+ .locator("[data-navigator-tree] [data-tree-button]")+ .filter({ hasText: name })+ .last();+ await item.waitFor({ state: "visible" });+ await item.click();+ await item.click();+};diff --git a/apps/builder/e2e/tests/mdx-content-block.[shard-4].e2e.ts b/apps/builder/e2e/tests/mdx-content-block.[shard-4].e2e.tsnew file mode 100644index 0000000000..73527da4c6--- /dev/null+++ b/apps/builder/e2e/tests/mdx-content-block.[shard-4].e2e.ts@@ -0,0 +1,412 @@+import type { Page, Response } from "playwright";+import {+ configureDynamicDetailContentBlock,+ configureRepresentableContentBlockBody,+ configureRepeatedContentBlock,+} from "../fixtures/mdx-content-block-project";+import { createContentModeProject } from "../fixtures/content-mode-suite";+import { expectTextHidden } from "../flows/assertions";+import {+ getAssetIdByFilename,+ openAssetsPanel,+ uploadAsset,+} from "../flows/assets-panel";+import {+ openProjectBuilder,+ waitForCanvasFrame,+ waitForCanvasText,+ waitForCanvasTextHidden,+} from "../flows/builder";+import {+ chooseContentBlockSource,+ disconnectContentBlockSource,+ selectContentBlock,+ useFileContent,+} from "../flows/content-block-source";+import { replaceCanvasText } from "../flows/content-editing";+import { waitForSyncStatus } from "../flows/sync-status";+import { getProjectBuilderUrl, newIsolatedPage, test } from "../harness";++const sourceFilename = "content-source.mdx";+const alternateFilename = "alternate-source.mdx";+const unresolvedFilename = "unresolved-source.mdx";++const sourceHeading = "MDX source heading";+const editedHeading = "Edited MDX source heading";+const alternateHeading = "Alternate MDX heading";++const isAssetContentResponse = (response: Response, method = "PUT") =>+ response.request().method() === method &&+ response.url().includes("/rest/assets/") &&+ response.url().includes("/content");++const waitForAssetWrite = (page: Page) =>+ page.waitForResponse(+ (response) => isAssetContentResponse(response) && response.status() === 200,+ { timeout: 30_000 }+ );++const openFixture = async ({+ page,+ projectId,+ authToken,+ mode,+ pageId,+}: {+ page: Page;+ projectId: string;+ authToken: string;+ mode?: "content" | "preview";+ pageId?: string;+}) => {+ await openProjectBuilder({ page, projectId, authToken, mode, pageId });+ await waitForSyncStatus({ page, status: "idle" });+};++test("Content Block MDX source lifecycle persists edits and disconnect copy", async () => {+ const fixture = await createContentModeProject({+ email: "[email protected]",+ title: "MDX Content Source E2E",+ });+ await configureRepresentableContentBlockBody(fixture.projectId);+ const { page, close } = await newIsolatedPage();++ try {+ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ });+ await openAssetsPanel({ page });+ await uploadAsset({ page, filename: sourceFilename });+ await uploadAsset({ page, filename: alternateFilename });++ await selectContentBlock({ page });+ await chooseContentBlockSource({ page, filename: sourceFilename });+ await useFileContent({ page });+ await waitForCanvasText({ page, text: sourceHeading });++ await Promise.all([+ waitForAssetWrite(page),+ replaceCanvasText({+ page,+ currentText: sourceHeading,+ text: editedHeading,+ waitForProjectSync: false,+ }),+ ]);++ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ });+ await waitForCanvasText({ page, text: editedHeading });+ await selectContentBlock({ page });++ let releaseRead: (() => void) | undefined;+ const readReleased = new Promise<void>((resolve) => {+ releaseRead = resolve;+ });+ let markReadContinued: (() => void) | undefined;+ const readContinued = new Promise<void>((resolve) => {+ markReadContinued = resolve;+ });+ let blockedRead = false;+ await page.route("**/rest/assets/*/content?*", async (route) => {+ if (route.request().method() !== "GET" || blockedRead) {+ await route.continue();+ return;+ }+ blockedRead = true;+ await readReleased;+ await route.continue();+ markReadContinued?.();+ });++ await chooseContentBlockSource({+ page,+ filename: alternateFilename,+ action: "Replace or switch",+ });+ await waitForCanvasText({ page, text: editedHeading });+ await page.getByText("Updating content source…", { exact: true }).waitFor();+ const loadingCanvas = await waitForCanvasFrame({ page });+ await loadingCanvas.getByText(editedHeading, { exact: true }).dblclick();+ if ((await loadingCanvas.locator('[contenteditable="true"]').count()) > 0) {+ throw new Error(+ "Previous MDX content must stay read-only while switching"+ );+ }++ releaseRead?.();+ await readContinued;+ await page.unroute("**/rest/assets/*/content?*");+ await selectContentBlock({ page });+ await chooseContentBlockSource({+ page,+ filename: alternateFilename,+ action: "Replace or switch",+ });+ await useFileContent({ page });+ await waitForCanvasText({ page, text: alternateHeading });+ await waitForCanvasTextHidden({ page, text: editedHeading });++ await selectContentBlock({ page });+ await page.getByRole("button", { name: "Disconnect", exact: true }).click();+ const disconnectDialog = page.getByRole("dialog", {+ name: "Disconnect content source",+ });+ await disconnectDialog.waitFor();+ await disconnectDialog.getByRole("button", { name: "Cancel" }).click();+ await page+ .getByRole("button", { name: "Disconnect", exact: true })+ .waitFor();+ await disconnectContentBlockSource({ page });+ await waitForSyncStatus({ page, status: "idle" });+ await waitForCanvasText({ page, text: alternateHeading });++ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ });+ await waitForCanvasText({ page, text: alternateHeading });+ await selectContentBlock({ page });+ await page.getByText("No content source", { exact: true }).waitFor();+ } finally {+ await close();+ }+});++test("Content Block shows recoverable conflicts without overwriting the file", async () => {+ const fixture = await createContentModeProject({+ email: "[email protected]",+ title: "MDX Content Conflict E2E",+ });+ const { page, close } = await newIsolatedPage();++ try {+ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ });+ await openAssetsPanel({ page });+ await uploadAsset({ page, filename: sourceFilename });+ await selectContentBlock({ page });+ await chooseContentBlockSource({ page, filename: sourceFilename });+ await useFileContent({ page });+ await waitForCanvasText({ page, text: sourceHeading });++ await page.route("**/rest/assets/*/content?*", async (route) => {+ if (route.request().method() === "PUT") {+ await route.fulfill({+ status: 409,+ contentType: "application/json",+ body: JSON.stringify({ message: "Asset revision conflict" }),+ });+ return;+ }+ await route.continue();+ });++ await replaceCanvasText({+ page,+ currentText: sourceHeading,+ text: "Unsaved conflict heading",+ waitForProjectSync: false,+ });+ const canvas = await waitForCanvasFrame({ page });+ await canvas.getByText("MDX conflict", { exact: true }).waitFor();+ await canvas.getByRole("button", { name: "Copy unsaved MDX" }).click();+ const copied = await page.evaluate(async () =>+ navigator.clipboard.readText()+ );+ if (copied.includes("Unsaved conflict heading") === false) {+ throw new Error("Expected conflict recovery to copy the unsaved MDX");+ }++ await page.unroute("**/rest/assets/*/content?*");+ await canvas.getByRole("button", { name: "Reload remote file" }).click();+ await waitForCanvasText({ page, text: sourceHeading });+ await canvas.getByText("MDX conflict", { exact: true }).waitFor({+ state: "hidden",+ });+ } finally {+ await close();+ }+});++test("Unresolved MDX templates are selectable only in the Builder canvas", async () => {+ const fixture = await createContentModeProject({+ email: "[email protected]",+ title: "MDX Content Warning E2E",+ });+ const { page, close } = await newIsolatedPage();++ try {+ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ });+ await openAssetsPanel({ page });+ await uploadAsset({ page, filename: unresolvedFilename });+ await selectContentBlock({ page });+ await chooseContentBlockSource({ page, filename: unresolvedFilename });+ await useFileContent({ page });++ await waitForCanvasText({ page, text: "Valid MDX sibling" });+ await waitForCanvasText({+ page,+ text: "Valid content after the missing template.",+ });+ const canvas = await waitForCanvasFrame({ page });+ const warning = canvas.getByText("Missing template: Missing E2E Template", {+ exact: true,+ });+ await warning.waitFor();+ await warning.click();+ await selectContentBlock({ page });+ await page.getByRole("list", { name: "MDX diagnostics" }).waitFor();+ await page.getByRole("button", { name: "Open file to repair" }).waitFor();++ const previewUrl = getProjectBuilderUrl({+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ mode: "preview",+ });+ await page.goto(previewUrl);+ await waitForCanvasText({ page, text: "Valid MDX sibling" });+ await waitForCanvasText({+ page,+ text: "Valid content after the missing template.",+ });+ const previewCanvas = await waitForCanvasFrame({ page });+ await previewCanvas+ .getByText("Missing template: Missing E2E Template", { exact: true })+ .waitFor({ state: "hidden" });+ await expectTextHidden({ page, text: "Open file to repair" });+ } finally {+ await close();+ }+});++test("Dynamic detail source follows the selected route parameter", async () => {+ const fixture = await createContentModeProject({+ email: "[email protected]",+ title: "MDX Content Detail E2E",+ });+ const { page, close } = await newIsolatedPage();++ try {+ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ });+ await openAssetsPanel({ page });+ await uploadAsset({ page, filename: sourceFilename });+ await uploadAsset({ page, filename: alternateFilename });+ const sourceAssetId = await getAssetIdByFilename({+ page,+ filename: sourceFilename,+ });+ const alternateAssetId = await getAssetIdByFilename({+ page,+ filename: alternateFilename,+ });+ const detailPageId = await configureDynamicDetailContentBlock({+ projectId: fixture.projectId,+ initialAssetId: sourceAssetId,+ });++ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ pageId: detailPageId,+ });+ await waitForCanvasText({ page, text: sourceHeading });++ await page+ .getByRole("button", { name: "Toggle dynamic page address" })+ .click();+ const parameter = page.getByPlaceholder("assetid");+ await parameter.fill(alternateAssetId);+ await parameter.press("Enter");+ await waitForCanvasText({ page, text: alternateHeading });+ await waitForCanvasTextHidden({ page, text: sourceHeading });++ await page+ .getByRole("button", { name: "Toggle dynamic page address" })+ .click();+ await page.getByPlaceholder("assetid").fill(sourceAssetId);+ await page.getByPlaceholder("assetid").press("Enter");+ await waitForCanvasText({ page, text: sourceHeading });+ await waitForCanvasTextHidden({ page, text: alternateHeading });+ } finally {+ await close();+ }+});++test("Repeated Content Block scopes edit distinct MDX files without leakage", async () => {+ const fixture = await createContentModeProject({+ email: "[email protected]",+ title: "MDX Content Repeated E2E",+ });+ const { page, close } = await newIsolatedPage();++ try {+ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ });+ await openAssetsPanel({ page });+ await uploadAsset({ page, filename: sourceFilename });+ await uploadAsset({ page, filename: alternateFilename });+ const sourceAssetId = await getAssetIdByFilename({+ page,+ filename: sourceFilename,+ });+ const alternateAssetId = await getAssetIdByFilename({+ page,+ filename: alternateFilename,+ });+ await configureRepeatedContentBlock({+ projectId: fixture.projectId,+ assetIds: [sourceAssetId, alternateAssetId],+ });++ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ });+ await waitForCanvasText({ page, text: sourceHeading });+ await waitForCanvasText({ page, text: alternateHeading });++ const write = waitForAssetWrite(page);+ await replaceCanvasText({+ page,+ currentText: sourceHeading,+ text: editedHeading,+ waitForProjectSync: false,+ });+ await write;+ await waitForCanvasText({ page, text: editedHeading });+ await waitForCanvasText({ page, text: alternateHeading });++ await openFixture({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ });+ await waitForCanvasText({ page, text: editedHeading });+ await waitForCanvasText({ page, text: alternateHeading });+ } finally {+ await close();+ }+});diff --git a/docs/university/core-components/content-block.md b/docs/university/core-components/content-block.mdindex b4f0768aee..53bf4d03d8 100644--- a/docs/university/core-components/content-block.md+++ b/docs/university/core-components/content-block.md@@ -15,8 +15,8 @@ Designers can create a library of templates, from little cards to fully built seNext is a breakdown of Content Block by mode:-1. [Design mode](content-block.md#design-mode) ⬇️-2. [Content mode](content-block.md#content-mode) ⬇️+1. [Design mode](content-block.md#content-block-in-design-mode) ⬇️+2. [Content mode](content-block.md#content-block-in-content-mode) ⬇️## Content Block in Design mode@@ -40,7 +40,7 @@ Notice that the child of Content Block is Templates. Drag/build the various instances you want to provide editors here.-For example, your client wants to update the section under the hero with the latest promotion. Sometimes the promotion is for an event while other times it’s a product. You can create those two designs, add them to “Templates” within Editable Block, and your client can insert instances of the desired template and edit its content.+For example, your client wants to update the section under the hero with the latest promotion. Sometimes the promotion is for an event while other times it’s a product. You can create those two designs, add them to Templates within the Content Block, and your client can insert instances of the desired template and edit its content.{% hint style="info" %}Editors don’t have access to the Style Panel, so be sure to provide fully designed templates.@@ -56,7 +56,7 @@ Each time they insert a template, its copy appears as a direct child of the ContOptionally, you can add instances as direct children of Content Block.-<figure><img src="../../.gitbook/assets/startingpoint-content-block.png" alt="" width="357"><figcaption><p>The "Feature" instances are provided as a starting point</p></figcaption></figure>+<figure><img src="../../.gitbook/assets/startingpoint-content-block.png" alt="Content Block containing Feature instances as its initial content" width="357"><figcaption><p>The "Feature" instances are provided as a starting point</p></figcaption></figure>Doing so will provide an initial setup for editors.@@ -66,9 +66,9 @@ Editors can delete direct children of the Content Block. They cannot delete theIn [Content mode](../foundations/modes.md#content), you can edit existing content inside Content Blocks. But what if you want to add _new_ content?-You can within Editable Block — region(s) on the page the designer designates as a place you can add new content from building blocks to entire sections.+You can within a Content Block—the region on the page where the designer allows new content, from small building blocks to complete sections.-For example, on your homepage, you change out promotions. Sometimes they are events, and other times they are products. The designer can add the Editable Block to that section on your homepage and provide you with an “Events template” and “Products template”. You can then insert instances of each template, delete them, and change out their content. The design is fully provided for you.+For example, on your homepage, you change out promotions. Sometimes they are events, and other times they are products. The designer can add a Content Block to that section and provide an “Events template” and “Products template”. You can then insert instances of each template, delete them, and change out their content. The design is fully provided for you.Next is how to use it.@@ -86,7 +86,7 @@ Each Content Block can have a unique set of templates you can choose from.On the canvas, hover where you want to insert, and the blue + button will appear. Click that, and you’ll see a list of templates provided by the designer.-<figure><img src="../../.gitbook/assets/templates-content-mode.png" alt=""><figcaption><p>Templates the designer provided</p></figcaption></figure>+<figure><img src="../../.gitbook/assets/templates-content-mode.png" alt="Template choices shown from the Content Block insertion button"><figcaption><p>Templates the designer provided</p></figcaption></figure>Select the one you want, and it’ll insert an instance/copy of that template.@@ -107,8 +107,215 @@ You can’t delete the template itself, so you can always add it back.Beyond adding new content, you can edit the existing content inside the Content Block. See [Content mode](../foundations/modes.md#content) for more information.+## Use an MDX file as the content source++A Content Block can store its editable body in an `.mdx` file in Assets instead+of in the project tree. Editors still work with normal instances on the canvas:+they can type, use the + button, edit allowed props, reorder content, and delete+content. Webstudio saves those changes back to the file as MDX.++The Content Block and its protected Templates list remain in the project. The+file stores only the authored body, so there is never a second persisted copy of+the same children in the project.++### Connect a content source++Select the Content Block, then use **Content source** in its settings. You can:++- Choose an existing `.mdx` Asset.+- Create an empty `.mdx` Asset.+- Bind the source to an expression that resolves to an Asset ID. This supports+ route parameters, detail pages, and repeated Collection content. Each+ rendered scope keeps its own file and editing state.+- Convert an existing `.md` Asset to a new `.mdx` Asset.++Direct selection only accepts `.mdx`. A dynamic expression must also resolve to+an `.mdx` Asset; a missing, inaccessible, or different file type is reported as+a source error. An empty file produces an empty editable region where an editor+can type or use the + button.++Publishing a dynamic source requires a finite candidate set that Webstudio can+derive from the route, detail query, or repeated records. An external or+otherwise unbounded runtime source blocks publication instead of including+unrelated MDX Assets. Dynamic candidates can use read Resources when Webstudio+can select them once per route after base Resources load. Publication rejects+candidate action Resources, Collection-item-scoped selection with+candidate-local Resources, and source/resource dependency cycles.++When both the block and the selected file already have body content, choose+which one becomes authoritative:++- **Use file content** removes the block's persisted body and displays the+ selected file.+- **Replace file body with block content** writes the supported block body to+ the file, then removes the persisted body.++Webstudio never merges the two bodies implicitly. The file's frontmatter is+preserved when its body is replaced. If only one side has body content,+Webstudio selects that side automatically.++Lifecycle and semantic edits validate every target first, then save each target+in a deterministic order. For **Replace file body with block content**, Webstudio+saves the file before connecting the Content Block. If a later step fails, the+earlier writes remain saved and the result identifies the failed and+not-attempted steps. Reinspect the current source and retry only those steps;+Webstudio does not roll back completed file writes.++### Convert Markdown to MDX++Choose **Convert Markdown** to preview the conversion before creating a file.+Webstudio converts everything it can, lists unsupported or unsafe parts, and+skips those parts in the preview. Review the complete converted source, then+choose **Create MDX file**. The original `.md` file is never changed.++Markdown and MDX are separate formats in Webstudio. A `.md` file keeps normal+Markdown behavior, including embedded HTML. An `.mdx` file uses the safe MDX+grammar described below. Changing only the extension does not convert the+content.++### Switch or disconnect a source++Use **Replace or switch** to select another `.mdx` file. Webstudio validates and+loads the new file before replacing the last usable canvas view. If both sides+have content, choose **Use file content** or **Replace file body with block+content** again.++Disconnecting always requires **Copy file content and disconnect**. Webstudio+copies the current resolved file body into ordinary project instances, removes+the source binding, and leaves the file unchanged. This makes it safe to+connect, switch, and disconnect at any time without silently dropping the+visible content.++## Author safe MDX++An MDX Content Block supports frontmatter, standard Markdown, GitHub Flavored+Markdown, comments, and a restricted Webstudio JSX element. It does not execute+arbitrary JavaScript.++Use ordinary Markdown for headings, paragraphs, lists, tables, links, images,+and formatting:++```mdx+---+title: Summer collection+---++# New arrivals++Browse the **latest products**.+```++Use `ws:tag` when Markdown cannot represent the element you need:++```mdx+<ws.element ws:tag="section" data-kind="promotion">++## Limited offer++Save while stock lasts.++</ws.element>+```++Blank lines inside a flow element let MDX parse its body as Markdown. Inline+Markdown and `<ws.element ws:tag="span">` can also appear inside a paragraph.+Write HTML-shaped elements with `ws:tag`; raw `<div>`-style JSX is not accepted+in an `.mdx` file. JSX prop values must be quoted strings or bare boolean+attributes. Webstudio rejects arbitrary component names, imports, exports,+expression blocks, attribute expressions and spreads, event-handler attributes,+unsafe tags, and unsafe URLs.++Webstudio serializes edited files into one deterministic form. A save may+normalize whitespace, quoting, table alignment, and frontmatter key order while+preserving the document's meaning, frontmatter, comments, unresolved template+references, and ignored authored props.++Undo inside an active canvas text editor or the Text File Editor uses that+editor's local history. Webstudio does not add saved MDX file changes to the+Builder's project-wide **Undo** and **Redo** history. Closing or remounting the+editor ends that local file history.++### Insert a template by name++Reference one direct child of the Content Block's flat Templates list with its+exact displayed name:++```mdx+<ws.element ws:name="Hero Card" tone="quiet">+ Optional authored children+</ws.element>+```++Template names must be unique within that Templates list. Webstudio prevents+an explicit duplicate rename. Renaming or deleting a template used by a+source-backed Content Block warns that `ws:name` references may disconnect;+the actions are **Abort** or **Rename**, and **Abort** or **Delete**. Webstudio+does not scan or rewrite every MDX file automatically.++MDX props have the same permissions as Content mode. Eligible content props+are applied to the resolved template. Unknown, stale, incompatible, and+design-only props remain in the file but are ignored and reported. They do not+override template structure or styling.++## Resolve source warnings++While a file loads or switches, Webstudio keeps the previous valid content+visible but read-only. Selectable canvas notices and the Content source control+show the filename, source location, render scope, reason, and a route to open+the file when available.++- **Retry** retries a failed save or load against the same pinned Asset.+- **Reload remote file** accepts the current remote revision after a conflict.+- **Copy unsaved MDX** preserves your local source before reloading or repairing+ the file.++If a `ws:name` has no matching template, Builder keeps the authored subtree and+shows a selectable warning box. Warning boxes exist only in Builder: they are+not added to project data or the MDX file. A published site omits the complete+unresolved subtree, renders its valid siblings, and shows no loading or warning+placeholder. The build reports a structured warning with the Asset, source+location, owning block, route, and render scope. Invalid or unsafe MDX that+cannot be isolated blocks publication for that required source.++## Edit MDX with MCP, CLI, or API++Webstudio's MCP, CLI, API, and Builder use the same parser, permissions,+materialized instance model, serializer, Asset authorization, and revision+checks. The focused Content Block operations can:++- Inspect a configured source, its resolved Asset/revision/render scope,+ capabilities, pending state, diagnostics, and repair routes.+- Connect and switch with the same content-authority choices, and disconnect by+ copying the current file body into the block.+- Apply semantic instance edits to the resolved MDX body.+- Within the same live editing session, retry, reload remote content, or return+ unsaved local MDX for recovery.+- Preview a bounded, AST-based `ws:name` rename or removal across automatically+ discovered or explicitly reviewed `.mdx` Assets, then update selected files+ with exact revision checks.++Use a dry run before a replacement or migration. Operations that require+approval return a short-lived confirmation token bound to the inspected+project, block, files, and revisions. Review the per-file update and omission+counts before confirming. A stale token or revision is rejected rather than+overwriting newer content. Migration reports partial per-file failures without+silently retrying them.++The operations return stable diagnostic and error codes through MCP, direct CLI+calls, and the HTTP API. Lifecycle and semantic edits return ordered per-target+results. They stop after a failed dependent step, leave completed writes in+place, and identify which steps must be replanned and retried. Template+migration similarly applies each explicitly reviewed file with its own revision+check and can return a partial result. Recovery of+unsaved local MDX requires the same live Builder or MCP session; a fresh+one-shot CLI process or stateless HTTP request returns a not-loaded result+instead of guessing which local state to recover. See [Webstudio MCP](../mcp.md)+for discovery and command syntax.+## Related- [Slot](slot.md) – Reusable component slots- [Modes](../foundations/modes.md) – Builder modes including Content mode- [Collection](collection.md) – Iterate over dynamic data+- [Assets](../foundations/assets.md) – Create, convert, and edit content files+- [Content Engine reference](../foundations/content-engine-reference.md) – Query file metadata, frontmatter, and contentdiff --git a/docs/university/foundations/assets.md b/docs/university/foundations/assets.mdindex 2a8bbc5c8c..834786668e 100644--- a/docs/university/foundations/assets.md+++ b/docs/university/foundations/assets.md@@ -17,7 +17,7 @@ The Assets panel is located on the left side of the builder. It stores all stati| **Video** | MP4, MOV, AVI, WebM || **Audio** | MP3, WAV, OGG, M4A || **Documents** | PDF, DOC, DOCX, XLS, XLSX, CSV, PPT, PPTX |-| **Code & text** | TXT, MD, JS, CSS, JSON, HTML, XML |+| **Code & text** | TXT, MD, MDX, JS, CSS, JSON, HTML, XML || **Archives** | ZIP, RAR |{% hint style="info" %}@@ -40,13 +40,16 @@ multiple selected assets does not insert multiple Image components.### Create and edit text filesOpen the add menu in the Assets panel and choose **Create text file**. Enter a-supported filename, such as `notes.md` or `data.json`. Webstudio creates the-blank file in the current folder and opens it in the code editor.+supported filename, such as `notes.md`, `article.mdx`, or `data.json`.+Webstudio creates the blank file in the current folder and opens it in the code+editor. You can also choose **Create MDX file** from a Content Block's+**Content source** control.-You can open uploaded `txt`, `csv`, `md`, `js`, `css`, `json`, `html`, `xml`,-and `svg` assets in the same editor. Syntax highlighting follows the file type;-unsupported text types use plain text. Markdown files also provide formatting-controls and a preview.+You can open uploaded `txt`, `csv`, `md`, `mdx`, `js`, `css`, `json`, `html`,+`xml`, and `svg` assets in the same editor. Syntax highlighting follows the+file type; unsupported text types use plain text. Markdown and MDX files provide+formatting controls. The file editor previews `.md`; connect `.mdx` to a Content+Block to see its materialized result on the canvas.Edits save when the editor loses focus or when you press `Command + S` onmacOS, `Ctrl + S` on Windows, or `Command/Ctrl + Enter`. The file extension is@@ -54,10 +57,28 @@ fixed, but you can rename its basename in Asset settings.### Use assets as content-Markdown and JSON files in Assets can be the source of truth for a site. The-Content Engine reads their structured fields, queries the files, and resolves-links between them. See [Content Engine](content-engine.md) for the supported-file structure and a complete article workflow.+Markdown, MDX, and JSON files in Assets can be the source of truth for a site.+The Content Engine reads their structured fields, queries the files, and+resolves links between them. See [Content Engine](content-engine.md) for the+supported file structure and a complete article workflow.++Markdown and MDX have different rendering and editing behavior:++| Extension | Use |+| --- | --- |+| `.md` | Standard Markdown with its normal embedded HTML behavior. Use it with Content Engine queries or Markdown rendering. |+| `.mdx` | Safe MDX with frontmatter, Markdown, and restricted `<ws.element>` JSX. It can be the editable body of a Content Block. |++The extensions are not interchangeable. A `.md` file may contain HTML that is+not valid safe MDX. From a Content Block, choose **Convert Markdown** to preview+a best-effort conversion. Webstudio lists and skips unsupported parts, creates+a new `.mdx` Asset, and leaves the original `.md` file unchanged.++When a Content Block is connected to an `.mdx` Asset, canvas edits save to that+file. The file is loaded and materialized before the published component tree+renders; the published page does not fetch it from the browser. See [Content+Block](../core-components/content-block.md#use-an-mdx-file-as-the-content-source)+for source binding, switching, recovery, and safe MDX syntax.## Organizing assets with foldersdiff --git a/docs/university/foundations/content-engine-reference.md b/docs/university/foundations/content-engine-reference.mdindex 94aa69a60f..b549d00c60 100644--- a/docs/university/foundations/content-engine-reference.md+++ b/docs/university/foundations/content-engine-reference.md@@ -1,12 +1,24 @@----description: Query Markdown and JSON Assets with the Content Engine.+description: Query Markdown, MDX, and JSON Assets with the Content Engine.---<!-- Generated from the Content Engine schemas and shared CLI documentation. Do not edit directly. --># Content Engine reference-Assets resources query Markdown and JSON files stored in the Assets panel. The Builder and Webstudio MCP use the same structured query contract.+Assets resources query Markdown, MDX, and JSON files stored in the Assets panel. The Builder and Webstudio MCP use the same structured query contract.++## Document formats++Content Engine indexes frontmatter from both `.md` and `.mdx` files and can return either body with `markdown-body-ref`. Their body grammars remain different:++| Extension | Body behavior |+| --- | --- |+| `.md` | Standard Markdown, including its normal embedded HTML behavior. It is not an editable Content Block source. |+| `.mdx` | Safe MDX: Markdown plus restricted `<ws.element>` JSX. It can be an editable Content Block source. |+| `.json` | A JSON object whose root fields are indexed under `properties`. |++Do not treat `.md` and `.mdx` as equivalent extensions. Use the Content Block conversion preview to create a new `.mdx` file from Markdown; unsupported or unsafe HTML is skipped and reported, and the original file remains unchanged.## MCP workflow@@ -22,7 +34,7 @@ Omit `query` when creating a resource to use the default many-result query for a## Fields-Every asset has the standard fields below. Markdown frontmatter and JSON root fields appear under `properties`, for example `properties.slug` or `properties.author.name`. The field catalog reports their observed types, occurrence counts, optionality, and mixed-type state. A JSON content file must contain an object at its root.+Every asset has the standard fields below. Markdown and MDX frontmatter and JSON root fields appear under `properties`, for example `properties.slug` or `properties.author.name`. The field catalog reports their observed types, occurrence counts, optionality, and mixed-type state. A JSON content file must contain an object at its root.| Field | Observed type || --- | --- |@@ -114,9 +126,9 @@ Choose `fields` and disable `includeMetadata` when the page needs only selected| `none` | Returns no file content. Use this for listings and any query that only needs fields or metadata. || `full` | Embeds the complete UTF-8 file content in the content database. `maxBytes` defaults to 1 MiB and cannot be set higher. The query fails if a selected file is larger. || `range` | Embeds a byte range selected by `offset` and `length` in the content database. `length` cannot exceed 256 KiB. |-| `markdown-body-ref` | Stores a reference to a Markdown body. Webstudio filters and paginates first, then reads only the selected bodies from Assets. `maxBytes` defaults to 1 MiB and cannot be set higher. The query fails if a selected source file is larger. |+| `markdown-body-ref` | Stores a reference to a Markdown or MDX body. Webstudio filters and paginates first, then reads only the selected bodies from Assets. `maxBytes` defaults to 1 MiB and cannot be set higher. The query fails if a selected source file is larger. |-Returned content has `encoding` and `text`. A range also reports its `offset`, returned `length`, and total file size. Use `markdown-body-ref` for article pages. It keeps article bodies out of the published content database and resolves relative Markdown links when the selected body is loaded.+Returned content has `encoding` and `text`. A range also reports its `offset`, returned `length`, and total file size. Use `markdown-body-ref` for article pages. It keeps Markdown and MDX bodies out of the published content database and resolves their relative links when the selected body is loaded.## Preview diagnostics@@ -149,7 +161,7 @@ A document reference is an exact object with one string field:{ "$ref": "<relative-path>[#<fragment>]" }```-Markdown references can appear in YAML frontmatter. JSON references can appear anywhere in the document. Either format can reference Markdown or JSON. References do not run inside a Markdown body.+Markdown and MDX references can appear in YAML frontmatter. JSON references can appear anywhere in the document. Any format can reference Markdown, MDX, or JSON. References do not run inside a Markdown or MDX body.| Reference | Inserted value || --- | --- |@@ -191,6 +203,9 @@ Resolve paths relative to the file containing the reference. JSON Pointer uses `| JSON string | 16 KiB || Indexed properties per document | 64 KiB || Generated excerpt | 2 KiB |+| MDX nesting depth | 100 |+| MDX nodes | 20000 |+| MDX JSX props | 4000 || Loaded file | 1 MiB || Loaded content per query | 2 MiB || Loaded files per query | 20 |diff --git a/docs/university/foundations/content-engine.md b/docs/university/foundations/content-engine.mdindex 749b34bffc..ebcf83df35 100644--- a/docs/university/foundations/content-engine.md+++ b/docs/university/foundations/content-engine.md@@ -4,11 +4,18 @@ description: Create a file-based blog with Markdown, Assets queries, and dynamic# 📚 Content Engine-Webstudio's Content Engine turns Markdown and JSON files in Assets into content-you can query and bind in the visual editor. The files remain the source of-truth, including their filenames, folders, metadata, and relative links. You-can move the same files between projects or use them outside Webstudio without-exporting them from a database first.+Webstudio's Content Engine turns Markdown, MDX, and JSON files in Assets into+content you can query and bind in the visual editor. The files remain the+source of truth, including their filenames, folders, metadata, and relative+links. You can move the same files between projects or use them outside+Webstudio without exporting them from a database first.++This tutorial uses `.md` files and a Markdown Embed. Use `.mdx` when the file+must also be the editable body of a [Content+Block](../core-components/content-block.md#use-an-mdx-file-as-the-content-source).+Content Engine indexes the frontmatter and can return the body in either format,+but `.md` keeps standard embedded HTML behavior while `.mdx` uses Webstudio's+safe MDX grammar.This guide creates a blog overview at `/blog` and one dynamic article page at`/blog/:slug`.@@ -291,21 +298,23 @@ will render it without another page design.## Connect content with document references-The Content Engine calls links between Markdown and JSON files **document+The Content Engine calls links between Markdown, MDX, and JSON files **documentreferences**. A document reference replaces an exact `$ref` object with datafrom another content file. This is Webstudio's syntax. It uses URI referencesfor file paths and [JSON Pointer](https://datatracker.ietf.org/doc/html/rfc6901)for values inside JSON files, but it does not implement JSON Schema resolution.-Both supported source formats can reference either target format:+All supported source formats can reference the other content formats:-| Source | Where references can appear | JSON target | Markdown target |+| Source | Where references can appear | JSON target | Markdown or MDX target || --- | --- | --- | --- || Markdown | YAML frontmatter | Yes | Yes |+| MDX | YAML frontmatter | Yes | Yes || JSON | Anywhere in the document | Yes | Yes |-References do not work inside a Markdown body. A `$ref` object can be nested in-an object or array, including inside a file reached through another reference.+References do not work inside a Markdown or MDX body. A `$ref` object can be+nested in an object or array, including inside a file reached through another+reference.### Reference syntax@@ -380,14 +389,14 @@ the resolved `properties.author` value is:}```-The same rules cover JSON to Markdown and Markdown frontmatter to JSON. A-referenced file can contain its own references, so shared records can be-composed across several files.+The same rules cover JSON to Markdown or MDX and Markdown or MDX frontmatter to+JSON. A referenced file can contain its own references, so shared records can+be composed across several files.The Content Engine loads referenced data when a query filters, sorts, or-returns a field that depends on it. The target must be another Markdown or JSON-file in the project's compiled Assets. Missing files, invalid fragments, and-reference cycles fail instead of returning partial data.+returns a field that depends on it. The target must be another Markdown, MDX,+or JSON file in the project's compiled Assets. Missing files, invalid+fragments, and reference cycles fail instead of returning partial data.## Relateddiff --git a/docs/university/mcp.md b/docs/university/mcp.mdindex 3d4b04145e..cb8bcb831c 100644--- a/docs/university/mcp.md+++ b/docs/university/mcp.md@@ -288,6 +288,63 @@ Component and template registry items use a shadcn-compatible top-level shape plPrefer the focused `components.*` tools over dumping `webstudio://project/components`. Do not write local scripts to parse full MCP discovery JSON for common component lookup.For “use every component” or design-system pages, start with compact `components.coverage-plan`, checkpoint, then page through roots/parts instead of dumping the full catalog.+## MDX Content Block workflow++Content Blocks can store their editable body in an `.mdx` Asset. The Builder,+direct CLI, HTTP API, and MCP use the same source resolver, safe MDX parser,+Content mode permissions, serializer, diagnostics, Asset authorization, and+revision checks.++Use the focused tools instead of downloading and rewriting the file as text:++1. Call `inspect-content-block-source` with the Content Block ID and exact+ render scope. For a dynamic source, also pass the bounded route, detail, or+ Collection variables required to resolve it. Inspect the configured source,+ resolved Asset/revision/scope, capabilities, pending session state,+ diagnostics, and repair routes.+2. Use `connect-content-block-source` or `switch-content-block-source`. When+ both sides contain body content, choose exactly `use-file-content` or+ `replace-file-body-with-block-content`; content is never merged implicitly.+3. Use `edit-content-block-source` for semantic text, prop, insert, move,+ reorder, or delete operations against the materialized MDX instances. Do not+ edit generated instance IDs in the file.+4. Use `disconnect-content-block-source` to copy the resolved file content into+ ordinary project instances and remove the source. The file remains+ unchanged; disconnect never discards the visible body.+5. If inspection reports a recoverable state, use+ `recover-content-block-source` only for an advertised action: retry, reload+ the remote revision, or copy unsaved local MDX. Recovery must run in the same+ live MCP or `mcp run` session that owns that state. A fresh one-shot CLI+ process or stateless HTTP request returns `content-source-not-loaded` rather+ than reconstructing unsaved in-memory content.++Run replacement and migration operations with `--dry-run` first. A required+approval returns a short-lived confirmation token bound to the inspected+project, Content Block, files, and revisions. Review the plan, then repeat the+operation with that token. Stale or replayed tokens and changed Asset revisions+are rejected. Disconnect also requires confirmation because it copies the file+body into project storage and removes the source, although it leaves the file+itself unchanged.++Use `migrate-content-block-template-references` to preview a `ws:name` rename+or removal across the bounded `.mdx` files discovered from one Content Block+and template. When automatic discovery cannot prove the complete candidate set,+pass no more than 100 explicitly reviewed Asset IDs. The tool parses the MDX+AST; it does not use search-and-replace. Review the selected files, update and+omission counts, and per-file diagnostics before confirmation. Each file uses+an exact revision check, and partial failures are returned explicitly without+overwriting newer content. Finite direct, detail, and repeated candidate sets+are supported; an unbounded or truncated candidate graph blocks automatic+apply until the reviewed set is supplied.++Read the machine-readable `status`, `code`, diagnostics, and source inspection+after every call. Lifecycle and semantic edits validate their targets, then+persist them in a deterministic order. A partial result lists saved, failed,+and not-attempted steps; completed writes are not rolled back. Reinspect the+current revisions and retry only unfinished steps. Template migration also+commits reviewed files one at a time and reports partial results. See [Content Block](core-components/content-block.md#use-an-mdx-file-as-the-content-source)+for the file grammar and Builder workflow.+## Consumer CapabilitiesMCP lets agents work on one configured Webstudio project at a time. In consumer@@ -319,6 +376,10 @@ terms, agents can:- Update plain text and expression text.- Update structured rich text.- Add, update, delete, and bind element props.+- Inspect, connect, switch, disconnect, recover, and semantically edit+ MDX-backed Content Blocks.+- Preview and apply bounded template-name migrations across reachable MDX+ Assets.- Bind props to expressions, resources, actions, and runtime system values.- Read, add, update, delete, and replace local styles.- Update selected style-source styles.@@ -1919,7 +1980,19 @@ source of truth. For tools with no required arguments, pass `{}`.## Content Engine reference-Assets resources query Markdown and JSON files stored in the Assets panel. The Builder and Webstudio MCP use the same structured query contract.+Assets resources query Markdown, MDX, and JSON files stored in the Assets panel. The Builder and Webstudio MCP use the same structured query contract.++### Document formats++Content Engine indexes frontmatter from both `.md` and `.mdx` files and can return either body with `markdown-body-ref`. Their body grammars remain different:++| Extension | Body behavior |+| --- | --- |+| `.md` | Standard Markdown, including its normal embedded HTML behavior. It is not an editable Content Block source. |+| `.mdx` | Safe MDX: Markdown plus restricted `<ws.element>` JSX. It can be an editable Content Block source. |+| `.json` | A JSON object whose root fields are indexed under `properties`. |++Do not treat `.md` and `.mdx` as equivalent extensions. Use the Content Block conversion preview to create a new `.mdx` file from Markdown; unsupported or unsafe HTML is skipped and reported, and the original file remains unchanged.### MCP workflow@@ -1935,7 +2008,7 @@ Omit `query` when creating a resource to use the default many-result query for a### Fields-Every asset has the standard fields below. Markdown frontmatter and JSON root fields appear under `properties`, for example `properties.slug` or `properties.author.name`. The field catalog reports their observed types, occurrence counts, optionality, and mixed-type state. A JSON content file must contain an object at its root.+Every asset has the standard fields below. Markdown and MDX frontmatter and JSON root fields appear under `properties`, for example `properties.slug` or `properties.author.name`. The field catalog reports their observed types, occurrence counts, optionality, and mixed-type state. A JSON content file must contain an object at its root.| Field | Observed type || --- | --- |@@ -2027,9 +2100,9 @@ Choose `fields` and disable `includeMetadata` when the page needs only selected| `none` | Returns no file content. Use this for listings and any query that only needs fields or metadata. || `full` | Embeds the complete UTF-8 file content in the content database. `maxBytes` defaults to 1 MiB and cannot be set higher. The query fails if a selected file is larger. || `range` | Embeds a byte range selected by `offset` and `length` in the content database. `length` cannot exceed 256 KiB. |-| `markdown-body-ref` | Stores a reference to a Markdown body. Webstudio filters and paginates first, then reads only the selected bodies from Assets. `maxBytes` defaults to 1 MiB and cannot be set higher. The query fails if a selected source file is larger. |+| `markdown-body-ref` | Stores a reference to a Markdown or MDX body. Webstudio filters and paginates first, then reads only the selected bodies from Assets. `maxBytes` defaults to 1 MiB and cannot be set higher. The query fails if a selected source file is larger. |-Returned content has `encoding` and `text`. A range also reports its `offset`, returned `length`, and total file size. Use `markdown-body-ref` for article pages. It keeps article bodies out of the published content database and resolves relative Markdown links when the selected body is loaded.+Returned content has `encoding` and `text`. A range also reports its `offset`, returned `length`, and total file size. Use `markdown-body-ref` for article pages. It keeps Markdown and MDX bodies out of the published content database and resolves their relative links when the selected body is loaded.### Preview diagnostics@@ -2062,7 +2135,7 @@ A document reference is an exact object with one string field:{ "$ref": "<relative-path>[#<fragment>]" }```-Markdown references can appear in YAML frontmatter. JSON references can appear anywhere in the document. Either format can reference Markdown or JSON. References do not run inside a Markdown body.+Markdown and MDX references can appear in YAML frontmatter. JSON references can appear anywhere in the document. Any format can reference Markdown, MDX, or JSON. References do not run inside a Markdown or MDX body.| Reference | Inserted value || --- | --- |@@ -2104,6 +2177,9 @@ Resolve paths relative to the file containing the reference. JSON Pointer uses `| JSON string | 16 KiB || Indexed properties per document | 64 KiB || Generated excerpt | 2 KiB |+| MDX nesting depth | 100 |+| MDX nodes | 20000 |+| MDX JSX props | 4000 || Loaded file | 1 MiB || Loaded content per query | 2 MiB || Loaded files per query | 20 |diff --git a/fixtures/react-router-cloudflare/.webstudio/data.json b/fixtures/react-router-cloudflare/.webstudio/data.jsonindex d5105eda9d..6306c0d759 100644--- a/fixtures/react-router-cloudflare/.webstudio/data.json+++ b/fixtures/react-router-cloudflare/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1pgeukw",+ "bundleVersion": "bundle-13vhe2w","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.server.tsx b/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.server.tsxindex 023be09459..40d1b230d9 100644--- a/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.server.tsx+++ b/fixtures/react-router-cloudflare/app/__generated__/[another-page]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/react-router-cloudflare/app/__generated__/_index.server.tsx b/fixtures/react-router-cloudflare/app/__generated__/_index.server.tsxindex 3896f613db..55164bf9dd 100644--- a/fixtures/react-router-cloudflare/app/__generated__/_index.server.tsx+++ b/fixtures/react-router-cloudflare/app/__generated__/_index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx b/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsxindex ab5d17cf89..6e59009a94 100644--- a/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx+++ b/fixtures/react-router-cloudflare/app/routes/[another-page]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/react-router-cloudflare/app/routes/_index.tsx b/fixtures/react-router-cloudflare/app/routes/_index.tsxindex d8fe87ddaa..eb717f372f 100644--- a/fixtures/react-router-cloudflare/app/routes/_index.tsx+++ b/fixtures/react-router-cloudflare/app/routes/_index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/react-router-docker/.webstudio/data.json b/fixtures/react-router-docker/.webstudio/data.jsonindex d5105eda9d..6306c0d759 100644--- a/fixtures/react-router-docker/.webstudio/data.json+++ b/fixtures/react-router-docker/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1pgeukw",+ "bundleVersion": "bundle-13vhe2w","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/react-router-docker/app/__generated__/[another-page]._index.server.tsx b/fixtures/react-router-docker/app/__generated__/[another-page]._index.server.tsxindex 023be09459..40d1b230d9 100644--- a/fixtures/react-router-docker/app/__generated__/[another-page]._index.server.tsx+++ b/fixtures/react-router-docker/app/__generated__/[another-page]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/react-router-docker/app/__generated__/_index.server.tsx b/fixtures/react-router-docker/app/__generated__/_index.server.tsxindex 3896f613db..55164bf9dd 100644--- a/fixtures/react-router-docker/app/__generated__/_index.server.tsx+++ b/fixtures/react-router-docker/app/__generated__/_index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/react-router-docker/app/routes/[another-page]._index.tsx b/fixtures/react-router-docker/app/routes/[another-page]._index.tsxindex ab5d17cf89..6e59009a94 100644--- a/fixtures/react-router-docker/app/routes/[another-page]._index.tsx+++ b/fixtures/react-router-docker/app/routes/[another-page]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/react-router-docker/app/routes/_index.tsx b/fixtures/react-router-docker/app/routes/_index.tsxindex d8fe87ddaa..eb717f372f 100644--- a/fixtures/react-router-docker/app/routes/_index.tsx+++ b/fixtures/react-router-docker/app/routes/_index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/react-router-netlify/.webstudio/data.json b/fixtures/react-router-netlify/.webstudio/data.jsonindex d5105eda9d..6306c0d759 100644--- a/fixtures/react-router-netlify/.webstudio/data.json+++ b/fixtures/react-router-netlify/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1pgeukw",+ "bundleVersion": "bundle-13vhe2w","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/react-router-netlify/app/__generated__/[another-page]._index.server.tsx b/fixtures/react-router-netlify/app/__generated__/[another-page]._index.server.tsxindex 023be09459..40d1b230d9 100644--- a/fixtures/react-router-netlify/app/__generated__/[another-page]._index.server.tsx+++ b/fixtures/react-router-netlify/app/__generated__/[another-page]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/react-router-netlify/app/__generated__/_index.server.tsx b/fixtures/react-router-netlify/app/__generated__/_index.server.tsxindex 3896f613db..55164bf9dd 100644--- a/fixtures/react-router-netlify/app/__generated__/_index.server.tsx+++ b/fixtures/react-router-netlify/app/__generated__/_index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx b/fixtures/react-router-netlify/app/routes/[another-page]._index.tsxindex ab5d17cf89..6e59009a94 100644--- a/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx+++ b/fixtures/react-router-netlify/app/routes/[another-page]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/react-router-netlify/app/routes/_index.tsx b/fixtures/react-router-netlify/app/routes/_index.tsxindex d8fe87ddaa..eb717f372f 100644--- a/fixtures/react-router-netlify/app/routes/_index.tsx+++ b/fixtures/react-router-netlify/app/routes/_index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/react-router-vercel/.webstudio/data.json b/fixtures/react-router-vercel/.webstudio/data.jsonindex d5105eda9d..6306c0d759 100644--- a/fixtures/react-router-vercel/.webstudio/data.json+++ b/fixtures/react-router-vercel/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1pgeukw",+ "bundleVersion": "bundle-13vhe2w","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/react-router-vercel/app/__generated__/[another-page]._index.server.tsx b/fixtures/react-router-vercel/app/__generated__/[another-page]._index.server.tsxindex 023be09459..40d1b230d9 100644--- a/fixtures/react-router-vercel/app/__generated__/[another-page]._index.server.tsx+++ b/fixtures/react-router-vercel/app/__generated__/[another-page]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/react-router-vercel/app/__generated__/_index.server.tsx b/fixtures/react-router-vercel/app/__generated__/_index.server.tsxindex 3896f613db..55164bf9dd 100644--- a/fixtures/react-router-vercel/app/__generated__/_index.server.tsx+++ b/fixtures/react-router-vercel/app/__generated__/_index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx b/fixtures/react-router-vercel/app/routes/[another-page]._index.tsxindex ab5d17cf89..6e59009a94 100644--- a/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx+++ b/fixtures/react-router-vercel/app/routes/[another-page]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/react-router-vercel/app/routes/_index.tsx b/fixtures/react-router-vercel/app/routes/_index.tsxindex d8fe87ddaa..eb717f372f 100644--- a/fixtures/react-router-vercel/app/routes/_index.tsx+++ b/fixtures/react-router-vercel/app/routes/_index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/ssg-cloudflare-pages/.webstudio/data.json b/fixtures/ssg-cloudflare-pages/.webstudio/data.jsonindex 6f72a667c2..3a375cb3b1 100644--- a/fixtures/ssg-cloudflare-pages/.webstudio/data.json+++ b/fixtures/ssg-cloudflare-pages/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1pgeukw",+ "bundleVersion": "bundle-13vhe2w","build": {"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.server.tsx b/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.server.tsxindex 023be09459..40d1b230d9 100644--- a/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.server.tsx+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/[another-page]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/ssg-cloudflare-pages/app/__generated__/_index.server.tsx b/fixtures/ssg-cloudflare-pages/app/__generated__/_index.server.tsxindex 3896f613db..55164bf9dd 100644--- a/fixtures/ssg-cloudflare-pages/app/__generated__/_index.server.tsx+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/_index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/ssg-cloudflare-pages/pages/another-page/+data.ts b/fixtures/ssg-cloudflare-pages/pages/another-page/+data.tsindex a6b39df159..d31a51808f 100644--- a/fixtures/ssg-cloudflare-pages/pages/another-page/+data.ts+++ b/fixtures/ssg-cloudflare-pages/pages/another-page/+data.ts@@ -70,6 +70,14 @@ export const data = async (pageContext: PageContextServer) => {getResources({ system }).data,url);+ Object.assign(+ resources,+ await loadResources(+ customFetch,+ getResources({ system, resources }).contentData,+ url+ )+ );const pageMeta = getPageMeta({ system, resources });return {diff --git a/fixtures/ssg-cloudflare-pages/pages/index/+data.ts b/fixtures/ssg-cloudflare-pages/pages/index/+data.tsindex 41189eeabd..5d63b8f89a 100644--- a/fixtures/ssg-cloudflare-pages/pages/index/+data.ts+++ b/fixtures/ssg-cloudflare-pages/pages/index/+data.ts@@ -70,6 +70,14 @@ export const data = async (pageContext: PageContextServer) => {getResources({ system }).data,url);+ Object.assign(+ resources,+ await loadResources(+ customFetch,+ getResources({ system, resources }).contentData,+ url+ )+ );const pageMeta = getPageMeta({ system, resources });return {diff --git a/fixtures/ssg-netlify-by-project-id/.webstudio/data.json b/fixtures/ssg-netlify-by-project-id/.webstudio/data.jsonindex 0fb364280a..e8a335f165 100644--- a/fixtures/ssg-netlify-by-project-id/.webstudio/data.json+++ b/fixtures/ssg-netlify-by-project-id/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1pgeukw",+ "bundleVersion": "bundle-13vhe2w","build": {"id": "8f0fdff2-e76b-4f86-9203-ea7df5f1143c","projectId": "8a7358b1-7de3-459d-b7b1-56dddfb6ce1e",diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.server.tsx b/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.server.tsxindex de8b65606e..49b47c91c4 100644--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.server.tsx+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/[redirect]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.server.tsx b/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.server.tsxindex 3896f613db..55164bf9dd 100644--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.server.tsx+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/ssg-netlify-by-project-id/pages/index/+data.ts b/fixtures/ssg-netlify-by-project-id/pages/index/+data.tsindex 41189eeabd..5d63b8f89a 100644--- a/fixtures/ssg-netlify-by-project-id/pages/index/+data.ts+++ b/fixtures/ssg-netlify-by-project-id/pages/index/+data.ts@@ -70,6 +70,14 @@ export const data = async (pageContext: PageContextServer) => {getResources({ system }).data,url);+ Object.assign(+ resources,+ await loadResources(+ customFetch,+ getResources({ system, resources }).contentData,+ url+ )+ );const pageMeta = getPageMeta({ system, resources });return {diff --git a/fixtures/ssg-netlify-by-project-id/pages/redirect/+data.ts b/fixtures/ssg-netlify-by-project-id/pages/redirect/+data.tsindex 8b9723c4ea..c4eac2f7bf 100644--- a/fixtures/ssg-netlify-by-project-id/pages/redirect/+data.ts+++ b/fixtures/ssg-netlify-by-project-id/pages/redirect/+data.ts@@ -70,6 +70,14 @@ export const data = async (pageContext: PageContextServer) => {getResources({ system }).data,url);+ Object.assign(+ resources,+ await loadResources(+ customFetch,+ getResources({ system, resources }).contentData,+ url+ )+ );const pageMeta = getPageMeta({ system, resources });return {diff --git a/fixtures/webstudio-cloudflare-template/.webstudio/data.json b/fixtures/webstudio-cloudflare-template/.webstudio/data.jsonindex 6f72a667c2..3a375cb3b1 100644--- a/fixtures/webstudio-cloudflare-template/.webstudio/data.json+++ b/fixtures/webstudio-cloudflare-template/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1pgeukw",+ "bundleVersion": "bundle-13vhe2w","build": {"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.server.tsx b/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.server.tsxindex 023be09459..40d1b230d9 100644--- a/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.server.tsx+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/[another-page]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/_index.server.tsx b/fixtures/webstudio-cloudflare-template/app/__generated__/_index.server.tsxindex 3896f613db..55164bf9dd 100644--- a/fixtures/webstudio-cloudflare-template/app/__generated__/_index.server.tsx+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/_index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsx b/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsxindex bff4144f99..3d1dcbfc55 100644--- a/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsx+++ b/fixtures/webstudio-cloudflare-template/app/routes/[another-page]._index.tsx@@ -128,6 +128,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx b/fixtures/webstudio-cloudflare-template/app/routes/_index.tsxindex eb8edabb69..b2a45427a4 100644--- a/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx+++ b/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx@@ -128,6 +128,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/.webstudio/data.json b/fixtures/webstudio-features/.webstudio/data.jsonindex 8d973bc83c..d9569cd84b 100644--- a/fixtures/webstudio-features/.webstudio/data.json+++ b/fixtures/webstudio-features/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-1pgeukw",+ "bundleVersion": "bundle-13vhe2w","build": {"id": "1b66ee06-8ea5-4420-9a0e-e0d3a67aca32","projectId": "cddc1d44-af37-4cb6-a430-d300cf6f932d",diff --git a/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.js b/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.jsindex 774f7dfb91..97d770004e 100644--- a/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.js+++ b/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.js@@ -1,194 +1,263 @@-var Yf=Object.defineProperty;var Hf=(t,e)=>{for(var n in e)Yf(t,n,{get:e[n],enumerable:!0})};var Us;function g(t,e,n){function r(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:i,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let u=i.prototype,d=Object.keys(u);for(let l=0;l<d.length;l++){let f=d[l];f in a||(a[f]=u[f].bind(a))}}let o=n?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=n?.Parent?new s:this;r(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var qh=Symbol("zod_brand"),Ne=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},St=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(Us=globalThis).__zod_globalConfig??(Us.__zod_globalConfig={});var At=globalThis.__zod_globalConfig;function be(t){return t&&Object.assign(At,t),At}var L={};Hf(L,{BIGINT_FORMAT_RANGES:()=>Js,Class:()=>uo,NUMBER_FORMAT_RANGES:()=>yo,aborted:()=>et,allowsEval:()=>po,assert:()=>rd,assertEqual:()=>Xf,assertIs:()=>td,assertNever:()=>nd,assertNotEqual:()=>ed,assignProp:()=>He,base64ToUint8Array:()=>Ws,base64urlToUint8Array:()=>Sd,cached:()=>vt,captureStackTrace:()=>Vn,cleanEnum:()=>xd,cleanRegex:()=>sn,clone:()=>we,cloneDef:()=>id,createTransparentProxy:()=>dd,defineLazy:()=>z,esc:()=>Gn,escapeRegex:()=>Ge,explicitlyAborted:()=>go,extend:()=>hd,finalizeIssue:()=>he,floatSafeRemainder:()=>lo,getElementAtPath:()=>ad,getEnumValues:()=>rn,getLengthableOrigin:()=>an,getParsedType:()=>fd,getSizableOrigin:()=>Ks,hexToUint8Array:()=>Ed,isObject:()=>ht,isPlainObject:()=>Xe,issue:()=>kt,joinValues:()=>od,jsonStringifyReplacer:()=>Et,merge:()=>gd,mergeDefs:()=>Qe,normalizeParams:()=>I,nullish:()=>on,numKeys:()=>ld,objectClone:()=>sd,omit:()=>md,optionalKeys:()=>ho,parsedType:()=>_d,partial:()=>bd,pick:()=>pd,prefixIssues:()=>Ve,primitiveTypes:()=>Vs,promiseAllObject:()=>cd,propertyKeyTypes:()=>mo,randomString:()=>ud,required:()=>wd,safeExtend:()=>yd,shallowClone:()=>Gs,slugify:()=>fo,stringifyPrimitive:()=>qs,uint8ArrayToBase64:()=>Ys,uint8ArrayToBase64url:()=>Ad,uint8ArrayToHex:()=>vd,unwrapMessage:()=>nn});function Xf(t){return t}function ed(t){return t}function td(t){}function nd(t){throw new Error("Unexpected value in exhaustive check")}function rd(t){}function rn(t){let e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,o])=>e.indexOf(+r)===-1).map(([r,o])=>o)}function od(t,e="|"){return t.map(n=>qs(n)).join(e)}function Et(t,e){return typeof e=="bigint"?e.toString():e}function vt(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function on(t){return t==null}function sn(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function lo(t,e){let n=t/e,r=Math.round(n),o=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r)<o?0:n-r}var Qs=Symbol("evaluating");function z(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==Qs)return r===void 0&&(r=Qs,r=n()),r},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function sd(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function He(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Qe(...t){let e={};for(let n of t){let r=Object.getOwnPropertyDescriptors(n);Object.assign(e,r)}return Object.defineProperties({},e)}function id(t){return Qe(t._zod.def)}function ad(t,e){return e?e.reduce((n,r)=>n?.[r],t):t}function cd(t){let e=Object.keys(t),n=e.map(r=>t[r]);return Promise.all(n).then(r=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=r[s];return o})}function ud(t=10){let e="abcdefghijklmnopqrstuvwxyz",n="";for(let r=0;r<t;r++)n+=e[Math.floor(Math.random()*e.length)];return n}function Gn(t){return JSON.stringify(t)}function fo(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Vn="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function ht(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var po=vt(()=>{if(At.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Xe(t){if(ht(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let n=e.prototype;return!(ht(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Gs(t){return Xe(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function ld(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}var fd=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},mo=new Set(["string","number","symbol"]),Vs=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Ge(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function we(t,e,n){let r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function I(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function dd(t){let e;return new Proxy({},{get(n,r,o){return e??(e=t()),Reflect.get(e,r,o)},set(n,r,o,s){return e??(e=t()),Reflect.set(e,r,o,s)},has(n,r){return e??(e=t()),Reflect.has(e,r)},deleteProperty(n,r){return e??(e=t()),Reflect.deleteProperty(e,r)},ownKeys(n){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(n,r){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,r)},defineProperty(n,r,o){return e??(e=t()),Reflect.defineProperty(e,r,o)}})}function qs(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function ho(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var yo={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Js={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function pd(t,e){let n=t._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let s=Qe(t._zod.def,{get shape(){let i={};for(let a in e){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(i[a]=n.shape[a])}return He(this,"shape",i),i},checks:[]});return we(t,s)}function md(t,e){let n=t._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let s=Qe(t._zod.def,{get shape(){let i={...t._zod.def.shape};for(let a in e){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete i[a]}return He(this,"shape",i),i},checks:[]});return we(t,s)}function hd(t,e){if(!Xe(e))throw new Error("Invalid input to extend: expected a plain object");let n=t._zod.def.checks;if(n&&n.length>0){let s=t._zod.def.shape;for(let i in e)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=Qe(t._zod.def,{get shape(){let s={...t._zod.def.shape,...e};return He(this,"shape",s),s}});return we(t,o)}function yd(t,e){if(!Xe(e))throw new Error("Invalid input to safeExtend: expected a plain object");let n=Qe(t._zod.def,{get shape(){let r={...t._zod.def.shape,...e};return He(this,"shape",r),r}});return we(t,n)}function gd(t,e){if(t._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n=Qe(t._zod.def,{get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return He(this,"shape",r),r},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return we(t,n)}function bd(t,e,n){let o=e._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let i=Qe(e._zod.def,{get shape(){let a=e._zod.def.shape,c={...a};if(n)for(let u in n){if(!(u in a))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(c[u]=t?new t({type:"optional",innerType:a[u]}):a[u])}else for(let u in a)c[u]=t?new t({type:"optional",innerType:a[u]}):a[u];return He(this,"shape",c),c},checks:[]});return we(e,i)}function wd(t,e,n){let r=Qe(e._zod.def,{get shape(){let o=e._zod.def.shape,s={...o};if(n)for(let i in n){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(s[i]=new t({type:"nonoptional",innerType:o[i]}))}else for(let i in o)s[i]=new t({type:"nonoptional",innerType:o[i]});return He(this,"shape",s),s}});return we(e,r)}function et(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function go(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue===!1)return!0;return!1}function Ve(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function nn(t){return typeof t=="string"?t:t?.message}function he(t,e,n){let r=t.message?t.message:nn(t.inst?._zod.def?.error?.(t))??nn(e?.error?.(t))??nn(n.customError?.(t))??nn(n.localeError?.(t))??"Invalid input",{inst:o,continue:s,input:i,...a}=t;return a.path??(a.path=[]),a.message=r,e?.reportInput&&(a.input=i),a}function Ks(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function an(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function _d(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let n=t;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return e}function kt(...t){let[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}function xd(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function Ws(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function Ys(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e)}function Sd(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-e.length%4)%4);return Ws(e+n)}function Ad(t){return Ys(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Ed(t){let e=t.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let n=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)n[r/2]=Number.parseInt(e.slice(r,r+2),16);return n}function vd(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var uo=class{constructor(...e){}};var Hs=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,Et,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},qn=g("$ZodError",Hs),bo=g("$ZodError",Hs,{Parent:Error});function Xs(t,e=n=>n.message){let n={},r=[];for(let o of t.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(e(o))):r.push(e(o));return{formErrors:r,fieldErrors:n}}function ei(t,e=n=>n.message){let n={_errors:[]},r=(o,s=[])=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>r({issues:a},[...s,...i.path]));else if(i.code==="invalid_key")r({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")r({issues:i.issues},[...s,...i.path]);else{let a=[...s,...i.path];if(a.length===0)n._errors.push(e(i));else{let c=n,u=0;for(;u<a.length;){let d=a[u];u===a.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(e(i))):c[d]=c[d]||{_errors:[]},c=c[d],u++}}}};return r(t),n}var Jn=t=>(e,n,r,o)=>{let s=r?{...r,async:!1}:{async:!1},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new Ne;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>he(c,s,be())));throw Vn(a,o?.callee),a}return i.value};var Kn=t=>async(e,n,r,o)=>{let s=r?{...r,async:!0}:{async:!0},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>he(c,s,be())));throw Vn(a,o?.callee),a}return i.value};var cn=t=>(e,n,r)=>{let o=r?{...r,async:!1}:{async:!1},s=e._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new Ne;return s.issues.length?{success:!1,error:new(t??qn)(s.issues.map(i=>he(i,o,be())))}:{success:!0,data:s.value}},ti=cn(bo),un=t=>async(e,n,r)=>{let o=r?{...r,async:!0}:{async:!0},s=e._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>he(i,o,be())))}:{success:!0,data:s.value}},ni=un(bo),ri=t=>(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Jn(t)(e,n,o)};var oi=t=>(e,n,r)=>Jn(t)(e,n,r);var si=t=>async(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Kn(t)(e,n,o)};var ii=t=>async(e,n,r)=>Kn(t)(e,n,r);var ai=t=>(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return cn(t)(e,n,o)};var ci=t=>(e,n,r)=>cn(t)(e,n,r);var ui=t=>async(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return un(t)(e,n,o)};var li=t=>async(e,n,r)=>un(t)(e,n,r);var fi=/^[cC][0-9a-z]{6,}$/,di=/^[0-9a-z]+$/,pi=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,mi=/^[0-9a-vA-V]{20}$/,hi=/^[A-Za-z0-9]{27}$/,yi=/^[a-zA-Z0-9_-]{21}$/,gi=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var bi=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,wo=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;var wi=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Dd="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function _i(){return new RegExp(Dd,"u")}var xi=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Si=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var Ai=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Ei=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,vi=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,_o=/^[A-Za-z0-9_-]*$/;var ki=/^https?$/,Di=/^\+[1-9]\d{6,14}$/,Ri="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Ii=new RegExp(`^${Ri}$`);function Oi(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Ci(t){return new RegExp(`^${Oi(t)}$`)}function Ni(t){let e=Oi({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let r=`${e}(?:${n.join("|")})`;return new RegExp(`^${Ri}T(?:${r})$`)}var $i=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var Ti=/^-?\d+$/,xo=/^-?\d+(?:\.\d+)?$/,zi=/^(?:true|false)$/i,Pi=/^null$/i;var Li=/^[^A-Z]*$/,Mi=/^[^a-z]*$/;var X=g("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Fi={number:"number",bigint:"bigint",object:"date"},So=g("$ZodCheckLessThan",(t,e)=>{X.init(t,e);let n=Fi[typeof e.value];t._zod.onattach.push(r=>{let o=r._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Ao=g("$ZodCheckGreaterThan",(t,e)=>{X.init(t,e);let n=Fi[typeof e.value];t._zod.onattach.push(r=>{let o=r._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Zi=g("$ZodCheckMultipleOf",(t,e)=>{X.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):lo(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),ji=g("$ZodCheckNumberFormat",(t,e)=>{X.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),r=n?"int":"number",[o,s]=yo[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,n&&(a.pattern=Ti)}),t._zod.check=i=>{let a=i.value;if(n){if(!Number.isInteger(a)){i.issues.push({expected:r,format:e.format,code:"invalid_type",continue:!1,input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,inclusive:!0,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,inclusive:!0,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:t,continue:!e.abort})}});var Bi=g("$ZodCheckMaxLength",(t,e)=>{var n;X.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!on(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{let o=r.value;if(o.length<=e.maximum)return;let i=an(o);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Ui=g("$ZodCheckMinLength",(t,e)=>{var n;X.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!on(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{let o=r.value;if(o.length>=e.minimum)return;let i=an(o);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Qi=g("$ZodCheckLengthEquals",(t,e)=>{var n;X.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!on(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=r=>{let o=r.value,s=o.length;if(s===e.length)return;let i=an(o),a=s>e.length;r.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),ln=g("$ZodCheckStringFormat",(t,e)=>{var n,r;X.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(r=t._zod).check??(r.check=()=>{})}),Gi=g("$ZodCheckRegex",(t,e)=>{ln.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Vi=g("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Li),ln.init(t,e)}),qi=g("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Mi),ln.init(t,e)}),Ji=g("$ZodCheckIncludes",(t,e)=>{X.init(t,e);let n=Ge(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Ki=g("$ZodCheckStartsWith",(t,e)=>{X.init(t,e);let n=new RegExp(`^${Ge(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),Wi=g("$ZodCheckEndsWith",(t,e)=>{X.init(t,e);let n=new RegExp(`.*${Ge(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}});var Yi=g("$ZodCheckOverwrite",(t,e)=>{X.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});var Yn=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`-`).filter(i=>i),o=Math.min(...r.map(i=>i.length-i.trimStart().length)),s=r.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let e=Function,n=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...n,o.join(`-`))}};var Xi={major:4,minor:4,patch:3};var U=g("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Xi;let r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(let o of r)for(let s of o._zod.onattach)s(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(i,a,c)=>{let u=et(i),d;for(let l of a){if(l._zod.def.when){if(go(i)||!l._zod.def.when(i))continue}else if(u)continue;let f=i.issues.length,p=l._zod.check(i);if(p instanceof Promise&&c?.async===!1)throw new Ne;if(d||p instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await p,i.issues.length!==f&&(u||(u=et(i,f)))});else{if(i.issues.length===f)continue;u||(u=et(i,f))}}return d?d.then(()=>i):i},s=(i,a,c)=>{if(et(i))return i.aborted=!0,i;let u=o(a,r,c);if(u instanceof Promise){if(c.async===!1)throw new Ne;return u.then(d=>t._zod.parse(d,c))}return t._zod.parse(u,c)};t._zod.run=(i,a)=>{if(a.skipChecks)return t._zod.parse(i,a);if(a.direction==="backward"){let u=t._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(d=>s(d,i,a)):s(u,i,a)}let c=t._zod.parse(i,a);if(c instanceof Promise){if(a.async===!1)throw new Ne;return c.then(u=>o(u,r,a))}return o(c,r,a)}}z(t,"~standard",()=>({validate:o=>{try{let s=ti(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return ni(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),er=g("$ZodString",(t,e)=>{U.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??$i(t._zod.bag),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),Q=g("$ZodStringFormat",(t,e)=>{ln.init(t,e),er.init(t,e)}),ca=g("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=bi),Q.init(t,e)}),ua=g("$ZodUUID",(t,e)=>{if(e.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=wo(r))}else e.pattern??(e.pattern=wo());Q.init(t,e)}),la=g("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=wi),Q.init(t,e)}),fa=g("$ZodURL",(t,e)=>{Q.init(t,e),t._zod.check=n=>{try{let r=n.value.trim();if(!e.normalize&&e.protocol?.source===ki.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:t,continue:!e.abort});return}let o=new URL(r);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),e.normalize?n.value=o.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),da=g("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=_i()),Q.init(t,e)}),pa=g("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=yi),Q.init(t,e)}),ma=g("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=fi),Q.init(t,e)}),ha=g("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=di),Q.init(t,e)}),ya=g("$ZodULID",(t,e)=>{e.pattern??(e.pattern=pi),Q.init(t,e)}),ga=g("$ZodXID",(t,e)=>{e.pattern??(e.pattern=mi),Q.init(t,e)}),ba=g("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=hi),Q.init(t,e)}),wa=g("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Ni(e)),Q.init(t,e)}),_a=g("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Ii),Q.init(t,e)}),xa=g("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Ci(e)),Q.init(t,e)}),Sa=g("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=gi),Q.init(t,e)}),Aa=g("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=xi),Q.init(t,e),t._zod.bag.format="ipv4"}),Ea=g("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Si),Q.init(t,e),t._zod.bag.format="ipv6",t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}});var va=g("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Ai),Q.init(t,e)}),ka=g("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Ei),Q.init(t,e),t._zod.check=n=>{let r=n.value.split("/");try{if(r.length!==2)throw new Error;let[o,s]=r;if(!s)throw new Error;let i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${o}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});function Da(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var Ra=g("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=vi),Q.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=n=>{Da(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function Rd(t){if(!_o.test(t))return!1;let e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return Da(n)}var Ia=g("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=_o),Q.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=n=>{Rd(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Oa=g("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Di),Q.init(t,e)});function Id(t,e=null){try{let n=t.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}var Ca=g("$ZodJWT",(t,e)=>{Q.init(t,e),t._zod.check=n=>{Id(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}});var vo=g("$ZodNumber",(t,e)=>{U.init(t,e),t._zod.pattern=t._zod.bag.pattern??xo,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}let o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),n}}),Na=g("$ZodNumberFormat",(t,e)=>{ji.init(t,e),vo.init(t,e)}),$a=g("$ZodBoolean",(t,e)=>{U.init(t,e),t._zod.pattern=zi,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=!!n.value}catch{}let o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),n}});var Ta=g("$ZodNull",(t,e)=>{U.init(t,e),t._zod.pattern=Pi,t._zod.values=new Set([null]),t._zod.parse=(n,r)=>{let o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),n}});var za=g("$ZodUnknown",(t,e)=>{U.init(t,e),t._zod.parse=n=>n}),Pa=g("$ZodNever",(t,e)=>{U.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function ea(t,e,n){t.issues.length&&e.issues.push(...Ve(n,t.issues)),e.value[n]=t.value}var La=g("$ZodArray",(t,e)=>{U.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),n;n.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},r);c instanceof Promise?s.push(c.then(u=>ea(u,n,i))):ea(c,n,i)}return s.length?Promise.all(s).then(()=>n):n}});function Xn(t,e,n,r,o,s){let i=n in r;if(t.issues.length){if(o&&s&&!i)return;e.issues.push(...Ve(n,t.issues))}if(!i&&!o){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}t.value===void 0?i&&(e.value[n]=void 0):e.value[n]=t.value}function Ma(t){let e=Object.keys(t.shape);for(let r of e)if(!t.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);let n=ho(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function Fa(t,e,n,r,o,s){let i=[],a=o.keySet,c=o.catchall._zod,u=c.def.type,d=c.optin==="optional",l=c.optout==="optional";for(let f in e){if(f==="__proto__"||a.has(f))continue;if(u==="never"){i.push(f);continue}let p=c.run({value:e[f],issues:[]},r);p instanceof Promise?t.push(p.then(y=>Xn(y,n,f,e,d,l))):Xn(p,n,f,e,d,l)}return i.length&&n.issues.push({code:"unrecognized_keys",keys:i,input:e,inst:s}),t.length?Promise.all(t).then(()=>n):n}var Od=g("$ZodObject",(t,e)=>{if(U.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let a=e.shape;Object.defineProperty(e,"shape",{get:()=>{let c={...a};return Object.defineProperty(e,"shape",{value:c}),c}})}let r=vt(()=>Ma(e));z(t._zod,"propValues",()=>{let a=e.shape,c={};for(let u in a){let d=a[u]._zod;if(d.values){c[u]??(c[u]=new Set);for(let l of d.values)c[u].add(l)}}return c});let o=ht,s=e.catchall,i;t._zod.parse=(a,c)=>{i??(i=r.value);let u=a.value;if(!o(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),a;a.value={};let d=[],l=i.shape;for(let f of i.keys){let p=l[f],y=p._zod.optin==="optional",m=p._zod.optout==="optional",h=p._zod.run({value:u[f],issues:[]},c);h instanceof Promise?d.push(h.then(b=>Xn(b,a,f,u,y,m))):Xn(h,a,f,u,y,m)}return s?Fa(d,u,a,c,r.value,t):d.length?Promise.all(d).then(()=>a):a}}),Za=g("$ZodObjectJIT",(t,e)=>{Od.init(t,e);let n=t._zod.parse,r=vt(()=>Ma(e)),o=f=>{let p=new Yn(["shape","payload","ctx"]),y=r.value,m=A=>{let _=Gn(A);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};p.write("const input = payload.value;");let h=Object.create(null),b=0;for(let A of y.keys)h[A]=`key_${b++}`;p.write("const newResult = {};");for(let A of y.keys){let _=h[A],w=Gn(A),E=f[A],k=E?._zod?.optin==="optional",x=E?._zod?.optout==="optional";p.write(`const ${_} = ${m(A)};`),k&&x?p.write(`- if (${_}.issues.length) {- if (${w} in input) {- payload.issues = payload.issues.concat(${_}.issues.map(iss => ({+var Qw=Object.create;var Su=Object.defineProperty;var Hw=Object.getOwnPropertyDescriptor;var Ww=Object.getOwnPropertyNames;var Kw=Object.getPrototypeOf,Xw=Object.prototype.hasOwnProperty;var ri=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Dp=(e,t)=>{for(var r in t)Su(e,r,{get:t[r],enumerable:!0})},Yw=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ww(t))!Xw.call(e,i)&&i!==r&&Su(e,i,{get:()=>t[i],enumerable:!(n=Hw(t,i))||n.enumerable});return e};var ns=(e,t,r)=>(r=e!=null?Qw(Kw(e)):{},Yw(t||!e||!e.__esModule?Su(r,"default",{value:e,enumerable:!0}):r,e));var Nx=ri((A4,sl)=>{(function(){var e;typeof sl<"u"?e=sl.exports=n:e=function(){return this||(0,eval)("this")}(),e.format=n,e.vsprintf=r,typeof console<"u"&&typeof console.log=="function"&&(e.printf=t);function t(){console.log(n.apply(null,arguments))}function r(i,s){return n.apply(null,[i].concat(s))}function n(i){for(var s=1,o=[].slice.call(arguments),u=0,c=i.length,f="",h,p=!1,m,d,x=!1,b,v=function(){return o[s++]},k=function(){for(var T="";/\d/.test(i[u]);)T+=i[u++],h=i[u];return T.length>0?parseInt(T):null};u<c;++u)if(h=i[u],p)switch(p=!1,h=="."?(x=!1,h=i[++u]):h=="0"&&i[u+1]=="."?(x=!0,u+=2,h=i[u]):x=!0,b=k(),h){case"b":f+=parseInt(v(),10).toString(2);break;case"c":m=v(),typeof m=="string"||m instanceof String?f+=m:f+=String.fromCharCode(parseInt(m,10));break;case"d":f+=parseInt(v(),10);break;case"f":d=String(parseFloat(v()).toFixed(b||6)),f+=x?d:d.replace(/^0/,"");break;case"j":f+=JSON.stringify(v());break;case"o":f+="0"+parseInt(v(),10).toString(8);break;case"s":f+=v();break;case"x":f+="0x"+parseInt(v(),10).toString(16);break;case"X":f+="0x"+parseInt(v(),10).toString(16).toUpperCase();break;default:f+=h;break}else h==="%"?p=!0:f+=h;return f}})()});var nb=ri((p8,rb)=>{rb.exports={quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:"\xA0",iexcl:"\xA1",cent:"\xA2",pound:"\xA3",curren:"\xA4",yen:"\xA5",brvbar:"\xA6",sect:"\xA7",uml:"\xA8",copy:"\xA9",ordf:"\xAA",laquo:"\xAB",not:"\xAC",shy:"\xAD",reg:"\xAE",macr:"\xAF",deg:"\xB0",plusmn:"\xB1",sup2:"\xB2",sup3:"\xB3",acute:"\xB4",micro:"\xB5",para:"\xB6",middot:"\xB7",cedil:"\xB8",sup1:"\xB9",ordm:"\xBA",raquo:"\xBB",frac14:"\xBC",frac12:"\xBD",frac34:"\xBE",iquest:"\xBF",Agrave:"\xC0",Aacute:"\xC1",Acirc:"\xC2",Atilde:"\xC3",Auml:"\xC4",Aring:"\xC5",AElig:"\xC6",Ccedil:"\xC7",Egrave:"\xC8",Eacute:"\xC9",Ecirc:"\xCA",Euml:"\xCB",Igrave:"\xCC",Iacute:"\xCD",Icirc:"\xCE",Iuml:"\xCF",ETH:"\xD0",Ntilde:"\xD1",Ograve:"\xD2",Oacute:"\xD3",Ocirc:"\xD4",Otilde:"\xD5",Ouml:"\xD6",times:"\xD7",Oslash:"\xD8",Ugrave:"\xD9",Uacute:"\xDA",Ucirc:"\xDB",Uuml:"\xDC",Yacute:"\xDD",THORN:"\xDE",szlig:"\xDF",agrave:"\xE0",aacute:"\xE1",acirc:"\xE2",atilde:"\xE3",auml:"\xE4",aring:"\xE5",aelig:"\xE6",ccedil:"\xE7",egrave:"\xE8",eacute:"\xE9",ecirc:"\xEA",euml:"\xEB",igrave:"\xEC",iacute:"\xED",icirc:"\xEE",iuml:"\xEF",eth:"\xF0",ntilde:"\xF1",ograve:"\xF2",oacute:"\xF3",ocirc:"\xF4",otilde:"\xF5",ouml:"\xF6",divide:"\xF7",oslash:"\xF8",ugrave:"\xF9",uacute:"\xFA",ucirc:"\xFB",uuml:"\xFC",yacute:"\xFD",thorn:"\xFE",yuml:"\xFF",OElig:"\u0152",oelig:"\u0153",Scaron:"\u0160",scaron:"\u0161",Yuml:"\u0178",fnof:"\u0192",circ:"\u02C6",tilde:"\u02DC",Alpha:"\u0391",Beta:"\u0392",Gamma:"\u0393",Delta:"\u0394",Epsilon:"\u0395",Zeta:"\u0396",Eta:"\u0397",Theta:"\u0398",Iota:"\u0399",Kappa:"\u039A",Lambda:"\u039B",Mu:"\u039C",Nu:"\u039D",Xi:"\u039E",Omicron:"\u039F",Pi:"\u03A0",Rho:"\u03A1",Sigma:"\u03A3",Tau:"\u03A4",Upsilon:"\u03A5",Phi:"\u03A6",Chi:"\u03A7",Psi:"\u03A8",Omega:"\u03A9",alpha:"\u03B1",beta:"\u03B2",gamma:"\u03B3",delta:"\u03B4",epsilon:"\u03B5",zeta:"\u03B6",eta:"\u03B7",theta:"\u03B8",iota:"\u03B9",kappa:"\u03BA",lambda:"\u03BB",mu:"\u03BC",nu:"\u03BD",xi:"\u03BE",omicron:"\u03BF",pi:"\u03C0",rho:"\u03C1",sigmaf:"\u03C2",sigma:"\u03C3",tau:"\u03C4",upsilon:"\u03C5",phi:"\u03C6",chi:"\u03C7",psi:"\u03C8",omega:"\u03C9",thetasym:"\u03D1",upsih:"\u03D2",piv:"\u03D6",ensp:"\u2002",emsp:"\u2003",thinsp:"\u2009",zwnj:"\u200C",zwj:"\u200D",lrm:"\u200E",rlm:"\u200F",ndash:"\u2013",mdash:"\u2014",lsquo:"\u2018",rsquo:"\u2019",sbquo:"\u201A",ldquo:"\u201C",rdquo:"\u201D",bdquo:"\u201E",dagger:"\u2020",Dagger:"\u2021",bull:"\u2022",hellip:"\u2026",permil:"\u2030",prime:"\u2032",Prime:"\u2033",lsaquo:"\u2039",rsaquo:"\u203A",oline:"\u203E",frasl:"\u2044",euro:"\u20AC",image:"\u2111",weierp:"\u2118",real:"\u211C",trade:"\u2122",alefsym:"\u2135",larr:"\u2190",uarr:"\u2191",rarr:"\u2192",darr:"\u2193",harr:"\u2194",crarr:"\u21B5",lArr:"\u21D0",uArr:"\u21D1",rArr:"\u21D2",dArr:"\u21D3",hArr:"\u21D4",forall:"\u2200",part:"\u2202",exist:"\u2203",empty:"\u2205",nabla:"\u2207",isin:"\u2208",notin:"\u2209",ni:"\u220B",prod:"\u220F",sum:"\u2211",minus:"\u2212",lowast:"\u2217",radic:"\u221A",prop:"\u221D",infin:"\u221E",ang:"\u2220",and:"\u2227",or:"\u2228",cap:"\u2229",cup:"\u222A",int:"\u222B",there4:"\u2234",sim:"\u223C",cong:"\u2245",asymp:"\u2248",ne:"\u2260",equiv:"\u2261",le:"\u2264",ge:"\u2265",sub:"\u2282",sup:"\u2283",nsub:"\u2284",sube:"\u2286",supe:"\u2287",oplus:"\u2295",otimes:"\u2297",perp:"\u22A5",sdot:"\u22C5",lceil:"\u2308",rceil:"\u2309",lfloor:"\u230A",rfloor:"\u230B",lang:"\u2329",rang:"\u232A",loz:"\u25CA",spades:"\u2660",clubs:"\u2663",hearts:"\u2665",diams:"\u2666"}});var df=ri((uu,ib)=>{(function(e,t){typeof uu=="object"&&typeof ib<"u"?t(uu):typeof define=="function"&&define.amd?define(["exports"],t):(e=typeof globalThis<"u"?globalThis:e||self,t(e.acorn={}))})(uu,function(e){"use strict";var t=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,78,5,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,199,7,137,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,55,9,266,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,233,0,3,0,8,1,6,0,475,6,110,6,6,9,4759,9,787719,239],r=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,7,25,39,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,5,57,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,24,43,261,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,33,24,3,24,45,74,6,0,67,12,65,1,2,0,15,4,10,7381,42,31,98,114,8702,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,208,30,2,2,2,1,2,6,3,4,10,1,225,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4381,3,5773,3,7472,16,621,2467,541,1507,4938,6,8489],n="\u200C\u200D\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0CF3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u180F-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1ABF-\u1ADD\u1AE0-\u1AEB\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\u30FB\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F\uFF65",i="\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088F\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5C\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDC-\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7DC\uA7F1-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC",s={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},o="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",u={5:o,"5module":o+" export import",6:o+" const class extends export import super"},c=/^in(stanceof)?$/,f=new RegExp("["+i+"]"),h=new RegExp("["+i+n+"]");function p(a,l){for(var y=65536,w=0;w<l.length;w+=2){if(y+=l[w],y>a)return!1;if(y+=l[w+1],y>=a)return!0}return!1}function m(a,l){return a<65?a===36:a<91?!0:a<97?a===95:a<123?!0:a<=65535?a>=170&&f.test(String.fromCharCode(a)):l===!1?!1:p(a,r)}function d(a,l){return a<48?a===36:a<58?!0:a<65?!1:a<91?!0:a<97?a===95:a<123?!0:a<=65535?a>=170&&h.test(String.fromCharCode(a)):l===!1?!1:p(a,r)||p(a,t)}var x=function(l,y){y===void 0&&(y={}),this.label=l,this.keyword=y.keyword,this.beforeExpr=!!y.beforeExpr,this.startsExpr=!!y.startsExpr,this.isLoop=!!y.isLoop,this.isAssign=!!y.isAssign,this.prefix=!!y.prefix,this.postfix=!!y.postfix,this.binop=y.binop||null,this.updateContext=null};function b(a,l){return new x(a,{beforeExpr:!0,binop:l})}var v={beforeExpr:!0},k={startsExpr:!0},T={};function E(a,l){return l===void 0&&(l={}),l.keyword=a,T[a]=new x(a,l)}var g={num:new x("num",k),regexp:new x("regexp",k),string:new x("string",k),name:new x("name",k),privateId:new x("privateId",k),eof:new x("eof"),bracketL:new x("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new x("]"),braceL:new x("{",{beforeExpr:!0,startsExpr:!0}),braceR:new x("}"),parenL:new x("(",{beforeExpr:!0,startsExpr:!0}),parenR:new x(")"),comma:new x(",",v),semi:new x(";",v),colon:new x(":",v),dot:new x("."),question:new x("?",v),questionDot:new x("?."),arrow:new x("=>",v),template:new x("template"),invalidTemplate:new x("invalidTemplate"),ellipsis:new x("...",v),backQuote:new x("`",k),dollarBraceL:new x("${",{beforeExpr:!0,startsExpr:!0}),eq:new x("=",{beforeExpr:!0,isAssign:!0}),assign:new x("_=",{beforeExpr:!0,isAssign:!0}),incDec:new x("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new x("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:b("||",1),logicalAND:b("&&",2),bitwiseOR:b("|",3),bitwiseXOR:b("^",4),bitwiseAND:b("&",5),equality:b("==/!=/===/!==",6),relational:b("</>/<=/>=",7),bitShift:b("<</>>/>>>",8),plusMin:new x("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:b("%",10),star:b("*",10),slash:b("/",10),starstar:new x("**",{beforeExpr:!0}),coalesce:b("??",1),_break:E("break"),_case:E("case",v),_catch:E("catch"),_continue:E("continue"),_debugger:E("debugger"),_default:E("default",v),_do:E("do",{isLoop:!0,beforeExpr:!0}),_else:E("else",v),_finally:E("finally"),_for:E("for",{isLoop:!0}),_function:E("function",k),_if:E("if"),_return:E("return",v),_switch:E("switch"),_throw:E("throw",v),_try:E("try"),_var:E("var"),_const:E("const"),_while:E("while",{isLoop:!0}),_with:E("with"),_new:E("new",{beforeExpr:!0,startsExpr:!0}),_this:E("this",k),_super:E("super",k),_class:E("class",k),_extends:E("extends",v),_export:E("export"),_import:E("import",k),_null:E("null",k),_true:E("true",k),_false:E("false",k),_in:E("in",{beforeExpr:!0,binop:7}),_instanceof:E("instanceof",{beforeExpr:!0,binop:7}),_typeof:E("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:E("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:E("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},I=/\r\n?|\n|\u2028|\u2029/,_=new RegExp(I.source,"g");function D(a){return a===10||a===13||a===8232||a===8233}function O(a,l,y){y===void 0&&(y=a.length);for(var w=l;w<y;w++){var C=a.charCodeAt(w);if(D(C))return w<y-1&&C===13&&a.charCodeAt(w+1)===10?w+2:w+1}return-1}var M=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/,P=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g,J=Object.prototype,V=J.hasOwnProperty,q=J.toString,ee=Object.hasOwn||function(a,l){return V.call(a,l)},re=Array.isArray||function(a){return q.call(a)==="[object Array]"},Ae=Object.create(null);function se(a){return Ae[a]||(Ae[a]=new RegExp("^(?:"+a.replace(/ /g,"|")+")$"))}function Ce(a){return a<=65535?String.fromCharCode(a):(a-=65536,String.fromCharCode((a>>10)+55296,(a&1023)+56320))}var yt=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,R=function(l,y){this.line=l,this.column=y};R.prototype.offset=function(l){return new R(this.line,this.column+l)};var Ge=function(l,y,w){this.start=y,this.end=w,l.sourceFile!==null&&(this.source=l.sourceFile)};function ut(a,l){for(var y=1,w=0;;){var C=O(a,w,l);if(C<0)return new R(y,l-w);++y,w=C}}var N={ecmaVersion:null,sourceType:"script",strict:!1,onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},Xe=!1;function Wt(a){var l={};for(var y in N)l[y]=a&&ee(a,y)?a[y]:N[y];if(l.ecmaVersion==="latest"?l.ecmaVersion=1e8:l.ecmaVersion==null?(!Xe&&typeof console=="object"&&console.warn&&(Xe=!0,console.warn(`Since Acorn 8.0.0, options.ecmaVersion is required.+Defaulting to 2020, but this will stop working in the future.`)),l.ecmaVersion=11):l.ecmaVersion>=2015&&(l.ecmaVersion-=2009),l.allowReserved==null&&(l.allowReserved=l.ecmaVersion<5),(!a||a.allowHashBang==null)&&(l.allowHashBang=l.ecmaVersion>=14),re(l.onToken)){var w=l.onToken;l.onToken=function(C){return w.push(C)}}if(re(l.onComment)&&(l.onComment=tn(l,l.onComment)),l.sourceType==="commonjs"&&l.allowAwaitOutsideFunction)throw new Error("Cannot use allowAwaitOutsideFunction with sourceType: commonjs");return l}function tn(a,l){return function(y,w,C,F,L,$){var Z={type:y?"Block":"Line",value:w,start:C,end:F};a.locations&&(Z.loc=new Ge(this,L,$)),a.ranges&&(Z.range=[C,F]),l.push(Z)}}var ct=1,De=2,Nt=4,xt=8,He=16,Pt=32,Kt=64,Kn=128,Xt=256,Yt=512,In=1024,br=ct|De|Xt;function Tn(a,l){return De|(a?Nt:0)|(l?xt:0)}var er=0,Br=1,St=2,Mr=3,Ie=4,Rn=5,Te=function(l,y,w){this.options=l=Wt(l),this.sourceFile=l.sourceFile,this.keywords=se(u[l.ecmaVersion>=6?6:l.sourceType==="module"?"5module":5]);var C="";l.allowReserved!==!0&&(C=s[l.ecmaVersion>=6?6:l.ecmaVersion===5?5:3],l.sourceType==="module"&&(C+=" await")),this.reservedWords=se(C);var F=(C?C+" ":"")+s.strict;this.reservedWordsStrict=se(F),this.reservedWordsStrictBind=se(F+" "+s.strictBind),this.input=String(y),this.containsEsc=!1,w?(this.pos=w,this.lineStart=this.input.lastIndexOf(`+`,w-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(I).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=g.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule=l.sourceType==="module",this.strict=this.inModule||l.strict===!0||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),this.pos===0&&l.allowHashBang&&this.input.slice(0,2)==="#!"&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(this.options.sourceType==="commonjs"?De:ct),this.regexpState=null,this.privateNameStack=[]},z={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowReturn:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},allowUsing:{configurable:!0},inClassStaticBlock:{configurable:!0}};Te.prototype.parse=function(){var l=this,y=this.options.program||this.startNode();return this.nextToken(),this.catchStackOverflow(function(){return l.parseTopLevel(y)})},z.inFunction.get=function(){return(this.currentVarScope().flags&De)>0},z.inGenerator.get=function(){return(this.currentVarScope().flags&xt)>0},z.inAsync.get=function(){return(this.currentVarScope().flags&Nt)>0},z.canAwait.get=function(){for(var a=this.scopeStack.length-1;a>=0;a--){var l=this.scopeStack[a],y=l.flags;if(y&(Xt|Yt))return!1;if(y&De)return(y&Nt)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},z.allowReturn.get=function(){return!!(this.inFunction||this.options.allowReturnOutsideFunction&&this.currentVarScope().flags&ct)},z.allowSuper.get=function(){var a=this.currentThisScope(),l=a.flags;return(l&Kt)>0||this.options.allowSuperOutsideMethod},z.allowDirectSuper.get=function(){return(this.currentThisScope().flags&Kn)>0},z.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},z.allowNewDotTarget.get=function(){for(var a=this.scopeStack.length-1;a>=0;a--){var l=this.scopeStack[a],y=l.flags;if(y&(Xt|Yt)||y&De&&!(y&He))return!0}return!1},z.allowUsing.get=function(){var a=this.currentScope(),l=a.flags;return!(l&In||!this.inModule&&l&ct)},z.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&Xt)>0},Te.extend=function(){for(var l=[],y=arguments.length;y--;)l[y]=arguments[y];for(var w=this,C=0;C<l.length;C++)w=l[C](w);return w},Te.parse=function(l,y){return new this(y,l).parse()},Te.parseExpressionAt=function(l,y,w){var C=new this(w,l,y);return C.nextToken(),C.parseExpression()},Te.tokenizer=function(l,y){return new this(y,l)},Object.defineProperties(Te.prototype,z);var S=Te.prototype,ne=/^(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/;S.strictDirective=function(a){if(this.options.ecmaVersion<5)return!1;for(;;){P.lastIndex=a,a+=P.exec(this.input)[0].length;var l=ne.exec(this.input.slice(a));if(!l)return!1;if((l[1]||l[2])==="use strict"){P.lastIndex=a+l[0].length;var y=P.exec(this.input),w=y.index+y[0].length,C=this.input.charAt(w);return C===";"||C==="}"||I.test(y[0])&&!(/[(`.[+\-/*%<>=,?^&]/.test(C)||C==="!"&&this.input.charAt(w+1)==="=")}a+=l[0].length,P.lastIndex=a,a+=P.exec(this.input)[0].length,this.input[a]===";"&&a++}},S.eat=function(a){return this.type===a?(this.next(),!0):!1},S.isContextual=function(a){return this.type===g.name&&this.value===a&&!this.containsEsc},S.eatContextual=function(a){return this.isContextual(a)?(this.next(),!0):!1},S.catchStackOverflow=function(a){try{return a()}catch(l){if(l instanceof Error&&(/\bstack\b.*\b(exceeded|overflow)\b/i.test(l.message)||/\btoo much recursion\b/i.test(l.message)))this.raise(this.start,"Not enough stack space to parse input");else throw l}},S.expectContextual=function(a){this.eatContextual(a)||this.unexpected()},S.canInsertSemicolon=function(){return this.type===g.eof||this.type===g.braceR||I.test(this.input.slice(this.lastTokEnd,this.start))},S.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},S.semicolon=function(){!this.eat(g.semi)&&!this.insertSemicolon()&&this.unexpected()},S.afterTrailingComma=function(a,l){if(this.type===a)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),l||this.next(),!0},S.expect=function(a){this.eat(a)||this.unexpected()},S.unexpected=function(a){this.raise(a??this.start,"Unexpected token")};var ye=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};S.checkPatternErrors=function(a,l){if(a){a.trailingComma>-1&&this.raiseRecoverable(a.trailingComma,"Comma is not permitted after the rest element");var y=l?a.parenthesizedAssign:a.parenthesizedBind;y>-1&&this.raiseRecoverable(y,l?"Assigning to rvalue":"Parenthesized pattern")}},S.checkExpressionErrors=function(a,l){if(!a)return!1;var y=a.shorthandAssign,w=a.doubleProto;if(!l)return y>=0||w>=0;y>=0&&this.raise(y,"Shorthand property assignments are valid only in destructuring patterns"),w>=0&&this.raiseRecoverable(w,"Redefinition of __proto__ property")},S.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos<this.awaitPos)&&this.raise(this.yieldPos,"Yield expression cannot be a default value"),this.awaitPos&&this.raise(this.awaitPos,"Await expression cannot be a default value")},S.isSimpleAssignTarget=function(a){return a.type==="ParenthesizedExpression"?this.isSimpleAssignTarget(a.expression):a.type==="Identifier"||a.type==="MemberExpression"};var U=Te.prototype;U.parseTopLevel=function(a){var l=Object.create(null);for(a.body||(a.body=[]);this.type!==g.eof;){var y=this.parseStatement(null,!0,l);a.body.push(y)}if(this.inModule)for(var w=0,C=Object.keys(this.undefinedExports);w<C.length;w+=1){var F=C[w];this.raiseRecoverable(this.undefinedExports[F].start,"Export '"+F+"' is not defined")}return this.adaptDirectivePrologue(a.body),this.next(),a.sourceType=this.options.sourceType==="commonjs"?"script":this.options.sourceType,this.finishNode(a,"Program")};var lt={kind:"loop"},wr={kind:"switch"};U.isLet=function(a){if(this.options.ecmaVersion<6||!this.isContextual("let"))return!1;P.lastIndex=this.pos;var l=P.exec(this.input),y=this.pos+l[0].length,w=this.fullCharCodeAt(y);if(w===91||w===92)return!0;if(a)return!1;if(w===123)return!0;if(m(w)){var C=y;do y+=w<=65535?1:2;while(d(w=this.fullCharCodeAt(y)));if(w===92)return!0;var F=this.input.slice(C,y);if(!c.test(F))return!0}return!1},U.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;P.lastIndex=this.pos;var a=P.exec(this.input),l=this.pos+a[0].length,y;return!I.test(this.input.slice(this.pos,l))&&this.input.slice(l,l+8)==="function"&&(l+8===this.input.length||!(d(y=this.fullCharCodeAt(l+8))||y===92))},U.isUsingKeyword=function(a,l){if(this.options.ecmaVersion<17||!this.isContextual(a?"await":"using"))return!1;P.lastIndex=this.pos;var y=P.exec(this.input),w=this.pos+y[0].length;if(I.test(this.input.slice(this.pos,w)))return!1;if(a){var C=w+5,F;if(this.input.slice(w,C)!=="using"||C===this.input.length||d(F=this.fullCharCodeAt(C))||F===92)return!1;P.lastIndex=C;var L=P.exec(this.input);if(w=C+L[0].length,L&&I.test(this.input.slice(C,w)))return!1}var $=this.fullCharCodeAt(w);if(!m($)&&$!==92)return!1;var Z=w;do w+=$<=65535?1:2;while(d($=this.fullCharCodeAt(w)));if($===92)return!0;var oe=this.input.slice(Z,w);if(c.test(oe))return!1;if(l&&!a&&oe==="of"){P.lastIndex=w;var fe=P.exec(this.input);if(w=w+fe[0].length,this.input.charCodeAt(w)!==61||($=this.input.charCodeAt(w+1))===61||$===62)return!1}return!0},U.isAwaitUsing=function(a){return this.isUsingKeyword(!0,a)},U.isUsing=function(a){return this.isUsingKeyword(!1,a)},U.parseStatement=function(a,l,y){var w=this.type,C=this.startNode(),F;switch(this.isLet(a)&&(w=g._var,F="let"),w){case g._break:case g._continue:return this.parseBreakContinueStatement(C,w.keyword);case g._debugger:return this.parseDebuggerStatement(C);case g._do:return this.parseDoStatement(C);case g._for:return this.parseForStatement(C);case g._function:return a&&(this.strict||a!=="if"&&a!=="label")&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(C,!1,!a);case g._class:return a&&this.unexpected(),this.parseClass(C,!0);case g._if:return this.parseIfStatement(C);case g._return:return this.parseReturnStatement(C);case g._switch:return this.parseSwitchStatement(C);case g._throw:return this.parseThrowStatement(C);case g._try:return this.parseTryStatement(C);case g._const:case g._var:return F=F||this.value,a&&F!=="var"&&this.unexpected(),this.parseVarStatement(C,F);case g._while:return this.parseWhileStatement(C);case g._with:return this.parseWithStatement(C);case g.braceL:return this.parseBlock(!0,C);case g.semi:return this.parseEmptyStatement(C);case g._export:case g._import:if(this.options.ecmaVersion>10&&w===g._import){P.lastIndex=this.pos;var L=P.exec(this.input),$=this.pos+L[0].length,Z=this.input.charCodeAt($);if(Z===40||Z===46)return this.parseExpressionStatement(C,this.parseExpression())}return this.options.allowImportExportEverywhere||(l||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),w===g._import?this.parseImport(C):this.parseExport(C,y);default:if(this.isAsyncFunction())return a&&this.unexpected(),this.next(),this.parseFunctionStatement(C,!0,!a);var oe=this.isAwaitUsing(!1)?"await using":this.isUsing(!1)?"using":null;if(oe)return this.allowUsing||this.raise(this.start,"Using declaration cannot appear in the top level when source type is `script` or in the bare case statement"),a&&this.raise(this.start,"Using declaration is not allowed in single-statement positions"),oe==="await using"&&(this.canAwait||this.raise(this.start,"Await using cannot appear outside of async function"),this.next()),this.next(),this.parseVar(C,!1,oe),this.semicolon(),this.finishNode(C,"VariableDeclaration");var fe=this.value,Pe=this.parseExpression();return w===g.name&&Pe.type==="Identifier"&&this.eat(g.colon)?this.parseLabeledStatement(C,fe,Pe,a):this.parseExpressionStatement(C,Pe)}},U.parseBreakContinueStatement=function(a,l){var y=l==="break";this.next(),this.eat(g.semi)||this.insertSemicolon()?a.label=null:this.type!==g.name?this.unexpected():(a.label=this.parseIdent(),this.semicolon());for(var w=0;w<this.labels.length;++w){var C=this.labels[w];if((a.label==null||C.name===a.label.name)&&(C.kind!=null&&(y||C.kind==="loop")||a.label&&y))break}return w===this.labels.length&&this.raise(a.start,"Unsyntactic "+l),this.finishNode(a,y?"BreakStatement":"ContinueStatement")},U.parseDebuggerStatement=function(a){return this.next(),this.semicolon(),this.finishNode(a,"DebuggerStatement")},U.parseDoStatement=function(a){return this.next(),this.labels.push(lt),a.body=this.parseStatement("do"),this.labels.pop(),this.expect(g._while),a.test=this.parseParenExpression(),this.options.ecmaVersion>=6?this.eat(g.semi):this.semicolon(),this.finishNode(a,"DoWhileStatement")},U.parseForStatement=function(a){this.next();var l=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(lt),this.enterScope(0),this.expect(g.parenL),this.type===g.semi)return l>-1&&this.unexpected(l),this.parseFor(a,null);var y=this.isLet();if(this.type===g._var||this.type===g._const||y){var w=this.startNode(),C=y?"let":this.value;return this.next(),this.parseVar(w,!0,C),this.finishNode(w,"VariableDeclaration"),this.parseForAfterInit(a,w,l)}var F=this.isContextual("let"),L=!1,$=this.isUsing(!0)?"using":this.isAwaitUsing(!0)?"await using":null;if($){var Z=this.startNode();return this.next(),$==="await using"&&(this.canAwait||this.raise(this.start,"Await using cannot appear outside of async function"),this.next()),this.parseVar(Z,!0,$),this.finishNode(Z,"VariableDeclaration"),this.parseForAfterInit(a,Z,l)}var oe=this.containsEsc,fe=new ye,Pe=this.start,rt=l>-1?this.parseExprSubscripts(fe,"await"):this.parseExpression(!0,fe);return this.type===g._in||(L=this.options.ecmaVersion>=6&&this.isContextual("of"))?(l>-1?(this.type===g._in&&this.unexpected(l),a.await=!0):L&&this.options.ecmaVersion>=8&&(rt.start===Pe&&!oe&&rt.type==="Identifier"&&rt.name==="async"?this.unexpected():this.options.ecmaVersion>=9&&(a.await=!1)),F&&L&&this.raise(rt.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(rt,!1,fe),this.checkLValPattern(rt),this.parseForIn(a,rt)):(this.checkExpressionErrors(fe,!0),l>-1&&this.unexpected(l),this.parseFor(a,rt))},U.parseForAfterInit=function(a,l,y){return(this.type===g._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&l.declarations.length===1?(this.type===g._in?((l.kind==="using"||l.kind==="await using")&&!l.declarations[0].init&&this.raise(this.start,"Using declaration is not allowed in for-in loops"),this.options.ecmaVersion>=9&&y>-1&&this.unexpected(y)):this.options.ecmaVersion>=9&&(a.await=y>-1),this.parseForIn(a,l)):(y>-1&&this.unexpected(y),this.parseFor(a,l))},U.parseFunctionStatement=function(a,l,y){return this.next(),this.parseFunction(a,rr|(y?0:Vr),!1,l)},U.parseIfStatement=function(a){return this.next(),a.test=this.parseParenExpression(),a.consequent=this.parseStatement("if"),a.alternate=this.eat(g._else)?this.parseStatement("if"):null,this.finishNode(a,"IfStatement")},U.parseReturnStatement=function(a){return this.allowReturn||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(g.semi)||this.insertSemicolon()?a.argument=null:(a.argument=this.parseExpression(),this.semicolon()),this.finishNode(a,"ReturnStatement")},U.parseSwitchStatement=function(a){this.next(),a.discriminant=this.parseParenExpression(),a.cases=[],this.expect(g.braceL),this.labels.push(wr),this.enterScope(In);for(var l,y=!1;this.type!==g.braceR;)if(this.type===g._case||this.type===g._default){var w=this.type===g._case;l&&this.finishNode(l,"SwitchCase"),a.cases.push(l=this.startNode()),l.consequent=[],this.next(),w?l.test=this.parseExpression():(y&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),y=!0,l.test=null),this.expect(g.colon)}else l||this.unexpected(),l.consequent.push(this.parseStatement(null));return this.exitScope(),l&&this.finishNode(l,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(a,"SwitchStatement")},U.parseThrowStatement=function(a){return this.next(),I.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),a.argument=this.parseExpression(),this.semicolon(),this.finishNode(a,"ThrowStatement")};var tr=[];U.parseCatchClauseParam=function(){var a=this.parseBindingAtom(),l=a.type==="Identifier";return this.enterScope(l?Pt:0),this.checkLValPattern(a,l?Ie:St),this.expect(g.parenR),a},U.parseTryStatement=function(a){if(this.next(),a.block=this.parseBlock(),a.handler=null,this.type===g._catch){var l=this.startNode();this.next(),this.eat(g.parenL)?l.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),l.param=null,this.enterScope(0)),l.body=this.parseBlock(!1),this.exitScope(),a.handler=this.finishNode(l,"CatchClause")}return a.finalizer=this.eat(g._finally)?this.parseBlock():null,!a.handler&&!a.finalizer&&this.raise(a.start,"Missing catch or finally clause"),this.finishNode(a,"TryStatement")},U.parseVarStatement=function(a,l,y){return this.next(),this.parseVar(a,!1,l,y),this.semicolon(),this.finishNode(a,"VariableDeclaration")},U.parseWhileStatement=function(a){return this.next(),a.test=this.parseParenExpression(),this.labels.push(lt),a.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(a,"WhileStatement")},U.parseWithStatement=function(a){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),a.object=this.parseParenExpression(),a.body=this.parseStatement("with"),this.finishNode(a,"WithStatement")},U.parseEmptyStatement=function(a){return this.next(),this.finishNode(a,"EmptyStatement")},U.parseLabeledStatement=function(a,l,y,w){for(var C=0,F=this.labels;C<F.length;C+=1){var L=F[C];L.name===l&&this.raise(y.start,"Label '"+l+"' is already declared")}for(var $=this.type.isLoop?"loop":this.type===g._switch?"switch":null,Z=this.labels.length-1;Z>=0;Z--){var oe=this.labels[Z];if(oe.statementStart===a.start)oe.statementStart=this.start,oe.kind=$;else break}return this.labels.push({name:l,kind:$,statementStart:this.start}),a.body=this.parseStatement(w?w.indexOf("label")===-1?w+"label":w:"label"),this.labels.pop(),a.label=y,this.finishNode(a,"LabeledStatement")},U.parseExpressionStatement=function(a,l){return a.expression=l,this.semicolon(),this.finishNode(a,"ExpressionStatement")},U.parseBlock=function(a,l,y){for(a===void 0&&(a=!0),l===void 0&&(l=this.startNode()),l.body=[],this.expect(g.braceL),a&&this.enterScope(0);this.type!==g.braceR;){var w=this.parseStatement(null);l.body.push(w)}return y&&(this.strict=!1),this.next(),a&&this.exitScope(),this.finishNode(l,"BlockStatement")},U.parseFor=function(a,l){return a.init=l,this.expect(g.semi),a.test=this.type===g.semi?null:this.parseExpression(),this.expect(g.semi),a.update=this.type===g.parenR?null:this.parseExpression(),this.expect(g.parenR),a.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(a,"ForStatement")},U.parseForIn=function(a,l){var y=this.type===g._in;return this.next(),l.type==="VariableDeclaration"&&l.declarations[0].init!=null&&(!y||this.options.ecmaVersion<8||this.strict||l.kind!=="var"||l.declarations[0].id.type!=="Identifier")&&this.raise(l.start,(y?"for-in":"for-of")+" loop variable declaration may not have an initializer"),a.left=l,a.right=y?this.parseExpression():this.parseMaybeAssign(),this.expect(g.parenR),a.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(a,y?"ForInStatement":"ForOfStatement")},U.parseVar=function(a,l,y,w){for(a.declarations=[],a.kind=y;;){var C=this.startNode();if(this.parseVarId(C,y),this.eat(g.eq)?C.init=this.parseMaybeAssign(l):!w&&y==="const"&&!(this.type===g._in||this.options.ecmaVersion>=6&&this.isContextual("of"))?this.unexpected():!w&&(y==="using"||y==="await using")&&this.options.ecmaVersion>=17&&this.type!==g._in&&!this.isContextual("of")?this.raise(this.lastTokEnd,"Missing initializer in "+y+" declaration"):!w&&C.id.type!=="Identifier"&&!(l&&(this.type===g._in||this.isContextual("of")))?this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):C.init=null,a.declarations.push(this.finishNode(C,"VariableDeclarator")),!this.eat(g.comma))break}return a},U.parseVarId=function(a,l){a.id=l==="using"||l==="await using"?this.parseIdent():this.parseBindingAtom(),this.checkLValPattern(a.id,l==="var"?Br:St,!1)};var rr=1,Vr=2,ze=4;U.parseFunction=function(a,l,y,w,C){this.initFunction(a),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!w)&&(this.type===g.star&&l&Vr&&this.unexpected(),a.generator=this.eat(g.star)),this.options.ecmaVersion>=8&&(a.async=!!w),l&rr&&(a.id=l&ze&&this.type!==g.name?null:this.parseIdent(),a.id&&!(l&Vr)&&this.checkLValSimple(a.id,this.strict||a.generator||a.async?this.treatFunctionsAsVar?Br:St:Mr));var F=this.yieldPos,L=this.awaitPos,$=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(Tn(a.async,a.generator)),l&rr||(a.id=this.type===g.name?this.parseIdent():null),this.parseFunctionParams(a),this.parseFunctionBody(a,y,!1,C),this.yieldPos=F,this.awaitPos=L,this.awaitIdentPos=$,this.finishNode(a,l&rr?"FunctionDeclaration":"FunctionExpression")},U.parseFunctionParams=function(a){this.expect(g.parenL),a.params=this.parseBindingList(g.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},U.parseClass=function(a,l){this.next();var y=this.strict;this.strict=!0,this.parseClassId(a,l),this.parseClassSuper(a);var w=this.enterClassBody(),C=this.startNode(),F=!1;for(C.body=[],this.expect(g.braceL);this.type!==g.braceR;){var L=this.parseClassElement(a.superClass!==null);L&&(C.body.push(L),L.type==="MethodDefinition"&&L.kind==="constructor"?(F&&this.raiseRecoverable(L.start,"Duplicate constructor in the same class"),F=!0):L.key&&L.key.type==="PrivateIdentifier"&&Yi(w,L)&&this.raiseRecoverable(L.key.start,"Identifier '#"+L.key.name+"' has already been declared"))}return this.strict=y,this.next(),a.body=this.finishNode(C,"ClassBody"),this.exitClassBody(),this.finishNode(a,l?"ClassDeclaration":"ClassExpression")},U.parseClassElement=function(a){if(this.eat(g.semi))return null;var l=this.options.ecmaVersion,y=this.startNode(),w="",C=!1,F=!1,L="method",$=!1;if(this.eatContextual("static")){if(l>=13&&this.eat(g.braceL))return this.parseClassStaticBlock(y),y;this.isClassElementNameStart()||this.type===g.star?$=!0:w="static"}if(y.static=$,!w&&l>=8&&this.eatContextual("async")&&((this.isClassElementNameStart()||this.type===g.star)&&!this.canInsertSemicolon()?F=!0:w="async"),!w&&(l>=9||!F)&&this.eat(g.star)&&(C=!0),!w&&!F&&!C){var Z=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?L=Z:w=Z)}if(w?(y.computed=!1,y.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),y.key.name=w,this.finishNode(y.key,"Identifier")):this.parseClassElementName(y),l<13||this.type===g.parenL||L!=="method"||C||F){var oe=!y.static&&bt(y,"constructor"),fe=oe&&a;oe&&L!=="method"&&this.raise(y.key.start,"Constructor can't have get/set modifier"),y.kind=oe?"constructor":L,this.parseClassMethod(y,C,F,fe)}else this.parseClassField(y);return y},U.isClassElementNameStart=function(){return this.type===g.name||this.type===g.privateId||this.type===g.num||this.type===g.string||this.type===g.bracketL||this.type.keyword},U.parseClassElementName=function(a){this.type===g.privateId?(this.value==="constructor"&&this.raise(this.start,"Classes can't have an element named '#constructor'"),a.computed=!1,a.key=this.parsePrivateIdent()):this.parsePropertyName(a)},U.parseClassMethod=function(a,l,y,w){var C=a.key;a.kind==="constructor"?(l&&this.raise(C.start,"Constructor can't be a generator"),y&&this.raise(C.start,"Constructor can't be an async method")):a.static&&bt(a,"prototype")&&this.raise(C.start,"Classes may not have a static property named prototype");var F=a.value=this.parseMethod(l,y,w);return a.kind==="get"&&F.params.length!==0&&this.raiseRecoverable(F.start,"getter should have no params"),a.kind==="set"&&F.params.length!==1&&this.raiseRecoverable(F.start,"setter should have exactly one param"),a.kind==="set"&&F.params[0].type==="RestElement"&&this.raiseRecoverable(F.params[0].start,"Setter cannot use rest params"),this.finishNode(a,"MethodDefinition")},U.parseClassField=function(a){return bt(a,"constructor")?this.raise(a.key.start,"Classes can't have a field named 'constructor'"):a.static&&bt(a,"prototype")&&this.raise(a.key.start,"Classes can't have a static field named 'prototype'"),this.eat(g.eq)?(this.enterScope(Yt|Kt),a.value=this.parseMaybeAssign(),this.exitScope()):a.value=null,this.semicolon(),this.finishNode(a,"PropertyDefinition")},U.parseClassStaticBlock=function(a){a.body=[];var l=this.labels;for(this.labels=[],this.enterScope(Xt|Kt);this.type!==g.braceR;){var y=this.parseStatement(null);a.body.push(y)}return this.next(),this.exitScope(),this.labels=l,this.finishNode(a,"StaticBlock")},U.parseClassId=function(a,l){this.type===g.name?(a.id=this.parseIdent(),l&&this.checkLValSimple(a.id,St,!1)):(l===!0&&this.unexpected(),a.id=null)},U.parseClassSuper=function(a){a.superClass=this.eat(g._extends)?this.parseExprSubscripts(null,!1):null},U.enterClassBody=function(){var a={declared:Object.create(null),used:[]};return this.privateNameStack.push(a),a.declared},U.exitClassBody=function(){var a=this.privateNameStack.pop(),l=a.declared,y=a.used;if(this.options.checkPrivateFields)for(var w=this.privateNameStack.length,C=w===0?null:this.privateNameStack[w-1],F=0;F<y.length;++F){var L=y[F];ee(l,L.name)||(C?C.used.push(L):this.raiseRecoverable(L.start,"Private field '#"+L.name+"' must be declared in an enclosing class"))}};function Yi(a,l){var y=l.key.name,w=a[y],C="true";return l.type==="MethodDefinition"&&(l.kind==="get"||l.kind==="set")&&(C=(l.static?"s":"i")+l.kind),w==="iget"&&C==="iset"||w==="iset"&&C==="iget"||w==="sget"&&C==="sset"||w==="sset"&&C==="sget"?(a[y]="true",!1):w?!0:(a[y]=C,!1)}function bt(a,l){var y=a.computed,w=a.key;return!y&&(w.type==="Identifier"&&w.name===l||w.type==="Literal"&&w.value===l)}U.parseExportAllDeclaration=function(a,l){return this.options.ecmaVersion>=11&&(this.eatContextual("as")?(a.exported=this.parseModuleExportName(),this.checkExport(l,a.exported,this.lastTokStart)):a.exported=null),this.expectContextual("from"),this.type!==g.string&&this.unexpected(),a.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(a.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(a,"ExportAllDeclaration")},U.parseExport=function(a,l){if(this.next(),this.eat(g.star))return this.parseExportAllDeclaration(a,l);if(this.eat(g._default))return this.checkExport(l,"default",this.lastTokStart),a.declaration=this.parseExportDefaultDeclaration(),this.finishNode(a,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())a.declaration=this.parseExportDeclaration(a),a.declaration.type==="VariableDeclaration"?this.checkVariableExport(l,a.declaration.declarations):this.checkExport(l,a.declaration.id,a.declaration.id.start),a.specifiers=[],a.source=null,this.options.ecmaVersion>=16&&(a.attributes=[]);else{if(a.declaration=null,a.specifiers=this.parseExportSpecifiers(l),this.eatContextual("from"))this.type!==g.string&&this.unexpected(),a.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(a.attributes=this.parseWithClause());else{for(var y=0,w=a.specifiers;y<w.length;y+=1){var C=w[y];this.checkUnreserved(C.local),this.checkLocalExport(C.local),C.local.type==="Literal"&&this.raise(C.local.start,"A string literal cannot be used as an exported binding without `from`.")}a.source=null,this.options.ecmaVersion>=16&&(a.attributes=[])}this.semicolon()}return this.finishNode(a,"ExportNamedDeclaration")},U.parseExportDeclaration=function(a){return this.parseStatement(null)},U.parseExportDefaultDeclaration=function(){var a;if(this.type===g._function||(a=this.isAsyncFunction())){var l=this.startNode();return this.next(),a&&this.next(),this.parseFunction(l,rr|ze,!1,a)}else if(this.type===g._class){var y=this.startNode();return this.parseClass(y,"nullableID")}else{var w=this.parseMaybeAssign();return this.semicolon(),w}},U.checkExport=function(a,l,y){a&&(typeof l!="string"&&(l=l.type==="Identifier"?l.name:l.value),ee(a,l)&&this.raiseRecoverable(y,"Duplicate export '"+l+"'"),a[l]=!0)},U.checkPatternExport=function(a,l){var y=l.type;if(y==="Identifier")this.checkExport(a,l,l.start);else if(y==="ObjectPattern")for(var w=0,C=l.properties;w<C.length;w+=1){var F=C[w];this.checkPatternExport(a,F)}else if(y==="ArrayPattern")for(var L=0,$=l.elements;L<$.length;L+=1){var Z=$[L];Z&&this.checkPatternExport(a,Z)}else y==="Property"?this.checkPatternExport(a,l.value):y==="AssignmentPattern"?this.checkPatternExport(a,l.left):y==="RestElement"&&this.checkPatternExport(a,l.argument)},U.checkVariableExport=function(a,l){if(a)for(var y=0,w=l;y<w.length;y+=1){var C=w[y];this.checkPatternExport(a,C.id)}},U.shouldParseExportStatement=function(){return this.type.keyword==="var"||this.type.keyword==="const"||this.type.keyword==="class"||this.type.keyword==="function"||this.isLet()||this.isAsyncFunction()},U.parseExportSpecifier=function(a){var l=this.startNode();return l.local=this.parseModuleExportName(),l.exported=this.eatContextual("as")?this.parseModuleExportName():l.local,this.checkExport(a,l.exported,l.exported.start),this.finishNode(l,"ExportSpecifier")},U.parseExportSpecifiers=function(a){var l=[],y=!0;for(this.expect(g.braceL);!this.eat(g.braceR);){if(y)y=!1;else if(this.expect(g.comma),this.afterTrailingComma(g.braceR))break;l.push(this.parseExportSpecifier(a))}return l},U.parseImport=function(a){return this.next(),this.type===g.string?(a.specifiers=tr,a.source=this.parseExprAtom()):(a.specifiers=this.parseImportSpecifiers(),this.expectContextual("from"),a.source=this.type===g.string?this.parseExprAtom():this.unexpected()),this.options.ecmaVersion>=16&&(a.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(a,"ImportDeclaration")},U.parseImportSpecifier=function(){var a=this.startNode();return a.imported=this.parseModuleExportName(),this.eatContextual("as")?a.local=this.parseIdent():(this.checkUnreserved(a.imported),a.local=a.imported),this.checkLValSimple(a.local,St),this.finishNode(a,"ImportSpecifier")},U.parseImportDefaultSpecifier=function(){var a=this.startNode();return a.local=this.parseIdent(),this.checkLValSimple(a.local,St),this.finishNode(a,"ImportDefaultSpecifier")},U.parseImportNamespaceSpecifier=function(){var a=this.startNode();return this.next(),this.expectContextual("as"),a.local=this.parseIdent(),this.checkLValSimple(a.local,St),this.finishNode(a,"ImportNamespaceSpecifier")},U.parseImportSpecifiers=function(){var a=[],l=!0;if(this.type===g.name&&(a.push(this.parseImportDefaultSpecifier()),!this.eat(g.comma)))return a;if(this.type===g.star)return a.push(this.parseImportNamespaceSpecifier()),a;for(this.expect(g.braceL);!this.eat(g.braceR);){if(l)l=!1;else if(this.expect(g.comma),this.afterTrailingComma(g.braceR))break;a.push(this.parseImportSpecifier())}return a},U.parseWithClause=function(){var a=[];if(!this.eat(g._with))return a;this.expect(g.braceL);for(var l={},y=!0;!this.eat(g.braceR);){if(y)y=!1;else if(this.expect(g.comma),this.afterTrailingComma(g.braceR))break;var w=this.parseImportAttribute(),C=w.key.type==="Identifier"?w.key.name:w.key.value;ee(l,C)&&this.raiseRecoverable(w.key.start,"Duplicate attribute key '"+C+"'"),l[C]=!0,a.push(w)}return a},U.parseImportAttribute=function(){var a=this.startNode();return a.key=this.type===g.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never"),this.expect(g.colon),this.type!==g.string&&this.unexpected(),a.value=this.parseExprAtom(),this.finishNode(a,"ImportAttribute")},U.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===g.string){var a=this.parseLiteral(this.value);return yt.test(a.value)&&this.raise(a.start,"An export name cannot include a lone surrogate."),a}return this.parseIdent(!0)},U.adaptDirectivePrologue=function(a){for(var l=0;l<a.length&&this.isDirectiveCandidate(a[l]);++l)a[l].directive=a[l].expression.raw.slice(1,-1)},U.isDirectiveCandidate=function(a){return this.options.ecmaVersion>=5&&a.type==="ExpressionStatement"&&a.expression.type==="Literal"&&typeof a.expression.value=="string"&&(this.input[a.start]==='"'||this.input[a.start]==="'")};var Ot=Te.prototype;Ot.toAssignable=function(a,l,y){if(this.options.ecmaVersion>=6&&a)switch(a.type){case"Identifier":this.inAsync&&a.name==="await"&&this.raise(a.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":a.type="ObjectPattern",y&&this.checkPatternErrors(y,!0);for(var w=0,C=a.properties;w<C.length;w+=1){var F=C[w];this.toAssignable(F,l),F.type==="RestElement"&&(F.argument.type==="ArrayPattern"||F.argument.type==="ObjectPattern")&&this.raise(F.argument.start,"Unexpected token")}break;case"Property":a.kind!=="init"&&this.raise(a.key.start,"Object pattern can't contain getter or setter"),this.toAssignable(a.value,l);break;case"ArrayExpression":a.type="ArrayPattern",y&&this.checkPatternErrors(y,!0),this.toAssignableList(a.elements,l);break;case"SpreadElement":a.type="RestElement",this.toAssignable(a.argument,l),a.argument.type==="AssignmentPattern"&&this.raise(a.argument.start,"Rest elements cannot have a default value");break;case"AssignmentExpression":a.operator!=="="&&this.raise(a.left.end,"Only '=' operator can be used for specifying default value."),a.type="AssignmentPattern",delete a.operator,this.toAssignable(a.left,l);break;case"ParenthesizedExpression":this.toAssignable(a.expression,l,y);break;case"ChainExpression":this.raiseRecoverable(a.start,"Optional chaining cannot appear in left-hand side");break;case"MemberExpression":if(!l)break;default:this.raise(a.start,"Assigning to rvalue")}else y&&this.checkPatternErrors(y,!0);return a},Ot.toAssignableList=function(a,l){for(var y=a.length,w=0;w<y;w++){var C=a[w];C&&this.toAssignable(C,l)}if(y){var F=a[y-1];this.options.ecmaVersion===6&&l&&F&&F.type==="RestElement"&&F.argument.type!=="Identifier"&&this.unexpected(F.argument.start)}return a},Ot.parseSpread=function(a){var l=this.startNode();return this.next(),l.argument=this.parseMaybeAssign(!1,a),this.finishNode(l,"SpreadElement")},Ot.parseRestBinding=function(){var a=this.startNode();return this.next(),this.options.ecmaVersion===6&&this.type!==g.name&&this.unexpected(),a.argument=this.parseBindingAtom(),this.finishNode(a,"RestElement")},Ot.parseBindingAtom=function(){if(this.options.ecmaVersion>=6)switch(this.type){case g.bracketL:var a=this.startNode();return this.next(),a.elements=this.parseBindingList(g.bracketR,!0,!0),this.finishNode(a,"ArrayPattern");case g.braceL:return this.parseObj(!0)}return this.parseIdent()},Ot.parseBindingList=function(a,l,y,w){for(var C=[],F=!0;!this.eat(a);)if(F?F=!1:this.expect(g.comma),l&&this.type===g.comma)C.push(null);else{if(y&&this.afterTrailingComma(a))break;if(this.type===g.ellipsis){var L=this.parseRestBinding();this.parseBindingListItem(L),C.push(L),this.type===g.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.expect(a);break}else C.push(this.parseAssignableListItem(w))}return C},Ot.parseAssignableListItem=function(a){var l=this.parseMaybeDefault(this.start,this.startLoc);return this.parseBindingListItem(l),l},Ot.parseBindingListItem=function(a){return a},Ot.parseMaybeDefault=function(a,l,y){if(y=y||this.parseBindingAtom(),this.options.ecmaVersion<6||!this.eat(g.eq))return y;var w=this.startNodeAt(a,l);return w.left=y,w.right=this.parseMaybeAssign(),this.finishNode(w,"AssignmentPattern")},Ot.checkLValSimple=function(a,l,y){l===void 0&&(l=er);var w=l!==er;switch(a.type){case"Identifier":this.strict&&this.reservedWordsStrictBind.test(a.name)&&this.raiseRecoverable(a.start,(w?"Binding ":"Assigning to ")+a.name+" in strict mode"),w&&(l===St&&a.name==="let"&&this.raiseRecoverable(a.start,"let is disallowed as a lexically bound name"),y&&(ee(y,a.name)&&this.raiseRecoverable(a.start,"Argument name clash"),y[a.name]=!0),l!==Rn&&this.declareName(a.name,l,a.start));break;case"ChainExpression":this.raiseRecoverable(a.start,"Optional chaining cannot appear in left-hand side");break;case"MemberExpression":w&&this.raiseRecoverable(a.start,"Binding member expression");break;case"ParenthesizedExpression":return w&&this.raiseRecoverable(a.start,"Binding parenthesized expression"),this.checkLValSimple(a.expression,l,y);default:this.raise(a.start,(w?"Binding":"Assigning to")+" rvalue")}},Ot.checkLValPattern=function(a,l,y){switch(l===void 0&&(l=er),a.type){case"ObjectPattern":for(var w=0,C=a.properties;w<C.length;w+=1){var F=C[w];this.checkLValInnerPattern(F,l,y)}break;case"ArrayPattern":for(var L=0,$=a.elements;L<$.length;L+=1){var Z=$[L];Z&&this.checkLValInnerPattern(Z,l,y)}break;default:this.checkLValSimple(a,l,y)}},Ot.checkLValInnerPattern=function(a,l,y){switch(l===void 0&&(l=er),a.type){case"Property":this.checkLValInnerPattern(a.value,l,y);break;case"AssignmentPattern":this.checkLValPattern(a.left,l,y);break;case"RestElement":this.checkLValPattern(a.argument,l,y);break;default:this.checkLValPattern(a,l,y)}};var Ft=function(l,y,w,C,F){this.token=l,this.isExpr=!!y,this.preserveSpace=!!w,this.override=C,this.generator=!!F},Ne={b_stat:new Ft("{",!1),b_expr:new Ft("{",!0),b_tmpl:new Ft("${",!1),p_stat:new Ft("(",!1),p_expr:new Ft("(",!0),q_tmpl:new Ft("`",!0,!0,function(a){return a.tryReadTemplateToken()}),f_stat:new Ft("function",!1),f_expr:new Ft("function",!0),f_expr_gen:new Ft("function",!0,!1,null,!0),f_gen:new Ft("function",!1,!1,null,!0)},Xn=Te.prototype;Xn.initialContext=function(){return[Ne.b_stat]},Xn.curContext=function(){return this.context[this.context.length-1]},Xn.braceIsBlock=function(a){var l=this.curContext();return l===Ne.f_expr||l===Ne.f_stat?!0:a===g.colon&&(l===Ne.b_stat||l===Ne.b_expr)?!l.isExpr:a===g._return||a===g.name&&this.exprAllowed?I.test(this.input.slice(this.lastTokEnd,this.start)):a===g._else||a===g.semi||a===g.eof||a===g.parenR||a===g.arrow?!0:a===g.braceL?l===Ne.b_stat:a===g._var||a===g._const||a===g.name?!1:!this.exprAllowed},Xn.inGeneratorContext=function(){for(var a=this.context.length-1;a>=1;a--){var l=this.context[a];if(l.token==="function")return l.generator}return!1},Xn.updateContext=function(a){var l,y=this.type;y.keyword&&a===g.dot?this.exprAllowed=!1:(l=y.updateContext)?l.call(this,a):this.exprAllowed=y.beforeExpr},Xn.overrideContext=function(a){this.curContext()!==a&&(this.context[this.context.length-1]=a)},g.parenR.updateContext=g.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=!0;return}var a=this.context.pop();a===Ne.b_stat&&this.curContext().token==="function"&&(a=this.context.pop()),this.exprAllowed=!a.isExpr},g.braceL.updateContext=function(a){this.context.push(this.braceIsBlock(a)?Ne.b_stat:Ne.b_expr),this.exprAllowed=!0},g.dollarBraceL.updateContext=function(){this.context.push(Ne.b_tmpl),this.exprAllowed=!0},g.parenL.updateContext=function(a){var l=a===g._if||a===g._for||a===g._with||a===g._while;this.context.push(l?Ne.p_stat:Ne.p_expr),this.exprAllowed=!0},g.incDec.updateContext=function(){},g._function.updateContext=g._class.updateContext=function(a){a.beforeExpr&&a!==g._else&&!(a===g.semi&&this.curContext()!==Ne.p_stat)&&!(a===g._return&&I.test(this.input.slice(this.lastTokEnd,this.start)))&&!((a===g.colon||a===g.braceL)&&this.curContext()===Ne.b_stat)?this.context.push(Ne.f_expr):this.context.push(Ne.f_stat),this.exprAllowed=!1},g.colon.updateContext=function(){this.curContext().token==="function"&&this.context.pop(),this.exprAllowed=!0},g.backQuote.updateContext=function(){this.curContext()===Ne.q_tmpl?this.context.pop():this.context.push(Ne.q_tmpl),this.exprAllowed=!1},g.star.updateContext=function(a){if(a===g._function){var l=this.context.length-1;this.context[l]===Ne.f_expr?this.context[l]=Ne.f_expr_gen:this.context[l]=Ne.f_gen}this.exprAllowed=!0},g.name.updateContext=function(a){var l=!1;this.options.ecmaVersion>=6&&a!==g.dot&&(this.value==="of"&&!this.exprAllowed||this.value==="yield"&&this.inGeneratorContext())&&(l=!0),this.exprAllowed=l};var ae=Te.prototype;ae.checkPropClash=function(a,l,y){if(!(this.options.ecmaVersion>=9&&a.type==="SpreadElement")&&!(this.options.ecmaVersion>=6&&(a.computed||a.method||a.shorthand))){var w=a.key,C;switch(w.type){case"Identifier":C=w.name;break;case"Literal":C=String(w.value);break;default:return}var F=a.kind;if(this.options.ecmaVersion>=6){C==="__proto__"&&F==="init"&&(l.proto&&(y?y.doubleProto<0&&(y.doubleProto=w.start):this.raiseRecoverable(w.start,"Redefinition of __proto__ property")),l.proto=!0);return}C="$"+C;var L=l[C];if(L){var $;F==="init"?$=this.strict&&L.init||L.get||L.set:$=L.init||L[F],$&&this.raiseRecoverable(w.start,"Redefinition of property")}else L=l[C]={init:!1,get:!1,set:!1};L[F]=!0}},ae.parseExpression=function(a,l){var y=this;return this.catchStackOverflow(function(){var w=y.start,C=y.startLoc,F=y.parseMaybeAssign(a,l);if(y.type===g.comma){var L=y.startNodeAt(w,C);for(L.expressions=[F];y.eat(g.comma);)L.expressions.push(y.parseMaybeAssign(a,l));return y.finishNode(L,"SequenceExpression")}return F})},ae.parseMaybeAssign=function(a,l,y){if(this.isContextual("yield")){if(this.inGenerator)return this.parseYield(a);this.exprAllowed=!1}var w=!1,C=-1,F=-1,L=-1;l?(C=l.parenthesizedAssign,F=l.trailingComma,L=l.doubleProto,l.parenthesizedAssign=l.trailingComma=-1):(l=new ye,w=!0);var $=this.start,Z=this.startLoc;(this.type===g.parenL||this.type===g.name)&&(this.potentialArrowAt=this.start,this.potentialArrowInForAwait=a==="await");var oe=this.parseMaybeConditional(a,l);if(y&&(oe=y.call(this,oe,$,Z)),this.type.isAssign){var fe=this.startNodeAt($,Z);return fe.operator=this.value,this.type===g.eq&&(oe=this.toAssignable(oe,!1,l)),w||(l.parenthesizedAssign=l.trailingComma=l.doubleProto=-1),l.shorthandAssign>=oe.start&&(l.shorthandAssign=-1),this.type===g.eq?this.checkLValPattern(oe):this.checkLValSimple(oe),fe.left=oe,this.next(),fe.right=this.parseMaybeAssign(a),L>-1&&(l.doubleProto=L),this.finishNode(fe,"AssignmentExpression")}else w&&this.checkExpressionErrors(l,!0);return C>-1&&(l.parenthesizedAssign=C),F>-1&&(l.trailingComma=F),oe},ae.parseMaybeConditional=function(a,l){var y=this.start,w=this.startLoc,C=this.parseExprOps(a,l);if(this.checkExpressionErrors(l))return C;if(!(C.type==="ArrowFunctionExpression"&&C.start===y)&&this.eat(g.question)){var F=this.startNodeAt(y,w);return F.test=C,F.consequent=this.parseMaybeAssign(),this.expect(g.colon),F.alternate=this.parseMaybeAssign(a),this.finishNode(F,"ConditionalExpression")}return C},ae.parseExprOps=function(a,l){var y=this.start,w=this.startLoc,C=this.parseMaybeUnary(l,!1,!1,a);return this.checkExpressionErrors(l)||C.start===y&&C.type==="ArrowFunctionExpression"?C:this.parseExprOp(C,y,w,-1,a)},ae.parseExprOp=function(a,l,y,w,C){var F=this.type.binop;if(F!=null&&(!C||this.type!==g._in)&&F>w){var L=this.type===g.logicalOR||this.type===g.logicalAND,$=this.type===g.coalesce;$&&(F=g.logicalAND.binop);var Z=this.value;this.next();var oe=this.start,fe=this.startLoc,Pe=this.parseExprOp(this.parseMaybeUnary(null,!1,!1,C),oe,fe,F,C),rt=this.buildBinary(l,y,a,Pe,Z,L||$);return(L&&this.type===g.coalesce||$&&(this.type===g.logicalOR||this.type===g.logicalAND))&&this.raiseRecoverable(this.start,"Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"),this.parseExprOp(rt,l,y,w,C)}return a},ae.buildBinary=function(a,l,y,w,C,F){w.type==="PrivateIdentifier"&&this.raise(w.start,"Private identifier can only be left side of binary expression");var L=this.startNodeAt(a,l);return L.left=y,L.operator=C,L.right=w,this.finishNode(L,F?"LogicalExpression":"BinaryExpression")},ae.parseMaybeUnary=function(a,l,y,w){var C=this.start,F=this.startLoc,L;if(this.isContextual("await")&&this.canAwait)L=this.parseAwait(w),l=!0;else if(this.type.prefix){var $=this.startNode(),Z=this.type===g.incDec;$.operator=this.value,$.prefix=!0,this.next(),$.argument=this.parseMaybeUnary(null,!0,Z,w),this.checkExpressionErrors(a,!0),Z?this.checkLValSimple($.argument):this.strict&&$.operator==="delete"&&np($.argument)?this.raiseRecoverable($.start,"Deleting local variable in strict mode"):$.operator==="delete"&&ku($.argument)?this.raiseRecoverable($.start,"Private fields can not be deleted"):l=!0,L=this.finishNode($,Z?"UpdateExpression":"UnaryExpression")}else if(!l&&this.type===g.privateId)(w||this.privateNameStack.length===0)&&this.options.checkPrivateFields&&this.unexpected(),L=this.parsePrivateIdent(),this.type!==g._in&&this.unexpected();else{if(L=this.parseExprSubscripts(a,w),this.checkExpressionErrors(a))return L;for(;this.type.postfix&&!this.canInsertSemicolon();){var oe=this.startNodeAt(C,F);oe.operator=this.value,oe.prefix=!1,oe.argument=L,this.checkLValSimple(L),this.next(),L=this.finishNode(oe,"UpdateExpression")}}if(!y&&this.eat(g.starstar))if(l)this.unexpected(this.lastTokStart);else return this.buildBinary(C,F,L,this.parseMaybeUnary(null,!1,!1,w),"**",!1);else return L};function np(a){return a.type==="Identifier"||a.type==="ParenthesizedExpression"&&np(a.expression)}function ku(a){return a.type==="MemberExpression"&&a.property.type==="PrivateIdentifier"||a.type==="ChainExpression"&&ku(a.expression)||a.type==="ParenthesizedExpression"&&ku(a.expression)}ae.parseExprSubscripts=function(a,l){var y=this.start,w=this.startLoc,C=this.parseExprAtom(a,l);if(C.type==="ArrowFunctionExpression"&&this.input.slice(this.lastTokStart,this.lastTokEnd)!==")")return C;var F=this.parseSubscripts(C,y,w,!1,l);return a&&F.type==="MemberExpression"&&(a.parenthesizedAssign>=F.start&&(a.parenthesizedAssign=-1),a.parenthesizedBind>=F.start&&(a.parenthesizedBind=-1),a.trailingComma>=F.start&&(a.trailingComma=-1)),F},ae.parseSubscripts=function(a,l,y,w,C){for(var F=this.options.ecmaVersion>=8&&a.type==="Identifier"&&a.name==="async"&&this.lastTokEnd===a.end&&!this.canInsertSemicolon()&&a.end-a.start===5&&this.potentialArrowAt===a.start,L=!1;;){var $=this.parseSubscript(a,l,y,w,F,L,C);if($.optional&&(L=!0),$===a||$.type==="ArrowFunctionExpression"){if(L){var Z=this.startNodeAt(l,y);Z.expression=$,$=this.finishNode(Z,"ChainExpression")}return $}a=$}},ae.shouldParseAsyncArrow=function(){return!this.canInsertSemicolon()&&this.eat(g.arrow)},ae.parseSubscriptAsyncArrow=function(a,l,y,w){return this.parseArrowExpression(this.startNodeAt(a,l),y,!0,w)},ae.parseSubscript=function(a,l,y,w,C,F,L){var $=this.options.ecmaVersion>=11,Z=$&&this.eat(g.questionDot);w&&Z&&this.raise(this.lastTokStart,"Optional chaining cannot appear in the callee of new expressions");var oe=this.eat(g.bracketL);if(oe||Z&&this.type!==g.parenL&&this.type!==g.backQuote||this.eat(g.dot)){var fe=this.startNodeAt(l,y);fe.object=a,oe?(fe.property=this.parseExpression(),this.expect(g.bracketR)):this.type===g.privateId&&a.type!=="Super"?fe.property=this.parsePrivateIdent():fe.property=this.parseIdent(this.options.allowReserved!=="never"),fe.computed=!!oe,$&&(fe.optional=Z),a=this.finishNode(fe,"MemberExpression")}else if(!w&&this.eat(g.parenL)){var Pe=new ye,rt=this.yieldPos,rs=this.awaitPos,Yn=this.awaitIdentPos;this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0;var go=this.parseExprList(g.parenR,this.options.ecmaVersion>=8,!1,Pe);if(C&&!Z&&this.shouldParseAsyncArrow())return this.checkPatternErrors(Pe,!1),this.checkYieldAwaitInDefaultParams(),this.awaitIdentPos>0&&this.raise(this.awaitIdentPos,"Cannot use 'await' as identifier inside an async function"),this.yieldPos=rt,this.awaitPos=rs,this.awaitIdentPos=Yn,this.parseSubscriptAsyncArrow(l,y,go,L);this.checkExpressionErrors(Pe,!0),this.yieldPos=rt||this.yieldPos,this.awaitPos=rs||this.awaitPos,this.awaitIdentPos=Yn||this.awaitIdentPos;var ei=this.startNodeAt(l,y);ei.callee=a,ei.arguments=go,$&&(ei.optional=Z),a=this.finishNode(ei,"CallExpression")}else if(this.type===g.backQuote){(Z||F)&&this.raise(this.start,"Optional chaining cannot appear in the tag of tagged template expressions");var ti=this.startNodeAt(l,y);ti.tag=a,ti.quasi=this.parseTemplate({isTagged:!0}),a=this.finishNode(ti,"TaggedTemplateExpression")}return a},ae.parseExprAtom=function(a,l,y){this.type===g.slash&&this.readRegexp();var w,C=this.potentialArrowAt===this.start;switch(this.type){case g._super:return this.allowSuper||this.raise(this.start,"'super' keyword outside a method"),w=this.startNode(),this.next(),this.type===g.parenL&&!this.allowDirectSuper&&this.raise(w.start,"super() call outside constructor of a subclass"),this.type!==g.dot&&this.type!==g.bracketL&&this.type!==g.parenL&&this.unexpected(),this.finishNode(w,"Super");case g._this:return w=this.startNode(),this.next(),this.finishNode(w,"ThisExpression");case g.name:var F=this.start,L=this.startLoc,$=this.containsEsc,Z=this.parseIdent(!1);if(this.options.ecmaVersion>=8&&!$&&Z.name==="async"&&!this.canInsertSemicolon()&&this.eat(g._function))return this.overrideContext(Ne.f_expr),this.parseFunction(this.startNodeAt(F,L),0,!1,!0,l);if(C&&!this.canInsertSemicolon()){if(this.eat(g.arrow))return this.parseArrowExpression(this.startNodeAt(F,L),[Z],!1,l);if(this.options.ecmaVersion>=8&&Z.name==="async"&&this.type===g.name&&!$&&(!this.potentialArrowInForAwait||this.value!=="of"||this.containsEsc))return Z=this.parseIdent(!1),(this.canInsertSemicolon()||!this.eat(g.arrow))&&this.unexpected(),this.parseArrowExpression(this.startNodeAt(F,L),[Z],!0,l)}return Z;case g.regexp:var oe=this.value;return w=this.parseLiteral(oe.value),w.regex={pattern:oe.pattern,flags:oe.flags},w;case g.num:case g.string:return this.parseLiteral(this.value);case g._null:case g._true:case g._false:return w=this.startNode(),w.value=this.type===g._null?null:this.type===g._true,w.raw=this.type.keyword,this.next(),this.finishNode(w,"Literal");case g.parenL:var fe=this.start,Pe=this.parseParenAndDistinguishExpression(C,l);return a&&(a.parenthesizedAssign<0&&!this.isSimpleAssignTarget(Pe)&&(a.parenthesizedAssign=fe),a.parenthesizedBind<0&&(a.parenthesizedBind=fe)),Pe;case g.bracketL:return w=this.startNode(),this.next(),w.elements=this.parseExprList(g.bracketR,!0,!0,a),this.finishNode(w,"ArrayExpression");case g.braceL:return this.overrideContext(Ne.b_expr),this.parseObj(!1,a);case g._function:return w=this.startNode(),this.next(),this.parseFunction(w,0);case g._class:return this.parseClass(this.startNode(),!1);case g._new:return this.parseNew();case g.backQuote:return this.parseTemplate();case g._import:return this.options.ecmaVersion>=11?this.parseExprImport(y):this.unexpected();default:return this.parseExprAtomDefault()}},ae.parseExprAtomDefault=function(){this.unexpected()},ae.parseExprImport=function(a){var l=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===g.parenL&&!a)return this.parseDynamicImport(l);if(this.type===g.dot){var y=this.startNodeAt(l.start,l.loc&&l.loc.start);return y.name="import",l.meta=this.finishNode(y,"Identifier"),this.parseImportMeta(l)}else this.unexpected()},ae.parseDynamicImport=function(a){if(this.next(),a.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(g.parenR)?a.options=null:(this.expect(g.comma),this.afterTrailingComma(g.parenR)?a.options=null:(a.options=this.parseMaybeAssign(),this.eat(g.parenR)||(this.expect(g.comma),this.afterTrailingComma(g.parenR)||this.unexpected())));else if(!this.eat(g.parenR)){var l=this.start;this.eat(g.comma)&&this.eat(g.parenR)?this.raiseRecoverable(l,"Trailing comma is not allowed in import()"):this.unexpected(l)}return this.finishNode(a,"ImportExpression")},ae.parseImportMeta=function(a){this.next();var l=this.containsEsc;return a.property=this.parseIdent(!0),a.property.name!=="meta"&&this.raiseRecoverable(a.property.start,"The only valid meta property for import is 'import.meta'"),l&&this.raiseRecoverable(a.start,"'import.meta' must not contain escaped characters"),this.options.sourceType!=="module"&&!this.options.allowImportExportEverywhere&&this.raiseRecoverable(a.start,"Cannot use 'import.meta' outside a module"),this.finishNode(a,"MetaProperty")},ae.parseLiteral=function(a){var l=this.startNode();return l.value=a,l.raw=this.input.slice(this.start,this.end),l.raw.charCodeAt(l.raw.length-1)===110&&(l.bigint=l.value!=null?l.value.toString():l.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(l,"Literal")},ae.parseParenExpression=function(){this.expect(g.parenL);var a=this.parseExpression();return this.expect(g.parenR),a},ae.shouldParseArrow=function(a){return!this.canInsertSemicolon()},ae.parseParenAndDistinguishExpression=function(a,l){var y=this.start,w=this.startLoc,C,F=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var L=this.start,$=this.startLoc,Z=[],oe=!0,fe=!1,Pe=new ye,rt=this.yieldPos,rs=this.awaitPos,Yn;for(this.yieldPos=0,this.awaitPos=0;this.type!==g.parenR;)if(oe?oe=!1:this.expect(g.comma),F&&this.afterTrailingComma(g.parenR,!0)){fe=!0;break}else if(this.type===g.ellipsis){Yn=this.start,Z.push(this.parseParenItem(this.parseRestBinding())),this.type===g.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}else Z.push(this.parseMaybeAssign(!1,Pe,this.parseParenItem));var go=this.lastTokEnd,ei=this.lastTokEndLoc;if(this.expect(g.parenR),a&&this.shouldParseArrow(Z)&&this.eat(g.arrow))return this.checkPatternErrors(Pe,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=rt,this.awaitPos=rs,this.parseParenArrowList(y,w,Z,l);(!Z.length||fe)&&this.unexpected(this.lastTokStart),Yn&&this.unexpected(Yn),this.checkExpressionErrors(Pe,!0),this.yieldPos=rt||this.yieldPos,this.awaitPos=rs||this.awaitPos,Z.length>1?(C=this.startNodeAt(L,$),C.expressions=Z,this.finishNodeAt(C,"SequenceExpression",go,ei)):C=Z[0]}else C=this.parseParenExpression();if(this.options.preserveParens){var ti=this.startNodeAt(y,w);return ti.expression=C,this.finishNode(ti,"ParenthesizedExpression")}else return C},ae.parseParenItem=function(a){return a},ae.parseParenArrowList=function(a,l,y,w){return this.parseArrowExpression(this.startNodeAt(a,l),y,!1,w)};var Aw=[];ae.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var a=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===g.dot){var l=this.startNodeAt(a.start,a.loc&&a.loc.start);l.name="new",a.meta=this.finishNode(l,"Identifier"),this.next();var y=this.containsEsc;return a.property=this.parseIdent(!0),a.property.name!=="target"&&this.raiseRecoverable(a.property.start,"The only valid meta property for new is 'new.target'"),y&&this.raiseRecoverable(a.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(a.start,"'new.target' can only be used in functions and class static block"),this.finishNode(a,"MetaProperty")}var w=this.start,C=this.startLoc;return a.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),w,C,!0,!1),a.callee.type==="Super"&&this.raiseRecoverable(w,"Invalid use of 'super'"),this.eat(g.parenL)?a.arguments=this.parseExprList(g.parenR,this.options.ecmaVersion>=8,!1):a.arguments=Aw,this.finishNode(a,"NewExpression")},ae.parseTemplateElement=function(a){var l=a.isTagged,y=this.startNode();return this.type===g.invalidTemplate?(l||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),y.value={raw:this.value.replace(/\r\n?/g,`+`),cooked:null}):y.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,`+`),cooked:this.value},this.next(),y.tail=this.type===g.backQuote,this.finishNode(y,"TemplateElement")},ae.parseTemplate=function(a){a===void 0&&(a={});var l=a.isTagged;l===void 0&&(l=!1);var y=this.startNode();this.next(),y.expressions=[];var w=this.parseTemplateElement({isTagged:l});for(y.quasis=[w];!w.tail;)this.type===g.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(g.dollarBraceL),y.expressions.push(this.parseExpression()),this.expect(g.braceR),y.quasis.push(w=this.parseTemplateElement({isTagged:l}));return this.next(),this.finishNode(y,"TemplateLiteral")},ae.isAsyncProp=function(a){return!a.computed&&a.key.type==="Identifier"&&a.key.name==="async"&&(this.type===g.name||this.type===g.num||this.type===g.string||this.type===g.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===g.star)&&!I.test(this.input.slice(this.lastTokEnd,this.start))},ae.parseObj=function(a,l){var y=this.startNode(),w=!0,C={};for(y.properties=[],this.next();!this.eat(g.braceR);){if(w)w=!1;else if(this.expect(g.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(g.braceR))break;var F=this.parseProperty(a,l);a||this.checkPropClash(F,C,l),y.properties.push(F)}return this.finishNode(y,a?"ObjectPattern":"ObjectExpression")},ae.parseProperty=function(a,l){var y=this.startNode(),w,C,F,L;if(this.options.ecmaVersion>=9&&this.eat(g.ellipsis))return a?(y.argument=this.parseIdent(!1),this.type===g.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(y,"RestElement")):(y.argument=this.parseMaybeAssign(!1,l),this.type===g.comma&&l&&l.trailingComma<0&&(l.trailingComma=this.start),this.finishNode(y,"SpreadElement"));this.options.ecmaVersion>=6&&(y.method=!1,y.shorthand=!1,(a||l)&&(F=this.start,L=this.startLoc),a||(w=this.eat(g.star)));var $=this.containsEsc;return this.parsePropertyName(y),!a&&!$&&this.options.ecmaVersion>=8&&!w&&this.isAsyncProp(y)?(C=!0,w=this.options.ecmaVersion>=9&&this.eat(g.star),this.parsePropertyName(y)):C=!1,this.parsePropertyValue(y,a,w,C,F,L,l,$),this.finishNode(y,"Property")},ae.parseGetterSetter=function(a){var l=a.key.name;this.parsePropertyName(a),a.value=this.parseMethod(!1),a.kind=l;var y=a.kind==="get"?0:1;if(a.value.params.length!==y){var w=a.value.start;a.kind==="get"?this.raiseRecoverable(w,"getter should have no params"):this.raiseRecoverable(w,"setter should have exactly one param")}else a.kind==="set"&&a.value.params[0].type==="RestElement"&&this.raiseRecoverable(a.value.params[0].start,"Setter cannot use rest params")},ae.parsePropertyValue=function(a,l,y,w,C,F,L,$){(y||w)&&this.type===g.colon&&this.unexpected(),this.eat(g.colon)?(a.value=l?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,L),a.kind="init"):this.options.ecmaVersion>=6&&this.type===g.parenL?(l&&this.unexpected(),a.method=!0,a.value=this.parseMethod(y,w),a.kind="init"):!l&&!$&&this.options.ecmaVersion>=5&&!a.computed&&a.key.type==="Identifier"&&(a.key.name==="get"||a.key.name==="set")&&this.type!==g.comma&&this.type!==g.braceR&&this.type!==g.eq?((y||w)&&this.unexpected(),this.parseGetterSetter(a)):this.options.ecmaVersion>=6&&!a.computed&&a.key.type==="Identifier"?((y||w)&&this.unexpected(),this.checkUnreserved(a.key),a.key.name==="await"&&!this.awaitIdentPos&&(this.awaitIdentPos=C),l?a.value=this.parseMaybeDefault(C,F,this.copyNode(a.key)):this.type===g.eq&&L?(L.shorthandAssign<0&&(L.shorthandAssign=this.start),a.value=this.parseMaybeDefault(C,F,this.copyNode(a.key))):a.value=this.copyNode(a.key),a.kind="init",a.shorthand=!0):this.unexpected()},ae.parsePropertyName=function(a){if(this.options.ecmaVersion>=6){if(this.eat(g.bracketL))return a.computed=!0,a.key=this.parseMaybeAssign(),this.expect(g.bracketR),a.key;a.computed=!1}return a.key=this.type===g.num||this.type===g.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")},ae.initFunction=function(a){a.id=null,this.options.ecmaVersion>=6&&(a.generator=a.expression=!1),this.options.ecmaVersion>=8&&(a.async=!1)},ae.parseMethod=function(a,l,y){var w=this.startNode(),C=this.yieldPos,F=this.awaitPos,L=this.awaitIdentPos;return this.initFunction(w),this.options.ecmaVersion>=6&&(w.generator=a),this.options.ecmaVersion>=8&&(w.async=!!l),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(Tn(l,w.generator)|Kt|(y?Kn:0)),this.expect(g.parenL),w.params=this.parseBindingList(g.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(w,!1,!0,!1),this.yieldPos=C,this.awaitPos=F,this.awaitIdentPos=L,this.finishNode(w,"FunctionExpression")},ae.parseArrowExpression=function(a,l,y,w){var C=this.yieldPos,F=this.awaitPos,L=this.awaitIdentPos;return this.enterScope(Tn(y,!1)|He),this.initFunction(a),this.options.ecmaVersion>=8&&(a.async=!!y),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,a.params=this.toAssignableList(l,!0),this.parseFunctionBody(a,!0,!1,w),this.yieldPos=C,this.awaitPos=F,this.awaitIdentPos=L,this.finishNode(a,"ArrowFunctionExpression")},ae.parseFunctionBody=function(a,l,y,w){var C=l&&this.type!==g.braceL,F=this.strict,L=!1;if(C)a.body=this.parseMaybeAssign(w),a.expression=!0,this.checkParams(a,!1);else{var $=this.options.ecmaVersion>=7&&!this.isSimpleParamList(a.params);(!F||$)&&(L=this.strictDirective(this.end),L&&$&&this.raiseRecoverable(a.start,"Illegal 'use strict' directive in function with non-simple parameter list"));var Z=this.labels;this.labels=[],L&&(this.strict=!0),this.checkParams(a,!F&&!L&&!l&&!y&&this.isSimpleParamList(a.params)),this.strict&&a.id&&this.checkLValSimple(a.id,Rn),a.body=this.parseBlock(!1,void 0,L&&!F),a.expression=!1,this.adaptDirectivePrologue(a.body.body),this.labels=Z}this.exitScope()},ae.isSimpleParamList=function(a){for(var l=0,y=a;l<y.length;l+=1){var w=y[l];if(w.type!=="Identifier")return!1}return!0},ae.checkParams=function(a,l){for(var y=Object.create(null),w=0,C=a.params;w<C.length;w+=1){var F=C[w];this.checkLValInnerPattern(F,Br,l?null:y)}},ae.parseExprList=function(a,l,y,w){for(var C=[],F=!0;!this.eat(a);){if(F)F=!1;else if(this.expect(g.comma),l&&this.afterTrailingComma(a))break;var L=void 0;y&&this.type===g.comma?L=null:this.type===g.ellipsis?(L=this.parseSpread(w),w&&this.type===g.comma&&w.trailingComma<0&&(w.trailingComma=this.start)):L=this.parseMaybeAssign(!1,w),C.push(L)}return C},ae.checkUnreserved=function(a){var l=a.start,y=a.end,w=a.name;if(this.inGenerator&&w==="yield"&&this.raiseRecoverable(l,"Cannot use 'yield' as identifier inside a generator"),this.inAsync&&w==="await"&&this.raiseRecoverable(l,"Cannot use 'await' as identifier inside an async function"),!(this.currentThisScope().flags&br)&&w==="arguments"&&this.raiseRecoverable(l,"Cannot use 'arguments' in class field initializer"),this.inClassStaticBlock&&(w==="arguments"||w==="await")&&this.raise(l,"Cannot use "+w+" in class static initialization block"),this.keywords.test(w)&&this.raise(l,"Unexpected keyword '"+w+"'"),!(this.options.ecmaVersion<6&&this.input.slice(l,y).indexOf("\\")!==-1)){var C=this.strict?this.reservedWordsStrict:this.reservedWords;C.test(w)&&(!this.inAsync&&w==="await"&&this.raiseRecoverable(l,"Cannot use keyword 'await' outside an async function"),this.raiseRecoverable(l,"The keyword '"+w+"' is reserved"))}},ae.parseIdent=function(a){var l=this.parseIdentNode();return this.next(!!a),this.finishNode(l,"Identifier"),a||(this.checkUnreserved(l),l.name==="await"&&!this.awaitIdentPos&&(this.awaitIdentPos=l.start)),l},ae.parseIdentNode=function(){var a=this.startNode();return this.type===g.name?a.name=this.value:this.type.keyword?(a.name=this.type.keyword,(a.name==="class"||a.name==="function")&&(this.lastTokEnd!==this.lastTokStart+1||this.input.charCodeAt(this.lastTokStart)!==46)&&this.context.pop(),this.type=g.name):this.unexpected(),a},ae.parsePrivateIdent=function(){var a=this.startNode();return this.type===g.privateId?a.name=this.value:this.unexpected(),this.next(),this.finishNode(a,"PrivateIdentifier"),this.options.checkPrivateFields&&(this.privateNameStack.length===0?this.raise(a.start,"Private field '#"+a.name+"' must be declared in an enclosing class"):this.privateNameStack[this.privateNameStack.length-1].used.push(a)),a},ae.parseYield=function(a){this.yieldPos||(this.yieldPos=this.start);var l=this.startNode();return this.next(),this.type===g.semi||this.canInsertSemicolon()||this.type!==g.star&&!this.type.startsExpr?(l.delegate=!1,l.argument=null):(l.delegate=this.eat(g.star),l.argument=this.parseMaybeAssign(a)),this.finishNode(l,"YieldExpression")},ae.parseAwait=function(a){this.awaitPos||(this.awaitPos=this.start);var l=this.startNode();return this.next(),l.argument=this.parseMaybeUnary(null,!0,!1,a),this.finishNode(l,"AwaitExpression")};var fo=Te.prototype;fo.raise=function(a,l){var y=ut(this.input,a);l+=" ("+y.line+":"+y.column+")",this.sourceFile&&(l+=" in "+this.sourceFile);var w=new SyntaxError(l);throw w.pos=a,w.loc=y,w.raisedAt=this.pos,w},fo.raiseRecoverable=fo.raise,fo.curPosition=function(){if(this.options.locations)return new R(this.curLine,this.pos-this.lineStart)};var rn=Te.prototype,Sw=function(l){this.flags=l,this.var=[],this.lexical=[],this.functions=[]};rn.enterScope=function(a){this.scopeStack.push(new Sw(a))},rn.exitScope=function(){this.scopeStack.pop()},rn.treatFunctionsAsVarInScope=function(a){return a.flags&De||!this.inModule&&a.flags&ct},rn.declareName=function(a,l,y){var w=!1;if(l===St){var C=this.currentScope();w=C.lexical.indexOf(a)>-1||C.functions.indexOf(a)>-1||C.var.indexOf(a)>-1,C.lexical.push(a),this.inModule&&C.flags&ct&&delete this.undefinedExports[a]}else if(l===Ie){var F=this.currentScope();F.lexical.push(a)}else if(l===Mr){var L=this.currentScope();this.treatFunctionsAsVar?w=L.lexical.indexOf(a)>-1:w=L.lexical.indexOf(a)>-1||L.var.indexOf(a)>-1,L.functions.push(a)}else for(var $=this.scopeStack.length-1;$>=0;--$){var Z=this.scopeStack[$];if(Z.lexical.indexOf(a)>-1&&!(Z.flags&Pt&&Z.lexical[0]===a)||!this.treatFunctionsAsVarInScope(Z)&&Z.functions.indexOf(a)>-1){w=!0;break}if(Z.var.push(a),this.inModule&&Z.flags&ct&&delete this.undefinedExports[a],Z.flags&br)break}w&&this.raiseRecoverable(y,"Identifier '"+a+"' has already been declared")},rn.checkLocalExport=function(a){this.scopeStack[0].lexical.indexOf(a.name)===-1&&this.scopeStack[0].var.indexOf(a.name)===-1&&(this.undefinedExports[a.name]=a)},rn.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},rn.currentVarScope=function(){for(var a=this.scopeStack.length-1;;a--){var l=this.scopeStack[a];if(l.flags&(br|Yt|Xt))return l}},rn.currentThisScope=function(){for(var a=this.scopeStack.length-1;;a--){var l=this.scopeStack[a];if(l.flags&(br|Yt|Xt)&&!(l.flags&He))return l}};var es=function(l,y,w){this.type="",this.start=y,this.end=0,l.options.locations&&(this.loc=new Ge(l,w)),l.options.directSourceFile&&(this.sourceFile=l.options.directSourceFile),l.options.ranges&&(this.range=[y,0])},ts=Te.prototype;ts.startNode=function(){return new es(this,this.start,this.startLoc)},ts.startNodeAt=function(a,l){return new es(this,a,l)};function ip(a,l,y,w){return a.type=l,a.end=y,this.options.locations&&(a.loc.end=w),this.options.ranges&&(a.range[1]=y),a}ts.finishNode=function(a,l){return ip.call(this,a,l,this.lastTokEnd,this.lastTokEndLoc)},ts.finishNodeAt=function(a,l,y,w){return ip.call(this,a,l,y,w)},ts.copyNode=function(a){var l=new es(this,a.start,this.startLoc);for(var y in a)l[y]=a[y];return l};var Ew="Berf Beria_Erfe Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sidetic Sidt Sunu Sunuwar Tai_Yo Tayo Todhri Todr Tolong_Siki Tols Tulu_Tigalari Tutg Unknown Zzzz",sp="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",op=sp+" Extended_Pictographic",ap=op,up=ap+" EBase EComp EMod EPres ExtPict",cp=up,_w=cp,Cw={9:sp,10:op,11:ap,12:up,13:cp,14:_w},Dw="Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji",Iw={9:"",10:"",11:"",12:"",13:"",14:Dw},lp="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",fp="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",pp=fp+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",hp=pp+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",dp=hp+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",mp=dp+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",Tw=mp+" "+Ew,Rw={9:fp,10:pp,11:hp,12:dp,13:mp,14:Tw},gp={};function Nw(a){var l=gp[a]={binary:se(Cw[a]+" "+lp),binaryOfStrings:se(Iw[a]),nonBinary:{General_Category:se(lp),Script:se(Rw[a])}};l.nonBinary.Script_Extensions=l.nonBinary.Script,l.nonBinary.gc=l.nonBinary.General_Category,l.nonBinary.sc=l.nonBinary.Script,l.nonBinary.scx=l.nonBinary.Script_Extensions}for(var Au=0,yp=[9,10,11,12,13,14];Au<yp.length;Au+=1){var Pw=yp[Au];Nw(Pw)}var H=Te.prototype,po=function(l,y){this.parent=l,this.base=y||this};po.prototype.separatedFrom=function(l){for(var y=this;y;y=y.parent)for(var w=l;w;w=w.parent)if(y.base===w.base&&y!==w)return!0;return!1},po.prototype.sibling=function(){return new po(this.parent,this.base)};var vr=function(l){this.parser=l,this.validFlags="gim"+(l.options.ecmaVersion>=6?"uy":"")+(l.options.ecmaVersion>=9?"s":"")+(l.options.ecmaVersion>=13?"d":"")+(l.options.ecmaVersion>=15?"v":""),this.unicodeProperties=gp[l.options.ecmaVersion>=14?14:l.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};vr.prototype.reset=function(l,y,w){var C=w.indexOf("v")!==-1,F=w.indexOf("u")!==-1;this.start=l|0,this.source=y+"",this.flags=w,C&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=F&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=F&&this.parser.options.ecmaVersion>=9)},vr.prototype.raise=function(l){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+l)},vr.prototype.at=function(l,y){y===void 0&&(y=!1);var w=this.source,C=w.length;if(l>=C)return-1;var F=w.charCodeAt(l);if(!(y||this.switchU)||F<=55295||F>=57344||l+1>=C)return F;var L=w.charCodeAt(l+1);return L>=56320&&L<=57343?(F<<10)+L-56613888:F},vr.prototype.nextIndex=function(l,y){y===void 0&&(y=!1);var w=this.source,C=w.length;if(l>=C)return C;var F=w.charCodeAt(l),L;return!(y||this.switchU)||F<=55295||F>=57344||l+1>=C||(L=w.charCodeAt(l+1))<56320||L>57343?l+1:l+2},vr.prototype.current=function(l){return l===void 0&&(l=!1),this.at(this.pos,l)},vr.prototype.lookahead=function(l){return l===void 0&&(l=!1),this.at(this.nextIndex(this.pos,l),l)},vr.prototype.advance=function(l){l===void 0&&(l=!1),this.pos=this.nextIndex(this.pos,l)},vr.prototype.eat=function(l,y){return y===void 0&&(y=!1),this.current(y)===l?(this.advance(y),!0):!1},vr.prototype.eatChars=function(l,y){y===void 0&&(y=!1);for(var w=this.pos,C=0,F=l;C<F.length;C+=1){var L=F[C],$=this.at(w,y);if($===-1||$!==L)return!1;w=this.nextIndex(w,y)}return this.pos=w,!0},H.validateRegExpFlags=function(a){for(var l=a.validFlags,y=a.flags,w=!1,C=!1,F=0;F<y.length;F++){var L=y.charAt(F);l.indexOf(L)===-1&&this.raise(a.start,"Invalid regular expression flag"),y.indexOf(L,F+1)>-1&&this.raise(a.start,"Duplicate regular expression flag"),L==="u"&&(w=!0),L==="v"&&(C=!0)}this.options.ecmaVersion>=15&&w&&C&&this.raise(a.start,"Invalid regular expression flag")};function Ow(a){for(var l in a)return!0;return!1}H.validateRegExpPattern=function(a){this.regexp_pattern(a),!a.switchN&&this.options.ecmaVersion>=9&&Ow(a.groupNames)&&(a.switchN=!0,this.regexp_pattern(a))},H.regexp_pattern=function(a){a.pos=0,a.lastIntValue=0,a.lastStringValue="",a.lastAssertionIsQuantifiable=!1,a.numCapturingParens=0,a.maxBackReference=0,a.groupNames=Object.create(null),a.backReferenceNames.length=0,a.branchID=null,this.regexp_disjunction(a),a.pos!==a.source.length&&(a.eat(41)&&a.raise("Unmatched ')'"),(a.eat(93)||a.eat(125))&&a.raise("Lone quantifier brackets")),a.maxBackReference>a.numCapturingParens&&a.raise("Invalid escape");for(var l=0,y=a.backReferenceNames;l<y.length;l+=1){var w=y[l];a.groupNames[w]||a.raise("Invalid named capture referenced")}},H.regexp_disjunction=function(a){var l=this.options.ecmaVersion>=16;for(l&&(a.branchID=new po(a.branchID,null)),this.regexp_alternative(a);a.eat(124);)l&&(a.branchID=a.branchID.sibling()),this.regexp_alternative(a);l&&(a.branchID=a.branchID.parent),this.regexp_eatQuantifier(a,!0)&&a.raise("Nothing to repeat"),a.eat(123)&&a.raise("Lone quantifier brackets")},H.regexp_alternative=function(a){for(;a.pos<a.source.length&&this.regexp_eatTerm(a););},H.regexp_eatTerm=function(a){return this.regexp_eatAssertion(a)?(a.lastAssertionIsQuantifiable&&this.regexp_eatQuantifier(a)&&a.switchU&&a.raise("Invalid quantifier"),!0):(a.switchU?this.regexp_eatAtom(a):this.regexp_eatExtendedAtom(a))?(this.regexp_eatQuantifier(a),!0):!1},H.regexp_eatAssertion=function(a){var l=a.pos;if(a.lastAssertionIsQuantifiable=!1,a.eat(94)||a.eat(36))return!0;if(a.eat(92)){if(a.eat(66)||a.eat(98))return!0;a.pos=l}if(a.eat(40)&&a.eat(63)){var y=!1;if(this.options.ecmaVersion>=9&&(y=a.eat(60)),a.eat(61)||a.eat(33))return this.regexp_disjunction(a),a.eat(41)||a.raise("Unterminated group"),a.lastAssertionIsQuantifiable=!y,!0}return a.pos=l,!1},H.regexp_eatQuantifier=function(a,l){return l===void 0&&(l=!1),this.regexp_eatQuantifierPrefix(a,l)?(a.eat(63),!0):!1},H.regexp_eatQuantifierPrefix=function(a,l){return a.eat(42)||a.eat(43)||a.eat(63)||this.regexp_eatBracedQuantifier(a,l)},H.regexp_eatBracedQuantifier=function(a,l){var y=a.pos;if(a.eat(123)){var w=0,C=-1;if(this.regexp_eatDecimalDigits(a)&&(w=a.lastIntValue,a.eat(44)&&this.regexp_eatDecimalDigits(a)&&(C=a.lastIntValue),a.eat(125)))return C!==-1&&C<w&&!l&&a.raise("numbers out of order in {} quantifier"),!0;a.switchU&&!l&&a.raise("Incomplete quantifier"),a.pos=y}return!1},H.regexp_eatAtom=function(a){return this.regexp_eatPatternCharacters(a)||a.eat(46)||this.regexp_eatReverseSolidusAtomEscape(a)||this.regexp_eatCharacterClass(a)||this.regexp_eatUncapturingGroup(a)||this.regexp_eatCapturingGroup(a)},H.regexp_eatReverseSolidusAtomEscape=function(a){var l=a.pos;if(a.eat(92)){if(this.regexp_eatAtomEscape(a))return!0;a.pos=l}return!1},H.regexp_eatUncapturingGroup=function(a){var l=a.pos;if(a.eat(40)){if(a.eat(63)){if(this.options.ecmaVersion>=16){var y=this.regexp_eatModifiers(a),w=a.eat(45);if(y||w){for(var C=0;C<y.length;C++){var F=y.charAt(C);y.indexOf(F,C+1)>-1&&a.raise("Duplicate regular expression modifiers")}if(w){var L=this.regexp_eatModifiers(a);!y&&!L&&a.current()===58&&a.raise("Invalid regular expression modifiers");for(var $=0;$<L.length;$++){var Z=L.charAt($);(L.indexOf(Z,$+1)>-1||y.indexOf(Z)>-1)&&a.raise("Duplicate regular expression modifiers")}}}}if(a.eat(58)){if(this.regexp_disjunction(a),a.eat(41))return!0;a.raise("Unterminated group")}}a.pos=l}return!1},H.regexp_eatCapturingGroup=function(a){if(a.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(a):a.current()===63&&a.raise("Invalid group"),this.regexp_disjunction(a),a.eat(41))return a.numCapturingParens+=1,!0;a.raise("Unterminated group")}return!1},H.regexp_eatModifiers=function(a){for(var l="",y=0;(y=a.current())!==-1&&Fw(y);)l+=Ce(y),a.advance();return l};function Fw(a){return a===105||a===109||a===115}H.regexp_eatExtendedAtom=function(a){return a.eat(46)||this.regexp_eatReverseSolidusAtomEscape(a)||this.regexp_eatCharacterClass(a)||this.regexp_eatUncapturingGroup(a)||this.regexp_eatCapturingGroup(a)||this.regexp_eatInvalidBracedQuantifier(a)||this.regexp_eatExtendedPatternCharacter(a)},H.regexp_eatInvalidBracedQuantifier=function(a){return this.regexp_eatBracedQuantifier(a,!0)&&a.raise("Nothing to repeat"),!1},H.regexp_eatSyntaxCharacter=function(a){var l=a.current();return xp(l)?(a.lastIntValue=l,a.advance(),!0):!1};function xp(a){return a===36||a>=40&&a<=43||a===46||a===63||a>=91&&a<=94||a>=123&&a<=125}H.regexp_eatPatternCharacters=function(a){for(var l=a.pos,y=0;(y=a.current())!==-1&&!xp(y);)a.advance();return a.pos!==l},H.regexp_eatExtendedPatternCharacter=function(a){var l=a.current();return l!==-1&&l!==36&&!(l>=40&&l<=43)&&l!==46&&l!==63&&l!==91&&l!==94&&l!==124?(a.advance(),!0):!1},H.regexp_groupSpecifier=function(a){if(a.eat(63)){this.regexp_eatGroupName(a)||a.raise("Invalid group");var l=this.options.ecmaVersion>=16,y=a.groupNames[a.lastStringValue];if(y)if(l)for(var w=0,C=y;w<C.length;w+=1){var F=C[w];F.separatedFrom(a.branchID)||a.raise("Duplicate capture group name")}else a.raise("Duplicate capture group name");l?(y||(a.groupNames[a.lastStringValue]=[])).push(a.branchID):a.groupNames[a.lastStringValue]=!0}},H.regexp_eatGroupName=function(a){if(a.lastStringValue="",a.eat(60)){if(this.regexp_eatRegExpIdentifierName(a)&&a.eat(62))return!0;a.raise("Invalid capture group name")}return!1},H.regexp_eatRegExpIdentifierName=function(a){if(a.lastStringValue="",this.regexp_eatRegExpIdentifierStart(a)){for(a.lastStringValue+=Ce(a.lastIntValue);this.regexp_eatRegExpIdentifierPart(a);)a.lastStringValue+=Ce(a.lastIntValue);return!0}return!1},H.regexp_eatRegExpIdentifierStart=function(a){var l=a.pos,y=this.options.ecmaVersion>=11,w=a.current(y);return a.advance(y),w===92&&this.regexp_eatRegExpUnicodeEscapeSequence(a,y)&&(w=a.lastIntValue),Lw(w)?(a.lastIntValue=w,!0):(a.pos=l,!1)};function Lw(a){return m(a,!0)||a===36||a===95}H.regexp_eatRegExpIdentifierPart=function(a){var l=a.pos,y=this.options.ecmaVersion>=11,w=a.current(y);return a.advance(y),w===92&&this.regexp_eatRegExpUnicodeEscapeSequence(a,y)&&(w=a.lastIntValue),zw(w)?(a.lastIntValue=w,!0):(a.pos=l,!1)};function zw(a){return d(a,!0)||a===36||a===95||a===8204||a===8205}H.regexp_eatAtomEscape=function(a){return this.regexp_eatBackReference(a)||this.regexp_eatCharacterClassEscape(a)||this.regexp_eatCharacterEscape(a)||a.switchN&&this.regexp_eatKGroupName(a)?!0:(a.switchU&&(a.current()===99&&a.raise("Invalid unicode escape"),a.raise("Invalid escape")),!1)},H.regexp_eatBackReference=function(a){var l=a.pos;if(this.regexp_eatDecimalEscape(a)){var y=a.lastIntValue;if(a.switchU)return y>a.maxBackReference&&(a.maxBackReference=y),!0;if(y<=a.numCapturingParens)return!0;a.pos=l}return!1},H.regexp_eatKGroupName=function(a){if(a.eat(107)){if(this.regexp_eatGroupName(a))return a.backReferenceNames.push(a.lastStringValue),!0;a.raise("Invalid named reference")}return!1},H.regexp_eatCharacterEscape=function(a){return this.regexp_eatControlEscape(a)||this.regexp_eatCControlLetter(a)||this.regexp_eatZero(a)||this.regexp_eatHexEscapeSequence(a)||this.regexp_eatRegExpUnicodeEscapeSequence(a,!1)||!a.switchU&&this.regexp_eatLegacyOctalEscapeSequence(a)||this.regexp_eatIdentityEscape(a)},H.regexp_eatCControlLetter=function(a){var l=a.pos;if(a.eat(99)){if(this.regexp_eatControlLetter(a))return!0;a.pos=l}return!1},H.regexp_eatZero=function(a){return a.current()===48&&!ho(a.lookahead())?(a.lastIntValue=0,a.advance(),!0):!1},H.regexp_eatControlEscape=function(a){var l=a.current();return l===116?(a.lastIntValue=9,a.advance(),!0):l===110?(a.lastIntValue=10,a.advance(),!0):l===118?(a.lastIntValue=11,a.advance(),!0):l===102?(a.lastIntValue=12,a.advance(),!0):l===114?(a.lastIntValue=13,a.advance(),!0):!1},H.regexp_eatControlLetter=function(a){var l=a.current();return bp(l)?(a.lastIntValue=l%32,a.advance(),!0):!1};function bp(a){return a>=65&&a<=90||a>=97&&a<=122}H.regexp_eatRegExpUnicodeEscapeSequence=function(a,l){l===void 0&&(l=!1);var y=a.pos,w=l||a.switchU;if(a.eat(117)){if(this.regexp_eatFixedHexDigits(a,4)){var C=a.lastIntValue;if(w&&C>=55296&&C<=56319){var F=a.pos;if(a.eat(92)&&a.eat(117)&&this.regexp_eatFixedHexDigits(a,4)){var L=a.lastIntValue;if(L>=56320&&L<=57343)return a.lastIntValue=(C-55296)*1024+(L-56320)+65536,!0}a.pos=F,a.lastIntValue=C}return!0}if(w&&a.eat(123)&&this.regexp_eatHexDigits(a)&&a.eat(125)&&Bw(a.lastIntValue))return!0;w&&a.raise("Invalid unicode escape"),a.pos=y}return!1};function Bw(a){return a>=0&&a<=1114111}H.regexp_eatIdentityEscape=function(a){if(a.switchU)return this.regexp_eatSyntaxCharacter(a)?!0:a.eat(47)?(a.lastIntValue=47,!0):!1;var l=a.current();return l!==99&&(!a.switchN||l!==107)?(a.lastIntValue=l,a.advance(),!0):!1},H.regexp_eatDecimalEscape=function(a){a.lastIntValue=0;var l=a.current();if(l>=49&&l<=57){do a.lastIntValue=10*a.lastIntValue+(l-48),a.advance();while((l=a.current())>=48&&l<=57);return!0}return!1};var wp=0,$r=1,Lt=2;H.regexp_eatCharacterClassEscape=function(a){var l=a.current();if(Mw(l))return a.lastIntValue=-1,a.advance(),$r;var y=!1;if(a.switchU&&this.options.ecmaVersion>=9&&((y=l===80)||l===112)){a.lastIntValue=-1,a.advance();var w;if(a.eat(123)&&(w=this.regexp_eatUnicodePropertyValueExpression(a))&&a.eat(125))return y&&w===Lt&&a.raise("Invalid property name"),w;a.raise("Invalid property name")}return wp};function Mw(a){return a===100||a===68||a===115||a===83||a===119||a===87}H.regexp_eatUnicodePropertyValueExpression=function(a){var l=a.pos;if(this.regexp_eatUnicodePropertyName(a)&&a.eat(61)){var y=a.lastStringValue;if(this.regexp_eatUnicodePropertyValue(a)){var w=a.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(a,y,w),$r}}if(a.pos=l,this.regexp_eatLoneUnicodePropertyNameOrValue(a)){var C=a.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(a,C)}return wp},H.regexp_validateUnicodePropertyNameAndValue=function(a,l,y){ee(a.unicodeProperties.nonBinary,l)||a.raise("Invalid property name"),a.unicodeProperties.nonBinary[l].test(y)||a.raise("Invalid property value")},H.regexp_validateUnicodePropertyNameOrValue=function(a,l){if(a.unicodeProperties.binary.test(l))return $r;if(a.switchV&&a.unicodeProperties.binaryOfStrings.test(l))return Lt;a.raise("Invalid property name")},H.regexp_eatUnicodePropertyName=function(a){var l=0;for(a.lastStringValue="";vp(l=a.current());)a.lastStringValue+=Ce(l),a.advance();return a.lastStringValue!==""};function vp(a){return bp(a)||a===95}H.regexp_eatUnicodePropertyValue=function(a){var l=0;for(a.lastStringValue="";Vw(l=a.current());)a.lastStringValue+=Ce(l),a.advance();return a.lastStringValue!==""};function Vw(a){return vp(a)||ho(a)}H.regexp_eatLoneUnicodePropertyNameOrValue=function(a){return this.regexp_eatUnicodePropertyValue(a)},H.regexp_eatCharacterClass=function(a){if(a.eat(91)){var l=a.eat(94),y=this.regexp_classContents(a);return a.eat(93)||a.raise("Unterminated character class"),l&&y===Lt&&a.raise("Negated character class may contain strings"),!0}return!1},H.regexp_classContents=function(a){return a.current()===93?$r:a.switchV?this.regexp_classSetExpression(a):(this.regexp_nonEmptyClassRanges(a),$r)},H.regexp_nonEmptyClassRanges=function(a){for(;this.regexp_eatClassAtom(a);){var l=a.lastIntValue;if(a.eat(45)&&this.regexp_eatClassAtom(a)){var y=a.lastIntValue;a.switchU&&(l===-1||y===-1)&&a.raise("Invalid character class"),l!==-1&&y!==-1&&l>y&&a.raise("Range out of order in character class")}}},H.regexp_eatClassAtom=function(a){var l=a.pos;if(a.eat(92)){if(this.regexp_eatClassEscape(a))return!0;if(a.switchU){var y=a.current();(y===99||Sp(y))&&a.raise("Invalid class escape"),a.raise("Invalid escape")}a.pos=l}var w=a.current();return w!==93?(a.lastIntValue=w,a.advance(),!0):!1},H.regexp_eatClassEscape=function(a){var l=a.pos;if(a.eat(98))return a.lastIntValue=8,!0;if(a.switchU&&a.eat(45))return a.lastIntValue=45,!0;if(!a.switchU&&a.eat(99)){if(this.regexp_eatClassControlLetter(a))return!0;a.pos=l}return this.regexp_eatCharacterClassEscape(a)||this.regexp_eatCharacterEscape(a)},H.regexp_classSetExpression=function(a){var l=$r,y;if(!this.regexp_eatClassSetRange(a))if(y=this.regexp_eatClassSetOperand(a)){y===Lt&&(l=Lt);for(var w=a.pos;a.eatChars([38,38]);){if(a.current()!==38&&(y=this.regexp_eatClassSetOperand(a))){y!==Lt&&(l=$r);continue}a.raise("Invalid character in character class")}if(w!==a.pos)return l;for(;a.eatChars([45,45]);)this.regexp_eatClassSetOperand(a)||a.raise("Invalid character in character class");if(w!==a.pos)return l}else a.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(a)){if(y=this.regexp_eatClassSetOperand(a),!y)return l;y===Lt&&(l=Lt)}},H.regexp_eatClassSetRange=function(a){var l=a.pos;if(this.regexp_eatClassSetCharacter(a)){var y=a.lastIntValue;if(a.eat(45)&&this.regexp_eatClassSetCharacter(a)){var w=a.lastIntValue;return y!==-1&&w!==-1&&y>w&&a.raise("Range out of order in character class"),!0}a.pos=l}return!1},H.regexp_eatClassSetOperand=function(a){return this.regexp_eatClassSetCharacter(a)?$r:this.regexp_eatClassStringDisjunction(a)||this.regexp_eatNestedClass(a)},H.regexp_eatNestedClass=function(a){var l=a.pos;if(a.eat(91)){var y=a.eat(94),w=this.regexp_classContents(a);if(a.eat(93))return y&&w===Lt&&a.raise("Negated character class may contain strings"),w;a.pos=l}if(a.eat(92)){var C=this.regexp_eatCharacterClassEscape(a);if(C)return C;a.pos=l}return null},H.regexp_eatClassStringDisjunction=function(a){var l=a.pos;if(a.eatChars([92,113])){if(a.eat(123)){var y=this.regexp_classStringDisjunctionContents(a);if(a.eat(125))return y}else a.raise("Invalid escape");a.pos=l}return null},H.regexp_classStringDisjunctionContents=function(a){for(var l=this.regexp_classString(a);a.eat(124);)this.regexp_classString(a)===Lt&&(l=Lt);return l},H.regexp_classString=function(a){for(var l=0;this.regexp_eatClassSetCharacter(a);)l++;return l===1?$r:Lt},H.regexp_eatClassSetCharacter=function(a){var l=a.pos;if(a.eat(92))return this.regexp_eatCharacterEscape(a)||this.regexp_eatClassSetReservedPunctuator(a)?!0:a.eat(98)?(a.lastIntValue=8,!0):(a.pos=l,!1);var y=a.current();return y<0||y===a.lookahead()&&$w(y)||jw(y)?!1:(a.advance(),a.lastIntValue=y,!0)};function $w(a){return a===33||a>=35&&a<=38||a>=42&&a<=44||a===46||a>=58&&a<=64||a===94||a===96||a===126}function jw(a){return a===40||a===41||a===45||a===47||a>=91&&a<=93||a>=123&&a<=125}H.regexp_eatClassSetReservedPunctuator=function(a){var l=a.current();return Uw(l)?(a.lastIntValue=l,a.advance(),!0):!1};function Uw(a){return a===33||a===35||a===37||a===38||a===44||a===45||a>=58&&a<=62||a===64||a===96||a===126}H.regexp_eatClassControlLetter=function(a){var l=a.current();return ho(l)||l===95?(a.lastIntValue=l%32,a.advance(),!0):!1},H.regexp_eatHexEscapeSequence=function(a){var l=a.pos;if(a.eat(120)){if(this.regexp_eatFixedHexDigits(a,2))return!0;a.switchU&&a.raise("Invalid escape"),a.pos=l}return!1},H.regexp_eatDecimalDigits=function(a){var l=a.pos,y=0;for(a.lastIntValue=0;ho(y=a.current());)a.lastIntValue=10*a.lastIntValue+(y-48),a.advance();return a.pos!==l};function ho(a){return a>=48&&a<=57}H.regexp_eatHexDigits=function(a){var l=a.pos,y=0;for(a.lastIntValue=0;kp(y=a.current());)a.lastIntValue=16*a.lastIntValue+Ap(y),a.advance();return a.pos!==l};function kp(a){return a>=48&&a<=57||a>=65&&a<=70||a>=97&&a<=102}function Ap(a){return a>=65&&a<=70?10+(a-65):a>=97&&a<=102?10+(a-97):a-48}H.regexp_eatLegacyOctalEscapeSequence=function(a){if(this.regexp_eatOctalDigit(a)){var l=a.lastIntValue;if(this.regexp_eatOctalDigit(a)){var y=a.lastIntValue;l<=3&&this.regexp_eatOctalDigit(a)?a.lastIntValue=l*64+y*8+a.lastIntValue:a.lastIntValue=l*8+y}else a.lastIntValue=l;return!0}return!1},H.regexp_eatOctalDigit=function(a){var l=a.current();return Sp(l)?(a.lastIntValue=l-48,a.advance(),!0):(a.lastIntValue=0,!1)};function Sp(a){return a>=48&&a<=55}H.regexp_eatFixedHexDigits=function(a,l){var y=a.pos;a.lastIntValue=0;for(var w=0;w<l;++w){var C=a.current();if(!kp(C))return a.pos=y,!1;a.lastIntValue=16*a.lastIntValue+Ap(C),a.advance()}return!0};var mo=function(l){this.type=l.type,this.value=l.value,this.start=l.start,this.end=l.end,l.options.locations&&(this.loc=new Ge(l,l.startLoc,l.endLoc)),l.options.ranges&&(this.range=[l.start,l.end])},he=Te.prototype;he.next=function(a){!a&&this.type.keyword&&this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword "+this.type.keyword),this.options.onToken&&this.options.onToken(new mo(this)),this.lastTokEnd=this.end,this.lastTokStart=this.start,this.lastTokEndLoc=this.endLoc,this.lastTokStartLoc=this.startLoc,this.nextToken()},he.getToken=function(){return this.next(),new mo(this)},typeof Symbol<"u"&&(he[Symbol.iterator]=function(){var a=this;return{next:function(){var l=a.getToken();return{done:l.type===g.eof,value:l}}}}),he.nextToken=function(){var a=this.curContext();if((!a||!a.preserveSpace)&&this.skipSpace(),this.start=this.pos,this.options.locations&&(this.startLoc=this.curPosition()),this.pos>=this.input.length)return this.finishToken(g.eof);if(a.override)return a.override(this);this.readToken(this.fullCharCodeAtPos())},he.readToken=function(a){return m(a,this.options.ecmaVersion>=6)||a===92?this.readWord():this.getTokenFromCode(a)},he.fullCharCodeAt=function(a){var l=this.input.charCodeAt(a);if(l<=55295||l>=56320)return l;var y=this.input.charCodeAt(a+1);return y<=56319||y>=57344?l:(l<<10)+y-56613888},he.fullCharCodeAtPos=function(){return this.fullCharCodeAt(this.pos)},he.skipBlockComment=function(){var a=this.options.onComment&&this.curPosition(),l=this.pos,y=this.input.indexOf("*/",this.pos+=2);if(y===-1&&this.raise(this.pos-2,"Unterminated comment"),this.pos=y+2,this.options.locations)for(var w=void 0,C=l;(w=O(this.input,C,this.pos))>-1;)++this.curLine,C=this.lineStart=w;this.options.onComment&&this.options.onComment(!0,this.input.slice(l+2,y),l,this.pos,a,this.curPosition())},he.skipLineComment=function(a){for(var l=this.pos,y=this.options.onComment&&this.curPosition(),w=this.input.charCodeAt(this.pos+=a);this.pos<this.input.length&&!D(w);)w=this.input.charCodeAt(++this.pos);this.options.onComment&&this.options.onComment(!1,this.input.slice(l+a,this.pos),l,this.pos,y,this.curPosition())},he.skipSpace=function(){e:for(;this.pos<this.input.length;){var a=this.input.charCodeAt(this.pos);switch(a){case 32:case 160:++this.pos;break;case 13:this.input.charCodeAt(this.pos+1)===10&&++this.pos;case 10:case 8232:case 8233:++this.pos,this.options.locations&&(++this.curLine,this.lineStart=this.pos);break;case 47:switch(this.input.charCodeAt(this.pos+1)){case 42:this.skipBlockComment();break;case 47:this.skipLineComment(2);break;default:break e}break;default:if(a>8&&a<14||a>=5760&&M.test(String.fromCharCode(a)))++this.pos;else break e}}},he.finishToken=function(a,l){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var y=this.type;this.type=a,this.value=l,this.updateContext(y)},he.readToken_dot=function(){var a=this.input.charCodeAt(this.pos+1);if(a>=48&&a<=57)return this.readNumber(!0);var l=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&a===46&&l===46?(this.pos+=3,this.finishToken(g.ellipsis)):(++this.pos,this.finishToken(g.dot))},he.readToken_slash=function(){var a=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):a===61?this.finishOp(g.assign,2):this.finishOp(g.slash,1)},he.readToken_mult_modulo_exp=function(a){var l=this.input.charCodeAt(this.pos+1),y=1,w=a===42?g.star:g.modulo;return this.options.ecmaVersion>=7&&a===42&&l===42&&(++y,w=g.starstar,l=this.input.charCodeAt(this.pos+2)),l===61?this.finishOp(g.assign,y+1):this.finishOp(w,y)},he.readToken_pipe_amp=function(a){var l=this.input.charCodeAt(this.pos+1);if(l===a){if(this.options.ecmaVersion>=12){var y=this.input.charCodeAt(this.pos+2);if(y===61)return this.finishOp(g.assign,3)}return this.finishOp(a===124?g.logicalOR:g.logicalAND,2)}return l===61?this.finishOp(g.assign,2):this.finishOp(a===124?g.bitwiseOR:g.bitwiseAND,1)},he.readToken_caret=function(){var a=this.input.charCodeAt(this.pos+1);return a===61?this.finishOp(g.assign,2):this.finishOp(g.bitwiseXOR,1)},he.readToken_plus_min=function(a){var l=this.input.charCodeAt(this.pos+1);return l===a?l===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||I.test(this.input.slice(this.lastTokEnd,this.pos)))?(this.skipLineComment(3),this.skipSpace(),this.nextToken()):this.finishOp(g.incDec,2):l===61?this.finishOp(g.assign,2):this.finishOp(g.plusMin,1)},he.readToken_lt_gt=function(a){var l=this.input.charCodeAt(this.pos+1),y=1;return l===a?(y=a===62&&this.input.charCodeAt(this.pos+2)===62?3:2,this.input.charCodeAt(this.pos+y)===61?this.finishOp(g.assign,y+1):this.finishOp(g.bitShift,y)):l===33&&a===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45?(this.skipLineComment(4),this.skipSpace(),this.nextToken()):(l===61&&(y=2),this.finishOp(g.relational,y))},he.readToken_eq_excl=function(a){var l=this.input.charCodeAt(this.pos+1);return l===61?this.finishOp(g.equality,this.input.charCodeAt(this.pos+2)===61?3:2):a===61&&l===62&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(g.arrow)):this.finishOp(a===61?g.eq:g.prefix,1)},he.readToken_question=function(){var a=this.options.ecmaVersion;if(a>=11){var l=this.input.charCodeAt(this.pos+1);if(l===46){var y=this.input.charCodeAt(this.pos+2);if(y<48||y>57)return this.finishOp(g.questionDot,2)}if(l===63){if(a>=12){var w=this.input.charCodeAt(this.pos+2);if(w===61)return this.finishOp(g.assign,3)}return this.finishOp(g.coalesce,2)}}return this.finishOp(g.question,1)},he.readToken_numberSign=function(){var a=this.options.ecmaVersion,l=35;if(a>=13&&(++this.pos,l=this.fullCharCodeAtPos(),m(l,!0)||l===92))return this.finishToken(g.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+Ce(l)+"'")},he.getTokenFromCode=function(a){switch(a){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(g.parenL);case 41:return++this.pos,this.finishToken(g.parenR);case 59:return++this.pos,this.finishToken(g.semi);case 44:return++this.pos,this.finishToken(g.comma);case 91:return++this.pos,this.finishToken(g.bracketL);case 93:return++this.pos,this.finishToken(g.bracketR);case 123:return++this.pos,this.finishToken(g.braceL);case 125:return++this.pos,this.finishToken(g.braceR);case 58:return++this.pos,this.finishToken(g.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(g.backQuote);case 48:var l=this.input.charCodeAt(this.pos+1);if(l===120||l===88)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(l===111||l===79)return this.readRadixNumber(8);if(l===98||l===66)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(a);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(a);case 124:case 38:return this.readToken_pipe_amp(a);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(a);case 60:case 62:return this.readToken_lt_gt(a);case 61:case 33:return this.readToken_eq_excl(a);case 63:return this.readToken_question();case 126:return this.finishOp(g.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+Ce(a)+"'")},he.finishOp=function(a,l){var y=this.input.slice(this.pos,this.pos+l);return this.pos+=l,this.finishToken(a,y)},he.readRegexp=function(){for(var a,l,y=this.pos;;){this.pos>=this.input.length&&this.raise(y,"Unterminated regular expression");var w=this.input.charAt(this.pos);if(I.test(w)&&this.raise(y,"Unterminated regular expression"),a)a=!1;else{if(w==="[")l=!0;else if(w==="]"&&l)l=!1;else if(w==="/"&&!l)break;a=w==="\\"}++this.pos}var C=this.input.slice(y,this.pos);++this.pos;var F=this.pos,L=this.readWord1();this.containsEsc&&this.unexpected(F);var $=this.regexpState||(this.regexpState=new vr(this));$.reset(y,C,L),this.validateRegExpFlags($),this.validateRegExpPattern($);var Z=null;try{Z=new RegExp(C,L)}catch{}return this.finishToken(g.regexp,{pattern:C,flags:L,value:Z})},he.readInt=function(a,l,y){for(var w=this.options.ecmaVersion>=12&&l===void 0,C=y&&this.input.charCodeAt(this.pos)===48,F=this.pos,L=0,$=0,Z=0,oe=l??1/0;Z<oe;++Z,++this.pos){var fe=this.input.charCodeAt(this.pos),Pe=void 0;if(w&&fe===95){C&&this.raiseRecoverable(this.pos,"Numeric separator is not allowed in legacy octal numeric literals"),$===95&&this.raiseRecoverable(this.pos,"Numeric separator must be exactly one underscore"),Z===0&&this.raiseRecoverable(this.pos,"Numeric separator is not allowed at the first of digits"),$=fe;continue}if(fe>=97?Pe=fe-97+10:fe>=65?Pe=fe-65+10:fe>=48&&fe<=57?Pe=fe-48:Pe=1/0,Pe>=a)break;$=fe,L=L*a+Pe}return w&&$===95&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===F||l!=null&&this.pos-F!==l?null:L};function qw(a,l){return l?parseInt(a,8):parseFloat(a.replace(/_/g,""))}function Ep(a){return typeof BigInt!="function"?null:BigInt(a.replace(/_/g,""))}he.readRadixNumber=function(a){var l=this.pos;this.pos+=2;var y=this.readInt(a);return y==null&&this.raise(this.start+2,"Expected number in radix "+a),this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110?(y=Ep(this.input.slice(l,this.pos)),++this.pos):m(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(g.num,y)},he.readNumber=function(a){var l=this.pos;!a&&this.readInt(10,void 0,!0)===null&&this.raise(l,"Invalid number");var y=this.pos-l>=2&&this.input.charCodeAt(l)===48;y&&this.strict&&this.raise(l,"Invalid number");var w=this.input.charCodeAt(this.pos);if(!y&&!a&&this.options.ecmaVersion>=11&&w===110){var C=Ep(this.input.slice(l,this.pos));return++this.pos,m(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(g.num,C)}y&&/[89]/.test(this.input.slice(l,this.pos))&&(y=!1),w===46&&!y&&(++this.pos,this.readInt(10),w=this.input.charCodeAt(this.pos)),(w===69||w===101)&&!y&&(w=this.input.charCodeAt(++this.pos),(w===43||w===45)&&++this.pos,this.readInt(10)===null&&this.raise(l,"Invalid number")),m(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var F=qw(this.input.slice(l,this.pos),y);return this.finishToken(g.num,F)},he.readCodePoint=function(){var a=this.input.charCodeAt(this.pos),l;if(a===123){this.options.ecmaVersion<6&&this.unexpected();var y=++this.pos;l=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,l>1114111&&this.invalidStringToken(y,"Code point out of bounds")}else l=this.readHexChar(4);return l},he.readString=function(a){for(var l="",y=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var w=this.input.charCodeAt(this.pos);if(w===a)break;w===92?(l+=this.input.slice(y,this.pos),l+=this.readEscapedChar(!1),y=this.pos):w===8232||w===8233?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(D(w)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return l+=this.input.slice(y,this.pos++),this.finishToken(g.string,l)};var _p={};he.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(a){if(a===_p)this.readInvalidTemplateToken();else throw a}this.inTemplateElement=!1},he.invalidStringToken=function(a,l){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw _p;this.raise(a,l)},he.readTmplToken=function(){for(var a="",l=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var y=this.input.charCodeAt(this.pos);if(y===96||y===36&&this.input.charCodeAt(this.pos+1)===123)return this.pos===this.start&&(this.type===g.template||this.type===g.invalidTemplate)?y===36?(this.pos+=2,this.finishToken(g.dollarBraceL)):(++this.pos,this.finishToken(g.backQuote)):(a+=this.input.slice(l,this.pos),this.finishToken(g.template,a));if(y===92)a+=this.input.slice(l,this.pos),a+=this.readEscapedChar(!0),l=this.pos;else if(D(y)){switch(a+=this.input.slice(l,this.pos),++this.pos,y){case 13:this.input.charCodeAt(this.pos)===10&&++this.pos;case 10:a+=`+`;break;default:a+=String.fromCharCode(y);break}this.options.locations&&(++this.curLine,this.lineStart=this.pos),l=this.pos}else++this.pos}},he.readInvalidTemplateToken=function(){for(;this.pos<this.input.length;this.pos++)switch(this.input[this.pos]){case"\\":++this.pos;break;case"$":if(this.input[this.pos+1]!=="{")break;case"`":return this.finishToken(g.invalidTemplate,this.input.slice(this.start,this.pos));case"\r":this.input[this.pos+1]===`+`&&++this.pos;case`+`:case"\u2028":case"\u2029":++this.curLine,this.lineStart=this.pos+1;break}this.raise(this.start,"Unterminated template")},he.readEscapedChar=function(a){var l=this.input.charCodeAt(++this.pos);switch(++this.pos,l){case 110:return`+`;case 114:return"\r";case 120:return String.fromCharCode(this.readHexChar(2));case 117:return Ce(this.readCodePoint());case 116:return" ";case 98:return"\b";case 118:return"\v";case 102:return"\f";case 13:this.input.charCodeAt(this.pos)===10&&++this.pos;case 10:return this.options.locations&&(this.lineStart=this.pos,++this.curLine),"";case 56:case 57:if(this.strict&&this.invalidStringToken(this.pos-1,"Invalid escape sequence"),a){var y=this.pos-1;this.invalidStringToken(y,"Invalid escape sequence in template string")}default:if(l>=48&&l<=55){var w=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],C=parseInt(w,8);return C>255&&(w=w.slice(0,-1),C=parseInt(w,8)),this.pos+=w.length-1,l=this.input.charCodeAt(this.pos),(w!=="0"||l===56||l===57)&&(this.strict||a)&&this.invalidStringToken(this.pos-1-w.length,a?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(C)}return D(l)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(l)}},he.readHexChar=function(a){var l=this.pos,y=this.readInt(16,a);return y===null&&this.invalidStringToken(l,"Bad character escape sequence"),y},he.readWord1=function(){this.containsEsc=!1;for(var a="",l=!0,y=this.pos,w=this.options.ecmaVersion>=6;this.pos<this.input.length;){var C=this.fullCharCodeAtPos();if(d(C,w))this.pos+=C<=65535?1:2;else if(C===92){this.containsEsc=!0,a+=this.input.slice(y,this.pos);var F=this.pos;this.input.charCodeAt(++this.pos)!==117&&this.invalidStringToken(this.pos,"Expecting Unicode escape sequence \\uXXXX"),++this.pos;var L=this.readCodePoint();(l?m:d)(L,w)||this.invalidStringToken(F,"Invalid Unicode escape"),a+=Ce(L),y=this.pos}else break;l=!1}return a+this.input.slice(y,this.pos)},he.readWord=function(){var a=this.readWord1(),l=g.name;return this.keywords.test(a)&&(l=T[a]),this.finishToken(l,a)};var Cp="8.17.0";Te.acorn={Parser:Te,version:Cp,defaultOptions:N,Position:R,SourceLocation:Ge,getLineInfo:ut,Node:es,TokenType:x,tokTypes:g,keywordTypes:T,TokContext:Ft,tokContexts:Ne,isIdentifierChar:d,isIdentifierStart:m,Token:mo,isNewLine:D,lineBreak:I,lineBreakG:_,nonASCIIwhitespace:M};function Zw(a,l){return Te.parse(a,l)}function Jw(a,l,y){return Te.parseExpressionAt(a,l,y)}function Gw(a,l){return Te.tokenizer(a,l)}e.Node=es,e.Parser=Te,e.Position=R,e.SourceLocation=Ge,e.TokContext=Ft,e.Token=mo,e.TokenType=x,e.defaultOptions=N,e.getLineInfo=ut,e.isIdentifierChar=d,e.isIdentifierStart=m,e.isNewLine=D,e.keywordTypes=T,e.lineBreak=I,e.lineBreakG=_,e.nonASCIIwhitespace=M,e.parse=Zw,e.parseExpressionAt=Jw,e.tokContexts=Ne,e.tokTypes=g,e.tokenizer=Gw,e.version=Cp})});var ab=ri((h8,mf)=>{"use strict";var _C=nb(),CC=/^[\da-fA-F]+$/,DC=/^\d+$/,sb=new WeakMap;function ob(e){e=e.Parser.acorn||e;let t=sb.get(e);if(!t){let r=e.tokTypes,n=e.TokContext,i=e.TokenType,s=new n("<tag",!1),o=new n("</tag",!1),u=new n("<tag>...</tag>",!0,!0),c={tc_oTag:s,tc_cTag:o,tc_expr:u},f={jsxName:new i("jsxName"),jsxText:new i("jsxText",{beforeExpr:!0}),jsxTagStart:new i("jsxTagStart",{startsExpr:!0}),jsxTagEnd:new i("jsxTagEnd")};f.jsxTagStart.updateContext=function(){this.context.push(u),this.context.push(s),this.exprAllowed=!1},f.jsxTagEnd.updateContext=function(h){let p=this.context.pop();p===s&&h===r.slash||p===o?(this.context.pop(),this.exprAllowed=this.curContext()===u):this.exprAllowed=!0},t={tokContexts:c,tokTypes:f},sb.set(e,t)}return t}function to(e){if(!e)return e;if(e.type==="JSXIdentifier")return e.name;if(e.type==="JSXNamespacedName")return e.namespace.name+":"+e.name.name;if(e.type==="JSXMemberExpression")return to(e.object)+"."+to(e.property)}mf.exports=function(e){return e=e||{},function(t){return IC({allowNamespaces:e.allowNamespaces!==!1,allowNamespacedObjects:!!e.allowNamespacedObjects},t)}};Object.defineProperty(mf.exports,"tokTypes",{get:function(){return ob(df()).tokTypes},configurable:!0,enumerable:!0});function IC(e,t){let r=t.acorn||df(),n=ob(r),i=r.tokTypes,s=n.tokTypes,o=r.tokContexts,u=n.tokContexts.tc_oTag,c=n.tokContexts.tc_cTag,f=n.tokContexts.tc_expr,h=r.isNewLine,p=r.isIdentifierStart,m=r.isIdentifierChar;return class extends t{static get acornJsx(){return n}jsx_readToken(){let d="",x=this.pos;for(;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated JSX contents");let b=this.input.charCodeAt(this.pos);switch(b){case 60:case 123:return this.pos===this.start?b===60&&this.exprAllowed?(++this.pos,this.finishToken(s.jsxTagStart)):this.getTokenFromCode(b):(d+=this.input.slice(x,this.pos),this.finishToken(s.jsxText,d));case 38:d+=this.input.slice(x,this.pos),d+=this.jsx_readEntity(),x=this.pos;break;case 62:case 125:this.raise(this.pos,"Unexpected token `"+this.input[this.pos]+"`. Did you mean `"+(b===62?">":"}")+'` or `{"'+this.input[this.pos]+'"}`?');default:h(b)?(d+=this.input.slice(x,this.pos),d+=this.jsx_readNewLine(!0),x=this.pos):++this.pos}}}jsx_readNewLine(d){let x=this.input.charCodeAt(this.pos),b;return++this.pos,x===13&&this.input.charCodeAt(this.pos)===10?(++this.pos,b=d?`+`:`\r+`):b=String.fromCharCode(x),this.options.locations&&(++this.curLine,this.lineStart=this.pos),b}jsx_readString(d){let x="",b=++this.pos;for(;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");let v=this.input.charCodeAt(this.pos);if(v===d)break;v===38?(x+=this.input.slice(b,this.pos),x+=this.jsx_readEntity(),b=this.pos):h(v)?(x+=this.input.slice(b,this.pos),x+=this.jsx_readNewLine(!1),b=this.pos):++this.pos}return x+=this.input.slice(b,this.pos++),this.finishToken(i.string,x)}jsx_readEntity(){let d="",x=0,b,v=this.input[this.pos];v!=="&"&&this.raise(this.pos,"Entity must start with an ampersand");let k=++this.pos;for(;this.pos<this.input.length&&x++<10;){if(v=this.input[this.pos++],v===";"){d[0]==="#"?d[1]==="x"?(d=d.substr(2),CC.test(d)&&(b=String.fromCharCode(parseInt(d,16)))):(d=d.substr(1),DC.test(d)&&(b=String.fromCharCode(parseInt(d,10)))):b=_C[d];break}d+=v}return b||(this.pos=k,"&")}jsx_readWord(){let d,x=this.pos;do d=this.input.charCodeAt(++this.pos);while(m(d)||d===45);return this.finishToken(s.jsxName,this.input.slice(x,this.pos))}jsx_parseIdentifier(){let d=this.startNode();return this.type===s.jsxName?d.name=this.value:this.type.keyword?d.name=this.type.keyword:this.unexpected(),this.next(),this.finishNode(d,"JSXIdentifier")}jsx_parseNamespacedName(){let d=this.start,x=this.startLoc,b=this.jsx_parseIdentifier();if(!e.allowNamespaces||!this.eat(i.colon))return b;var v=this.startNodeAt(d,x);return v.namespace=b,v.name=this.jsx_parseIdentifier(),this.finishNode(v,"JSXNamespacedName")}jsx_parseElementName(){if(this.type===s.jsxTagEnd)return"";let d=this.start,x=this.startLoc,b=this.jsx_parseNamespacedName();for(this.type===i.dot&&b.type==="JSXNamespacedName"&&!e.allowNamespacedObjects&&this.unexpected();this.eat(i.dot);){let v=this.startNodeAt(d,x);v.object=b,v.property=this.jsx_parseIdentifier(),b=this.finishNode(v,"JSXMemberExpression")}return b}jsx_parseAttributeValue(){switch(this.type){case i.braceL:let d=this.jsx_parseExpressionContainer();return d.expression.type==="JSXEmptyExpression"&&this.raise(d.start,"JSX attributes must only be assigned a non-empty expression"),d;case s.jsxTagStart:case i.string:return this.parseExprAtom();default:this.raise(this.start,"JSX value should be either an expression or a quoted JSX text")}}jsx_parseEmptyExpression(){let d=this.startNodeAt(this.lastTokEnd,this.lastTokEndLoc);return this.finishNodeAt(d,"JSXEmptyExpression",this.start,this.startLoc)}jsx_parseExpressionContainer(){let d=this.startNode();return this.next(),d.expression=this.type===i.braceR?this.jsx_parseEmptyExpression():this.parseExpression(),this.expect(i.braceR),this.finishNode(d,"JSXExpressionContainer")}jsx_parseAttribute(){let d=this.startNode();return this.eat(i.braceL)?(this.expect(i.ellipsis),d.argument=this.parseMaybeAssign(),this.expect(i.braceR),this.finishNode(d,"JSXSpreadAttribute")):(d.name=this.jsx_parseNamespacedName(),d.value=this.eat(i.eq)?this.jsx_parseAttributeValue():null,this.finishNode(d,"JSXAttribute"))}jsx_parseOpeningElementAt(d,x){let b=this.startNodeAt(d,x);b.attributes=[];let v=this.jsx_parseElementName();for(v&&(b.name=v);this.type!==i.slash&&this.type!==s.jsxTagEnd;)b.attributes.push(this.jsx_parseAttribute());return b.selfClosing=this.eat(i.slash),this.expect(s.jsxTagEnd),this.finishNode(b,v?"JSXOpeningElement":"JSXOpeningFragment")}jsx_parseClosingElementAt(d,x){let b=this.startNodeAt(d,x),v=this.jsx_parseElementName();return v&&(b.name=v),this.expect(s.jsxTagEnd),this.finishNode(b,v?"JSXClosingElement":"JSXClosingFragment")}jsx_parseElementAt(d,x){let b=this.startNodeAt(d,x),v=[],k=this.jsx_parseOpeningElementAt(d,x),T=null;if(!k.selfClosing){e:for(;;)switch(this.type){case s.jsxTagStart:if(d=this.start,x=this.startLoc,this.next(),this.eat(i.slash)){T=this.jsx_parseClosingElementAt(d,x);break e}v.push(this.jsx_parseElementAt(d,x));break;case s.jsxText:v.push(this.parseExprAtom());break;case i.braceL:v.push(this.jsx_parseExpressionContainer());break;default:this.unexpected()}to(T.name)!==to(k.name)&&this.raise(T.start,"Expected corresponding JSX closing tag for <"+to(k.name)+">")}let E=k.name?"Element":"Fragment";return b["opening"+E]=k,b["closing"+E]=T,b.children=v,this.type===i.relational&&this.value==="<"&&this.raise(this.start,"Adjacent JSX elements must be wrapped in an enclosing tag"),this.finishNode(b,"JSX"+E)}jsx_parseText(){let d=this.parseLiteral(this.value);return d.type="JSXText",d}jsx_parseElement(){let d=this.start,x=this.startLoc;return this.next(),this.jsx_parseElementAt(d,x)}parseExprAtom(d){return this.type===s.jsxText?this.jsx_parseText():this.type===s.jsxTagStart?this.jsx_parseElement():super.parseExprAtom(d)}readToken(d){let x=this.curContext();if(x===f)return this.jsx_readToken();if(x===u||x===c){if(p(d))return this.jsx_readWord();if(d==62)return++this.pos,this.finishToken(s.jsxTagEnd);if((d===34||d===39)&&x==u)return this.jsx_readString(d)}return d===60&&this.exprAllowed&&this.input.charCodeAt(this.pos+1)!==33?(++this.pos,this.finishToken(s.jsxTagStart)):super.readToken(d)}updateContext(d){if(this.type==i.braceL){var x=this.curContext();x==u?this.context.push(o.b_expr):x==f?this.context.push(o.b_tmpl):super.updateContext(d),this.exprAllowed=!0}else if(this.type===i.slash&&d===s.jsxTagStart)this.context.length-=2,this.context.push(c),this.exprAllowed=!1;else return super.updateContext(d)}}}});var zf=ri((c$,Yb)=>{Yb.exports=function(t){return t!=null&&t.constructor!=null&&typeof t.constructor.isBuffer=="function"&&t.constructor.isBuffer(t)}});var u1=ri((l$,a1)=>{"use strict";var du=Object.prototype.hasOwnProperty,o1=Object.prototype.toString,e1=Object.defineProperty,t1=Object.getOwnPropertyDescriptor,r1=function(t){return typeof Array.isArray=="function"?Array.isArray(t):o1.call(t)==="[object Array]"},n1=function(t){if(!t||o1.call(t)!=="[object Object]")return!1;var r=du.call(t,"constructor"),n=t.constructor&&t.constructor.prototype&&du.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!r&&!n)return!1;var i;for(i in t);return typeof i>"u"||du.call(t,i)},i1=function(t,r){e1&&r.name==="__proto__"?e1(t,r.name,{enumerable:!0,configurable:!0,value:r.newValue,writable:!0}):t[r.name]=r.newValue},s1=function(t,r){if(r==="__proto__")if(du.call(t,r)){if(t1)return t1(t,r).value}else return;return t[r]};a1.exports=function e(){var t,r,n,i,s,o,u=arguments[0],c=1,f=arguments.length,h=!1;for(typeof u=="boolean"&&(h=u,u=arguments[1]||{},c=2),(u==null||typeof u!="object"&&typeof u!="function")&&(u={});c<f;++c)if(t=arguments[c],t!=null)for(r in t)n=s1(u,r),i=s1(t,r),u!==i&&(h&&i&&(n1(i)||(s=r1(i)))?(s?(s=!1,o=n&&r1(n)?n:[]):o=n&&n1(n)?n:{},i1(u,{name:r,newValue:e(h,o,i)})):typeof i<"u"&&i1(u,{name:r,newValue:i}));return u}});var Ip;function B(e,t,r){function n(u,c){if(u._zod||Object.defineProperty(u,"_zod",{value:{def:c,constr:o,traits:new Set},enumerable:!1}),u._zod.traits.has(e))return;u._zod.traits.add(e),t(u,c);let f=o.prototype,h=Object.keys(f);for(let p=0;p<h.length;p++){let m=h[p];m in u||(u[m]=f[m].bind(u))}}let i=r?.Parent??Object;class s extends i{}Object.defineProperty(s,"name",{value:e});function o(u){var c;let f=r?.Parent?new s:this;n(f,u),(c=f._zod).deferred??(c.deferred=[]);for(let h of f._zod.deferred)h();return f}return Object.defineProperty(o,"init",{value:n}),Object.defineProperty(o,Symbol.hasInstance,{value:u=>r?.Parent&&u instanceof r.Parent?!0:u?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var OD=Symbol("zod_brand"),kr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},ni=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(Ip=globalThis).__zod_globalConfig??(Ip.__zod_globalConfig={});var ii=globalThis.__zod_globalConfig;function nr(e){return e&&Object.assign(ii,e),ii}var ve={};Dp(ve,{BIGINT_FORMAT_RANGES:()=>Op,Class:()=>_u,NUMBER_FORMAT_RANGES:()=>Nu,aborted:()=>on,allowsEval:()=>Iu,assert:()=>iv,assertEqual:()=>ev,assertIs:()=>rv,assertNever:()=>nv,assertNotEqual:()=>tv,assignProp:()=>nn,base64ToUint8Array:()=>Lp,base64urlToUint8Array:()=>Av,cached:()=>oi,captureStackTrace:()=>xo,cleanEnum:()=>kv,cleanRegex:()=>as,clone:()=>ir,cloneDef:()=>av,createTransparentProxy:()=>hv,defineLazy:()=>xe,esc:()=>yo,escapeRegex:()=>Ur,explicitlyAborted:()=>Pu,extend:()=>gv,finalizeIssue:()=>zt,floatSafeRemainder:()=>Cu,getElementAtPath:()=>uv,getEnumValues:()=>ss,getLengthableOrigin:()=>us,getParsedType:()=>pv,getSizableOrigin:()=>Fp,hexToUint8Array:()=>Ev,isObject:()=>Nn,isPlainObject:()=>sn,issue:()=>ai,joinValues:()=>sv,jsonStringifyReplacer:()=>si,merge:()=>xv,mergeDefs:()=>jr,normalizeParams:()=>ie,nullish:()=>os,numKeys:()=>fv,objectClone:()=>ov,omit:()=>mv,optionalKeys:()=>Ru,parsedType:()=>vv,partial:()=>bv,pick:()=>dv,prefixIssues:()=>qr,primitiveTypes:()=>Np,promiseAllObject:()=>cv,propertyKeyTypes:()=>Tu,randomString:()=>lv,required:()=>wv,safeExtend:()=>yv,shallowClone:()=>Rp,slugify:()=>Du,stringifyPrimitive:()=>Pp,uint8ArrayToBase64:()=>zp,uint8ArrayToBase64url:()=>Sv,uint8ArrayToHex:()=>_v,unwrapMessage:()=>is});function ev(e){return e}function tv(e){return e}function rv(e){}function nv(e){throw new Error("Unexpected value in exhaustive check")}function iv(e){}function ss(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,i])=>t.indexOf(+n)===-1).map(([n,i])=>i)}function sv(e,t="|"){return e.map(r=>Pp(r)).join(t)}function si(e,t){return typeof t=="bigint"?t.toString():t}function oi(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function os(e){return e==null}function as(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Cu(e,t){let r=e/t,n=Math.round(r),i=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)<i?0:r-n}var Tp=Symbol("evaluating");function xe(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==Tp)return n===void 0&&(n=Tp,n=r()),n},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function ov(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function nn(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function jr(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function av(e){return jr(e._zod.def)}function uv(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function cv(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let i={};for(let s=0;s<t.length;s++)i[t[s]]=n[s];return i})}function lv(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function yo(e){return JSON.stringify(e)}function Du(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var xo="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Nn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Iu=oi(()=>{if(ii.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function sn(e){if(Nn(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(Nn(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Rp(e){return sn(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function fv(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var pv=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},Tu=new Set(["string","number","symbol"]),Np=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Ur(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ir(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function ie(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function hv(e){let t;return new Proxy({},{get(r,n,i){return t??(t=e()),Reflect.get(t,n,i)},set(r,n,i,s){return t??(t=e()),Reflect.set(t,n,i,s)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,i){return t??(t=e()),Reflect.defineProperty(t,n,i)}})}function Pp(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Ru(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Nu={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Op={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function dv(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let s=jr(e._zod.def,{get shape(){let o={};for(let u in t){if(!(u in r.shape))throw new Error(`Unrecognized key: "${u}"`);t[u]&&(o[u]=r.shape[u])}return nn(this,"shape",o),o},checks:[]});return ir(e,s)}function mv(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let s=jr(e._zod.def,{get shape(){let o={...e._zod.def.shape};for(let u in t){if(!(u in r.shape))throw new Error(`Unrecognized key: "${u}"`);t[u]&&delete o[u]}return nn(this,"shape",o),o},checks:[]});return ir(e,s)}function gv(e,t){if(!sn(t))throw new Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let s=e._zod.def.shape;for(let o in t)if(Object.getOwnPropertyDescriptor(s,o)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let i=jr(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return nn(this,"shape",s),s}});return ir(e,i)}function yv(e,t){if(!sn(t))throw new Error("Invalid input to safeExtend: expected a plain object");let r=jr(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return nn(this,"shape",n),n}});return ir(e,r)}function xv(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=jr(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return nn(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return ir(e,r)}function bv(e,t,r){let i=t._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let o=jr(t._zod.def,{get shape(){let u=t._zod.def.shape,c={...u};if(r)for(let f in r){if(!(f in u))throw new Error(`Unrecognized key: "${f}"`);r[f]&&(c[f]=e?new e({type:"optional",innerType:u[f]}):u[f])}else for(let f in u)c[f]=e?new e({type:"optional",innerType:u[f]}):u[f];return nn(this,"shape",c),c},checks:[]});return ir(t,o)}function wv(e,t,r){let n=jr(t._zod.def,{get shape(){let i=t._zod.def.shape,s={...i};if(r)for(let o in r){if(!(o in s))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=new e({type:"nonoptional",innerType:i[o]}))}else for(let o in i)s[o]=new e({type:"nonoptional",innerType:i[o]});return nn(this,"shape",s),s}});return ir(t,n)}function on(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Pu(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function qr(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function is(e){return typeof e=="string"?e:e?.message}function zt(e,t,r){let n=e.message?e.message:is(e.inst?._zod.def?.error?.(e))??is(t?.error?.(e))??is(r.customError?.(e))??is(r.localeError?.(e))??"Invalid input",{inst:i,continue:s,input:o,...u}=e;return u.path??(u.path=[]),u.message=n,t?.reportInput&&(u.input=o),u}function Fp(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function us(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function vv(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function ai(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function kv(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function Lp(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function zp(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function Av(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return Lp(t+r)}function Sv(e){return zp(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Ev(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)r[n/2]=Number.parseInt(t.slice(n,n+2),16);return r}function _v(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var _u=class{constructor(...t){}};var Bp=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,si,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},bo=B("$ZodError",Bp),Ou=B("$ZodError",Bp,{Parent:Error});function Mp(e,t=r=>r.message){let r={},n=[];for(let i of e.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(t(i))):n.push(t(i));return{formErrors:n,fieldErrors:r}}function Vp(e,t=r=>r.message){let r={_errors:[]},n=(i,s=[])=>{for(let o of i.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(u=>n({issues:u},[...s,...o.path]));else if(o.code==="invalid_key")n({issues:o.issues},[...s,...o.path]);else if(o.code==="invalid_element")n({issues:o.issues},[...s,...o.path]);else{let u=[...s,...o.path];if(u.length===0)r._errors.push(t(o));else{let c=r,f=0;for(;f<u.length;){let h=u[f];f===u.length-1?(c[h]=c[h]||{_errors:[]},c[h]._errors.push(t(o))):c[h]=c[h]||{_errors:[]},c=c[h],f++}}}};return n(e),r}var wo=e=>(t,r,n,i)=>{let s=n?{...n,async:!1}:{async:!1},o=t._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new kr;if(o.issues.length){let u=new(i?.Err??e)(o.issues.map(c=>zt(c,s,nr())));throw xo(u,i?.callee),u}return o.value};var vo=e=>async(t,r,n,i)=>{let s=n?{...n,async:!0}:{async:!0},o=t._zod.run({value:r,issues:[]},s);if(o instanceof Promise&&(o=await o),o.issues.length){let u=new(i?.Err??e)(o.issues.map(c=>zt(c,s,nr())));throw xo(u,i?.callee),u}return o.value};var cs=e=>(t,r,n)=>{let i=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new kr;return s.issues.length?{success:!1,error:new(e??bo)(s.issues.map(o=>zt(o,i,nr())))}:{success:!0,data:s.value}},$p=cs(Ou),ls=e=>async(t,r,n)=>{let i=n?{...n,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(o=>zt(o,i,nr())))}:{success:!0,data:s.value}},jp=ls(Ou),Up=e=>(t,r,n)=>{let i=n?{...n,direction:"backward"}:{direction:"backward"};return wo(e)(t,r,i)};var qp=e=>(t,r,n)=>wo(e)(t,r,n);var Zp=e=>async(t,r,n)=>{let i=n?{...n,direction:"backward"}:{direction:"backward"};return vo(e)(t,r,i)};var Jp=e=>async(t,r,n)=>vo(e)(t,r,n);var Gp=e=>(t,r,n)=>{let i=n?{...n,direction:"backward"}:{direction:"backward"};return cs(e)(t,r,i)};var Qp=e=>(t,r,n)=>cs(e)(t,r,n);var Hp=e=>async(t,r,n)=>{let i=n?{...n,direction:"backward"}:{direction:"backward"};return ls(e)(t,r,i)};var Wp=e=>async(t,r,n)=>ls(e)(t,r,n);var Kp=/^[cC][0-9a-z]{6,}$/,Xp=/^[0-9a-z]+$/,Yp=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,eh=/^[0-9a-vA-V]{20}$/,th=/^[A-Za-z0-9]{27}$/,rh=/^[a-zA-Z0-9_-]{21}$/,nh=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var ih=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Fu=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;var sh=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Dv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function oh(){return new RegExp(Dv,"u")}var ah=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,uh=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var ch=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,lh=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,fh=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Lu=/^[A-Za-z0-9_-]*$/;var ph=/^https?$/,hh=/^\+[1-9]\d{6,14}$/,dh="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",mh=new RegExp(`^${dh}$`);function gh(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function yh(e){return new RegExp(`^${gh(e)}$`)}function xh(e){let t=gh({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${dh}T(?:${n})$`)}var bh=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var wh=/^-?\d+$/,zu=/^-?\d+(?:\.\d+)?$/,vh=/^(?:true|false)$/i,kh=/^null$/i;var Ah=/^[^A-Z]*$/,Sh=/^[^a-z]*$/;var tt=B("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Eh={number:"number",bigint:"bigint",object:"date"},Bu=B("$ZodCheckLessThan",(e,t)=>{tt.init(e,t);let r=Eh[typeof t.value];e._zod.onattach.push(n=>{let i=n._zod.bag,s=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?i.maximum=t.value:i.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Mu=B("$ZodCheckGreaterThan",(e,t)=>{tt.init(e,t);let r=Eh[typeof t.value];e._zod.onattach.push(n=>{let i=n._zod.bag,s=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?i.minimum=t.value:i.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),_h=B("$ZodCheckMultipleOf",(e,t)=>{tt.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):Cu(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Ch=B("$ZodCheckNumberFormat",(e,t)=>{tt.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[i,s]=Nu[t.format];e._zod.onattach.push(o=>{let u=o._zod.bag;u.format=t.format,u.minimum=i,u.maximum=s,r&&(u.pattern=wh)}),e._zod.check=o=>{let u=o.value;if(r){if(!Number.isInteger(u)){o.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:u,inst:e});return}if(!Number.isSafeInteger(u)){u>0?o.issues.push({input:u,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):o.issues.push({input:u,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}u<i&&o.issues.push({origin:"number",input:u,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),u>s&&o.issues.push({origin:"number",input:u,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}});var Dh=B("$ZodCheckMaxLength",(e,t)=>{var r;tt.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!os(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<i&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let i=n.value;if(i.length<=t.maximum)return;let o=us(i);n.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Ih=B("$ZodCheckMinLength",(e,t)=>{var r;tt.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!os(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let i=n.value;if(i.length>=t.minimum)return;let o=us(i);n.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Th=B("$ZodCheckLengthEquals",(e,t)=>{var r;tt.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!os(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=n=>{let i=n.value,s=i.length;if(s===t.length)return;let o=us(i),u=s>t.length;n.issues.push({origin:o,...u?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),fs=B("$ZodCheckStringFormat",(e,t)=>{var r,n;tt.init(e,t),e._zod.onattach.push(i=>{let s=i._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),Rh=B("$ZodCheckRegex",(e,t)=>{fs.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Nh=B("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Ah),fs.init(e,t)}),Ph=B("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Sh),fs.init(e,t)}),Oh=B("$ZodCheckIncludes",(e,t)=>{tt.init(e,t);let r=Ur(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(i=>{let s=i._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),Fh=B("$ZodCheckStartsWith",(e,t)=>{tt.init(e,t);let r=new RegExp(`^${Ur(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Lh=B("$ZodCheckEndsWith",(e,t)=>{tt.init(e,t);let r=new RegExp(`.*${Ur(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var zh=B("$ZodCheckOverwrite",(e,t)=>{tt.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Ao=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(`+`).filter(o=>o),i=Math.min(...n.map(o=>o.length-o.trimStart().length)),s=n.map(o=>o.slice(i)).map(o=>" ".repeat(this.indent*2)+o);for(let o of s)this.content.push(o)}compile(){let t=Function,r=this?.args,i=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...r,i.join(`+`))}};var Mh={major:4,minor:4,patch:3};var Re=B("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Mh;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let i of n)for(let s of i._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let i=(o,u,c)=>{let f=on(o),h;for(let p of u){if(p._zod.def.when){if(Pu(o)||!p._zod.def.when(o))continue}else if(f)continue;let m=o.issues.length,d=p._zod.check(o);if(d instanceof Promise&&c?.async===!1)throw new kr;if(h||d instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await d,o.issues.length!==m&&(f||(f=on(o,m)))});else{if(o.issues.length===m)continue;f||(f=on(o,m))}}return h?h.then(()=>o):o},s=(o,u,c)=>{if(on(o))return o.aborted=!0,o;let f=i(u,n,c);if(f instanceof Promise){if(c.async===!1)throw new kr;return f.then(h=>e._zod.parse(h,c))}return e._zod.parse(f,c)};e._zod.run=(o,u)=>{if(u.skipChecks)return e._zod.parse(o,u);if(u.direction==="backward"){let f=e._zod.parse({value:o.value,issues:[]},{...u,skipChecks:!0});return f instanceof Promise?f.then(h=>s(h,o,u)):s(f,o,u)}let c=e._zod.parse(o,u);if(c instanceof Promise){if(u.async===!1)throw new kr;return c.then(f=>i(f,n,u))}return i(c,n,u)}}xe(e,"~standard",()=>({validate:i=>{try{let s=$p(e,i);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return jp(e,i).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}))}),_o=B("$ZodString",(e,t)=>{Re.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??bh(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),Oe=B("$ZodStringFormat",(e,t)=>{fs.init(e,t),_o.init(e,t)}),Qh=B("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=ih),Oe.init(e,t)}),Hh=B("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Fu(n))}else t.pattern??(t.pattern=Fu());Oe.init(e,t)}),Wh=B("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=sh),Oe.init(e,t)}),Kh=B("$ZodURL",(e,t)=>{Oe.init(e,t),e._zod.check=r=>{try{let n=r.value.trim();if(!t.normalize&&t.protocol?.source===ph.source&&!/^https?:\/\//i.test(n)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}let i=new URL(n);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=i.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Xh=B("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=oh()),Oe.init(e,t)}),Yh=B("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=rh),Oe.init(e,t)}),ed=B("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Kp),Oe.init(e,t)}),td=B("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Xp),Oe.init(e,t)}),rd=B("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Yp),Oe.init(e,t)}),nd=B("$ZodXID",(e,t)=>{t.pattern??(t.pattern=eh),Oe.init(e,t)}),id=B("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=th),Oe.init(e,t)}),sd=B("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=xh(t)),Oe.init(e,t)}),od=B("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=mh),Oe.init(e,t)}),ad=B("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=yh(t)),Oe.init(e,t)}),ud=B("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=nh),Oe.init(e,t)}),cd=B("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ah),Oe.init(e,t),e._zod.bag.format="ipv4"}),ld=B("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=uh),Oe.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}});var fd=B("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=ch),Oe.init(e,t)}),pd=B("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=lh),Oe.init(e,t),e._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[i,s]=n;if(!s)throw new Error;let o=Number(s);if(`${o}`!==s)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${i}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function hd(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var dd=B("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=fh),Oe.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{hd(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function Iv(e){if(!Lu.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return hd(r)}var md=B("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Lu),Oe.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{Iv(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),gd=B("$ZodE164",(e,t)=>{t.pattern??(t.pattern=hh),Oe.init(e,t)});function Tv(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let i=JSON.parse(atob(n));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}var yd=B("$ZodJWT",(e,t)=>{Oe.init(e,t),e._zod.check=r=>{Tv(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var $u=B("$ZodNumber",(e,t)=>{Re.init(e,t),e._zod.pattern=e._zod.bag.pattern??zu,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let i=r.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return r;let s=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...s?{received:s}:{}}),r}}),xd=B("$ZodNumberFormat",(e,t)=>{Ch.init(e,t),$u.init(e,t)}),bd=B("$ZodBoolean",(e,t)=>{Re.init(e,t),e._zod.pattern=vh,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}let i=r.value;return typeof i=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),r}});var wd=B("$ZodNull",(e,t)=>{Re.init(e,t),e._zod.pattern=kh,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let i=r.value;return i===null||r.issues.push({expected:"null",code:"invalid_type",input:i,inst:e}),r}});var vd=B("$ZodUnknown",(e,t)=>{Re.init(e,t),e._zod.parse=r=>r}),kd=B("$ZodNever",(e,t)=>{Re.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function Vh(e,t,r){e.issues.length&&t.issues.push(...qr(r,e.issues)),t.value[r]=e.value}var Ad=B("$ZodArray",(e,t)=>{Re.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);let s=[];for(let o=0;o<i.length;o++){let u=i[o],c=t.element._zod.run({value:u,issues:[]},n);c instanceof Promise?s.push(c.then(f=>Vh(f,r,o))):Vh(c,r,o)}return s.length?Promise.all(s).then(()=>r):r}});function Eo(e,t,r,n,i,s){let o=r in n;if(e.issues.length){if(i&&s&&!o)return;t.issues.push(...qr(r,e.issues))}if(!o&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}e.value===void 0?o&&(t.value[r]=void 0):t.value[r]=e.value}function Sd(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);let r=Ru(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function Ed(e,t,r,n,i,s){let o=[],u=i.keySet,c=i.catchall._zod,f=c.def.type,h=c.optin==="optional",p=c.optout==="optional";for(let m in t){if(m==="__proto__"||u.has(m))continue;if(f==="never"){o.push(m);continue}let d=c.run({value:t[m],issues:[]},n);d instanceof Promise?e.push(d.then(x=>Eo(x,r,m,t,h,p))):Eo(d,r,m,t,h,p)}return o.length&&r.issues.push({code:"unrecognized_keys",keys:o,input:t,inst:s}),e.length?Promise.all(e).then(()=>r):r}var Rv=B("$ZodObject",(e,t)=>{if(Re.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let u=t.shape;Object.defineProperty(t,"shape",{get:()=>{let c={...u};return Object.defineProperty(t,"shape",{value:c}),c}})}let n=oi(()=>Sd(t));xe(e._zod,"propValues",()=>{let u=t.shape,c={};for(let f in u){let h=u[f]._zod;if(h.values){c[f]??(c[f]=new Set);for(let p of h.values)c[f].add(p)}}return c});let i=Nn,s=t.catchall,o;e._zod.parse=(u,c)=>{o??(o=n.value);let f=u.value;if(!i(f))return u.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),u;u.value={};let h=[],p=o.shape;for(let m of o.keys){let d=p[m],x=d._zod.optin==="optional",b=d._zod.optout==="optional",v=d._zod.run({value:f[m],issues:[]},c);v instanceof Promise?h.push(v.then(k=>Eo(k,u,m,f,x,b))):Eo(v,u,m,f,x,b)}return s?Ed(h,f,u,c,n.value,e):h.length?Promise.all(h).then(()=>u):u}}),_d=B("$ZodObjectJIT",(e,t)=>{Rv.init(e,t);let r=e._zod.parse,n=oi(()=>Sd(t)),i=m=>{let d=new Ao(["shape","payload","ctx"]),x=n.value,b=E=>{let g=yo(E);return`shape[${g}]._zod.run({ value: input[${g}], issues: [] }, ctx)`};d.write("const input = payload.value;");let v=Object.create(null),k=0;for(let E of x.keys)v[E]=`key_${k++}`;d.write("const newResult = {};");for(let E of x.keys){let g=v[E],I=yo(E),_=m[E],D=_?._zod?.optin==="optional",O=_?._zod?.optout==="optional";d.write(`const ${g} = ${b(E)};`),D&&O?d.write(`+ if (${g}.issues.length) {+ if (${I} in input) {+ payload.issues = payload.issues.concat(${g}.issues.map(iss => ({...iss,- path: iss.path ? [${w}, ...iss.path] : [${w}]+ path: iss.path ? [${I}, ...iss.path] : [${I}]})));}}- if (${_}.value === undefined) {- if (${w} in input) {- newResult[${w}] = undefined;+ if (${g}.value === undefined) {+ if (${I} in input) {+ newResult[${I}] = undefined;}} else {- newResult[${w}] = ${_}.value;+ newResult[${I}] = ${g}.value;}- `):k?p.write(`- if (${_}.issues.length) {- payload.issues = payload.issues.concat(${_}.issues.map(iss => ({+ `):D?d.write(`+ if (${g}.issues.length) {+ payload.issues = payload.issues.concat(${g}.issues.map(iss => ({...iss,- path: iss.path ? [${w}, ...iss.path] : [${w}]+ path: iss.path ? [${I}, ...iss.path] : [${I}]})));}- if (${_}.value === undefined) {- if (${w} in input) {- newResult[${w}] = undefined;+ if (${g}.value === undefined) {+ if (${I} in input) {+ newResult[${I}] = undefined;}} else {- newResult[${w}] = ${_}.value;+ newResult[${I}] = ${g}.value;}- `):p.write(`- const ${_}_present = ${w} in input;- if (${_}.issues.length) {- payload.issues = payload.issues.concat(${_}.issues.map(iss => ({+ `):d.write(`+ const ${g}_present = ${I} in input;+ if (${g}.issues.length) {+ payload.issues = payload.issues.concat(${g}.issues.map(iss => ({...iss,- path: iss.path ? [${w}, ...iss.path] : [${w}]+ path: iss.path ? [${I}, ...iss.path] : [${I}]})));}- if (!${_}_present && !${_}.issues.length) {+ if (!${g}_present && !${g}.issues.length) {payload.issues.push({code: "invalid_type",expected: "nonoptional",input: undefined,- path: [${w}]+ path: [${I}]});}- if (${_}_present) {- if (${_}.value === undefined) {- newResult[${w}] = undefined;+ if (${g}_present) {+ if (${g}.value === undefined) {+ newResult[${I}] = undefined;} else {- newResult[${w}] = ${_}.value;+ newResult[${I}] = ${g}.value;}}- `)}p.write("payload.value = newResult;"),p.write("return payload;");let S=p.compile();return(A,_)=>S(f,A,_)},s,i=ht,a=!At.jitless,u=a&&po.value,d=e.catchall,l;t._zod.parse=(f,p)=>{l??(l=r.value);let y=f.value;return i(y)?a&&u&&p?.async===!1&&p.jitless!==!0?(s||(s=o(e.shape)),f=s(f,p),d?Fa([],y,f,p,l,t):f):n(f,p):(f.issues.push({expected:"object",code:"invalid_type",input:y,inst:t}),f)}});function ta(t,e,n,r){for(let s of t)if(s.issues.length===0)return e.value=s.value,e;let o=t.filter(s=>!et(s));return o.length===1?(e.value=o[0].value,o[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(s=>s.issues.map(i=>he(i,r,be())))}),e)}var ko=g("$ZodUnion",(t,e)=>{U.init(t,e),z(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),z(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),z(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),z(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(o=>o._zod.pattern);return new RegExp(`^(${r.map(o=>sn(o.source)).join("|")})$`)}});let n=e.options.length===1?e.options[0]._zod.run:null;t._zod.parse=(r,o)=>{if(n)return n(r,o);let s=!1,i=[];for(let a of e.options){let c=a._zod.run({value:r.value,issues:[]},o);if(c instanceof Promise)i.push(c),s=!0;else{if(c.issues.length===0)return c;i.push(c)}}return s?Promise.all(i).then(a=>ta(a,r,t,o)):ta(i,r,t,o)}});var ja=g("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,ko.init(t,e);let n=t._zod.parse;z(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let r=vt(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues?.[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!ht(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=r.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback||s.direction==="backward"?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(r.value.keys()),input:i,path:[e.discriminator],inst:t}),o)}}),Ba=g("$ZodIntersection",(t,e)=>{U.init(t,e),t._zod.parse=(n,r)=>{let o=n.value,s=e.left._zod.run({value:o,issues:[]},r),i=e.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>na(n,c,u)):na(n,s,i)}});function Eo(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Xe(t)&&Xe(e)){let n=Object.keys(e),r=Object.keys(t).filter(s=>n.indexOf(s)!==-1),o={...t,...e};for(let s of r){let i=Eo(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<t.length;r++){let o=t[r],s=e[r],i=Eo(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function na(t,e,n){let r=new Map,o;for(let a of e.issues)if(a.code==="unrecognized_keys"){o??(o=a);for(let c of a.keys)r.has(c)||r.set(c,{}),r.get(c).l=!0}else t.issues.push(a);for(let a of n.issues)if(a.code==="unrecognized_keys")for(let c of a.keys)r.has(c)||r.set(c,{}),r.get(c).r=!0;else t.issues.push(a);let s=[...r].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&o&&t.issues.push({...o,keys:s}),et(t))return t;let i=Eo(e.value,n.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return t.value=i.data,t}var Ua=g("$ZodRecord",(t,e)=>{U.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Xe(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),n;let s=[],i=e.keyType._zod.values;if(i){n.value={};let a=new Set;for(let u of i)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){a.add(typeof u=="number"?u.toString():u);let d=e.keyType._zod.run({value:u,issues:[]},r);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(d.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map(p=>he(p,r,be())),input:u,path:[u],inst:t});continue}let l=d.value,f=e.valueType._zod.run({value:o[u],issues:[]},r);f instanceof Promise?s.push(f.then(p=>{p.issues.length&&n.issues.push(...Ve(u,p.issues)),n.value[l]=p.value})):(f.issues.length&&n.issues.push(...Ve(u,f.issues)),n.value[l]=f.value)}let c;for(let u in o)a.has(u)||(c=c??[],c.push(u));c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:c})}else{n.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,a))continue;let c=e.keyType._zod.run({value:a,issues:[]},r);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&xo.test(a)&&c.issues.length){let l=e.keyType._zod.run({value:Number(a),issues:[]},r);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");l.issues.length===0&&(c=l)}if(c.issues.length){e.mode==="loose"?n.value[a]=o[a]:n.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(l=>he(l,r,be())),input:a,path:[a],inst:t});continue}let d=e.valueType._zod.run({value:o[a],issues:[]},r);d instanceof Promise?s.push(d.then(l=>{l.issues.length&&n.issues.push(...Ve(a,l.issues)),n.value[c.value]=l.value})):(d.issues.length&&n.issues.push(...Ve(a,d.issues)),n.value[c.value]=d.value)}}return s.length?Promise.all(s).then(()=>n):n}});var Qa=g("$ZodEnum",(t,e)=>{U.init(t,e);let n=rn(e.entries),r=new Set(n);t._zod.values=r,t._zod.pattern=new RegExp(`^(${n.filter(o=>mo.has(typeof o)).map(o=>typeof o=="string"?Ge(o):o.toString()).join("|")})$`),t._zod.parse=(o,s)=>{let i=o.value;return r.has(i)||o.issues.push({code:"invalid_value",values:n,input:i,inst:t}),o}}),Ga=g("$ZodLiteral",(t,e)=>{if(U.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");let n=new Set(e.values);t._zod.values=n,t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Ge(r):r?Ge(r.toString()):String(r)).join("|")})$`),t._zod.parse=(r,o)=>{let s=r.value;return n.has(s)||r.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),r}});var Va=g("$ZodTransform",(t,e)=>{U.init(t,e),t._zod.optin="optional",t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new St(t.constructor.name);let o=e.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(n.value=i,n.fallback=!0,n));if(o instanceof Promise)throw new Ne;return n.value=o,n.fallback=!0,n}});function ra(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var Do=g("$ZodOptional",(t,e)=>{U.init(t,e),t._zod.optin="optional",t._zod.optout="optional",z(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),z(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${sn(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>{if(e.innerType._zod.optin==="optional"){let o=n.value,s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(i=>ra(i,o)):ra(s,o)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),qa=g("$ZodExactOptional",(t,e)=>{Do.init(t,e),z(t._zod,"values",()=>e.innerType._zod.values),z(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(n,r)=>e.innerType._zod.run(n,r)}),Ja=g("$ZodNullable",(t,e)=>{U.init(t,e),z(t._zod,"optin",()=>e.innerType._zod.optin),z(t._zod,"optout",()=>e.innerType._zod.optout),z(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${sn(n.source)}|null)$`):void 0}),z(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),Ka=g("$ZodDefault",(t,e)=>{U.init(t,e),t._zod.optin="optional",z(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);if(n.value===void 0)return n.value=e.defaultValue,n;let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>oa(s,e)):oa(o,e)}});function oa(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Wa=g("$ZodPrefault",(t,e)=>{U.init(t,e),t._zod.optin="optional",z(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),Ya=g("$ZodNonOptional",(t,e)=>{U.init(t,e),z(t._zod,"values",()=>{let n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>sa(s,t)):sa(o,t)}});function sa(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var Ha=g("$ZodCatch",(t,e)=>{U.init(t,e),t._zod.optin="optional",z(t._zod,"optout",()=>e.innerType._zod.optout),z(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(i=>he(i,r,be()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=o.value,o.issues.length&&(n.value=e.catchValue({...n,error:{issues:o.issues.map(s=>he(s,r,be()))},input:n.value}),n.issues=[],n.fallback=!0),n)}});var Xa=g("$ZodPipe",(t,e)=>{U.init(t,e),z(t._zod,"values",()=>e.in._zod.values),z(t._zod,"optin",()=>e.in._zod.optin),z(t._zod,"optout",()=>e.out._zod.optout),z(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(n,r)=>{if(r.direction==="backward"){let s=e.out._zod.run(n,r);return s instanceof Promise?s.then(i=>Hn(i,e.in,r)):Hn(s,e.in,r)}let o=e.in._zod.run(n,r);return o instanceof Promise?o.then(s=>Hn(s,e.out,r)):Hn(o,e.out,r)}});function Hn(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues,fallback:t.fallback},n)}var ec=g("$ZodReadonly",(t,e)=>{U.init(t,e),z(t._zod,"propValues",()=>e.innerType._zod.propValues),z(t._zod,"values",()=>e.innerType._zod.values),z(t._zod,"optin",()=>e.innerType?._zod?.optin),z(t._zod,"optout",()=>e.innerType?._zod?.optout),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(ia):ia(o)}});function ia(t){return t.value=Object.freeze(t.value),t}var tc=g("$ZodLazy",(t,e)=>{U.init(t,e),z(t._zod,"innerType",()=>{let n=e;return n._cachedInner||(n._cachedInner=e.getter()),n._cachedInner}),z(t._zod,"pattern",()=>t._zod.innerType?._zod?.pattern),z(t._zod,"propValues",()=>t._zod.innerType?._zod?.propValues),z(t._zod,"optin",()=>t._zod.innerType?._zod?.optin??void 0),z(t._zod,"optout",()=>t._zod.innerType?._zod?.optout??void 0),t._zod.parse=(n,r)=>t._zod.innerType._zod.run(n,r)}),nc=g("$ZodCustom",(t,e)=>{X.init(t,e),U.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{let r=n.value,o=e.fn(r);if(o instanceof Promise)return o.then(s=>aa(s,n,r,t));aa(o,n,r,t)}});function aa(t,e,n,r){if(!t){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),e.issues.push(kt(o))}}var rc,ly=Symbol("ZodOutput"),fy=Symbol("ZodInput"),Ro=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...n){let r=n[0];return this._map.set(e,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){let n=e._zod.parent;if(n){let r={...this.get(n)??{}};delete r.id;let o={...r,...this._map.get(e)};return Object.keys(o).length?o:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Cd(){return new Ro}(rc=globalThis).__zod_globalRegistry??(rc.__zod_globalRegistry=Cd());var yt=globalThis.__zod_globalRegistry;function oc(t,e){return new t({type:"string",...I(e)})}function sc(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...I(e)})}function Io(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...I(e)})}function ic(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...I(e)})}function ac(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...I(e)})}function cc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...I(e)})}function uc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...I(e)})}function lc(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...I(e)})}function fc(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...I(e)})}function dc(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...I(e)})}function pc(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...I(e)})}function mc(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...I(e)})}function hc(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...I(e)})}function yc(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...I(e)})}function gc(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...I(e)})}function bc(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...I(e)})}function wc(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...I(e)})}function _c(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...I(e)})}function xc(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...I(e)})}function Sc(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...I(e)})}function Ac(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...I(e)})}function Ec(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...I(e)})}function vc(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...I(e)})}function kc(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...I(e)})}function Dc(t,e){return new t({type:"string",format:"date",check:"string_format",...I(e)})}function Rc(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...I(e)})}function Ic(t,e){return new t({type:"string",format:"duration",check:"string_format",...I(e)})}function Oc(t,e){return new t({type:"number",checks:[],...I(e)})}function Cc(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...I(e)})}function Nc(t,e){return new t({type:"boolean",...I(e)})}function $c(t,e){return new t({type:"null",...I(e)})}function Tc(t){return new t({type:"unknown"})}function zc(t,e){return new t({type:"never",...I(e)})}function tr(t,e){return new So({check:"less_than",...I(e),value:t,inclusive:!1})}function fn(t,e){return new So({check:"less_than",...I(e),value:t,inclusive:!0})}function nr(t,e){return new Ao({check:"greater_than",...I(e),value:t,inclusive:!1})}function dn(t,e){return new Ao({check:"greater_than",...I(e),value:t,inclusive:!0})}function rr(t,e){return new Zi({check:"multiple_of",...I(e),value:t})}function or(t,e){return new Bi({check:"max_length",...I(e),maximum:t})}function Dt(t,e){return new Ui({check:"min_length",...I(e),minimum:t})}function sr(t,e){return new Qi({check:"length_equals",...I(e),length:t})}function Oo(t,e){return new Gi({check:"string_format",format:"regex",...I(e),pattern:t})}function Co(t){return new Vi({check:"string_format",format:"lowercase",...I(t)})}function No(t){return new qi({check:"string_format",format:"uppercase",...I(t)})}function $o(t,e){return new Ji({check:"string_format",format:"includes",...I(e),includes:t})}function To(t,e){return new Ki({check:"string_format",format:"starts_with",...I(e),prefix:t})}function zo(t,e){return new Wi({check:"string_format",format:"ends_with",...I(e),suffix:t})}function tt(t){return new Yi({check:"overwrite",tx:t})}function Po(t){return tt(e=>e.normalize(t))}function Lo(){return tt(t=>t.trim())}function Mo(){return tt(t=>t.toLowerCase())}function Fo(){return tt(t=>t.toUpperCase())}function Zo(){return tt(t=>fo(t))}function Pc(t,e,n){return new t({type:"array",element:e,...I(n)})}function Lc(t,e,n){return new t({type:"custom",check:"custom",fn:e,...I(n)})}function Mc(t,e){let n=Nd(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(kt(o,r.value,n._zod.def));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=n),s.continue??(s.continue=!n._zod.def.abort),r.issues.push(kt(s))}},t(r.value,r)),e);return n}function Nd(t,e){let n=new X({check:"custom",...I(e)});return n._zod.check=t,n}function jo(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??yt,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0}}function J(t,e,n={path:[],schemaPath:[]}){var r;let o=t._zod.def,s=e.seen.get(t);if(s)return s.count++,n.schemaPath.includes(t)&&(s.cycle=n.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:n.path};e.seen.set(t,i);let a=t._zod.toJSONSchema?.();if(a)i.schema=a;else{let d={...n,schemaPath:[...n.schemaPath,t],path:n.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,i.schema,d);else{let f=i.schema,p=e.processors[o.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);p(t,e,f,d)}let l=t._zod.parent;l&&(i.ref||(i.ref=l),J(l,e,d),e.seen.get(l).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&Object.assign(i.schema,c),e.io==="input"&&ne(t)&&(delete i.schema.examples,delete i.schema.default),e.io==="input"&&"_prefault"in i.schema&&((r=i.schema).default??(r.default=i.schema._prefault)),delete i.schema._prefault,e.seen.get(t).schema}function Bo(t,e){let n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=new Map;for(let i of t.seen.entries()){let a=t.metadataRegistry.get(i[0])?.id;if(a){let c=r.get(a);if(c&&c!==i[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(a,i[0])}}let o=i=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let l=t.external.registry.get(i[0])?.id,f=t.external.uri??(y=>y);if(l)return{ref:f(l)};let p=i[1].defId??i[1].schema.id??`schema${t.counter++}`;return i[1].defId=p,{defId:p,ref:`${f("__shared")}#/${a}/${p}`}}if(i[1]===n)return{ref:"#"};let u=`#/${a}/`,d=i[1].schema.id??`__schema${t.counter++}`;return{defId:d,ref:u+d}},s=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:u}=o(i);a.def={...a.schema},u&&(a.defId=u);let d=a.schema;for(let l in d)delete d[l];d.$ref=c};if(t.cycles==="throw")for(let i of t.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>+ `)}d.write("payload.value = newResult;"),d.write("return payload;");let T=d.compile();return(E,g)=>T(m,E,g)},s,o=Nn,u=!ii.jitless,f=u&&Iu.value,h=t.catchall,p;e._zod.parse=(m,d)=>{p??(p=n.value);let x=m.value;return o(x)?u&&f&&d?.async===!1&&d.jitless!==!0?(s||(s=i(t.shape)),m=s(m,d),h?Ed([],x,m,d,p,e):m):r(m,d):(m.issues.push({expected:"object",code:"invalid_type",input:x,inst:e}),m)}});function $h(e,t,r,n){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let i=e.filter(s=>!on(s));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(s=>s.issues.map(o=>zt(o,n,nr())))}),t)}var ju=B("$ZodUnion",(e,t)=>{Re.init(e,t),xe(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),xe(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),xe(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),xe(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){let n=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${n.map(i=>as(i.source)).join("|")})$`)}});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,i)=>{if(r)return r(n,i);let s=!1,o=[];for(let u of t.options){let c=u._zod.run({value:n.value,issues:[]},i);if(c instanceof Promise)o.push(c),s=!0;else{if(c.issues.length===0)return c;o.push(c)}}return s?Promise.all(o).then(u=>$h(u,n,e,i)):$h(o,n,e,i)}});var Cd=B("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,ju.init(e,t);let r=e._zod.parse;xe(e._zod,"propValues",()=>{let i={};for(let s of t.options){let o=s._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let[u,c]of Object.entries(o)){i[u]||(i[u]=new Set);for(let f of c)i[u].add(f)}}return i});let n=oi(()=>{let i=t.options,s=new Map;for(let o of i){let u=o._zod.propValues?.[t.discriminator];if(!u||u.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(o)}"`);for(let c of u){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,o)}}return s});e._zod.parse=(i,s)=>{let o=i.value;if(!Nn(o))return i.issues.push({code:"invalid_type",expected:"object",input:o,inst:e}),i;let u=n.value.get(o?.[t.discriminator]);return u?u._zod.run(i,s):t.unionFallback||s.direction==="backward"?r(i,s):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(n.value.keys()),input:o,path:[t.discriminator],inst:e}),i)}}),Dd=B("$ZodIntersection",(e,t)=>{Re.init(e,t),e._zod.parse=(r,n)=>{let i=r.value,s=t.left._zod.run({value:i,issues:[]},n),o=t.right._zod.run({value:i,issues:[]},n);return s instanceof Promise||o instanceof Promise?Promise.all([s,o]).then(([c,f])=>jh(r,c,f)):jh(r,s,o)}});function Vu(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(sn(e)&&sn(t)){let r=Object.keys(t),n=Object.keys(e).filter(s=>r.indexOf(s)!==-1),i={...e,...t};for(let s of n){let o=Vu(e[s],t[s]);if(!o.valid)return{valid:!1,mergeErrorPath:[s,...o.mergeErrorPath]};i[s]=o.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let i=e[n],s=t[n],o=Vu(i,s);if(!o.valid)return{valid:!1,mergeErrorPath:[n,...o.mergeErrorPath]};r.push(o.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function jh(e,t,r){let n=new Map,i;for(let u of t.issues)if(u.code==="unrecognized_keys"){i??(i=u);for(let c of u.keys)n.has(c)||n.set(c,{}),n.get(c).l=!0}else e.issues.push(u);for(let u of r.issues)if(u.code==="unrecognized_keys")for(let c of u.keys)n.has(c)||n.set(c,{}),n.get(c).r=!0;else e.issues.push(u);let s=[...n].filter(([,u])=>u.l&&u.r).map(([u])=>u);if(s.length&&i&&e.issues.push({...i,keys:s}),on(e))return e;let o=Vu(t.value,r.value);if(!o.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var Id=B("$ZodRecord",(e,t)=>{Re.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!sn(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),r;let s=[],o=t.keyType._zod.values;if(o){r.value={};let u=new Set;for(let f of o)if(typeof f=="string"||typeof f=="number"||typeof f=="symbol"){u.add(typeof f=="number"?f.toString():f);let h=t.keyType._zod.run({value:f,issues:[]},n);if(h instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(h.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:h.issues.map(d=>zt(d,n,nr())),input:f,path:[f],inst:e});continue}let p=h.value,m=t.valueType._zod.run({value:i[f],issues:[]},n);m instanceof Promise?s.push(m.then(d=>{d.issues.length&&r.issues.push(...qr(f,d.issues)),r.value[p]=d.value})):(m.issues.length&&r.issues.push(...qr(f,m.issues)),r.value[p]=m.value)}let c;for(let f in i)u.has(f)||(c=c??[],c.push(f));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:c})}else{r.value={};for(let u of Reflect.ownKeys(i)){if(u==="__proto__"||!Object.prototype.propertyIsEnumerable.call(i,u))continue;let c=t.keyType._zod.run({value:u,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof u=="string"&&zu.test(u)&&c.issues.length){let p=t.keyType._zod.run({value:Number(u),issues:[]},n);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");p.issues.length===0&&(c=p)}if(c.issues.length){t.mode==="loose"?r.value[u]=i[u]:r.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(p=>zt(p,n,nr())),input:u,path:[u],inst:e});continue}let h=t.valueType._zod.run({value:i[u],issues:[]},n);h instanceof Promise?s.push(h.then(p=>{p.issues.length&&r.issues.push(...qr(u,p.issues)),r.value[c.value]=p.value})):(h.issues.length&&r.issues.push(...qr(u,h.issues)),r.value[c.value]=h.value)}}return s.length?Promise.all(s).then(()=>r):r}});var Td=B("$ZodEnum",(e,t)=>{Re.init(e,t);let r=ss(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter(i=>Tu.has(typeof i)).map(i=>typeof i=="string"?Ur(i):i.toString()).join("|")})$`),e._zod.parse=(i,s)=>{let o=i.value;return n.has(o)||i.issues.push({code:"invalid_value",values:r,input:o,inst:e}),i}}),Rd=B("$ZodLiteral",(e,t)=>{if(Re.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?Ur(n):n?Ur(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,i)=>{let s=n.value;return r.has(s)||n.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),n}});var Nd=B("$ZodTransform",(e,t)=>{Re.init(e,t),e._zod.optin="optional",e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new ni(e.constructor.name);let i=t.transform(r.value,r);if(n.async)return(i instanceof Promise?i:Promise.resolve(i)).then(o=>(r.value=o,r.fallback=!0,r));if(i instanceof Promise)throw new kr;return r.value=i,r.fallback=!0,r}});function Uh(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var Uu=B("$ZodOptional",(e,t)=>{Re.init(e,t),e._zod.optin="optional",e._zod.optout="optional",xe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),xe(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${as(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(t.innerType._zod.optin==="optional"){let i=r.value,s=t.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>Uh(o,i)):Uh(s,i)}return r.value===void 0?r:t.innerType._zod.run(r,n)}}),Pd=B("$ZodExactOptional",(e,t)=>{Uu.init(e,t),xe(e._zod,"values",()=>t.innerType._zod.values),xe(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),Od=B("$ZodNullable",(e,t)=>{Re.init(e,t),xe(e._zod,"optin",()=>t.innerType._zod.optin),xe(e._zod,"optout",()=>t.innerType._zod.optout),xe(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${as(r.source)}|null)$`):void 0}),xe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),Fd=B("$ZodDefault",(e,t)=>{Re.init(e,t),e._zod.optin="optional",xe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;let i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>qh(s,t)):qh(i,t)}});function qh(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Ld=B("$ZodPrefault",(e,t)=>{Re.init(e,t),e._zod.optin="optional",xe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),zd=B("$ZodNonOptional",(e,t)=>{Re.init(e,t),xe(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{let i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>Zh(s,e)):Zh(i,e)}});function Zh(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var Bd=B("$ZodCatch",(e,t)=>{Re.init(e,t),e._zod.optin="optional",xe(e._zod,"optout",()=>t.innerType._zod.optout),xe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>(r.value=s.value,s.issues.length&&(r.value=t.catchValue({...r,error:{issues:s.issues.map(o=>zt(o,n,nr()))},input:r.value}),r.issues=[],r.fallback=!0),r)):(r.value=i.value,i.issues.length&&(r.value=t.catchValue({...r,error:{issues:i.issues.map(s=>zt(s,n,nr()))},input:r.value}),r.issues=[],r.fallback=!0),r)}});var Md=B("$ZodPipe",(e,t)=>{Re.init(e,t),xe(e._zod,"values",()=>t.in._zod.values),xe(e._zod,"optin",()=>t.in._zod.optin),xe(e._zod,"optout",()=>t.out._zod.optout),xe(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){let s=t.out._zod.run(r,n);return s instanceof Promise?s.then(o=>So(o,t.in,n)):So(s,t.in,n)}let i=t.in._zod.run(r,n);return i instanceof Promise?i.then(s=>So(s,t.out,n)):So(i,t.out,n)}});function So(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}var Vd=B("$ZodReadonly",(e,t)=>{Re.init(e,t),xe(e._zod,"propValues",()=>t.innerType._zod.propValues),xe(e._zod,"values",()=>t.innerType._zod.values),xe(e._zod,"optin",()=>t.innerType?._zod?.optin),xe(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(Jh):Jh(i)}});function Jh(e){return e.value=Object.freeze(e.value),e}var $d=B("$ZodLazy",(e,t)=>{Re.init(e,t),xe(e._zod,"innerType",()=>{let r=t;return r._cachedInner||(r._cachedInner=t.getter()),r._cachedInner}),xe(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),xe(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),xe(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),xe(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),jd=B("$ZodCustom",(e,t)=>{tt.init(e,t),Re.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{let n=r.value,i=t.fn(n);if(i instanceof Promise)return i.then(s=>Gh(s,r,n,e));Gh(i,r,n,e)}});function Gh(e,t,r,n){if(!e){let i={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(i.params=n._zod.def.params),t.issues.push(ai(i))}}var Ud,KD=Symbol("ZodOutput"),XD=Symbol("ZodInput"),qu=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...r){let n=r[0];return this._map.set(t,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let n={...this.get(r)??{}};delete n.id;let i={...n,...this._map.get(t)};return Object.keys(i).length?i:void 0}return this._map.get(t)}has(t){return this._map.has(t)}};function Nv(){return new qu}(Ud=globalThis).__zod_globalRegistry??(Ud.__zod_globalRegistry=Nv());var Pn=globalThis.__zod_globalRegistry;function qd(e,t){return new e({type:"string",...ie(t)})}function Zd(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...ie(t)})}function Zu(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...ie(t)})}function Jd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...ie(t)})}function Gd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ie(t)})}function Qd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ie(t)})}function Hd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ie(t)})}function Wd(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...ie(t)})}function Kd(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...ie(t)})}function Xd(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...ie(t)})}function Yd(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...ie(t)})}function em(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...ie(t)})}function tm(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...ie(t)})}function rm(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...ie(t)})}function nm(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...ie(t)})}function im(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...ie(t)})}function sm(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...ie(t)})}function om(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ie(t)})}function am(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ie(t)})}function um(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...ie(t)})}function cm(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...ie(t)})}function lm(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...ie(t)})}function fm(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...ie(t)})}function pm(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ie(t)})}function hm(e,t){return new e({type:"string",format:"date",check:"string_format",...ie(t)})}function dm(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...ie(t)})}function mm(e,t){return new e({type:"string",format:"duration",check:"string_format",...ie(t)})}function gm(e,t){return new e({type:"number",checks:[],...ie(t)})}function ym(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...ie(t)})}function xm(e,t){return new e({type:"boolean",...ie(t)})}function bm(e,t){return new e({type:"null",...ie(t)})}function wm(e){return new e({type:"unknown"})}function vm(e,t){return new e({type:"never",...ie(t)})}function Co(e,t){return new Bu({check:"less_than",...ie(t),value:e,inclusive:!1})}function ps(e,t){return new Bu({check:"less_than",...ie(t),value:e,inclusive:!0})}function Do(e,t){return new Mu({check:"greater_than",...ie(t),value:e,inclusive:!1})}function hs(e,t){return new Mu({check:"greater_than",...ie(t),value:e,inclusive:!0})}function Io(e,t){return new _h({check:"multiple_of",...ie(t),value:e})}function To(e,t){return new Dh({check:"max_length",...ie(t),maximum:e})}function ui(e,t){return new Ih({check:"min_length",...ie(t),minimum:e})}function Ro(e,t){return new Th({check:"length_equals",...ie(t),length:e})}function Ju(e,t){return new Rh({check:"string_format",format:"regex",...ie(t),pattern:e})}function Gu(e){return new Nh({check:"string_format",format:"lowercase",...ie(e)})}function Qu(e){return new Ph({check:"string_format",format:"uppercase",...ie(e)})}function Hu(e,t){return new Oh({check:"string_format",format:"includes",...ie(t),includes:e})}function Wu(e,t){return new Fh({check:"string_format",format:"starts_with",...ie(t),prefix:e})}function Ku(e,t){return new Lh({check:"string_format",format:"ends_with",...ie(t),suffix:e})}function an(e){return new zh({check:"overwrite",tx:e})}function Xu(e){return an(t=>t.normalize(e))}function Yu(){return an(e=>e.trim())}function ec(){return an(e=>e.toLowerCase())}function tc(){return an(e=>e.toUpperCase())}function rc(){return an(e=>Du(e))}function km(e,t,r){return new e({type:"array",element:t,...ie(r)})}function Am(e,t,r){return new e({type:"custom",check:"custom",fn:t,...ie(r)})}function Sm(e,t){let r=Pv(n=>(n.addIssue=i=>{if(typeof i=="string")n.issues.push(ai(i,n.value,r._zod.def));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),n.issues.push(ai(s))}},e(n.value,n)),t);return r}function Pv(e,t){let r=new tt({check:"custom",...ie(t)});return r._zod.check=e,r}function nc(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Pn,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function $e(e,t,r={path:[],schemaPath:[]}){var n;let i=e._zod.def,s=t.seen.get(e);if(s)return s.count++,r.schemaPath.includes(e)&&(s.cycle=r.path),s.schema;let o={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,o);let u=e._zod.toJSONSchema?.();if(u)o.schema=u;else{let h={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,h);else{let m=o.schema,d=t.processors[i.type];if(!d)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);d(e,t,m,h)}let p=e._zod.parent;p&&(o.ref||(o.ref=p),$e(p,t,h),t.seen.get(p).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io==="input"&&ft(e)&&(delete o.schema.examples,delete o.schema.default),t.io==="input"&&"_prefault"in o.schema&&((n=o.schema).default??(n.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function ic(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let o of e.seen.entries()){let u=e.metadataRegistry.get(o[0])?.id;if(u){let c=n.get(u);if(c&&c!==o[0])throw new Error(`Duplicate schema id "${u}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(u,o[0])}}let i=o=>{let u=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let p=e.external.registry.get(o[0])?.id,m=e.external.uri??(x=>x);if(p)return{ref:m(p)};let d=o[1].defId??o[1].schema.id??`schema${e.counter++}`;return o[1].defId=d,{defId:d,ref:`${m("__shared")}#/${u}/${d}`}}if(o[1]===r)return{ref:"#"};let f=`#/${u}/`,h=o[1].schema.id??`__schema${e.counter++}`;return{defId:h,ref:f+h}},s=o=>{if(o[1].schema.$ref)return;let u=o[1],{ref:c,defId:f}=i(o);u.def={...u.schema},f&&(u.defId=f);let h=u.schema;for(let p in h)delete h[p];h.$ref=c};if(e.cycles==="throw")for(let o of e.seen.entries()){let u=o[1];if(u.cycle)throw new Error(`Cycle detected: #/${u.cycle?.join("/")}/<root>-Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of t.seen.entries()){let a=i[1];if(e===i[0]){s(i);continue}if(t.external){let u=t.external.registry.get(i[0])?.id;if(e!==i[0]&&u){s(i);continue}}if(t.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1&&t.reused==="ref"){s(i);continue}}}function Uo(t,e){let n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,d={...u},l=c.ref;if(c.ref=null,l){r(l);let p=t.seen.get(l),y=p.schema;if(y.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(y)):Object.assign(u,y),Object.assign(u,d),a._zod.parent===l)for(let h in u)h==="$ref"||h==="allOf"||h in d||delete u[h];if(y.$ref&&p.def)for(let h in u)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(u[h])===JSON.stringify(p.def[h])&&delete u[h]}let f=a._zod.parent;if(f&&f!==l){r(f);let p=t.seen.get(f);if(p?.schema.$ref&&(u.$ref=p.schema.$ref,p.def))for(let y in u)y==="$ref"||y==="allOf"||y in p.def&&JSON.stringify(u[y])===JSON.stringify(p.def[y])&&delete u[y]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...t.seen.entries()].reverse())r(a[0]);let o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(a)}Object.assign(o,n.def??n.schema);let s=t.metadataRegistry.get(e)?.id;s!==void 0&&o.id===s&&delete o.id;let i=t.external?.defs??{};for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,i[c.defId]=c.def)}t.external||Object.keys(i).length>0&&(t.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:pn(e,"input",t.processors),output:pn(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function ne(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let r=t._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return ne(r.element,n);if(r.type==="set")return ne(r.valueType,n);if(r.type==="lazy")return ne(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return ne(r.innerType,n);if(r.type==="intersection")return ne(r.left,n)||ne(r.right,n);if(r.type==="record"||r.type==="map")return ne(r.keyType,n)||ne(r.valueType,n);if(r.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:ne(r.in,n)||ne(r.out,n);if(r.type==="object"){for(let o in r.shape)if(ne(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(let o of r.options)if(ne(o,n))return!0;return!1}if(r.type==="tuple"){for(let o of r.items)if(ne(o,n))return!0;return!!(r.rest&&ne(r.rest,n))}return!1}var Fc=(t,e={})=>n=>{let r=jo({...n,processors:e});return J(t,r),Bo(r,t),Uo(r,t)},pn=(t,e,n={})=>r=>{let{libraryOptions:o,target:s}=r??{},i=jo({...o??{},target:s,io:e,processors:n});return J(t,i),Bo(i,t),Uo(i,t)};var $d={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Zc=(t,e,n,r)=>{let o=n;o.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof s=="number"&&(o.minLength=s),typeof i=="number"&&(o.maxLength=i),a&&(o.format=$d[a]??a,o.format===""&&delete o.format,a==="time"&&delete o.format),u&&(o.contentEncoding=u),c&&c.size>0){let d=[...c];d.length===1?o.pattern=d[0].source:d.length>1&&(o.allOf=[...d.map(l=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:l.source}))])}},jc=(t,e,n,r)=>{let o=n,{minimum:s,maximum:i,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:d}=t._zod.bag;typeof a=="string"&&a.includes("int")?o.type="integer":o.type="number";let l=typeof d=="number"&&d>=(s??Number.NEGATIVE_INFINITY),f=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),p=e.target==="draft-04"||e.target==="openapi-3.0";l?p?(o.minimum=d,o.exclusiveMinimum=!0):o.exclusiveMinimum=d:typeof s=="number"&&(o.minimum=s),f?p?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof i=="number"&&(o.maximum=i),typeof c=="number"&&(o.multipleOf=c)},Bc=(t,e,n,r)=>{n.type="boolean"};var Uc=(t,e,n,r)=>{e.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"};var Qc=(t,e,n,r)=>{n.not={}};var Gc=(t,e,n,r)=>{};var Vc=(t,e,n,r)=>{let o=t._zod.def,s=rn(o.entries);s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),n.enum=s},qc=(t,e,n,r)=>{let o=t._zod.def,s=[];for(let i of o.values)if(i===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){let i=s[0];n.type=i===null?"null":typeof i,e.target==="draft-04"||e.target==="openapi-3.0"?n.enum=[i]:n.const=i}else s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),s.every(i=>typeof i=="boolean")&&(n.type="boolean"),s.every(i=>i===null)&&(n.type="null"),n.enum=s};var Jc=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var Kc=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var Wc=(t,e,n,r)=>{let o=n,s=t._zod.def,{minimum:i,maximum:a}=t._zod.bag;typeof i=="number"&&(o.minItems=i),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=J(s.element,e,{...r,path:[...r.path,"items"]})},Yc=(t,e,n,r)=>{let o=n,s=t._zod.def;o.type="object",o.properties={};let i=s.shape;for(let u in i)o.properties[u]=J(i[u],e,{...r,path:[...r.path,"properties",u]});let a=new Set(Object.keys(i)),c=new Set([...a].filter(u=>{let d=s.shape[u]._zod;return e.io==="input"?d.optin===void 0:d.optout===void 0}));c.size>0&&(o.required=Array.from(c)),s.catchall?._zod.def.type==="never"?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=J(s.catchall,e,{...r,path:[...r.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},Hc=(t,e,n,r)=>{let o=t._zod.def,s=o.inclusive===!1,i=o.options.map((a,c)=>J(a,e,{...r,path:[...r.path,s?"oneOf":"anyOf",c]}));s?n.oneOf=i:n.anyOf=i},Xc=(t,e,n,r)=>{let o=t._zod.def,s=J(o.left,e,{...r,path:[...r.path,"allOf",0]}),i=J(o.right,e,{...r,path:[...r.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];n.allOf=c};var eu=(t,e,n,r)=>{let o=n,s=t._zod.def;o.type="object";let i=s.keyType,c=i._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let d=J(s.valueType,e,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(let l of c)o.patternProperties[l.source]=d}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(o.propertyNames=J(s.keyType,e,{...r,path:[...r.path,"propertyNames"]})),o.additionalProperties=J(s.valueType,e,{...r,path:[...r.path,"additionalProperties"]});let u=i._zod.values;if(u){let d=[...u].filter(l=>typeof l=="string"||typeof l=="number");d.length>0&&(o.required=d)}},tu=(t,e,n,r)=>{let o=t._zod.def,s=J(o.innerType,e,r),i=e.seen.get(t);e.target==="openapi-3.0"?(i.ref=o.innerType,n.nullable=!0):n.anyOf=[s,{type:"null"}]},nu=(t,e,n,r)=>{let o=t._zod.def;J(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType},ru=(t,e,n,r)=>{let o=t._zod.def;J(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},ou=(t,e,n,r)=>{let o=t._zod.def;J(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType,e.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},su=(t,e,n,r)=>{let o=t._zod.def;J(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=i},iu=(t,e,n,r)=>{let o=t._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=e.io==="input"?s?o.out:o.in:o.out;J(i,e,r);let a=e.seen.get(t);a.ref=i},au=(t,e,n,r)=>{let o=t._zod.def;J(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType,n.readOnly=!0};var Qo=(t,e,n,r)=>{let o=t._zod.def;J(o.innerType,e,r);let s=e.seen.get(t);s.ref=o.innerType},cu=(t,e,n,r)=>{let o=t._zod.innerType;J(o,e,r);let s=e.seen.get(t);s.ref=o};var Zd=g("ZodISODateTime",(t,e)=>{wa.init(t,e),q.init(t,e)});function uu(t){return kc(Zd,t)}var jd=g("ZodISODate",(t,e)=>{_a.init(t,e),q.init(t,e)});function lu(t){return Dc(jd,t)}var Bd=g("ZodISOTime",(t,e)=>{xa.init(t,e),q.init(t,e)});function fu(t){return Rc(Bd,t)}var Ud=g("ZodISODuration",(t,e)=>{Sa.init(t,e),q.init(t,e)});function du(t){return Ic(Ud,t)}var Vd=(t,e)=>{qn.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>ei(t,n)},flatten:{value:n=>Xs(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,Et,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,Et,2)}},isEmpty:{get(){return t.issues.length===0}}})};var le=g("ZodError",Vd,{Parent:Error});var pu=Jn(le),mu=Kn(le),hu=cn(le),yu=un(le),gu=ri(le),bu=oi(le),wu=si(le),_u=ii(le),xu=ai(le),Su=ci(le),Au=ui(le),Eu=li(le);var vu=new WeakMap;function mn(t,e,n){let r=Object.getPrototypeOf(t),o=vu.get(r);if(o||(o=new Set,vu.set(r,o)),!o.has(e)){o.add(e);for(let s in n){let i=n[s];Object.defineProperty(r,s,{configurable:!0,enumerable:!1,get(){let a=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}var G=g("ZodType",(t,e)=>(U.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:pn(t,"input"),output:pn(t,"output")}}),t.toJSONSchema=Fc(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(n,r)=>pu(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>hu(t,n,r),t.parseAsync=async(n,r)=>mu(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>yu(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>gu(t,n,r),t.decode=(n,r)=>bu(t,n,r),t.encodeAsync=async(n,r)=>wu(t,n,r),t.decodeAsync=async(n,r)=>_u(t,n,r),t.safeEncode=(n,r)=>xu(t,n,r),t.safeDecode=(n,r)=>Su(t,n,r),t.safeEncodeAsync=async(n,r)=>Au(t,n,r),t.safeDecodeAsync=async(n,r)=>Eu(t,n,r),mn(t,"ZodType",{check(...n){let r=this.def;return this.clone(L.mergeDefs(r,{checks:[...r.checks??[],...n.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return we(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(Zp(n,r))},superRefine(n,r){return this.check(jp(n,r))},overwrite(n){return this.check(tt(n))},optional(){return Ou(this)},exactOptional(){return kp(this)},nullable(){return Cu(this)},nullish(){return Ou(Cu(this))},nonoptional(n){return Np(this,n)},array(){return V(this)},or(n){return Rt([this,n])},and(n){return xp(this,n)},transform(n){return Nu(this,Ep(n))},default(n){return Ip(this,n)},prefault(n){return Cp(this,n)},catch(n){return Tp(this,n)},pipe(n){return Nu(this,n)},readonly(){return Lp(this)},describe(n){let r=this.clone();return yt.add(r,{description:n}),r},meta(...n){if(n.length===0)return yt.get(this);let r=this.clone();return yt.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(t,"description",{get(){return yt.get(t)?.description},configurable:!0}),t)),$u=g("_ZodString",(t,e)=>{er.init(t,e),G.init(t,e),t._zod.processJSONSchema=(r,o,s)=>Zc(t,r,o,s);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,mn(t,"_ZodString",{regex(...r){return this.check(Oo(...r))},includes(...r){return this.check($o(...r))},startsWith(...r){return this.check(To(...r))},endsWith(...r){return this.check(zo(...r))},min(...r){return this.check(Dt(...r))},max(...r){return this.check(or(...r))},length(...r){return this.check(sr(...r))},nonempty(...r){return this.check(Dt(1,...r))},lowercase(r){return this.check(Co(r))},uppercase(r){return this.check(No(r))},trim(){return this.check(Lo())},normalize(...r){return this.check(Po(...r))},toLowerCase(){return this.check(Mo())},toUpperCase(){return this.check(Fo())},slugify(){return this.check(Zo())}})}),Jd=g("ZodString",(t,e)=>{er.init(t,e),$u.init(t,e),t.email=n=>t.check(sc(Kd,n)),t.url=n=>t.check(lc(Wd,n)),t.jwt=n=>t.check(vc(fp,n)),t.emoji=n=>t.check(fc(Yd,n)),t.guid=n=>t.check(Io(ku,n)),t.uuid=n=>t.check(ic(ar,n)),t.uuidv4=n=>t.check(ac(ar,n)),t.uuidv6=n=>t.check(cc(ar,n)),t.uuidv7=n=>t.check(uc(ar,n)),t.nanoid=n=>t.check(dc(Hd,n)),t.guid=n=>t.check(Io(ku,n)),t.cuid=n=>t.check(pc(Xd,n)),t.cuid2=n=>t.check(mc(ep,n)),t.ulid=n=>t.check(hc(tp,n)),t.base64=n=>t.check(Sc(cp,n)),t.base64url=n=>t.check(Ac(up,n)),t.xid=n=>t.check(yc(np,n)),t.ksuid=n=>t.check(gc(rp,n)),t.ipv4=n=>t.check(bc(op,n)),t.ipv6=n=>t.check(wc(sp,n)),t.cidrv4=n=>t.check(_c(ip,n)),t.cidrv6=n=>t.check(xc(ap,n)),t.e164=n=>t.check(Ec(lp,n)),t.datetime=n=>t.check(uu(n)),t.date=n=>t.check(lu(n)),t.time=n=>t.check(fu(n)),t.duration=n=>t.check(du(n))});function v(t){return oc(Jd,t)}var q=g("ZodStringFormat",(t,e)=>{Q.init(t,e),$u.init(t,e)}),Kd=g("ZodEmail",(t,e)=>{la.init(t,e),q.init(t,e)});var ku=g("ZodGUID",(t,e)=>{ca.init(t,e),q.init(t,e)});var ar=g("ZodUUID",(t,e)=>{ua.init(t,e),q.init(t,e)});var Wd=g("ZodURL",(t,e)=>{fa.init(t,e),q.init(t,e)});var Yd=g("ZodEmoji",(t,e)=>{da.init(t,e),q.init(t,e)});var Hd=g("ZodNanoID",(t,e)=>{pa.init(t,e),q.init(t,e)});var Xd=g("ZodCUID",(t,e)=>{ma.init(t,e),q.init(t,e)});var ep=g("ZodCUID2",(t,e)=>{ha.init(t,e),q.init(t,e)});var tp=g("ZodULID",(t,e)=>{ya.init(t,e),q.init(t,e)});var np=g("ZodXID",(t,e)=>{ga.init(t,e),q.init(t,e)});var rp=g("ZodKSUID",(t,e)=>{ba.init(t,e),q.init(t,e)});var op=g("ZodIPv4",(t,e)=>{Aa.init(t,e),q.init(t,e)});var sp=g("ZodIPv6",(t,e)=>{Ea.init(t,e),q.init(t,e)});var ip=g("ZodCIDRv4",(t,e)=>{va.init(t,e),q.init(t,e)});var ap=g("ZodCIDRv6",(t,e)=>{ka.init(t,e),q.init(t,e)});var cp=g("ZodBase64",(t,e)=>{Ra.init(t,e),q.init(t,e)});var up=g("ZodBase64URL",(t,e)=>{Ia.init(t,e),q.init(t,e)});var lp=g("ZodE164",(t,e)=>{Oa.init(t,e),q.init(t,e)});var fp=g("ZodJWT",(t,e)=>{Ca.init(t,e),q.init(t,e)});var Tu=g("ZodNumber",(t,e)=>{vo.init(t,e),G.init(t,e),t._zod.processJSONSchema=(r,o,s)=>jc(t,r,o,s),mn(t,"ZodNumber",{gt(r,o){return this.check(nr(r,o))},gte(r,o){return this.check(dn(r,o))},min(r,o){return this.check(dn(r,o))},lt(r,o){return this.check(tr(r,o))},lte(r,o){return this.check(fn(r,o))},max(r,o){return this.check(fn(r,o))},int(r){return this.check(Du(r))},safe(r){return this.check(Du(r))},positive(r){return this.check(nr(0,r))},nonnegative(r){return this.check(dn(0,r))},negative(r){return this.check(tr(0,r))},nonpositive(r){return this.check(fn(0,r))},multipleOf(r,o){return this.check(rr(r,o))},step(r,o){return this.check(rr(r,o))},finite(){return this}});let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function F(t){return Oc(Tu,t)}var dp=g("ZodNumberFormat",(t,e)=>{Na.init(t,e),Tu.init(t,e)});function Du(t){return Cc(dp,t)}var pp=g("ZodBoolean",(t,e)=>{$a.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Bc(t,n,r,o)});function nt(t){return Nc(pp,t)}var mp=g("ZodNull",(t,e)=>{Ta.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Uc(t,n,r,o)});function hp(t){return $c(mp,t)}var yp=g("ZodUnknown",(t,e)=>{za.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Gc(t,n,r,o)});function Ru(){return Tc(yp)}var gp=g("ZodNever",(t,e)=>{Pa.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Qc(t,n,r,o)});function zu(t){return zc(gp,t)}var bp=g("ZodArray",(t,e)=>{La.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Wc(t,n,r,o),t.element=e.element,mn(t,"ZodArray",{min(n,r){return this.check(Dt(n,r))},nonempty(n){return this.check(Dt(1,n))},max(n,r){return this.check(or(n,r))},length(n,r){return this.check(sr(n,r))},unwrap(){return this.element}})});function V(t,e){return Pc(bp,t,e)}var Pu=g("ZodObject",(t,e)=>{Za.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Yc(t,n,r,o),L.defineLazy(t,"shape",()=>e.shape),mn(t,"ZodObject",{keyof(){return ce(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:Ru()})},loose(){return this.clone({...this._zod.def,catchall:Ru()})},strict(){return this.clone({...this._zod.def,catchall:zu()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return L.extend(this,n)},safeExtend(n){return L.safeExtend(this,n)},merge(n){return L.merge(this,n)},pick(n){return L.pick(this,n)},omit(n){return L.omit(this,n)},partial(...n){return L.partial(Mu,this,n[0])},required(...n){return L.required(Fu,this,n[0])}})});function ye(t,e){let n={type:"object",shape:t??{},...L.normalizeParams(e)};return new Pu(n)}function C(t,e){return new Pu({type:"object",shape:t,catchall:zu(),...L.normalizeParams(e)})}var Lu=g("ZodUnion",(t,e)=>{ko.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Hc(t,n,r,o),t.options=e.options});function Rt(t,e){return new Lu({type:"union",options:t,...L.normalizeParams(e)})}var wp=g("ZodDiscriminatedUnion",(t,e)=>{Lu.init(t,e),ja.init(t,e)});function It(t,e,n){return new wp({type:"union",options:e,discriminator:t,...L.normalizeParams(n)})}var _p=g("ZodIntersection",(t,e)=>{Ba.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Xc(t,n,r,o)});function xp(t,e){return new _p({type:"intersection",left:t,right:e})}var Iu=g("ZodRecord",(t,e)=>{Ua.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>eu(t,n,r,o),t.keyType=e.keyType,t.valueType=e.valueType});function _e(t,e,n){return!e||!e._zod?new Iu({type:"record",keyType:v(),valueType:t,...L.normalizeParams(e)}):new Iu({type:"record",keyType:t,valueType:e,...L.normalizeParams(n)})}var Go=g("ZodEnum",(t,e)=>{Qa.init(t,e),G.init(t,e),t._zod.processJSONSchema=(r,o,s)=>Vc(t,r,o,s),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(r,o)=>{let s={};for(let i of r)if(n.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Go({...e,checks:[],...L.normalizeParams(o),entries:s})},t.exclude=(r,o)=>{let s={...e.entries};for(let i of r)if(n.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Go({...e,checks:[],...L.normalizeParams(o),entries:s})}});function ce(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new Go({type:"enum",entries:n,...L.normalizeParams(e)})}var Sp=g("ZodLiteral",(t,e)=>{Ga.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>qc(t,n,r,o),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function Z(t,e){return new Sp({type:"literal",values:Array.isArray(t)?t:[t],...L.normalizeParams(e)})}var Ap=g("ZodTransform",(t,e)=>{Va.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Kc(t,n,r,o),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new St(t.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(L.issue(s,n.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),n.issues.push(L.issue(i))}};let o=e.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n.fallback=!0,n)):(n.value=o,n.fallback=!0,n)}});function Ep(t){return new Ap({type:"transform",transform:t})}var Mu=g("ZodOptional",(t,e)=>{Do.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Qo(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Ou(t){return new Mu({type:"optional",innerType:t})}var vp=g("ZodExactOptional",(t,e)=>{qa.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Qo(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function kp(t){return new vp({type:"optional",innerType:t})}var Dp=g("ZodNullable",(t,e)=>{Ja.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>tu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Cu(t){return new Dp({type:"nullable",innerType:t})}var Rp=g("ZodDefault",(t,e)=>{Ka.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ru(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Ip(t,e){return new Rp({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():L.shallowClone(e)}})}var Op=g("ZodPrefault",(t,e)=>{Wa.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ou(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Cp(t,e){return new Op({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():L.shallowClone(e)}})}var Fu=g("ZodNonOptional",(t,e)=>{Ya.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>nu(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Np(t,e){return new Fu({type:"nonoptional",innerType:t,...L.normalizeParams(e)})}var $p=g("ZodCatch",(t,e)=>{Ha.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>su(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Tp(t,e){return new $p({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var zp=g("ZodPipe",(t,e)=>{Xa.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>iu(t,n,r,o),t.in=e.in,t.out=e.out});function Nu(t,e){return new zp({type:"pipe",in:t,out:e})}var Pp=g("ZodReadonly",(t,e)=>{ec.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>au(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Lp(t){return new Pp({type:"readonly",innerType:t})}var Mp=g("ZodLazy",(t,e)=>{tc.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>cu(t,n,r,o),t.unwrap=()=>t._zod.def.getter()});function Vo(t){return new Mp({type:"lazy",getter:t})}var Fp=g("ZodCustom",(t,e)=>{nc.init(t,e),G.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Jc(t,n,r,o)});function Zp(t,e={}){return Lc(Fp,t,e)}function jp(t,e){return Mc(t,e)}function rt(t){let e=Vo(()=>Rt([v(t),F(),nt(),hp(),V(e),_e(v(),e)]));return e}var Zu=t=>"field"in t?[t]:("all"in t?t.all:t.any).flatMap(Zu),hn=t=>Zu(t);var Ot=(t,e)=>{if("field"in t)return e(t);let n="all"in t?t.all:t.any,r=!1;if("all"in t){for(let o of n){let s=Ot(o,e);if(s===!1)return!1;r||=s===void 0}return r?void 0:!0}for(let o of n){let s=Ot(o,e);if(s===!0)return!0;r||=s===void 0}return r?void 0:!1},ju=t=>JSON.stringify(t),qo=t=>{if("field"in t)return{conditions:1,depth:0};let e="all"in t?t.all:t.any,n=0,r=1;for(let o of e){let s=qo(o);n+=s.conditions,r=Math.max(r,s.depth+1)}return{conditions:n,depth:r}},Bu=(t,e={})=>{let n=o=>{let s=V(o),i=e.maximumChildren===void 0?s:s.max(e.maximumChildren);return Rt([t,C({all:i}),C({any:i})])},r=Vo(()=>n(r));return e.maximumConditions===void 0&&e.maximumDepth===void 0?r:r.superRefine((o,s)=>{let{conditions:i,depth:a}=qo(o);e.maximumConditions!==void 0&&i>e.maximumConditions&&s.addIssue({code:"custom",message:e.maximumConditionsMessage??"Query exceeds the condition limit"}),e.maximumDepth!==void 0&&a>e.maximumDepth&&s.addIssue({code:"custom",message:e.maximumDepthMessage??"Query exceeds the nesting limit"})})};var R={requestBytes:524288,filterCount:32,filterDepth:8,sortCount:8,outputFieldCount:256,fieldPathDepth:9,defaultResultCount:20,resultCount:1e3,resultBytes:16777216,candidateDocuments:1e3,databaseBytes:512e3,frontmatterBytes:65536,frontmatterDepth:8,frontmatterFields:256,frontmatterStringBytes:16384,jsonBytes:1048576,jsonDepth:8,jsonFields:256,jsonStringBytes:16384,indexedPropertiesBytes:65536,excerptBytes:2048,hydratedFileBytes:1048576,hydratedTotalBytes:2097152,hydratedFileCount:20,hydratedRangeBytes:262144,concurrentContentReads:8};function gt(t,e=new Set){if(typeof t=="number"&&isNaN(t))throw new Error("NaN is not allowed");if(typeof t=="number"&&!isFinite(t))throw new Error("Infinity is not allowed");if(t===null||typeof t!="object")return JSON.stringify(t);if(typeof t.toJSON=="function"){if(e.has(t))throw new Error("Circular reference detected");e.add(t);let r=gt(t.toJSON(),e);return e.delete(t),r}if(e.has(t))throw new Error("Circular reference detected");e.add(t);let n;if(Array.isArray(t))n=`[${t.map(o=>gt(o===void 0||typeof o=="symbol"?null:o,e)).join(",")}]`;else{let r=[];for(let o of Object.keys(t).sort())t[o]===void 0||typeof t[o]=="symbol"||r.push(`${gt(o)}:${gt(t[o],e)}`);n=`{${r.join(",")}}`}return e.delete(t),n}var Bp=new TextEncoder,Ct=t=>Bp.encode(t),$e=t=>Ct(t).byteLength,re=class extends Error{constructor(){super("Byte stream exceeds the configured limit"),this.name="ByteLimitExceededError"}},Up=(t,e)=>{let n=new Uint8Array(e),r=0;for(let o of t)n.set(o,r),r+=o.byteLength;return n},Nt=t=>typeof t=="string"?{async*[Symbol.asyncIterator](){yield Ct(t)}}:t instanceof Uint8Array?{async*[Symbol.asyncIterator](){yield t}}:t,Jo=async(t,e)=>{let n=[],r=0;for await(let o of Nt(t)){let s=e-r;if(s<=0)break;let i=o.subarray(0,s);if(n.push(i),r+=i.byteLength,r===e)break}return Up(n,r)},Te=async(t,e)=>{let n=await Jo(t,e+1);if(n.byteLength>e)throw new re;return n},fe=t=>new TextDecoder("utf-8",{fatal:!0}).decode(t),$t=t=>t.charCodeAt(0)===65279?t.slice(1):t;var Uu=t=>{for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n>=55296&&n<=56319){let r=t.charCodeAt(e+1);if(e+1>=t.length||r<56320||r>57343)throw new Error("JSON strings cannot contain lone Unicode surrogates");e+=1;continue}if(n>=56320&&n<=57343)throw new Error("JSON strings cannot contain lone Unicode surrogates")}},Ko=(t,e)=>{if(t===null||typeof t=="boolean")return t;if(typeof t=="string")return Uu(t),t;if(typeof t=="number"){if(Number.isFinite(t)===!1)throw new Error("JSON cannot contain non-finite numbers");return t}if(Array.isArray(t)){if(Object.getOwnPropertySymbols(t).length>0)throw new Error("JSON arrays cannot contain symbol properties");if(e.has(t))throw new Error("JSON cannot contain circular references");e.add(t);try{let n=[];for(let r=0;r<t.length;r+=1){if(Object.hasOwn(t,r)===!1)throw new Error("JSON arrays cannot be sparse");let o=t[r];if(o===void 0)throw new Error("JSON arrays cannot contain undefined values");n.push(Ko(o,e))}if(Object.keys(t).length!==t.length)throw new Error("JSON arrays cannot contain named properties");return n}finally{e.delete(t)}}if(typeof t=="object"){let n=Object.getPrototypeOf(t);if(n!==Object.prototype&&n!==null)throw new Error("JSON can contain only plain objects");if(Object.getOwnPropertySymbols(t).length>0)throw new Error("JSON objects cannot contain symbol properties");if(e.has(t))throw new Error("JSON cannot contain circular references");e.add(t);let r={};try{for(let[o,s]of Object.entries(t))Uu(o),s!==void 0&&Object.defineProperty(r,o,{value:Ko(s,e),enumerable:!0,configurable:!0,writable:!0})}finally{e.delete(t)}return r}throw new Error("Value cannot be represented as JSON")},ot=t=>Ko(t,new Set),de=t=>{let e=gt(ot(t));if(e===void 0)throw new Error("Value cannot be represented as canonical JSON");return e},yn=(t,e)=>t===void 0||e===void 0?t===e:de(t)===de(e),ze=(t,e)=>t<e?-1:t>e?1:0,Wo=async t=>{let e=typeof t=="string"?Ct(t):t,n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")},Qu=async t=>`sha256:${await Wo(t)}`;var Gu=It("type",[C({type:Z("document")}),C({type:Z("json"),path:V(v()).min(1)}),C({type:Z("markdown-body")}),C({type:Z("markdown-frontmatter")})]),Yo=C({documentId:v().min(1),revision:v().min(1),representation:Gu}),Qp=t=>{let e=Gu.parse(t);return e.type==="json"?Object.freeze({...e,path:Object.freeze([...e.path])}):Object.freeze(e)},Vu=t=>{let e=Yo.parse(t);return Object.freeze({...e,representation:Qp(e.representation)})};var cr=C({id:v().min(1),revision:v().min(1),contentRef:v().min(1),format:ce(["json","markdown"]).optional()}),ur=C({sourceId:v().min(1),referenceId:v().min(1),reference:Yo});var Tt=t=>{let e=new Map;for(let n of t){let r=e.get(n.sourceId)??[];r.push(n),e.set(n.sourceId,r)}return e};var Pe=class extends Error{code;documentIds;constructor({code:e,message:n,documentIds:r=[]}){super(n),this.name="DocumentGraphError",this.code=e,this.documentIds=Object.freeze([...r])}},Gp=(t,e)=>ze(t.sourceId,e.sourceId)||ze(t.referenceId,e.referenceId),gn=({nodes:t,edges:e})=>{let n=t.map(a=>Object.freeze(cr.parse(a))).sort((a,c)=>ze(a.id,c.id)),r=new Map,o=new Map;for(let a of n){if(r.has(a.id))throw new Pe({code:"DUPLICATE_NODE",message:`Document graph contains duplicate node ${a.id}`,documentIds:[a.id]});r.set(a.id,a);let c=o.get(a.contentRef);if(c!==void 0&&(c.revision!==a.revision||c.format!==a.format))throw new Pe({code:"CONTENT_IDENTITY_CONFLICT",message:`Document graph content reference ${a.contentRef} has conflicting identities`,documentIds:[c.id,a.id]});o.set(a.contentRef,a)}let s=e.map(a=>{let c=ur.parse(a);return Object.freeze({...c,reference:Vu(c.reference)})}).sort(Gp),i=new Set;for(let a of s){if(r.get(a.sourceId)===void 0)throw new Pe({code:"SOURCE_NOT_FOUND",message:`Document graph source ${a.sourceId} does not exist`,documentIds:[a.sourceId]});let u=r.get(a.reference.documentId);if(u===void 0)throw new Pe({code:"TARGET_NOT_FOUND",message:`Document graph target ${a.reference.documentId} does not exist`,documentIds:[a.sourceId,a.reference.documentId]});if(u.revision!==a.reference.revision)throw new Pe({code:"TARGET_REVISION_MISMATCH",message:`Document graph target ${u.id} revision does not match its reference`,documentIds:[a.sourceId,u.id]});let d=`${a.sourceId}\0${a.referenceId}`;if(i.has(d))throw new Pe({code:"DUPLICATE_REFERENCE",message:`Document ${a.sourceId} contains duplicate reference ID ${a.referenceId}`,documentIds:[a.sourceId]});i.add(d)}return Object.freeze({nodes:Object.freeze(n),edges:Object.freeze(s)})},Vp=t=>new Map(t.nodes.map(e=>[e.id,e]));var lr=({graph:t,rootIds:e})=>{let n=Vp(t),r=Tt(t.edges),o=new Map,s=[],i=[],a=c=>{let u=n.get(c);if(u===void 0)throw new Pe({code:"ROOT_NOT_FOUND",message:`Document graph root ${c} does not exist`,documentIds:[c]});let d=o.get(c);if(d!=="visited"){if(d==="visiting"){let l=s.indexOf(c),f=[...s.slice(l),c];throw new Pe({code:"CYCLE",message:`Document graph contains a cycle: ${f.join(" -> ")}`,documentIds:f})}o.set(c,"visiting"),s.push(c);for(let l of r.get(c)??[])a(l.reference.documentId);s.pop(),o.set(c,"visited"),i.push(u)}};for(let c of[...new Set(e)].sort(ze))a(c);return Object.freeze(i)};var qp=v().regex(/^sha256:[a-f0-9]{64}$/),qu=C({format:Z("webstudio-document-graph"),version:Z(1),nodes:V(cr),edges:V(ur),integrity:C({algorithm:Z("sha256"),checksum:qp})});var Jp=v().min(1).refine(t=>t.startsWith("/")===!1,{error:"Asset path must be relative"}).refine(t=>t.includes("\\")===!1&&t.split("/").every(e=>e.length>0&&e!==".."&&e!=="."),{error:"Asset path must be normalized and must not contain dot segments"}),Wu=C({_id:v().min(1),_type:Z("asset.file"),name:v().min(1),description:v().optional(),path:Jp,key:v(),folderId:v().min(1).optional(),extension:v().regex(/^[a-z0-9]*$/),mimeType:v().min(1),size:F().int().nonnegative(),createdAt:v().datetime().optional(),revision:v().min(1),contentRef:v().min(1),properties:_e(v(),rt()),excerpt:v().optional(),metadataError:C({code:v().min(1),message:v().min(1)}).optional()}),Xo=Wu.partial().required({_id:!0}),Kp=ce(["null","boolean","number","string","object","array"]),Wp=ye({format:Z("webstudio-builder-asset-field-catalog"),version:Z(1),canonicalRevision:v().regex(/^sha256:[a-f0-9]{64}$/),documentCount:F().int().nonnegative(),fields:_e(v().min(1),ye({queryPath:V(v().min(1)).min(1).max(R.fieldPathDepth).optional(),types:V(Kp).min(1),occurrences:F().int().positive(),optional:Z(!0).optional(),mixed:Z(!0).optional()}))}).superRefine((t,e)=>{for(let[n,r]of Object.entries(t.fields)){let o=[...new Set(r.types)].sort();JSON.stringify(r.types)!==JSON.stringify(o)&&e.addIssue({code:"custom",path:["fields",n,"types"],message:"Observed field types must be unique and sorted"}),r.occurrences>t.documentCount&&e.addIssue({code:"custom",path:["fields",n,"occurrences"],message:"Field occurrences cannot exceed the document count"});let s=r.occurrences<t.documentCount;r.optional===!0!==s&&e.addIssue({code:"custom",path:["fields",n,"optional"],message:"Field optionality must match its occurrence count"});let i=o.length>1;r.mixed===!0!==i&&e.addIssue({code:"custom",path:["fields",n,"mixed"],message:"Mixed status must match the observed types"})}}),fr=v().regex(/^sha256:[a-f0-9]{64}$/),Yu=C({fields:V(V(v().min(1)).min(1).max(R.fieldPathDepth)).min(1).max(R.outputFieldCount+1),rows:V(V(rt())).max(R.resultCount),totalCount:F().int().nonnegative().max(R.candidateDocuments),hasMore:nt()}).superRefine(({fields:t,rows:e},n)=>{for(let[r,o]of e.entries())o.length!==t.length&&n.addIssue({code:"custom",path:["rows",r],message:"Materialized query rows must match the field count"})}),Ju=C({format:Z("webstudio-content-database"),version:Z(1),assetRevision:fr,documents:V(Xo),documentGraph:qu.optional(),contents:_e(v().min(1),v()).optional(),assetReferences:_e(v().min(1),V(C({start:F().int().nonnegative(),end:F().int().positive(),assetId:v().min(1),suffix:v().min(1).optional()}).refine(({start:t,end:e})=>e>t,{message:"Markdown asset reference range must not be empty"}))).optional(),assetValueReferences:_e(v().min(1),V(C({path:V(v().min(1).or(F().int().nonnegative())).min(1),assetId:v().min(1),suffix:v().min(1).optional()}))).optional(),fieldCatalog:Wp,queries:_e(fr,Yu).optional(),database:C({maxBytes:F().int().positive(),unboundedBytes:F().int().nonnegative(),sourceDocumentCount:F().int().nonnegative(),includedDocumentCount:F().int().nonnegative().optional()}).optional(),integrity:C({algorithm:Z("sha256"),checksum:fr})}).superRefine((t,e)=>{t.documents.length>R.candidateDocuments&&e.addIssue({code:"custom",path:["documents"],message:"Asset index exceeds the document limit"}),(t.fieldCatalog.canonicalRevision!==t.assetRevision||t.fieldCatalog.documentCount!==t.documents.length)&&e.addIssue({code:"custom",path:["fieldCatalog"],message:"Asset index field catalog does not match its documents"}),t.database!==void 0&&t.database.sourceDocumentCount<t.documents.length&&e.addIssue({code:"custom",path:["database","sourceDocumentCount"],message:"Source document count cannot be smaller than the database"}),t.database?.includedDocumentCount!==void 0&&(t.database.includedDocumentCount<t.documents.length||t.database.includedDocumentCount>t.database.sourceDocumentCount)&&e.addIssue({code:"custom",path:["database","includedDocumentCount"],message:"Included document count must match the database bounds"});let n;for(let[o,s]of t.documents.entries())n!==void 0&&s._id<=n&&e.addIssue({code:"custom",path:["documents",o,"_id"],message:"Asset index documents must have unique sorted IDs"}),n=s._id;let r=new Set(t.documents.flatMap(({contentRef:o})=>o===void 0?[]:[o]));for(let o of Object.keys(t.contents??{}))r.has(o)===!1&&e.addIssue({code:"custom",path:["contents",o],message:"Embedded content must belong to an indexed document"});for(let o of Object.keys(t.assetReferences??{}))r.has(o)===!1&&e.addIssue({code:"custom",path:["assetReferences",o],message:"Asset references must belong to an indexed document"})}),Yp=It("mode",[ye({mode:Z("none")}),ye({mode:Z("full"),maxBytes:F().int().positive().max(R.hydratedFileBytes).optional()}),ye({mode:Z("range"),offset:F().int().nonnegative(),length:F().int().positive().max(R.hydratedRangeBytes)}),ye({mode:Z("markdown-body-ref"),maxBytes:F().int().positive().max(R.hydratedFileBytes).optional()})]),es={id:["string"],url:["string"],width:["number"],height:["number"],name:["string"],description:["string"],path:["string"],key:["string"],folderId:["string"],extension:["string"],mimeType:["string"],size:["number"],createdAt:["string"],revision:["string"],excerpt:["string"]},Hu=Object.keys(es),Xu=["url","width","height"],dr=t=>Xu.includes(t),el=Hu.filter(t=>dr(t)===!1&&t!=="excerpt"),tl=el.filter(t=>t!=="id"),nl=t=>el.includes(t),Hp=ce(Hu),bn=V(v().min(1)).min(1).max(R.fieldPathDepth).superRefine((t,e)=>{if(t[0]==="properties"){t.length<2&&e.addIssue({code:"custom",message:"A properties field path must select a property"});return}(t.length!==1||Hp.safeParse(t[0]).success===!1)&&e.addIssue({code:"custom",message:"Asset query field path is unsupported"})}),Ho=nt().default(!0),Xp=It("mode",[C({mode:Z("all"),includeMetadata:Ho}),C({mode:Z("base"),includeMetadata:Ho}),C({mode:Z("fields"),includeMetadata:Ho,fields:V(bn).max(R.outputFieldCount).refine(t=>new Set(t.map(ju)).size===t.length,{error:"Selected output fields must be unique"})})]),em={mode:"fields",includeMetadata:!1,fields:Xu.map(t=>[t])},rl=["eq","ne","contains","startsWith","endsWith","gt","gte","lt","lte"],_b=[...rl,"in","exists","isEmpty"],tm=C({field:bn,operator:ce(rl),value:rt()}),nm=C({field:bn,operator:Z("in"),value:V(rt()).max(R.resultCount)}),rm=C({field:bn,operator:ce(["exists","isEmpty"]),value:nt()}),om=It("operator",[tm,nm,rm]),sm=Bu(om,{maximumChildren:R.filterCount,maximumConditions:R.filterCount,maximumDepth:R.filterDepth,maximumConditionsMessage:"Asset query exceeds the filter limit",maximumDepthMessage:"Asset query exceeds the filter nesting limit"});var im=sm,ol=t=>{let e=new Set(["eq","ne","in","exists"]);return t.some(n=>n==="string"||n==="array")&&e.add("contains"),t.includes("string")&&(e.add("startsWith"),e.add("endsWith")),t.some(n=>n==="string"||n==="number")&&(e.add("gt"),e.add("gte"),e.add("lt"),e.add("lte")),t.some(n=>n==="string"||n==="array"||n==="object")&&e.add("isEmpty"),[...e]},am=C({field:bn,direction:ce(["asc","desc"])}),cm=ce(["many","one","first","last"]),um=({output:t,content:e})=>t.includeMetadata||t.mode==="all"||t.mode==="fields"&&t.fields.length>0||e.mode!=="none",st=C({result:cm.default("many"),where:im.default({all:[]}),sort:V(am).max(R.sortCount).default([]),limit:F().int().nonnegative().max(R.resultCount).default(R.defaultResultCount),offset:F().int().nonnegative().max(R.candidateDocuments).default(0),output:Xp.default(em),content:Yp.default({mode:"none"})}).superRefine((t,e)=>{um(t)===!1&&e.addIssue({code:"custom",message:"Select at least one asset query output"}),(t.result==="first"||t.result==="last")&&t.sort.length===0&&e.addIssue({code:"custom",path:["sort"],message:"Add sorting to define which item is first."})}),sl=C({query:st,indexRevision:v().min(1).max(255).optional()}),lm=ye({_id:v().min(1),revision:v().min(1),contentRef:v().min(1),encoding:Z("utf-8"),text:v(),range:ye({offset:F().int().nonnegative(),length:F().int().nonnegative(),total:F().int().nonnegative()}).optional()}),fm=lm.omit({_id:!0,revision:!0,contentRef:!0}),il=Wu.omit({_id:!0,_type:!0,contentRef:!0}).partial().extend({id:v().min(1),url:v().min(1).optional(),width:F().positive().optional(),height:F().positive().optional(),content:fm.optional()}).refine(t=>t.width===void 0==(t.height===void 0),{error:"Asset dimensions must include both width and height"}),dm=C({format:Z("webstudio-content-database"),version:Z(1),revision:fr,usedBytes:F().int().nonnegative(),maxBytes:F().int().positive(),unboundedBytes:F().int().nonnegative(),includedDocumentCount:F().int().nonnegative(),omittedDocumentCount:F().int().nonnegative(),omissionReason:ce(["size","unavailable"]).optional(),truncated:nt()}),Ku=dm.pick({usedBytes:!0,maxBytes:!0,unboundedBytes:!0,includedDocumentCount:!0,omittedDocumentCount:!0,omissionReason:!0,truncated:!0}),ts=C({items:V(il),totalCount:F().int().nonnegative(),hasMore:nt()}),pm=C({item:il.nullable(),totalCount:F().int().nonnegative()}),al=Rt([ts,pm]),mm=C({scope:Z("query-preview"),query:Ku,database:Ku,artifacts:C({query:Ju,database:Ju}).optional(),unresolved:al.optional()}),xb=C({data:al,__diagnostics__:mm}),hm=ce(["INVALID_REQUEST","REQUEST_CANCELLED","UNAUTHORIZED","FORBIDDEN","STALE_INDEX","CONTENT_IDENTITY_REQUIRED","CONTENT_NOT_TEXT","CONTENT_DECODING_FAILED","CONTENT_LIMIT_EXCEEDED","MULTIPLE_RESULTS","INTERNAL_ERROR"]),ym=ye({ok:Z(!1),error:ye({code:hm,message:v().min(1),retryable:nt(),details:_e(v(),rt()).optional()}),meta:ye({queryHash:v().min(1).optional(),indexRevision:v().min(1).optional(),assetRevision:v().min(1).optional()}).optional()}),cl=({code:t,message:e,retryable:n=!1,details:r})=>ym.parse({ok:!1,error:{code:t,message:e,retryable:n,details:r}});var ul=function*(t){if(t.length>0&&!t.startsWith("/")||/~(?![01])/.test(t))throw Error("Invalid JSON Pointer");let e=1,n=0;for(;n<t.length;){let r=t.indexOf("/",e);n=r===-1?t.length:r;let o=t.slice(e,n);e=n+1,yield bm(o)}};var ns=(t,e)=>e+"/"+gm(t),gm=t=>t.toString().replace(/~/g,"~0").replace(/\//g,"~1"),bm=t=>t.toString().replace(/~1/g,"/").replace(/~0/g,"~");var pr=async(t,e,n)=>{if(Number.isSafeInteger(e)===!1||e<=0)throw new Error("Concurrency must be a positive safe integer");let r=0,o=new Array(t.length),s=async()=>{for(;r<t.length;){let u=r;r+=1,o[u]=await n(t[u])}},i=Array.from({length:Math.min(e,t.length)},s),c=(await Promise.allSettled(i)).find(u=>u.status==="rejected");if(c!==void 0)throw c.reason;return o};var zt=t=>typeof t=="object"&&t!==null&&Array.isArray(t)===!1,ll=t=>{if(zt(t)===!1)return;let e=Object.keys(t);if(!(e.length!==1||e[0]!=="$ref"))return t.$ref};var pe=class extends Error{code;referenceId;constructor({code:e,message:n,referenceId:r,cause:o}){super(n,{cause:o}),this.name="JsonDocumentError",this.code=e,this.referenceId=r}},wm=(t,e)=>{let n=ll(t);if(n!==void 0){if(typeof n!="string")throw new pe({code:"INVALID_REFERENCE_MARKER",message:`JSON reference marker ${e} must contain a string $ref`,referenceId:e});return n}},_m=t=>`#${t}`;var fl=async({source:t,maximumBytes:e=R.hydratedFileBytes})=>{let n;try{n=await Te(t,e)}catch(o){throw o instanceof re?new pe({code:"CONTENT_LIMIT_EXCEEDED",message:"JSON document exceeds the byte limit",cause:o}):o}let r;try{r=$t(fe(n))}catch(o){throw new pe({code:"CONTENT_DECODING_FAILED",message:"JSON document is not valid UTF-8",cause:o})}try{return ot(JSON.parse(r))}catch(o){throw new pe({code:"INVALID_DOCUMENT",message:"JSON document is invalid",cause:o})}};var xm=(t,e)=>{let n=t;for(let r of e){if(Array.isArray(n)){let o=Number(r);if(Number.isSafeInteger(o)===!1||o<0||String(o)!==r||o>=n.length)return;n=n[o];continue}if(zt(n)&&Object.hasOwn(n,r)){n=n[r];continue}return}return n},dl=({document:t,representation:e})=>{let n=ot(t);if(e.type==="document")return n;if(e.type!=="json")throw new pe({code:"UNSUPPORTED_REPRESENTATION",message:`JSON documents do not support ${e.type}`});let r=xm(n,e.path);if(r===void 0)throw new pe({code:"JSON_PATH_NOT_FOUND",message:"JSON document path does not exist"});return r},Sm=(t,e,n)=>{Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0})},mr=({document:t,references:e,allowUnresolvedReferences:n=!1})=>{let r=ot(t),o=new Set,s=(a,c)=>{let u=_m(c);if(wm(a,u)!==void 0){if(e.has(u)===!1){if(n)return a;throw new pe({code:"REFERENCE_NOT_FOUND",message:`Resolved JSON reference ${u} is unavailable`,referenceId:u})}o.add(u);try{return ot(e.get(u))}catch(l){throw new pe({code:"INVALID_RESOLVED_VALUE",message:`Resolved JSON reference ${u} is not JSON-compatible`,referenceId:u,cause:l})}}if(Array.isArray(a))return a.map((l,f)=>s(l,ns(String(f),c)));if(zt(a)){let l={};for(let[f,p]of Object.entries(a))Sm(l,f,s(p,ns(f,c)));return l}return a},i=s(r,"");for(let a of[...e.keys()].sort())if(o.has(a)===!1)throw new pe({code:"UNUSED_REFERENCE",message:`Resolved JSON reference ${a} has no marker`,referenceId:a});return i};var hr=Symbol.for("yaml.alias"),yr=Symbol.for("yaml.document"),xe=Symbol.for("yaml.map"),rs=Symbol.for("yaml.pair"),me=Symbol.for("yaml.scalar"),qe=Symbol.for("yaml.seq"),oe=Symbol.for("yaml.node.type"),Se=t=>!!t&&typeof t=="object"&&t[oe]===hr,Le=t=>!!t&&typeof t=="object"&&t[oe]===yr,Ae=t=>!!t&&typeof t=="object"&&t[oe]===xe,T=t=>!!t&&typeof t=="object"&&t[oe]===rs,N=t=>!!t&&typeof t=="object"&&t[oe]===me,Ee=t=>!!t&&typeof t=="object"&&t[oe]===qe;function j(t){if(t&&typeof t=="object")switch(t[oe]){case xe:case qe:return!0}return!1}function P(t){if(t&&typeof t=="object")switch(t[oe]){case hr:case xe:case me:case qe:return!0}return!1}var gr=t=>(N(t)||j(t))&&!!t.anchor;var ue=Symbol("break visit"),pl=Symbol("skip children"),Me=Symbol("remove node");function Fe(t,e){let n=ml(e);Le(t)?Pt(null,t.contents,n,Object.freeze([t]))===Me&&(t.contents=null):Pt(null,t,n,Object.freeze([]))}Fe.BREAK=ue;Fe.SKIP=pl;Fe.REMOVE=Me;function Pt(t,e,n,r){let o=hl(t,e,n,r);if(P(o)||T(o))return yl(t,r,o),Pt(t,o,n,r);if(typeof o!="symbol"){if(j(e)){r=Object.freeze(r.concat(e));for(let s=0;s<e.items.length;++s){let i=Pt(s,e.items[s],n,r);if(typeof i=="number")s=i-1;else{if(i===ue)return ue;i===Me&&(e.items.splice(s,1),s-=1)}}}else if(T(e)){r=Object.freeze(r.concat(e));let s=Pt("key",e.key,n,r);if(s===ue)return ue;s===Me&&(e.key=null);let i=Pt("value",e.value,n,r);if(i===ue)return ue;i===Me&&(e.value=null)}}return o}async function br(t,e){let n=ml(e);Le(t)?await Lt(null,t.contents,n,Object.freeze([t]))===Me&&(t.contents=null):await Lt(null,t,n,Object.freeze([]))}br.BREAK=ue;br.SKIP=pl;br.REMOVE=Me;async function Lt(t,e,n,r){let o=await hl(t,e,n,r);if(P(o)||T(o))return yl(t,r,o),Lt(t,o,n,r);if(typeof o!="symbol"){if(j(e)){r=Object.freeze(r.concat(e));for(let s=0;s<e.items.length;++s){let i=await Lt(s,e.items[s],n,r);if(typeof i=="number")s=i-1;else{if(i===ue)return ue;i===Me&&(e.items.splice(s,1),s-=1)}}}else if(T(e)){r=Object.freeze(r.concat(e));let s=await Lt("key",e.key,n,r);if(s===ue)return ue;s===Me&&(e.key=null);let i=await Lt("value",e.value,n,r);if(i===ue)return ue;i===Me&&(e.value=null)}}return o}function ml(t){return typeof t=="object"&&(t.Collection||t.Node||t.Value)?Object.assign({Alias:t.Node,Map:t.Node,Scalar:t.Node,Seq:t.Node},t.Value&&{Map:t.Value,Scalar:t.Value,Seq:t.Value},t.Collection&&{Map:t.Collection,Seq:t.Collection},t):t}function hl(t,e,n,r){if(typeof n=="function")return n(t,e,r);if(Ae(e))return n.Map?.(t,e,r);if(Ee(e))return n.Seq?.(t,e,r);if(T(e))return n.Pair?.(t,e,r);if(N(e))return n.Scalar?.(t,e,r);if(Se(e))return n.Alias?.(t,e,r)}function yl(t,e,n){let r=e[e.length-1];if(j(r))r.items[t]=n;else if(T(r))t==="key"?r.key=n:r.value=n;else if(Le(r))r.contents=n;else{let o=Se(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}var Am={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Em=t=>t.replace(/[!,[\]{}]/g,e=>Am[e]),Ze=class t{constructor(e,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,n)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,n){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let r=e.trim().split(/[ \t]+/),o=r.shift();switch(o){case"%TAG":{if(r.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[s,i]=r;return this.tags[s]=i,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[s]=r;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let i=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,i),!1}}default:return n(0,`Unknown directive ${o}`,!0),!1}}tagName(e,n){if(e==="!")return"!";if(e[0]!=="!")return n(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let i=e.slice(2,-1);return i==="!"||i==="!!"?(n(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&n("Verbatim tags must end with a >"),i)}let[,r,o]=e.match(/^(.*!)([^!]*)$/s);o||n(`The ${e} tag has no suffix`);let s=this.tags[r];if(s)try{return s+decodeURIComponent(o)}catch(i){return n(String(i)),null}return r==="!"?e:(n(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[n,r]of Object.entries(this.tags))if(e.startsWith(r))return n+Em(e.substring(r.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),o;if(e&&r.length>0&&P(e.contents)){let s={};Fe(e.contents,(i,a)=>{P(a)&&a.tag&&(s[a.tag]=!0)}),o=Object.keys(s)}else o=[];for(let[s,i]of r)s==="!!"&&i==="tag:yaml.org,2002:"||(!e||o.some(a=>a.startsWith(i)))&&n.push(`%TAG ${s} ${i}`);return n.join(`-`)}};Ze.defaultYaml={explicit:!1,version:"1.2"};Ze.defaultTags={"!!":"tag:yaml.org,2002:"};function wr(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(n)}return!0}function os(t){let e=new Set;return Fe(t,{Value(n,r){r.anchor&&e.add(r.anchor)}}),e}function ss(t,e){for(let n=1;;++n){let r=`${t}${n}`;if(!e.has(r))return r}}function gl(t,e){let n=[],r=new Map,o=null;return{onAnchor:s=>{n.push(s),o??(o=os(t));let i=ss(e,o);return o.add(i),i},setAnchors:()=>{for(let s of n){let i=r.get(s);if(typeof i=="object"&&i.anchor&&(N(i.node)||j(i.node)))i.node.anchor=i.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:r}}function it(t,e,n,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let o=0,s=r.length;o<s;++o){let i=r[o],a=it(t,r,String(o),i);a===void 0?delete r[o]:a!==i&&(r[o]=a)}else if(r instanceof Map)for(let o of Array.from(r.keys())){let s=r.get(o),i=it(t,r,o,s);i===void 0?r.delete(o):i!==s&&r.set(o,i)}else if(r instanceof Set)for(let o of Array.from(r)){let s=it(t,r,o,o);s===void 0?r.delete(o):s!==o&&(r.delete(o),r.add(s))}else for(let[o,s]of Object.entries(r)){let i=it(t,r,o,s);i===void 0?delete r[o]:i!==s&&(r[o]=i)}return t.call(e,n,r)}function Y(t,e,n){if(Array.isArray(t))return t.map((r,o)=>Y(r,String(o),n));if(t&&typeof t.toJSON=="function"){if(!n||!gr(t))return t.toJSON(e,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(t,r),n.onCreate=s=>{r.res=s,delete n.onCreate};let o=t.toJSON(e,n);return n.onCreate&&n.onCreate(o),o}return typeof t=="bigint"&&!n?.keep?Number(t):t}var at=class{constructor(e){Object.defineProperty(this,oe,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:n,maxAliasCount:r,onAnchor:o,reviver:s}={}){if(!Le(e))throw new TypeError("A document argument is required");let i={anchors:new Map,doc:e,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},a=Y(this,"",i);if(typeof o=="function")for(let{count:c,res:u}of i.anchors.values())o(u,c);return typeof s=="function"?it(s,{"":a},"",a):a}};var Je=class extends at{constructor(e){super(hr),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;n?.aliasResolveCache?r=n.aliasResolveCache:(r=[],Fe(e,{Node:(s,i)=>{(Se(i)||gr(i))&&r.push(i)}}),n&&(n.aliasResolveCache=r));let o;for(let s of r){if(s===this)break;s.anchor===this.source&&(o=s)}return o}toJSON(e,n){if(!n)return{source:this.source};let{anchors:r,doc:o,maxAliasCount:s}=n,i=this.resolve(o,n);if(!i){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=r.get(i);if(a||(Y(i,null,n),a=r.get(i)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=_r(o,i,r)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,n,r){let o=`*${this.source}`;if(e){if(wr(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(e.implicitKey)return`${o} `}return o}};function _r(t,e,n){if(Se(e)){let r=e.resolve(t),o=n&&r&&n.get(r);return o?o.count*o.aliasCount:0}else if(j(e)){let r=0;for(let o of e.items){let s=_r(t,o,n);s>r&&(r=s)}return r}else if(T(e)){let r=_r(t,e.key,n),o=_r(t,e.value,n);return Math.max(r,o)}return 1}var xr=t=>!t||typeof t!="function"&&typeof t!="object",D=class extends at{constructor(e){super(me),this.value=e}toJSON(e,n){return n?.keep?this.value:Y(this.value,e,n)}toString(){return String(this.value)}};D.BLOCK_FOLDED="BLOCK_FOLDED";D.BLOCK_LITERAL="BLOCK_LITERAL";D.PLAIN="PLAIN";D.QUOTE_DOUBLE="QUOTE_DOUBLE";D.QUOTE_SINGLE="QUOTE_SINGLE";var vm="tag:yaml.org,2002:";function km(t,e,n){if(e){let r=n.filter(s=>s.tag===e),o=r.find(s=>!s.format)??r[0];if(!o)throw new Error(`Tag ${e} not found`);return o}return n.find(r=>r.identify?.(t)&&!r.format)}function Ke(t,e,n){if(Le(t)&&(t=t.contents),P(t))return t;if(T(t)){let l=n.schema[xe].createNode?.(n.schema,null,n);return l.items.push(t),l}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:r,onAnchor:o,onTagObj:s,schema:i,sourceObjects:a}=n,c;if(r&&t&&typeof t=="object"){if(c=a.get(t),c)return c.anchor??(c.anchor=o(t)),new Je(c.anchor);c={anchor:null,node:null},a.set(t,c)}e?.startsWith("!!")&&(e=vm+e.slice(2));let u=km(t,e,i.tags);if(!u){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let l=new D(t);return c&&(c.node=l),l}u=t instanceof Map?i[xe]:Symbol.iterator in Object(t)?i[qe]:i[xe]}s&&(s(u),delete n.onTagObj);let d=u?.createNode?u.createNode(n.schema,t,n):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(n.schema,t,n):new D(t);return e?d.tag=e:u.default||(d.tag=u.tag),c&&(c.node=d),d}function wn(t,e,n){let r=n;for(let o=e.length-1;o>=0;--o){let s=e[o];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let i=[];i[s]=r,r=i}else r=new Map([[s,r]])}return Ke(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var Ft=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,Mt=class extends at{constructor(e,n){super(e),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(e){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(n.schema=e),n.items=n.items.map(r=>P(r)||T(r)?r.clone(e):r),this.range&&(n.range=this.range.slice()),n}addIn(e,n){if(Ft(e))this.add(n);else{let[r,...o]=e,s=this.get(r,!0);if(j(s))s.addIn(o,n);else if(s===void 0&&this.schema)this.set(r,wn(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}deleteIn(e){let[n,...r]=e;if(r.length===0)return this.delete(n);let o=this.get(n,!0);if(j(o))return o.deleteIn(r);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}getIn(e,n){let[r,...o]=e,s=this.get(r,!0);return o.length===0?!n&&N(s)?s.value:s:j(s)?s.getIn(o,n):void 0}hasAllNullValues(e){return this.items.every(n=>{if(!T(n))return!1;let r=n.value;return r==null||e&&N(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[n,...r]=e;if(r.length===0)return this.has(n);let o=this.get(n,!0);return j(o)?o.hasIn(r):!1}setIn(e,n){let[r,...o]=e;if(o.length===0)this.set(r,n);else{let s=this.get(r,!0);if(j(s))s.setIn(o,n);else if(s===void 0&&this.schema)this.set(r,wn(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}};var bl=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function ge(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var je=(t,e,n)=>t.endsWith(`-`)?ge(n,e):n.includes(`+Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let o of e.seen.entries()){let u=o[1];if(t===o[0]){s(o);continue}if(e.external){let f=e.external.registry.get(o[0])?.id;if(t!==o[0]&&f){s(o);continue}}if(e.metadataRegistry.get(o[0])?.id){s(o);continue}if(u.cycle){s(o);continue}if(u.count>1&&e.reused==="ref"){s(o);continue}}}function sc(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=u=>{let c=e.seen.get(u);if(c.ref===null)return;let f=c.def??c.schema,h={...f},p=c.ref;if(c.ref=null,p){n(p);let d=e.seen.get(p),x=d.schema;if(x.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(f.allOf=f.allOf??[],f.allOf.push(x)):Object.assign(f,x),Object.assign(f,h),u._zod.parent===p)for(let v in f)v==="$ref"||v==="allOf"||v in h||delete f[v];if(x.$ref&&d.def)for(let v in f)v==="$ref"||v==="allOf"||v in d.def&&JSON.stringify(f[v])===JSON.stringify(d.def[v])&&delete f[v]}let m=u._zod.parent;if(m&&m!==p){n(m);let d=e.seen.get(m);if(d?.schema.$ref&&(f.$ref=d.schema.$ref,d.def))for(let x in f)x==="$ref"||x==="allOf"||x in d.def&&JSON.stringify(f[x])===JSON.stringify(d.def[x])&&delete f[x]}e.override({zodSchema:u,jsonSchema:f,path:c.path??[]})};for(let u of[...e.seen.entries()].reverse())n(u[0]);let i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let u=e.external.registry.get(t)?.id;if(!u)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(u)}Object.assign(i,r.def??r.schema);let s=e.metadataRegistry.get(t)?.id;s!==void 0&&i.id===s&&delete i.id;let o=e.external?.defs??{};for(let u of e.seen.entries()){let c=u[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,o[c.defId]=c.def)}e.external||Object.keys(o).length>0&&(e.target==="draft-2020-12"?i.$defs=o:i.definitions=o);try{let u=JSON.parse(JSON.stringify(i));return Object.defineProperty(u,"~standard",{value:{...t["~standard"],jsonSchema:{input:ds(t,"input",e.processors),output:ds(t,"output",e.processors)}},enumerable:!1,writable:!1}),u}catch{throw new Error("Error converting schema to JSON.")}}function ft(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return ft(n.element,r);if(n.type==="set")return ft(n.valueType,r);if(n.type==="lazy")return ft(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return ft(n.innerType,r);if(n.type==="intersection")return ft(n.left,r)||ft(n.right,r);if(n.type==="record"||n.type==="map")return ft(n.keyType,r)||ft(n.valueType,r);if(n.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:ft(n.in,r)||ft(n.out,r);if(n.type==="object"){for(let i in n.shape)if(ft(n.shape[i],r))return!0;return!1}if(n.type==="union"){for(let i of n.options)if(ft(i,r))return!0;return!1}if(n.type==="tuple"){for(let i of n.items)if(ft(i,r))return!0;return!!(n.rest&&ft(n.rest,r))}return!1}var Em=(e,t={})=>r=>{let n=nc({...r,processors:t});return $e(e,n),ic(n,e),sc(n,e)},ds=(e,t,r={})=>n=>{let{libraryOptions:i,target:s}=n??{},o=nc({...i??{},target:s,io:t,processors:r});return $e(e,o),ic(o,e),sc(o,e)};var Ov={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},_m=(e,t,r,n)=>{let i=r;i.type="string";let{minimum:s,maximum:o,format:u,patterns:c,contentEncoding:f}=e._zod.bag;if(typeof s=="number"&&(i.minLength=s),typeof o=="number"&&(i.maxLength=o),u&&(i.format=Ov[u]??u,i.format===""&&delete i.format,u==="time"&&delete i.format),f&&(i.contentEncoding=f),c&&c.size>0){let h=[...c];h.length===1?i.pattern=h[0].source:h.length>1&&(i.allOf=[...h.map(p=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},Cm=(e,t,r,n)=>{let i=r,{minimum:s,maximum:o,format:u,multipleOf:c,exclusiveMaximum:f,exclusiveMinimum:h}=e._zod.bag;typeof u=="string"&&u.includes("int")?i.type="integer":i.type="number";let p=typeof h=="number"&&h>=(s??Number.NEGATIVE_INFINITY),m=typeof f=="number"&&f<=(o??Number.POSITIVE_INFINITY),d=t.target==="draft-04"||t.target==="openapi-3.0";p?d?(i.minimum=h,i.exclusiveMinimum=!0):i.exclusiveMinimum=h:typeof s=="number"&&(i.minimum=s),m?d?(i.maximum=f,i.exclusiveMaximum=!0):i.exclusiveMaximum=f:typeof o=="number"&&(i.maximum=o),typeof c=="number"&&(i.multipleOf=c)},Dm=(e,t,r,n)=>{r.type="boolean"};var Im=(e,t,r,n)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"};var Tm=(e,t,r,n)=>{r.not={}};var Rm=(e,t,r,n)=>{};var Nm=(e,t,r,n)=>{let i=e._zod.def,s=ss(i.entries);s.every(o=>typeof o=="number")&&(r.type="number"),s.every(o=>typeof o=="string")&&(r.type="string"),r.enum=s},Pm=(e,t,r,n)=>{let i=e._zod.def,s=[];for(let o of i.values)if(o===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof o=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(o))}else s.push(o);if(s.length!==0)if(s.length===1){let o=s[0];r.type=o===null?"null":typeof o,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[o]:r.const=o}else s.every(o=>typeof o=="number")&&(r.type="number"),s.every(o=>typeof o=="string")&&(r.type="string"),s.every(o=>typeof o=="boolean")&&(r.type="boolean"),s.every(o=>o===null)&&(r.type="null"),r.enum=s};var Om=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var Fm=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var Lm=(e,t,r,n)=>{let i=r,s=e._zod.def,{minimum:o,maximum:u}=e._zod.bag;typeof o=="number"&&(i.minItems=o),typeof u=="number"&&(i.maxItems=u),i.type="array",i.items=$e(s.element,t,{...n,path:[...n.path,"items"]})},zm=(e,t,r,n)=>{let i=r,s=e._zod.def;i.type="object",i.properties={};let o=s.shape;for(let f in o)i.properties[f]=$e(o[f],t,{...n,path:[...n.path,"properties",f]});let u=new Set(Object.keys(o)),c=new Set([...u].filter(f=>{let h=s.shape[f]._zod;return t.io==="input"?h.optin===void 0:h.optout===void 0}));c.size>0&&(i.required=Array.from(c)),s.catchall?._zod.def.type==="never"?i.additionalProperties=!1:s.catchall?s.catchall&&(i.additionalProperties=$e(s.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},Bm=(e,t,r,n)=>{let i=e._zod.def,s=i.inclusive===!1,o=i.options.map((u,c)=>$e(u,t,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));s?r.oneOf=o:r.anyOf=o},Mm=(e,t,r,n)=>{let i=e._zod.def,s=$e(i.left,t,{...n,path:[...n.path,"allOf",0]}),o=$e(i.right,t,{...n,path:[...n.path,"allOf",1]}),u=f=>"allOf"in f&&Object.keys(f).length===1,c=[...u(s)?s.allOf:[s],...u(o)?o.allOf:[o]];r.allOf=c};var Vm=(e,t,r,n)=>{let i=r,s=e._zod.def;i.type="object";let o=s.keyType,c=o._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let h=$e(s.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});i.patternProperties={};for(let p of c)i.patternProperties[p.source]=h}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(i.propertyNames=$e(s.keyType,t,{...n,path:[...n.path,"propertyNames"]})),i.additionalProperties=$e(s.valueType,t,{...n,path:[...n.path,"additionalProperties"]});let f=o._zod.values;if(f){let h=[...f].filter(p=>typeof p=="string"||typeof p=="number");h.length>0&&(i.required=h)}},$m=(e,t,r,n)=>{let i=e._zod.def,s=$e(i.innerType,t,n),o=t.seen.get(e);t.target==="openapi-3.0"?(o.ref=i.innerType,r.nullable=!0):r.anyOf=[s,{type:"null"}]},jm=(e,t,r,n)=>{let i=e._zod.def;$e(i.innerType,t,n);let s=t.seen.get(e);s.ref=i.innerType},Um=(e,t,r,n)=>{let i=e._zod.def;$e(i.innerType,t,n);let s=t.seen.get(e);s.ref=i.innerType,r.default=JSON.parse(JSON.stringify(i.defaultValue))},qm=(e,t,r,n)=>{let i=e._zod.def;$e(i.innerType,t,n);let s=t.seen.get(e);s.ref=i.innerType,t.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},Zm=(e,t,r,n)=>{let i=e._zod.def;$e(i.innerType,t,n);let s=t.seen.get(e);s.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=o},Jm=(e,t,r,n)=>{let i=e._zod.def,s=i.in._zod.traits.has("$ZodTransform"),o=t.io==="input"?s?i.out:i.in:i.out;$e(o,t,n);let u=t.seen.get(e);u.ref=o},Gm=(e,t,r,n)=>{let i=e._zod.def;$e(i.innerType,t,n);let s=t.seen.get(e);s.ref=i.innerType,r.readOnly=!0};var oc=(e,t,r,n)=>{let i=e._zod.def;$e(i.innerType,t,n);let s=t.seen.get(e);s.ref=i.innerType},Qm=(e,t,r,n)=>{let i=e._zod.innerType;$e(i,t,n);let s=t.seen.get(e);s.ref=i};var $v=B("ZodISODateTime",(e,t)=>{sd.init(e,t),Be.init(e,t)});function Hm(e){return pm($v,e)}var jv=B("ZodISODate",(e,t)=>{od.init(e,t),Be.init(e,t)});function Wm(e){return hm(jv,e)}var Uv=B("ZodISOTime",(e,t)=>{ad.init(e,t),Be.init(e,t)});function Km(e){return dm(Uv,e)}var qv=B("ZodISODuration",(e,t)=>{ud.init(e,t),Be.init(e,t)});function Xm(e){return mm(qv,e)}var Gv=(e,t)=>{bo.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>Vp(e,r)},flatten:{value:r=>Mp(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,si,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,si,2)}},isEmpty:{get(){return e.issues.length===0}}})};var Et=B("ZodError",Gv,{Parent:Error});var Ym=wo(Et),eg=vo(Et),tg=cs(Et),rg=ls(Et),ng=Up(Et),ig=qp(Et),sg=Zp(Et),og=Jp(Et),ag=Gp(Et),ug=Qp(Et),cg=Hp(Et),lg=Wp(Et);var fg=new WeakMap;function ms(e,t,r){let n=Object.getPrototypeOf(e),i=fg.get(n);if(i||(i=new Set,fg.set(n,i)),!i.has(t)){i.add(t);for(let s in r){let o=r[s];Object.defineProperty(n,s,{configurable:!0,enumerable:!1,get(){let u=o.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:u}),u},set(u){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:u})}})}}}var Fe=B("ZodType",(e,t)=>(Re.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:ds(e,"input"),output:ds(e,"output")}}),e.toJSONSchema=Em(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,n)=>Ym(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>tg(e,r,n),e.parseAsync=async(r,n)=>eg(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>rg(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>ng(e,r,n),e.decode=(r,n)=>ig(e,r,n),e.encodeAsync=async(r,n)=>sg(e,r,n),e.decodeAsync=async(r,n)=>og(e,r,n),e.safeEncode=(r,n)=>ag(e,r,n),e.safeDecode=(r,n)=>ug(e,r,n),e.safeEncodeAsync=async(r,n)=>cg(e,r,n),e.safeDecodeAsync=async(r,n)=>lg(e,r,n),ms(e,"ZodType",{check(...r){let n=this.def;return this.clone(ve.mergeDefs(n,{checks:[...n.checks??[],...r.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return ir(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check($k(r,n))},superRefine(r,n){return this.check(jk(r,n))},overwrite(r){return this.check(an(r))},optional(){return gg(this)},exactOptional(){return Ck(this)},nullable(){return yg(this)},nullish(){return gg(yg(this))},nonoptional(r){return Pk(this,r)},array(){return Le(this)},or(r){return ci([this,r])},and(r){return kk(this,r)},transform(r){return xg(this,Ek(r))},default(r){return Tk(this,r)},prefault(r){return Nk(this,r)},catch(r){return Fk(this,r)},pipe(r){return xg(this,r)},readonly(){return Bk(this)},describe(r){let n=this.clone();return Pn.add(n,{description:r}),n},meta(...r){if(r.length===0)return Pn.get(this);let n=this.clone();return Pn.add(n,r[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(e,"description",{get(){return Pn.get(e)?.description},configurable:!0}),e)),bg=B("_ZodString",(e,t)=>{_o.init(e,t),Fe.init(e,t),e._zod.processJSONSchema=(n,i,s)=>_m(e,n,i,s);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,ms(e,"_ZodString",{regex(...n){return this.check(Ju(...n))},includes(...n){return this.check(Hu(...n))},startsWith(...n){return this.check(Wu(...n))},endsWith(...n){return this.check(Ku(...n))},min(...n){return this.check(ui(...n))},max(...n){return this.check(To(...n))},length(...n){return this.check(Ro(...n))},nonempty(...n){return this.check(ui(1,...n))},lowercase(n){return this.check(Gu(n))},uppercase(n){return this.check(Qu(n))},trim(){return this.check(Yu())},normalize(...n){return this.check(Xu(...n))},toLowerCase(){return this.check(ec())},toUpperCase(){return this.check(tc())},slugify(){return this.check(rc())}})}),Hv=B("ZodString",(e,t)=>{_o.init(e,t),bg.init(e,t),e.email=r=>e.check(Zd(Wv,r)),e.url=r=>e.check(Wd(Kv,r)),e.jwt=r=>e.check(fm(pk,r)),e.emoji=r=>e.check(Kd(Xv,r)),e.guid=r=>e.check(Zu(pg,r)),e.uuid=r=>e.check(Jd(Po,r)),e.uuidv4=r=>e.check(Gd(Po,r)),e.uuidv6=r=>e.check(Qd(Po,r)),e.uuidv7=r=>e.check(Hd(Po,r)),e.nanoid=r=>e.check(Xd(Yv,r)),e.guid=r=>e.check(Zu(pg,r)),e.cuid=r=>e.check(Yd(ek,r)),e.cuid2=r=>e.check(em(tk,r)),e.ulid=r=>e.check(tm(rk,r)),e.base64=r=>e.check(um(ck,r)),e.base64url=r=>e.check(cm(lk,r)),e.xid=r=>e.check(rm(nk,r)),e.ksuid=r=>e.check(nm(ik,r)),e.ipv4=r=>e.check(im(sk,r)),e.ipv6=r=>e.check(sm(ok,r)),e.cidrv4=r=>e.check(om(ak,r)),e.cidrv6=r=>e.check(am(uk,r)),e.e164=r=>e.check(lm(fk,r)),e.datetime=r=>e.check(Hm(r)),e.date=r=>e.check(Wm(r)),e.time=r=>e.check(Km(r)),e.duration=r=>e.check(Xm(r))});function G(e){return qd(Hv,e)}var Be=B("ZodStringFormat",(e,t)=>{Oe.init(e,t),bg.init(e,t)}),Wv=B("ZodEmail",(e,t)=>{Wh.init(e,t),Be.init(e,t)});var pg=B("ZodGUID",(e,t)=>{Qh.init(e,t),Be.init(e,t)});var Po=B("ZodUUID",(e,t)=>{Hh.init(e,t),Be.init(e,t)});var Kv=B("ZodURL",(e,t)=>{Kh.init(e,t),Be.init(e,t)});var Xv=B("ZodEmoji",(e,t)=>{Xh.init(e,t),Be.init(e,t)});var Yv=B("ZodNanoID",(e,t)=>{Yh.init(e,t),Be.init(e,t)});var ek=B("ZodCUID",(e,t)=>{ed.init(e,t),Be.init(e,t)});var tk=B("ZodCUID2",(e,t)=>{td.init(e,t),Be.init(e,t)});var rk=B("ZodULID",(e,t)=>{rd.init(e,t),Be.init(e,t)});var nk=B("ZodXID",(e,t)=>{nd.init(e,t),Be.init(e,t)});var ik=B("ZodKSUID",(e,t)=>{id.init(e,t),Be.init(e,t)});var sk=B("ZodIPv4",(e,t)=>{cd.init(e,t),Be.init(e,t)});var ok=B("ZodIPv6",(e,t)=>{ld.init(e,t),Be.init(e,t)});var ak=B("ZodCIDRv4",(e,t)=>{fd.init(e,t),Be.init(e,t)});var uk=B("ZodCIDRv6",(e,t)=>{pd.init(e,t),Be.init(e,t)});var ck=B("ZodBase64",(e,t)=>{dd.init(e,t),Be.init(e,t)});var lk=B("ZodBase64URL",(e,t)=>{md.init(e,t),Be.init(e,t)});var fk=B("ZodE164",(e,t)=>{gd.init(e,t),Be.init(e,t)});var pk=B("ZodJWT",(e,t)=>{yd.init(e,t),Be.init(e,t)});var wg=B("ZodNumber",(e,t)=>{$u.init(e,t),Fe.init(e,t),e._zod.processJSONSchema=(n,i,s)=>Cm(e,n,i,s),ms(e,"ZodNumber",{gt(n,i){return this.check(Do(n,i))},gte(n,i){return this.check(hs(n,i))},min(n,i){return this.check(hs(n,i))},lt(n,i){return this.check(Co(n,i))},lte(n,i){return this.check(ps(n,i))},max(n,i){return this.check(ps(n,i))},int(n){return this.check(hg(n))},safe(n){return this.check(hg(n))},positive(n){return this.check(Do(0,n))},nonnegative(n){return this.check(hs(0,n))},negative(n){return this.check(Co(0,n))},nonpositive(n){return this.check(ps(0,n))},multipleOf(n,i){return this.check(Io(n,i))},step(n,i){return this.check(Io(n,i))},finite(){return this}});let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function Se(e){return gm(wg,e)}var hk=B("ZodNumberFormat",(e,t)=>{xd.init(e,t),wg.init(e,t)});function hg(e){return ym(hk,e)}var dk=B("ZodBoolean",(e,t)=>{bd.init(e,t),Fe.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Dm(e,r,n,i)});function un(e){return xm(dk,e)}var mk=B("ZodNull",(e,t)=>{wd.init(e,t),Fe.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Im(e,r,n,i)});function gk(e){return bm(mk,e)}var yk=B("ZodUnknown",(e,t)=>{vd.init(e,t),Fe.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Rm(e,r,n,i)});function dg(){return wm(yk)}var xk=B("ZodNever",(e,t)=>{kd.init(e,t),Fe.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Tm(e,r,n,i)});function vg(e){return vm(xk,e)}var bk=B("ZodArray",(e,t)=>{Ad.init(e,t),Fe.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Lm(e,r,n,i),e.element=t.element,ms(e,"ZodArray",{min(r,n){return this.check(ui(r,n))},nonempty(r){return this.check(ui(1,r))},max(r,n){return this.check(To(r,n))},length(r,n){return this.check(Ro(r,n))},unwrap(){return this.element}})});function Le(e,t){return km(bk,e,t)}var kg=B("ZodObject",(e,t)=>{_d.init(e,t),Fe.init(e,t),e._zod.processJSONSchema=(r,n,i)=>zm(e,r,n,i),ve.defineLazy(e,"shape",()=>t.shape),ms(e,"ZodObject",{keyof(){return wt(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:dg()})},loose(){return this.clone({...this._zod.def,catchall:dg()})},strict(){return this.clone({...this._zod.def,catchall:vg()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return ve.extend(this,r)},safeExtend(r){return ve.safeExtend(this,r)},merge(r){return ve.merge(this,r)},pick(r){return ve.pick(this,r)},omit(r){return ve.omit(this,r)},partial(...r){return ve.partial(Sg,this,r[0])},required(...r){return ve.required(Eg,this,r[0])}})});function Bt(e,t){let r={type:"object",shape:e??{},...ve.normalizeParams(t)};return new kg(r)}function le(e,t){return new kg({type:"object",shape:e,catchall:vg(),...ve.normalizeParams(t)})}var Ag=B("ZodUnion",(e,t)=>{ju.init(e,t),Fe.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Bm(e,r,n,i),e.options=t.options});function ci(e,t){return new Ag({type:"union",options:e,...ve.normalizeParams(t)})}var wk=B("ZodDiscriminatedUnion",(e,t)=>{Ag.init(e,t),Cd.init(e,t)});function li(e,t,r){return new wk({type:"union",options:t,discriminator:e,...ve.normalizeParams(r)})}var vk=B("ZodIntersection",(e,t)=>{Dd.init(e,t),Fe.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Mm(e,r,n,i)});function kk(e,t){return new vk({type:"intersection",left:e,right:t})}var mg=B("ZodRecord",(e,t)=>{Id.init(e,t),Fe.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Vm(e,r,n,i),e.keyType=t.keyType,e.valueType=t.valueType});function sr(e,t,r){return!t||!t._zod?new mg({type:"record",keyType:G(),valueType:e,...ve.normalizeParams(t)}):new mg({type:"record",keyType:e,valueType:t,...ve.normalizeParams(r)})}var ac=B("ZodEnum",(e,t)=>{Td.init(e,t),Fe.init(e,t),e._zod.processJSONSchema=(n,i,s)=>Nm(e,n,i,s),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,i)=>{let s={};for(let o of n)if(r.has(o))s[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new ac({...t,checks:[],...ve.normalizeParams(i),entries:s})},e.exclude=(n,i)=>{let s={...t.entries};for(let o of n)if(r.has(o))delete s[o];else throw new Error(`Key ${o} not found in enum`);return new ac({...t,checks:[],...ve.normalizeParams(i),entries:s})}});function wt(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new ac({type:"enum",entries:r,...ve.normalizeParams(t)})}var Ak=B("ZodLiteral",(e,t)=>{Rd.init(e,t),Fe.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Pm(e,r,n,i),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Ee(e,t){return new Ak({type:"literal",values:Array.isArray(e)?e:[e],...ve.normalizeParams(t)})}var Sk=B("ZodTransform",(e,t)=>{Nd.init(e,t),Fe.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Fm(e,r,n,i),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new ni(e.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(ve.issue(s,r.value,t));else{let o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),r.issues.push(ve.issue(o))}};let i=t.transform(r.value,r);return i instanceof Promise?i.then(s=>(r.value=s,r.fallback=!0,r)):(r.value=i,r.fallback=!0,r)}});function Ek(e){return new Sk({type:"transform",transform:e})}var Sg=B("ZodOptional",(e,t)=>{Uu.init(e,t),Fe.init(e,t),e._zod.processJSONSchema=(r,n,i)=>oc(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function gg(e){return new Sg({type:"optional",innerType:e})}var _k=B("ZodExactOptional",(e,t)=>{Pd.init(e,t),Fe.init(e,t),e._zod.processJSONSchema=(r,n,i)=>oc(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function Ck(e){return new _k({type:"optional",innerType:e})}var Dk=B("ZodNullable",(e,t)=>{Od.init(e,t),Fe.init(e,t),e._zod.processJSONSchema=(r,n,i)=>$m(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function yg(e){return new Dk({type:"nullable",innerType:e})}var Ik=B("ZodDefault",(e,t)=>{Fd.init(e,t),Fe.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Um(e,r,n,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Tk(e,t){return new Ik({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():ve.shallowClone(t)}})}var Rk=B("ZodPrefault",(e,t)=>{Ld.init(e,t),Fe.init(e,t),e._zod.processJSONSchema=(r,n,i)=>qm(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function Nk(e,t){return new Rk({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():ve.shallowClone(t)}})}var Eg=B("ZodNonOptional",(e,t)=>{zd.init(e,t),Fe.init(e,t),e._zod.processJSONSchema=(r,n,i)=>jm(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function Pk(e,t){return new Eg({type:"nonoptional",innerType:e,...ve.normalizeParams(t)})}var Ok=B("ZodCatch",(e,t)=>{Bd.init(e,t),Fe.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Zm(e,r,n,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Fk(e,t){return new Ok({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var Lk=B("ZodPipe",(e,t)=>{Md.init(e,t),Fe.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Jm(e,r,n,i),e.in=t.in,e.out=t.out});function xg(e,t){return new Lk({type:"pipe",in:e,out:t})}var zk=B("ZodReadonly",(e,t)=>{Vd.init(e,t),Fe.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Gm(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function Bk(e){return new zk({type:"readonly",innerType:e})}var Mk=B("ZodLazy",(e,t)=>{$d.init(e,t),Fe.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Qm(e,r,n,i),e.unwrap=()=>e._zod.def.getter()});function uc(e){return new Mk({type:"lazy",getter:e})}var Vk=B("ZodCustom",(e,t)=>{jd.init(e,t),Fe.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Om(e,r,n,i)});function $k(e,t={}){return Am(Vk,e,t)}function jk(e,t){return Sm(e,t)}function cn(e){let t=uc(()=>ci([G(e),Se(),un(),gk(),Le(t),sr(G(),t)]));return t}var _g=e=>"field"in e?[e]:("all"in e?e.all:e.any).flatMap(_g),gs=e=>_g(e);var fi=(e,t)=>{if("field"in e)return t(e);let r="all"in e?e.all:e.any,n=!1;if("all"in e){for(let i of r){let s=fi(i,t);if(s===!1)return!1;n||=s===void 0}return n?void 0:!0}for(let i of r){let s=fi(i,t);if(s===!0)return!0;n||=s===void 0}return n?void 0:!1},Cg=e=>JSON.stringify(e),cc=e=>{if("field"in e)return{conditions:1,depth:0};let t="all"in e?e.all:e.any,r=0,n=1;for(let i of t){let s=cc(i);r+=s.conditions,n=Math.max(n,s.depth+1)}return{conditions:r,depth:n}},Dg=(e,t={})=>{let r=i=>{let s=Le(i),o=t.maximumChildren===void 0?s:s.max(t.maximumChildren);return ci([e,le({all:o}),le({any:o})])},n=uc(()=>r(n));return t.maximumConditions===void 0&&t.maximumDepth===void 0?n:n.superRefine((i,s)=>{let{conditions:o,depth:u}=cc(i);t.maximumConditions!==void 0&&o>t.maximumConditions&&s.addIssue({code:"custom",message:t.maximumConditionsMessage??"Query exceeds the condition limit"}),t.maximumDepth!==void 0&&u>t.maximumDepth&&s.addIssue({code:"custom",message:t.maximumDepthMessage??"Query exceeds the nesting limit"})})};var Q={requestBytes:524288,filterCount:32,filterDepth:8,sortCount:8,outputFieldCount:256,fieldPathDepth:9,defaultResultCount:20,resultCount:1e3,resultBytes:16777216,candidateDocuments:1e3,databaseBytes:512e3,frontmatterBytes:65536,frontmatterDepth:8,frontmatterFields:256,frontmatterStringBytes:16384,jsonBytes:1048576,jsonDepth:8,jsonFields:256,jsonStringBytes:16384,indexedPropertiesBytes:65536,excerptBytes:2048,mdxDepth:100,mdxNodes:2e4,mdxProps:4e3,hydratedFileBytes:1048576,hydratedTotalBytes:2097152,hydratedFileCount:20,hydratedRangeBytes:262144,concurrentContentReads:8};function On(e,t=new Set){if(typeof e=="number"&&isNaN(e))throw new Error("NaN is not allowed");if(typeof e=="number"&&!isFinite(e))throw new Error("Infinity is not allowed");if(e===null||typeof e!="object")return JSON.stringify(e);if(typeof e.toJSON=="function"){if(t.has(e))throw new Error("Circular reference detected");t.add(e);let n=On(e.toJSON(),t);return t.delete(e),n}if(t.has(e))throw new Error("Circular reference detected");t.add(e);let r;if(Array.isArray(e))r=`[${e.map(i=>On(i===void 0||typeof i=="symbol"?null:i,t)).join(",")}]`;else{let n=[];for(let i of Object.keys(e).sort())e[i]===void 0||typeof e[i]=="symbol"||n.push(`${On(i)}:${On(e[i],t)}`);r=`{${n.join(",")}}`}return t.delete(e),r}var Uk=new TextEncoder,pi=e=>Uk.encode(e),Mt=e=>pi(e).byteLength,pt=class extends Error{constructor(){super("Byte stream exceeds the configured limit"),this.name="ByteLimitExceededError"}},qk=(e,t)=>{let r=new Uint8Array(t),n=0;for(let i of e)r.set(i,n),n+=i.byteLength;return r},hi=e=>typeof e=="string"?{async*[Symbol.asyncIterator](){yield pi(e)}}:e instanceof Uint8Array?{async*[Symbol.asyncIterator](){yield e}}:e,Ig=e=>({async*[Symbol.asyncIterator](){let t=e.getReader(),r=!1;try{for(;;){let n=await t.read();if(n.done){r=!0;return}yield n.value}}finally{if(r===!1)try{await t.cancel()}catch{}t.releaseLock()}}}),lc=async(e,t)=>{let r=[],n=0;for await(let i of hi(e)){let s=t-n;if(s<=0)break;let o=i.subarray(0,s);if(r.push(o),n+=o.byteLength,n===t)break}return qk(r,n)},Ar=async(e,t)=>{let r=await lc(e,t+1);if(r.byteLength>t)throw new pt;return r},_t=e=>new TextDecoder("utf-8",{fatal:!0}).decode(e),di=e=>e.charCodeAt(0)===65279?e.slice(1):e;var Tg=e=>{for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(t+1>=e.length||n<56320||n>57343)throw new Error("JSON strings cannot contain lone Unicode surrogates");t+=1;continue}if(r>=56320&&r<=57343)throw new Error("JSON strings cannot contain lone Unicode surrogates")}},fc=(e,t)=>{if(e===null||typeof e=="boolean")return e;if(typeof e=="string")return Tg(e),e;if(typeof e=="number"){if(Number.isFinite(e)===!1)throw new Error("JSON cannot contain non-finite numbers");return e}if(Array.isArray(e)){if(Object.getOwnPropertySymbols(e).length>0)throw new Error("JSON arrays cannot contain symbol properties");if(t.has(e))throw new Error("JSON cannot contain circular references");t.add(e);try{let r=[];for(let n=0;n<e.length;n+=1){if(Object.hasOwn(e,n)===!1)throw new Error("JSON arrays cannot be sparse");let i=e[n];if(i===void 0)throw new Error("JSON arrays cannot contain undefined values");r.push(fc(i,t))}if(Object.keys(e).length!==e.length)throw new Error("JSON arrays cannot contain named properties");return r}finally{t.delete(e)}}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error("JSON can contain only plain objects");if(Object.getOwnPropertySymbols(e).length>0)throw new Error("JSON objects cannot contain symbol properties");if(t.has(e))throw new Error("JSON cannot contain circular references");t.add(e);let n={};try{for(let[i,s]of Object.entries(e))Tg(i),s!==void 0&&Object.defineProperty(n,i,{value:fc(s,t),enumerable:!0,configurable:!0,writable:!0})}finally{t.delete(e)}return n}throw new Error("Value cannot be represented as JSON")},ln=e=>fc(e,new Set),Ct=e=>{let t=On(ln(e));if(t===void 0)throw new Error("Value cannot be represented as canonical JSON");return t},ys=(e,t)=>e===void 0||t===void 0?e===t:Ct(e)===Ct(t),Sr=(e,t)=>e<t?-1:e>t?1:0,pc=async e=>{let t=typeof e=="string"?pi(e):e,r=await globalThis.crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r),n=>n.toString(16).padStart(2,"0")).join("")},Rg=async e=>`sha256:${await pc(e)}`;var Ng=li("type",[le({type:Ee("document")}),le({type:Ee("json"),path:Le(G()).min(1)}),le({type:Ee("markdown-body")}),le({type:Ee("markdown-frontmatter")})]),hc=le({documentId:G().min(1),revision:G().min(1),representation:Ng}),Zk=e=>{let t=Ng.parse(e);return t.type==="json"?Object.freeze({...t,path:Object.freeze([...t.path])}):Object.freeze(t)},Pg=e=>{let t=hc.parse(e);return Object.freeze({...t,representation:Zk(t.representation)})};var xs=["json","markdown","mdx"],Og=e=>typeof e=="string"&&xs.includes(e),Fg=e=>{let t=e.split(";",1)[0].trim().toLowerCase();if(t==="application/json")return"json";if(t==="text/markdown")return"markdown";if(t==="text/mdx")return"mdx"};var Oo=le({id:G().min(1),revision:G().min(1),contentRef:G().min(1),format:wt(xs).optional()}),Fo=le({sourceId:G().min(1),referenceId:G().min(1),reference:hc});var mi=e=>{let t=new Map;for(let r of e){let n=t.get(r.sourceId)??[];n.push(r),t.set(r.sourceId,n)}return t};var Er=class extends Error{code;documentIds;constructor({code:t,message:r,documentIds:n=[]}){super(r),this.name="DocumentGraphError",this.code=t,this.documentIds=Object.freeze([...n])}},Jk=(e,t)=>Sr(e.sourceId,t.sourceId)||Sr(e.referenceId,t.referenceId),bs=({nodes:e,edges:t})=>{let r=e.map(u=>Object.freeze(Oo.parse(u))).sort((u,c)=>Sr(u.id,c.id)),n=new Map,i=new Map;for(let u of r){if(n.has(u.id))throw new Er({code:"DUPLICATE_NODE",message:`Document graph contains duplicate node ${u.id}`,documentIds:[u.id]});n.set(u.id,u);let c=i.get(u.contentRef);if(c!==void 0&&(c.revision!==u.revision||c.format!==u.format))throw new Er({code:"CONTENT_IDENTITY_CONFLICT",message:`Document graph content reference ${u.contentRef} has conflicting identities`,documentIds:[c.id,u.id]});i.set(u.contentRef,u)}let s=t.map(u=>{let c=Fo.parse(u);return Object.freeze({...c,reference:Pg(c.reference)})}).sort(Jk),o=new Set;for(let u of s){if(n.get(u.sourceId)===void 0)throw new Er({code:"SOURCE_NOT_FOUND",message:`Document graph source ${u.sourceId} does not exist`,documentIds:[u.sourceId]});let f=n.get(u.reference.documentId);if(f===void 0)throw new Er({code:"TARGET_NOT_FOUND",message:`Document graph target ${u.reference.documentId} does not exist`,documentIds:[u.sourceId,u.reference.documentId]});if(f.revision!==u.reference.revision)throw new Er({code:"TARGET_REVISION_MISMATCH",message:`Document graph target ${f.id} revision does not match its reference`,documentIds:[u.sourceId,f.id]});let h=`${u.sourceId}\0${u.referenceId}`;if(o.has(h))throw new Er({code:"DUPLICATE_REFERENCE",message:`Document ${u.sourceId} contains duplicate reference ID ${u.referenceId}`,documentIds:[u.sourceId]});o.add(h)}return Object.freeze({nodes:Object.freeze(r),edges:Object.freeze(s)})},Gk=e=>new Map(e.nodes.map(t=>[t.id,t]));var Lo=({graph:e,rootIds:t})=>{let r=Gk(e),n=mi(e.edges),i=new Map,s=[],o=[],u=c=>{let f=r.get(c);if(f===void 0)throw new Er({code:"ROOT_NOT_FOUND",message:`Document graph root ${c} does not exist`,documentIds:[c]});let h=i.get(c);if(h!=="visited"){if(h==="visiting"){let p=s.indexOf(c),m=[...s.slice(p),c];throw new Er({code:"CYCLE",message:`Document graph contains a cycle: ${m.join(" -> ")}`,documentIds:m})}i.set(c,"visiting"),s.push(c);for(let p of n.get(c)??[])u(p.reference.documentId);s.pop(),i.set(c,"visited"),o.push(f)}};for(let c of[...new Set(t)].sort(Sr))u(c);return Object.freeze(o)};var Qk=G().regex(/^sha256:[a-f0-9]{64}$/),Lg=le({format:Ee("webstudio-document-graph"),version:Ee(1),nodes:Le(Oo),edges:Le(Fo),integrity:le({algorithm:Ee("sha256"),checksum:Qk})});var Hk=G().min(1).refine(e=>e.startsWith("/")===!1,{error:"Asset path must be relative"}).refine(e=>e.includes("\\")===!1&&e.split("/").every(t=>t.length>0&&t!==".."&&t!=="."),{error:"Asset path must be normalized and must not contain dot segments"}),Mg=le({_id:G().min(1),_type:Ee("asset.file"),name:G().min(1),description:G().optional(),path:Hk,key:G(),folderId:G().min(1).optional(),extension:G().regex(/^[a-z0-9]*$/),mimeType:G().min(1),size:Se().int().nonnegative(),createdAt:G().datetime().optional(),revision:G().min(1),contentRef:G().min(1),properties:sr(G(),cn()),excerpt:G().optional(),metadataError:le({code:G().min(1),message:G().min(1)}).optional()}),mc=Mg.partial().required({_id:!0}),Wk=wt(["null","boolean","number","string","object","array"]),Kk=Bt({format:Ee("webstudio-builder-asset-field-catalog"),version:Ee(1),canonicalRevision:G().regex(/^sha256:[a-f0-9]{64}$/),documentCount:Se().int().nonnegative(),fields:sr(G().min(1),Bt({queryPath:Le(G().min(1)).min(1).max(Q.fieldPathDepth).optional(),types:Le(Wk).min(1),occurrences:Se().int().positive(),optional:Ee(!0).optional(),mixed:Ee(!0).optional()}))}).superRefine((e,t)=>{for(let[r,n]of Object.entries(e.fields)){let i=[...new Set(n.types)].sort();JSON.stringify(n.types)!==JSON.stringify(i)&&t.addIssue({code:"custom",path:["fields",r,"types"],message:"Observed field types must be unique and sorted"}),n.occurrences>e.documentCount&&t.addIssue({code:"custom",path:["fields",r,"occurrences"],message:"Field occurrences cannot exceed the document count"});let s=n.occurrences<e.documentCount;n.optional===!0!==s&&t.addIssue({code:"custom",path:["fields",r,"optional"],message:"Field optionality must match its occurrence count"});let o=i.length>1;n.mixed===!0!==o&&t.addIssue({code:"custom",path:["fields",r,"mixed"],message:"Mixed status must match the observed types"})}}),zo=G().regex(/^sha256:[a-f0-9]{64}$/),Vg=le({fields:Le(Le(G().min(1)).min(1).max(Q.fieldPathDepth)).min(1).max(Q.outputFieldCount+1),rows:Le(Le(cn())).max(Q.resultCount),totalCount:Se().int().nonnegative().max(Q.candidateDocuments),hasMore:un()}).superRefine(({fields:e,rows:t},r)=>{for(let[n,i]of t.entries())i.length!==e.length&&r.addIssue({code:"custom",path:["rows",n],message:"Materialized query rows must match the field count"})}),zg=le({format:Ee("webstudio-content-database"),version:Ee(1),assetRevision:zo,documents:Le(mc),documentGraph:Lg.optional(),contents:sr(G().min(1),G()).optional(),assetReferences:sr(G().min(1),Le(le({start:Se().int().nonnegative(),end:Se().int().positive(),assetId:G().min(1),suffix:G().min(1).optional()}).refine(({start:e,end:t})=>t>e,{message:"Markdown asset reference range must not be empty"}))).optional(),assetValueReferences:sr(G().min(1),Le(le({path:Le(G().min(1).or(Se().int().nonnegative())).min(1),assetId:G().min(1),suffix:G().min(1).optional()}))).optional(),fieldCatalog:Kk,queries:sr(zo,Vg).optional(),database:le({maxBytes:Se().int().positive(),unboundedBytes:Se().int().nonnegative(),sourceDocumentCount:Se().int().nonnegative(),includedDocumentCount:Se().int().nonnegative().optional()}).optional(),integrity:le({algorithm:Ee("sha256"),checksum:zo})}).superRefine((e,t)=>{e.documents.length>Q.candidateDocuments&&t.addIssue({code:"custom",path:["documents"],message:"Asset index exceeds the document limit"}),(e.fieldCatalog.canonicalRevision!==e.assetRevision||e.fieldCatalog.documentCount!==e.documents.length)&&t.addIssue({code:"custom",path:["fieldCatalog"],message:"Asset index field catalog does not match its documents"}),e.database!==void 0&&e.database.sourceDocumentCount<e.documents.length&&t.addIssue({code:"custom",path:["database","sourceDocumentCount"],message:"Source document count cannot be smaller than the database"}),e.database?.includedDocumentCount!==void 0&&(e.database.includedDocumentCount<e.documents.length||e.database.includedDocumentCount>e.database.sourceDocumentCount)&&t.addIssue({code:"custom",path:["database","includedDocumentCount"],message:"Included document count must match the database bounds"});let r;for(let[i,s]of e.documents.entries())r!==void 0&&s._id<=r&&t.addIssue({code:"custom",path:["documents",i,"_id"],message:"Asset index documents must have unique sorted IDs"}),r=s._id;let n=new Set(e.documents.flatMap(({contentRef:i})=>i===void 0?[]:[i]));for(let i of Object.keys(e.contents??{}))n.has(i)===!1&&t.addIssue({code:"custom",path:["contents",i],message:"Embedded content must belong to an indexed document"});for(let i of Object.keys(e.assetReferences??{}))n.has(i)===!1&&t.addIssue({code:"custom",path:["assetReferences",i],message:"Asset references must belong to an indexed document"})}),Xk=li("mode",[Bt({mode:Ee("none")}),Bt({mode:Ee("full"),maxBytes:Se().int().positive().max(Q.hydratedFileBytes).optional()}),Bt({mode:Ee("range"),offset:Se().int().nonnegative(),length:Se().int().positive().max(Q.hydratedRangeBytes)}),Bt({mode:Ee("markdown-body-ref"),maxBytes:Se().int().positive().max(Q.hydratedFileBytes).optional()})]),gc={id:["string"],url:["string"],width:["number"],height:["number"],name:["string"],description:["string"],path:["string"],key:["string"],folderId:["string"],extension:["string"],mimeType:["string"],size:["number"],createdAt:["string"],revision:["string"],excerpt:["string"]},$g=Object.keys(gc),jg=["url","width","height"],Bo=e=>jg.includes(e),Ug=$g.filter(e=>Bo(e)===!1&&e!=="excerpt"),qg=Ug.filter(e=>e!=="id"),Zg=e=>Ug.includes(e),Yk=wt($g),ws=Le(G().min(1)).min(1).max(Q.fieldPathDepth).superRefine((e,t)=>{if(e[0]==="properties"){e.length<2&&t.addIssue({code:"custom",message:"A properties field path must select a property"});return}(e.length!==1||Yk.safeParse(e[0]).success===!1)&&t.addIssue({code:"custom",message:"Asset query field path is unsupported"})}),dc=un().default(!0),eA=li("mode",[le({mode:Ee("all"),includeMetadata:dc}),le({mode:Ee("base"),includeMetadata:dc}),le({mode:Ee("fields"),includeMetadata:dc,fields:Le(ws).max(Q.outputFieldCount).refine(e=>new Set(e.map(Cg)).size===e.length,{error:"Selected output fields must be unique"})})]),tA={mode:"fields",includeMetadata:!1,fields:jg.map(e=>[e])},Jg=["eq","ne","contains","startsWith","endsWith","gt","gte","lt","lte"],cR=[...Jg,"in","exists","isEmpty"],rA=le({field:ws,operator:wt(Jg),value:cn()}),nA=le({field:ws,operator:Ee("in"),value:Le(cn()).max(Q.resultCount)}),iA=le({field:ws,operator:wt(["exists","isEmpty"]),value:un()}),sA=li("operator",[rA,nA,iA]),oA=Dg(sA,{maximumChildren:Q.filterCount,maximumConditions:Q.filterCount,maximumDepth:Q.filterDepth,maximumConditionsMessage:"Asset query exceeds the filter limit",maximumDepthMessage:"Asset query exceeds the filter nesting limit"});var aA=oA,Gg=e=>{let t=new Set(["eq","ne","in","exists"]);return e.some(r=>r==="string"||r==="array")&&t.add("contains"),e.includes("string")&&(t.add("startsWith"),t.add("endsWith")),e.some(r=>r==="string"||r==="number")&&(t.add("gt"),t.add("gte"),t.add("lt"),t.add("lte")),e.some(r=>r==="string"||r==="array"||r==="object")&&t.add("isEmpty"),[...t]},uA=le({field:ws,direction:wt(["asc","desc"])}),cA=wt(["many","one","first","last"]),lA=({output:e,content:t})=>e.includeMetadata||e.mode==="all"||e.mode==="fields"&&e.fields.length>0||t.mode!=="none",fn=le({result:cA.default("many"),where:aA.default({all:[]}),sort:Le(uA).max(Q.sortCount).default([]),limit:Se().int().nonnegative().max(Q.resultCount).default(Q.defaultResultCount),offset:Se().int().nonnegative().max(Q.candidateDocuments).default(0),output:eA.default(tA),content:Xk.default({mode:"none"})}).superRefine((e,t)=>{lA(e)===!1&&t.addIssue({code:"custom",message:"Select at least one asset query output"}),(e.result==="first"||e.result==="last")&&e.sort.length===0&&t.addIssue({code:"custom",path:["sort"],message:"Add sorting to define which item is first."})}),Qg=le({query:fn,indexRevision:G().min(1).max(255).optional()}),fA=Bt({_id:G().min(1),revision:G().min(1),contentRef:G().min(1),encoding:Ee("utf-8"),text:G(),range:Bt({offset:Se().int().nonnegative(),length:Se().int().nonnegative(),total:Se().int().nonnegative()}).optional()}),pA=fA.omit({_id:!0,revision:!0,contentRef:!0}),Hg=Mg.omit({_id:!0,_type:!0,contentRef:!0}).partial().extend({id:G().min(1),url:G().min(1).optional(),width:Se().positive().optional(),height:Se().positive().optional(),content:pA.optional()}).refine(e=>e.width===void 0==(e.height===void 0),{error:"Asset dimensions must include both width and height"}),hA=le({format:Ee("webstudio-content-database"),version:Ee(1),revision:zo,usedBytes:Se().int().nonnegative(),maxBytes:Se().int().positive(),unboundedBytes:Se().int().nonnegative(),includedDocumentCount:Se().int().nonnegative(),omittedDocumentCount:Se().int().nonnegative(),omissionReason:wt(["size","unavailable"]).optional(),truncated:un()}),Bg=hA.pick({usedBytes:!0,maxBytes:!0,unboundedBytes:!0,includedDocumentCount:!0,omittedDocumentCount:!0,omissionReason:!0,truncated:!0}),yc=le({items:Le(Hg),totalCount:Se().int().nonnegative(),hasMore:un()}),dA=le({item:Hg.nullable(),totalCount:Se().int().nonnegative()}),Wg=ci([yc,dA]),mA=le({scope:Ee("query-preview"),query:Bg,database:Bg,artifacts:le({query:zg,database:zg}).optional(),unresolved:Wg.optional()}),lR=le({data:Wg,__diagnostics__:mA}),gA=wt(["INVALID_REQUEST","REQUEST_CANCELLED","UNAUTHORIZED","FORBIDDEN","STALE_INDEX","CONTENT_IDENTITY_REQUIRED","CONTENT_NOT_TEXT","CONTENT_DECODING_FAILED","CONTENT_LIMIT_EXCEEDED","MULTIPLE_RESULTS","INTERNAL_ERROR"]),yA=Bt({ok:Ee(!1),error:Bt({code:gA,message:G().min(1),retryable:un(),details:sr(G(),cn()).optional()}),meta:Bt({queryHash:G().min(1).optional(),indexRevision:G().min(1).optional(),assetRevision:G().min(1).optional()}).optional()}),Kg=({code:e,message:t,retryable:r=!1,details:n})=>yA.parse({ok:!1,error:{code:e,message:t,retryable:r,details:n}});var Xg=function*(e){if(e.length>0&&!e.startsWith("/")||/~(?![01])/.test(e))throw Error("Invalid JSON Pointer");let t=1,r=0;for(;r<e.length;){let n=e.indexOf("/",t);r=n===-1?e.length:n;let i=e.slice(t,r);t=r+1,yield bA(i)}};var xc=(e,t)=>t+"/"+xA(e),xA=e=>e.toString().replace(/~/g,"~0").replace(/\//g,"~1"),bA=e=>e.toString().replace(/~1/g,"/").replace(/~0/g,"~");var Mo=async(e,t,r)=>{if(Number.isSafeInteger(t)===!1||t<=0)throw new Error("Concurrency must be a positive safe integer");let n=0,i=new Array(e.length),s=async()=>{for(;n<e.length;){let f=n;n+=1,i[f]=await r(e[f])}},o=Array.from({length:Math.min(t,e.length)},s),c=(await Promise.allSettled(o)).find(f=>f.status==="rejected");if(c!==void 0)throw c.reason;return i};var gi=e=>typeof e=="object"&&e!==null&&Array.isArray(e)===!1,Yg=e=>{if(gi(e)===!1)return;let t=Object.keys(e);if(!(t.length!==1||t[0]!=="$ref"))return e.$ref};var Dt=class extends Error{code;referenceId;constructor({code:t,message:r,referenceId:n,cause:i}){super(r,{cause:i}),this.name="JsonDocumentError",this.code=t,this.referenceId=n}},wA=(e,t)=>{let r=Yg(e);if(r!==void 0){if(typeof r!="string")throw new Dt({code:"INVALID_REFERENCE_MARKER",message:`JSON reference marker ${t} must contain a string $ref`,referenceId:t});return r}},vA=e=>`#${e}`;var ey=async({source:e,maximumBytes:t=Q.hydratedFileBytes})=>{let r;try{r=await Ar(e,t)}catch(i){throw i instanceof pt?new Dt({code:"CONTENT_LIMIT_EXCEEDED",message:"JSON document exceeds the byte limit",cause:i}):i}let n;try{n=di(_t(r))}catch(i){throw new Dt({code:"CONTENT_DECODING_FAILED",message:"JSON document is not valid UTF-8",cause:i})}try{return ln(JSON.parse(n))}catch(i){throw new Dt({code:"INVALID_DOCUMENT",message:"JSON document is invalid",cause:i})}};var kA=(e,t)=>{let r=e;for(let n of t){if(Array.isArray(r)){let i=Number(n);if(Number.isSafeInteger(i)===!1||i<0||String(i)!==n||i>=r.length)return;r=r[i];continue}if(gi(r)&&Object.hasOwn(r,n)){r=r[n];continue}return}return r},ty=({document:e,representation:t})=>{let r=ln(e);if(t.type==="document")return r;if(t.type!=="json")throw new Dt({code:"UNSUPPORTED_REPRESENTATION",message:`JSON documents do not support ${t.type}`});let n=kA(r,t.path);if(n===void 0)throw new Dt({code:"JSON_PATH_NOT_FOUND",message:"JSON document path does not exist"});return n},AA=(e,t,r)=>{Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0})},Vo=({document:e,references:t,allowUnresolvedReferences:r=!1})=>{let n=ln(e),i=new Set,s=(u,c)=>{let f=vA(c);if(wA(u,f)!==void 0){if(t.has(f)===!1){if(r)return u;throw new Dt({code:"REFERENCE_NOT_FOUND",message:`Resolved JSON reference ${f} is unavailable`,referenceId:f})}i.add(f);try{return ln(t.get(f))}catch(p){throw new Dt({code:"INVALID_RESOLVED_VALUE",message:`Resolved JSON reference ${f} is not JSON-compatible`,referenceId:f,cause:p})}}if(Array.isArray(u))return u.map((p,m)=>s(p,xc(String(m),c)));if(gi(u)){let p={};for(let[m,d]of Object.entries(u))AA(p,m,s(d,xc(m,c)));return p}return u},o=s(n,"");for(let u of[...t.keys()].sort())if(i.has(u)===!1)throw new Dt({code:"UNUSED_REFERENCE",message:`Resolved JSON reference ${u} has no marker`,referenceId:u});return o};var $o=Symbol.for("yaml.alias"),jo=Symbol.for("yaml.document"),or=Symbol.for("yaml.map"),bc=Symbol.for("yaml.pair"),It=Symbol.for("yaml.scalar"),Zr=Symbol.for("yaml.seq"),ht=Symbol.for("yaml.node.type"),ar=e=>!!e&&typeof e=="object"&&e[ht]===$o,_r=e=>!!e&&typeof e=="object"&&e[ht]===jo,ur=e=>!!e&&typeof e=="object"&&e[ht]===or,ge=e=>!!e&&typeof e=="object"&&e[ht]===bc,pe=e=>!!e&&typeof e=="object"&&e[ht]===It,cr=e=>!!e&&typeof e=="object"&&e[ht]===Zr;function _e(e){if(e&&typeof e=="object")switch(e[ht]){case or:case Zr:return!0}return!1}function be(e){if(e&&typeof e=="object")switch(e[ht]){case $o:case or:case It:case Zr:return!0}return!1}var Uo=e=>(pe(e)||_e(e))&&!!e.anchor;var vt=Symbol("break visit"),ry=Symbol("skip children"),Cr=Symbol("remove node");function Dr(e,t){let r=ny(t);_r(e)?yi(null,e.contents,r,Object.freeze([e]))===Cr&&(e.contents=null):yi(null,e,r,Object.freeze([]))}Dr.BREAK=vt;Dr.SKIP=ry;Dr.REMOVE=Cr;function yi(e,t,r,n){let i=iy(e,t,r,n);if(be(i)||ge(i))return sy(e,n,i),yi(e,i,r,n);if(typeof i!="symbol"){if(_e(t)){n=Object.freeze(n.concat(t));for(let s=0;s<t.items.length;++s){let o=yi(s,t.items[s],r,n);if(typeof o=="number")s=o-1;else{if(o===vt)return vt;o===Cr&&(t.items.splice(s,1),s-=1)}}}else if(ge(t)){n=Object.freeze(n.concat(t));let s=yi("key",t.key,r,n);if(s===vt)return vt;s===Cr&&(t.key=null);let o=yi("value",t.value,r,n);if(o===vt)return vt;o===Cr&&(t.value=null)}}return i}async function qo(e,t){let r=ny(t);_r(e)?await xi(null,e.contents,r,Object.freeze([e]))===Cr&&(e.contents=null):await xi(null,e,r,Object.freeze([]))}qo.BREAK=vt;qo.SKIP=ry;qo.REMOVE=Cr;async function xi(e,t,r,n){let i=await iy(e,t,r,n);if(be(i)||ge(i))return sy(e,n,i),xi(e,i,r,n);if(typeof i!="symbol"){if(_e(t)){n=Object.freeze(n.concat(t));for(let s=0;s<t.items.length;++s){let o=await xi(s,t.items[s],r,n);if(typeof o=="number")s=o-1;else{if(o===vt)return vt;o===Cr&&(t.items.splice(s,1),s-=1)}}}else if(ge(t)){n=Object.freeze(n.concat(t));let s=await xi("key",t.key,r,n);if(s===vt)return vt;s===Cr&&(t.key=null);let o=await xi("value",t.value,r,n);if(o===vt)return vt;o===Cr&&(t.value=null)}}return i}function ny(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function iy(e,t,r,n){if(typeof r=="function")return r(e,t,n);if(ur(t))return r.Map?.(e,t,n);if(cr(t))return r.Seq?.(e,t,n);if(ge(t))return r.Pair?.(e,t,n);if(pe(t))return r.Scalar?.(e,t,n);if(ar(t))return r.Alias?.(e,t,n)}function sy(e,t,r){let n=t[t.length-1];if(_e(n))n.items[e]=r;else if(ge(n))e==="key"?n.key=r:n.value=r;else if(_r(n))n.contents=r;else{let i=ar(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}var SA={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},EA=e=>e.replace(/[!,[\]{}]/g,t=>SA[t]),Ir=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let n=t.trim().split(/[ \t]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[s,o]=n;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[s]=n;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let o=/^\d+\.\d+$/.test(s);return r(6,`Unsupported YAML version ${s}`,o),!1}}default:return r(0,`Unknown directive ${i}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,n,i]=t.match(/^(.*!)([^!]*)$/s);i||r(`The ${t} tag has no suffix`);let s=this.tags[n];if(s)try{return s+decodeURIComponent(i)}catch(o){return r(String(o)),null}return n==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,n]of Object.entries(this.tags))if(t.startsWith(n))return r+EA(t.substring(n.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),i;if(t&&n.length>0&&be(t.contents)){let s={};Dr(t.contents,(o,u)=>{be(u)&&u.tag&&(s[u.tag]=!0)}),i=Object.keys(s)}else i=[];for(let[s,o]of n)s==="!!"&&o==="tag:yaml.org,2002:"||(!t||i.some(u=>u.startsWith(o)))&&r.push(`%TAG ${s} ${o}`);return r.join(`+`)}};Ir.defaultYaml={explicit:!1,version:"1.2"};Ir.defaultTags={"!!":"tag:yaml.org,2002:"};function Zo(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function wc(e){let t=new Set;return Dr(e,{Value(r,n){n.anchor&&t.add(n.anchor)}}),t}function vc(e,t){for(let r=1;;++r){let n=`${e}${r}`;if(!t.has(n))return n}}function oy(e,t){let r=[],n=new Map,i=null;return{onAnchor:s=>{r.push(s),i??(i=wc(e));let o=vc(t,i);return i.add(o),o},setAnchors:()=>{for(let s of r){let o=n.get(s);if(typeof o=="object"&&o.anchor&&(pe(o.node)||_e(o.node)))o.node.anchor=o.anchor;else{let u=new Error("Failed to resolve repeated object (this should not happen)");throw u.source=s,u}}},sourceObjects:n}}function pn(e,t,r,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,s=n.length;i<s;++i){let o=n[i],u=pn(e,n,String(i),o);u===void 0?delete n[i]:u!==o&&(n[i]=u)}else if(n instanceof Map)for(let i of Array.from(n.keys())){let s=n.get(i),o=pn(e,n,i,s);o===void 0?n.delete(i):o!==s&&n.set(i,o)}else if(n instanceof Set)for(let i of Array.from(n)){let s=pn(e,n,i,i);s===void 0?n.delete(i):s!==i&&(n.delete(i),n.add(s))}else for(let[i,s]of Object.entries(n)){let o=pn(e,n,i,s);o===void 0?delete n[i]:o!==s&&(n[i]=o)}return e.call(t,r,n)}function We(e,t,r){if(Array.isArray(e))return e.map((n,i)=>We(n,String(i),r));if(e&&typeof e.toJSON=="function"){if(!r||!Uo(e))return e.toJSON(t,r);let n={aliasCount:0,count:1,res:void 0};r.anchors.set(e,n),r.onCreate=s=>{n.res=s,delete r.onCreate};let i=e.toJSON(t,r);return r.onCreate&&r.onCreate(i),i}return typeof e=="bigint"&&!r?.keep?Number(e):e}var hn=class{constructor(t){Object.defineProperty(this,ht,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:n,onAnchor:i,reviver:s}={}){if(!_r(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},u=We(this,"",o);if(typeof i=="function")for(let{count:c,res:f}of o.anchors.values())i(f,c);return typeof s=="function"?pn(s,{"":u},"",u):u}};var Jr=class extends hn{constructor(t){super($o),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let n;r?.aliasResolveCache?n=r.aliasResolveCache:(n=[],Dr(t,{Node:(s,o)=>{(ar(o)||Uo(o))&&n.push(o)}}),r&&(r.aliasResolveCache=n));let i;for(let s of n){if(s===this)break;s.anchor===this.source&&(i=s)}return i}toJSON(t,r){if(!r)return{source:this.source};let{anchors:n,doc:i,maxAliasCount:s}=r,o=this.resolve(i,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let u=n.get(o);if(u||(We(o,null,r),u=n.get(o)),u?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(u.count+=1,u.aliasCount===0&&(u.aliasCount=Jo(i,o,n)),u.count*u.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return u.res}toString(t,r,n){let i=`*${this.source}`;if(t){if(Zo(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(t.implicitKey)return`${i} `}return i}};function Jo(e,t,r){if(ar(t)){let n=t.resolve(e),i=r&&n&&r.get(n);return i?i.count*i.aliasCount:0}else if(_e(t)){let n=0;for(let i of t.items){let s=Jo(e,i,r);s>n&&(n=s)}return n}else if(ge(t)){let n=Jo(e,t.key,r),i=Jo(e,t.value,r);return Math.max(n,i)}return 1}var Go=e=>!e||typeof e!="function"&&typeof e!="object",Y=class extends hn{constructor(t){super(It),this.value=t}toJSON(t,r){return r?.keep?this.value:We(this.value,t,r)}toString(){return String(this.value)}};Y.BLOCK_FOLDED="BLOCK_FOLDED";Y.BLOCK_LITERAL="BLOCK_LITERAL";Y.PLAIN="PLAIN";Y.QUOTE_DOUBLE="QUOTE_DOUBLE";Y.QUOTE_SINGLE="QUOTE_SINGLE";var _A="tag:yaml.org,2002:";function CA(e,t,r){if(t){let n=r.filter(s=>s.tag===t),i=n.find(s=>!s.format)??n[0];if(!i)throw new Error(`Tag ${t} not found`);return i}return r.find(n=>n.identify?.(e)&&!n.format)}function Gr(e,t,r){if(_r(e)&&(e=e.contents),be(e))return e;if(ge(e)){let p=r.schema[or].createNode?.(r.schema,null,r);return p.items.push(e),p}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:n,onAnchor:i,onTagObj:s,schema:o,sourceObjects:u}=r,c;if(n&&e&&typeof e=="object"){if(c=u.get(e),c)return c.anchor??(c.anchor=i(e)),new Jr(c.anchor);c={anchor:null,node:null},u.set(e,c)}t?.startsWith("!!")&&(t=_A+t.slice(2));let f=CA(e,t,o.tags);if(!f){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let p=new Y(e);return c&&(c.node=p),p}f=e instanceof Map?o[or]:Symbol.iterator in Object(e)?o[Zr]:o[or]}s&&(s(f),delete r.onTagObj);let h=f?.createNode?f.createNode(r.schema,e,r):typeof f?.nodeClass?.from=="function"?f.nodeClass.from(r.schema,e,r):new Y(e);return t?h.tag=t:f.default||(h.tag=f.tag),c&&(c.node=h),h}function vs(e,t,r){let n=r;for(let i=t.length-1;i>=0;--i){let s=t[i];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=n,n=o}else n=new Map([[s,n]])}return Gr(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var wi=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,bi=class extends hn{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(n=>be(n)||ge(n)?n.clone(t):n),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(wi(t))this.add(r);else{let[n,...i]=t,s=this.get(n,!0);if(_e(s))s.addIn(i,r);else if(s===void 0&&this.schema)this.set(n,vs(this.schema,i,r));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}deleteIn(t){let[r,...n]=t;if(n.length===0)return this.delete(r);let i=this.get(r,!0);if(_e(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}getIn(t,r){let[n,...i]=t,s=this.get(n,!0);return i.length===0?!r&&pe(s)?s.value:s:_e(s)?s.getIn(i,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!ge(r))return!1;let n=r.value;return n==null||t&&pe(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(t){let[r,...n]=t;if(n.length===0)return this.has(r);let i=this.get(r,!0);return _e(i)?i.hasIn(n):!1}setIn(t,r){let[n,...i]=t;if(i.length===0)this.set(n,r);else{let s=this.get(n,!0);if(_e(s))s.setIn(i,r);else if(s===void 0&&this.schema)this.set(n,vs(this.schema,i,r));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};var ay=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Vt(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Tr=(e,t,r)=>e.endsWith(`+`)?Vt(r,t):r.includes(``)?`-`+ge(n,e):(t.endsWith(" ")?"":" ")+n;var is="flow",Sr="block",_n="quoted";function xn(t,e,n="flow",{indentAtStart:r,lineWidth:o=80,minContentWidth:s=20,onFold:i,onOverflow:a}={}){if(!o||o<0)return t;o<s&&(s=0);let c=Math.max(1+s,1+o-e.length);if(t.length<=c)return t;let u=[],d={},l=o-e.length;typeof r=="number"&&(r>o-Math.max(2,s)?u.push(0):l=o-r);let f,p,y=!1,m=-1,h=-1,b=-1;n===Sr&&(m=wl(t,m,e.length),m!==-1&&(l=m+c));for(let A;A=t[m+=1];){if(n===_n&&A==="\\"){switch(h=m,t[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}b=m}if(A===`-`)n===Sr&&(m=wl(t,m,e.length)),l=m+e.length+c,f=void 0;else{if(A===" "&&p&&p!==" "&&p!==`-`&&p!==" "){let _=t[m+1];_&&_!==" "&&_!==`-`&&_!==" "&&(f=m)}if(m>=l)if(f)u.push(f),l=f+c,f=void 0;else if(n===_n){for(;p===" "||p===" ";)p=A,A=t[m+=1],y=!0;let _=m>b+1?m-2:h-1;if(d[_])return t;u.push(_),d[_]=!0,l=_+c,f=void 0}else y=!0}p=A}if(y&&a&&a(),u.length===0)return t;i&&i();let S=t.slice(0,u[0]);for(let A=0;A<u.length;++A){let _=u[A],w=u[A+1]||t.length;_===0?S=`-${e}${t.slice(0,w)}`:(n===_n&&d[_]&&(S+=`${t[_]}\\`),S+=`-${e}${t.slice(_+1,w)}`)}return S}function wl(t,e,n){let r=e,o=e+1,s=t[o];for(;s===" "||s===" ";)if(e<o+n)s=t[++e];else{do s=t[++e];while(s&&s!==`-`);r=e,o=e+1,s=t[o]}return r}var Er=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),vr=t=>/^(%|---|\.\.\.)/m.test(t);function Dm(t,e,n){if(!e||e<0)return!1;let r=e-n,o=t.length;if(o<=r)return!1;for(let s=0,i=0;s<o;++s)if(t[s]===`-`){if(s-i>r)return!0;if(i=s+1,o-i<=r)return!1}return!0}function Sn(t,e){let n=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=e,o=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(vr(t)?" ":""),i="",a=0;for(let c=0,u=n[c];u;u=n[++c])if(u===" "&&n[c+1]==="\\"&&n[c+2]==="n"&&(i+=n.slice(a,c)+"\\ ",c+=1,a=c,u="\\"),u==="\\")switch(n[c+1]){case"u":{i+=n.slice(a,c);let d=n.substr(c+2,4);switch(d){case"0000":i+="\\0";break;case"0007":i+="\\a";break;case"000b":i+="\\v";break;case"001b":i+="\\e";break;case"0085":i+="\\N";break;case"00a0":i+="\\_";break;case"2028":i+="\\L";break;case"2029":i+="\\P";break;default:d.substr(0,2)==="00"?i+="\\x"+d.substr(2):i+=n.substr(c,6)}c+=5,a=c+1}break;case"n":if(r||n[c+2]==='"'||n.length<o)c+=1;else{for(i+=n.slice(a,c)+`+`+Vt(r,t):(e.endsWith(" ")?"":" ")+r;var kc="flow",Qo="block",ks="quoted";function As(e,t,r="flow",{indentAtStart:n,lineWidth:i=80,minContentWidth:s=20,onFold:o,onOverflow:u}={}){if(!i||i<0)return e;i<s&&(s=0);let c=Math.max(1+s,1+i-t.length);if(e.length<=c)return e;let f=[],h={},p=i-t.length;typeof n=="number"&&(n>i-Math.max(2,s)?f.push(0):p=i-n);let m,d,x=!1,b=-1,v=-1,k=-1;r===Qo&&(b=uy(e,b,t.length),b!==-1&&(p=b+c));for(let E;E=e[b+=1];){if(r===ks&&E==="\\"){switch(v=b,e[b+1]){case"x":b+=3;break;case"u":b+=5;break;case"U":b+=9;break;default:b+=1}k=b}if(E===`+`)r===Qo&&(b=uy(e,b,t.length)),p=b+t.length+c,m=void 0;else{if(E===" "&&d&&d!==" "&&d!==`+`&&d!==" "){let g=e[b+1];g&&g!==" "&&g!==`+`&&g!==" "&&(m=b)}if(b>=p)if(m)f.push(m),p=m+c,m=void 0;else if(r===ks){for(;d===" "||d===" ";)d=E,E=e[b+=1],x=!0;let g=b>k+1?b-2:v-1;if(h[g])return e;f.push(g),h[g]=!0,p=g+c,m=void 0}else x=!0}d=E}if(x&&u&&u(),f.length===0)return e;o&&o();let T=e.slice(0,f[0]);for(let E=0;E<f.length;++E){let g=f[E],I=f[E+1]||e.length;g===0?T=`+${t}${e.slice(0,I)}`:(r===ks&&h[g]&&(T+=`${e[g]}\\`),T+=`+${t}${e.slice(g+1,I)}`)}return T}function uy(e,t,r){let n=t,i=t+1,s=e[i];for(;s===" "||s===" ";)if(t<i+r)s=e[++t];else{do s=e[++t];while(s&&s!==`+`);n=t,i=t+1,s=e[i]}return n}var Wo=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Ko=e=>/^(%|---|\.\.\.)/m.test(e);function DA(e,t,r){if(!t||t<0)return!1;let n=t-r,i=e.length;if(i<=n)return!1;for(let s=0,o=0;s<i;++s)if(e[s]===`+`){if(s-o>n)return!0;if(o=s+1,i-o<=n)return!1}return!0}function Ss(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:n}=t,i=t.options.doubleQuotedMinMultiLineLength,s=t.indent||(Ko(e)?" ":""),o="",u=0;for(let c=0,f=r[c];f;f=r[++c])if(f===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(u,c)+"\\ ",c+=1,u=c,f="\\"),f==="\\")switch(r[c+1]){case"u":{o+=r.slice(u,c);let h=r.substr(c+2,4);switch(h){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:h.substr(0,2)==="00"?o+="\\x"+h.substr(2):o+=r.substr(c,6)}c+=5,u=c+1}break;case"n":if(n||r[c+2]==='"'||r.length<i)c+=1;else{for(o+=r.slice(u,c)+`-`;n[c+2]==="\\"&&n[c+3]==="n"&&n[c+4]!=='"';)i+=`-`,c+=2;i+=s,n[c+2]===" "&&(i+="\\"),c+=1,a=c+1}break;default:c+=1}return i=a?i+n.slice(a):n,r?i:xn(i,s,_n,Er(e,!1))}function as(t,e){if(e.options.singleQuote===!1||e.implicitKey&&t.includes(`-`)||/[ \t]\n|\n[ \t]/.test(t))return Sn(t,e);let n=e.indent||(vr(t)?" ":""),r="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&-${n}`)+"'";return e.implicitKey?r:xn(r,n,is,Er(e,!1))}function Zt(t,e){let{singleQuote:n}=e.options,r;if(n===!1)r=Sn;else{let o=t.includes('"'),s=t.includes("'");o&&!s?r=as:s&&!o?r=Sn:r=n?as:Sn}return r(t,e)}var cs;try{cs=new RegExp(`(^|(?<!+`;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)o+=`+`,c+=2;o+=s,r[c+2]===" "&&(o+="\\"),c+=1,u=c+1}break;default:c+=1}return o=u?o+r.slice(u):r,n?o:As(o,s,ks,Wo(t,!1))}function Ac(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`+`)||/[ \t]\n|\n[ \t]/.test(e))return Ss(e,t);let r=t.indent||(Ko(e)?" ":""),n="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&+${r}`)+"'";return t.implicitKey?n:As(n,r,kc,Wo(t,!1))}function vi(e,t){let{singleQuote:r}=t.options,n;if(r===!1)n=Ss;else{let i=e.includes('"'),s=e.includes("'");i&&!s?n=Ac:s&&!i?n=Ss:n=r?Ac:Ss}return n(e,t)}var Sc;try{Sc=new RegExp(`(^|(?<!))+(?!-|$)`,"g")}catch{cs=/\n+(?!\n|$)/g}function Ar({comment:t,type:e,value:n},r,o,s){let{blockQuote:i,commentString:a,lineWidth:c}=r.options;if(!i||/\n[\t ]+$/.test(n))return Zt(n,r);let u=r.indent||(r.forceBlockIndent||vr(n)?" ":""),d=i==="literal"?!0:i==="folded"||e===D.BLOCK_FOLDED?!1:e===D.BLOCK_LITERAL?!0:!Dm(n,c,u.length);if(!n)return d?`|+|$)`,"g")}catch{Sc=/\n+(?!\n|$)/g}function Ho({comment:e,type:t,value:r},n,i,s){let{blockQuote:o,commentString:u,lineWidth:c}=n.options;if(!o||/\n[\t ]+$/.test(r))return vi(r,n);let f=n.indent||(n.forceBlockIndent||Ko(r)?" ":""),h=o==="literal"?!0:o==="folded"||t===Y.BLOCK_FOLDED?!1:t===Y.BLOCK_LITERAL?!0:!DA(r,c,f.length);if(!r)return h?`|`:`>-`;let l,f;for(f=n.length;f>0;--f){let w=n[f-1];if(w!==`-`&&w!==" "&&w!==" ")break}let p=n.substring(f),y=p.indexOf(`-`);y===-1?l="-":n===p||y!==p.length-1?(l="+",s&&s()):l="",p&&(n=n.slice(0,-p.length),p[p.length-1]===`-`&&(p=p.slice(0,-1)),p=p.replace(cs,`$&${u}`));let m=!1,h,b=-1;for(h=0;h<n.length;++h){let w=n[h];if(w===" ")m=!0;else if(w===`-`)b=h;else break}let S=n.substring(0,b<h?b+1:h);S&&(n=n.substring(S.length),S=S.replace(/\n+/g,`$&${u}`));let _=(m?u?"2":"1":"")+l;if(t&&(_+=" "+a(t.replace(/ ?[\r\n]+/g," ")),o&&o()),!d){let w=n.replace(/\n+/g,`-$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`),E=!1,k=Er(r,!0);i!=="folded"&&e!==D.BLOCK_FOLDED&&(k.onOverflow=()=>{E=!0});let x=xn(`${S}${w}${p}`,u,Sr,k);if(!E)return`>${_}-${u}${x}`}return n=n.replace(/\n+/g,`$&${u}`),`|${_}-${u}${S}${n}${p}`}function Rm(t,e,n,r){let{type:o,value:s}=t,{actualString:i,implicitKey:a,indent:c,indentStep:u,inFlow:d}=e;if(a&&s.includes(`-`)||d&&/[[\]{},]/.test(s))return Zt(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||d||!s.includes(`-`)?Zt(s,e):Ar(t,e,n,r);if(!a&&!d&&o!==D.PLAIN&&s.includes(`-`))return Ar(t,e,n,r);if(vr(s)){if(c==="")return e.forceBlockIndent=!0,Ar(t,e,n,r);if(a&&c===u)return Zt(s,e)}let l=s.replace(/\n+/g,`$&-${c}`);if(i){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(l),{compat:p,tags:y}=e.doc.schema;if(y.some(f)||p?.some(f))return Zt(s,e)}return a?l:xn(l,c,is,Er(e,!1))}function bt(t,e,n,r){let{implicitKey:o,inFlow:s}=e,i=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:a}=t;a!==D.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(i.value)&&(a=D.QUOTE_DOUBLE);let c=d=>{switch(d){case D.BLOCK_FOLDED:case D.BLOCK_LITERAL:return o||s?Zt(i.value,e):Ar(i,e,n,r);case D.QUOTE_DOUBLE:return Sn(i.value,e);case D.QUOTE_SINGLE:return as(i.value,e);case D.PLAIN:return Rm(i,e,n,r);default:return null}},u=c(a);if(u===null){let{defaultKeyType:d,defaultStringType:l}=e.options,f=o&&d||l;if(u=c(f),u===null)throw new Error(`Unsupported default string type ${f}`)}return u}function kr(t,e){let n=Object.assign({blockQuote:!0,commentString:bl,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),r;switch(n.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:t,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:r,options:n}}function Im(t,e){if(e.tag){let o=t.filter(s=>s.tag===e.tag);if(o.length>0)return o.find(s=>s.format===e.format)??o[0]}let n,r;if(N(e)){r=e.value;let o=t.filter(s=>s.identify?.(r));if(o.length>1){let s=o.filter(i=>i.test);s.length>0&&(o=s)}n=o.find(s=>s.format===e.format)??o.find(s=>!s.format)}else r=e,n=t.find(o=>o.nodeClass&&r instanceof o.nodeClass);if(!n){let o=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${o} value`)}return n}function Om(t,e,{anchors:n,doc:r}){if(!r.directives)return"";let o=[],s=(N(t)||j(t))&&t.anchor;s&&wr(s)&&(n.add(s),o.push(`&${s}`));let i=t.tag??(e.default?null:e.tag);return i&&o.push(r.directives.tagString(i)),o.join(" ")}function We(t,e,n,r){if(T(t))return t.toString(e,n,r);if(Se(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let o,s=P(t)?t:e.doc.createNode(t,{onTagObj:c=>o=c});o??(o=Im(e.doc.schema.tags,s));let i=Om(s,o,e);i.length>0&&(e.indentAtStart=(e.indentAtStart??0)+i.length+1);let a=typeof o.stringify=="function"?o.stringify(s,e,n,r):N(s)?bt(s,e,n,r):s.toString(e,n,r);return i?N(s)||a[0]==="{"||a[0]==="["?`${i} ${a}`:`${i}-${e.indent}${a}`:a}function _l({key:t,value:e},n,r,o){let{allNullValues:s,doc:i,indent:a,indentStep:c,options:{commentString:u,indentSeq:d,simpleKeys:l}}=n,f=P(t)&&t.comment||null;if(l){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(j(t)||!P(t)&&typeof t=="object"){let k="With simple keys, collection cannot be used as a key value";throw new Error(k)}}let p=!l&&(!t||f&&e==null&&!n.inFlow||j(t)||(N(t)?t.type===D.BLOCK_FOLDED||t.type===D.BLOCK_LITERAL:typeof t=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(l||!s),indent:a+c});let y=!1,m=!1,h=We(t,n,()=>y=!0,()=>m=!0);if(!p&&!n.inFlow&&h.length>1024){if(l)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(n.inFlow){if(s||e==null)return y&&r&&r(),h===""?"?":p?`? ${h}`:h}else if(s&&!l||e==null&&p)return h=`? ${h}`,f&&!y?h+=je(h,n.indent,u(f)):m&&o&&o(),h;y&&(f=null),p?(f&&(h+=je(h,n.indent,u(f))),h=`? ${h}-${a}:`):(h=`${h}:`,f&&(h+=je(h,n.indent,u(f))));let b,S,A;P(e)?(b=!!e.spaceBefore,S=e.commentBefore,A=e.comment):(b=!1,S=null,A=null,e&&typeof e=="object"&&(e=i.createNode(e))),n.implicitKey=!1,!p&&!f&&N(e)&&(n.indentAtStart=h.length+1),m=!1,!d&&c.length>=2&&!n.inFlow&&!p&&Ee(e)&&!e.flow&&!e.tag&&!e.anchor&&(n.indent=n.indent.substring(2));let _=!1,w=We(e,n,()=>_=!0,()=>m=!0),E=" ";if(f||b||S){if(E=b?`-`:"",S){let k=u(S);E+=`-${ge(k,n.indent)}`}w===""&&!n.inFlow?E===`-`&&A&&(E=`+`;let p,m;for(m=r.length;m>0;--m){let I=r[m-1];if(I!==`+`&&I!==" "&&I!==" ")break}let d=r.substring(m),x=d.indexOf(`+`);x===-1?p="-":r===d||x!==d.length-1?(p="+",s&&s()):p="",d&&(r=r.slice(0,-d.length),d[d.length-1]===`+`&&(d=d.slice(0,-1)),d=d.replace(Sc,`$&${f}`));let b=!1,v,k=-1;for(v=0;v<r.length;++v){let I=r[v];if(I===" ")b=!0;else if(I===`+`)k=v;else break}let T=r.substring(0,k<v?k+1:v);T&&(r=r.substring(T.length),T=T.replace(/\n+/g,`$&${f}`));let g=(b?f?"2":"1":"")+p;if(e&&(g+=" "+u(e.replace(/ ?[\r\n]+/g," ")),i&&i()),!h){let I=r.replace(/\n+/g,`+$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${f}`),_=!1,D=Wo(n,!0);o!=="folded"&&t!==Y.BLOCK_FOLDED&&(D.onOverflow=()=>{_=!0});let O=As(`${T}${I}${d}`,f,Qo,D);if(!_)return`>${g}+${f}${O}`}return r=r.replace(/\n+/g,`$&${f}`),`|${g}+${f}${T}${r}${d}`}function IA(e,t,r,n){let{type:i,value:s}=e,{actualString:o,implicitKey:u,indent:c,indentStep:f,inFlow:h}=t;if(u&&s.includes(`+`)||h&&/[[\]{},]/.test(s))return vi(s,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return u||h||!s.includes(`+`)?vi(s,t):Ho(e,t,r,n);if(!u&&!h&&i!==Y.PLAIN&&s.includes(`+`))return Ho(e,t,r,n);if(Ko(s)){if(c==="")return t.forceBlockIndent=!0,Ho(e,t,r,n);if(u&&c===f)return vi(s,t)}let p=s.replace(/\n+/g,`$&+${c}`);if(o){let m=b=>b.default&&b.tag!=="tag:yaml.org,2002:str"&&b.test?.test(p),{compat:d,tags:x}=t.doc.schema;if(x.some(m)||d?.some(m))return vi(s,t)}return u?p:As(p,c,kc,Wo(t,!1))}function Fn(e,t,r,n){let{implicitKey:i,inFlow:s}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:u}=e;u!==Y.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(u=Y.QUOTE_DOUBLE);let c=h=>{switch(h){case Y.BLOCK_FOLDED:case Y.BLOCK_LITERAL:return i||s?vi(o.value,t):Ho(o,t,r,n);case Y.QUOTE_DOUBLE:return Ss(o.value,t);case Y.QUOTE_SINGLE:return Ac(o.value,t);case Y.PLAIN:return IA(o,t,r,n);default:return null}},f=c(u);if(f===null){let{defaultKeyType:h,defaultStringType:p}=t.options,m=i&&h||p;if(f=c(m),f===null)throw new Error(`Unsupported default string type ${m}`)}return f}function Xo(e,t){let r=Object.assign({blockQuote:!0,commentString:ay,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),n;switch(r.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:n,options:r}}function TA(e,t){if(t.tag){let i=e.filter(s=>s.tag===t.tag);if(i.length>0)return i.find(s=>s.format===t.format)??i[0]}let r,n;if(pe(t)){n=t.value;let i=e.filter(s=>s.identify?.(n));if(i.length>1){let s=i.filter(o=>o.test);s.length>0&&(i=s)}r=i.find(s=>s.format===t.format)??i.find(s=>!s.format)}else n=t,r=e.find(i=>i.nodeClass&&n instanceof i.nodeClass);if(!r){let i=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${i} value`)}return r}function RA(e,t,{anchors:r,doc:n}){if(!n.directives)return"";let i=[],s=(pe(e)||_e(e))&&e.anchor;s&&Zo(s)&&(r.add(s),i.push(`&${s}`));let o=e.tag??(t.default?null:t.tag);return o&&i.push(n.directives.tagString(o)),i.join(" ")}function Qr(e,t,r,n){if(ge(e))return e.toString(t,r,n);if(ar(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i,s=be(e)?e:t.doc.createNode(e,{onTagObj:c=>i=c});i??(i=TA(t.doc.schema.tags,s));let o=RA(s,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let u=typeof i.stringify=="function"?i.stringify(s,t,r,n):pe(s)?Fn(s,t,r,n):s.toString(t,r,n);return o?pe(s)||u[0]==="{"||u[0]==="["?`${o} ${u}`:`${o}+${t.indent}${u}`:u}function cy({key:e,value:t},r,n,i){let{allNullValues:s,doc:o,indent:u,indentStep:c,options:{commentString:f,indentSeq:h,simpleKeys:p}}=r,m=be(e)&&e.comment||null;if(p){if(m)throw new Error("With simple keys, key nodes cannot have comments");if(_e(e)||!be(e)&&typeof e=="object"){let D="With simple keys, collection cannot be used as a key value";throw new Error(D)}}let d=!p&&(!e||m&&t==null&&!r.inFlow||_e(e)||(pe(e)?e.type===Y.BLOCK_FOLDED||e.type===Y.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!d&&(p||!s),indent:u+c});let x=!1,b=!1,v=Qr(e,r,()=>x=!0,()=>b=!0);if(!d&&!r.inFlow&&v.length>1024){if(p)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");d=!0}if(r.inFlow){if(s||t==null)return x&&n&&n(),v===""?"?":d?`? ${v}`:v}else if(s&&!p||t==null&&d)return v=`? ${v}`,m&&!x?v+=Tr(v,r.indent,f(m)):b&&i&&i(),v;x&&(m=null),d?(m&&(v+=Tr(v,r.indent,f(m))),v=`? ${v}+${u}:`):(v=`${v}:`,m&&(v+=Tr(v,r.indent,f(m))));let k,T,E;be(t)?(k=!!t.spaceBefore,T=t.commentBefore,E=t.comment):(k=!1,T=null,E=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!d&&!m&&pe(t)&&(r.indentAtStart=v.length+1),b=!1,!h&&c.length>=2&&!r.inFlow&&!d&&cr(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let g=!1,I=Qr(t,r,()=>g=!0,()=>b=!0),_=" ";if(m||k||T){if(_=k?`+`:"",T){let D=f(T);_+=`+${Vt(D,r.indent)}`}I===""&&!r.inFlow?_===`+`&&E&&(_=`-`):E+=`-${n.indent}`}else if(!p&&j(e)){let k=w[0],x=w.indexOf(`-`),O=x!==-1,M=n.inFlow??e.flow??e.items.length===0;if(O||!M){let B=!1;if(O&&(k==="&"||k==="!")){let $=w.indexOf(" ");k==="&"&&$!==-1&&$<x&&w[$+1]==="!"&&($=w.indexOf(" ",$+1)),($===-1||x<$)&&(B=!0)}B||(E=`-${n.indent}`)}}else(w===""||w[0]===`-`)&&(E="");return h+=E+w,n.inFlow?_&&r&&r():A&&!_?h+=je(h,n.indent,u(A)):m&&o&&o(),h}function us(t,e){(t==="debug"||t==="warn")&&console.warn(e)}var Dr="<<",ve={identify:t=>t===Dr||typeof t=="symbol"&&t.description===Dr,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new D(Symbol(Dr)),{addToJSMap:fs}),stringify:()=>Dr},xl=(t,e)=>(ve.identify(e)||N(e)&&(!e.type||e.type===D.PLAIN)&&ve.identify(e.value))&&t?.doc.schema.tags.some(n=>n.tag===ve.tag&&n.default);function fs(t,e,n){let r=Sl(t,n);if(Ee(r))for(let o of r.items)ls(t,e,o);else if(Array.isArray(r))for(let o of r)ls(t,e,o);else ls(t,e,r)}function ls(t,e,n){let r=Sl(t,n);if(!Ae(r))throw new Error("Merge sources must be maps or map aliases");let o=r.toJSON(null,t,Map);for(let[s,i]of o)e instanceof Map?e.has(s)||e.set(s,i):e instanceof Set?e.add(s):Object.prototype.hasOwnProperty.call(e,s)||Object.defineProperty(e,s,{value:i,writable:!0,enumerable:!0,configurable:!0});return e}function Sl(t,e){return t&&Se(e)?e.resolve(t.doc,t):e}function Rr(t,e,{key:n,value:r}){if(P(n)&&n.addToJSMap)n.addToJSMap(t,e,r);else if(xl(t,n))fs(t,e,r);else{let o=Y(n,"",t);if(e instanceof Map)e.set(o,Y(r,o,t));else if(e instanceof Set)e.add(o);else{let s=Cm(n,o,t),i=Y(r,s,t);s in e?Object.defineProperty(e,s,{value:i,writable:!0,enumerable:!0,configurable:!0}):e[s]=i}}return e}function Cm(t,e,n){if(e===null)return"";if(typeof e!="object")return String(e);if(P(t)&&n?.doc){let r=kr(n.doc,{});r.anchors=new Set;for(let s of n.anchors.keys())r.anchors.add(s.anchor);r.inFlow=!0,r.inStringifyKey=!0;let o=t.toString(r);if(!n.mapKeyWarned){let s=JSON.stringify(o);s.length>40&&(s=s.substring(0,36)+'..."'),us(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return o}return JSON.stringify(e)}function jt(t,e,n){let r=Ke(t,void 0,n),o=Ke(e,void 0,n);return new K(r,o)}var K=class t{constructor(e,n=null){Object.defineProperty(this,oe,{value:rs}),this.key=e,this.value=n}clone(e){let{key:n,value:r}=this;return P(n)&&(n=n.clone(e)),P(r)&&(r=r.clone(e)),new t(n,r)}toJSON(e,n){let r=n?.mapAsMap?new Map:{};return Rr(n,r,this)}toString(e,n,r){return e?.doc?_l(this,e,n,r):JSON.stringify(this)}};function Or(t,e,n){return(e.inFlow??t.flow?$m:Nm)(t,e,n)}function Nm({comment:t,items:e},n,{blockItemPrefix:r,flowChars:o,itemIndent:s,onChompKeep:i,onComment:a}){let{indent:c,options:{commentString:u}}=n,d=Object.assign({},n,{indent:s,type:null}),l=!1,f=[];for(let y=0;y<e.length;++y){let m=e[y],h=null;if(P(m))!l&&m.spaceBefore&&f.push(""),Ir(n,f,m.commentBefore,l),m.comment&&(h=m.comment);else if(T(m)){let S=P(m.key)?m.key:null;S&&(!l&&S.spaceBefore&&f.push(""),Ir(n,f,S.commentBefore,l))}l=!1;let b=We(m,d,()=>h=null,()=>l=!0);h&&(b+=je(b,s,u(h))),l&&h&&(l=!1),f.push(r+b)}let p;if(f.length===0)p=o.start+o.end;else{p=f[0];for(let y=1;y<f.length;++y){let m=f[y];p+=m?`-${c}${m}`:`-`}}return t?(p+=`-`+ge(u(t),c),a&&a()):l&&i&&i(),p}function $m({items:t},e,{flowChars:n,itemIndent:r}){let{indent:o,indentStep:s,flowCollectionPadding:i,options:{commentString:a}}=e;r+=s;let c=Object.assign({},e,{indent:r,inFlow:!0,type:null}),u=!1,d=0,l=[];for(let y=0;y<t.length;++y){let m=t[y],h=null;if(P(m))m.spaceBefore&&l.push(""),Ir(e,l,m.commentBefore,!1),m.comment&&(h=m.comment);else if(T(m)){let S=P(m.key)?m.key:null;S&&(S.spaceBefore&&l.push(""),Ir(e,l,S.commentBefore,!1),S.comment&&(u=!0));let A=P(m.value)?m.value:null;A?(A.comment&&(h=A.comment),A.commentBefore&&(u=!0)):m.value==null&&S?.comment&&(h=S.comment)}h&&(u=!0);let b=We(m,c,()=>h=null);u||(u=l.length>d||b.includes(`-`)),y<t.length-1?b+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(u||(u=l.reduce((S,A)=>S+A.length+2,2)+(b.length+2)>e.options.lineWidth)),u&&(b+=",")),h&&(b+=je(b,r,a(h))),l.push(b),d=l.length}let{start:f,end:p}=n;if(l.length===0)return f+p;if(!u){let y=l.reduce((m,h)=>m+h.length+2,2);u=e.options.lineWidth>0&&y>e.options.lineWidth}if(u){let y=f;for(let m of l)y+=m?`-${s}${o}${m}`:`-`;return`${y}-${o}${p}`}else return`${f}${i}${l.join(" ")}${i}${p}`}function Ir({indent:t,options:{commentString:e}},n,r,o){if(r&&o&&(r=r.replace(/^\n+/,"")),r){let s=ge(e(r),t);n.push(s.trimStart())}}function ct(t,e){let n=N(e)?e.value:e;for(let r of t)if(T(r)&&(r.key===e||r.key===n||N(r.key)&&r.key.value===n))return r}var W=class extends Mt{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(xe,e),this.items=[]}static from(e,n,r){let{keepUndefined:o,replacer:s}=r,i=new this(e),a=(c,u)=>{if(typeof s=="function")u=s.call(n,c,u);else if(Array.isArray(s)&&!s.includes(c))return;(u!==void 0||o)&&i.items.push(jt(c,u,r))};if(n instanceof Map)for(let[c,u]of n)a(c,u);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof e.sortMapEntries=="function"&&i.items.sort(e.sortMapEntries),i}add(e,n){let r;T(e)?r=e:!e||typeof e!="object"||!("key"in e)?r=new K(e,e?.value):r=new K(e.key,e.value);let o=ct(this.items,r.key),s=this.schema?.sortMapEntries;if(o){if(!n)throw new Error(`Key ${r.key} already set`);N(o.value)&&xr(r.value)?o.value.value=r.value:o.value=r.value}else if(s){let i=this.items.findIndex(a=>s(r,a)<0);i===-1?this.items.push(r):this.items.splice(i,0,r)}else this.items.push(r)}delete(e){let n=ct(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){let o=ct(this.items,e)?.value;return(!n&&N(o)?o.value:o)??void 0}has(e){return!!ct(this.items,e)}set(e,n){this.add(new K(e,n),!0)}toJSON(e,n,r){let o=r?new r:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(o);for(let s of this.items)Rr(n,o,s);return o}toString(e,n,r){if(!e)return JSON.stringify(this);for(let o of this.items)if(!T(o))throw new Error(`Map items must all be pairs; found ${JSON.stringify(o)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Or(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:n})}};var ke={collection:"map",default:!0,nodeClass:W,tag:"tag:yaml.org,2002:map",resolve(t,e){return Ae(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,n)=>W.from(t,e,n)};var ee=class extends Mt{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(qe,e),this.items=[]}add(e){this.items.push(e)}delete(e){let n=Cr(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){let r=Cr(e);if(typeof r!="number")return;let o=this.items[r];return!n&&N(o)?o.value:o}has(e){let n=Cr(e);return typeof n=="number"&&n<this.items.length}set(e,n){let r=Cr(e);if(typeof r!="number")throw new Error(`Expected a valid index, not ${e}.`);let o=this.items[r];N(o)&&xr(n)?o.value=n:this.items[r]=n}toJSON(e,n){let r=[];n?.onCreate&&n.onCreate(r);let o=0;for(let s of this.items)r.push(Y(s,String(o++),n));return r}toString(e,n,r){return e?Or(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:r,onComment:n}):JSON.stringify(this)}static from(e,n,r){let{replacer:o}=r,s=new this(e);if(n&&Symbol.iterator in Object(n)){let i=0;for(let a of n){if(typeof o=="function"){let c=n instanceof Set?a:String(i++);a=o.call(n,c,a)}s.items.push(Ke(a,void 0,r))}}return s}};function Cr(t){let e=N(t)?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}var De={collection:"seq",default:!0,nodeClass:ee,tag:"tag:yaml.org,2002:seq",resolve(t,e){return Ee(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,n)=>ee.from(t,e,n)};var ut={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,n,r){return e=Object.assign({actualString:!0},e),bt(t,e,n,r)}};var wt={identify:t=>t==null,createNode:()=>new D(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new D(null),stringify:({source:t},e)=>typeof t=="string"&&wt.test.test(t)?t:e.options.nullStr};var An={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new D(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},n){if(t&&An.test.test(t)){let r=t[0]==="t"||t[0]==="T";if(e===r)return t}return e?n.options.trueStr:n.options.falseStr}};function te({format:t,minFractionDigits:e,tag:n,value:r}){if(typeof r=="bigint")return String(r);let o=typeof r=="number"?r:Number(r);if(!isFinite(o))return isNaN(o)?".nan":o<0?"-.inf":".inf";let s=Object.is(r,-0)?"-0":JSON.stringify(r);if(!t&&e&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let i=s.indexOf(".");i<0&&(i=s.length,s+=".");let a=e-(s.length-i-1);for(;a-- >0;)s+="0"}return s}var Nr={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:te},$r={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():te(t)}},Tr={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new D(parseFloat(t)),n=t.indexOf(".");return n!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-n-1),e},stringify:te};var zr=t=>typeof t=="bigint"||Number.isInteger(t),ds=(t,e,n,{intAsBigInt:r})=>r?BigInt(t):parseInt(t.substring(e),n);function Al(t,e,n){let{value:r}=t;return zr(r)&&r>=0?n+r.toString(e):te(t)}var Pr={identify:t=>zr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,n)=>ds(t,2,8,n),stringify:t=>Al(t,8,"0o")},Lr={identify:zr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,n)=>ds(t,0,10,n),stringify:te},Mr={identify:t=>zr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,n)=>ds(t,2,16,n),stringify:t=>Al(t,16,"0x")};var El=[ke,De,ut,wt,An,Pr,Lr,Mr,Nr,$r,Tr];function vl(t){return typeof t=="bigint"||Number.isInteger(t)}var Fr=({value:t})=>JSON.stringify(t),Tm=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:Fr},{identify:t=>t==null,createNode:()=>new D(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Fr},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:Fr},{identify:vl,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:n})=>n?BigInt(t):parseInt(t,10),stringify:({value:t})=>vl(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:Fr}],zm={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},kl=[ke,De].concat(Tm,zm);var En={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof atob=="function"){let n=atob(t.replace(/[\n\r]/g,"")),r=new Uint8Array(n.length);for(let o=0;o<n.length;++o)r[o]=n.charCodeAt(o);return r}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),t},stringify({comment:t,type:e,value:n},r,o,s){if(!n)return"";let i=n,a;if(typeof btoa=="function"){let c="";for(let u=0;u<i.length;++u)c+=String.fromCharCode(i[u]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=D.BLOCK_LITERAL),e!==D.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),u=Math.ceil(a.length/c),d=new Array(u);for(let l=0,f=0;l<u;++l,f+=c)d[l]=a.substr(f,c);a=d.join(e===D.BLOCK_LITERAL?`-`:" ")}return bt({comment:t,type:e,value:a},r,o,s)}};function ps(t,e){if(Ee(t))for(let n=0;n<t.items.length;++n){let r=t.items[n];if(!T(r)){if(Ae(r)){r.items.length>1&&e("Each pair must have its own sequence indicator");let o=r.items[0]||new K(new D(null));if(r.commentBefore&&(o.key.commentBefore=o.key.commentBefore?`${r.commentBefore}-${o.key.commentBefore}`:r.commentBefore),r.comment){let s=o.value??o.key;s.comment=s.comment?`${r.comment}-${s.comment}`:r.comment}r=o}t.items[n]=T(r)?r:new K(r)}}else e("Expected a sequence for this tag");return t}function ms(t,e,n){let{replacer:r}=n,o=new ee(t);o.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let i of e){typeof r=="function"&&(i=r.call(e,String(s++),i));let a,c;if(Array.isArray(i))if(i.length===2)a=i[0],c=i[1];else throw new TypeError(`Expected [key, value] tuple: ${i}`);else if(i&&i instanceof Object){let u=Object.keys(i);if(u.length===1)a=u[0],c=i[a];else throw new TypeError(`Expected tuple with one key, not ${u.length} keys`)}else a=i;o.items.push(jt(a,c,n))}return o}var vn={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:ps,createNode:ms};var Bt=class t extends ee{constructor(){super(),this.add=W.prototype.add.bind(this),this.delete=W.prototype.delete.bind(this),this.get=W.prototype.get.bind(this),this.has=W.prototype.has.bind(this),this.set=W.prototype.set.bind(this),this.tag=t.tag}toJSON(e,n){if(!n)return super.toJSON(e);let r=new Map;n?.onCreate&&n.onCreate(r);for(let o of this.items){let s,i;if(T(o)?(s=Y(o.key,"",n),i=Y(o.value,s,n)):s=Y(o,"",n),r.has(s))throw new Error("Ordered maps must not include duplicate keys");r.set(s,i)}return r}static from(e,n,r){let o=ms(e,n,r),s=new this;return s.items=o.items,s}};Bt.tag="tag:yaml.org,2002:omap";var kn={collection:"seq",identify:t=>t instanceof Map,nodeClass:Bt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let n=ps(t,e),r=[];for(let{key:o}of n.items)N(o)&&(r.includes(o.value)?e(`Ordered maps must not include duplicate keys: ${o.value}`):r.push(o.value));return Object.assign(new Bt,n)},createNode:(t,e,n)=>Bt.from(t,e,n)};function Dl({value:t,source:e},n){return e&&(t?hs:ys).test.test(e)?e:t?n.options.trueStr:n.options.falseStr}var hs={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new D(!0),stringify:Dl},ys={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new D(!1),stringify:Dl};var Rl={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:te},Il={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():te(t)}},Ol={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new D(parseFloat(t.replace(/_/g,""))),n=t.indexOf(".");if(n!==-1){let r=t.substring(n+1).replace(/_/g,"");r[r.length-1]==="0"&&(e.minFractionDigits=r.length)}return e},stringify:te};var Dn=t=>typeof t=="bigint"||Number.isInteger(t);function Zr(t,e,n,{intAsBigInt:r}){let o=t[0];if((o==="-"||o==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),r){switch(n){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let i=BigInt(t);return o==="-"?BigInt(-1)*i:i}let s=parseInt(t,n);return o==="-"?-1*s:s}function gs(t,e,n){let{value:r}=t;if(Dn(r)){let o=r.toString(e);return r<0?"-"+n+o.substr(1):n+o}return te(t)}var Cl={identify:Dn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,n)=>Zr(t,2,2,n),stringify:t=>gs(t,2,"0b")},Nl={identify:Dn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,n)=>Zr(t,1,8,n),stringify:t=>gs(t,8,"0")},$l={identify:Dn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,n)=>Zr(t,0,10,n),stringify:te},Tl={identify:Dn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,n)=>Zr(t,2,16,n),stringify:t=>gs(t,16,"0x")};var Ut=class t extends W{constructor(e){super(e),this.tag=t.tag}add(e){let n;T(e)?n=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?n=new K(e.key,null):n=new K(e,null),ct(this.items,n.key)||this.items.push(n)}get(e,n){let r=ct(this.items,e);return!n&&T(r)?N(r.key)?r.key.value:r.key:r}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let r=ct(this.items,e);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new K(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),n,r);throw new Error("Set items must all have null values")}static from(e,n,r){let{replacer:o}=r,s=new this(e);if(n&&Symbol.iterator in Object(n))for(let i of n)typeof o=="function"&&(i=o.call(n,i,i)),s.items.push(jt(i,null,r));return s}};Ut.tag="tag:yaml.org,2002:set";var Rn={collection:"map",identify:t=>t instanceof Set,nodeClass:Ut,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,n)=>Ut.from(t,e,n),resolve(t,e){if(Ae(t)){if(t.hasAllNullValues(!0))return Object.assign(new Ut,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};function bs(t,e){let n=t[0],r=n==="-"||n==="+"?t.substring(1):t,o=i=>e?BigInt(i):Number(i),s=r.replace(/_/g,"").split(":").reduce((i,a)=>i*o(60)+o(a),o(0));return n==="-"?o(-1)*s:s}function zl(t){let{value:e}=t,n=i=>i;if(typeof e=="bigint")n=i=>BigInt(i);else if(isNaN(e)||!isFinite(e))return te(t);let r="";e<0&&(r="-",e*=n(-1));let o=n(60),s=[e%o];return e<60?s.unshift(0):(e=(e-s[0])/o,s.unshift(e%o),e>=60&&(e=(e-s[0])/o,s.unshift(e))),r+s.map(i=>String(i).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var jr={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:n})=>bs(t,n),stringify:zl},Br={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>bs(t,!1),stringify:zl},Qt={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(Qt.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,r,o,s,i,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,u=Date.UTC(n,r-1,o,s||0,i||0,a||0,c),d=e[8];if(d&&d!=="Z"){let l=bs(d,!1);Math.abs(l)<30&&(l*=60),u-=6e4*l}return new Date(u)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};var ws=[ke,De,ut,wt,hs,ys,Cl,Nl,$l,Tl,Rl,Il,Ol,En,ve,kn,vn,Rn,jr,Br,Qt];var Pl=new Map([["core",El],["failsafe",[ke,De,ut]],["json",kl],["yaml11",ws],["yaml-1.1",ws]]),Ll={binary:En,bool:An,float:Tr,floatExp:$r,floatNaN:Nr,floatTime:Br,int:Lr,intHex:Mr,intOct:Pr,intTime:jr,map:ke,merge:ve,null:wt,omap:kn,pairs:vn,seq:De,set:Rn,timestamp:Qt},Ml={"tag:yaml.org,2002:binary":En,"tag:yaml.org,2002:merge":ve,"tag:yaml.org,2002:omap":kn,"tag:yaml.org,2002:pairs":vn,"tag:yaml.org,2002:set":Rn,"tag:yaml.org,2002:timestamp":Qt};function Ur(t,e,n){let r=Pl.get(e);if(r&&!t)return n&&!r.includes(ve)?r.concat(ve):r.slice();let o=r;if(!o)if(Array.isArray(t))o=[];else{let s=Array.from(Pl.keys()).filter(i=>i!=="yaml11").map(i=>JSON.stringify(i)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${s} or define customTags array`)}if(Array.isArray(t))for(let s of t)o=o.concat(s);else typeof t=="function"&&(o=t(o.slice()));return n&&(o=o.concat(ve)),o.reduce((s,i)=>{let a=typeof i=="string"?Ll[i]:i;if(!a){let c=JSON.stringify(i),u=Object.keys(Ll).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${u}`)}return s.includes(a)||s.push(a),s},[])}var Pm=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,In=class t{constructor({compat:e,customTags:n,merge:r,resolveKnownTags:o,schema:s,sortMapEntries:i,toStringDefaults:a}){this.compat=Array.isArray(e)?Ur(e,"compat"):e?Ur(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=o?Ml:{},this.tags=Ur(n,this.name,r),this.toStringOptions=a??null,Object.defineProperty(this,xe,{value:ke}),Object.defineProperty(this,me,{value:ut}),Object.defineProperty(this,qe,{value:De}),this.sortMapEntries=typeof i=="function"?i:i===!0?Pm:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function Fl(t,e){let n=[],r=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(n.push(c),r=!0):t.directives.docStart&&(r=!0)}r&&n.push("---");let o=kr(t,e),{commentString:s}=o.options;if(t.commentBefore){n.length!==1&&n.unshift("");let c=s(t.commentBefore);n.unshift(ge(c,""))}let i=!1,a=null;if(t.contents){if(P(t.contents)){if(t.contents.spaceBefore&&r&&n.push(""),t.contents.commentBefore){let d=s(t.contents.commentBefore);n.push(ge(d,""))}o.forceBlockIndent=!!t.comment,a=t.contents.comment}let c=a?void 0:()=>i=!0,u=We(t.contents,o,()=>a=null,c);a&&(u+=je(u,"",s(a))),(u[0]==="|"||u[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${u}`:n.push(u)}else n.push(We(t.contents,o));if(t.directives?.docEnd)if(t.comment){let c=s(t.comment);c.includes(`-`)?(n.push("..."),n.push(ge(c,""))):n.push(`... ${c}`)}else n.push("...");else{let c=t.comment;c&&i&&(c=c.replace(/^\n+/,"")),c&&((!i||a)&&n[n.length-1]!==""&&n.push(""),n.push(ge(s(c),"")))}return n.join(`+`):_+=`+${r.indent}`}else if(!d&&_e(t)){let D=I[0],O=I.indexOf(`+`),M=O!==-1,P=r.inFlow??t.flow??t.items.length===0;if(M||!P){let J=!1;if(M&&(D==="&"||D==="!")){let V=I.indexOf(" ");D==="&"&&V!==-1&&V<O&&I[V+1]==="!"&&(V=I.indexOf(" ",V+1)),(V===-1||O<V)&&(J=!0)}J||(_=`+${r.indent}`)}}else(I===""||I[0]===`+`)&&(_="");return v+=_+I,r.inFlow?g&&n&&n():E&&!g?v+=Tr(v,r.indent,f(E)):b&&i&&i(),v}function Ec(e,t){(e==="debug"||e==="warn")&&console.warn(t)}var Yo="<<",lr={identify:e=>e===Yo||typeof e=="symbol"&&e.description===Yo,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Y(Symbol(Yo)),{addToJSMap:Cc}),stringify:()=>Yo},ly=(e,t)=>(lr.identify(t)||pe(t)&&(!t.type||t.type===Y.PLAIN)&&lr.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===lr.tag&&r.default);function Cc(e,t,r){let n=fy(e,r);if(cr(n))for(let i of n.items)_c(e,t,i);else if(Array.isArray(n))for(let i of n)_c(e,t,i);else _c(e,t,n)}function _c(e,t,r){let n=fy(e,r);if(!ur(n))throw new Error("Merge sources must be maps or map aliases");let i=n.toJSON(null,e,Map);for(let[s,o]of i)t instanceof Map?t.has(s)||t.set(s,o):t instanceof Set?t.add(s):Object.prototype.hasOwnProperty.call(t,s)||Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function fy(e,t){return e&&ar(t)?t.resolve(e.doc,e):t}function ea(e,t,{key:r,value:n}){if(be(r)&&r.addToJSMap)r.addToJSMap(e,t,n);else if(ly(e,r))Cc(e,t,n);else{let i=We(r,"",e);if(t instanceof Map)t.set(i,We(n,i,e));else if(t instanceof Set)t.add(i);else{let s=NA(r,i,e),o=We(n,s,e);s in t?Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[s]=o}}return t}function NA(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(be(e)&&r?.doc){let n=Xo(r.doc,{});n.anchors=new Set;for(let s of r.anchors.keys())n.anchors.add(s.anchor);n.inFlow=!0,n.inStringifyKey=!0;let i=e.toString(n);if(!r.mapKeyWarned){let s=JSON.stringify(i);s.length>40&&(s=s.substring(0,36)+'..."'),Ec(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return i}return JSON.stringify(t)}function ki(e,t,r){let n=Gr(e,void 0,r),i=Gr(t,void 0,r);return new je(n,i)}var je=class e{constructor(t,r=null){Object.defineProperty(this,ht,{value:bc}),this.key=t,this.value=r}clone(t){let{key:r,value:n}=this;return be(r)&&(r=r.clone(t)),be(n)&&(n=n.clone(t)),new e(r,n)}toJSON(t,r){let n=r?.mapAsMap?new Map:{};return ea(r,n,this)}toString(t,r,n){return t?.doc?cy(this,t,r,n):JSON.stringify(this)}};function ra(e,t,r){return(t.inFlow??e.flow?OA:PA)(e,t,r)}function PA({comment:e,items:t},r,{blockItemPrefix:n,flowChars:i,itemIndent:s,onChompKeep:o,onComment:u}){let{indent:c,options:{commentString:f}}=r,h=Object.assign({},r,{indent:s,type:null}),p=!1,m=[];for(let x=0;x<t.length;++x){let b=t[x],v=null;if(be(b))!p&&b.spaceBefore&&m.push(""),ta(r,m,b.commentBefore,p),b.comment&&(v=b.comment);else if(ge(b)){let T=be(b.key)?b.key:null;T&&(!p&&T.spaceBefore&&m.push(""),ta(r,m,T.commentBefore,p))}p=!1;let k=Qr(b,h,()=>v=null,()=>p=!0);v&&(k+=Tr(k,s,f(v))),p&&v&&(p=!1),m.push(n+k)}let d;if(m.length===0)d=i.start+i.end;else{d=m[0];for(let x=1;x<m.length;++x){let b=m[x];d+=b?`+${c}${b}`:`+`}}return e?(d+=`+`+Vt(f(e),c),u&&u()):p&&o&&o(),d}function OA({items:e},t,{flowChars:r,itemIndent:n}){let{indent:i,indentStep:s,flowCollectionPadding:o,options:{commentString:u}}=t;n+=s;let c=Object.assign({},t,{indent:n,inFlow:!0,type:null}),f=!1,h=0,p=[];for(let x=0;x<e.length;++x){let b=e[x],v=null;if(be(b))b.spaceBefore&&p.push(""),ta(t,p,b.commentBefore,!1),b.comment&&(v=b.comment);else if(ge(b)){let T=be(b.key)?b.key:null;T&&(T.spaceBefore&&p.push(""),ta(t,p,T.commentBefore,!1),T.comment&&(f=!0));let E=be(b.value)?b.value:null;E?(E.comment&&(v=E.comment),E.commentBefore&&(f=!0)):b.value==null&&T?.comment&&(v=T.comment)}v&&(f=!0);let k=Qr(b,c,()=>v=null);f||(f=p.length>h||k.includes(`+`)),x<e.length-1?k+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(f||(f=p.reduce((T,E)=>T+E.length+2,2)+(k.length+2)>t.options.lineWidth)),f&&(k+=",")),v&&(k+=Tr(k,n,u(v))),p.push(k),h=p.length}let{start:m,end:d}=r;if(p.length===0)return m+d;if(!f){let x=p.reduce((b,v)=>b+v.length+2,2);f=t.options.lineWidth>0&&x>t.options.lineWidth}if(f){let x=m;for(let b of p)x+=b?`+${s}${i}${b}`:`+`;return`${x}+${i}${d}`}else return`${m}${o}${p.join(" ")}${o}${d}`}function ta({indent:e,options:{commentString:t}},r,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let s=Vt(t(n),e);r.push(s.trimStart())}}function dn(e,t){let r=pe(t)?t.value:t;for(let n of e)if(ge(n)&&(n.key===t||n.key===r||pe(n.key)&&n.key.value===r))return n}var qe=class extends bi{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(or,t),this.items=[]}static from(t,r,n){let{keepUndefined:i,replacer:s}=n,o=new this(t),u=(c,f)=>{if(typeof s=="function")f=s.call(r,c,f);else if(Array.isArray(s)&&!s.includes(c))return;(f!==void 0||i)&&o.items.push(ki(c,f,n))};if(r instanceof Map)for(let[c,f]of r)u(c,f);else if(r&&typeof r=="object")for(let c of Object.keys(r))u(c,r[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,r){let n;ge(t)?n=t:!t||typeof t!="object"||!("key"in t)?n=new je(t,t?.value):n=new je(t.key,t.value);let i=dn(this.items,n.key),s=this.schema?.sortMapEntries;if(i){if(!r)throw new Error(`Key ${n.key} already set`);pe(i.value)&&Go(n.value)?i.value.value=n.value:i.value=n.value}else if(s){let o=this.items.findIndex(u=>s(n,u)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(t){let r=dn(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let i=dn(this.items,t)?.value;return(!r&&pe(i)?i.value:i)??void 0}has(t){return!!dn(this.items,t)}set(t,r){this.add(new je(t,r),!0)}toJSON(t,r,n){let i=n?new n:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(i);for(let s of this.items)ea(r,i,s);return i}toString(t,r,n){if(!t)return JSON.stringify(this);for(let i of this.items)if(!ge(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),ra(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:n,onComment:r})}};var fr={collection:"map",default:!0,nodeClass:qe,tag:"tag:yaml.org,2002:map",resolve(e,t){return ur(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>qe.from(e,t,r)};var nt=class extends bi{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Zr,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=na(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let n=na(t);if(typeof n!="number")return;let i=this.items[n];return!r&&pe(i)?i.value:i}has(t){let r=na(t);return typeof r=="number"&&r<this.items.length}set(t,r){let n=na(t);if(typeof n!="number")throw new Error(`Expected a valid index, not ${t}.`);let i=this.items[n];pe(i)&&Go(r)?i.value=r:this.items[n]=r}toJSON(t,r){let n=[];r?.onCreate&&r.onCreate(n);let i=0;for(let s of this.items)n.push(We(s,String(i++),r));return n}toString(t,r,n){return t?ra(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:n,onComment:r}):JSON.stringify(this)}static from(t,r,n){let{replacer:i}=n,s=new this(t);if(r&&Symbol.iterator in Object(r)){let o=0;for(let u of r){if(typeof i=="function"){let c=r instanceof Set?u:String(o++);u=i.call(r,c,u)}s.items.push(Gr(u,void 0,n))}}return s}};function na(e){let t=pe(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}var pr={collection:"seq",default:!0,nodeClass:nt,tag:"tag:yaml.org,2002:seq",resolve(e,t){return cr(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>nt.from(e,t,r)};var mn={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,r,n){return t=Object.assign({actualString:!0},t),Fn(e,t,r,n)}};var Ln={identify:e=>e==null,createNode:()=>new Y(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Y(null),stringify:({source:e},t)=>typeof e=="string"&&Ln.test.test(e)?e:t.options.nullStr};var Es={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Y(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&Es.test.test(e)){let n=e[0]==="t"||e[0]==="T";if(t===n)return e}return t?r.options.trueStr:r.options.falseStr}};function it({format:e,minFractionDigits:t,tag:r,value:n}){if(typeof n=="bigint")return String(n);let i=typeof n=="number"?n:Number(n);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let s=Object.is(n,-0)?"-0":JSON.stringify(n);if(!e&&t&&(!r||r==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let o=s.indexOf(".");o<0&&(o=s.length,s+=".");let u=t-(s.length-o-1);for(;u-- >0;)s+="0"}return s}var ia={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:it},sa={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():it(e)}},oa={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new Y(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:it};var aa=e=>typeof e=="bigint"||Number.isInteger(e),Dc=(e,t,r,{intAsBigInt:n})=>n?BigInt(e):parseInt(e.substring(t),r);function py(e,t,r){let{value:n}=e;return aa(n)&&n>=0?r+n.toString(t):it(e)}var ua={identify:e=>aa(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>Dc(e,2,8,r),stringify:e=>py(e,8,"0o")},ca={identify:aa,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>Dc(e,0,10,r),stringify:it},la={identify:e=>aa(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>Dc(e,2,16,r),stringify:e=>py(e,16,"0x")};var hy=[fr,pr,mn,Ln,Es,ua,ca,la,ia,sa,oa];function dy(e){return typeof e=="bigint"||Number.isInteger(e)}var fa=({value:e})=>JSON.stringify(e),FA=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:fa},{identify:e=>e==null,createNode:()=>new Y(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:fa},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:fa},{identify:dy,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>dy(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:fa}],LA={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},my=[fr,pr].concat(FA,LA);var _s={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof atob=="function"){let r=atob(e.replace(/[\n\r]/g,"")),n=new Uint8Array(r.length);for(let i=0;i<r.length;++i)n[i]=r.charCodeAt(i);return n}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:r},n,i,s){if(!r)return"";let o=r,u;if(typeof btoa=="function"){let c="";for(let f=0;f<o.length;++f)c+=String.fromCharCode(o[f]);u=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=Y.BLOCK_LITERAL),t!==Y.QUOTE_DOUBLE){let c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),f=Math.ceil(u.length/c),h=new Array(f);for(let p=0,m=0;p<f;++p,m+=c)h[p]=u.substr(m,c);u=h.join(t===Y.BLOCK_LITERAL?`+`:" ")}return Fn({comment:e,type:t,value:u},n,i,s)}};function Ic(e,t){if(cr(e))for(let r=0;r<e.items.length;++r){let n=e.items[r];if(!ge(n)){if(ur(n)){n.items.length>1&&t("Each pair must have its own sequence indicator");let i=n.items[0]||new je(new Y(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore}+${i.key.commentBefore}`:n.commentBefore),n.comment){let s=i.value??i.key;s.comment=s.comment?`${n.comment}+${s.comment}`:n.comment}n=i}e.items[r]=ge(n)?n:new je(n)}}else t("Expected a sequence for this tag");return e}function Tc(e,t,r){let{replacer:n}=r,i=new nt(e);i.tag="tag:yaml.org,2002:pairs";let s=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof n=="function"&&(o=n.call(t,String(s++),o));let u,c;if(Array.isArray(o))if(o.length===2)u=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let f=Object.keys(o);if(f.length===1)u=f[0],c=o[u];else throw new TypeError(`Expected tuple with one key, not ${f.length} keys`)}else u=o;i.items.push(ki(u,c,r))}return i}var Cs={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Ic,createNode:Tc};var Ai=class e extends nt{constructor(){super(),this.add=qe.prototype.add.bind(this),this.delete=qe.prototype.delete.bind(this),this.get=qe.prototype.get.bind(this),this.has=qe.prototype.has.bind(this),this.set=qe.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let n=new Map;r?.onCreate&&r.onCreate(n);for(let i of this.items){let s,o;if(ge(i)?(s=We(i.key,"",r),o=We(i.value,s,r)):s=We(i,"",r),n.has(s))throw new Error("Ordered maps must not include duplicate keys");n.set(s,o)}return n}static from(t,r,n){let i=Tc(t,r,n),s=new this;return s.items=i.items,s}};Ai.tag="tag:yaml.org,2002:omap";var Ds={collection:"seq",identify:e=>e instanceof Map,nodeClass:Ai,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Ic(e,t),n=[];for(let{key:i}of r.items)pe(i)&&(n.includes(i.value)?t(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new Ai,r)},createNode:(e,t,r)=>Ai.from(e,t,r)};function gy({value:e,source:t},r){return t&&(e?Rc:Nc).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var Rc={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Y(!0),stringify:gy},Nc={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Y(!1),stringify:gy};var yy={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:it},xy={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():it(e)}},by={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new Y(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let n=e.substring(r+1).replace(/_/g,"");n[n.length-1]==="0"&&(t.minFractionDigits=n.length)}return t},stringify:it};var Is=e=>typeof e=="bigint"||Number.isInteger(e);function pa(e,t,r,{intAsBigInt:n}){let i=e[0];if((i==="-"||i==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),n){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return i==="-"?BigInt(-1)*o:o}let s=parseInt(e,r);return i==="-"?-1*s:s}function Pc(e,t,r){let{value:n}=e;if(Is(n)){let i=n.toString(t);return n<0?"-"+r+i.substr(1):r+i}return it(e)}var wy={identify:Is,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>pa(e,2,2,r),stringify:e=>Pc(e,2,"0b")},vy={identify:Is,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>pa(e,1,8,r),stringify:e=>Pc(e,8,"0")},ky={identify:Is,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>pa(e,0,10,r),stringify:it},Ay={identify:Is,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>pa(e,2,16,r),stringify:e=>Pc(e,16,"0x")};var Si=class e extends qe{constructor(t){super(t),this.tag=e.tag}add(t){let r;ge(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new je(t.key,null):r=new je(t,null),dn(this.items,r.key)||this.items.push(r)}get(t,r){let n=dn(this.items,t);return!r&&ge(n)?pe(n.key)?n.key.value:n.key:n}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let n=dn(this.items,t);n&&!r?this.items.splice(this.items.indexOf(n),1):!n&&r&&this.items.push(new je(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,n){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,n);throw new Error("Set items must all have null values")}static from(t,r,n){let{replacer:i}=n,s=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof i=="function"&&(o=i.call(r,o,o)),s.items.push(ki(o,null,n));return s}};Si.tag="tag:yaml.org,2002:set";var Ts={collection:"map",identify:e=>e instanceof Set,nodeClass:Si,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>Si.from(e,t,r),resolve(e,t){if(ur(e)){if(e.hasAllNullValues(!0))return Object.assign(new Si,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};function Oc(e,t){let r=e[0],n=r==="-"||r==="+"?e.substring(1):e,i=o=>t?BigInt(o):Number(o),s=n.replace(/_/g,"").split(":").reduce((o,u)=>o*i(60)+i(u),i(0));return r==="-"?i(-1)*s:s}function Sy(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return it(e);let n="";t<0&&(n="-",t*=r(-1));let i=r(60),s=[t%i];return t<60?s.unshift(0):(t=(t-s[0])/i,s.unshift(t%i),t>=60&&(t=(t-s[0])/i,s.unshift(t))),n+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var ha={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>Oc(e,r),stringify:Sy},da={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>Oc(e,!1),stringify:Sy},Ei={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(Ei.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,n,i,s,o,u]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,f=Date.UTC(r,n-1,i,s||0,o||0,u||0,c),h=t[8];if(h&&h!=="Z"){let p=Oc(h,!1);Math.abs(p)<30&&(p*=60),f-=6e4*p}return new Date(f)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};var Fc=[fr,pr,mn,Ln,Rc,Nc,wy,vy,ky,Ay,yy,xy,by,_s,lr,Ds,Cs,Ts,ha,da,Ei];var Ey=new Map([["core",hy],["failsafe",[fr,pr,mn]],["json",my],["yaml11",Fc],["yaml-1.1",Fc]]),_y={binary:_s,bool:Es,float:oa,floatExp:sa,floatNaN:ia,floatTime:da,int:ca,intHex:la,intOct:ua,intTime:ha,map:fr,merge:lr,null:Ln,omap:Ds,pairs:Cs,seq:pr,set:Ts,timestamp:Ei},Cy={"tag:yaml.org,2002:binary":_s,"tag:yaml.org,2002:merge":lr,"tag:yaml.org,2002:omap":Ds,"tag:yaml.org,2002:pairs":Cs,"tag:yaml.org,2002:set":Ts,"tag:yaml.org,2002:timestamp":Ei};function ma(e,t,r){let n=Ey.get(t);if(n&&!e)return r&&!n.includes(lr)?n.concat(lr):n.slice();let i=n;if(!i)if(Array.isArray(e))i=[];else{let s=Array.from(Ey.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${s} or define customTags array`)}if(Array.isArray(e))for(let s of e)i=i.concat(s);else typeof e=="function"&&(i=e(i.slice()));return r&&(i=i.concat(lr)),i.reduce((s,o)=>{let u=typeof o=="string"?_y[o]:o;if(!u){let c=JSON.stringify(o),f=Object.keys(_y).map(h=>JSON.stringify(h)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${f}`)}return s.includes(u)||s.push(u),s},[])}var zA=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Rs=class e{constructor({compat:t,customTags:r,merge:n,resolveKnownTags:i,schema:s,sortMapEntries:o,toStringDefaults:u}){this.compat=Array.isArray(t)?ma(t,"compat"):t?ma(null,t):null,this.name=typeof s=="string"&&s||"core",this.knownTags=i?Cy:{},this.tags=ma(r,this.name,n),this.toStringOptions=u??null,Object.defineProperty(this,or,{value:fr}),Object.defineProperty(this,It,{value:mn}),Object.defineProperty(this,Zr,{value:pr}),this.sortMapEntries=typeof o=="function"?o:o===!0?zA:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};function Dy(e,t){let r=[],n=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),n=!0):e.directives.docStart&&(n=!0)}n&&r.push("---");let i=Xo(e,t),{commentString:s}=i.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=s(e.commentBefore);r.unshift(Vt(c,""))}let o=!1,u=null;if(e.contents){if(be(e.contents)){if(e.contents.spaceBefore&&n&&r.push(""),e.contents.commentBefore){let h=s(e.contents.commentBefore);r.push(Vt(h,""))}i.forceBlockIndent=!!e.comment,u=e.contents.comment}let c=u?void 0:()=>o=!0,f=Qr(e.contents,i,()=>u=null,c);u&&(f+=Tr(f,"",s(u))),(f[0]==="|"||f[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${f}`:r.push(f)}else r.push(Qr(e.contents,i));if(e.directives?.docEnd)if(e.comment){let c=s(e.comment);c.includes(`+`)?(r.push("..."),r.push(Vt(c,""))):r.push(`... ${c}`)}else r.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||u)&&r[r.length-1]!==""&&r.push(""),r.push(Vt(s(c),"")))}return r.join(``)+`-`}var lt=class t{constructor(e,n,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,oe,{value:yr});let o=null;typeof n=="function"||Array.isArray(n)?o=n:r===void 0&&n&&(r=n,n=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=s;let{version:i}=s;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(i=this.directives.yaml.version)):this.directives=new Ze({version:i}),this.setSchema(i,r),this.contents=e===void 0?null:this.createNode(e,o,r)}clone(){let e=Object.create(t.prototype,{[oe]:{value:yr}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=P(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Gt(this.contents)&&this.contents.add(e)}addIn(e,n){Gt(this.contents)&&this.contents.addIn(e,n)}createAlias(e,n){if(!e.anchor){let r=os(this);e.anchor=!n||r.has(n)?ss(n||"a",r):n}return new Je(e.anchor)}createNode(e,n,r){let o;if(typeof n=="function")e=n.call({"":e},"",e),o=n;else if(Array.isArray(n)){let h=S=>typeof S=="number"||S instanceof String||S instanceof Number,b=n.filter(h).map(String);b.length>0&&(n=n.concat(b)),o=n}else r===void 0&&n&&(r=n,n=void 0);let{aliasDuplicateObjects:s,anchorPrefix:i,flow:a,keepUndefined:c,onTagObj:u,tag:d}=r??{},{onAnchor:l,setAnchors:f,sourceObjects:p}=gl(this,i||"a"),y={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:l,onTagObj:u,replacer:o,schema:this.schema,sourceObjects:p},m=Ke(e,d,y);return a&&j(m)&&(m.flow=!0),f(),m}createPair(e,n,r={}){let o=this.createNode(e,null,r),s=this.createNode(n,null,r);return new K(o,s)}delete(e){return Gt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Ft(e)?this.contents==null?!1:(this.contents=null,!0):Gt(this.contents)?this.contents.deleteIn(e):!1}get(e,n){return j(this.contents)?this.contents.get(e,n):void 0}getIn(e,n){return Ft(e)?!n&&N(this.contents)?this.contents.value:this.contents:j(this.contents)?this.contents.getIn(e,n):void 0}has(e){return j(this.contents)?this.contents.has(e):!1}hasIn(e){return Ft(e)?this.contents!==void 0:j(this.contents)?this.contents.hasIn(e):!1}set(e,n){this.contents==null?this.contents=wn(this.schema,[e],n):Gt(this.contents)&&this.contents.set(e,n)}setIn(e,n){Ft(e)?this.contents=n:this.contents==null?this.contents=wn(this.schema,Array.from(e),n):Gt(this.contents)&&this.contents.setIn(e,n)}setSchema(e,n={}){typeof e=="number"&&(e=String(e));let r;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Ze({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Ze({version:e}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let o=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${o}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(r)this.schema=new In(Object.assign(r,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:n,mapAsMap:r,maxAliasCount:o,onAnchor:s,reviver:i}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof o=="number"?o:100},c=Y(this.contents,n??"",a);if(typeof s=="function")for(let{count:u,res:d}of a.anchors.values())s(d,u);return typeof i=="function"?it(i,{"":c},"",c):c}toJSON(e,n){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:n})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let n=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return Fl(this,e)}};function Gt(t){if(j(t))return!0;throw new Error("Expected a YAML collection as document contents")}var On=class extends Error{constructor(e,n,r,o){super(),this.name=e,this.code=r,this.message=o,this.pos=n}},Re=class extends On{constructor(e,n,r){super("YAMLParseError",e,n,r)}},Cn=class extends On{constructor(e,n,r){super("YAMLWarning",e,n,r)}},_s=(t,e)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>e.linePos(a));let{line:r,col:o}=n.linePos[0];n.message+=` at line ${r}, column ${o}`;let s=o-1,i=t.substring(e.lineStarts[r-1],e.lineStarts[r]).replace(/[\n\r]+$/,"");if(s>=60&&i.length>80){let a=Math.min(s-39,i.length-79);i="\u2026"+i.substring(a),s-=a-1}if(i.length>80&&(i=i.substring(0,79)+"\u2026"),r>1&&/^ *$/.test(i.substring(0,s))){let a=t.substring(e.lineStarts[r-2],e.lineStarts[r-1]);a.length>80&&(a=a.substring(0,79)+`\u2026-`),i=a+i}if(/[^ ]/.test(i)){let a=1,c=n.linePos[1];c?.line===r&&c.col>o&&(a=Math.max(1,Math.min(c.col-o,80-s)));let u=" ".repeat(s)+"^".repeat(a);n.message+=`:+`}var gn=class e{constructor(t,r,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ht,{value:jo});let i=null;typeof r=="function"||Array.isArray(r)?i=r:n===void 0&&r&&(n=r,r=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=s;let{version:o}=s;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Ir({version:o}),this.setSchema(o,n),this.contents=t===void 0?null:this.createNode(t,i,n)}clone(){let t=Object.create(e.prototype,{[ht]:{value:jo}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=be(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){_i(this.contents)&&this.contents.add(t)}addIn(t,r){_i(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let n=wc(this);t.anchor=!r||n.has(r)?vc(r||"a",n):r}return new Jr(t.anchor)}createNode(t,r,n){let i;if(typeof r=="function")t=r.call({"":t},"",t),i=r;else if(Array.isArray(r)){let v=T=>typeof T=="number"||T instanceof String||T instanceof Number,k=r.filter(v).map(String);k.length>0&&(r=r.concat(k)),i=r}else n===void 0&&r&&(n=r,r=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:u,keepUndefined:c,onTagObj:f,tag:h}=n??{},{onAnchor:p,setAnchors:m,sourceObjects:d}=oy(this,o||"a"),x={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:p,onTagObj:f,replacer:i,schema:this.schema,sourceObjects:d},b=Gr(t,h,x);return u&&_e(b)&&(b.flow=!0),m(),b}createPair(t,r,n={}){let i=this.createNode(t,null,n),s=this.createNode(r,null,n);return new je(i,s)}delete(t){return _i(this.contents)?this.contents.delete(t):!1}deleteIn(t){return wi(t)?this.contents==null?!1:(this.contents=null,!0):_i(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return _e(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return wi(t)?!r&&pe(this.contents)?this.contents.value:this.contents:_e(this.contents)?this.contents.getIn(t,r):void 0}has(t){return _e(this.contents)?this.contents.has(t):!1}hasIn(t){return wi(t)?this.contents!==void 0:_e(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=vs(this.schema,[t],r):_i(this.contents)&&this.contents.set(t,r)}setIn(t,r){wi(t)?this.contents=r:this.contents==null?this.contents=vs(this.schema,Array.from(t),r):_i(this.contents)&&this.contents.setIn(t,r)}setSchema(t,r={}){typeof t=="number"&&(t=String(t));let n;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Ir({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Ir({version:t}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let i=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(r.schema instanceof Object)this.schema=r.schema;else if(n)this.schema=new Rs(Object.assign(n,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:n,maxAliasCount:i,onAnchor:s,reviver:o}={}){let u={anchors:new Map,doc:this,keep:!t,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},c=We(this.contents,r??"",u);if(typeof s=="function")for(let{count:f,res:h}of u.anchors.values())s(h,f);return typeof o=="function"?pn(o,{"":c},"",c):c}toJSON(t,r){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:r})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let r=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return Dy(this,t)}};function _i(e){if(_e(e))return!0;throw new Error("Expected a YAML collection as document contents")}var Ns=class extends Error{constructor(t,r,n,i){super(),this.name=t,this.code=n,this.message=i,this.pos=r}},hr=class extends Ns{constructor(t,r,n){super("YAMLParseError",t,r,n)}},Ps=class extends Ns{constructor(t,r,n){super("YAMLWarning",t,r,n)}},Lc=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(u=>t.linePos(u));let{line:n,col:i}=r.linePos[0];r.message+=` at line ${n}, column ${i}`;let s=i-1,o=e.substring(t.lineStarts[n-1],t.lineStarts[n]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let u=Math.min(s-39,o.length-79);o="\u2026"+o.substring(u),s-=u-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,s))){let u=e.substring(t.lineStarts[n-2],t.lineStarts[n-1]);u.length>80&&(u=u.substring(0,79)+`\u2026+`),o=u+o}if(/[^ ]/.test(o)){let u=1,c=r.linePos[1];c?.line===n&&c.col>i&&(u=Math.max(1,Math.min(c.col-i,80-s)));let f=" ".repeat(s)+"^".repeat(u);r.message+=`:-${i}-${u}-`}};function Be(t,{flow:e,indicator:n,next:r,offset:o,onError:s,parentIndent:i,startOnNewline:a}){let c=!1,u=a,d=a,l="",f="",p=!1,y=!1,m=null,h=null,b=null,S=null,A=null,_=null,w=null;for(let x of t)switch(y&&(x.type!=="space"&&x.type!=="newline"&&x.type!=="comma"&&s(x.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),y=!1),m&&(u&&x.type!=="comment"&&x.type!=="newline"&&s(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),x.type){case"space":!e&&(n!=="doc-start"||r?.type!=="flow-collection")&&x.source.includes(" ")&&(m=x),d=!0;break;case"comment":{d||s(x,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let O=x.source.substring(1)||" ";l?l+=f+O:l=O,f="",u=!1;break}case"newline":u?l?l+=x.source:(!_||n!=="seq-item-ind")&&(c=!0):f+=x.source,u=!0,p=!0,(h||b)&&(S=x),d=!0;break;case"anchor":h&&s(x,"MULTIPLE_ANCHORS","A node can have at most one anchor"),x.source.endsWith(":")&&s(x.offset+x.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),h=x,w??(w=x.offset),u=!1,d=!1,y=!0;break;case"tag":{b&&s(x,"MULTIPLE_TAGS","A node can have at most one tag"),b=x,w??(w=x.offset),u=!1,d=!1,y=!0;break}case n:(h||b)&&s(x,"BAD_PROP_ORDER",`Anchors and tags must be after the ${x.source} indicator`),_&&s(x,"UNEXPECTED_TOKEN",`Unexpected ${x.source} in ${e??"collection"}`),_=x,u=n==="seq-item-ind"||n==="explicit-key-ind",d=!1;break;case"comma":if(e){A&&s(x,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),A=x,u=!1,d=!1;break}default:s(x,"UNEXPECTED_TOKEN",`Unexpected ${x.type} token`),u=!1,d=!1}let E=t[t.length-1],k=E?E.offset+E.source.length:o;return y&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&s(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(u&&m.indent<=i||r?.type==="block-map"||r?.type==="block-seq")&&s(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:A,found:_,spaceBefore:c,comment:l,hasNewline:p,anchor:h,tag:b,newlineAfterProp:S,end:k,start:w??k}}function ft(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(`-`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let n of e.start)if(n.type==="newline")return!0;if(e.sep){for(let n of e.sep)if(n.type==="newline")return!0}if(ft(e.key)||ft(e.value))return!0}return!1;default:return!0}}function Nn(t,e,n){if(e?.type==="flow-collection"){let r=e.end[0];r.indent===t&&(r.source==="]"||r.source==="}")&&ft(e)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}function Qr(t,e,n){let{uniqueKeys:r}=t.options;if(r===!1)return!1;let o=typeof r=="function"?r:(s,i)=>s===i||N(s)&&N(i)&&s.value===i.value;return e.some(s=>o(s.key,n))}var Zl="All mapping items must start at the same column";function jl({composeNode:t,composeEmptyNode:e},n,r,o,s){let i=s?.nodeClass??W,a=new i(n.schema);n.atRoot&&(n.atRoot=!1);let c=r.offset,u=null;for(let d of r.items){let{start:l,key:f,sep:p,value:y}=d,m=Be(l,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:o,parentIndent:r.indent,startOnNewline:!0}),h=!m.found;if(h){if(f&&(f.type==="block-seq"?o(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&o(c,"BAD_INDENT",Zl)),!m.anchor&&!m.tag&&!p){u=m.end,m.comment&&(a.comment?a.comment+=`-`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||ft(f))&&o(f??l[l.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==r.indent&&o(c,"BAD_INDENT",Zl);n.atKey=!0;let b=m.end,S=f?t(n,f,m,o):e(n,b,l,null,m,o);n.schema.compat&&Nn(r.indent,f,o),n.atKey=!1,Qr(n,a.items,S)&&o(b,"DUPLICATE_KEY","Map keys must be unique");let A=Be(p??[],{indicator:"map-value-ind",next:y,offset:S.range[2],onError:o,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=A.end,A.found){h&&(y?.type==="block-map"&&!A.hasNewline&&o(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&m.start<A.found.offset-1024&&o(S.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let _=y?t(n,y,A,o):e(n,c,p,null,A,o);n.schema.compat&&Nn(r.indent,y,o),c=_.range[2];let w=new K(S,_);n.options.keepSourceTokens&&(w.srcToken=d),a.items.push(w)}else{h&&o(S.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),A.comment&&(S.comment?S.comment+=`-`+A.comment:S.comment=A.comment);let _=new K(S);n.options.keepSourceTokens&&(_.srcToken=d),a.items.push(_)}}return u&&u<c&&o(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[r.offset,c,u??c],a}function Bl({composeNode:t,composeEmptyNode:e},n,r,o,s){let i=s?.nodeClass??ee,a=new i(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=r.offset,u=null;for(let{start:d,value:l}of r.items){let f=Be(d,{indicator:"seq-item-ind",next:l,offset:c,onError:o,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||l)l?.type==="block-seq"?o(f.end,"BAD_INDENT","All sequence items must start at the same column"):o(c,"MISSING_CHAR","Sequence item without - indicator");else{u=f.end,f.comment&&(a.comment=f.comment);continue}let p=l?t(n,l,f,o):e(n,f.end,d,null,f,o);n.schema.compat&&Nn(r.indent,l,o),c=p.range[2],a.items.push(p)}return a.range=[r.offset,c,u??c],a}function Ue(t,e,n,r){let o="";if(t){let s=!1,i="";for(let a of t){let{source:c,type:u}=a;switch(u){case"space":s=!0;break;case"comment":{n&&!s&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let d=c.substring(1)||" ";o?o+=i+d:o=d,i="";break}case"newline":o&&(i+=c),s=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${u} at node end`)}e+=c.length}}return{comment:o,offset:e}}var xs="Block collections are not allowed within flow collections",Ss=t=>t&&(t.type==="block-map"||t.type==="block-seq");function Ul({composeNode:t,composeEmptyNode:e},n,r,o,s){let i=r.start.source==="{",a=i?"flow map":"flow sequence",c=s?.nodeClass??(i?W:ee),u=new c(n.schema);u.flow=!0;let d=n.atRoot;d&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let l=r.offset+r.start.source.length;for(let h=0;h<r.items.length;++h){let b=r.items[h],{start:S,key:A,sep:_,value:w}=b,E=Be(S,{flow:a,indicator:"explicit-key-ind",next:A??_?.[0],offset:l,onError:o,parentIndent:r.indent,startOnNewline:!1});if(!E.found){if(!E.anchor&&!E.tag&&!_&&!w){h===0&&E.comma?o(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):h<r.items.length-1&&o(E.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),E.comment&&(u.comment?u.comment+=`-`+E.comment:u.comment=E.comment),l=E.end;continue}!i&&n.options.strict&&ft(A)&&o(A,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(h===0)E.comma&&o(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(E.comma||o(E.start,"MISSING_CHAR",`Missing , between ${a} items`),E.comment){let k="";e:for(let x of S)switch(x.type){case"comma":case"space":break;case"comment":k=x.source.substring(1);break e;default:break e}if(k){let x=u.items[u.items.length-1];T(x)&&(x=x.value??x.key),x.comment?x.comment+=`-`+k:x.comment=k,E.comment=E.comment.substring(k.length+1)}}if(!i&&!_&&!E.found){let k=w?t(n,w,E,o):e(n,E.end,_,null,E,o);u.items.push(k),l=k.range[2],Ss(w)&&o(k.range,"BLOCK_IN_FLOW",xs)}else{n.atKey=!0;let k=E.end,x=A?t(n,A,E,o):e(n,k,S,null,E,o);Ss(A)&&o(x.range,"BLOCK_IN_FLOW",xs),n.atKey=!1;let O=Be(_??[],{flow:a,indicator:"map-value-ind",next:w,offset:x.range[2],onError:o,parentIndent:r.indent,startOnNewline:!1});if(O.found){if(!i&&!E.found&&n.options.strict){if(_)for(let $ of _){if($===O.found)break;if($.type==="newline"){o($,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}E.start<O.found.offset-1024&&o(O.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else w&&("source"in w&&w.source?.[0]===":"?o(w,"MISSING_CHAR",`Missing space after : in ${a}`):o(O.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let M=w?t(n,w,O,o):O.found?e(n,O.end,_,null,O,o):null;M?Ss(w)&&o(M.range,"BLOCK_IN_FLOW",xs):O.comment&&(x.comment?x.comment+=`-`+O.comment:x.comment=O.comment);let B=new K(x,M);if(n.options.keepSourceTokens&&(B.srcToken=b),i){let $=u;Qr(n,$.items,x)&&o(k,"DUPLICATE_KEY","Map keys must be unique"),$.items.push(B)}else{let $=new W(n.schema);$.flow=!0,$.items.push(B);let ae=(M??x).range;$.range=[x.range[0],ae[1],ae[2]],u.items.push($)}l=M?M.range[2]:O.end}}let f=i?"}":"]",[p,...y]=r.end,m=l;if(p?.source===f)m=p.offset+p.source.length;else{let h=a[0].toUpperCase()+a.substring(1),b=d?`${h} must end with a ${f}`:`${h} in block collection must be sufficiently indented and end with a ${f}`;o(l,d?"MISSING_CHAR":"BAD_INDENT",b),p&&p.source.length!==1&&y.unshift(p)}if(y.length>0){let h=Ue(y,m,n.options.strict,o);h.comment&&(u.comment?u.comment+=`-`+h.comment:u.comment=h.comment),u.range=[r.offset,m,h.offset]}else u.range=[r.offset,m,m];return u}function As(t,e,n,r,o,s){let i=n.type==="block-map"?jl(t,e,n,r,s):n.type==="block-seq"?Bl(t,e,n,r,s):Ul(t,e,n,r,s),a=i.constructor;return o==="!"||o===a.tagName?(i.tag=a.tagName,i):(o&&(i.tag=o),i)}function Ql(t,e,n,r,o){let s=r.tag,i=s?e.directives.tagName(s.source,f=>o(s,"TAG_RESOLVE_FAILED",f)):null;if(n.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=r,y=f&&s?f.offset>s.offset?f:s:f??s;y&&(!p||p.offset<y.offset)&&o(y,"MISSING_CHAR","Missing newline after block sequence props")}let a=n.type==="block-map"?"map":n.type==="block-seq"?"seq":n.start.source==="{"?"map":"seq";if(!s||!i||i==="!"||i===W.tagName&&a==="map"||i===ee.tagName&&a==="seq")return As(t,e,n,o,i);let c=e.schema.tags.find(f=>f.tag===i&&f.collection===a);if(!c){let f=e.schema.knownTags[i];if(f?.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?o(s,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):o(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,!0),As(t,e,n,o,i)}let u=As(t,e,n,o,i,c),d=c.resolve?.(u,f=>o(s,"TAG_RESOLVE_FAILED",f),e.options)??u,l=P(d)?d:new D(d);return l.range=u.range,l.tag=i,c?.format&&(l.format=c.format),l}function Es(t,e,n){let r=e.offset,o=Lm(e,t.options.strict,n);if(!o)return{value:"",type:null,comment:"",range:[r,r,r]};let s=o.mode===">"?D.BLOCK_FOLDED:D.BLOCK_LITERAL,i=e.source?Mm(e.source):[],a=i.length;for(let m=i.length-1;m>=0;--m){let h=i[m][1];if(h===""||h==="\r")a=m;else break}if(a===0){let m=o.chomp==="+"&&i.length>0?`-`.repeat(Math.max(1,i.length-1)):"",h=r+o.length;return e.source&&(h+=e.source.length),{value:m,type:s,comment:o.comment,range:[r,h,h]}}let c=e.indent+o.indent,u=e.offset+o.length,d=0;for(let m=0;m<a;++m){let[h,b]=i[m];if(b===""||b==="\r")o.indent===0&&h.length>c&&(c=h.length);else{h.length<c&&n(u+h.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),o.indent===0&&(c=h.length),d=m,c===0&&!t.atRoot&&n(u,"BAD_INDENT","Block scalar values in collections must be indented");break}u+=h.length+b.length+1}for(let m=i.length-1;m>=a;--m)i[m][0].length>c&&(a=m+1);let l="",f="",p=!1;for(let m=0;m<d;++m)l+=i[m][0].slice(c)+`-`;for(let m=d;m<a;++m){let[h,b]=i[m];u+=h.length+b.length+1;let S=b[b.length-1]==="\r";if(S&&(b=b.slice(0,-1)),b&&h.length<c){let _=`Block scalar lines must not be less indented than their ${o.indent?"explicit indentation indicator":"first line"}`;n(u-b.length-(S?2:1),"BAD_INDENT",_),h=""}s===D.BLOCK_LITERAL?(l+=f+h.slice(c)+b,f=`-`):h.length>c||b[0]===" "?(f===" "?f=`-`:!p&&f===`-`&&(f=`+${o}+${f}+`}};function Rr(e,{flow:t,indicator:r,next:n,offset:i,onError:s,parentIndent:o,startOnNewline:u}){let c=!1,f=u,h=u,p="",m="",d=!1,x=!1,b=null,v=null,k=null,T=null,E=null,g=null,I=null;for(let O of e)switch(x&&(O.type!=="space"&&O.type!=="newline"&&O.type!=="comma"&&s(O.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),x=!1),b&&(f&&O.type!=="comment"&&O.type!=="newline"&&s(b,"TAB_AS_INDENT","Tabs are not allowed as indentation"),b=null),O.type){case"space":!t&&(r!=="doc-start"||n?.type!=="flow-collection")&&O.source.includes(" ")&&(b=O),h=!0;break;case"comment":{h||s(O,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let M=O.source.substring(1)||" ";p?p+=m+M:p=M,m="",f=!1;break}case"newline":f?p?p+=O.source:(!g||r!=="seq-item-ind")&&(c=!0):m+=O.source,f=!0,d=!0,(v||k)&&(T=O),h=!0;break;case"anchor":v&&s(O,"MULTIPLE_ANCHORS","A node can have at most one anchor"),O.source.endsWith(":")&&s(O.offset+O.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),v=O,I??(I=O.offset),f=!1,h=!1,x=!0;break;case"tag":{k&&s(O,"MULTIPLE_TAGS","A node can have at most one tag"),k=O,I??(I=O.offset),f=!1,h=!1,x=!0;break}case r:(v||k)&&s(O,"BAD_PROP_ORDER",`Anchors and tags must be after the ${O.source} indicator`),g&&s(O,"UNEXPECTED_TOKEN",`Unexpected ${O.source} in ${t??"collection"}`),g=O,f=r==="seq-item-ind"||r==="explicit-key-ind",h=!1;break;case"comma":if(t){E&&s(O,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),E=O,f=!1,h=!1;break}default:s(O,"UNEXPECTED_TOKEN",`Unexpected ${O.type} token`),f=!1,h=!1}let _=e[e.length-1],D=_?_.offset+_.source.length:i;return x&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&s(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),b&&(f&&b.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&s(b,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:E,found:g,spaceBefore:c,comment:p,hasNewline:d,anchor:v,tag:k,newlineAfterProp:T,end:D,start:I??D}}function yn(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`+`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(yn(t.key)||yn(t.value))return!0}return!1;default:return!0}}function Os(e,t,r){if(t?.type==="flow-collection"){let n=t.end[0];n.indent===e&&(n.source==="]"||n.source==="}")&&yn(t)&&r(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}function ga(e,t,r){let{uniqueKeys:n}=e.options;if(n===!1)return!1;let i=typeof n=="function"?n:(s,o)=>s===o||pe(s)&&pe(o)&&s.value===o.value;return t.some(s=>i(s.key,r))}var Iy="All mapping items must start at the same column";function Ty({composeNode:e,composeEmptyNode:t},r,n,i,s){let o=s?.nodeClass??qe,u=new o(r.schema);r.atRoot&&(r.atRoot=!1);let c=n.offset,f=null;for(let h of n.items){let{start:p,key:m,sep:d,value:x}=h,b=Rr(p,{indicator:"explicit-key-ind",next:m??d?.[0],offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0}),v=!b.found;if(v){if(m&&(m.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in m&&m.indent!==n.indent&&i(c,"BAD_INDENT",Iy)),!b.anchor&&!b.tag&&!d){f=b.end,b.comment&&(u.comment?u.comment+=`+`+b.comment:u.comment=b.comment);continue}(b.newlineAfterProp||yn(m))&&i(m??p[p.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else b.found?.indent!==n.indent&&i(c,"BAD_INDENT",Iy);r.atKey=!0;let k=b.end,T=m?e(r,m,b,i):t(r,k,p,null,b,i);r.schema.compat&&Os(n.indent,m,i),r.atKey=!1,ga(r,u.items,T)&&i(k,"DUPLICATE_KEY","Map keys must be unique");let E=Rr(d??[],{indicator:"map-value-ind",next:x,offset:T.range[2],onError:i,parentIndent:n.indent,startOnNewline:!m||m.type==="block-scalar"});if(c=E.end,E.found){v&&(x?.type==="block-map"&&!E.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&b.start<E.found.offset-1024&&i(T.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let g=x?e(r,x,E,i):t(r,c,d,null,E,i);r.schema.compat&&Os(n.indent,x,i),c=g.range[2];let I=new je(T,g);r.options.keepSourceTokens&&(I.srcToken=h),u.items.push(I)}else{v&&i(T.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),E.comment&&(T.comment?T.comment+=`+`+E.comment:T.comment=E.comment);let g=new je(T);r.options.keepSourceTokens&&(g.srcToken=h),u.items.push(g)}}return f&&f<c&&i(f,"IMPOSSIBLE","Map comment with trailing content"),u.range=[n.offset,c,f??c],u}function Ry({composeNode:e,composeEmptyNode:t},r,n,i,s){let o=s?.nodeClass??nt,u=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=n.offset,f=null;for(let{start:h,value:p}of n.items){let m=Rr(h,{indicator:"seq-item-ind",next:p,offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0});if(!m.found)if(m.anchor||m.tag||p)p?.type==="block-seq"?i(m.end,"BAD_INDENT","All sequence items must start at the same column"):i(c,"MISSING_CHAR","Sequence item without - indicator");else{f=m.end,m.comment&&(u.comment=m.comment);continue}let d=p?e(r,p,m,i):t(r,m.end,h,null,m,i);r.schema.compat&&Os(n.indent,p,i),c=d.range[2],u.items.push(d)}return u.range=[n.offset,c,f??c],u}function Nr(e,t,r,n){let i="";if(e){let s=!1,o="";for(let u of e){let{source:c,type:f}=u;switch(f){case"space":s=!0;break;case"comment":{r&&!s&&n(u,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let h=c.substring(1)||" ";i?i+=o+h:i=h,o="";break}case"newline":i&&(o+=c),s=!0;break;default:n(u,"UNEXPECTED_TOKEN",`Unexpected ${f} at node end`)}t+=c.length}}return{comment:i,offset:t}}var zc="Block collections are not allowed within flow collections",Bc=e=>e&&(e.type==="block-map"||e.type==="block-seq");function Ny({composeNode:e,composeEmptyNode:t},r,n,i,s){let o=n.start.source==="{",u=o?"flow map":"flow sequence",c=s?.nodeClass??(o?qe:nt),f=new c(r.schema);f.flow=!0;let h=r.atRoot;h&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let p=n.offset+n.start.source.length;for(let v=0;v<n.items.length;++v){let k=n.items[v],{start:T,key:E,sep:g,value:I}=k,_=Rr(T,{flow:u,indicator:"explicit-key-ind",next:E??g?.[0],offset:p,onError:i,parentIndent:n.indent,startOnNewline:!1});if(!_.found){if(!_.anchor&&!_.tag&&!g&&!I){v===0&&_.comma?i(_.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${u}`):v<n.items.length-1&&i(_.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${u}`),_.comment&&(f.comment?f.comment+=`+`+_.comment:f.comment=_.comment),p=_.end;continue}!o&&r.options.strict&&yn(E)&&i(E,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(v===0)_.comma&&i(_.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${u}`);else if(_.comma||i(_.start,"MISSING_CHAR",`Missing , between ${u} items`),_.comment){let D="";e:for(let O of T)switch(O.type){case"comma":case"space":break;case"comment":D=O.source.substring(1);break e;default:break e}if(D){let O=f.items[f.items.length-1];ge(O)&&(O=O.value??O.key),O.comment?O.comment+=`+`+D:O.comment=D,_.comment=_.comment.substring(D.length+1)}}if(!o&&!g&&!_.found){let D=I?e(r,I,_,i):t(r,_.end,g,null,_,i);f.items.push(D),p=D.range[2],Bc(I)&&i(D.range,"BLOCK_IN_FLOW",zc)}else{r.atKey=!0;let D=_.end,O=E?e(r,E,_,i):t(r,D,T,null,_,i);Bc(E)&&i(O.range,"BLOCK_IN_FLOW",zc),r.atKey=!1;let M=Rr(g??[],{flow:u,indicator:"map-value-ind",next:I,offset:O.range[2],onError:i,parentIndent:n.indent,startOnNewline:!1});if(M.found){if(!o&&!_.found&&r.options.strict){if(g)for(let V of g){if(V===M.found)break;if(V.type==="newline"){i(V,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}_.start<M.found.offset-1024&&i(M.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else I&&("source"in I&&I.source?.[0]===":"?i(I,"MISSING_CHAR",`Missing space after : in ${u}`):i(M.start,"MISSING_CHAR",`Missing , or : between ${u} items`));let P=I?e(r,I,M,i):M.found?t(r,M.end,g,null,M,i):null;P?Bc(I)&&i(P.range,"BLOCK_IN_FLOW",zc):M.comment&&(O.comment?O.comment+=`+`+M.comment:O.comment=M.comment);let J=new je(O,P);if(r.options.keepSourceTokens&&(J.srcToken=k),o){let V=f;ga(r,V.items,O)&&i(D,"DUPLICATE_KEY","Map keys must be unique"),V.items.push(J)}else{let V=new qe(r.schema);V.flow=!0,V.items.push(J);let q=(P??O).range;V.range=[O.range[0],q[1],q[2]],f.items.push(V)}p=P?P.range[2]:M.end}}let m=o?"}":"]",[d,...x]=n.end,b=p;if(d?.source===m)b=d.offset+d.source.length;else{let v=u[0].toUpperCase()+u.substring(1),k=h?`${v} must end with a ${m}`:`${v} in block collection must be sufficiently indented and end with a ${m}`;i(p,h?"MISSING_CHAR":"BAD_INDENT",k),d&&d.source.length!==1&&x.unshift(d)}if(x.length>0){let v=Nr(x,b,r.options.strict,i);v.comment&&(f.comment?f.comment+=`+`+v.comment:f.comment=v.comment),f.range=[n.offset,b,v.offset]}else f.range=[n.offset,b,b];return f}function Mc(e,t,r,n,i,s){let o=r.type==="block-map"?Ty(e,t,r,n,s):r.type==="block-seq"?Ry(e,t,r,n,s):Ny(e,t,r,n,s),u=o.constructor;return i==="!"||i===u.tagName?(o.tag=u.tagName,o):(i&&(o.tag=i),o)}function Py(e,t,r,n,i){let s=n.tag,o=s?t.directives.tagName(s.source,m=>i(s,"TAG_RESOLVE_FAILED",m)):null;if(r.type==="block-seq"){let{anchor:m,newlineAfterProp:d}=n,x=m&&s?m.offset>s.offset?m:s:m??s;x&&(!d||d.offset<x.offset)&&i(x,"MISSING_CHAR","Missing newline after block sequence props")}let u=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!s||!o||o==="!"||o===qe.tagName&&u==="map"||o===nt.tagName&&u==="seq")return Mc(e,t,r,i,o);let c=t.schema.tags.find(m=>m.tag===o&&m.collection===u);if(!c){let m=t.schema.knownTags[o];if(m?.collection===u)t.schema.tags.push(Object.assign({},m,{default:!1})),c=m;else return m?i(s,"BAD_COLLECTION_TYPE",`${m.tag} used for ${u} collection, but expects ${m.collection??"scalar"}`,!0):i(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Mc(e,t,r,i,o)}let f=Mc(e,t,r,i,o,c),h=c.resolve?.(f,m=>i(s,"TAG_RESOLVE_FAILED",m),t.options)??f,p=be(h)?h:new Y(h);return p.range=f.range,p.tag=o,c?.format&&(p.format=c.format),p}function Vc(e,t,r){let n=t.offset,i=BA(t,e.options.strict,r);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};let s=i.mode===">"?Y.BLOCK_FOLDED:Y.BLOCK_LITERAL,o=t.source?MA(t.source):[],u=o.length;for(let b=o.length-1;b>=0;--b){let v=o[b][1];if(v===""||v==="\r")u=b;else break}if(u===0){let b=i.chomp==="+"&&o.length>0?`+`.repeat(Math.max(1,o.length-1)):"",v=n+i.length;return t.source&&(v+=t.source.length),{value:b,type:s,comment:i.comment,range:[n,v,v]}}let c=t.indent+i.indent,f=t.offset+i.length,h=0;for(let b=0;b<u;++b){let[v,k]=o[b];if(k===""||k==="\r")i.indent===0&&v.length>c&&(c=v.length);else{v.length<c&&r(f+v.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),i.indent===0&&(c=v.length),h=b,c===0&&!e.atRoot&&r(f,"BAD_INDENT","Block scalar values in collections must be indented");break}f+=v.length+k.length+1}for(let b=o.length-1;b>=u;--b)o[b][0].length>c&&(u=b+1);let p="",m="",d=!1;for(let b=0;b<h;++b)p+=o[b][0].slice(c)+`+`;for(let b=h;b<u;++b){let[v,k]=o[b];f+=v.length+k.length+1;let T=k[k.length-1]==="\r";if(T&&(k=k.slice(0,-1)),k&&v.length<c){let g=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;r(f-k.length-(T?2:1),"BAD_INDENT",g),v=""}s===Y.BLOCK_LITERAL?(p+=m+v.slice(c)+k,m=`+`):v.length>c||k[0]===" "?(m===" "?m=`+`:!d&&m===`+`&&(m=`-`),l+=f+h.slice(c)+b,f=`-`,p=!0):b===""?f===`-`?l+=`-`:f=`-`:(l+=f+b,f=" ",p=!1)}switch(o.chomp){case"-":break;case"+":for(let m=a;m<i.length;++m)l+=`-`+i[m][0].slice(c);l[l.length-1]!==`-`&&(l+=`-`);break;default:l+=`-`}let y=r+o.length+e.source.length;return{value:l,type:s,comment:o.comment,range:[r,y,y]}}function Lm({offset:t,props:e},n,r){if(e[0].type!=="block-scalar-header")return r(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:o}=e[0],s=o[0],i=0,a="",c=-1;for(let f=1;f<o.length;++f){let p=o[f];if(!a&&(p==="-"||p==="+"))a=p;else{let y=Number(p);!i&&y?i=y:c===-1&&(c=t+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${o}`);let u=!1,d="",l=o.length;for(let f=1;f<e.length;++f){let p=e[f];switch(p.type){case"space":u=!0;case"newline":l+=p.source.length;break;case"comment":n&&!u&&r(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),l+=p.source.length,d=p.source.substring(1);break;case"error":r(p,"UNEXPECTED_TOKEN",p.message),l+=p.source.length;break;default:{let y=`Unexpected token in block scalar header: ${p.type}`;r(p,"UNEXPECTED_TOKEN",y);let m=p.source;m&&typeof m=="string"&&(l+=m.length)}}}return{mode:s,indent:i,chomp:a,comment:d,length:l}}function Mm(t){let e=t.split(/\n( *)/),n=e[0],r=n.match(/^( *)/),s=[r?.[1]?[r[1],n.slice(r[1].length)]:["",n]];for(let i=1;i<e.length;i+=2)s.push([e[i],e[i+1]]);return s}function vs(t,e,n){let{offset:r,type:o,source:s,end:i}=t,a,c,u=(f,p,y)=>n(r+f,p,y);switch(o){case"scalar":a=D.PLAIN,c=Fm(s,u);break;case"single-quoted-scalar":a=D.QUOTE_SINGLE,c=Zm(s,u);break;case"double-quoted-scalar":a=D.QUOTE_DOUBLE,c=jm(s,u);break;default:return n(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${o}`),{value:"",type:null,comment:"",range:[r,r+s.length,r+s.length]}}let d=r+s.length,l=Ue(i,d,e,n);return{value:c,type:a,comment:l.comment,range:[r,d,l.offset]}}function Fm(t,e){let n="";switch(t[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${t[0]}`;break}case"@":case"`":{n=`reserved character ${t[0]}`;break}}return n&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),Gl(t)}function Zm(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),Gl(t.slice(1,-1)).replace(/''/g,"'")}function Gl(t){let e,n;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?-`,"sy"),n=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?-`,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,n=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=e.exec(t);if(!r)return t;let o=r[1],s=" ",i=e.lastIndex;for(n.lastIndex=i;r=n.exec(t);)r[1]===""?s===`-`?o+=s:s=`-`:(o+=s+r[1],s=" "),i=n.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=i,r=a.exec(t),o+s+(r?.[1]??"")}function jm(t,e){let n="";for(let r=1;r<t.length-1;++r){let o=t[r];if(!(o==="\r"&&t[r+1]===`-`))if(o===`-`){let{fold:s,offset:i}=Bm(t,r);n+=s,r=i}else if(o==="\\"){let s=t[++r],i=Um[s];if(i)n+=i;else if(s===`-`)for(s=t[r+1];s===" "||s===" ";)s=t[++r+1];else if(s==="\r"&&t[r+1]===`-`)for(s=t[++r+1];s===" "||s===" ";)s=t[++r+1];else if(s==="x"||s==="u"||s==="U"){let a=s==="x"?2:s==="u"?4:8;n+=Qm(t,r+1,a,e),r+=a}else{let a=t.substr(r-1,2);e(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),n+=a}}else if(o===" "||o===" "){let s=r,i=t[r+1];for(;i===" "||i===" ";)i=t[++r+1];i!==`-`&&!(i==="\r"&&t[r+2]===`-`)&&(n+=r>s?t.slice(s,r+1):o)}else n+=o}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),n}function Bm(t,e){let n="",r=t[e+1];for(;(r===" "||r===" "||r===`-`||r==="\r")&&!(r==="\r"&&t[e+2]!==`-`);)r===`-`&&(n+=`-`),e+=1,r=t[e+1];return n||(n=" "),{fold:n,offset:e}}var Um={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`-`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Qm(t,e,n,r){let o=t.substr(e,n),i=o.length===n&&/^[0-9a-fA-F]+$/.test(o)?parseInt(o,16):NaN;try{return String.fromCodePoint(i)}catch{let a=t.substr(e-2,n+2);return r(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}function ks(t,e,n,r){let{value:o,type:s,comment:i,range:a}=e.type==="block-scalar"?Es(t,e,r):vs(e,t.options.strict,r),c=n?t.directives.tagName(n.source,l=>r(n,"TAG_RESOLVE_FAILED",l)):null,u;t.options.stringKeys&&t.atKey?u=t.schema[me]:c?u=Gm(t.schema,o,c,n,r):e.type==="scalar"?u=Vm(t,o,e,r):u=t.schema[me];let d;try{let l=u.resolve(o,f=>r(n??e,"TAG_RESOLVE_FAILED",f),t.options);d=N(l)?l:new D(l)}catch(l){let f=l instanceof Error?l.message:String(l);r(n??e,"TAG_RESOLVE_FAILED",f),d=new D(o)}return d.range=a,d.source=o,s&&(d.type=s),c&&(d.tag=c),u.format&&(d.format=u.format),i&&(d.comment=i),d}function Gm(t,e,n,r,o){if(n==="!")return t[me];let s=[];for(let a of t.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(e))return a;let i=t.knownTags[n];return i&&!i.collection?(t.tags.push(Object.assign({},i,{default:!1,test:void 0})),i):(o(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),t[me])}function Vm({atKey:t,directives:e,schema:n},r,o,s){let i=n.tags.find(a=>(a.default===!0||t&&a.default==="key")&&a.test?.test(r))||n[me];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(r))??n[me];if(i.tag!==a.tag){let c=e.tagString(i.tag),u=e.tagString(a.tag),d=`Value may be parsed as either ${c} or ${u}`;s(o,"TAG_RESOLVE_FAILED",d,!0)}}return i}function Vl(t,e,n){if(e){n??(n=e.length);for(let r=n-1;r>=0;--r){let o=e[r];switch(o.type){case"space":case"comment":case"newline":t-=o.source.length;continue}for(o=e[++r];o?.type==="space";)t+=o.source.length,o=e[++r];break}}return t}var qm={composeNode:Ds,composeEmptyNode:Gr};function Ds(t,e,n,r){let o=t.atKey,{spaceBefore:s,comment:i,anchor:a,tag:c}=n,u,d=!0;switch(e.type){case"alias":u=Jm(t,e,r),(a||c)&&r(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":u=ks(t,e,c,r),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{u=Ql(qm,t,e,n,r),a&&(u.anchor=a.source.substring(1))}catch(l){let f=l instanceof Error?l.message:String(l);r(e,"RESOURCE_EXHAUSTION",f)}break;default:{let l=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;r(e,"UNEXPECTED_TOKEN",l),d=!1}}return u??(u=Gr(t,e.offset,void 0,null,n,r)),a&&u.anchor===""&&r(a,"BAD_ALIAS","Anchor cannot be an empty string"),o&&t.options.stringKeys&&(!N(u)||typeof u.value!="string"||u.tag&&u.tag!=="tag:yaml.org,2002:str")&&r(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(u.spaceBefore=!0),i&&(e.type==="scalar"&&e.source===""?u.comment=i:u.commentBefore=i),t.options.keepSourceTokens&&d&&(u.srcToken=e),u}function Gr(t,e,n,r,{spaceBefore:o,comment:s,anchor:i,tag:a,end:c},u){let d={type:"scalar",offset:Vl(e,n,r),indent:-1,source:""},l=ks(t,d,a,u);return i&&(l.anchor=i.source.substring(1),l.anchor===""&&u(i,"BAD_ALIAS","Anchor cannot be an empty string")),o&&(l.spaceBefore=!0),s&&(l.comment=s,l.range[2]=c),l}function Jm({options:t},{offset:e,source:n,end:r},o){let s=new Je(n.substring(1));s.source===""&&o(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&o(e+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let i=e+n.length,a=Ue(r,i,t.strict,o);return s.range=[e,i,a.offset],a.comment&&(s.comment=a.comment),s}function ql(t,e,{offset:n,start:r,value:o,end:s},i){let a=Object.assign({_directives:e},t),c=new lt(void 0,a),u={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=Be(r,{indicator:"doc-start",next:o??s?.[0],offset:n,onError:i,parentIndent:0,startOnNewline:!0});d.found&&(c.directives.docStart=!0,o&&(o.type==="block-map"||o.type==="block-seq")&&!d.hasNewline&&i(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=o?Ds(u,o,d,i):Gr(u,d.end,r,null,d,i);let l=c.contents.range[2],f=Ue(s,l,!1,i);return f.comment&&(c.comment=f.comment),c.range=[n,l,f.offset],c}function $n(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:n}=t;return[e,e+(typeof n=="string"?n.length:1)]}function Jl(t){let e="",n=!1,r=!1;for(let o=0;o<t.length;++o){let s=t[o];switch(s[0]){case"#":e+=(e===""?"":r?`+`),p+=m+v.slice(c)+k,m=`+`,d=!0):k===""?m===`+`?p+=`+`:m=`+`:(p+=m+k,m=" ",d=!1)}switch(i.chomp){case"-":break;case"+":for(let b=u;b<o.length;++b)p+=`+`+o[b][0].slice(c);p[p.length-1]!==`+`&&(p+=`+`);break;default:p+=`+`}let x=n+i.length+t.source.length;return{value:p,type:s,comment:i.comment,range:[n,x,x]}}function BA({offset:e,props:t},r,n){if(t[0].type!=="block-scalar-header")return n(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:i}=t[0],s=i[0],o=0,u="",c=-1;for(let m=1;m<i.length;++m){let d=i[m];if(!u&&(d==="-"||d==="+"))u=d;else{let x=Number(d);!o&&x?o=x:c===-1&&(c=e+m)}}c!==-1&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let f=!1,h="",p=i.length;for(let m=1;m<t.length;++m){let d=t[m];switch(d.type){case"space":f=!0;case"newline":p+=d.source.length;break;case"comment":r&&!f&&n(d,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),p+=d.source.length,h=d.source.substring(1);break;case"error":n(d,"UNEXPECTED_TOKEN",d.message),p+=d.source.length;break;default:{let x=`Unexpected token in block scalar header: ${d.type}`;n(d,"UNEXPECTED_TOKEN",x);let b=d.source;b&&typeof b=="string"&&(p+=b.length)}}}return{mode:s,indent:o,chomp:u,comment:h,length:p}}function MA(e){let t=e.split(/\n( *)/),r=t[0],n=r.match(/^( *)/),s=[n?.[1]?[n[1],r.slice(n[1].length)]:["",r]];for(let o=1;o<t.length;o+=2)s.push([t[o],t[o+1]]);return s}function $c(e,t,r){let{offset:n,type:i,source:s,end:o}=e,u,c,f=(m,d,x)=>r(n+m,d,x);switch(i){case"scalar":u=Y.PLAIN,c=VA(s,f);break;case"single-quoted-scalar":u=Y.QUOTE_SINGLE,c=$A(s,f);break;case"double-quoted-scalar":u=Y.QUOTE_DOUBLE,c=jA(s,f);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[n,n+s.length,n+s.length]}}let h=n+s.length,p=Nr(o,h,t,r);return{value:c,type:u,comment:p.comment,range:[n,h,p.offset]}}function VA(e,t){let r="";switch(e[0]){case" ":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${e[0]}`;break}case"@":case"`":{r=`reserved character ${e[0]}`;break}}return r&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),Oy(e)}function $A(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Oy(e.slice(1,-1)).replace(/''/g,"'")}function Oy(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?+`,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?+`,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=t.exec(e);if(!n)return e;let i=n[1],s=" ",o=t.lastIndex;for(r.lastIndex=o;n=r.exec(e);)n[1]===""?s===`+`?i+=s:s=`+`:(i+=s+n[1],s=" "),o=r.lastIndex;let u=/[ \t]*(.*)/sy;return u.lastIndex=o,n=u.exec(e),i+s+(n?.[1]??"")}function jA(e,t){let r="";for(let n=1;n<e.length-1;++n){let i=e[n];if(!(i==="\r"&&e[n+1]===`+`))if(i===`+`){let{fold:s,offset:o}=UA(e,n);r+=s,n=o}else if(i==="\\"){let s=e[++n],o=qA[s];if(o)r+=o;else if(s===`+`)for(s=e[n+1];s===" "||s===" ";)s=e[++n+1];else if(s==="\r"&&e[n+1]===`+`)for(s=e[++n+1];s===" "||s===" ";)s=e[++n+1];else if(s==="x"||s==="u"||s==="U"){let u=s==="x"?2:s==="u"?4:8;r+=ZA(e,n+1,u,t),n+=u}else{let u=e.substr(n-1,2);t(n-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${u}`),r+=u}}else if(i===" "||i===" "){let s=n,o=e[n+1];for(;o===" "||o===" ";)o=e[++n+1];o!==`+`&&!(o==="\r"&&e[n+2]===`+`)&&(r+=n>s?e.slice(s,n+1):i)}else r+=i}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function UA(e,t){let r="",n=e[t+1];for(;(n===" "||n===" "||n===`+`||n==="\r")&&!(n==="\r"&&e[t+2]!==`+`);)n===`+`&&(r+=`+`),t+=1,n=e[t+1];return r||(r=" "),{fold:r,offset:t}}var qA={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`+`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function ZA(e,t,r,n){let i=e.substr(t,r),o=i.length===r&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(o)}catch{let u=e.substr(t-2,r+2);return n(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${u}`),u}}function jc(e,t,r,n){let{value:i,type:s,comment:o,range:u}=t.type==="block-scalar"?Vc(e,t,n):$c(t,e.options.strict,n),c=r?e.directives.tagName(r.source,p=>n(r,"TAG_RESOLVE_FAILED",p)):null,f;e.options.stringKeys&&e.atKey?f=e.schema[It]:c?f=JA(e.schema,i,c,r,n):t.type==="scalar"?f=GA(e,i,t,n):f=e.schema[It];let h;try{let p=f.resolve(i,m=>n(r??t,"TAG_RESOLVE_FAILED",m),e.options);h=pe(p)?p:new Y(p)}catch(p){let m=p instanceof Error?p.message:String(p);n(r??t,"TAG_RESOLVE_FAILED",m),h=new Y(i)}return h.range=u,h.source=i,s&&(h.type=s),c&&(h.tag=c),f.format&&(h.format=f.format),o&&(h.comment=o),h}function JA(e,t,r,n,i){if(r==="!")return e[It];let s=[];for(let u of e.tags)if(!u.collection&&u.tag===r)if(u.default&&u.test)s.push(u);else return u;for(let u of s)if(u.test?.test(t))return u;let o=e.knownTags[r];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[It])}function GA({atKey:e,directives:t,schema:r},n,i,s){let o=r.tags.find(u=>(u.default===!0||e&&u.default==="key")&&u.test?.test(n))||r[It];if(r.compat){let u=r.compat.find(c=>c.default&&c.test?.test(n))??r[It];if(o.tag!==u.tag){let c=t.tagString(o.tag),f=t.tagString(u.tag),h=`Value may be parsed as either ${c} or ${f}`;s(i,"TAG_RESOLVE_FAILED",h,!0)}}return o}function Fy(e,t,r){if(t){r??(r=t.length);for(let n=r-1;n>=0;--n){let i=t[n];switch(i.type){case"space":case"comment":case"newline":e-=i.source.length;continue}for(i=t[++n];i?.type==="space";)e+=i.source.length,i=t[++n];break}}return e}var QA={composeNode:Uc,composeEmptyNode:ya};function Uc(e,t,r,n){let i=e.atKey,{spaceBefore:s,comment:o,anchor:u,tag:c}=r,f,h=!0;switch(t.type){case"alias":f=HA(e,t,n),(u||c)&&n(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":f=jc(e,t,c,n),u&&(f.anchor=u.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{f=Py(QA,e,t,r,n),u&&(f.anchor=u.source.substring(1))}catch(p){let m=p instanceof Error?p.message:String(p);n(t,"RESOURCE_EXHAUSTION",m)}break;default:{let p=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;n(t,"UNEXPECTED_TOKEN",p),h=!1}}return f??(f=ya(e,t.offset,void 0,null,r,n)),u&&f.anchor===""&&n(u,"BAD_ALIAS","Anchor cannot be an empty string"),i&&e.options.stringKeys&&(!pe(f)||typeof f.value!="string"||f.tag&&f.tag!=="tag:yaml.org,2002:str")&&n(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(f.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?f.comment=o:f.commentBefore=o),e.options.keepSourceTokens&&h&&(f.srcToken=t),f}function ya(e,t,r,n,{spaceBefore:i,comment:s,anchor:o,tag:u,end:c},f){let h={type:"scalar",offset:Fy(t,r,n),indent:-1,source:""},p=jc(e,h,u,f);return o&&(p.anchor=o.source.substring(1),p.anchor===""&&f(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(p.spaceBefore=!0),s&&(p.comment=s,p.range[2]=c),p}function HA({options:e},{offset:t,source:r,end:n},i){let s=new Jr(r.substring(1));s.source===""&&i(t,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&i(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+r.length,u=Nr(n,o,e.strict,i);return s.range=[t,o,u.offset],u.comment&&(s.comment=u.comment),s}function Ly(e,t,{offset:r,start:n,value:i,end:s},o){let u=Object.assign({_directives:t},e),c=new gn(void 0,u),f={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},h=Rr(n,{indicator:"doc-start",next:i??s?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});h.found&&(c.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!h.hasNewline&&o(h.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?Uc(f,i,h,o):ya(f,h.end,n,null,h,o);let p=c.contents.range[2],m=Nr(s,p,!1,o);return m.comment&&(c.comment=m.comment),c.range=[r,p,m.offset],c}function Fs(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:r}=e;return[t,t+(typeof r=="string"?r.length:1)]}function zy(e){let t="",r=!1,n=!1;for(let i=0;i<e.length;++i){let s=e[i];switch(s[0]){case"#":t+=(t===""?"":n?``:`-`)+(s.substring(1)||" "),n=!0,r=!1;break;case"%":t[o+1]?.[0]!=="#"&&(o+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:e,afterEmptyLine:r}}var Tn=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,r,o,s)=>{let i=$n(n);s?this.warnings.push(new Cn(i,r,o)):this.errors.push(new Re(i,r,o))},this.directives=new Ze({version:e.version||"1.2"}),this.options=e}decorate(e,n){let{comment:r,afterEmptyLine:o}=Jl(this.prelude);if(r){let s=e.contents;if(n)e.comment=e.comment?`${e.comment}-${r}`:r;else if(o||e.directives.docStart||!s)e.commentBefore=r;else if(j(s)&&!s.flow&&s.items.length>0){let i=s.items[0];T(i)&&(i=i.key);let a=i.commentBefore;i.commentBefore=a?`${r}-${a}`:r}else{let i=s.commentBefore;s.commentBefore=i?`${r}-${i}`:r}}if(n){for(let s=0;s<this.errors.length;++s)e.errors.push(this.errors[s]);for(let s=0;s<this.warnings.length;++s)e.warnings.push(this.warnings[s])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Jl(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,n=!1,r=-1){for(let o of e)yield*this.next(o);yield*this.end(n,r)}*next(e){switch(e.type){case"directive":this.directives.add(e.source,(n,r,o)=>{let s=$n(e);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",r,o)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let n=ql(this.options,this.directives,e,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let n=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,r=new Re($n(e),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new Re($n(e),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let n=Ue(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let r=this.doc.comment;this.doc.comment=r?`${r}-${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new Re($n(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let r=Object.assign({_directives:this.directives},this.options),o=new lt(void 0,r);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),o.range=[0,n,n],this.decorate(o,!1),yield o}}};var Rs=Symbol("break visit"),Km=Symbol("skip children"),Kl=Symbol("remove item");function _t(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),Wl(Object.freeze([]),t,e)}_t.BREAK=Rs;_t.SKIP=Km;_t.REMOVE=Kl;_t.itemAtPath=(t,e)=>{let n=t;for(let[r,o]of e){let s=n?.[r];if(s&&"items"in s)n=s.items[o];else return}return n};_t.parentCollection=(t,e)=>{let n=_t.itemAtPath(t,e.slice(0,-1)),r=e[e.length-1][0],o=n?.[r];if(o&&"items"in o)return o;throw new Error("Parent collection not found")};function Wl(t,e,n){let r=n(e,t);if(typeof r=="symbol")return r;for(let o of["key","value"]){let s=e[o];if(s&&"items"in s){for(let i=0;i<s.items.length;++i){let a=Wl(Object.freeze(t.concat([[o,i]])),s.items[i],n);if(typeof a=="number")i=a-1;else{if(a===Rs)return Rs;a===Kl&&(s.items.splice(i,1),i-=1)}}typeof r=="function"&&o==="key"&&(r=r(e,t))}}return typeof r=="function"?r(e,t):r}var Is="\uFEFF",Os="",Cs="",Vr="";function Yl(t){switch(t){case Is:return"byte-order-mark";case Os:return"doc-mode";case Cs:return"flow-error-end";case Vr:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`+`)+(s.substring(1)||" "),r=!0,n=!1;break;case"%":e[i+1]?.[0]!=="#"&&(i+=1),r=!1;break;default:r||(n=!0),r=!1}}return{comment:t,afterEmptyLine:n}}var Ls=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,n,i,s)=>{let o=Fs(r);s?this.warnings.push(new Ps(o,n,i)):this.errors.push(new hr(o,n,i))},this.directives=new Ir({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:n,afterEmptyLine:i}=zy(this.prelude);if(n){let s=t.contents;if(r)t.comment=t.comment?`${t.comment}+${n}`:n;else if(i||t.directives.docStart||!s)t.commentBefore=n;else if(_e(s)&&!s.flow&&s.items.length>0){let o=s.items[0];ge(o)&&(o=o.key);let u=o.commentBefore;o.commentBefore=u?`${n}+${u}`:n}else{let o=s.commentBefore;s.commentBefore=o?`${n}+${o}`:n}}if(r){for(let s=0;s<this.errors.length;++s)t.errors.push(this.errors[s]);for(let s=0;s<this.warnings.length;++s)t.warnings.push(this.warnings[s])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:zy(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,r=!1,n=-1){for(let i of t)yield*this.next(i);yield*this.end(r,n)}*next(t){switch(t.type){case"directive":this.directives.add(t.source,(r,n,i)=>{let s=Fs(t);s[0]+=r,this.onError(s,"BAD_DIRECTIVE",n,i)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=Ly(this.options,this.directives,t,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(r,!1),this.doc&&(yield this.doc),this.doc=r,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let r=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,n=new hr(Fs(t),"UNEXPECTED_TOKEN",r);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){let n="Unexpected doc-end without preceding document";this.errors.push(new hr(Fs(t),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let r=Nr(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let n=this.doc.comment;this.doc.comment=n?`${n}+${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new hr(Fs(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let n=Object.assign({_directives:this.directives},this.options),i=new gn(void 0,n);this.atDirectives&&this.onError(r,"MISSING_CHAR","Missing directives-end indicator line"),i.range=[0,r,r],this.decorate(i,!1),yield i}}};var qc=Symbol("break visit"),WA=Symbol("skip children"),By=Symbol("remove item");function zn(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),My(Object.freeze([]),e,t)}zn.BREAK=qc;zn.SKIP=WA;zn.REMOVE=By;zn.itemAtPath=(e,t)=>{let r=e;for(let[n,i]of t){let s=r?.[n];if(s&&"items"in s)r=s.items[i];else return}return r};zn.parentCollection=(e,t)=>{let r=zn.itemAtPath(e,t.slice(0,-1)),n=t[t.length-1][0],i=r?.[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function My(e,t,r){let n=r(t,e);if(typeof n=="symbol")return n;for(let i of["key","value"]){let s=t[i];if(s&&"items"in s){for(let o=0;o<s.items.length;++o){let u=My(Object.freeze(e.concat([[i,o]])),s.items[o],r);if(typeof u=="number")o=u-1;else{if(u===qc)return qc;u===By&&(s.items.splice(o,1),o-=1)}}typeof n=="function"&&i==="key"&&(n=n(t,e))}}return typeof n=="function"?n(t,e):n}var Zc="\uFEFF",Jc="",Gc="",xa="";function Vy(e){switch(e){case Zc:return"byte-order-mark";case Jc:return"doc-mode";case Gc:return"flow-error-end";case xa:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case``:case`\r-`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}function Ie(t){switch(t){case void 0:case" ":case`-`:case"\r":case" ":return!0;default:return!1}}var Hl=new Set("0123456789ABCDEFabcdef"),Ym=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),qr=new Set(",[]{}"),Hm=new Set(` ,[]{}-\r `),Ns=t=>!t||Hm.has(t),zn=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,n=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!n;let r=this.next??"stream";for(;r&&(n||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let e=this.pos,n=this.buffer[e];for(;n===" "||n===" ";)n=this.buffer[++e];return!n||n==="#"||n===`-`?!0:n==="\r"?this.buffer[e+1]===`-`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let n=this.buffer[e];if(this.indentNext>0){let r=0;for(;n===" ";)n=this.buffer[++r+e];if(n==="\r"){let o=this.buffer[r+e+1];if(o===`-`||!o&&!this.atEnd)return e+r+1}return n===`-`||r>=this.indentNext||!n&&!this.atEnd?e+r:-1}if(n==="-"||n==="."){let r=this.buffer.substr(e,3);if((r==="---"||r==="...")&&Ie(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`-`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===Is&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let n=e.length,r=e.indexOf("#");for(;r!==-1;){let s=e[r-1];if(s===" "||s===" "){n=r-1;break}else r=e.indexOf("#",r+1)}for(;;){let s=e[n-1];if(s===" "||s===" ")n-=1;else break}let o=(yield*this.pushCount(n))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-o),this.pushNewline(),"stream"}if(this.atLineEnd()){let n=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-n),yield*this.pushNewline(),"stream"}return yield Os,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let n=this.peek(3);if((n==="---"||n==="...")&&Ie(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,n==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Ie(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&Ie(n)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(e[n]){case"#":yield*this.pushCount(e.length-n);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Ns),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,n,r=-1;do e=yield*this.pushNewline(),e>0?(n=yield*this.pushSpaces(!1),this.indentValue=r=n):n=0,n+=yield*this.pushSpaces(!0);while(e+n>0);let o=this.getLine();if(o===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&o[0]!=="#"||r===0&&(o.startsWith("---")||o.startsWith("..."))&&Ie(o[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(o[0]==="]"||o[0]==="}")))return this.flowLevel=0,yield Cs,yield*this.parseLineStart();let s=0;for(;o[s]===",";)s+=yield*this.pushCount(1),s+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(s+=yield*this.pushIndicators(),o[s]){case void 0:return"flow";case"#":return yield*this.pushCount(o.length-s),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(Ns),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let i=this.charAt(1);if(this.flowKey||Ie(i)||i===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),n=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;n!==-1&&this.buffer[n+1]==="'";)n=this.buffer.indexOf("'",n+2);else for(;n!==-1;){let s=0;for(;this.buffer[n-1-s]==="\\";)s+=1;if(s%2===0)break;n=this.buffer.indexOf('"',n+1)}let r=this.buffer.substring(0,n),o=r.indexOf(`-`,this.pos);if(o!==-1){for(;o!==-1;){let s=this.continueScalar(o+1);if(s===-1)break;o=r.indexOf(`-`,s)}o!==-1&&(n=o-(r[o-1]==="\r"?2:1))}if(n===-1){if(!this.atEnd)return this.setNext("quoted-scalar");n=this.buffer.length}return yield*this.pushToIndex(n+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let n=this.buffer[++e];if(n==="+")this.blockScalarKeep=!0;else if(n>"0"&&n<="9")this.blockScalarIndent=Number(n)-1;else if(n!=="-")break}return yield*this.pushUntil(n=>Ie(n)||n==="#")}*parseBlockScalar(){let e=this.pos-1,n=0,r;e:for(let s=this.pos;r=this.buffer[s];++s)switch(r){case" ":n+=1;break;case`-`:e=s,n=0;break;case"\r":{let i=this.buffer[s+1];if(!i&&!this.atEnd)return this.setNext("block-scalar");if(i===`-`)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(n>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=n:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let s=this.continueScalar(e+1);if(s===-1)break;e=this.buffer.indexOf(`-`,s)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let o=e+1;for(r=this.buffer[o];r===" ";)r=this.buffer[++o];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`-`;)r=this.buffer[++o];e=o-1}else if(!this.blockScalarKeep)do{let s=e-1,i=this.buffer[s];i==="\r"&&(i=this.buffer[--s]);let a=s;for(;i===" ";)i=this.buffer[--s];if(i===`-`&&s>=this.pos&&s+1+n>a)e=s;else break}while(!0);return yield Vr,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,n=this.pos-1,r=this.pos-1,o;for(;o=this.buffer[++r];)if(o===":"){let s=this.buffer[r+1];if(Ie(s)||e&&qr.has(s))break;n=r}else if(Ie(o)){let s=this.buffer[r+1];if(o==="\r"&&(s===`-`?(r+=1,o=`-`,s=this.buffer[r+1]):n=r),s==="#"||e&&qr.has(s))break;if(o===`-`){let i=this.continueScalar(r+1);if(i===-1)break;r=Math.max(r,i-2)}}else{if(e&&qr.has(o))break;n=r}return!o&&!this.atEnd?this.setNext("plain-scalar"):(yield Vr,yield*this.pushToIndex(n+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,n){let r=this.buffer.slice(this.pos,e);return r?(yield r,this.pos+=r.length,r.length):(n&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Ns),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,r=this.charAt(1);if(Ie(r)||n&&qr.has(r)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,n=this.buffer[e];for(;!Ie(n)&&n!==">";)n=this.buffer[++e];return yield*this.pushToIndex(n===">"?e+1:e,!1)}else{let e=this.pos+1,n=this.buffer[e];for(;n;)if(Ym.has(n))n=this.buffer[++e];else if(n==="%"&&Hl.has(this.buffer[e+1])&&Hl.has(this.buffer[e+2]))n=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`-`?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`-`?yield*this.pushCount(2):0}*pushSpaces(e){let n=this.pos-1,r;do r=this.buffer[++n];while(r===" "||e&&r===" ");let o=n-this.pos;return o>0&&(yield this.buffer.substr(this.pos,o),this.pos=n),o}*pushUntil(e){let n=this.pos,r=this.buffer[n];for(;!e(r);)r=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};var Pn=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let n=0,r=this.lineStarts.length;for(;n<r;){let s=n+r>>1;this.lineStarts[s]<e?n=s+1:r=s}if(this.lineStarts[n]===e)return{line:n+1,col:1};if(n===0)return{line:0,col:e};let o=this.lineStarts[n-1];return{line:n,col:e-o+1}}}};function dt(t,e){for(let n=0;n<t.length;++n)if(t[n].type===e)return!0;return!1}function Xl(t){for(let e=0;e<t.length;++e)switch(t[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function tf(t){switch(t?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Jr(t){switch(t.type){case"document":return t.start;case"block-map":{let e=t.items[t.items.length-1];return e.sep??e.start}case"block-seq":return t.items[t.items.length-1].start;default:return[]}}function Vt(t){if(t.length===0)return[];let e=t.length;e:for(;--e>=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function Kr(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let n=0;n<e.length;++n)t.push(e[n])}function ef(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!dt(e.start,"explicit-key-ind")&&!dt(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,tf(e.value)?e.value.end?Kr(e.value.end,e.sep):e.value.end=e.sep:Kr(e.start,e.sep),delete e.sep)}var Ln=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new zn,this.onNewLine=e}*parse(e,n=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(e,n))yield*this.next(r);n||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let n=Yl(e);if(n)if(n==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=n,yield*this.step(),n){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let r=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let n=e??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let r=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in r?r.indent:0:n.type==="flow-collection"&&r.type==="document"&&(n.indent=0),n.type==="flow-collection"&&ef(n),r.type){case"document":r.value=n;break;case"block-scalar":r.props.push(n);break;case"block-map":{let o=r.items[r.items.length-1];if(o.value){r.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(o.sep)o.value=n;else{Object.assign(o,{key:n,sep:[]}),this.onKeyLine=!o.explicitKey;return}break}case"block-seq":{let o=r.items[r.items.length-1];o.value?r.items.push({start:[],value:n}):o.value=n;break}case"flow-collection":{let o=r.items[r.items.length-1];!o||o.value?r.items.push({start:[],key:n,sep:[]}):o.sep?o.value=n:Object.assign(o,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let o=n.items[n.items.length-1];o&&!o.sep&&!o.value&&o.start.length>0&&Xl(o.start)===-1&&(n.indent===0||o.start.every(s=>s.type!=="comment"||s.indent<n.indent))&&(r.type==="document"?r.end=o.start:r.items.push({start:o.start}),n.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{Xl(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let n=Jr(this.peek(2)),r=Vt(n),o;e.end?(o=e.end,o.push(this.sourceToken),delete e.end):o=[this.sourceToken];let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:r,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let n=this.source.indexOf(`-`)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`-`,n)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else if(n.sep)n.sep.push(this.sourceToken);else{if(this.atIndentedComment(n.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){Kr(o,n.start),o.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let r=!this.onKeyLine&&this.indent===e.indent,o=r&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",s=[];if(o&&n.sep&&!n.value){let i=[];for(let a=0;a<n.sep.length;++a){let c=n.sep[a];switch(c.type){case"newline":i.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(i.length=0);break;default:i.length=0}}i.length>=2&&(s=n.sep.splice(i[1]))}switch(this.type){case"anchor":case"tag":o||n.value?(s.push(this.sourceToken),e.items.push({start:s}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):o||n.value?(s.push(this.sourceToken),e.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(dt(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(tf(n.key)&&!dt(n.sep,"newline")){let i=Vt(n.start),a=n.key,c=n.sep;c.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:a,sep:c}]})}else s.length>0?n.sep=n.sep.concat(s,this.sourceToken):n.sep.push(this.sourceToken);else if(dt(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let i=Vt(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||o?e.items.push({start:s,key:null,sep:[this.sourceToken]}):dt(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);o||n.value?(e.items.push({start:s,key:i,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(i):(Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!0);return}default:{let i=this.startBlockValue(e);if(i){if(i.type==="block-seq"){if(!n.explicitKey&&n.sep&&!dt(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&e.items.push({start:s});this.stack.push(i);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){Kr(o,n.start),o.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=e.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;n.value||dt(n.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>e.indent){let r=this.startBlockValue(e);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let n=e.items[e.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?e.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);!n||n.value?e.items.push({start:[],key:o,sep:[]}):n.sep?this.stack.push(o):Object.assign(n,{key:o,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let r=this.startBlockValue(e);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===e.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let o=Jr(r),s=Vt(o);ef(e);let i=e.end.splice(1,e.end.length);i.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let n=this.source.indexOf(`-`)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`-`,n)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=Jr(e),r=Vt(n);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=Jr(e),r=Vt(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,n){return this.type!=="comment"||this.indent<=n?!1:e.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};function Xm(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new Pn||null,prettyErrors:e}}function $s(t,e={}){let{lineCounter:n,prettyErrors:r}=Xm(e),o=new Ln(n?.addNewLine),s=new Tn(e),i=null;for(let a of s.compose(o.parse(t),!0,t.length))if(!i)i=a;else if(i.options.logLevel!=="silent"){i.errors.push(new Re(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(i.errors.forEach(_s(t,n)),i.warnings.forEach(_s(t,n))),i}var Oe=class extends Error{code;constructor(e){super(`Structured data failed validation: ${e}`),this.name="StructuredDataError",this.code=e}},th=t=>$e(JSON.stringify(t)),nf=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null},rf=(t,e)=>{if(nf(t)===!1)throw new Oe("INVALID");let n=0,r=(s,i)=>{if(i>e.depth)throw new Oe("DEPTH_EXCEEDED");if(typeof s=="string"){if($e(s)>e.stringBytes)throw new Oe("STRING_BYTES_EXCEEDED");return s}if(s===null||typeof s=="boolean"||typeof s=="number"&&Number.isFinite(s)&&(Number.isInteger(s)===!1||Number.isSafeInteger(s)))return s;if(Array.isArray(s))return s.map(a=>{if(n+=1,n>e.fields)throw new Oe("FIELDS_EXCEEDED");return r(a,i+1)});if(nf(s)){let a=Object.create(null);for(let[c,u]of Object.entries(s)){if(n+=1,n>e.fields)throw new Oe("FIELDS_EXCEEDED");a[c]=r(u,i+1)}return a}throw new Oe("INVALID")},o=r(t,1);if(th(o)>e.serializedBytes)throw new Oe("SERIALIZED_BYTES_EXCEEDED");return o};var H=class extends Error{code;constructor(e,n){super(n),this.name="MarkdownMetadataError",this.code=e}};var Mn=new Uint8Array([239,187,191]),of=Mn.byteLength+10,nh=(t,e,n=0)=>t.byteLength-n<e.byteLength?!1:e.every((r,o)=>t[n+o]===r),Fn=(t,e)=>{let n=0;if(nh(t,Mn))n=Mn.byteLength;else if(t.byteLength<Mn.byteLength&&Mn.slice(0,t.byteLength).every((s,i)=>s===t[i]))return e?null:void 0;if(t.byteLength<n+4)return e?null:void 0;if(t[n]!==45||t[n+1]!==45||t[n+2]!==45)return null;let r=n+3;if(t[r]===10)r+=1;else if(t[r]===13){if(t.byteLength===r+1)return e?null:void 0;if(t[r+1]!==10)return null;r+=2}else return null;let o=r;for(let s=r;s<=t.byteLength;s+=1){let i=s===t.byteLength;if(i===!1&&t[s]!==10)continue;if(i&&e===!1)return;let a=s;if(a>o&&t[a-1]===13&&(a-=1),a-o===3&&(t[o]===45&&t[o+1]===45&&t[o+2]===45||t[o]===46&&t[o+1]===46&&t[o+2]===46))return{yamlStart:r,yamlEnd:o,blockEnd:i?s:s+1};o=s+1}};var rh={bytes:R.frontmatterBytes,depth:R.frontmatterDepth,fields:R.frontmatterFields,stringBytes:R.frontmatterStringBytes,serializedBytes:R.indexedPropertiesBytes},sf=t=>{try{return fe(t)}catch{throw new H("FRONTMATTER_DECODING_FAILED","Markdown frontmatter is not valid UTF-8")}},af=(t,e)=>{let n=$s(t,{schema:"core",uniqueKeys:!0});if(n.errors.length>0)throw new H("FRONTMATTER_INVALID","Markdown frontmatter contains invalid YAML");let r;try{r=n.toJS({maxAliasCount:0})}catch{throw new H("FRONTMATTER_INVALID","Markdown frontmatter contains unsupported YAML aliases")}if(r===null)return{};try{return rf(r,e)}catch(o){throw o instanceof Oe?o.code==="DEPTH_EXCEEDED"?new H("FRONTMATTER_DEPTH_EXCEEDED","Markdown frontmatter exceeds the nesting limit"):o.code==="FIELDS_EXCEEDED"?new H("FRONTMATTER_FIELDS_EXCEEDED","Markdown frontmatter exceeds the field limit"):o.code==="STRING_BYTES_EXCEEDED"?new H("FRONTMATTER_STRING_BYTES_EXCEEDED","Markdown frontmatter contains a string that exceeds the byte limit"):o.code==="SERIALIZED_BYTES_EXCEEDED"?new H("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter properties exceed the indexed byte limit"):new H("FRONTMATTER_INVALID","Markdown frontmatter must contain a JSON-compatible object"):o}},cf=async(t,e={})=>{let n={...rh,...e},r=n.bytes+of,o=new Uint8Array(r),s=0;for await(let c of Nt(t)){let u=0;for(;u<c.byteLength;){let d=r-s;if(d<=0)break;let l=Math.max(0,6-s),f=Math.min(c.byteLength-u,l);if(l===0){let m=c.subarray(u,Math.min(c.byteLength,u+d)),h=m.indexOf(10);f=h===-1?m.byteLength:h+1}o.set(c.subarray(u,u+f),s),s+=f,u+=f;let p=o.subarray(0,s),y=Fn(p,!1);if(y===null)return{properties:{},frontmatterBytes:0,consumedBytes:p.length};if(y!==void 0){let m=y.yamlEnd-y.yamlStart;if(m>n.bytes)throw new H("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter exceeds the byte limit");let h=sf(p.subarray(y.yamlStart,y.yamlEnd));return{properties:af(h,n),frontmatterBytes:m,consumedBytes:y.blockEnd}}}if(s>=r)break}let i=o.subarray(0,s),a=Fn(i,!0);if(a===null)return{properties:{},frontmatterBytes:0,consumedBytes:i.length};if(a!==void 0){let c=a.yamlEnd-a.yamlStart;if(c<=n.bytes){let u=sf(i.subarray(a.yamlStart,a.yamlEnd));return{properties:af(u,n),frontmatterBytes:c,consumedBytes:a.blockEnd}}}throw new H("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter is not closed within the byte limit")};var Wr=async(t,e=R.hydratedFileBytes)=>{if(Number.isInteger(e)===!1||e<=0||e>R.hydratedFileBytes)throw new H("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown body byte limit is outside the supported range");let n;try{n=await Te(t,e)}catch(a){throw a instanceof re?new H("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown content exceeds the byte limit"):a}let r;try{r=fe(n)}catch{throw new H("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}let s=Fn(n,!0)?.blockEnd??0,i;try{i=s===0?$t(r):fe(n.subarray(s))}catch{throw new H("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}return{body:i,bodyBytes:$e(i),sourceBytes:n.byteLength}};var pt=class extends Error{code;referenceId;constructor({code:e,message:n,referenceId:r,cause:o}){super(n,{cause:o}),this.name="MarkdownDocumentError",this.code=e,this.referenceId=r}},oh=C({source:v(),body:v(),frontmatter:_e(v(),rt())}),Hr=t=>{let e;try{e=oh.parse(t)}catch(n){throw new pt({code:"INVALID_DOCUMENT",message:"Markdown document is invalid",cause:n})}return Object.freeze({source:e.source,body:e.body,frontmatter:ot(e.frontmatter)})},Yr="#frontmatter",sh=t=>`${Yr}${t.slice(1)}`,ih=t=>{if(t!==Yr&&t.startsWith(`${Yr}/`)===!1)throw new pt({code:"UNUSED_REFERENCE",message:`Resolved Markdown reference ${t} is outside frontmatter`,referenceId:t});return`#${t.slice(Yr.length)}`},ah=t=>{let e=t.referenceId===void 0?void 0:sh(t.referenceId),n="INVALID_DOCUMENT";throw(t.code==="INVALID_REFERENCE_MARKER"||t.code==="INVALID_REFERENCE"||t.code==="REFERENCE_NOT_FOUND"||t.code==="INVALID_RESOLVED_VALUE"||t.code==="UNUSED_REFERENCE")&&(n=t.code),new pt({code:n,message:t.message,referenceId:e,cause:t})},uf=async({source:t,maximumBytes:e=R.hydratedFileBytes})=>{let n;try{n=await Te(t,e)}catch(i){throw i instanceof re?new pt({code:"CONTENT_LIMIT_EXCEEDED",message:"Markdown document exceeds the byte limit",cause:i}):i}let r;try{r=$t(fe(n))}catch(i){throw new pt({code:"CONTENT_DECODING_FAILED",message:"Markdown document is not valid UTF-8",cause:i})}let[o,s]=await Promise.all([Wr(n,e),cf(n)]);return Hr({source:r,body:o.body,frontmatter:s.properties})};var lf=({document:t,references:e,allowUnresolvedReferences:n=!1})=>{let r=Hr(t),o=new Map;for(let[i,a]of e)o.set(ih(i),a);let s;try{s=mr({document:r.frontmatter,references:o,allowUnresolvedReferences:n})}catch(i){throw i instanceof pe&&ah(i),i}return Hr({...r,frontmatter:s})},ff=({document:t,representation:e})=>{let n=Hr(t);if(e.type==="document")return n.source;if(e.type==="markdown-body")return n.body;if(e.type==="markdown-frontmatter")return n.frontmatter;throw new pt({code:"UNSUPPORTED_REPRESENTATION",message:`Markdown documents do not support ${e.type}`})};var df=t=>{let e=t.format==="markdown"?t.value.frontmatter:t.value;return zt(e)?e:void 0},Xr=t=>Object.freeze(t),pf=async({format:t,source:e,maximumBytes:n=R.hydratedFileBytes})=>Xr(t==="json"?{format:t,value:await fl({source:e,maximumBytes:n})}:{format:t,value:await uf({source:e,maximumBytes:n})});var mf=({document:t,references:e,allowUnresolvedReferences:n})=>t.format==="json"?Xr({format:t.format,value:mr({document:t.value,references:e,allowUnresolvedReferences:n})}):Xr({format:t.format,value:lf({document:t.value,references:e,allowUnresolvedReferences:n})}),hf=({document:t,representation:e})=>t.format==="json"?dl({document:t.value,representation:e}):ff({document:t.value,representation:e});var eo=class extends Error{code;documentId;expectedRevision;actualRevision;expectedFormat;actualFormat;constructor({code:e,documentId:n,expectedRevision:r,actualRevision:o,expectedFormat:s,actualFormat:i}){super(`Document ${n} source ${e==="REVISION_MISMATCH"?"revision":"format"} does not match its graph`),this.name="DocumentSourceError",this.code=e,this.documentId=n,this.expectedRevision=r,this.actualRevision=o,this.expectedFormat=s,this.actualFormat=i}},qt=({node:t,source:e})=>{if(e.revision!==t.revision)throw new eo({code:"REVISION_MISMATCH",documentId:t.id,expectedRevision:t.revision,actualRevision:e.revision});if(t.format!==void 0&&e.format!==t.format)throw new eo({code:"FORMAT_MISMATCH",documentId:t.id,expectedFormat:t.format,actualFormat:e.format});return e};var Jt=t=>{if(typeof t=="object"&&t!==null){let e=Reflect.get(t,"code");if(typeof e=="string"&&e.length>0)return e;let n=Reflect.get(t,"name");if(typeof n=="string"&&n.length>0)return n}return"UNKNOWN"},se=(t,e)=>{try{t?.(e)}catch{}},yf=({load:t,onEvent:e})=>async(n,r)=>{let o={documentId:n.id,revision:n.revision};se(e,{type:"document-fetch-started",...o});try{let s=await t(n,r);return se(e,{type:"document-fetch-completed",...o}),s}catch(s){throw se(e,{type:"document-fetch-failed",...o,errorCode:Jt(s)}),s}};var ch=C({format:ce(["json","markdown"]),revision:v().min(1)}),Kt=class extends Error{code;documentId;status;constructor({code:e,message:n,documentId:r,status:o,cause:s}){super(n,{cause:s}),this.name="HttpDocumentLoaderError",this.code=e,this.documentId=r,this.status=o}},uh=t=>({async*[Symbol.asyncIterator](){let e=t.getReader(),n=!1;try{for(;;){let r=await e.read();if(r.done){n=!0;return}yield r.value}}finally{if(n===!1)try{await e.cancel()}catch{}e.releaseLock()}}}),gf=({fetch:t,getRequest:e,getMetadata:n,onEvent:r})=>yf({load:async(s,{signal:i})=>{let a;try{a=await t(e(s),{signal:i})}catch(d){throw new Kt({code:"REQUEST_FAILED",message:`Document ${s.id} request failed`,documentId:s.id,cause:d})}if(a.ok===!1)throw new Kt({code:"HTTP_STATUS",message:`Document ${s.id} request returned status ${a.status}`,documentId:s.id,status:a.status});let c;try{c=ch.parse(n({node:s,response:a}))}catch(d){throw new Kt({code:"INVALID_METADATA",message:`Document ${s.id} response metadata is invalid`,documentId:s.id,cause:d})}let u=a.body;if(u===null)throw new Kt({code:"BODY_MISSING",message:`Document ${s.id} response body is unavailable`,documentId:s.id});return Object.freeze({...c,source:uh(u)})},onEvent:r});var Wt=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,wf=new Set,Ts=typeof process=="object"&&process?process:{},_f=(t,e,n,r)=>{typeof Ts.emitWarning=="function"?Ts.emitWarning(t,e,n,r):console.error(`[${n}] ${e}: ${t}`)},to=globalThis.AbortController,bf=globalThis.AbortSignal;if(typeof to>"u"){bf=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,o){this._onabort.push(o)}},to=class{constructor(){e()}signal=new bf;abort(r){if(!this.signal.aborted){this.signal.reason=r,this.signal.aborted=!0;for(let o of this.signal._onabort)o(r);this.signal.onabort?.(r)}}};let t=Ts.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,_f("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var lh=t=>!wf.has(t),XE=Symbol("type"),mt=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),xf=t=>mt(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?Yt:null:null,Yt=class extends Array{constructor(e){super(e),this.fill(0)}},zs=class t{heap;length;static#c=!1;static create(e){let n=xf(e);if(!n)return[];t.#c=!0;let r=new t(e,n);return t.#c=!1,r}constructor(e,n){if(!t.#c)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new n(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},Ht=class t{#c;#f;#h;#y;#O;#C;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#o;#g;#r;#n;#e;#u;#d;#a;#s;#b;#i;#w;#_;#p;#x;#k;#l;static unsafeExposeInternals(e){return{starts:e.#_,ttls:e.#p,sizes:e.#w,keyMap:e.#r,keyList:e.#n,valList:e.#e,next:e.#u,prev:e.#d,get head(){return e.#a},get tail(){return e.#s},free:e.#b,isBackgroundFetch:n=>e.#t(n),backgroundFetch:(n,r,o,s)=>e.#T(n,r,o,s),moveToTail:n=>e.#I(n),indexes:n=>e.#S(n),rindexes:n=>e.#A(n),isStale:n=>e.#m(n)}}get max(){return this.#c}get maxSize(){return this.#f}get calculatedSize(){return this.#g}get size(){return this.#o}get fetchMethod(){return this.#O}get memoMethod(){return this.#C}get dispose(){return this.#h}get disposeAfter(){return this.#y}constructor(e){let{max:n=0,ttl:r,ttlResolution:o=1,ttlAutopurge:s,updateAgeOnGet:i,updateAgeOnHas:a,allowStale:c,dispose:u,disposeAfter:d,noDisposeOnSet:l,noUpdateTTL:f,maxSize:p=0,maxEntrySize:y=0,sizeCalculation:m,fetchMethod:h,memoMethod:b,noDeleteOnFetchRejection:S,noDeleteOnStaleGet:A,allowStaleOnFetchRejection:_,allowStaleOnFetchAbort:w,ignoreFetchAbort:E}=e;if(n!==0&&!mt(n))throw new TypeError("max option must be a nonnegative integer");let k=n?xf(n):Array;if(!k)throw new Error("invalid max value: "+n);if(this.#c=n,this.#f=p,this.maxEntrySize=y||this.#f,this.sizeCalculation=m,this.sizeCalculation){if(!this.#f&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(b!==void 0&&typeof b!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#C=b,h!==void 0&&typeof h!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#O=h,this.#k=!!h,this.#r=new Map,this.#n=new Array(n).fill(void 0),this.#e=new Array(n).fill(void 0),this.#u=new k(n),this.#d=new k(n),this.#a=0,this.#s=0,this.#b=zs.create(n),this.#o=0,this.#g=0,typeof u=="function"&&(this.#h=u),typeof d=="function"?(this.#y=d,this.#i=[]):(this.#y=void 0,this.#i=void 0),this.#x=!!this.#h,this.#l=!!this.#y,this.noDisposeOnSet=!!l,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!S,this.allowStaleOnFetchRejection=!!_,this.allowStaleOnFetchAbort=!!w,this.ignoreFetchAbort=!!E,this.maxEntrySize!==0){if(this.#f!==0&&!mt(this.#f))throw new TypeError("maxSize must be a positive integer if specified");if(!mt(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#j()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!A,this.updateAgeOnGet=!!i,this.updateAgeOnHas=!!a,this.ttlResolution=mt(o)||o===0?o:1,this.ttlAutopurge=!!s,this.ttl=r||0,this.ttl){if(!mt(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#z()}if(this.#c===0&&this.ttl===0&&this.#f===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#c&&!this.#f){let x="LRU_CACHE_UNBOUNDED";lh(x)&&(wf.add(x),_f("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",x,t))}}getRemainingTTL(e){return this.#r.has(e)?1/0:0}#z(){let e=new Yt(this.#c),n=new Yt(this.#c);this.#p=e,this.#_=n,this.#P=(s,i,a=Wt.now())=>{if(n[s]=i!==0?a:0,e[s]=i,i!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#m(s)&&this.#E(this.#n[s],"expire")},i+1);c.unref&&c.unref()}},this.#D=s=>{n[s]=e[s]!==0?Wt.now():0},this.#v=(s,i)=>{if(e[i]){let a=e[i],c=n[i];if(!a||!c)return;s.ttl=a,s.start=c,s.now=r||o();let u=s.now-c;s.remainingTTL=a-u}};let r=0,o=()=>{let s=Wt.now();if(this.ttlResolution>0){r=s;let i=setTimeout(()=>r=0,this.ttlResolution);i.unref&&i.unref()}return s};this.getRemainingTTL=s=>{let i=this.#r.get(s);if(i===void 0)return 0;let a=e[i],c=n[i];if(!a||!c)return 1/0;let u=(r||o())-c;return a-u},this.#m=s=>{let i=n[s],a=e[s];return!!a&&!!i&&(r||o())-i>a}}#D=()=>{};#v=()=>{};#P=()=>{};#m=()=>!1;#j(){let e=new Yt(this.#c);this.#g=0,this.#w=e,this.#R=n=>{this.#g-=e[n],e[n]=0},this.#L=(n,r,o,s)=>{if(this.#t(r))return 0;if(!mt(o))if(s){if(typeof s!="function")throw new TypeError("sizeCalculation must be a function");if(o=s(r,n),!mt(o))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return o},this.#N=(n,r,o)=>{if(e[n]=r,this.#f){let s=this.#f-e[n];for(;this.#g>s;)this.#$(!0)}this.#g+=e[n],o&&(o.entrySize=r,o.totalCalculatedSize=this.#g)}}#R=e=>{};#N=(e,n,r)=>{};#L=(e,n,r,o)=>{if(r||o)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#S({allowStale:e=this.allowStale}={}){if(this.#o)for(let n=this.#s;!(!this.#M(n)||((e||!this.#m(n))&&(yield n),n===this.#a));)n=this.#d[n]}*#A({allowStale:e=this.allowStale}={}){if(this.#o)for(let n=this.#a;!(!this.#M(n)||((e||!this.#m(n))&&(yield n),n===this.#s));)n=this.#u[n]}#M(e){return e!==void 0&&this.#r.get(this.#n[e])===e}*entries(){for(let e of this.#S())this.#e[e]!==void 0&&this.#n[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#n[e],this.#e[e]])}*rentries(){for(let e of this.#A())this.#e[e]!==void 0&&this.#n[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#n[e],this.#e[e]])}*keys(){for(let e of this.#S()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*rkeys(){for(let e of this.#A()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*values(){for(let e of this.#S())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}*rvalues(){for(let e of this.#A())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,n={}){for(let r of this.#S()){let o=this.#e[r],s=this.#t(o)?o.__staleWhileFetching:o;if(s!==void 0&&e(s,this.#n[r],this))return this.get(this.#n[r],n)}}forEach(e,n=this){for(let r of this.#S()){let o=this.#e[r],s=this.#t(o)?o.__staleWhileFetching:o;s!==void 0&&e.call(n,s,this.#n[r],this)}}rforEach(e,n=this){for(let r of this.#A()){let o=this.#e[r],s=this.#t(o)?o.__staleWhileFetching:o;s!==void 0&&e.call(n,s,this.#n[r],this)}}purgeStale(){let e=!1;for(let n of this.#A({allowStale:!0}))this.#m(n)&&(this.#E(this.#n[n],"expire"),e=!0);return e}info(e){let n=this.#r.get(e);if(n===void 0)return;let r=this.#e[n],o=this.#t(r)?r.__staleWhileFetching:r;if(o===void 0)return;let s={value:o};if(this.#p&&this.#_){let i=this.#p[n],a=this.#_[n];if(i&&a){let c=i-(Wt.now()-a);s.ttl=c,s.start=Date.now()}}return this.#w&&(s.size=this.#w[n]),s}dump(){let e=[];for(let n of this.#S({allowStale:!0})){let r=this.#n[n],o=this.#e[n],s=this.#t(o)?o.__staleWhileFetching:o;if(s===void 0||r===void 0)continue;let i={value:s};if(this.#p&&this.#_){i.ttl=this.#p[n];let a=Wt.now()-this.#_[n];i.start=Math.floor(Date.now()-a)}this.#w&&(i.size=this.#w[n]),e.unshift([r,i])}return e}load(e){this.clear();for(let[n,r]of e){if(r.start){let o=Date.now()-r.start;r.start=Wt.now()-o}this.set(n,r.value,r)}}set(e,n,r={}){if(n===void 0)return this.delete(e),this;let{ttl:o=this.ttl,start:s,noDisposeOnSet:i=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:c}=r,{noUpdateTTL:u=this.noUpdateTTL}=r,d=this.#L(e,n,r.size||0,a);if(this.maxEntrySize&&d>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.#E(e,"set"),this;let l=this.#o===0?void 0:this.#r.get(e);if(l===void 0)l=this.#o===0?this.#s:this.#b.length!==0?this.#b.pop():this.#o===this.#c?this.#$(!1):this.#o,this.#n[l]=e,this.#e[l]=n,this.#r.set(e,l),this.#u[this.#s]=l,this.#d[l]=this.#s,this.#s=l,this.#o++,this.#N(l,d,c),c&&(c.set="add"),u=!1;else{this.#I(l);let f=this.#e[l];if(n!==f){if(this.#k&&this.#t(f)){f.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:p}=f;p!==void 0&&!i&&(this.#x&&this.#h?.(p,e,"set"),this.#l&&this.#i?.push([p,e,"set"]))}else i||(this.#x&&this.#h?.(f,e,"set"),this.#l&&this.#i?.push([f,e,"set"]));if(this.#R(l),this.#N(l,d,c),this.#e[l]=n,c){c.set="replace";let p=f&&this.#t(f)?f.__staleWhileFetching:f;p!==void 0&&(c.oldValue=p)}}else c&&(c.set="update")}if(o!==0&&!this.#p&&this.#z(),this.#p&&(u||this.#P(l,o,s),c&&this.#v(c,l)),!i&&this.#l&&this.#i){let f=this.#i,p;for(;p=f?.shift();)this.#y?.(...p)}return this}pop(){try{for(;this.#o;){let e=this.#e[this.#a];if(this.#$(!0),this.#t(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#l&&this.#i){let e=this.#i,n;for(;n=e?.shift();)this.#y?.(...n)}}}#$(e){let n=this.#a,r=this.#n[n],o=this.#e[n];return this.#k&&this.#t(o)?o.__abortController.abort(new Error("evicted")):(this.#x||this.#l)&&(this.#x&&this.#h?.(o,r,"evict"),this.#l&&this.#i?.push([o,r,"evict"])),this.#R(n),e&&(this.#n[n]=void 0,this.#e[n]=void 0,this.#b.push(n)),this.#o===1?(this.#a=this.#s=0,this.#b.length=0):this.#a=this.#u[n],this.#r.delete(r),this.#o--,n}has(e,n={}){let{updateAgeOnHas:r=this.updateAgeOnHas,status:o}=n,s=this.#r.get(e);if(s!==void 0){let i=this.#e[s];if(this.#t(i)&&i.__staleWhileFetching===void 0)return!1;if(this.#m(s))o&&(o.has="stale",this.#v(o,s));else return r&&this.#D(s),o&&(o.has="hit",this.#v(o,s)),!0}else o&&(o.has="miss");return!1}peek(e,n={}){let{allowStale:r=this.allowStale}=n,o=this.#r.get(e);if(o===void 0||!r&&this.#m(o))return;let s=this.#e[o];return this.#t(s)?s.__staleWhileFetching:s}#T(e,n,r,o){let s=n===void 0?void 0:this.#e[n];if(this.#t(s))return s;let i=new to,{signal:a}=r;a?.addEventListener("abort",()=>i.abort(a.reason),{signal:i.signal});let c={signal:i.signal,options:r,context:o},u=(m,h=!1)=>{let{aborted:b}=i.signal,S=r.ignoreFetchAbort&&m!==void 0;if(r.status&&(b&&!h?(r.status.fetchAborted=!0,r.status.fetchError=i.signal.reason,S&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),b&&!S&&!h)return l(i.signal.reason);let A=p;return this.#e[n]===p&&(m===void 0?A.__staleWhileFetching?this.#e[n]=A.__staleWhileFetching:this.#E(e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,m,c.options))),m},d=m=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=m),l(m)),l=m=>{let{aborted:h}=i.signal,b=h&&r.allowStaleOnFetchAbort,S=b||r.allowStaleOnFetchRejection,A=S||r.noDeleteOnFetchRejection,_=p;if(this.#e[n]===p&&(!A||_.__staleWhileFetching===void 0?this.#E(e,"fetch"):b||(this.#e[n]=_.__staleWhileFetching)),S)return r.status&&_.__staleWhileFetching!==void 0&&(r.status.returnedStale=!0),_.__staleWhileFetching;if(_.__returned===_)throw m},f=(m,h)=>{let b=this.#O?.(e,s,c);b&&b instanceof Promise&&b.then(S=>m(S===void 0?void 0:S),h),i.signal.addEventListener("abort",()=>{(!r.ignoreFetchAbort||r.allowStaleOnFetchAbort)&&(m(void 0),r.allowStaleOnFetchAbort&&(m=S=>u(S,!0)))})};r.status&&(r.status.fetchDispatched=!0);let p=new Promise(f).then(u,d),y=Object.assign(p,{__abortController:i,__staleWhileFetching:s,__returned:void 0});return n===void 0?(this.set(e,y,{...c.options,status:void 0}),n=this.#r.get(e)):this.#e[n]=y,y}#t(e){if(!this.#k)return!1;let n=e;return!!n&&n instanceof Promise&&n.hasOwnProperty("__staleWhileFetching")&&n.__abortController instanceof to}async fetch(e,n={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,ttl:i=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:c=0,sizeCalculation:u=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:l=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:f=this.allowStaleOnFetchRejection,ignoreFetchAbort:p=this.ignoreFetchAbort,allowStaleOnFetchAbort:y=this.allowStaleOnFetchAbort,context:m,forceRefresh:h=!1,status:b,signal:S}=n;if(!this.#k)return b&&(b.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:s,status:b});let A={allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:s,ttl:i,noDisposeOnSet:a,size:c,sizeCalculation:u,noUpdateTTL:d,noDeleteOnFetchRejection:l,allowStaleOnFetchRejection:f,allowStaleOnFetchAbort:y,ignoreFetchAbort:p,status:b,signal:S},_=this.#r.get(e);if(_===void 0){b&&(b.fetch="miss");let w=this.#T(e,_,A,m);return w.__returned=w}else{let w=this.#e[_];if(this.#t(w)){let M=r&&w.__staleWhileFetching!==void 0;return b&&(b.fetch="inflight",M&&(b.returnedStale=!0)),M?w.__staleWhileFetching:w.__returned=w}let E=this.#m(_);if(!h&&!E)return b&&(b.fetch="hit"),this.#I(_),o&&this.#D(_),b&&this.#v(b,_),w;let k=this.#T(e,_,A,m),O=k.__staleWhileFetching!==void 0&&r;return b&&(b.fetch=E?"stale":"refresh",O&&E&&(b.returnedStale=!0)),O?k.__staleWhileFetching:k.__returned=k}}async forceFetch(e,n={}){let r=await this.fetch(e,n);if(r===void 0)throw new Error("fetch() returned undefined");return r}memo(e,n={}){let r=this.#C;if(!r)throw new Error("no memoMethod provided to constructor");let{context:o,forceRefresh:s,...i}=n,a=this.get(e,i);if(!s&&a!==void 0)return a;let c=r(e,a,{options:i,context:o});return this.set(e,c,i),c}get(e,n={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,status:i}=n,a=this.#r.get(e);if(a!==void 0){let c=this.#e[a],u=this.#t(c);return i&&this.#v(i,a),this.#m(a)?(i&&(i.get="stale"),u?(i&&r&&c.__staleWhileFetching!==void 0&&(i.returnedStale=!0),r?c.__staleWhileFetching:void 0):(s||this.#E(e,"expire"),i&&r&&(i.returnedStale=!0),r?c:void 0)):(i&&(i.get="hit"),u?c.__staleWhileFetching:(this.#I(a),o&&this.#D(a),c))}else i&&(i.get="miss")}#F(e,n){this.#d[n]=e,this.#u[e]=n}#I(e){e!==this.#s&&(e===this.#a?this.#a=this.#u[e]:this.#F(this.#d[e],this.#u[e]),this.#F(this.#s,e),this.#s=e)}delete(e){return this.#E(e,"delete")}#E(e,n){let r=!1;if(this.#o!==0){let o=this.#r.get(e);if(o!==void 0)if(r=!0,this.#o===1)this.#Z(n);else{this.#R(o);let s=this.#e[o];if(this.#t(s)?s.__abortController.abort(new Error("deleted")):(this.#x||this.#l)&&(this.#x&&this.#h?.(s,e,n),this.#l&&this.#i?.push([s,e,n])),this.#r.delete(e),this.#n[o]=void 0,this.#e[o]=void 0,o===this.#s)this.#s=this.#d[o];else if(o===this.#a)this.#a=this.#u[o];else{let i=this.#d[o];this.#u[i]=this.#u[o];let a=this.#u[o];this.#d[a]=this.#d[o]}this.#o--,this.#b.push(o)}}if(this.#l&&this.#i?.length){let o=this.#i,s;for(;s=o?.shift();)this.#y?.(...s)}return r}clear(){return this.#Z("delete")}#Z(e){for(let n of this.#A({allowStale:!0})){let r=this.#e[n];if(this.#t(r))r.__abortController.abort(new Error("deleted"));else{let o=this.#n[n];this.#x&&this.#h?.(r,o,e),this.#l&&this.#i?.push([r,o,e])}}if(this.#r.clear(),this.#e.fill(void 0),this.#n.fill(void 0),this.#p&&this.#_&&(this.#p.fill(0),this.#_.fill(0)),this.#w&&this.#w.fill(0),this.#a=0,this.#s=0,this.#b.length=0,this.#g=0,this.#o=0,this.#l&&this.#i){let n=this.#i,r;for(;r=n?.shift();)this.#y?.(...r)}}};var Ps=({maximumBytes:t=R.hydratedTotalBytes*4}={})=>{if(Number.isSafeInteger(t)===!1||t<=0)throw new TypeError("Document source cache byte limit must be positive");return new Ht({maxSize:t,sizeCalculation:e=>Math.max(1,e.bytes.byteLength)})},Zn=class extends Error{code="CONTENT_LIMIT_EXCEEDED";documentId;contentByteLimit;constructor({message:e,documentId:n,contentByteLimit:r,cause:o}){super(e,{cause:o}),this.name="CachedDocumentLoaderError",this.documentId=n,this.contentByteLimit=r}},no=({contentRef:t,revision:e,format:n})=>de([t,e,n??null]),fh=t=>{if(typeof t!="object"||t===null)return!1;let e=t;return(e.format==="json"||e.format==="markdown")&&typeof e.revision=="string"&&e.revision.length>0&&e.bytes instanceof Uint8Array},Sf=t=>Object.freeze({format:t.format,revision:t.revision,source:t.bytes}),Af=({load:t,cache:e,maximumBytes:n=R.hydratedFileBytes,onEvent:r})=>{let o=new Map;return async(s,i)=>{let a=no(s),c=o.get(a)??new Map;o.set(a,c);let u=c.get(i.signal);if(u!==void 0)return await u;let d=(async()=>{let l;try{l=await e.get(a)}catch(m){se(r,{type:"document-cache-read-failed",documentId:s.id,revision:s.revision,errorCode:Jt(m)})}if(fh(l)&&l.revision===s.revision&&l.bytes.byteLength<=n&&(s.format===void 0||l.format===s.format))return se(r,{type:"document-cache-hit",documentId:s.id,revision:s.revision}),Sf(l);se(r,{type:"document-cache-miss",documentId:s.id,revision:s.revision});let f=qt({node:s,source:await t(s,i)}),p;try{p=await Te(f.source,n)}catch(m){throw m instanceof re?new Zn({message:`Document ${s.id} exceeds the cache byte limit`,documentId:s.id,contentByteLimit:n,cause:m}):m}let y=Object.freeze({format:f.format,revision:f.revision,bytes:p});try{await e.set(a,y),se(r,{type:"document-cache-stored",documentId:s.id,revision:s.revision})}catch(m){se(r,{type:"document-cache-write-failed",documentId:s.id,revision:s.revision,errorCode:Jt(m)})}return Sf(y)})();c.set(i.signal,d);try{return await d}finally{c.delete(i.signal),c.size===0&&o.delete(a)}}};var Ye=class extends Error{code;documentId;referenceId;constructor({code:e,message:n,documentId:r,referenceId:o,cause:s}){super(n,{cause:s}),this.name="DocumentGraphResolutionError",this.code=e,this.documentId=r,this.referenceId=o}},ro=t=>{if(t?.aborted)throw new Ye({code:"REQUEST_CANCELLED",message:"Document graph resolution was cancelled",cause:t.reason})},Ef=async({graph:t,rootIds:e,concurrency:n,signal:r,load:o,select:s,assemble:i})=>{ro(r);let a=lr({graph:t,rootIds:e}),c=new Map(a.map(p=>[p.id,p])),u=new Map,d=new Map;for(let p of a){let y=d.get(p.contentRef);y===void 0?d.set(p.contentRef,{representative:p,nodes:[p]}):y.nodes.push(p)}await pr([...d.values()],n,async p=>{ro(r);let y=p.representative;try{let m=await o(y,{signal:r});for(let h of p.nodes)u.set(h.id,m)}catch(m){throw r?.aborted&&ro(r),new Ye({code:"DOCUMENT_LOAD_FAILED",message:`Document ${y.id} could not be loaded`,documentId:y.id,cause:m})}});let l=Tt(t.edges),f=new Map;for(let p of a){ro(r);let y=new Map;for(let h of l.get(p.id)??[]){let b=c.get(h.reference.documentId);if(b===void 0||f.has(h.reference.documentId)===!1)throw new Ye({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${p.id} dependency ${h.reference.documentId} is unavailable`,documentId:p.id,referenceId:h.referenceId});let S=f.get(h.reference.documentId),A;if(s===void 0){if(h.reference.representation.type!=="document")throw new Ye({code:"REPRESENTATION_SELECTOR_REQUIRED",message:`Document ${p.id} reference ${h.referenceId} requires a representation selector`,documentId:p.id,referenceId:h.referenceId});A=S}else try{A=await s({reference:h.reference,value:S,sourceNode:p,targetNode:b})}catch(_){throw new Ye({code:"DOCUMENT_SELECTION_FAILED",message:`Document ${p.id} reference ${h.referenceId} could not be selected`,documentId:p.id,referenceId:h.referenceId,cause:_})}y.set(h.referenceId,A)}if(u.has(p.id)===!1)throw new Ye({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${p.id} source is unavailable`,documentId:p.id});let m=u.get(p.id);try{f.set(p.id,await i({node:p,source:m,references:y}))}catch(h){throw new Ye({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${p.id} could not be assembled`,documentId:p.id,cause:h})}}return Object.freeze({roots:Object.freeze(e.map(p=>f.get(p))),values:f})};var xt=class extends Error{code;documentId;documentCount;documentLimit;contentByteLimit;totalBytes;totalByteLimit;constructor({code:e,message:n,documentId:r,documentCount:o,documentLimit:s,contentByteLimit:i,totalBytes:a,totalByteLimit:c,cause:u}){super(n,{cause:u}),this.name="DocumentResolutionLimitError",this.code=e,this.documentId=r,this.documentCount=o,this.documentLimit=s,this.contentByteLimit=i,this.totalBytes=a,this.totalByteLimit=c}},dh=(t,e)=>{let n=0,r=[],o=async()=>{if(e?.throwIfAborted(),n<t){n+=1;return}await new Promise((i,a)=>{let c,u=()=>{let d=r.indexOf(c);d!==-1&&r.splice(d,1);try{e?.throwIfAborted()}catch(l){a(l)}};c={start:()=>{e?.removeEventListener("abort",u),i()}},r.push(c),e?.addEventListener("abort",u,{once:!0})})},s=()=>{let i=r.shift();if(i===void 0){n-=1;return}i.start()};return async i=>{await o();try{return await i()}finally{s()}}},ph=async({graph:t,rootIds:e,concurrency:n,maximumBytes:r,maximumTotalBytes:o=R.hydratedTotalBytes,maximumDocuments:s=R.hydratedFileCount,signal:i,onEvent:a,allowUnresolvedReferences:c=!1,load:u})=>{let d=lr({graph:t,rootIds:e}).length,l={rootCount:e.length,documentCount:d};se(a,{type:"resolution-started",...l});try{if(d>s)throw new xt({code:"DOCUMENT_COUNT_EXCEEDED",message:"Document graph resolution exceeds the document limit",documentCount:d,documentLimit:s});let f=0,p=Promise.resolve(),y=await Ef({graph:t,rootIds:e,concurrency:n,signal:i,load:async(m,h)=>{let b=p,S=()=>{};p=new Promise(_=>{S=_});let A;try{A={status:"fulfilled",value:await u(m,h)}}catch(_){A={status:"rejected",reason:_}}await b;try{if(A.status==="rejected")throw A.reason;if(A.value.byteLength>r)throw new xt({code:"CONTENT_LIMIT_EXCEEDED",message:`Document ${m.id} exceeds the byte limit`,documentId:m.id,contentByteLimit:r,cause:new re});let _=f+A.value.byteLength;if(_>o)throw new xt({code:"TOTAL_BYTES_EXCEEDED",message:"Document graph resolution exceeds the total byte limit",documentId:m.id,totalBytes:_,totalByteLimit:o});return f=_,await A.value.parse()}finally{S()}},select:({reference:m,value:h})=>hf({document:h,representation:m.representation}),assemble:({source:m,references:h})=>mf({document:m,references:h,allowUnresolvedReferences:c})});return se(a,{type:"resolution-completed",...l}),y}catch(f){throw se(a,{type:"resolution-failed",...l,errorCode:Jt(f)}),f}},vf=({load:t,concurrency:e,signal:n,maximumDocumentBytes:r=R.hydratedFileBytes,maximumCacheBytes:o=R.hydratedTotalBytes*4})=>{if(Number.isSafeInteger(e)===!1||e<=0)throw new TypeError("Document resolution concurrency must be positive");if(Number.isSafeInteger(r)===!1||r<=0)throw new TypeError("Document resolution byte limit must be positive");if(Number.isSafeInteger(o)===!1||o<=0)throw new TypeError("Document resolution cache byte limit must be positive");let s=new Ht({maxSize:o,sizeCalculation:({byteLength:f})=>Math.max(1,f)}),i=new Map,a=dh(e,n),c=f=>{if(f!==void 0&&f!==n)throw new TypeError("Document resolution session signal does not match");n?.throwIfAborted()},u=async f=>(c(),n===void 0?await f:await new Promise((p,y)=>{let m=()=>n.removeEventListener("abort",h),h=()=>{m();try{n.throwIfAborted()}catch(b){y(b)}};n.addEventListener("abort",h,{once:!0}),f.then(b=>{m(),p(b)},b=>{m(),y(b)}),n.aborted&&h()})),d=async(f,p)=>{c(p.signal);let y=no(f),m=s.get(y);if(m!==void 0)return m;let h=i.get(y);if(h!==void 0)return await u(h);let b=a(async()=>{c(p.signal);let S=qt({node:f,source:await t(f,{signal:n})});c(p.signal);let A=await Jo(S.source,r+1);c(p.signal);let _,w=Object.freeze({format:S.format,revision:S.revision,bytes:A,byteLength:A.byteLength,parse:()=>(_??=pf({format:S.format,source:A,maximumBytes:r}),_)});return w.byteLength<=o&&s.set(y,w),w});i.set(y,b);try{return await u(b)}finally{i.delete(y)}};return Object.freeze({getCached:f=>{c();let p=s.get(no(f));if(!(p===void 0||p.byteLength>r))return Object.freeze({format:p.format,revision:p.revision,source:p.bytes.slice()})},resolve:async f=>await ph({...f,concurrency:e,maximumBytes:r,signal:n,load:d})})};var kf=t=>{if(t.output.mode==="all")return"all";let e=[];for(let{field:n}of hn(t.where))n[0]==="properties"&&e.push(n);for(let{field:n}of t.sort)n[0]==="properties"&&e.push(n);if(t.output.mode==="fields")for(let n of t.output.fields)n[0]==="properties"&&e.push(n);return e},Df=t=>{let e;if(t==="#frontmatter")e="";else if(t.startsWith("#frontmatter/"))e=t.slice(12);else if(t==="#")e="";else if(t.startsWith("#/"))e=t.slice(1);else return;try{return["properties",...ul(e)]}catch{return}},Rf=(t,e)=>{let n=Math.min(t.length,e.length);for(let r=0;r<n;r+=1)if(t[r]!==e[r])return!1;return!0},If=({queryPaths:t,referenceId:e})=>{let n=Df(e);return n!==void 0&&(t==="all"||t.some(r=>Rf(r,n)))},Of=({graph:t,sourceId:e,field:n})=>n[0]!=="properties"?!1:t.edges.some(r=>{if(r.sourceId!==e)return!1;let o=Df(r.referenceId);return o!==void 0&&Rf(n,o)}),Cf=({graph:t,query:e})=>{let n=kf(e),r=new Set;for(let o of t.edges)If({queryPaths:n,referenceId:o.referenceId})&&r.add(o.sourceId);return[...r]},Nf=({graph:t,query:e,rootIds:n})=>{let r=kf(e),o=new Set(n),s=new Map(t.nodes.map(l=>[l.id,l])),i=Tt(t.edges),a=new Set(n),c=new Set,u=new Set,d=l=>{if(a.add(l),!u.has(l)){u.add(l);for(let f of i.get(l)??[])c.add(f),d(f.reference.documentId)}};for(let l of t.edges)o.has(l.sourceId)&&If({queryPaths:r,referenceId:l.referenceId})&&(c.add(l),d(l.reference.documentId));return gn({nodes:[...a].map(l=>{let f=s.get(l);if(f===void 0)throw new Error(`Document graph query root ${l} does not exist`);return f}),edges:[...c]})};var $f=({artifact:t})=>{if(t.documentGraph===void 0)return;let e=new Map(t.documents.map(s=>[s._id,s])),n=new Map(t.documentGraph.nodes.map(s=>[s.id,s])),r=new Map;for(let{sourceId:s}of t.documentGraph.edges){if(n.has(s))continue;let i=e.get(s);if(i?.properties===void 0)throw new Error(`Runtime document graph source ${s} is unavailable`);r.set(s,i),n.set(s,{id:s,revision:s,contentRef:s,format:"json"})}return{graph:gn({nodes:[...n.values()],edges:t.documentGraph.edges.map(({sourceId:s,referenceId:i,documentId:a,representation:c})=>{let u=n.get(a);if(u===void 0)throw new Error(`Runtime document graph target ${a} is unavailable`);return{sourceId:s,referenceId:i,reference:{documentId:a,revision:u.revision,representation:c}}})}),inlineDocuments:r}};var mh=(t,e)=>{if(e===void 0||e.length===0)return t;let n=new URL("https://content.webstudio.invalid/__assets__/"),r=new URL(t,n),o=new URL(e,n);for(let[a,c]of o.searchParams)r.searchParams.append(a,c);if(o.hash!==""&&(r.hash=o.hash),URL.canParse(t))return r.href;if(t.startsWith("//"))return`//${r.host}${r.pathname}${r.search}${r.hash}`;if(t.startsWith("/"))return`${r.pathname}${r.search}${r.hash}`;let s=n.pathname;return`${r.pathname.startsWith(s)?r.pathname.slice(s.length):r.pathname}${r.search}${r.hash}`},Tf=({markdown:t,references:e,assetUrls:n})=>{let r=t.length,o=t;for(let s of[...e].sort((i,a)=>a.start-i.start)){if(s.start<0||s.end<=s.start||s.end>t.length||s.end>r)throw new Error("Markdown asset reference range is invalid");r=s.start;let i=n[s.assetId];if(i===void 0)continue;let a=mh(i,s.suffix);o=`${o.slice(0,s.start)}${a}${o.slice(s.end)}`}return o};var ie=class extends Error{code;details;constructor({code:e,message:n,details:r}){super(n),this.name="AssetResourceHydrationError",this.code=e,this.details=r}},hh=t=>{if(t===null)return[];let e=Array.isArray(t)?t:[t],n=new Map;for(let r of e){if(typeof r!="object"||r===null||!("_id"in r)||typeof r._id!="string"||!("revision"in r)||typeof r.revision!="string"||!("contentRef"in r)||typeof r.contentRef!="string")throw new ie({code:"CONTENT_IDENTITY_REQUIRED",message:"Hydrated query results must retain _id, revision, and contentRef"});let o=n.get(r._id);if(o!==void 0&&(o.revision!==r.revision||o.contentRef!==r.contentRef))throw new ie({code:"CONTENT_IDENTITY_REQUIRED",message:"A selected asset ID has conflicting content identity",details:{assetId:r._id}});n.set(r._id,{_id:r._id,revision:r.revision,contentRef:r.contentRef})}return Array.from(n.values())},yh=t=>typeof t.mimeType=="string"&&(t.mimeType.startsWith("text/")||["application/json","application/javascript","application/xml","image/svg+xml"].includes(t.mimeType)),gh=async({read:t,contentRef:e,range:n,maximumBytes:r})=>{if(r===0)return new Uint8Array;let o=await t(e,n);try{return await Te(o.data,r)}catch(s){throw s instanceof re?new ie({code:"CONTENT_LIMIT_EXCEEDED",message:"Asset storage returned more content than requested"}):s}},bh=t=>{try{return fe(t)}catch{throw new ie({code:"CONTENT_DECODING_FAILED",message:"Selected asset content is not valid UTF-8"})}},wh=(t,e)=>{if(e.mode==="range")return Math.max(0,Math.min(e.length,t.size-e.offset));let n=e.maxBytes??R.hydratedFileBytes;if(t.size>n)throw new ie({code:"CONTENT_LIMIT_EXCEEDED",message:"Selected asset exceeds the per-file content limit",details:{assetId:t._id,assetBytes:t.size,fileByteLimit:n}});return t.size},zf=async({result:t,documents:e,options:n,read:r,assetReferences:o,assetUrls:s})=>{if(n.mode==="none")return{content:{},hydratedFileCount:0,hydratedBytes:0};let i=hh(t);if(i.length>R.hydratedFileCount)throw new ie({code:"CONTENT_LIMIT_EXCEEDED",message:"Too many selected assets requested content hydration",details:{fileCount:i.length,fileCountLimit:R.hydratedFileCount}});let a=new Map(e.map(l=>[l._id,l])),c=i.map(l=>{let f=a.get(l._id);if(f===void 0||f.revision!==l.revision||f.contentRef!==l.contentRef||typeof f.size!="number"||typeof f.mimeType!="string")throw new ie({code:"CONTENT_IDENTITY_REQUIRED",message:"Selected asset content identity is stale or unavailable",details:{assetId:l._id}});let p={...f,size:f.size,mimeType:f.mimeType};if(yh(p)===!1)throw new ie({code:"CONTENT_NOT_TEXT",message:"Selected binary asset cannot be embedded as text",details:{assetId:l._id,mimeType:p.mimeType}});return{identity:l,document:p,readLength:wh(p,n)}}),u=c.reduce((l,f)=>l+f.readLength,0);if(u>R.hydratedTotalBytes)throw new ie({code:"CONTENT_LIMIT_EXCEEDED",message:"Selected assets exceed the total hydrated-content limit",details:{totalReadBytes:u,totalByteLimit:R.hydratedTotalBytes}});let d=await pr(c,R.concurrentContentReads,async l=>{let f=n.mode==="range"?{offset:n.offset,length:l.readLength}:l.readLength===0?void 0:{offset:0,length:l.readLength},p=await gh({read:r,contentRef:l.identity.contentRef,range:f,maximumBytes:l.readLength});if(p.byteLength!==l.readLength)throw new ie({code:"CONTENT_IDENTITY_REQUIRED",message:"Selected asset bytes do not match canonical metadata",details:{assetId:l.identity._id}});let y;if(n.mode==="markdown-body-ref")try{y=(await Wr(p,l.readLength||1)).body;let h=o?.[l.identity.contentRef];h!==void 0&&s!==void 0&&(y=Tf({markdown:y,references:h,assetUrls:s}))}catch{throw new ie({code:"CONTENT_DECODING_FAILED",message:"Selected Markdown body could not be decoded",details:{assetId:l.identity._id}})}else y=bh(p);let m=$e(y);return{id:l.identity._id,returnedBytes:m,content:{...l.identity,encoding:"utf-8",text:y,...n.mode==="range"?{range:{offset:n.offset,length:p.byteLength,total:l.document.size}}:{}}}});return{content:Object.fromEntries(d.map(({id:l,content:f})=>[l,f])),hydratedFileCount:c.length,hydratedBytes:d.reduce((l,{returnedBytes:f})=>l+f,0)}};var Lv=v().datetime({offset:!0}).transform(t=>new Date(t).toISOString());var _h=/^[A-Za-z_][A-Za-z0-9_]*$/,Pf=(t,e)=>_h.test(e)?`${t}.${e}`:`${t}[${JSON.stringify(e)}]`;var Lf=({document:t,includes:e})=>{let n={};for(let r of tl){let o=t[r];o!==void 0&&e(r)&&(n[r]=o)}return n},Mf=({source:t,target:e,path:n})=>{let[r,...o]=n;if(r===void 0||Object.hasOwn(t,r)===!1)return;let s=t[r];if(o.length===0){Object.defineProperty(e,r,{value:s,enumerable:!0,configurable:!0,writable:!0});return}if(typeof s!="object"||s===null||Array.isArray(s))return;let i={};if(Mf({source:s,target:i,path:o}),Object.keys(i).length===0)return;let a=e[r];Object.defineProperty(e,r,{value:{...typeof a=="object"&&a!==null&&Array.isArray(a)===!1?a:{},...i},enumerable:!0,configurable:!0,writable:!0})},Ff=({properties:t,fields:e})=>{let n={};for(let r of e)r[0]==="properties"&&Mf({source:t,target:n,path:r.slice(1)});return n};var jn=t=>Object.fromEntries(Object.entries(t??{}).map(([e,n])=>[e,n.url]));var xh=(t,e)=>{if(e===void 0)return t;let n="https://content.webstudio.invalid",r=new URL(t,`${n}/`),o=new URL(e,`${n}/`);for(let[s,i]of o.searchParams)r.searchParams.append(s,i);return o.hash!==""&&(r.hash=o.hash),t.startsWith("//")?`//${r.host}${r.pathname}${r.search}${r.hash}`:t.startsWith("/")?`${r.pathname}${r.search}${r.hash}`:r.href},Ls=({value:t,path:e,replacement:n})=>{let[r,...o]=e;if(r===void 0)return n;if(typeof t!="object"||t===null||Object.hasOwn(t,r)===!1)return t;if(Array.isArray(t)){if(typeof r!="number")return t;let s=[...t];return s[r]=Ls({value:t[r],path:o,replacement:n}),s}return typeof r!="string"?t:{...t,[r]:Ls({value:t[r],path:o,replacement:n})}},Xt=({value:t,references:e,assetUrls:n})=>{let r=t;for(let o of e??[]){let s=n[o.assetId];s!==void 0&&(r=Ls({value:r,path:o.path,replacement:xh(s,o.suffix)}))}return r};var Ce=class extends Error{constructor(e,n){super(e,n),this.name="AssetQueryExecutionError"}},Bn=class extends Ce{code="MULTIPLE_RESULTS";matchedCount;constructor(e){super(`Expected at most one asset, but the query matched ${e}.`),this.matchedCount=e,this.name="AssetQueryMultipleResultsError"}},tn=class extends Error{constructor(){super("The requested asset index revision is stale"),this.name="AssetIndexRevisionError"}},Zf=t=>{if(t[0]!=="properties")return t[0];let e="properties";for(let n of t.slice(1))e=Pf(e,n);return e},jf=({filter:t,fieldTypes:e})=>ol(e).includes(t.operator),Bf=(t,e)=>t!==void 0&&Object.hasOwn(t.fields,e)?t.fields[e]:void 0,Sh=({query:t,catalog:e})=>{let n=st.parse(t),r=new Map,o=[];for(let s of hn(n.where)){let i=Zf(s.field);if(r.set(i,s.field),s.field[0]==="properties"){let a=Bf(e,i);e!==void 0&&a===void 0?o.push(`Asset field ${i} is not currently observed`):a!==void 0&&jf({filter:s,fieldTypes:a.types})===!1&&o.push(`Operator ${s.operator} is not compatible with the currently observed types of ${i}`)}else if(jf({filter:s,fieldTypes:es[s.field[0]]})===!1)throw new Ce(`Operator ${s.operator} is incompatible with ${i}`)}for(let s of n.sort){let i=Zf(s.field);if(r.set(i,s.field),s.field[0]==="properties"){let a=Bf(e,i);e!==void 0&&a===void 0?o.push(`Asset field ${i} is not currently observed`):a!==void 0&&a.types.some(c=>c==="object"||c==="array")&&o.push(`Asset field ${i} currently includes structured values that use deterministic JSON sort order`)}}return{query:n,referencedFieldPaths:[...r.values()],warnings:[...new Set(o)]}},Fs=(t,e,n)=>{let r=e[0]==="id"?t._id:dr(e[0])?n?.[e[0]]:t[e[0]];for(let o of e.slice(1)){if(typeof r!="object"||r===null||Object.hasOwn(r,o)===!1)return;r=r[o]}return r},Ah=t=>typeof t=="string"||Array.isArray(t)?t.length===0:typeof t=="object"&&t!==null&&Object.keys(t).length===0,Eh=(t,e)=>{if(typeof t=="number"&&typeof e=="number")return t-e;if(typeof t=="string"&&typeof e=="string")return ze(t,e)},Zs=(t,e,n)=>{let r=Fs(t,e.field,n);if(e.operator==="exists")return r!=null===e.value;if(e.operator==="isEmpty")return Ah(r)===e.value;if(e.operator==="eq")return yn(r,e.value);if(e.operator==="ne")return yn(r,e.value)===!1;if(e.operator==="in")return e.value.some(s=>yn(r,s));if(e.operator==="contains")return typeof r=="string"&&typeof e.value=="string"?r.includes(e.value):Array.isArray(r)&&r.some(s=>yn(s,e.value));if(e.operator==="startsWith")return typeof r=="string"&&typeof e.value=="string"&&r.startsWith(e.value);if(e.operator==="endsWith")return typeof r=="string"&&typeof e.value=="string"&&r.endsWith(e.value);let o=Eh(r,e.value);return o===void 0?!1:e.operator==="gt"?o>0:e.operator==="gte"?o>=0:e.operator==="lt"?o<0:o<=0},vh=({document:t,where:e,runtimeAsset:n,filterKeys:r,filterResults:o})=>Ot(e,s=>{let i=r.get(s)??de(s),a=o.get(i);if(a!==void 0)return a;let c=Zs(t,s,n);return o.set(i,c),c})===!0,kh=({document:t,content:e})=>e.mode!=="markdown-body-ref"||t.mimeType==="text/markdown"||t.extension==="md",Dh=(t,e)=>{let n=t==null,r=e==null;return n||r?n===r?0:n?1:-1:typeof t=="number"&&typeof e=="number"?t-e:(typeof t=="string"||typeof t=="boolean")&&(typeof e=="string"||typeof e=="boolean")?ze(String(t),String(e)):ze(de(t),de(e))},Rh=({left:t,right:e,sort:n,runtimeAssets:r})=>{for(let o of n){let s=Dh(Fs(t,o.field,r?.[t._id]),Fs(e,o.field,r?.[e._id]));if(s!==0)return o.direction==="asc"?s:-s}return ze(t._id,e._id)};var Ih=(t,e)=>{if(t.properties===void 0)return;if(e.mode==="all")return Object.keys(t.properties).length===0?void 0:t.properties;if(e.mode!=="fields"||e.fields.some(r=>r[0]==="properties")===!1)return;let n=Ff({properties:t.properties,fields:e.fields});return Object.keys(n).length===0?void 0:n},en=(t,e)=>t.includeMetadata&&nl(e)||t.mode==="fields"&&t.fields.some(n=>n.length===1&&n[0]===e),Oh=t=>t.mode==="all"||t.mode==="fields"&&t.fields.some(e=>e.length===1&&e[0]==="excerpt"),Ch=(t,e,n)=>{if(en(e,"url")&&n===void 0)throw new Error(`Asset URL is unavailable for ${t._id}`);let r=Ih(t,e),o=n?.width!==void 0&&n.height!==void 0;return{...n!==void 0&&en(e,"url")?{url:n.url}:{},...o&&en(e,"width")?{width:n.width}:{},...o&&en(e,"height")?{height:n.height}:{},...Lf({document:t,includes:s=>en(e,s)}),...r===void 0?{}:{properties:r},...t.excerpt===void 0||Oh(e)===!1?{}:{excerpt:t.excerpt},...t.metadataError===void 0||e.includeMetadata===!1?{}:{metadataError:t.metadataError}}},js=t=>{if($e(de(t))>R.resultBytes)throw new Ce("Asset query result exceeds the byte limit")},oo=(t,e,n)=>{t[e]={status:"rejected",reason:n}},Nh=({inputs:t,catalog:e,results:n})=>{let r=new Map,o=new Map,s=[];for(let[i,a]of t.entries()){let c;try{c=Sh({query:a,catalog:e}).query}catch(l){oo(n,i,l);continue}for(let l of hn(c.where))o.set(l,de(l));let u=de(c.sort),d=r.get(u);d===void 0&&(d={sort:c.sort,documents:new Set,sorted:[]},r.set(u,d)),s.push({index:i,query:c,matches:new Map,sortGroup:d})}return{filterKeys:o,preparedQueries:s,sortGroups:r}},Uf=({preparedQueries:t,results:e,createReason:n})=>{for(let{index:r}of t)oo(e,r,n())},Ms=t=>t.map(e=>{if(e===void 0)throw new Error("Asset query result was not settled");return e}),$h=({preparedQueries:t,documents:e,filterKeys:n,sortGroups:r,results:o,runtimeAssets:s})=>{for(let i of e){let a=s?.[i._id],c=new Map;for(let u of t){if(o[u.index]!==void 0)continue;let{query:d}=u;try{if(kh({document:i,content:d.content})===!1||vh({document:i,where:d.where,runtimeAsset:a,filterKeys:n,filterResults:c})===!1)continue;let l=Ch(i,d.output,a);if(d.content.mode==="none"&&Object.keys(l).length===0&&en(d.output,"id")===!1)continue;let f={document:i,item:{id:i._id,...l}};u.matches.set(i,f),u.sortGroup.documents.add(i)}catch(l){oo(o,u.index,l)}}}for(let i of r.values())i.sorted=[...i.documents].sort((a,c)=>Rh({left:a,right:c,sort:i.sort,runtimeAssets:s}))},Th=async({preparedQueries:t,results:e,read:n,assetReferences:r,assetUrls:o})=>{await Promise.all(t.map(async s=>{if(e[s.index]!==void 0)return;let{query:i}=s;try{let a=s.sortGroup.sorted.flatMap(p=>{let y=s.matches.get(p);return y===void 0?[]:[y]}),c=i.result??"many";if(c==="one"&&a.length>1)throw new Bn(a.length);let u=c==="many"?a.slice(i.offset,i.offset+i.limit):c==="last"?a.slice(-1):a.slice(0,1),d=u.map(({document:p})=>p),l=u.map(({item:p})=>p);if(i.content.mode!=="none"){let p=i.content;if(n===void 0)throw new Ce("Asset content reader is unavailable");let y=await zf({result:d,documents:d,options:p,read:n,assetReferences:r,assetUrls:r===void 0?void 0:o});l=d.map((m,h)=>{let b=y.content[m._id];if(b===void 0)throw new Ce("Selected asset content could not be read");return{...l[h],content:{encoding:b.encoding,text:b.text,...b.range===void 0?{}:{range:b.range}}}})}let f=c==="many"?{items:l,totalCount:a.length,hasMore:i.offset+u.length<a.length}:{item:l[0]??null,totalCount:a.length};js(f),e[s.index]={status:"fulfilled",value:f}}catch(a){oo(e,s.index,a)}}))},Qf=async({queries:t,catalog:e,documents:n,read:r,runtimeAssets:o,assetReferences:s,assetValueReferences:i})=>{let a=Array.from({length:t.length}),{filterKeys:c,preparedQueries:u,sortGroups:d}=Nh({inputs:t,catalog:e,results:a});if(n.length>R.candidateDocuments)return Uf({preparedQueries:u,results:a,createReason:()=>new Ce("Asset query document limit was exceeded")}),Ms(a);let l=jn(o),f;try{f=n.map(p=>Xt({value:p,references:i?.[p._id],assetUrls:l}))}catch(p){return Uf({preparedQueries:u,results:a,createReason:()=>p}),Ms(a)}return $h({preparedQueries:u,documents:f,filterKeys:c,sortGroups:d,results:a,runtimeAssets:o}),await Th({preparedQueries:u,results:a,read:r,assetReferences:s,assetUrls:l}),Ms(a)};var zh=async t=>await Qu(de(st.parse(t)));var Ph=({item:t,field:e,value:n})=>{let r=t;for(let[o,s]of e.entries()){if(o===e.length-1){Object.defineProperty(r,s,{value:n,enumerable:!0,configurable:!0,writable:!0});return}let i=Object.hasOwn(r,s)?r[s]:void 0;if(typeof i=="object"&&i!==null){r=i;continue}let a={};Object.defineProperty(r,s,{value:a,enumerable:!0,configurable:!0,writable:!0}),r=a}},Lh=t=>ts.parse({items:t.rows.map(e=>{let n={};for(let[r,o]of t.fields.entries())Ph({item:n,field:o,value:e[r]});return n}),totalCount:t.totalCount,hasMore:t.hasMore}),Gf=async({queries:t,query:e,assetValueReferences:n,assetUrls:r={}})=>{if(t===void 0)return;let o=t[await zh(st.parse(e))];if(o===void 0)return;let s=Lh(o),i={...s,items:s.items.map(a=>Xt({value:a,references:n?.[a.id],assetUrls:r}))};return js(i),i};var Mh=(t,e)=>e===void 0?Nt(t):{async*[Symbol.asyncIterator](){let n=0,r=0;for await(let o of Nt(t)){if(r===e.length)return;if(n+o.byteLength<=e.offset){n+=o.byteLength;continue}let s=Math.max(0,e.offset-n),i=Math.min(o.byteLength-s,e.length-r);i>0&&(yield o.subarray(s,s+i),r+=i),n+=o.byteLength}}},Fh=({graph:t,load:e,getCached:n,readFallback:r,signal:o})=>{let s=new Map(t.nodes.map(i=>[i.contentRef,i]));return async(i,a)=>{let c=s.get(i);if(c===void 0){if(r!==void 0)return await r(i,a);throw new Error(`Document content reference ${i} is unavailable`)}let u=qt({node:c,source:n(c)??await e(c,{signal:o})});return{data:Mh(u.source,a),...a===void 0?{}:{contentLength:a.length}}}},Zh=({artifact:t,revision:e,catalog:n,documentGraph:r,inlineDocuments:o,readContent:s})=>{let i=new Map(t.documents.map(w=>[w._id,w])),a=w=>{if(w.indexRevision!==void 0&&w.indexRevision!==e)throw new tn},c=w=>async(E,k)=>{let x=t.contents?.[E];if(x===void 0){let B=w??s;if(B===void 0)throw new Error("Content is not embedded in this database");return await B(E,k)}let O=Ct(x),M=k===void 0?O:O.slice(k.offset,k.offset+k.length);return{data:async function*(){yield M}(),contentLength:M.byteLength}},u=w=>{if(w.status==="rejected")throw w.reason;return w.value},d=async({requests:w,queryContentReader:E,runtimeAssets:k,documents:x=t.documents})=>await Qf({queries:w.map(({query:O})=>O),catalog:n,documents:x,read:c(E),runtimeAssets:k,assetReferences:t.assetReferences,assetValueReferences:t.assetValueReferences}),l=async({request:w,...E})=>u((await d({...E,requests:[w]}))[0]),f=async({requests:w,queryContentReader:E,runtimeAssets:k})=>{let x=Array.from({length:w.length}),O=jn(k),M=[];for(let[B,$]of w.entries()){try{a($);let ae=await Gf({queries:t.queries,query:$.query,assetValueReferences:t.assetValueReferences,assetUrls:O});if(ae!==void 0){x[B]={status:"fulfilled",value:ae};continue}}catch(ae){x[B]={status:"rejected",reason:ae};continue}M.push(B)}if(M.length>0){let B=await d({requests:M.map($=>w[$]),queryContentReader:E,runtimeAssets:k});for(let[$,ae]of M.entries())x[ae]=B[$]}return x.map(B=>{if(B===void 0)throw new Error("Content database query was not settled");return B})},p=async(w,E,k)=>u((await f({requests:[w],queryContentReader:E,runtimeAssets:k}))[0]),y=async(...w)=>await p(...w),m=w=>async(E,k)=>{let x=o?.get(E.id);return x!==void 0?{format:"json",revision:E.revision,source:JSON.stringify(x.properties)}:await w(E,k)},h=({graph:w,query:E,runtimeAssets:k})=>{let x=jn(k);return Cf({graph:w,query:E}).filter(O=>{let M=i.get(O),B=M===void 0?void 0:Xt({value:M,references:t.assetValueReferences?.[O],assetUrls:x});return B===void 0?!1:Ot(E.where,$=>{if(!Of({graph:w,sourceId:O,field:$.field}))return Zs(B,$,k?.[O])})!==!1})},b=({rootIds:w,roots:E})=>{let k=new Map(w.flatMap((x,O)=>{let M=df(E[O]);return M===void 0?[]:[[x,M]]}));return t.documents.map(x=>{let O=k.get(x._id);return O===void 0?x:Xo.parse({...x,properties:O})})},S=async({request:w,graph:E,resolutionSession:k,contentReader:x,runtimeAssets:O,onEvent:M})=>{a(w);let B=st.parse(w.query),$=h({graph:E,query:B,runtimeAssets:O});if($.length===0)return await p(w,x,O);let ae=Nf({graph:E,query:B,rootIds:$});se(M,{type:"roots-selected",rootCount:$.length});let io=await k.resolve({graph:ae,rootIds:$,onEvent:M,allowUnresolvedReferences:!0}),ao=b({rootIds:$,roots:io.roots});return await l({request:w,queryContentReader:x,runtimeAssets:O,documents:ao})},A=async({requests:w,load:E,resolutionSession:k,readContent:x,runtimeAssets:O,signal:M,onEvent:B})=>{if(r===void 0)return await f({requests:w,queryContentReader:x,runtimeAssets:O});let $=m(E),ae=k??vf({load:$,concurrency:R.concurrentContentReads,signal:M}),io=Fh({graph:r,load:$,getCached:ae.getCached,readFallback:x??s,signal:M});return await Promise.allSettled(w.map(ao=>S({request:ao,graph:r,resolutionSession:ae,contentReader:io,runtimeAssets:O,onEvent:B})))};return{query:y,queryManyWithDocumentGraph:A,queryWithDocumentGraph:async({request:w,...E})=>u((await A({...E,requests:[w]}))[0])}};var Bs=({artifact:t,readContent:e})=>{let n=$f({artifact:t});return Zh({artifact:t,revision:t.revision,documentGraph:n?.graph,inlineDocuments:n?.inlineDocuments,readContent:e})};var so=class extends Error{constructor(e,n){super(e,n),this.name="AssetQueryRequestError"}},Un=class extends Error{},jh=async(t,e)=>{if(Number.isSafeInteger(e)===!1||e<0)throw new TypeError("Request byte limit must be a non-negative integer");let n=Number(t.headers.get("content-length"));if(Number.isFinite(n)&&n>e)throw new Un("Request exceeds the byte limit");let r=t.body?.getReader(),o=[],s=0;if(r!==void 0)for(;;){let{done:c,value:u}=await r.read();if(c)break;if(s+=u.byteLength,s>e){try{await r.cancel()}catch{}throw new Un("Request exceeds the byte limit")}o.push(u)}let i=new Uint8Array(s),a=0;for(let c of o)i.set(c,a),a+=c.byteLength;return i},Vf=async t=>{let e;try{e=await jh(t,R.requestBytes)}catch(n){throw n instanceof Un?new so("Asset query request exceeds the byte limit",{cause:n}):n}try{return sl.parse(JSON.parse(fe(e)))}catch(n){throw new so("Asset query request is invalid",{cause:n})}};var qf=t=>{if(t instanceof tn)return{code:"STALE_INDEX",message:t.message,retryable:!1,status:409};if(t instanceof Bn)return{code:t.code,message:t.message,retryable:!1,details:{matchedCount:t.matchedCount},status:409};if(t instanceof Ce)return{code:"INVALID_REQUEST",message:t.message,retryable:!1,status:400};if(t instanceof ie)return{code:t.code,message:t.message,retryable:!1,details:t.details,status:400};let e=new Set,n=t;for(;n!==void 0&&e.has(n)===!1;){if(n instanceof xt){let r={};for(let[o,s]of Object.entries({assetId:n.documentId,documentCount:n.documentCount,documentLimit:n.documentLimit,contentByteLimit:n.contentByteLimit,totalBytes:n.totalBytes,totalByteLimit:n.totalByteLimit}))s!==void 0&&(r[o]=s);return{code:"CONTENT_LIMIT_EXCEEDED",message:n.message,retryable:!1,details:r,status:400}}if(n instanceof Zn)return{code:"CONTENT_LIMIT_EXCEEDED",message:n.message,retryable:!1,details:{assetId:n.documentId,contentByteLimit:n.contentByteLimit},status:400};e.add(n),n=n instanceof Error?n.cause:void 0}};var Bh="/$resources/assets",Jf=(t,e=200)=>new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json; charset=utf-8"}}),Qn=({code:t,message:e,status:n,retryable:r=!1,details:o})=>Jf(cl({code:t,message:e,retryable:r,details:o}),n),Uh=(t,e,n)=>typeof t=="string"||t instanceof URL?new Request(new URL(t,e),n):new Request(t,n),Qh=async({deploymentId:t,artifact:e,request:n})=>{let r=await n.clone().text(),o=n.headers.get("cache-control"),s=await Wo(JSON.stringify([t,e.revision,r,o])),i=new URL(n.url);return i.searchParams.set("ws-asset-resource",s),new Request(i,{method:"GET"})},Ik=({deploymentId:t,artifact:e,runtimeAssets:n,cache:r,baseUrl:o,fetchDocument:s=globalThis.fetch,onDocumentGraphEvent:i})=>{Kf({artifact:e,runtimeAssets:n});let a=Ps();return Wf({deploymentId:t,artifact:e,runtimeAssets:n,cache:r,baseUrl:o,database:Bs({artifact:e}),fetchDocument:s,documentCache:a,onDocumentGraphEvent:i})},Gh=({baseUrl:t,runtimeAssets:e,fetchDocument:n,cache:r,onEvent:o})=>Af({cache:r,onEvent:o,load:gf({fetch:n,getRequest:s=>{let i=e[s.id];if(i===void 0)throw new Error(`Published document URL is unavailable for ${s.id}`);return new URL(i.url,t)},getMetadata:({node:s})=>({format:s.format,revision:s.revision}),onEvent:o})}),Kf=({artifact:t,runtimeAssets:e})=>{let n=[t.assetReferences,t.assetValueReferences].flatMap(s=>Object.values(s??{}).flat()).map(({assetId:s})=>s).find(s=>e[s]===void 0);if(n!==void 0)throw new Error(`Published referenced asset URL is unavailable for ${n}`);let r=t.documentGraph?.nodes.find(({id:s})=>e[s]===void 0)?.id;if(r!==void 0)throw new Error(`Published document URL is unavailable for ${r}`);let o=t.documentGraph?.nodes.find(({id:s,contentRef:i})=>e[s]?.contentRef!==i)?.id;if(o!==void 0)throw new Error(`Published document identity does not match graph node ${o}`)},Wf=({deploymentId:t,artifact:e,runtimeAssets:n,cache:r,baseUrl:o,database:s,fetchDocument:i,documentCache:a,onDocumentGraphEvent:c})=>{let u=new URL(o).origin,d=Gh({baseUrl:o,runtimeAssets:n,fetchDocument:i,cache:a,onEvent:c});return async(l,f)=>{let p=Uh(l,o,f),y=new URL(p.url);if(y.origin!==u||y.pathname!==Bh||p.method.toUpperCase()!=="POST")return;let m;try{m=await Vf(p.clone())}catch{return Qn({code:"INVALID_REQUEST",message:"Asset resource request is invalid",status:400})}let h=r===void 0||p.headers.has("cache-control")===!1?void 0:await Qh({deploymentId:t,artifact:e,request:p});if(h!==void 0&&r!==void 0){let b=await r.match(h).catch(()=>{});if(b!==void 0)return new Response(b.body,b)}try{if(p.signal.aborted)return Qn({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let b=Jf(await s.queryWithDocumentGraph({request:m,load:d,runtimeAssets:n,signal:p.signal,onEvent:c}));return h!==void 0&&r!==void 0&&p.signal.aborted===!1&&(b.headers.set("cache-control",p.headers.get("cache-control")),await r.put(h,b.clone()).catch(()=>{})),b}catch(b){if(p.signal.aborted)return Qn({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let S=qf(b);return Qn(S!==void 0?S:{code:"INTERNAL_ERROR",message:"Published asset query failed",status:500,retryable:!0})}}},Ok=({deploymentId:t,artifact:e,runtimeAssets:n,onDocumentGraphEvent:r=void 0})=>{let o=globalThis.caches,s,i=()=>(s??=o.open(`webstudio-assets-${t}`),s),a=o===void 0?void 0:{match:async d=>(await i()).match(d),put:async(d,l)=>(await i()).put(d,l)};Kf({artifact:e,runtimeAssets:n});let c=Bs({artifact:e}),u=Ps();return async({request:d,fallback:l})=>{let f=new URL(d.url).origin,p=Wf({deploymentId:t,artifact:e,runtimeAssets:n,cache:a,baseUrl:f,database:c,fetchDocument:l,documentCache:u,onDocumentGraphEvent:r});return async(y,m)=>await p(y,m)??l(y,m)}};export{Ok as createGeneratedAssetResourceRuntime,Ik as createPublishedAssetResourceFetch};+`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}function dr(e){switch(e){case void 0:case" ":case`+`:case"\r":case" ":return!0;default:return!1}}var $y=new Set("0123456789ABCDEFabcdef"),XA=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),ba=new Set(",[]{}"),YA=new Set(` ,[]{}+\r `),Qc=e=>!e||YA.has(e),zs=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let n=this.next??"stream";for(;n&&(r||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`+`?!0:r==="\r"?this.buffer[t+1]===`+`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let r=this.buffer[t];if(this.indentNext>0){let n=0;for(;r===" ";)r=this.buffer[++n+t];if(r==="\r"){let i=this.buffer[n+t+1];if(i===`+`||!i&&!this.atEnd)return t+n+1}return r===`+`||n>=this.indentNext||!r&&!this.atEnd?t+n:-1}if(r==="-"||r==="."){let n=this.buffer.substr(t,3);if((n==="---"||n==="...")&&dr(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`+`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===Zc&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,n=t.indexOf("#");for(;n!==-1;){let s=t[n-1];if(s===" "||s===" "){r=n-1;break}else n=t.indexOf("#",n+1)}for(;;){let s=t[r-1];if(s===" "||s===" ")r-=1;else break}let i=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-i),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield Jc,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&dr(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,r==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!dr(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&dr(r)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Qc),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,n=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=n=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let i=this.getLine();if(i===null)return this.setNext("flow");if((n!==-1&&n<this.indentNext&&i[0]!=="#"||n===0&&(i.startsWith("---")||i.startsWith("..."))&&dr(i[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}")))return this.flowLevel=0,yield Gc,yield*this.parseLineStart();let s=0;for(;i[s]===",";)s+=yield*this.pushCount(1),s+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(s+=yield*this.pushIndicators(),i[s]){case void 0:return"flow";case"#":return yield*this.pushCount(i.length-s),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(Qc),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||dr(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let s=0;for(;this.buffer[r-1-s]==="\\";)s+=1;if(s%2===0)break;r=this.buffer.indexOf('"',r+1)}let n=this.buffer.substring(0,r),i=n.indexOf(`+`,this.pos);if(i!==-1){for(;i!==-1;){let s=this.continueScalar(i+1);if(s===-1)break;i=n.indexOf(`+`,s)}i!==-1&&(r=i-(n[i-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>dr(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,n;e:for(let s=this.pos;n=this.buffer[s];++s)switch(n){case" ":r+=1;break;case`+`:t=s,r=0;break;case"\r":{let o=this.buffer[s+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`+`)break}default:break e}if(!n&&!this.atEnd)return this.setNext("block-scalar");if(r>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=r:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let s=this.continueScalar(t+1);if(s===-1)break;t=this.buffer.indexOf(`+`,s)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let i=t+1;for(n=this.buffer[i];n===" ";)n=this.buffer[++i];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===`+`;)n=this.buffer[++i];t=i-1}else if(!this.blockScalarKeep)do{let s=t-1,o=this.buffer[s];o==="\r"&&(o=this.buffer[--s]);let u=s;for(;o===" ";)o=this.buffer[--s];if(o===`+`&&s>=this.pos&&s+1+r>u)t=s;else break}while(!0);return yield xa,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,n=this.pos-1,i;for(;i=this.buffer[++n];)if(i===":"){let s=this.buffer[n+1];if(dr(s)||t&&ba.has(s))break;r=n}else if(dr(i)){let s=this.buffer[n+1];if(i==="\r"&&(s===`+`?(n+=1,i=`+`,s=this.buffer[n+1]):r=n),s==="#"||t&&ba.has(s))break;if(i===`+`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(t&&ba.has(i))break;r=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield xa,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let n=this.buffer.slice(this.pos,t);return n?(yield n,this.pos+=n.length,n.length):(r&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(Qc),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,n=this.charAt(1);if(dr(n)||r&&ba.has(n)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,r=this.buffer[t];for(;!dr(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(XA.has(r))r=this.buffer[++t];else if(r==="%"&&$y.has(this.buffer[t+1])&&$y.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`+`?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`+`?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,n;do n=this.buffer[++r];while(n===" "||t&&n===" ");let i=r-this.pos;return i>0&&(yield this.buffer.substr(this.pos,i),this.pos=r),i}*pushUntil(t){let r=this.pos,n=this.buffer[r];for(;!t(n);)n=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};var Bs=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,n=this.lineStarts.length;for(;r<n;){let s=r+n>>1;this.lineStarts[s]<t?r=s+1:n=s}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let i=this.lineStarts[r-1];return{line:r,col:t-i+1}}}};function xn(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function jy(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function qy(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function wa(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function Ci(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function va(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function Uy(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!xn(t.start,"explicit-key-ind")&&!xn(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,qy(t.value)?t.value.end?va(t.value.end,t.sep):t.value.end=t.sep:va(t.start,t.sep),delete t.sep)}var Ms=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new zs,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(t,r))yield*this.next(n);r||(yield*this.end())}*next(t){if(this.source=t,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=Vy(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let n=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:n,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let n=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in n?n.indent:0:r.type==="flow-collection"&&n.type==="document"&&(r.indent=0),r.type==="flow-collection"&&Uy(r),n.type){case"document":n.value=r;break;case"block-scalar":n.props.push(r);break;case"block-map":{let i=n.items[n.items.length-1];if(i.value){n.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(i.sep)i.value=r;else{Object.assign(i,{key:r,sep:[]}),this.onKeyLine=!i.explicitKey;return}break}case"block-seq":{let i=n.items[n.items.length-1];i.value?n.items.push({start:[],value:r}):i.value=r;break}case"flow-collection":{let i=n.items[n.items.length-1];!i||i.value?n.items.push({start:[],key:r,sep:[]}):i.sep?i.value=r:Object.assign(i,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let i=r.items[r.items.length-1];i&&!i.sep&&!i.value&&i.start.length>0&&jy(i.start)===-1&&(r.indent===0||i.start.every(s=>s.type!=="comment"||s.indent<r.indent))&&(n.type==="document"?n.end=i.start:n.items.push({start:i.start}),r.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{jy(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let r=wa(this.peek(2)),n=Ci(r),i;t.end?(i=t.end,i.push(this.sourceToken),delete t.end):i=[this.sourceToken];let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:n,key:t,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`+`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`+`,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let n="end"in r.value?r.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let i=t.items[t.items.length-2]?.value?.end;if(Array.isArray(i)){va(i,r.start),i.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let n=!this.onKeyLine&&this.indent===t.indent,i=n&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",s=[];if(i&&r.sep&&!r.value){let o=[];for(let u=0;u<r.sep.length;++u){let c=r.sep[u];switch(c.type){case"newline":o.push(u);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(s=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||r.value?(s.push(this.sourceToken),t.items.push({start:s}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):i||r.value?(s.push(this.sourceToken),t.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(xn(r.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(qy(r.key)&&!xn(r.sep,"newline")){let o=Ci(r.start),u=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:u,sep:c}]})}else s.length>0?r.sep=r.sep.concat(s,this.sourceToken):r.sep.push(this.sourceToken);else if(xn(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=Ci(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||i?t.items.push({start:s,key:null,sep:[this.sourceToken]}):xn(r.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);i||r.value?(t.items.push({start:s,key:o,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(o):(Object.assign(r,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!xn(r.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&t.items.push({start:s});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(r.value){let n="end"in r.value?r.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,t.indent)){let i=t.items[t.items.length-2]?.value?.end;if(Array.isArray(i)){va(i,r.start),i.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=t.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;r.value||xn(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let n=this.startBlockValue(t);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:i,sep:[]}):r.sep?this.stack.push(i):Object.assign(r,{key:i,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let n=this.startBlockValue(t);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===t.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let i=wa(n),s=Ci(i);Uy(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let u={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:s,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=u}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let r=this.source.indexOf(`+`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`+`,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=wa(t),n=Ci(r);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=wa(t),n=Ci(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};function eS(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Bs||null,prettyErrors:t}}function Hc(e,t={}){let{lineCounter:r,prettyErrors:n}=eS(t),i=new Ms(r?.addNewLine),s=new Ls(t),o=null;for(let u of s.compose(i.parse(e),!0,e.length))if(!o)o=u;else if(o.options.logLevel!=="silent"){o.errors.push(new hr(u.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&r&&(o.errors.forEach(Lc(e,r)),o.warnings.forEach(Lc(e,r))),o}var mr=class extends Error{code;constructor(t){super(`Structured data failed validation: ${t}`),this.name="StructuredDataError",this.code=t}},rS=e=>Mt(JSON.stringify(e)),Zy=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Jy=(e,t)=>{if(Zy(e)===!1)throw new mr("INVALID");let r=0,n=(s,o)=>{if(o>t.depth)throw new mr("DEPTH_EXCEEDED");if(typeof s=="string"){if(Mt(s)>t.stringBytes)throw new mr("STRING_BYTES_EXCEEDED");return s}if(s===null||typeof s=="boolean"||typeof s=="number"&&Number.isFinite(s)&&(Number.isInteger(s)===!1||Number.isSafeInteger(s)))return s;if(Array.isArray(s))return s.map(u=>{if(r+=1,r>t.fields)throw new mr("FIELDS_EXCEEDED");return n(u,o+1)});if(Zy(s)){let u=Object.create(null);for(let[c,f]of Object.entries(s)){if(r+=1,r>t.fields)throw new mr("FIELDS_EXCEEDED");u[c]=n(f,o+1)}return u}throw new mr("INVALID")},i=n(e,1);if(rS(i)>t.serializedBytes)throw new mr("SERIALIZED_BYTES_EXCEEDED");return i};var Ye=class extends Error{code;constructor(t,r){super(r),this.name="MarkdownMetadataError",this.code=t}};var Vs=new Uint8Array([239,187,191]),Gy=Vs.byteLength+10,nS=(e,t,r=0)=>e.byteLength-r<t.byteLength?!1:t.every((n,i)=>e[r+i]===n),$s=(e,t)=>{let r=0;if(nS(e,Vs))r=Vs.byteLength;else if(e.byteLength<Vs.byteLength&&Vs.slice(0,e.byteLength).every((s,o)=>s===e[o]))return t?null:void 0;if(e.byteLength<r+4)return t?null:void 0;if(e[r]!==45||e[r+1]!==45||e[r+2]!==45)return null;let n=r+3;if(e[n]===10)n+=1;else if(e[n]===13){if(e.byteLength===n+1)return t?null:void 0;if(e[n+1]!==10)return null;n+=2}else return null;let i=n;for(let s=n;s<=e.byteLength;s+=1){let o=s===e.byteLength;if(o===!1&&e[s]!==10)continue;if(o&&t===!1)return;let u=s;if(u>i&&e[u-1]===13&&(u-=1),u-i===3&&(e[i]===45&&e[i+1]===45&&e[i+2]===45||e[i]===46&&e[i+1]===46&&e[i+2]===46))return{yamlStart:n,yamlEnd:i,blockEnd:o?s:s+1};i=s+1}};var iS={bytes:Q.frontmatterBytes,depth:Q.frontmatterDepth,fields:Q.frontmatterFields,stringBytes:Q.frontmatterStringBytes,serializedBytes:Q.indexedPropertiesBytes},Qy=e=>{try{return _t(e)}catch{throw new Ye("FRONTMATTER_DECODING_FAILED","Markdown frontmatter is not valid UTF-8")}},Hy=(e,t)=>{let r=Hc(e,{schema:"core",uniqueKeys:!0});if(r.errors.length>0)throw new Ye("FRONTMATTER_INVALID","Markdown frontmatter contains invalid YAML");let n;try{n=r.toJS({maxAliasCount:0})}catch{throw new Ye("FRONTMATTER_INVALID","Markdown frontmatter contains unsupported YAML aliases")}if(n===null)return{};try{return Jy(n,t)}catch(i){throw i instanceof mr?i.code==="DEPTH_EXCEEDED"?new Ye("FRONTMATTER_DEPTH_EXCEEDED","Markdown frontmatter exceeds the nesting limit"):i.code==="FIELDS_EXCEEDED"?new Ye("FRONTMATTER_FIELDS_EXCEEDED","Markdown frontmatter exceeds the field limit"):i.code==="STRING_BYTES_EXCEEDED"?new Ye("FRONTMATTER_STRING_BYTES_EXCEEDED","Markdown frontmatter contains a string that exceeds the byte limit"):i.code==="SERIALIZED_BYTES_EXCEEDED"?new Ye("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter properties exceed the indexed byte limit"):new Ye("FRONTMATTER_INVALID","Markdown frontmatter must contain a JSON-compatible object"):i}},ka=async(e,t={})=>{let r={...iS,...t},n=r.bytes+Gy,i=new Uint8Array(n),s=0;for await(let c of hi(e)){let f=0;for(;f<c.byteLength;){let h=n-s;if(h<=0)break;let p=Math.max(0,6-s),m=Math.min(c.byteLength-f,p);if(p===0){let b=c.subarray(f,Math.min(c.byteLength,f+h)),v=b.indexOf(10);m=v===-1?b.byteLength:v+1}i.set(c.subarray(f,f+m),s),s+=m,f+=m;let d=i.subarray(0,s),x=$s(d,!1);if(x===null)return{properties:{},frontmatterBytes:0,consumedBytes:d.length};if(x!==void 0){let b=x.yamlEnd-x.yamlStart;if(b>r.bytes)throw new Ye("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter exceeds the byte limit");let v=Qy(d.subarray(x.yamlStart,x.yamlEnd));return{properties:Hy(v,r),frontmatterBytes:b,consumedBytes:x.blockEnd}}}if(s>=n)break}let o=i.subarray(0,s),u=$s(o,!0);if(u===null)return{properties:{},frontmatterBytes:0,consumedBytes:o.length};if(u!==void 0){let c=u.yamlEnd-u.yamlStart;if(c<=r.bytes){let f=Qy(o.subarray(u.yamlStart,u.yamlEnd));return{properties:Hy(f,r),frontmatterBytes:c,consumedBytes:u.blockEnd}}}throw new Ye("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter is not closed within the byte limit")};var Aa=async(e,t=Q.hydratedFileBytes)=>{if(Number.isInteger(t)===!1||t<=0||t>Q.hydratedFileBytes)throw new Ye("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown body byte limit is outside the supported range");let r;try{r=await Ar(e,t)}catch(u){throw u instanceof pt?new Ye("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown content exceeds the byte limit"):u}let n;try{n=_t(r)}catch{throw new Ye("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}let s=$s(r,!0)?.blockEnd??0,o;try{o=s===0?di(n):_t(r.subarray(s))}catch{throw new Ye("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}return{body:o,bodyBytes:Mt(o),sourceBytes:r.byteLength}};var bn=class extends Error{code;referenceId;constructor({code:t,message:r,referenceId:n,cause:i}){super(r,{cause:i}),this.name="MarkdownDocumentError",this.code=t,this.referenceId=n}},sS=le({source:G(),body:G(),frontmatter:sr(G(),cn())}),Ea=e=>{let t;try{t=sS.parse(e)}catch(r){throw new bn({code:"INVALID_DOCUMENT",message:"Markdown document is invalid",cause:r})}return Object.freeze({source:t.source,body:t.body,frontmatter:ln(t.frontmatter)})},Sa="#frontmatter",oS=e=>`${Sa}${e.slice(1)}`,aS=e=>{if(e!==Sa&&e.startsWith(`${Sa}/`)===!1)throw new bn({code:"UNUSED_REFERENCE",message:`Resolved Markdown reference ${e} is outside frontmatter`,referenceId:e});return`#${e.slice(Sa.length)}`},uS=e=>{let t=e.referenceId===void 0?void 0:oS(e.referenceId),r="INVALID_DOCUMENT";throw(e.code==="INVALID_REFERENCE_MARKER"||e.code==="INVALID_REFERENCE"||e.code==="REFERENCE_NOT_FOUND"||e.code==="INVALID_RESOLVED_VALUE"||e.code==="UNUSED_REFERENCE")&&(r=e.code),new bn({code:r,message:e.message,referenceId:t,cause:e})},_a=async({source:e,maximumBytes:t=Q.hydratedFileBytes})=>{let r;try{r=await Ar(e,t)}catch(o){throw o instanceof pt?new bn({code:"CONTENT_LIMIT_EXCEEDED",message:"Markdown document exceeds the byte limit",cause:o}):o}let n;try{n=di(_t(r))}catch(o){throw new bn({code:"CONTENT_DECODING_FAILED",message:"Markdown document is not valid UTF-8",cause:o})}let[i,s]=await Promise.all([Aa(r,t),ka(r)]);return Ea({source:n,body:i.body,frontmatter:s.properties})};var Ca=({document:e,references:t,allowUnresolvedReferences:r=!1})=>{let n=Ea(e),i=new Map;for(let[o,u]of t)i.set(aS(o),u);let s;try{s=Vo({document:n.frontmatter,references:i,allowUnresolvedReferences:r})}catch(o){throw o instanceof Dt&&uS(o),o}return Ea({...n,frontmatter:s})},Da=({document:e,representation:t})=>{let r=Ea(e);if(t.type==="document")return r.source;if(t.type==="markdown-body")return r.body;if(t.type==="markdown-frontmatter")return r.frontmatter;throw new bn({code:"UNSUPPORTED_REPRESENTATION",message:`Markdown documents do not support ${t.type}`})};function Wy(e,t){let r={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,r),e.applyData(t,r)}function Ky(e,t){let r={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,r),[e.applyData(t,r),{type:"text",value:`+`}]}function Xy(e,t){let r=t.value?t.value+`+`:"",n=t.lang?t.lang.match(/^[^ \t]+(?=[ \t]|$)/):null,i={};n&&(i.className=["language-"+n]);let s={type:"element",tagName:"code",properties:i,children:[{type:"text",value:r}]};return t.meta&&(s.data={meta:t.meta}),e.patch(t,s),s=e.applyData(t,s),s={type:"element",tagName:"pre",properties:{},children:[s]},e.patch(t,s),s}function Yy(e,t){let r={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function ex(e,t){let r={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}var tx=/[!-\/:-@\[-`\{-~\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1B7D\u1B7E\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]/;var Ze=wn(/[A-Za-z]/),Ue=wn(/[\dA-Za-z]/),rx=wn(/[#-'*+\--9=?A-Z^-~]/);function Bn(e){return e!==null&&(e<32||e===127)}var js=wn(/\d/),nx=wn(/[\dA-Fa-f]/),ix=wn(/[!-/:-@[-`{-~]/);function j(e){return e!==null&&e<-2}function ue(e){return e!==null&&(e<0||e===32)}function W(e){return e===-2||e===-1||e===32}var Mn=wn(tx),Ke=wn(/\s/);function wn(e){return t;function t(r){return r!==null&&e.test(String.fromCharCode(r))}}function $t(e){let t=[],r=-1,n=0,i=0;for(;++r<e.length;){let s=e.charCodeAt(r),o="";if(s===37&&Ue(e.charCodeAt(r+1))&&Ue(e.charCodeAt(r+2)))i=2;else if(s<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(s))||(o=String.fromCharCode(s));else if(s>55295&&s<57344){let u=e.charCodeAt(r+1);s<56320&&u>56319&&u<57344?(o=String.fromCharCode(s,u),i=1):o="\uFFFD"}else o=String.fromCharCode(s);o&&(t.push(e.slice(n,r),encodeURIComponent(o)),n=r+i+1,o=""),i&&(r+=i,i=0)}return t.join("")+e.slice(n)}function Ia(e,t){let r=String(t.identifier).toUpperCase(),n=$t(r.toLowerCase()),i=e.footnoteOrder.indexOf(r),s;i===-1?(e.footnoteOrder.push(r),e.footnoteCounts[r]=1,s=e.footnoteOrder.length):(e.footnoteCounts[r]++,s=i+1);let o=e.footnoteCounts[r],u={type:"element",tagName:"a",properties:{href:"#"+e.clobberPrefix+"fn-"+n,id:e.clobberPrefix+"fnref-"+n+(o>1?"-"+o:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(s)}]};e.patch(t,u);let c={type:"element",tagName:"sup",properties:{},children:[u]};return e.patch(t,c),e.applyData(t,c)}function sx(e,t){let r=e.footnoteById,n=1;for(;n in r;)n++;let i=String(n);return r[i]={type:"footnoteDefinition",identifier:i,children:[{type:"paragraph",children:t.children}],position:t.position},Ia(e,{type:"footnoteReference",identifier:i,position:t.position})}function ox(e,t){let r={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function ax(e,t){if(e.dangerous){let r={type:"raw",value:t.value};return e.patch(t,r),e.applyData(t,r)}return null}function Ta(e,t){let r=t.referenceType,n="]";if(r==="collapsed"?n+="[]":r==="full"&&(n+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return{type:"text",value:"!["+t.alt+n};let i=e.all(t),s=i[0];s&&s.type==="text"?s.value="["+s.value:i.unshift({type:"text",value:"["});let o=i[i.length-1];return o&&o.type==="text"?o.value+=n:i.push({type:"text",value:n}),i}function ux(e,t){let r=e.definition(t.identifier);if(!r)return Ta(e,t);let n={src:$t(r.url||""),alt:t.alt};r.title!==null&&r.title!==void 0&&(n.title=r.title);let i={type:"element",tagName:"img",properties:n,children:[]};return e.patch(t,i),e.applyData(t,i)}function cx(e,t){let r={src:$t(t.url)};t.alt!==null&&t.alt!==void 0&&(r.alt=t.alt),t.title!==null&&t.title!==void 0&&(r.title=t.title);let n={type:"element",tagName:"img",properties:r,children:[]};return e.patch(t,n),e.applyData(t,n)}function lx(e,t){let r={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,r);let n={type:"element",tagName:"code",properties:{},children:[r]};return e.patch(t,n),e.applyData(t,n)}function fx(e,t){let r=e.definition(t.identifier);if(!r)return Ta(e,t);let n={href:$t(r.url||"")};r.title!==null&&r.title!==void 0&&(n.title=r.title);let i={type:"element",tagName:"a",properties:n,children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function px(e,t){let r={href:$t(t.url)};t.title!==null&&t.title!==void 0&&(r.title=t.title);let n={type:"element",tagName:"a",properties:r,children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function hx(e,t,r){let n=e.all(t),i=r?cS(r):dx(t),s={},o=[];if(typeof t.checked=="boolean"){let h=n[0],p;h&&h.type==="element"&&h.tagName==="p"?p=h:(p={type:"element",tagName:"p",properties:{},children:[]},n.unshift(p)),p.children.length>0&&p.children.unshift({type:"text",value:" "}),p.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),s.className=["task-list-item"]}let u=-1;for(;++u<n.length;){let h=n[u];(i||u!==0||h.type!=="element"||h.tagName!=="p")&&o.push({type:"text",value:`+`}),h.type==="element"&&h.tagName==="p"&&!i?o.push(...h.children):o.push(h)}let c=n[n.length-1];c&&(i||c.type!=="element"||c.tagName!=="p")&&o.push({type:"text",value:`+`});let f={type:"element",tagName:"li",properties:s,children:o};return e.patch(t,f),e.applyData(t,f)}function cS(e){let t=!1;if(e.type==="list"){t=e.spread||!1;let r=e.children,n=-1;for(;!t&&++n<r.length;)t=dx(r[n])}return t}function dx(e){let t=e.spread;return t??e.children.length>1}function mx(e,t){let r={},n=e.all(t),i=-1;for(typeof t.start=="number"&&t.start!==1&&(r.start=t.start);++i<n.length;){let o=n[i];if(o.type==="element"&&o.tagName==="li"&&o.properties&&Array.isArray(o.properties.className)&&o.properties.className.includes("task-list-item")){r.className=["contains-task-list"];break}}let s={type:"element",tagName:t.ordered?"ol":"ul",properties:r,children:e.wrap(n,!0)};return e.patch(t,s),e.applyData(t,s)}function gx(e,t){let r={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function yx(e,t){let r={type:"root",children:e.wrap(e.all(t))};return e.patch(t,r),e.applyData(t,r)}function xx(e,t){let r={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}var Di=bx("start"),Ii=bx("end");function Wc(e){return{start:Di(e),end:Ii(e)}}function bx(e){return t;function t(r){let n=r&&r.position&&r.position[e]||{};return{line:n.line||null,column:n.column||null,offset:n.offset>-1?n.offset:null}}}function wx(e,t){let r=e.all(t),n=r.shift(),i=[];if(n){let o={type:"element",tagName:"thead",properties:{},children:e.wrap([n],!0)};e.patch(t.children[0],o),i.push(o)}if(r.length>0){let o={type:"element",tagName:"tbody",properties:{},children:e.wrap(r,!0)},u=Di(t.children[1]),c=Ii(t.children[t.children.length-1]);u.line&&c.line&&(o.position={start:u,end:c}),i.push(o)}let s={type:"element",tagName:"table",properties:{},children:e.wrap(i,!0)};return e.patch(t,s),e.applyData(t,s)}function vx(e,t,r){let n=r?r.children:void 0,s=(n?n.indexOf(t):1)===0?"th":"td",o=r&&r.type==="table"?r.align:void 0,u=o?o.length:t.children.length,c=-1,f=[];for(;++c<u;){let p=t.children[c],m={},d=o?o[c]:void 0;d&&(m.align=d);let x={type:"element",tagName:s,properties:m,children:[]};p&&(x.children=e.all(p),e.patch(p,x),x=e.applyData(t,x)),f.push(x)}let h={type:"element",tagName:"tr",properties:{},children:e.wrap(f,!0)};return e.patch(t,h),e.applyData(t,h)}function kx(e,t){let r={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function Sx(e){let t=String(e),r=/\r?\n|\r/g,n=r.exec(t),i=0,s=[];for(;n;)s.push(Ax(t.slice(i,n.index),i>0,!0),n[0]),i=n.index+n[0].length,n=r.exec(t);return s.push(Ax(t.slice(i),i>0,!1)),s.join("")}function Ax(e,t,r){let n=0,i=e.length;if(t){let s=e.codePointAt(n);for(;s===9||s===32;)n++,s=e.codePointAt(n)}if(r){let s=e.codePointAt(i-1);for(;s===9||s===32;)i--,s=e.codePointAt(i-1)}return i>n?e.slice(n,i):""}function Ex(e,t){let r={type:"text",value:Sx(String(t.value))};return e.patch(t,r),e.applyData(t,r)}function _x(e,t){let r={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,r),e.applyData(t,r)}var vn={blockquote:Wy,break:Ky,code:Xy,delete:Yy,emphasis:ex,footnoteReference:Ia,footnote:sx,heading:ox,html:ax,imageReference:ux,image:cx,inlineCode:lx,linkReference:fx,link:px,listItem:hx,list:mx,paragraph:gx,root:yx,strong:xx,table:wx,tableCell:kx,tableRow:vx,text:Ex,thematicBreak:_x,toml:Ra,yaml:Ra,definition:Ra,footnoteDefinition:Ra};function Ra(){return null}var Ti=function(e){if(e==null)return hS;if(typeof e=="string")return pS(e);if(typeof e=="object")return Array.isArray(e)?lS(e):fS(e);if(typeof e=="function")return Na(e);throw new Error("Expected function, string, or object as test")};function lS(e){let t=[],r=-1;for(;++r<e.length;)t[r]=Ti(e[r]);return Na(n);function n(...i){let s=-1;for(;++s<t.length;)if(t[s].call(this,...i))return!0;return!1}}function fS(e){return Na(t);function t(r){let n;for(n in e)if(r[n]!==e[n])return!1;return!0}}function pS(e){return Na(t);function t(r){return r&&r.type===e}}function Na(e){return t;function t(r,...n){return!!(r&&typeof r=="object"&&"type"in r&&e.call(this,r,...n))}}function hS(){return!0}var Kc=!0,Pa=!1,Xc="skip",Us=function(e,t,r,n){typeof t=="function"&&typeof r!="function"&&(n=r,r=t,t=null);let i=Ti(t),s=n?-1:1;o(e,void 0,[])();function o(u,c,f){let h=u&&typeof u=="object"?u:{};if(typeof h.type=="string"){let m=typeof h.tagName=="string"?h.tagName:typeof h.name=="string"?h.name:void 0;Object.defineProperty(p,"name",{value:"node ("+(u.type+(m?"<"+m+">":""))+")"})}return p;function p(){let m=[],d,x,b;if((!t||i(u,c,f[f.length-1]||null))&&(m=dS(r(u,f)),m[0]===Pa))return m;if(u.children&&m[0]!==Xc)for(x=(n?u.children.length:-1)+s,b=f.concat(u);x>-1&&x<u.children.length;){if(d=o(u.children[x],x,b)(),d[0]===Pa)return d;x=typeof d[1]=="number"?d[1]:x+s}return m}}};function dS(e){return Array.isArray(e)?e:typeof e=="number"?[Kc,e]:[e]}var qs=function(e,t,r,n){typeof t=="function"&&typeof r!="function"&&(n=r,r=t,t=null),Us(e,t,i,n);function i(s,o){let u=o[o.length-1];return r(s,u?u.children.indexOf(s):null,u)}};function Yc(e){return!e||!e.position||!e.position.start||!e.position.start.line||!e.position.start.column||!e.position.end||!e.position.end.line||!e.position.end.column}var Cx={}.hasOwnProperty;function el(e){let t=Object.create(null);if(!e||!e.type)throw new Error("mdast-util-definitions expected node");return qs(e,"definition",n=>{let i=Dx(n.identifier);i&&!Cx.call(t,i)&&(t[i]=n)}),r;function r(n){let i=Dx(n);return i&&Cx.call(t,i)?t[i]:null}}function Dx(e){return String(e||"").toUpperCase()}var Oa={}.hasOwnProperty;function Ix(e,t){let r=t||{},n=r.allowDangerousHtml||!1,i={};return o.dangerous=n,o.clobberPrefix=r.clobberPrefix===void 0||r.clobberPrefix===null?"user-content-":r.clobberPrefix,o.footnoteLabel=r.footnoteLabel||"Footnotes",o.footnoteLabelTagName=r.footnoteLabelTagName||"h2",o.footnoteLabelProperties=r.footnoteLabelProperties||{className:["sr-only"]},o.footnoteBackLabel=r.footnoteBackLabel||"Back to content",o.unknownHandler=r.unknownHandler,o.passThrough=r.passThrough,o.handlers={...vn,...r.handlers},o.definition=el(e),o.footnoteById=i,o.footnoteOrder=[],o.footnoteCounts={},o.patch=mS,o.applyData=gS,o.one=u,o.all=c,o.wrap=xS,o.augment=s,qs(e,"footnoteDefinition",f=>{let h=String(f.identifier).toUpperCase();Oa.call(i,h)||(i[h]=f)}),o;function s(f,h){if(f&&"data"in f&&f.data){let p=f.data;p.hName&&(h.type!=="element"&&(h={type:"element",tagName:"",properties:{},children:[]}),h.tagName=p.hName),h.type==="element"&&p.hProperties&&(h.properties={...h.properties,...p.hProperties}),"children"in h&&h.children&&p.hChildren&&(h.children=p.hChildren)}if(f){let p="type"in f?f:{position:f};Yc(p)||(h.position={start:Di(p),end:Ii(p)})}return h}function o(f,h,p,m){return Array.isArray(p)&&(m=p,p={}),s(f,{type:"element",tagName:h,properties:p||{},children:m||[]})}function u(f,h){return Tx(o,f,h)}function c(f){return tl(o,f)}}function mS(e,t){e.position&&(t.position=Wc(e))}function gS(e,t){let r=t;if(e&&e.data){let n=e.data.hName,i=e.data.hChildren,s=e.data.hProperties;typeof n=="string"&&(r.type==="element"?r.tagName=n:r={type:"element",tagName:n,properties:{},children:[]}),r.type==="element"&&s&&(r.properties={...r.properties,...s}),"children"in r&&r.children&&i!==null&&i!==void 0&&(r.children=i)}return r}function Tx(e,t,r){let n=t&&t.type;if(!n)throw new Error("Expected node, got `"+t+"`");return Oa.call(e.handlers,n)?e.handlers[n](e,t,r):e.passThrough&&e.passThrough.includes(n)?"children"in t?{...t,children:tl(e,t)}:t:e.unknownHandler?e.unknownHandler(e,t,r):yS(e,t)}function tl(e,t){let r=[];if("children"in t){let n=t.children,i=-1;for(;++i<n.length;){let s=Tx(e,n[i],t);if(s){if(i&&n[i-1].type==="break"&&(!Array.isArray(s)&&s.type==="text"&&(s.value=s.value.replace(/^\s+/,"")),!Array.isArray(s)&&s.type==="element")){let o=s.children[0];o&&o.type==="text"&&(o.value=o.value.replace(/^\s+/,""))}Array.isArray(s)?r.push(...s):r.push(s)}}}return r}function yS(e,t){let r=t.data||{},n="value"in t&&!(Oa.call(r,"hProperties")||Oa.call(r,"hChildren"))?{type:"text",value:t.value}:{type:"element",tagName:"div",properties:{},children:tl(e,t)};return e.patch(t,n),e.applyData(t,n)}function xS(e,t){let r=[],n=-1;for(t&&r.push({type:"text",value:`+`});++n<e.length;)n&&r.push({type:"text",value:`+`}),r.push(e[n]);return t&&e.length>0&&r.push({type:"text",value:`+`}),r}function Rx(e){let t=[],r=-1;for(;++r<e.footnoteOrder.length;){let n=e.footnoteById[e.footnoteOrder[r]];if(!n)continue;let i=e.all(n),s=String(n.identifier).toUpperCase(),o=$t(s.toLowerCase()),u=0,c=[];for(;++u<=e.footnoteCounts[s];){let p={type:"element",tagName:"a",properties:{href:"#"+e.clobberPrefix+"fnref-"+o+(u>1?"-"+u:""),dataFootnoteBackref:!0,className:["data-footnote-backref"],ariaLabel:e.footnoteBackLabel},children:[{type:"text",value:"\u21A9"}]};u>1&&p.children.push({type:"element",tagName:"sup",children:[{type:"text",value:String(u)}]}),c.length>0&&c.push({type:"text",value:" "}),c.push(p)}let f=i[i.length-1];if(f&&f.type==="element"&&f.tagName==="p"){let p=f.children[f.children.length-1];p&&p.type==="text"?p.value+=" ":f.children.push({type:"text",value:" "}),f.children.push(...c)}else i.push(...c);let h={type:"element",tagName:"li",properties:{id:e.clobberPrefix+"fn-"+o},children:e.wrap(i,!0)};e.patch(n,h),t.push(h)}if(t.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:e.footnoteLabelTagName,properties:{...JSON.parse(JSON.stringify(e.footnoteLabelProperties)),id:"footnote-label"},children:[{type:"text",value:e.footnoteLabel}]},{type:"text",value:`+`},{type:"element",tagName:"ol",properties:{},children:e.wrap(t,!0)},{type:"text",value:`+`}]}}function rl(e,t){let r=Ix(e,t),n=r.one(e,null),i=Rx(r);return i&&n.children.push({type:"text",value:`+`},i),Array.isArray(n)?{type:"root",children:n}:n}var Zs=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,r.url]));var il=(e,t)=>{if(t===void 0||t.length===0)return e;let r=new URL("https://content.webstudio.invalid/__assets__/"),n=new URL(e,r),i=new URL(t,r);for(let[o,u]of i.searchParams)n.searchParams.append(o,u);return i.hash!==""&&(n.hash=i.hash),e.startsWith("//")?`//${n.host}${n.pathname}${n.search}${n.hash}`:e.startsWith("/")?`${n.pathname}${n.search}${n.hash}`:URL.canParse(e)?n.href:`${n.pathname.startsWith(r.pathname)?n.pathname.slice(r.pathname.length):n.pathname}${n.search}${n.hash}`},nl=({value:e,path:t,replacement:r})=>{let[n,...i]=t;if(n===void 0)return r;if(typeof e!="object"||e===null||Object.hasOwn(e,n)===!1)return e;if(Array.isArray(e)){if(typeof n!="number")return e;let s=[...e];return s[n]=nl({value:e[n],path:i,replacement:r}),s}return typeof n!="string"?e:{...e,[n]:nl({value:e[n],path:i,replacement:r})}},Ri=({value:e,references:t,assetUrls:r})=>{let n=e;for(let i of t??[]){let s=r[i.assetId];s!==void 0&&(n=nl({value:n,path:i.path,replacement:il(s,i.suffix)}))}return n};var Px=ns(Nx(),1),Js=Object.assign(Vn(Error),{eval:Vn(EvalError),range:Vn(RangeError),reference:Vn(ReferenceError),syntax:Vn(SyntaxError),type:Vn(TypeError),uri:Vn(URIError)});function Vn(e){return t.displayName=e.displayName||e.name,t;function t(r,...n){let i=r&&(0,Px.default)(r,...n);return new e(i)}}var Fa={}.hasOwnProperty,Ox={yaml:"-",toml:"+"};function Gs(e){let t=[],r=-1,n=Array.isArray(e)?e:e?[e]:["yaml"];for(;++r<n.length;)t[r]=bS(n[r]);return t}function bS(e){let t=e;if(typeof t=="string"){if(!Fa.call(Ox,t))throw Js("Missing matter definition for `%s`",t);t={type:t,marker:Ox[t]}}else if(typeof t!="object")throw Js("Expected matter to be an object, not `%j`",t);if(!Fa.call(t,"type"))throw Js("Missing `type` in matter `%j`",t);if(!Fa.call(t,"fence")&&!Fa.call(t,"marker"))throw Js("Missing `marker` or `fence` in matter `%j`",t);return t}function al(e){let t=Gs(e),r={},n=-1;for(;++n<t.length;){let i=t[n],s=ol(i,"open").charCodeAt(0),o=wS(i),u=r[s];Array.isArray(u)?u.push(o):r[s]=[o]}return{flow:r}}function wS(e){let t=e.anywhere,r=e.type,n=r+"Fence",i=n+"Sequence",s=r+"Value",o={tokenize:h,partial:!0},u,c=0;return{tokenize:f,concrete:!0};function f(p,m,d){let x=this;return b;function b(D){let O=x.now();return O.column===1&&(O.line===1||t)&&(u=ol(e,"open"),c=0,D===u.charCodeAt(c))?(p.enter(r),p.enter(n),p.enter(i),v(D)):d(D)}function v(D){return c===u.length?(p.exit(i),W(D)?(p.enter("whitespace"),k(D)):T(D)):D===u.charCodeAt(c++)?(p.consume(D),v):d(D)}function k(D){return W(D)?(p.consume(D),k):(p.exit("whitespace"),T(D))}function T(D){return j(D)?(p.exit(n),p.enter("lineEnding"),p.consume(D),p.exit("lineEnding"),u=ol(e,"close"),c=0,p.attempt(o,_,E)):d(D)}function E(D){return D===null||j(D)?I(D):(p.enter(s),g(D))}function g(D){return D===null||j(D)?(p.exit(s),I(D)):(p.consume(D),g)}function I(D){return D===null?d(D):(p.enter("lineEnding"),p.consume(D),p.exit("lineEnding"),p.attempt(o,_,E))}function _(D){return p.exit(r),m(D)}}function h(p,m,d){let x=0;return b;function b(E){return E===u.charCodeAt(x)?(p.enter(n),p.enter(i),v(E)):d(E)}function v(E){return x===u.length?(p.exit(i),W(E)?(p.enter("whitespace"),k(E)):T(E)):E===u.charCodeAt(x++)?(p.consume(E),v):d(E)}function k(E){return W(E)?(p.consume(E),k):(p.exit("whitespace"),T(E))}function T(E){return E===null||j(E)?(p.exit(n),m(E)):d(E)}}}function ol(e,t){return e.marker?Fx(e.marker,t).repeat(3):Fx(e.fence,t)}function Fx(e,t){return typeof e=="string"?e:e[t]}function cl(e){let t=Gs(e),r={},n={},i=-1;for(;++i<t.length;){let s=t[i];r[s.type]=vS(s),n[s.type]=kS,n[s.type+"Value"]=AS}return{enter:r,exit:n}}function vS(e){return t;function t(r){this.enter({type:e.type,value:""},r),this.buffer()}}function kS(e){let t=this.resume(),r=this.exit(e);r.value=t.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,"")}function AS(e){this.config.enter.data.call(this,e),this.config.exit.data.call(this,e)}function ll(e){let t=[],r={},n=Gs(e),i=-1;for(;++i<n.length;){let s=n[i];r[s.type]=SS(s),t.push({atBreak:!0,character:ul(s,"open").charAt(0)})}return{unsafe:t,handlers:r}}function SS(e){let t=ul(e,"open"),r=ul(e,"close");return n;function n(i){return t+(i.value?`+`+i.value:"")+`+`+r}}function ul(e,t){return e.marker?Lx(e.marker,t).repeat(3):Lx(e.fence,t)}function Lx(e,t){return typeof e=="string"?e:e[t]}function fl(e="yaml"){let t=this.data();r("micromarkExtensions",al(e)),r("fromMarkdownExtensions",cl(e)),r("toMarkdownExtensions",ll(e));function r(n,i){(t[n]?t[n]:t[n]=[]).push(i)}}function Je(e,t,r,n){let i=e.length,s=0,o;if(t<0?t=-t>i?0:i+t:t=t>i?i:t,r=r>0?r:0,n.length<1e4)o=Array.from(n),o.unshift(t,r),e.splice(...o);else for(r&&e.splice(t,r);s<n.length;)o=n.slice(s,s+1e4),o.unshift(t,0),e.splice(...o),s+=1e4,t+=1e4}function dt(e,t){return e.length>0?(Je(e,e.length,0,t),e):t}var zx={}.hasOwnProperty;function Ni(e){let t={},r=-1;for(;++r<e.length;)ES(t,e[r]);return t}function ES(e,t){let r;for(r in t){let i=(zx.call(e,r)?e[r]:void 0)||(e[r]={}),s=t[r],o;if(s)for(o in s){zx.call(i,o)||(i[o]=[]);let u=s[o];_S(i[o],Array.isArray(u)?u:u?[u]:[])}}}function _S(e,t){let r=-1,n=[];for(;++r<t.length;)(t[r].add==="after"?e:n).push(t[r]);Je(e,0,0,n)}var CS={tokenize:NS,partial:!0},Bx={tokenize:PS,partial:!0},Mx={tokenize:OS,partial:!0},Vx={tokenize:FS,partial:!0},DS={tokenize:LS,partial:!0},$x={tokenize:TS,previous:Ux},jx={tokenize:RS,previous:qx},Hr={tokenize:IS,previous:Zx},Pr={},hl={text:Pr},$n=48;for(;$n<123;)Pr[$n]=Hr,$n++,$n===58?$n=65:$n===91&&($n=97);Pr[43]=Hr;Pr[45]=Hr;Pr[46]=Hr;Pr[95]=Hr;Pr[72]=[Hr,jx];Pr[104]=[Hr,jx];Pr[87]=[Hr,$x];Pr[119]=[Hr,$x];function IS(e,t,r){let n=this,i,s;return o;function o(p){return!pl(p)||!Zx.call(n,n.previous)||dl(n.events)?r(p):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),u(p))}function u(p){return pl(p)?(e.consume(p),u):p===64?(e.consume(p),c):r(p)}function c(p){return p===46?e.check(DS,h,f)(p):p===45||p===95||Ue(p)?(s=!0,e.consume(p),c):h(p)}function f(p){return e.consume(p),i=!0,c}function h(p){return s&&i&&Ze(n.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(p)):r(p)}}function TS(e,t,r){let n=this;return i;function i(o){return o!==87&&o!==119||!Ux.call(n,n.previous)||dl(n.events)?r(o):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(CS,e.attempt(Bx,e.attempt(Mx,s),r),r)(o))}function s(o){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(o)}}function RS(e,t,r){let n=this,i="",s=!1;return o;function o(p){return(p===72||p===104)&&qx.call(n,n.previous)&&!dl(n.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),i+=String.fromCodePoint(p),e.consume(p),u):r(p)}function u(p){if(Ze(p)&&i.length<5)return i+=String.fromCodePoint(p),e.consume(p),u;if(p===58){let m=i.toLowerCase();if(m==="http"||m==="https")return e.consume(p),c}return r(p)}function c(p){return p===47?(e.consume(p),s?f:(s=!0,c)):r(p)}function f(p){return p===null||Bn(p)||ue(p)||Ke(p)||Mn(p)?r(p):e.attempt(Bx,e.attempt(Mx,h),r)(p)}function h(p){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(p)}}function NS(e,t,r){let n=0;return i;function i(o){return(o===87||o===119)&&n<3?(n++,e.consume(o),i):o===46&&n===3?(e.consume(o),s):r(o)}function s(o){return o===null?r(o):t(o)}}function PS(e,t,r){let n,i,s;return o;function o(f){return f===46||f===95?e.check(Vx,c,u)(f):f===null||ue(f)||Ke(f)||f!==45&&Mn(f)?c(f):(s=!0,e.consume(f),o)}function u(f){return f===95?n=!0:(i=n,n=void 0),e.consume(f),o}function c(f){return i||n||!s?r(f):t(f)}}function OS(e,t){let r=0,n=0;return i;function i(o){return o===40?(r++,e.consume(o),i):o===41&&n<r?s(o):o===33||o===34||o===38||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===60||o===63||o===93||o===95||o===126?e.check(Vx,t,s)(o):o===null||ue(o)||Ke(o)?t(o):(e.consume(o),i)}function s(o){return o===41&&n++,e.consume(o),i}}function FS(e,t,r){return n;function n(u){return u===33||u===34||u===39||u===41||u===42||u===44||u===46||u===58||u===59||u===63||u===95||u===126?(e.consume(u),n):u===38?(e.consume(u),s):u===93?(e.consume(u),i):u===60||u===null||ue(u)||Ke(u)?t(u):r(u)}function i(u){return u===null||u===40||u===91||ue(u)||Ke(u)?t(u):n(u)}function s(u){return Ze(u)?o(u):r(u)}function o(u){return u===59?(e.consume(u),n):Ze(u)?(e.consume(u),o):r(u)}}function LS(e,t,r){return n;function n(s){return e.consume(s),i}function i(s){return Ue(s)?r(s):t(s)}}function Ux(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||ue(e)}function qx(e){return!Ze(e)}function Zx(e){return!(e===47||pl(e))}function pl(e){return e===43||e===45||e===46||e===95||Ue(e)}function dl(e){let t=e.length,r=!1;for(;t--;){let n=e[t][1];if((n.type==="labelLink"||n.type==="labelImage")&&!n._balanced){r=!0;break}if(n._gfmAutolinkLiteralWalkedInto){r=!1;break}}return e.length>0&&!r&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),r}function Pi(e){if(e===null||ue(e)||Ke(e))return 1;if(Mn(e))return 2}function kn(e,t,r){let n=[],i=-1;for(;++i<e.length;){let s=e[i].resolveAll;s&&!n.includes(s)&&(t=s(t,r),n.push(s))}return t}var Qs={name:"attention",tokenize:BS,resolveAll:zS};function zS(e,t){let r=-1,n,i,s,o,u,c,f,h;for(;++r<e.length;)if(e[r][0]==="enter"&&e[r][1].type==="attentionSequence"&&e[r][1]._close){for(n=r;n--;)if(e[n][0]==="exit"&&e[n][1].type==="attentionSequence"&&e[n][1]._open&&t.sliceSerialize(e[n][1]).charCodeAt(0)===t.sliceSerialize(e[r][1]).charCodeAt(0)){if((e[n][1]._close||e[r][1]._open)&&(e[r][1].end.offset-e[r][1].start.offset)%3&&!((e[n][1].end.offset-e[n][1].start.offset+e[r][1].end.offset-e[r][1].start.offset)%3))continue;c=e[n][1].end.offset-e[n][1].start.offset>1&&e[r][1].end.offset-e[r][1].start.offset>1?2:1;let p=Object.assign({},e[n][1].end),m=Object.assign({},e[r][1].start);Jx(p,-c),Jx(m,c),o={type:c>1?"strongSequence":"emphasisSequence",start:p,end:Object.assign({},e[n][1].end)},u={type:c>1?"strongSequence":"emphasisSequence",start:Object.assign({},e[r][1].start),end:m},s={type:c>1?"strongText":"emphasisText",start:Object.assign({},e[n][1].end),end:Object.assign({},e[r][1].start)},i={type:c>1?"strong":"emphasis",start:Object.assign({},o.start),end:Object.assign({},u.end)},e[n][1].end=Object.assign({},o.start),e[r][1].start=Object.assign({},u.end),f=[],e[n][1].end.offset-e[n][1].start.offset&&(f=dt(f,[["enter",e[n][1],t],["exit",e[n][1],t]])),f=dt(f,[["enter",i,t],["enter",o,t],["exit",o,t],["enter",s,t]]),f=dt(f,kn(t.parser.constructs.insideSpan.null,e.slice(n+1,r),t)),f=dt(f,[["exit",s,t],["enter",u,t],["exit",u,t],["exit",i,t]]),e[r][1].end.offset-e[r][1].start.offset?(h=2,f=dt(f,[["enter",e[r][1],t],["exit",e[r][1],t]])):h=0,Je(e,n-1,r-n+3,f),r=n+f.length-h-2;break}}for(r=-1;++r<e.length;)e[r][1].type==="attentionSequence"&&(e[r][1].type="data");return e}function BS(e,t){let r=this.parser.constructs.attentionMarkers.null,n=this.previous,i=Pi(n),s;return o;function o(c){return s=c,e.enter("attentionSequence"),u(c)}function u(c){if(c===s)return e.consume(c),u;let f=e.exit("attentionSequence"),h=Pi(c),p=!h||h===2&&i||r.includes(c),m=!i||i===2&&h||r.includes(n);return f._open=!!(s===42?p:p&&(i||!m)),f._close=!!(s===42?m:m&&(h||!p)),t(c)}}function Jx(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}var ml={name:"autolink",tokenize:MS};function MS(e,t,r){let n=0;return i;function i(d){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(d),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),s}function s(d){return Ze(d)?(e.consume(d),o):f(d)}function o(d){return d===43||d===45||d===46||Ue(d)?(n=1,u(d)):f(d)}function u(d){return d===58?(e.consume(d),n=0,c):(d===43||d===45||d===46||Ue(d))&&n++<32?(e.consume(d),u):(n=0,f(d))}function c(d){return d===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(d),e.exit("autolinkMarker"),e.exit("autolink"),t):d===null||d===32||d===60||Bn(d)?r(d):(e.consume(d),c)}function f(d){return d===64?(e.consume(d),h):rx(d)?(e.consume(d),f):r(d)}function h(d){return Ue(d)?p(d):r(d)}function p(d){return d===46?(e.consume(d),n=0,h):d===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(d),e.exit("autolinkMarker"),e.exit("autolink"),t):m(d)}function m(d){if((d===45||Ue(d))&&n++<63){let x=d===45?m:p;return e.consume(d),x}return r(d)}}function te(e,t,r,n){let i=n?n-1:Number.POSITIVE_INFINITY,s=0;return o;function o(c){return W(c)?(e.enter(r),u(c)):t(c)}function u(c){return W(c)&&s++<i?(e.consume(c),u):(e.exit(r),t(c))}}var jt={tokenize:VS,partial:!0};function VS(e,t,r){return n;function n(s){return W(s)?te(e,i,"linePrefix")(s):i(s)}function i(s){return s===null||j(s)?t(s):r(s)}}var La={name:"blockQuote",tokenize:$S,continuation:{tokenize:jS},exit:US};function $S(e,t,r){let n=this;return i;function i(o){if(o===62){let u=n.containerState;return u.open||(e.enter("blockQuote",{_container:!0}),u.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(o),e.exit("blockQuoteMarker"),s}return r(o)}function s(o){return W(o)?(e.enter("blockQuotePrefixWhitespace"),e.consume(o),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(o))}}function jS(e,t,r){let n=this;return i;function i(o){return W(o)?te(e,s,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o):s(o)}function s(o){return e.attempt(La,t,r)(o)}}function US(e){e.exit("blockQuote")}var za={name:"characterEscape",tokenize:qS};function qS(e,t,r){return n;function n(s){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(s),e.exit("escapeMarker"),i}function i(s){return ix(s)?(e.enter("characterEscapeValue"),e.consume(s),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):r(s)}}var gl={AElig:"\xC6",AMP:"&",Aacute:"\xC1",Abreve:"\u0102",Acirc:"\xC2",Acy:"\u0410",Afr:"\u{1D504}",Agrave:"\xC0",Alpha:"\u0391",Amacr:"\u0100",And:"\u2A53",Aogon:"\u0104",Aopf:"\u{1D538}",ApplyFunction:"\u2061",Aring:"\xC5",Ascr:"\u{1D49C}",Assign:"\u2254",Atilde:"\xC3",Auml:"\xC4",Backslash:"\u2216",Barv:"\u2AE7",Barwed:"\u2306",Bcy:"\u0411",Because:"\u2235",Bernoullis:"\u212C",Beta:"\u0392",Bfr:"\u{1D505}",Bopf:"\u{1D539}",Breve:"\u02D8",Bscr:"\u212C",Bumpeq:"\u224E",CHcy:"\u0427",COPY:"\xA9",Cacute:"\u0106",Cap:"\u22D2",CapitalDifferentialD:"\u2145",Cayleys:"\u212D",Ccaron:"\u010C",Ccedil:"\xC7",Ccirc:"\u0108",Cconint:"\u2230",Cdot:"\u010A",Cedilla:"\xB8",CenterDot:"\xB7",Cfr:"\u212D",Chi:"\u03A7",CircleDot:"\u2299",CircleMinus:"\u2296",CirclePlus:"\u2295",CircleTimes:"\u2297",ClockwiseContourIntegral:"\u2232",CloseCurlyDoubleQuote:"\u201D",CloseCurlyQuote:"\u2019",Colon:"\u2237",Colone:"\u2A74",Congruent:"\u2261",Conint:"\u222F",ContourIntegral:"\u222E",Copf:"\u2102",Coproduct:"\u2210",CounterClockwiseContourIntegral:"\u2233",Cross:"\u2A2F",Cscr:"\u{1D49E}",Cup:"\u22D3",CupCap:"\u224D",DD:"\u2145",DDotrahd:"\u2911",DJcy:"\u0402",DScy:"\u0405",DZcy:"\u040F",Dagger:"\u2021",Darr:"\u21A1",Dashv:"\u2AE4",Dcaron:"\u010E",Dcy:"\u0414",Del:"\u2207",Delta:"\u0394",Dfr:"\u{1D507}",DiacriticalAcute:"\xB4",DiacriticalDot:"\u02D9",DiacriticalDoubleAcute:"\u02DD",DiacriticalGrave:"`",DiacriticalTilde:"\u02DC",Diamond:"\u22C4",DifferentialD:"\u2146",Dopf:"\u{1D53B}",Dot:"\xA8",DotDot:"\u20DC",DotEqual:"\u2250",DoubleContourIntegral:"\u222F",DoubleDot:"\xA8",DoubleDownArrow:"\u21D3",DoubleLeftArrow:"\u21D0",DoubleLeftRightArrow:"\u21D4",DoubleLeftTee:"\u2AE4",DoubleLongLeftArrow:"\u27F8",DoubleLongLeftRightArrow:"\u27FA",DoubleLongRightArrow:"\u27F9",DoubleRightArrow:"\u21D2",DoubleRightTee:"\u22A8",DoubleUpArrow:"\u21D1",DoubleUpDownArrow:"\u21D5",DoubleVerticalBar:"\u2225",DownArrow:"\u2193",DownArrowBar:"\u2913",DownArrowUpArrow:"\u21F5",DownBreve:"\u0311",DownLeftRightVector:"\u2950",DownLeftTeeVector:"\u295E",DownLeftVector:"\u21BD",DownLeftVectorBar:"\u2956",DownRightTeeVector:"\u295F",DownRightVector:"\u21C1",DownRightVectorBar:"\u2957",DownTee:"\u22A4",DownTeeArrow:"\u21A7",Downarrow:"\u21D3",Dscr:"\u{1D49F}",Dstrok:"\u0110",ENG:"\u014A",ETH:"\xD0",Eacute:"\xC9",Ecaron:"\u011A",Ecirc:"\xCA",Ecy:"\u042D",Edot:"\u0116",Efr:"\u{1D508}",Egrave:"\xC8",Element:"\u2208",Emacr:"\u0112",EmptySmallSquare:"\u25FB",EmptyVerySmallSquare:"\u25AB",Eogon:"\u0118",Eopf:"\u{1D53C}",Epsilon:"\u0395",Equal:"\u2A75",EqualTilde:"\u2242",Equilibrium:"\u21CC",Escr:"\u2130",Esim:"\u2A73",Eta:"\u0397",Euml:"\xCB",Exists:"\u2203",ExponentialE:"\u2147",Fcy:"\u0424",Ffr:"\u{1D509}",FilledSmallSquare:"\u25FC",FilledVerySmallSquare:"\u25AA",Fopf:"\u{1D53D}",ForAll:"\u2200",Fouriertrf:"\u2131",Fscr:"\u2131",GJcy:"\u0403",GT:">",Gamma:"\u0393",Gammad:"\u03DC",Gbreve:"\u011E",Gcedil:"\u0122",Gcirc:"\u011C",Gcy:"\u0413",Gdot:"\u0120",Gfr:"\u{1D50A}",Gg:"\u22D9",Gopf:"\u{1D53E}",GreaterEqual:"\u2265",GreaterEqualLess:"\u22DB",GreaterFullEqual:"\u2267",GreaterGreater:"\u2AA2",GreaterLess:"\u2277",GreaterSlantEqual:"\u2A7E",GreaterTilde:"\u2273",Gscr:"\u{1D4A2}",Gt:"\u226B",HARDcy:"\u042A",Hacek:"\u02C7",Hat:"^",Hcirc:"\u0124",Hfr:"\u210C",HilbertSpace:"\u210B",Hopf:"\u210D",HorizontalLine:"\u2500",Hscr:"\u210B",Hstrok:"\u0126",HumpDownHump:"\u224E",HumpEqual:"\u224F",IEcy:"\u0415",IJlig:"\u0132",IOcy:"\u0401",Iacute:"\xCD",Icirc:"\xCE",Icy:"\u0418",Idot:"\u0130",Ifr:"\u2111",Igrave:"\xCC",Im:"\u2111",Imacr:"\u012A",ImaginaryI:"\u2148",Implies:"\u21D2",Int:"\u222C",Integral:"\u222B",Intersection:"\u22C2",InvisibleComma:"\u2063",InvisibleTimes:"\u2062",Iogon:"\u012E",Iopf:"\u{1D540}",Iota:"\u0399",Iscr:"\u2110",Itilde:"\u0128",Iukcy:"\u0406",Iuml:"\xCF",Jcirc:"\u0134",Jcy:"\u0419",Jfr:"\u{1D50D}",Jopf:"\u{1D541}",Jscr:"\u{1D4A5}",Jsercy:"\u0408",Jukcy:"\u0404",KHcy:"\u0425",KJcy:"\u040C",Kappa:"\u039A",Kcedil:"\u0136",Kcy:"\u041A",Kfr:"\u{1D50E}",Kopf:"\u{1D542}",Kscr:"\u{1D4A6}",LJcy:"\u0409",LT:"<",Lacute:"\u0139",Lambda:"\u039B",Lang:"\u27EA",Laplacetrf:"\u2112",Larr:"\u219E",Lcaron:"\u013D",Lcedil:"\u013B",Lcy:"\u041B",LeftAngleBracket:"\u27E8",LeftArrow:"\u2190",LeftArrowBar:"\u21E4",LeftArrowRightArrow:"\u21C6",LeftCeiling:"\u2308",LeftDoubleBracket:"\u27E6",LeftDownTeeVector:"\u2961",LeftDownVector:"\u21C3",LeftDownVectorBar:"\u2959",LeftFloor:"\u230A",LeftRightArrow:"\u2194",LeftRightVector:"\u294E",LeftTee:"\u22A3",LeftTeeArrow:"\u21A4",LeftTeeVector:"\u295A",LeftTriangle:"\u22B2",LeftTriangleBar:"\u29CF",LeftTriangleEqual:"\u22B4",LeftUpDownVector:"\u2951",LeftUpTeeVector:"\u2960",LeftUpVector:"\u21BF",LeftUpVectorBar:"\u2958",LeftVector:"\u21BC",LeftVectorBar:"\u2952",Leftarrow:"\u21D0",Leftrightarrow:"\u21D4",LessEqualGreater:"\u22DA",LessFullEqual:"\u2266",LessGreater:"\u2276",LessLess:"\u2AA1",LessSlantEqual:"\u2A7D",LessTilde:"\u2272",Lfr:"\u{1D50F}",Ll:"\u22D8",Lleftarrow:"\u21DA",Lmidot:"\u013F",LongLeftArrow:"\u27F5",LongLeftRightArrow:"\u27F7",LongRightArrow:"\u27F6",Longleftarrow:"\u27F8",Longleftrightarrow:"\u27FA",Longrightarrow:"\u27F9",Lopf:"\u{1D543}",LowerLeftArrow:"\u2199",LowerRightArrow:"\u2198",Lscr:"\u2112",Lsh:"\u21B0",Lstrok:"\u0141",Lt:"\u226A",Map:"\u2905",Mcy:"\u041C",MediumSpace:"\u205F",Mellintrf:"\u2133",Mfr:"\u{1D510}",MinusPlus:"\u2213",Mopf:"\u{1D544}",Mscr:"\u2133",Mu:"\u039C",NJcy:"\u040A",Nacute:"\u0143",Ncaron:"\u0147",Ncedil:"\u0145",Ncy:"\u041D",NegativeMediumSpace:"\u200B",NegativeThickSpace:"\u200B",NegativeThinSpace:"\u200B",NegativeVeryThinSpace:"\u200B",NestedGreaterGreater:"\u226B",NestedLessLess:"\u226A",NewLine:`+`,Nfr:"\u{1D511}",NoBreak:"\u2060",NonBreakingSpace:"\xA0",Nopf:"\u2115",Not:"\u2AEC",NotCongruent:"\u2262",NotCupCap:"\u226D",NotDoubleVerticalBar:"\u2226",NotElement:"\u2209",NotEqual:"\u2260",NotEqualTilde:"\u2242\u0338",NotExists:"\u2204",NotGreater:"\u226F",NotGreaterEqual:"\u2271",NotGreaterFullEqual:"\u2267\u0338",NotGreaterGreater:"\u226B\u0338",NotGreaterLess:"\u2279",NotGreaterSlantEqual:"\u2A7E\u0338",NotGreaterTilde:"\u2275",NotHumpDownHump:"\u224E\u0338",NotHumpEqual:"\u224F\u0338",NotLeftTriangle:"\u22EA",NotLeftTriangleBar:"\u29CF\u0338",NotLeftTriangleEqual:"\u22EC",NotLess:"\u226E",NotLessEqual:"\u2270",NotLessGreater:"\u2278",NotLessLess:"\u226A\u0338",NotLessSlantEqual:"\u2A7D\u0338",NotLessTilde:"\u2274",NotNestedGreaterGreater:"\u2AA2\u0338",NotNestedLessLess:"\u2AA1\u0338",NotPrecedes:"\u2280",NotPrecedesEqual:"\u2AAF\u0338",NotPrecedesSlantEqual:"\u22E0",NotReverseElement:"\u220C",NotRightTriangle:"\u22EB",NotRightTriangleBar:"\u29D0\u0338",NotRightTriangleEqual:"\u22ED",NotSquareSubset:"\u228F\u0338",NotSquareSubsetEqual:"\u22E2",NotSquareSuperset:"\u2290\u0338",NotSquareSupersetEqual:"\u22E3",NotSubset:"\u2282\u20D2",NotSubsetEqual:"\u2288",NotSucceeds:"\u2281",NotSucceedsEqual:"\u2AB0\u0338",NotSucceedsSlantEqual:"\u22E1",NotSucceedsTilde:"\u227F\u0338",NotSuperset:"\u2283\u20D2",NotSupersetEqual:"\u2289",NotTilde:"\u2241",NotTildeEqual:"\u2244",NotTildeFullEqual:"\u2247",NotTildeTilde:"\u2249",NotVerticalBar:"\u2224",Nscr:"\u{1D4A9}",Ntilde:"\xD1",Nu:"\u039D",OElig:"\u0152",Oacute:"\xD3",Ocirc:"\xD4",Ocy:"\u041E",Odblac:"\u0150",Ofr:"\u{1D512}",Ograve:"\xD2",Omacr:"\u014C",Omega:"\u03A9",Omicron:"\u039F",Oopf:"\u{1D546}",OpenCurlyDoubleQuote:"\u201C",OpenCurlyQuote:"\u2018",Or:"\u2A54",Oscr:"\u{1D4AA}",Oslash:"\xD8",Otilde:"\xD5",Otimes:"\u2A37",Ouml:"\xD6",OverBar:"\u203E",OverBrace:"\u23DE",OverBracket:"\u23B4",OverParenthesis:"\u23DC",PartialD:"\u2202",Pcy:"\u041F",Pfr:"\u{1D513}",Phi:"\u03A6",Pi:"\u03A0",PlusMinus:"\xB1",Poincareplane:"\u210C",Popf:"\u2119",Pr:"\u2ABB",Precedes:"\u227A",PrecedesEqual:"\u2AAF",PrecedesSlantEqual:"\u227C",PrecedesTilde:"\u227E",Prime:"\u2033",Product:"\u220F",Proportion:"\u2237",Proportional:"\u221D",Pscr:"\u{1D4AB}",Psi:"\u03A8",QUOT:'"',Qfr:"\u{1D514}",Qopf:"\u211A",Qscr:"\u{1D4AC}",RBarr:"\u2910",REG:"\xAE",Racute:"\u0154",Rang:"\u27EB",Rarr:"\u21A0",Rarrtl:"\u2916",Rcaron:"\u0158",Rcedil:"\u0156",Rcy:"\u0420",Re:"\u211C",ReverseElement:"\u220B",ReverseEquilibrium:"\u21CB",ReverseUpEquilibrium:"\u296F",Rfr:"\u211C",Rho:"\u03A1",RightAngleBracket:"\u27E9",RightArrow:"\u2192",RightArrowBar:"\u21E5",RightArrowLeftArrow:"\u21C4",RightCeiling:"\u2309",RightDoubleBracket:"\u27E7",RightDownTeeVector:"\u295D",RightDownVector:"\u21C2",RightDownVectorBar:"\u2955",RightFloor:"\u230B",RightTee:"\u22A2",RightTeeArrow:"\u21A6",RightTeeVector:"\u295B",RightTriangle:"\u22B3",RightTriangleBar:"\u29D0",RightTriangleEqual:"\u22B5",RightUpDownVector:"\u294F",RightUpTeeVector:"\u295C",RightUpVector:"\u21BE",RightUpVectorBar:"\u2954",RightVector:"\u21C0",RightVectorBar:"\u2953",Rightarrow:"\u21D2",Ropf:"\u211D",RoundImplies:"\u2970",Rrightarrow:"\u21DB",Rscr:"\u211B",Rsh:"\u21B1",RuleDelayed:"\u29F4",SHCHcy:"\u0429",SHcy:"\u0428",SOFTcy:"\u042C",Sacute:"\u015A",Sc:"\u2ABC",Scaron:"\u0160",Scedil:"\u015E",Scirc:"\u015C",Scy:"\u0421",Sfr:"\u{1D516}",ShortDownArrow:"\u2193",ShortLeftArrow:"\u2190",ShortRightArrow:"\u2192",ShortUpArrow:"\u2191",Sigma:"\u03A3",SmallCircle:"\u2218",Sopf:"\u{1D54A}",Sqrt:"\u221A",Square:"\u25A1",SquareIntersection:"\u2293",SquareSubset:"\u228F",SquareSubsetEqual:"\u2291",SquareSuperset:"\u2290",SquareSupersetEqual:"\u2292",SquareUnion:"\u2294",Sscr:"\u{1D4AE}",Star:"\u22C6",Sub:"\u22D0",Subset:"\u22D0",SubsetEqual:"\u2286",Succeeds:"\u227B",SucceedsEqual:"\u2AB0",SucceedsSlantEqual:"\u227D",SucceedsTilde:"\u227F",SuchThat:"\u220B",Sum:"\u2211",Sup:"\u22D1",Superset:"\u2283",SupersetEqual:"\u2287",Supset:"\u22D1",THORN:"\xDE",TRADE:"\u2122",TSHcy:"\u040B",TScy:"\u0426",Tab:" ",Tau:"\u03A4",Tcaron:"\u0164",Tcedil:"\u0162",Tcy:"\u0422",Tfr:"\u{1D517}",Therefore:"\u2234",Theta:"\u0398",ThickSpace:"\u205F\u200A",ThinSpace:"\u2009",Tilde:"\u223C",TildeEqual:"\u2243",TildeFullEqual:"\u2245",TildeTilde:"\u2248",Topf:"\u{1D54B}",TripleDot:"\u20DB",Tscr:"\u{1D4AF}",Tstrok:"\u0166",Uacute:"\xDA",Uarr:"\u219F",Uarrocir:"\u2949",Ubrcy:"\u040E",Ubreve:"\u016C",Ucirc:"\xDB",Ucy:"\u0423",Udblac:"\u0170",Ufr:"\u{1D518}",Ugrave:"\xD9",Umacr:"\u016A",UnderBar:"_",UnderBrace:"\u23DF",UnderBracket:"\u23B5",UnderParenthesis:"\u23DD",Union:"\u22C3",UnionPlus:"\u228E",Uogon:"\u0172",Uopf:"\u{1D54C}",UpArrow:"\u2191",UpArrowBar:"\u2912",UpArrowDownArrow:"\u21C5",UpDownArrow:"\u2195",UpEquilibrium:"\u296E",UpTee:"\u22A5",UpTeeArrow:"\u21A5",Uparrow:"\u21D1",Updownarrow:"\u21D5",UpperLeftArrow:"\u2196",UpperRightArrow:"\u2197",Upsi:"\u03D2",Upsilon:"\u03A5",Uring:"\u016E",Uscr:"\u{1D4B0}",Utilde:"\u0168",Uuml:"\xDC",VDash:"\u22AB",Vbar:"\u2AEB",Vcy:"\u0412",Vdash:"\u22A9",Vdashl:"\u2AE6",Vee:"\u22C1",Verbar:"\u2016",Vert:"\u2016",VerticalBar:"\u2223",VerticalLine:"|",VerticalSeparator:"\u2758",VerticalTilde:"\u2240",VeryThinSpace:"\u200A",Vfr:"\u{1D519}",Vopf:"\u{1D54D}",Vscr:"\u{1D4B1}",Vvdash:"\u22AA",Wcirc:"\u0174",Wedge:"\u22C0",Wfr:"\u{1D51A}",Wopf:"\u{1D54E}",Wscr:"\u{1D4B2}",Xfr:"\u{1D51B}",Xi:"\u039E",Xopf:"\u{1D54F}",Xscr:"\u{1D4B3}",YAcy:"\u042F",YIcy:"\u0407",YUcy:"\u042E",Yacute:"\xDD",Ycirc:"\u0176",Ycy:"\u042B",Yfr:"\u{1D51C}",Yopf:"\u{1D550}",Yscr:"\u{1D4B4}",Yuml:"\u0178",ZHcy:"\u0416",Zacute:"\u0179",Zcaron:"\u017D",Zcy:"\u0417",Zdot:"\u017B",ZeroWidthSpace:"\u200B",Zeta:"\u0396",Zfr:"\u2128",Zopf:"\u2124",Zscr:"\u{1D4B5}",aacute:"\xE1",abreve:"\u0103",ac:"\u223E",acE:"\u223E\u0333",acd:"\u223F",acirc:"\xE2",acute:"\xB4",acy:"\u0430",aelig:"\xE6",af:"\u2061",afr:"\u{1D51E}",agrave:"\xE0",alefsym:"\u2135",aleph:"\u2135",alpha:"\u03B1",amacr:"\u0101",amalg:"\u2A3F",amp:"&",and:"\u2227",andand:"\u2A55",andd:"\u2A5C",andslope:"\u2A58",andv:"\u2A5A",ang:"\u2220",ange:"\u29A4",angle:"\u2220",angmsd:"\u2221",angmsdaa:"\u29A8",angmsdab:"\u29A9",angmsdac:"\u29AA",angmsdad:"\u29AB",angmsdae:"\u29AC",angmsdaf:"\u29AD",angmsdag:"\u29AE",angmsdah:"\u29AF",angrt:"\u221F",angrtvb:"\u22BE",angrtvbd:"\u299D",angsph:"\u2222",angst:"\xC5",angzarr:"\u237C",aogon:"\u0105",aopf:"\u{1D552}",ap:"\u2248",apE:"\u2A70",apacir:"\u2A6F",ape:"\u224A",apid:"\u224B",apos:"'",approx:"\u2248",approxeq:"\u224A",aring:"\xE5",ascr:"\u{1D4B6}",ast:"*",asymp:"\u2248",asympeq:"\u224D",atilde:"\xE3",auml:"\xE4",awconint:"\u2233",awint:"\u2A11",bNot:"\u2AED",backcong:"\u224C",backepsilon:"\u03F6",backprime:"\u2035",backsim:"\u223D",backsimeq:"\u22CD",barvee:"\u22BD",barwed:"\u2305",barwedge:"\u2305",bbrk:"\u23B5",bbrktbrk:"\u23B6",bcong:"\u224C",bcy:"\u0431",bdquo:"\u201E",becaus:"\u2235",because:"\u2235",bemptyv:"\u29B0",bepsi:"\u03F6",bernou:"\u212C",beta:"\u03B2",beth:"\u2136",between:"\u226C",bfr:"\u{1D51F}",bigcap:"\u22C2",bigcirc:"\u25EF",bigcup:"\u22C3",bigodot:"\u2A00",bigoplus:"\u2A01",bigotimes:"\u2A02",bigsqcup:"\u2A06",bigstar:"\u2605",bigtriangledown:"\u25BD",bigtriangleup:"\u25B3",biguplus:"\u2A04",bigvee:"\u22C1",bigwedge:"\u22C0",bkarow:"\u290D",blacklozenge:"\u29EB",blacksquare:"\u25AA",blacktriangle:"\u25B4",blacktriangledown:"\u25BE",blacktriangleleft:"\u25C2",blacktriangleright:"\u25B8",blank:"\u2423",blk12:"\u2592",blk14:"\u2591",blk34:"\u2593",block:"\u2588",bne:"=\u20E5",bnequiv:"\u2261\u20E5",bnot:"\u2310",bopf:"\u{1D553}",bot:"\u22A5",bottom:"\u22A5",bowtie:"\u22C8",boxDL:"\u2557",boxDR:"\u2554",boxDl:"\u2556",boxDr:"\u2553",boxH:"\u2550",boxHD:"\u2566",boxHU:"\u2569",boxHd:"\u2564",boxHu:"\u2567",boxUL:"\u255D",boxUR:"\u255A",boxUl:"\u255C",boxUr:"\u2559",boxV:"\u2551",boxVH:"\u256C",boxVL:"\u2563",boxVR:"\u2560",boxVh:"\u256B",boxVl:"\u2562",boxVr:"\u255F",boxbox:"\u29C9",boxdL:"\u2555",boxdR:"\u2552",boxdl:"\u2510",boxdr:"\u250C",boxh:"\u2500",boxhD:"\u2565",boxhU:"\u2568",boxhd:"\u252C",boxhu:"\u2534",boxminus:"\u229F",boxplus:"\u229E",boxtimes:"\u22A0",boxuL:"\u255B",boxuR:"\u2558",boxul:"\u2518",boxur:"\u2514",boxv:"\u2502",boxvH:"\u256A",boxvL:"\u2561",boxvR:"\u255E",boxvh:"\u253C",boxvl:"\u2524",boxvr:"\u251C",bprime:"\u2035",breve:"\u02D8",brvbar:"\xA6",bscr:"\u{1D4B7}",bsemi:"\u204F",bsim:"\u223D",bsime:"\u22CD",bsol:"\\",bsolb:"\u29C5",bsolhsub:"\u27C8",bull:"\u2022",bullet:"\u2022",bump:"\u224E",bumpE:"\u2AAE",bumpe:"\u224F",bumpeq:"\u224F",cacute:"\u0107",cap:"\u2229",capand:"\u2A44",capbrcup:"\u2A49",capcap:"\u2A4B",capcup:"\u2A47",capdot:"\u2A40",caps:"\u2229\uFE00",caret:"\u2041",caron:"\u02C7",ccaps:"\u2A4D",ccaron:"\u010D",ccedil:"\xE7",ccirc:"\u0109",ccups:"\u2A4C",ccupssm:"\u2A50",cdot:"\u010B",cedil:"\xB8",cemptyv:"\u29B2",cent:"\xA2",centerdot:"\xB7",cfr:"\u{1D520}",chcy:"\u0447",check:"\u2713",checkmark:"\u2713",chi:"\u03C7",cir:"\u25CB",cirE:"\u29C3",circ:"\u02C6",circeq:"\u2257",circlearrowleft:"\u21BA",circlearrowright:"\u21BB",circledR:"\xAE",circledS:"\u24C8",circledast:"\u229B",circledcirc:"\u229A",circleddash:"\u229D",cire:"\u2257",cirfnint:"\u2A10",cirmid:"\u2AEF",cirscir:"\u29C2",clubs:"\u2663",clubsuit:"\u2663",colon:":",colone:"\u2254",coloneq:"\u2254",comma:",",commat:"@",comp:"\u2201",compfn:"\u2218",complement:"\u2201",complexes:"\u2102",cong:"\u2245",congdot:"\u2A6D",conint:"\u222E",copf:"\u{1D554}",coprod:"\u2210",copy:"\xA9",copysr:"\u2117",crarr:"\u21B5",cross:"\u2717",cscr:"\u{1D4B8}",csub:"\u2ACF",csube:"\u2AD1",csup:"\u2AD0",csupe:"\u2AD2",ctdot:"\u22EF",cudarrl:"\u2938",cudarrr:"\u2935",cuepr:"\u22DE",cuesc:"\u22DF",cularr:"\u21B6",cularrp:"\u293D",cup:"\u222A",cupbrcap:"\u2A48",cupcap:"\u2A46",cupcup:"\u2A4A",cupdot:"\u228D",cupor:"\u2A45",cups:"\u222A\uFE00",curarr:"\u21B7",curarrm:"\u293C",curlyeqprec:"\u22DE",curlyeqsucc:"\u22DF",curlyvee:"\u22CE",curlywedge:"\u22CF",curren:"\xA4",curvearrowleft:"\u21B6",curvearrowright:"\u21B7",cuvee:"\u22CE",cuwed:"\u22CF",cwconint:"\u2232",cwint:"\u2231",cylcty:"\u232D",dArr:"\u21D3",dHar:"\u2965",dagger:"\u2020",daleth:"\u2138",darr:"\u2193",dash:"\u2010",dashv:"\u22A3",dbkarow:"\u290F",dblac:"\u02DD",dcaron:"\u010F",dcy:"\u0434",dd:"\u2146",ddagger:"\u2021",ddarr:"\u21CA",ddotseq:"\u2A77",deg:"\xB0",delta:"\u03B4",demptyv:"\u29B1",dfisht:"\u297F",dfr:"\u{1D521}",dharl:"\u21C3",dharr:"\u21C2",diam:"\u22C4",diamond:"\u22C4",diamondsuit:"\u2666",diams:"\u2666",die:"\xA8",digamma:"\u03DD",disin:"\u22F2",div:"\xF7",divide:"\xF7",divideontimes:"\u22C7",divonx:"\u22C7",djcy:"\u0452",dlcorn:"\u231E",dlcrop:"\u230D",dollar:"$",dopf:"\u{1D555}",dot:"\u02D9",doteq:"\u2250",doteqdot:"\u2251",dotminus:"\u2238",dotplus:"\u2214",dotsquare:"\u22A1",doublebarwedge:"\u2306",downarrow:"\u2193",downdownarrows:"\u21CA",downharpoonleft:"\u21C3",downharpoonright:"\u21C2",drbkarow:"\u2910",drcorn:"\u231F",drcrop:"\u230C",dscr:"\u{1D4B9}",dscy:"\u0455",dsol:"\u29F6",dstrok:"\u0111",dtdot:"\u22F1",dtri:"\u25BF",dtrif:"\u25BE",duarr:"\u21F5",duhar:"\u296F",dwangle:"\u29A6",dzcy:"\u045F",dzigrarr:"\u27FF",eDDot:"\u2A77",eDot:"\u2251",eacute:"\xE9",easter:"\u2A6E",ecaron:"\u011B",ecir:"\u2256",ecirc:"\xEA",ecolon:"\u2255",ecy:"\u044D",edot:"\u0117",ee:"\u2147",efDot:"\u2252",efr:"\u{1D522}",eg:"\u2A9A",egrave:"\xE8",egs:"\u2A96",egsdot:"\u2A98",el:"\u2A99",elinters:"\u23E7",ell:"\u2113",els:"\u2A95",elsdot:"\u2A97",emacr:"\u0113",empty:"\u2205",emptyset:"\u2205",emptyv:"\u2205",emsp13:"\u2004",emsp14:"\u2005",emsp:"\u2003",eng:"\u014B",ensp:"\u2002",eogon:"\u0119",eopf:"\u{1D556}",epar:"\u22D5",eparsl:"\u29E3",eplus:"\u2A71",epsi:"\u03B5",epsilon:"\u03B5",epsiv:"\u03F5",eqcirc:"\u2256",eqcolon:"\u2255",eqsim:"\u2242",eqslantgtr:"\u2A96",eqslantless:"\u2A95",equals:"=",equest:"\u225F",equiv:"\u2261",equivDD:"\u2A78",eqvparsl:"\u29E5",erDot:"\u2253",erarr:"\u2971",escr:"\u212F",esdot:"\u2250",esim:"\u2242",eta:"\u03B7",eth:"\xF0",euml:"\xEB",euro:"\u20AC",excl:"!",exist:"\u2203",expectation:"\u2130",exponentiale:"\u2147",fallingdotseq:"\u2252",fcy:"\u0444",female:"\u2640",ffilig:"\uFB03",fflig:"\uFB00",ffllig:"\uFB04",ffr:"\u{1D523}",filig:"\uFB01",fjlig:"fj",flat:"\u266D",fllig:"\uFB02",fltns:"\u25B1",fnof:"\u0192",fopf:"\u{1D557}",forall:"\u2200",fork:"\u22D4",forkv:"\u2AD9",fpartint:"\u2A0D",frac12:"\xBD",frac13:"\u2153",frac14:"\xBC",frac15:"\u2155",frac16:"\u2159",frac18:"\u215B",frac23:"\u2154",frac25:"\u2156",frac34:"\xBE",frac35:"\u2157",frac38:"\u215C",frac45:"\u2158",frac56:"\u215A",frac58:"\u215D",frac78:"\u215E",frasl:"\u2044",frown:"\u2322",fscr:"\u{1D4BB}",gE:"\u2267",gEl:"\u2A8C",gacute:"\u01F5",gamma:"\u03B3",gammad:"\u03DD",gap:"\u2A86",gbreve:"\u011F",gcirc:"\u011D",gcy:"\u0433",gdot:"\u0121",ge:"\u2265",gel:"\u22DB",geq:"\u2265",geqq:"\u2267",geqslant:"\u2A7E",ges:"\u2A7E",gescc:"\u2AA9",gesdot:"\u2A80",gesdoto:"\u2A82",gesdotol:"\u2A84",gesl:"\u22DB\uFE00",gesles:"\u2A94",gfr:"\u{1D524}",gg:"\u226B",ggg:"\u22D9",gimel:"\u2137",gjcy:"\u0453",gl:"\u2277",glE:"\u2A92",gla:"\u2AA5",glj:"\u2AA4",gnE:"\u2269",gnap:"\u2A8A",gnapprox:"\u2A8A",gne:"\u2A88",gneq:"\u2A88",gneqq:"\u2269",gnsim:"\u22E7",gopf:"\u{1D558}",grave:"`",gscr:"\u210A",gsim:"\u2273",gsime:"\u2A8E",gsiml:"\u2A90",gt:">",gtcc:"\u2AA7",gtcir:"\u2A7A",gtdot:"\u22D7",gtlPar:"\u2995",gtquest:"\u2A7C",gtrapprox:"\u2A86",gtrarr:"\u2978",gtrdot:"\u22D7",gtreqless:"\u22DB",gtreqqless:"\u2A8C",gtrless:"\u2277",gtrsim:"\u2273",gvertneqq:"\u2269\uFE00",gvnE:"\u2269\uFE00",hArr:"\u21D4",hairsp:"\u200A",half:"\xBD",hamilt:"\u210B",hardcy:"\u044A",harr:"\u2194",harrcir:"\u2948",harrw:"\u21AD",hbar:"\u210F",hcirc:"\u0125",hearts:"\u2665",heartsuit:"\u2665",hellip:"\u2026",hercon:"\u22B9",hfr:"\u{1D525}",hksearow:"\u2925",hkswarow:"\u2926",hoarr:"\u21FF",homtht:"\u223B",hookleftarrow:"\u21A9",hookrightarrow:"\u21AA",hopf:"\u{1D559}",horbar:"\u2015",hscr:"\u{1D4BD}",hslash:"\u210F",hstrok:"\u0127",hybull:"\u2043",hyphen:"\u2010",iacute:"\xED",ic:"\u2063",icirc:"\xEE",icy:"\u0438",iecy:"\u0435",iexcl:"\xA1",iff:"\u21D4",ifr:"\u{1D526}",igrave:"\xEC",ii:"\u2148",iiiint:"\u2A0C",iiint:"\u222D",iinfin:"\u29DC",iiota:"\u2129",ijlig:"\u0133",imacr:"\u012B",image:"\u2111",imagline:"\u2110",imagpart:"\u2111",imath:"\u0131",imof:"\u22B7",imped:"\u01B5",in:"\u2208",incare:"\u2105",infin:"\u221E",infintie:"\u29DD",inodot:"\u0131",int:"\u222B",intcal:"\u22BA",integers:"\u2124",intercal:"\u22BA",intlarhk:"\u2A17",intprod:"\u2A3C",iocy:"\u0451",iogon:"\u012F",iopf:"\u{1D55A}",iota:"\u03B9",iprod:"\u2A3C",iquest:"\xBF",iscr:"\u{1D4BE}",isin:"\u2208",isinE:"\u22F9",isindot:"\u22F5",isins:"\u22F4",isinsv:"\u22F3",isinv:"\u2208",it:"\u2062",itilde:"\u0129",iukcy:"\u0456",iuml:"\xEF",jcirc:"\u0135",jcy:"\u0439",jfr:"\u{1D527}",jmath:"\u0237",jopf:"\u{1D55B}",jscr:"\u{1D4BF}",jsercy:"\u0458",jukcy:"\u0454",kappa:"\u03BA",kappav:"\u03F0",kcedil:"\u0137",kcy:"\u043A",kfr:"\u{1D528}",kgreen:"\u0138",khcy:"\u0445",kjcy:"\u045C",kopf:"\u{1D55C}",kscr:"\u{1D4C0}",lAarr:"\u21DA",lArr:"\u21D0",lAtail:"\u291B",lBarr:"\u290E",lE:"\u2266",lEg:"\u2A8B",lHar:"\u2962",lacute:"\u013A",laemptyv:"\u29B4",lagran:"\u2112",lambda:"\u03BB",lang:"\u27E8",langd:"\u2991",langle:"\u27E8",lap:"\u2A85",laquo:"\xAB",larr:"\u2190",larrb:"\u21E4",larrbfs:"\u291F",larrfs:"\u291D",larrhk:"\u21A9",larrlp:"\u21AB",larrpl:"\u2939",larrsim:"\u2973",larrtl:"\u21A2",lat:"\u2AAB",latail:"\u2919",late:"\u2AAD",lates:"\u2AAD\uFE00",lbarr:"\u290C",lbbrk:"\u2772",lbrace:"{",lbrack:"[",lbrke:"\u298B",lbrksld:"\u298F",lbrkslu:"\u298D",lcaron:"\u013E",lcedil:"\u013C",lceil:"\u2308",lcub:"{",lcy:"\u043B",ldca:"\u2936",ldquo:"\u201C",ldquor:"\u201E",ldrdhar:"\u2967",ldrushar:"\u294B",ldsh:"\u21B2",le:"\u2264",leftarrow:"\u2190",leftarrowtail:"\u21A2",leftharpoondown:"\u21BD",leftharpoonup:"\u21BC",leftleftarrows:"\u21C7",leftrightarrow:"\u2194",leftrightarrows:"\u21C6",leftrightharpoons:"\u21CB",leftrightsquigarrow:"\u21AD",leftthreetimes:"\u22CB",leg:"\u22DA",leq:"\u2264",leqq:"\u2266",leqslant:"\u2A7D",les:"\u2A7D",lescc:"\u2AA8",lesdot:"\u2A7F",lesdoto:"\u2A81",lesdotor:"\u2A83",lesg:"\u22DA\uFE00",lesges:"\u2A93",lessapprox:"\u2A85",lessdot:"\u22D6",lesseqgtr:"\u22DA",lesseqqgtr:"\u2A8B",lessgtr:"\u2276",lesssim:"\u2272",lfisht:"\u297C",lfloor:"\u230A",lfr:"\u{1D529}",lg:"\u2276",lgE:"\u2A91",lhard:"\u21BD",lharu:"\u21BC",lharul:"\u296A",lhblk:"\u2584",ljcy:"\u0459",ll:"\u226A",llarr:"\u21C7",llcorner:"\u231E",llhard:"\u296B",lltri:"\u25FA",lmidot:"\u0140",lmoust:"\u23B0",lmoustache:"\u23B0",lnE:"\u2268",lnap:"\u2A89",lnapprox:"\u2A89",lne:"\u2A87",lneq:"\u2A87",lneqq:"\u2268",lnsim:"\u22E6",loang:"\u27EC",loarr:"\u21FD",lobrk:"\u27E6",longleftarrow:"\u27F5",longleftrightarrow:"\u27F7",longmapsto:"\u27FC",longrightarrow:"\u27F6",looparrowleft:"\u21AB",looparrowright:"\u21AC",lopar:"\u2985",lopf:"\u{1D55D}",loplus:"\u2A2D",lotimes:"\u2A34",lowast:"\u2217",lowbar:"_",loz:"\u25CA",lozenge:"\u25CA",lozf:"\u29EB",lpar:"(",lparlt:"\u2993",lrarr:"\u21C6",lrcorner:"\u231F",lrhar:"\u21CB",lrhard:"\u296D",lrm:"\u200E",lrtri:"\u22BF",lsaquo:"\u2039",lscr:"\u{1D4C1}",lsh:"\u21B0",lsim:"\u2272",lsime:"\u2A8D",lsimg:"\u2A8F",lsqb:"[",lsquo:"\u2018",lsquor:"\u201A",lstrok:"\u0142",lt:"<",ltcc:"\u2AA6",ltcir:"\u2A79",ltdot:"\u22D6",lthree:"\u22CB",ltimes:"\u22C9",ltlarr:"\u2976",ltquest:"\u2A7B",ltrPar:"\u2996",ltri:"\u25C3",ltrie:"\u22B4",ltrif:"\u25C2",lurdshar:"\u294A",luruhar:"\u2966",lvertneqq:"\u2268\uFE00",lvnE:"\u2268\uFE00",mDDot:"\u223A",macr:"\xAF",male:"\u2642",malt:"\u2720",maltese:"\u2720",map:"\u21A6",mapsto:"\u21A6",mapstodown:"\u21A7",mapstoleft:"\u21A4",mapstoup:"\u21A5",marker:"\u25AE",mcomma:"\u2A29",mcy:"\u043C",mdash:"\u2014",measuredangle:"\u2221",mfr:"\u{1D52A}",mho:"\u2127",micro:"\xB5",mid:"\u2223",midast:"*",midcir:"\u2AF0",middot:"\xB7",minus:"\u2212",minusb:"\u229F",minusd:"\u2238",minusdu:"\u2A2A",mlcp:"\u2ADB",mldr:"\u2026",mnplus:"\u2213",models:"\u22A7",mopf:"\u{1D55E}",mp:"\u2213",mscr:"\u{1D4C2}",mstpos:"\u223E",mu:"\u03BC",multimap:"\u22B8",mumap:"\u22B8",nGg:"\u22D9\u0338",nGt:"\u226B\u20D2",nGtv:"\u226B\u0338",nLeftarrow:"\u21CD",nLeftrightarrow:"\u21CE",nLl:"\u22D8\u0338",nLt:"\u226A\u20D2",nLtv:"\u226A\u0338",nRightarrow:"\u21CF",nVDash:"\u22AF",nVdash:"\u22AE",nabla:"\u2207",nacute:"\u0144",nang:"\u2220\u20D2",nap:"\u2249",napE:"\u2A70\u0338",napid:"\u224B\u0338",napos:"\u0149",napprox:"\u2249",natur:"\u266E",natural:"\u266E",naturals:"\u2115",nbsp:"\xA0",nbump:"\u224E\u0338",nbumpe:"\u224F\u0338",ncap:"\u2A43",ncaron:"\u0148",ncedil:"\u0146",ncong:"\u2247",ncongdot:"\u2A6D\u0338",ncup:"\u2A42",ncy:"\u043D",ndash:"\u2013",ne:"\u2260",neArr:"\u21D7",nearhk:"\u2924",nearr:"\u2197",nearrow:"\u2197",nedot:"\u2250\u0338",nequiv:"\u2262",nesear:"\u2928",nesim:"\u2242\u0338",nexist:"\u2204",nexists:"\u2204",nfr:"\u{1D52B}",ngE:"\u2267\u0338",nge:"\u2271",ngeq:"\u2271",ngeqq:"\u2267\u0338",ngeqslant:"\u2A7E\u0338",nges:"\u2A7E\u0338",ngsim:"\u2275",ngt:"\u226F",ngtr:"\u226F",nhArr:"\u21CE",nharr:"\u21AE",nhpar:"\u2AF2",ni:"\u220B",nis:"\u22FC",nisd:"\u22FA",niv:"\u220B",njcy:"\u045A",nlArr:"\u21CD",nlE:"\u2266\u0338",nlarr:"\u219A",nldr:"\u2025",nle:"\u2270",nleftarrow:"\u219A",nleftrightarrow:"\u21AE",nleq:"\u2270",nleqq:"\u2266\u0338",nleqslant:"\u2A7D\u0338",nles:"\u2A7D\u0338",nless:"\u226E",nlsim:"\u2274",nlt:"\u226E",nltri:"\u22EA",nltrie:"\u22EC",nmid:"\u2224",nopf:"\u{1D55F}",not:"\xAC",notin:"\u2209",notinE:"\u22F9\u0338",notindot:"\u22F5\u0338",notinva:"\u2209",notinvb:"\u22F7",notinvc:"\u22F6",notni:"\u220C",notniva:"\u220C",notnivb:"\u22FE",notnivc:"\u22FD",npar:"\u2226",nparallel:"\u2226",nparsl:"\u2AFD\u20E5",npart:"\u2202\u0338",npolint:"\u2A14",npr:"\u2280",nprcue:"\u22E0",npre:"\u2AAF\u0338",nprec:"\u2280",npreceq:"\u2AAF\u0338",nrArr:"\u21CF",nrarr:"\u219B",nrarrc:"\u2933\u0338",nrarrw:"\u219D\u0338",nrightarrow:"\u219B",nrtri:"\u22EB",nrtrie:"\u22ED",nsc:"\u2281",nsccue:"\u22E1",nsce:"\u2AB0\u0338",nscr:"\u{1D4C3}",nshortmid:"\u2224",nshortparallel:"\u2226",nsim:"\u2241",nsime:"\u2244",nsimeq:"\u2244",nsmid:"\u2224",nspar:"\u2226",nsqsube:"\u22E2",nsqsupe:"\u22E3",nsub:"\u2284",nsubE:"\u2AC5\u0338",nsube:"\u2288",nsubset:"\u2282\u20D2",nsubseteq:"\u2288",nsubseteqq:"\u2AC5\u0338",nsucc:"\u2281",nsucceq:"\u2AB0\u0338",nsup:"\u2285",nsupE:"\u2AC6\u0338",nsupe:"\u2289",nsupset:"\u2283\u20D2",nsupseteq:"\u2289",nsupseteqq:"\u2AC6\u0338",ntgl:"\u2279",ntilde:"\xF1",ntlg:"\u2278",ntriangleleft:"\u22EA",ntrianglelefteq:"\u22EC",ntriangleright:"\u22EB",ntrianglerighteq:"\u22ED",nu:"\u03BD",num:"#",numero:"\u2116",numsp:"\u2007",nvDash:"\u22AD",nvHarr:"\u2904",nvap:"\u224D\u20D2",nvdash:"\u22AC",nvge:"\u2265\u20D2",nvgt:">\u20D2",nvinfin:"\u29DE",nvlArr:"\u2902",nvle:"\u2264\u20D2",nvlt:"<\u20D2",nvltrie:"\u22B4\u20D2",nvrArr:"\u2903",nvrtrie:"\u22B5\u20D2",nvsim:"\u223C\u20D2",nwArr:"\u21D6",nwarhk:"\u2923",nwarr:"\u2196",nwarrow:"\u2196",nwnear:"\u2927",oS:"\u24C8",oacute:"\xF3",oast:"\u229B",ocir:"\u229A",ocirc:"\xF4",ocy:"\u043E",odash:"\u229D",odblac:"\u0151",odiv:"\u2A38",odot:"\u2299",odsold:"\u29BC",oelig:"\u0153",ofcir:"\u29BF",ofr:"\u{1D52C}",ogon:"\u02DB",ograve:"\xF2",ogt:"\u29C1",ohbar:"\u29B5",ohm:"\u03A9",oint:"\u222E",olarr:"\u21BA",olcir:"\u29BE",olcross:"\u29BB",oline:"\u203E",olt:"\u29C0",omacr:"\u014D",omega:"\u03C9",omicron:"\u03BF",omid:"\u29B6",ominus:"\u2296",oopf:"\u{1D560}",opar:"\u29B7",operp:"\u29B9",oplus:"\u2295",or:"\u2228",orarr:"\u21BB",ord:"\u2A5D",order:"\u2134",orderof:"\u2134",ordf:"\xAA",ordm:"\xBA",origof:"\u22B6",oror:"\u2A56",orslope:"\u2A57",orv:"\u2A5B",oscr:"\u2134",oslash:"\xF8",osol:"\u2298",otilde:"\xF5",otimes:"\u2297",otimesas:"\u2A36",ouml:"\xF6",ovbar:"\u233D",par:"\u2225",para:"\xB6",parallel:"\u2225",parsim:"\u2AF3",parsl:"\u2AFD",part:"\u2202",pcy:"\u043F",percnt:"%",period:".",permil:"\u2030",perp:"\u22A5",pertenk:"\u2031",pfr:"\u{1D52D}",phi:"\u03C6",phiv:"\u03D5",phmmat:"\u2133",phone:"\u260E",pi:"\u03C0",pitchfork:"\u22D4",piv:"\u03D6",planck:"\u210F",planckh:"\u210E",plankv:"\u210F",plus:"+",plusacir:"\u2A23",plusb:"\u229E",pluscir:"\u2A22",plusdo:"\u2214",plusdu:"\u2A25",pluse:"\u2A72",plusmn:"\xB1",plussim:"\u2A26",plustwo:"\u2A27",pm:"\xB1",pointint:"\u2A15",popf:"\u{1D561}",pound:"\xA3",pr:"\u227A",prE:"\u2AB3",prap:"\u2AB7",prcue:"\u227C",pre:"\u2AAF",prec:"\u227A",precapprox:"\u2AB7",preccurlyeq:"\u227C",preceq:"\u2AAF",precnapprox:"\u2AB9",precneqq:"\u2AB5",precnsim:"\u22E8",precsim:"\u227E",prime:"\u2032",primes:"\u2119",prnE:"\u2AB5",prnap:"\u2AB9",prnsim:"\u22E8",prod:"\u220F",profalar:"\u232E",profline:"\u2312",profsurf:"\u2313",prop:"\u221D",propto:"\u221D",prsim:"\u227E",prurel:"\u22B0",pscr:"\u{1D4C5}",psi:"\u03C8",puncsp:"\u2008",qfr:"\u{1D52E}",qint:"\u2A0C",qopf:"\u{1D562}",qprime:"\u2057",qscr:"\u{1D4C6}",quaternions:"\u210D",quatint:"\u2A16",quest:"?",questeq:"\u225F",quot:'"',rAarr:"\u21DB",rArr:"\u21D2",rAtail:"\u291C",rBarr:"\u290F",rHar:"\u2964",race:"\u223D\u0331",racute:"\u0155",radic:"\u221A",raemptyv:"\u29B3",rang:"\u27E9",rangd:"\u2992",range:"\u29A5",rangle:"\u27E9",raquo:"\xBB",rarr:"\u2192",rarrap:"\u2975",rarrb:"\u21E5",rarrbfs:"\u2920",rarrc:"\u2933",rarrfs:"\u291E",rarrhk:"\u21AA",rarrlp:"\u21AC",rarrpl:"\u2945",rarrsim:"\u2974",rarrtl:"\u21A3",rarrw:"\u219D",ratail:"\u291A",ratio:"\u2236",rationals:"\u211A",rbarr:"\u290D",rbbrk:"\u2773",rbrace:"}",rbrack:"]",rbrke:"\u298C",rbrksld:"\u298E",rbrkslu:"\u2990",rcaron:"\u0159",rcedil:"\u0157",rceil:"\u2309",rcub:"}",rcy:"\u0440",rdca:"\u2937",rdldhar:"\u2969",rdquo:"\u201D",rdquor:"\u201D",rdsh:"\u21B3",real:"\u211C",realine:"\u211B",realpart:"\u211C",reals:"\u211D",rect:"\u25AD",reg:"\xAE",rfisht:"\u297D",rfloor:"\u230B",rfr:"\u{1D52F}",rhard:"\u21C1",rharu:"\u21C0",rharul:"\u296C",rho:"\u03C1",rhov:"\u03F1",rightarrow:"\u2192",rightarrowtail:"\u21A3",rightharpoondown:"\u21C1",rightharpoonup:"\u21C0",rightleftarrows:"\u21C4",rightleftharpoons:"\u21CC",rightrightarrows:"\u21C9",rightsquigarrow:"\u219D",rightthreetimes:"\u22CC",ring:"\u02DA",risingdotseq:"\u2253",rlarr:"\u21C4",rlhar:"\u21CC",rlm:"\u200F",rmoust:"\u23B1",rmoustache:"\u23B1",rnmid:"\u2AEE",roang:"\u27ED",roarr:"\u21FE",robrk:"\u27E7",ropar:"\u2986",ropf:"\u{1D563}",roplus:"\u2A2E",rotimes:"\u2A35",rpar:")",rpargt:"\u2994",rppolint:"\u2A12",rrarr:"\u21C9",rsaquo:"\u203A",rscr:"\u{1D4C7}",rsh:"\u21B1",rsqb:"]",rsquo:"\u2019",rsquor:"\u2019",rthree:"\u22CC",rtimes:"\u22CA",rtri:"\u25B9",rtrie:"\u22B5",rtrif:"\u25B8",rtriltri:"\u29CE",ruluhar:"\u2968",rx:"\u211E",sacute:"\u015B",sbquo:"\u201A",sc:"\u227B",scE:"\u2AB4",scap:"\u2AB8",scaron:"\u0161",sccue:"\u227D",sce:"\u2AB0",scedil:"\u015F",scirc:"\u015D",scnE:"\u2AB6",scnap:"\u2ABA",scnsim:"\u22E9",scpolint:"\u2A13",scsim:"\u227F",scy:"\u0441",sdot:"\u22C5",sdotb:"\u22A1",sdote:"\u2A66",seArr:"\u21D8",searhk:"\u2925",searr:"\u2198",searrow:"\u2198",sect:"\xA7",semi:";",seswar:"\u2929",setminus:"\u2216",setmn:"\u2216",sext:"\u2736",sfr:"\u{1D530}",sfrown:"\u2322",sharp:"\u266F",shchcy:"\u0449",shcy:"\u0448",shortmid:"\u2223",shortparallel:"\u2225",shy:"\xAD",sigma:"\u03C3",sigmaf:"\u03C2",sigmav:"\u03C2",sim:"\u223C",simdot:"\u2A6A",sime:"\u2243",simeq:"\u2243",simg:"\u2A9E",simgE:"\u2AA0",siml:"\u2A9D",simlE:"\u2A9F",simne:"\u2246",simplus:"\u2A24",simrarr:"\u2972",slarr:"\u2190",smallsetminus:"\u2216",smashp:"\u2A33",smeparsl:"\u29E4",smid:"\u2223",smile:"\u2323",smt:"\u2AAA",smte:"\u2AAC",smtes:"\u2AAC\uFE00",softcy:"\u044C",sol:"/",solb:"\u29C4",solbar:"\u233F",sopf:"\u{1D564}",spades:"\u2660",spadesuit:"\u2660",spar:"\u2225",sqcap:"\u2293",sqcaps:"\u2293\uFE00",sqcup:"\u2294",sqcups:"\u2294\uFE00",sqsub:"\u228F",sqsube:"\u2291",sqsubset:"\u228F",sqsubseteq:"\u2291",sqsup:"\u2290",sqsupe:"\u2292",sqsupset:"\u2290",sqsupseteq:"\u2292",squ:"\u25A1",square:"\u25A1",squarf:"\u25AA",squf:"\u25AA",srarr:"\u2192",sscr:"\u{1D4C8}",ssetmn:"\u2216",ssmile:"\u2323",sstarf:"\u22C6",star:"\u2606",starf:"\u2605",straightepsilon:"\u03F5",straightphi:"\u03D5",strns:"\xAF",sub:"\u2282",subE:"\u2AC5",subdot:"\u2ABD",sube:"\u2286",subedot:"\u2AC3",submult:"\u2AC1",subnE:"\u2ACB",subne:"\u228A",subplus:"\u2ABF",subrarr:"\u2979",subset:"\u2282",subseteq:"\u2286",subseteqq:"\u2AC5",subsetneq:"\u228A",subsetneqq:"\u2ACB",subsim:"\u2AC7",subsub:"\u2AD5",subsup:"\u2AD3",succ:"\u227B",succapprox:"\u2AB8",succcurlyeq:"\u227D",succeq:"\u2AB0",succnapprox:"\u2ABA",succneqq:"\u2AB6",succnsim:"\u22E9",succsim:"\u227F",sum:"\u2211",sung:"\u266A",sup1:"\xB9",sup2:"\xB2",sup3:"\xB3",sup:"\u2283",supE:"\u2AC6",supdot:"\u2ABE",supdsub:"\u2AD8",supe:"\u2287",supedot:"\u2AC4",suphsol:"\u27C9",suphsub:"\u2AD7",suplarr:"\u297B",supmult:"\u2AC2",supnE:"\u2ACC",supne:"\u228B",supplus:"\u2AC0",supset:"\u2283",supseteq:"\u2287",supseteqq:"\u2AC6",supsetneq:"\u228B",supsetneqq:"\u2ACC",supsim:"\u2AC8",supsub:"\u2AD4",supsup:"\u2AD6",swArr:"\u21D9",swarhk:"\u2926",swarr:"\u2199",swarrow:"\u2199",swnwar:"\u292A",szlig:"\xDF",target:"\u2316",tau:"\u03C4",tbrk:"\u23B4",tcaron:"\u0165",tcedil:"\u0163",tcy:"\u0442",tdot:"\u20DB",telrec:"\u2315",tfr:"\u{1D531}",there4:"\u2234",therefore:"\u2234",theta:"\u03B8",thetasym:"\u03D1",thetav:"\u03D1",thickapprox:"\u2248",thicksim:"\u223C",thinsp:"\u2009",thkap:"\u2248",thksim:"\u223C",thorn:"\xFE",tilde:"\u02DC",times:"\xD7",timesb:"\u22A0",timesbar:"\u2A31",timesd:"\u2A30",tint:"\u222D",toea:"\u2928",top:"\u22A4",topbot:"\u2336",topcir:"\u2AF1",topf:"\u{1D565}",topfork:"\u2ADA",tosa:"\u2929",tprime:"\u2034",trade:"\u2122",triangle:"\u25B5",triangledown:"\u25BF",triangleleft:"\u25C3",trianglelefteq:"\u22B4",triangleq:"\u225C",triangleright:"\u25B9",trianglerighteq:"\u22B5",tridot:"\u25EC",trie:"\u225C",triminus:"\u2A3A",triplus:"\u2A39",trisb:"\u29CD",tritime:"\u2A3B",trpezium:"\u23E2",tscr:"\u{1D4C9}",tscy:"\u0446",tshcy:"\u045B",tstrok:"\u0167",twixt:"\u226C",twoheadleftarrow:"\u219E",twoheadrightarrow:"\u21A0",uArr:"\u21D1",uHar:"\u2963",uacute:"\xFA",uarr:"\u2191",ubrcy:"\u045E",ubreve:"\u016D",ucirc:"\xFB",ucy:"\u0443",udarr:"\u21C5",udblac:"\u0171",udhar:"\u296E",ufisht:"\u297E",ufr:"\u{1D532}",ugrave:"\xF9",uharl:"\u21BF",uharr:"\u21BE",uhblk:"\u2580",ulcorn:"\u231C",ulcorner:"\u231C",ulcrop:"\u230F",ultri:"\u25F8",umacr:"\u016B",uml:"\xA8",uogon:"\u0173",uopf:"\u{1D566}",uparrow:"\u2191",updownarrow:"\u2195",upharpoonleft:"\u21BF",upharpoonright:"\u21BE",uplus:"\u228E",upsi:"\u03C5",upsih:"\u03D2",upsilon:"\u03C5",upuparrows:"\u21C8",urcorn:"\u231D",urcorner:"\u231D",urcrop:"\u230E",uring:"\u016F",urtri:"\u25F9",uscr:"\u{1D4CA}",utdot:"\u22F0",utilde:"\u0169",utri:"\u25B5",utrif:"\u25B4",uuarr:"\u21C8",uuml:"\xFC",uwangle:"\u29A7",vArr:"\u21D5",vBar:"\u2AE8",vBarv:"\u2AE9",vDash:"\u22A8",vangrt:"\u299C",varepsilon:"\u03F5",varkappa:"\u03F0",varnothing:"\u2205",varphi:"\u03D5",varpi:"\u03D6",varpropto:"\u221D",varr:"\u2195",varrho:"\u03F1",varsigma:"\u03C2",varsubsetneq:"\u228A\uFE00",varsubsetneqq:"\u2ACB\uFE00",varsupsetneq:"\u228B\uFE00",varsupsetneqq:"\u2ACC\uFE00",vartheta:"\u03D1",vartriangleleft:"\u22B2",vartriangleright:"\u22B3",vcy:"\u0432",vdash:"\u22A2",vee:"\u2228",veebar:"\u22BB",veeeq:"\u225A",vellip:"\u22EE",verbar:"|",vert:"|",vfr:"\u{1D533}",vltri:"\u22B2",vnsub:"\u2282\u20D2",vnsup:"\u2283\u20D2",vopf:"\u{1D567}",vprop:"\u221D",vrtri:"\u22B3",vscr:"\u{1D4CB}",vsubnE:"\u2ACB\uFE00",vsubne:"\u228A\uFE00",vsupnE:"\u2ACC\uFE00",vsupne:"\u228B\uFE00",vzigzag:"\u299A",wcirc:"\u0175",wedbar:"\u2A5F",wedge:"\u2227",wedgeq:"\u2259",weierp:"\u2118",wfr:"\u{1D534}",wopf:"\u{1D568}",wp:"\u2118",wr:"\u2240",wreath:"\u2240",wscr:"\u{1D4CC}",xcap:"\u22C2",xcirc:"\u25EF",xcup:"\u22C3",xdtri:"\u25BD",xfr:"\u{1D535}",xhArr:"\u27FA",xharr:"\u27F7",xi:"\u03BE",xlArr:"\u27F8",xlarr:"\u27F5",xmap:"\u27FC",xnis:"\u22FB",xodot:"\u2A00",xopf:"\u{1D569}",xoplus:"\u2A01",xotime:"\u2A02",xrArr:"\u27F9",xrarr:"\u27F6",xscr:"\u{1D4CD}",xsqcup:"\u2A06",xuplus:"\u2A04",xutri:"\u25B3",xvee:"\u22C1",xwedge:"\u22C0",yacute:"\xFD",yacy:"\u044F",ycirc:"\u0177",ycy:"\u044B",yen:"\xA5",yfr:"\u{1D536}",yicy:"\u0457",yopf:"\u{1D56A}",yscr:"\u{1D4CE}",yucy:"\u044E",yuml:"\xFF",zacute:"\u017A",zcaron:"\u017E",zcy:"\u0437",zdot:"\u017C",zeetrf:"\u2128",zeta:"\u03B6",zfr:"\u{1D537}",zhcy:"\u0436",zigrarr:"\u21DD",zopf:"\u{1D56B}",zscr:"\u{1D4CF}",zwj:"\u200D",zwnj:"\u200C"};var ZS={}.hasOwnProperty;function Wr(e){return ZS.call(gl,e)?gl[e]:!1}var Ba={name:"characterReference",tokenize:JS};function JS(e,t,r){let n=this,i=0,s,o;return u;function u(p){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(p),e.exit("characterReferenceMarker"),c}function c(p){return p===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(p),e.exit("characterReferenceMarkerNumeric"),f):(e.enter("characterReferenceValue"),s=31,o=Ue,h(p))}function f(p){return p===88||p===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(p),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),s=6,o=nx,h):(e.enter("characterReferenceValue"),s=7,o=js,h(p))}function h(p){if(p===59&&i){let m=e.exit("characterReferenceValue");return o===Ue&&!Wr(n.sliceSerialize(m))?r(p):(e.enter("characterReferenceMarker"),e.consume(p),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return o(p)&&i++<s?(e.consume(p),h):r(p)}}var Gx={tokenize:QS,partial:!0},Ma={name:"codeFenced",tokenize:GS,concrete:!0};function GS(e,t,r){let n=this,i={tokenize:I,partial:!0},s=0,o=0,u;return c;function c(_){return f(_)}function f(_){let D=n.events[n.events.length-1];return s=D&&D[1].type==="linePrefix"?D[2].sliceSerialize(D[1],!0).length:0,u=_,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),h(_)}function h(_){return _===u?(o++,e.consume(_),h):o<3?r(_):(e.exit("codeFencedFenceSequence"),W(_)?te(e,p,"whitespace")(_):p(_))}function p(_){return _===null||j(_)?(e.exit("codeFencedFence"),n.interrupt?t(_):e.check(Gx,b,g)(_)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),m(_))}function m(_){return _===null||j(_)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),p(_)):W(_)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),te(e,d,"whitespace")(_)):_===96&&_===u?r(_):(e.consume(_),m)}function d(_){return _===null||j(_)?p(_):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),x(_))}function x(_){return _===null||j(_)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),p(_)):_===96&&_===u?r(_):(e.consume(_),x)}function b(_){return e.attempt(i,g,v)(_)}function v(_){return e.enter("lineEnding"),e.consume(_),e.exit("lineEnding"),k}function k(_){return s>0&&W(_)?te(e,T,"linePrefix",s+1)(_):T(_)}function T(_){return _===null||j(_)?e.check(Gx,b,g)(_):(e.enter("codeFlowValue"),E(_))}function E(_){return _===null||j(_)?(e.exit("codeFlowValue"),T(_)):(e.consume(_),E)}function g(_){return e.exit("codeFenced"),t(_)}function I(_,D,O){let M=0;return P;function P(re){return _.enter("lineEnding"),_.consume(re),_.exit("lineEnding"),J}function J(re){return _.enter("codeFencedFence"),W(re)?te(_,V,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(re):V(re)}function V(re){return re===u?(_.enter("codeFencedFenceSequence"),q(re)):O(re)}function q(re){return re===u?(M++,_.consume(re),q):M>=o?(_.exit("codeFencedFenceSequence"),W(re)?te(_,ee,"whitespace")(re):ee(re)):O(re)}function ee(re){return re===null||j(re)?(_.exit("codeFencedFence"),D(re)):O(re)}}}function QS(e,t,r){let n=this;return i;function i(o){return o===null?r(o):(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),s)}function s(o){return n.parser.lazy[n.now().line]?r(o):t(o)}}var Hs={name:"codeIndented",tokenize:WS},HS={tokenize:KS,partial:!0};function WS(e,t,r){let n=this;return i;function i(f){return e.enter("codeIndented"),te(e,s,"linePrefix",5)(f)}function s(f){let h=n.events[n.events.length-1];return h&&h[1].type==="linePrefix"&&h[2].sliceSerialize(h[1],!0).length>=4?o(f):r(f)}function o(f){return f===null?c(f):j(f)?e.attempt(HS,o,c)(f):(e.enter("codeFlowValue"),u(f))}function u(f){return f===null||j(f)?(e.exit("codeFlowValue"),o(f)):(e.consume(f),u)}function c(f){return e.exit("codeIndented"),t(f)}}function KS(e,t,r){let n=this;return i;function i(o){return n.parser.lazy[n.now().line]?r(o):j(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),i):te(e,s,"linePrefix",5)(o)}function s(o){let u=n.events[n.events.length-1];return u&&u[1].type==="linePrefix"&&u[2].sliceSerialize(u[1],!0).length>=4?t(o):j(o)?i(o):r(o)}}var yl={name:"codeText",tokenize:eE,resolve:XS,previous:YS};function XS(e){let t=e.length-4,r=3,n,i;if((e[r][1].type==="lineEnding"||e[r][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(n=r;++n<t;)if(e[n][1].type==="codeTextData"){e[r][1].type="codeTextPadding",e[t][1].type="codeTextPadding",r+=2,t-=2;break}}for(n=r-1,t++;++n<=t;)i===void 0?n!==t&&e[n][1].type!=="lineEnding"&&(i=n):(n===t||e[n][1].type==="lineEnding")&&(e[i][1].type="codeTextData",n!==i+2&&(e[i][1].end=e[n-1][1].end,e.splice(i+2,n-i-2),t-=n-i-2,n=i+2),i=void 0);return e}function YS(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function eE(e,t,r){let n=this,i=0,s,o;return u;function u(m){return e.enter("codeText"),e.enter("codeTextSequence"),c(m)}function c(m){return m===96?(e.consume(m),i++,c):(e.exit("codeTextSequence"),f(m))}function f(m){return m===null?r(m):m===32?(e.enter("space"),e.consume(m),e.exit("space"),f):m===96?(o=e.enter("codeTextSequence"),s=0,p(m)):j(m)?(e.enter("lineEnding"),e.consume(m),e.exit("lineEnding"),f):(e.enter("codeTextData"),h(m))}function h(m){return m===null||m===32||m===96||j(m)?(e.exit("codeTextData"),f(m)):(e.consume(m),h)}function p(m){return m===96?(e.consume(m),s++,p):s===i?(e.exit("codeTextSequence"),e.exit("codeText"),t(m)):(o.type="codeTextData",h(m))}}function Va(e){let t={},r=-1,n,i,s,o,u,c,f;for(;++r<e.length;){for(;r in t;)r=t[r];if(n=e[r],r&&n[1].type==="chunkFlow"&&e[r-1][1].type==="listItemPrefix"&&(c=n[1]._tokenizer.events,s=0,s<c.length&&c[s][1].type==="lineEndingBlank"&&(s+=2),s<c.length&&c[s][1].type==="content"))for(;++s<c.length&&c[s][1].type!=="content";)c[s][1].type==="chunkText"&&(c[s][1]._isInFirstContentOfListItem=!0,s++);if(n[0]==="enter")n[1].contentType&&(Object.assign(t,tE(e,r)),r=t[r],f=!0);else if(n[1]._container){for(s=r,i=void 0;s--&&(o=e[s],o[1].type==="lineEnding"||o[1].type==="lineEndingBlank");)o[0]==="enter"&&(i&&(e[i][1].type="lineEndingBlank"),o[1].type="lineEnding",i=s);i&&(n[1].end=Object.assign({},e[i][1].start),u=e.slice(i,r),u.unshift(n),Je(e,i,r-i+1,u))}}return!f}function tE(e,t){let r=e[t][1],n=e[t][2],i=t-1,s=[],o=r._tokenizer||n.parser[r.contentType](r.start),u=o.events,c=[],f={},h,p,m=-1,d=r,x=0,b=0,v=[b];for(;d;){for(;e[++i][1]!==d;);s.push(i),d._tokenizer||(h=n.sliceStream(d),d.next||h.push(null),p&&o.defineSkip(d.start),d._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=!0),o.write(h),d._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=void 0)),p=d,d=d.next}for(d=r;++m<u.length;)u[m][0]==="exit"&&u[m-1][0]==="enter"&&u[m][1].type===u[m-1][1].type&&u[m][1].start.line!==u[m][1].end.line&&(b=m+1,v.push(b),d._tokenizer=void 0,d.previous=void 0,d=d.next);for(o.events=[],d?(d._tokenizer=void 0,d.previous=void 0):v.pop(),m=v.length;m--;){let k=u.slice(v[m],v[m+1]),T=s.pop();c.unshift([T,T+k.length-1]),Je(e,T,2,k)}for(m=-1;++m<c.length;)f[x+c[m][0]]=x+c[m][1],x+=c[m][1]-c[m][0]-1;return f}var xl={tokenize:iE,resolve:nE},rE={tokenize:sE,partial:!0};function nE(e){return Va(e),e}function iE(e,t){let r;return n;function n(u){return e.enter("content"),r=e.enter("chunkContent",{contentType:"content"}),i(u)}function i(u){return u===null?s(u):j(u)?e.check(rE,o,s)(u):(e.consume(u),i)}function s(u){return e.exit("chunkContent"),e.exit("content"),t(u)}function o(u){return e.consume(u),e.exit("chunkContent"),r.next=e.enter("chunkContent",{contentType:"content",previous:r}),r=r.next,i}}function sE(e,t,r){let n=this;return i;function i(o){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),te(e,s,"linePrefix")}function s(o){if(o===null||j(o))return r(o);let u=n.events[n.events.length-1];return!n.parser.constructs.disable.null.includes("codeIndented")&&u&&u[1].type==="linePrefix"&&u[2].sliceSerialize(u[1],!0).length>=4?t(o):e.interrupt(n.parser.constructs.flow,r,t)(o)}}function $a(e,t,r,n,i,s,o,u,c){let f=c||Number.POSITIVE_INFINITY,h=0;return p;function p(k){return k===60?(e.enter(n),e.enter(i),e.enter(s),e.consume(k),e.exit(s),m):k===null||k===32||k===41||Bn(k)?r(k):(e.enter(n),e.enter(o),e.enter(u),e.enter("chunkString",{contentType:"string"}),b(k))}function m(k){return k===62?(e.enter(s),e.consume(k),e.exit(s),e.exit(i),e.exit(n),t):(e.enter(u),e.enter("chunkString",{contentType:"string"}),d(k))}function d(k){return k===62?(e.exit("chunkString"),e.exit(u),m(k)):k===null||k===60||j(k)?r(k):(e.consume(k),k===92?x:d)}function x(k){return k===60||k===62||k===92?(e.consume(k),d):d(k)}function b(k){return!h&&(k===null||k===41||ue(k))?(e.exit("chunkString"),e.exit(u),e.exit(o),e.exit(n),t(k)):h<f&&k===40?(e.consume(k),h++,b):k===41?(e.consume(k),h--,b):k===null||k===32||k===40||Bn(k)?r(k):(e.consume(k),k===92?v:b)}function v(k){return k===40||k===41||k===92?(e.consume(k),b):b(k)}}function ja(e,t,r,n,i,s){let o=this,u=0,c;return f;function f(d){return e.enter(n),e.enter(i),e.consume(d),e.exit(i),e.enter(s),h}function h(d){return u>999||d===null||d===91||d===93&&!c||d===94&&!u&&"_hiddenFootnoteSupport"in o.parser.constructs?r(d):d===93?(e.exit(s),e.enter(i),e.consume(d),e.exit(i),e.exit(n),t):j(d)?(e.enter("lineEnding"),e.consume(d),e.exit("lineEnding"),h):(e.enter("chunkString",{contentType:"string"}),p(d))}function p(d){return d===null||d===91||d===93||j(d)||u++>999?(e.exit("chunkString"),h(d)):(e.consume(d),c||(c=!W(d)),d===92?m:p)}function m(d){return d===91||d===92||d===93?(e.consume(d),u++,p):p(d)}}function Ua(e,t,r,n,i,s){let o;return u;function u(m){return m===34||m===39||m===40?(e.enter(n),e.enter(i),e.consume(m),e.exit(i),o=m===40?41:m,c):r(m)}function c(m){return m===o?(e.enter(i),e.consume(m),e.exit(i),e.exit(n),t):(e.enter(s),f(m))}function f(m){return m===o?(e.exit(s),c(o)):m===null?r(m):j(m)?(e.enter("lineEnding"),e.consume(m),e.exit("lineEnding"),te(e,f,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),h(m))}function h(m){return m===o||m===null||j(m)?(e.exit("chunkString"),f(m)):(e.consume(m),m===92?p:h)}function p(m){return m===o||m===92?(e.consume(m),h):h(m)}}function jn(e,t){let r;return n;function n(i){return j(i)?(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),r=!0,n):W(i)?te(e,n,r?"linePrefix":"lineSuffix")(i):t(i)}}function st(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}var bl={name:"definition",tokenize:aE},oE={tokenize:uE,partial:!0};function aE(e,t,r){let n=this,i;return s;function s(d){return e.enter("definition"),o(d)}function o(d){return ja.call(n,e,u,r,"definitionLabel","definitionLabelMarker","definitionLabelString")(d)}function u(d){return i=st(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)),d===58?(e.enter("definitionMarker"),e.consume(d),e.exit("definitionMarker"),c):r(d)}function c(d){return ue(d)?jn(e,f)(d):f(d)}function f(d){return $a(e,h,r,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(d)}function h(d){return e.attempt(oE,p,p)(d)}function p(d){return W(d)?te(e,m,"whitespace")(d):m(d)}function m(d){return d===null||j(d)?(e.exit("definition"),n.parser.defined.push(i),t(d)):r(d)}}function uE(e,t,r){return n;function n(u){return ue(u)?jn(e,i)(u):r(u)}function i(u){return Ua(e,s,r,"definitionTitle","definitionTitleMarker","definitionTitleString")(u)}function s(u){return W(u)?te(e,o,"whitespace")(u):o(u)}function o(u){return u===null||j(u)?t(u):r(u)}}var wl={name:"hardBreakEscape",tokenize:cE};function cE(e,t,r){return n;function n(s){return e.enter("hardBreakEscape"),e.consume(s),i}function i(s){return j(s)?(e.exit("hardBreakEscape"),t(s)):r(s)}}var vl={name:"headingAtx",tokenize:fE,resolve:lE};function lE(e,t){let r=e.length-2,n=3,i,s;return e[n][1].type==="whitespace"&&(n+=2),r-2>n&&e[r][1].type==="whitespace"&&(r-=2),e[r][1].type==="atxHeadingSequence"&&(n===r-1||r-4>n&&e[r-2][1].type==="whitespace")&&(r-=n+1===r?2:4),r>n&&(i={type:"atxHeadingText",start:e[n][1].start,end:e[r][1].end},s={type:"chunkText",start:e[n][1].start,end:e[r][1].end,contentType:"text"},Je(e,n,r-n+1,[["enter",i,t],["enter",s,t],["exit",s,t],["exit",i,t]])),e}function fE(e,t,r){let n=0;return i;function i(h){return e.enter("atxHeading"),s(h)}function s(h){return e.enter("atxHeadingSequence"),o(h)}function o(h){return h===35&&n++<6?(e.consume(h),o):h===null||ue(h)?(e.exit("atxHeadingSequence"),u(h)):r(h)}function u(h){return h===35?(e.enter("atxHeadingSequence"),c(h)):h===null||j(h)?(e.exit("atxHeading"),t(h)):W(h)?te(e,u,"whitespace")(h):(e.enter("atxHeadingText"),f(h))}function c(h){return h===35?(e.consume(h),c):(e.exit("atxHeadingSequence"),u(h))}function f(h){return h===null||h===35||ue(h)?(e.exit("atxHeadingText"),u(h)):(e.consume(h),f)}}var Qx=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],kl=["pre","script","style","textarea"];var Al={name:"htmlFlow",tokenize:mE,resolveTo:dE,concrete:!0},pE={tokenize:yE,partial:!0},hE={tokenize:gE,partial:!0};function dE(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function mE(e,t,r){let n=this,i,s,o,u,c;return f;function f(N){return h(N)}function h(N){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(N),p}function p(N){return N===33?(e.consume(N),m):N===47?(e.consume(N),s=!0,b):N===63?(e.consume(N),i=3,n.interrupt?t:R):Ze(N)?(e.consume(N),o=String.fromCharCode(N),v):r(N)}function m(N){return N===45?(e.consume(N),i=2,d):N===91?(e.consume(N),i=5,u=0,x):Ze(N)?(e.consume(N),i=4,n.interrupt?t:R):r(N)}function d(N){return N===45?(e.consume(N),n.interrupt?t:R):r(N)}function x(N){let Xe="CDATA[";return N===Xe.charCodeAt(u++)?(e.consume(N),u===Xe.length?n.interrupt?t:V:x):r(N)}function b(N){return Ze(N)?(e.consume(N),o=String.fromCharCode(N),v):r(N)}function v(N){if(N===null||N===47||N===62||ue(N)){let Xe=N===47,Wt=o.toLowerCase();return!Xe&&!s&&kl.includes(Wt)?(i=1,n.interrupt?t(N):V(N)):Qx.includes(o.toLowerCase())?(i=6,Xe?(e.consume(N),k):n.interrupt?t(N):V(N)):(i=7,n.interrupt&&!n.parser.lazy[n.now().line]?r(N):s?T(N):E(N))}return N===45||Ue(N)?(e.consume(N),o+=String.fromCharCode(N),v):r(N)}function k(N){return N===62?(e.consume(N),n.interrupt?t:V):r(N)}function T(N){return W(N)?(e.consume(N),T):P(N)}function E(N){return N===47?(e.consume(N),P):N===58||N===95||Ze(N)?(e.consume(N),g):W(N)?(e.consume(N),E):P(N)}function g(N){return N===45||N===46||N===58||N===95||Ue(N)?(e.consume(N),g):I(N)}function I(N){return N===61?(e.consume(N),_):W(N)?(e.consume(N),I):E(N)}function _(N){return N===null||N===60||N===61||N===62||N===96?r(N):N===34||N===39?(e.consume(N),c=N,D):W(N)?(e.consume(N),_):O(N)}function D(N){return N===c?(e.consume(N),c=null,M):N===null||j(N)?r(N):(e.consume(N),D)}function O(N){return N===null||N===34||N===39||N===47||N===60||N===61||N===62||N===96||ue(N)?I(N):(e.consume(N),O)}function M(N){return N===47||N===62||W(N)?E(N):r(N)}function P(N){return N===62?(e.consume(N),J):r(N)}function J(N){return N===null||j(N)?V(N):W(N)?(e.consume(N),J):r(N)}function V(N){return N===45&&i===2?(e.consume(N),Ae):N===60&&i===1?(e.consume(N),se):N===62&&i===4?(e.consume(N),Ge):N===63&&i===3?(e.consume(N),R):N===93&&i===5?(e.consume(N),yt):j(N)&&(i===6||i===7)?(e.exit("htmlFlowData"),e.check(pE,ut,q)(N)):N===null||j(N)?(e.exit("htmlFlowData"),q(N)):(e.consume(N),V)}function q(N){return e.check(hE,ee,ut)(N)}function ee(N){return e.enter("lineEnding"),e.consume(N),e.exit("lineEnding"),re}function re(N){return N===null||j(N)?q(N):(e.enter("htmlFlowData"),V(N))}function Ae(N){return N===45?(e.consume(N),R):V(N)}function se(N){return N===47?(e.consume(N),o="",Ce):V(N)}function Ce(N){if(N===62){let Xe=o.toLowerCase();return kl.includes(Xe)?(e.consume(N),Ge):V(N)}return Ze(N)&&o.length<8?(e.consume(N),o+=String.fromCharCode(N),Ce):V(N)}function yt(N){return N===93?(e.consume(N),R):V(N)}function R(N){return N===62?(e.consume(N),Ge):N===45&&i===2?(e.consume(N),R):V(N)}function Ge(N){return N===null||j(N)?(e.exit("htmlFlowData"),ut(N)):(e.consume(N),Ge)}function ut(N){return e.exit("htmlFlow"),t(N)}}function gE(e,t,r){let n=this;return i;function i(o){return j(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),s):r(o)}function s(o){return n.parser.lazy[n.now().line]?r(o):t(o)}}function yE(e,t,r){return n;function n(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),e.attempt(jt,t,r)}}var Sl={name:"htmlText",tokenize:xE};function xE(e,t,r){let n=this,i,s,o;return u;function u(R){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(R),c}function c(R){return R===33?(e.consume(R),f):R===47?(e.consume(R),I):R===63?(e.consume(R),E):Ze(R)?(e.consume(R),O):r(R)}function f(R){return R===45?(e.consume(R),h):R===91?(e.consume(R),s=0,x):Ze(R)?(e.consume(R),T):r(R)}function h(R){return R===45?(e.consume(R),d):r(R)}function p(R){return R===null?r(R):R===45?(e.consume(R),m):j(R)?(o=p,se(R)):(e.consume(R),p)}function m(R){return R===45?(e.consume(R),d):p(R)}function d(R){return R===62?Ae(R):R===45?m(R):p(R)}function x(R){let Ge="CDATA[";return R===Ge.charCodeAt(s++)?(e.consume(R),s===Ge.length?b:x):r(R)}function b(R){return R===null?r(R):R===93?(e.consume(R),v):j(R)?(o=b,se(R)):(e.consume(R),b)}function v(R){return R===93?(e.consume(R),k):b(R)}function k(R){return R===62?Ae(R):R===93?(e.consume(R),k):b(R)}function T(R){return R===null||R===62?Ae(R):j(R)?(o=T,se(R)):(e.consume(R),T)}function E(R){return R===null?r(R):R===63?(e.consume(R),g):j(R)?(o=E,se(R)):(e.consume(R),E)}function g(R){return R===62?Ae(R):E(R)}function I(R){return Ze(R)?(e.consume(R),_):r(R)}function _(R){return R===45||Ue(R)?(e.consume(R),_):D(R)}function D(R){return j(R)?(o=D,se(R)):W(R)?(e.consume(R),D):Ae(R)}function O(R){return R===45||Ue(R)?(e.consume(R),O):R===47||R===62||ue(R)?M(R):r(R)}function M(R){return R===47?(e.consume(R),Ae):R===58||R===95||Ze(R)?(e.consume(R),P):j(R)?(o=M,se(R)):W(R)?(e.consume(R),M):Ae(R)}function P(R){return R===45||R===46||R===58||R===95||Ue(R)?(e.consume(R),P):J(R)}function J(R){return R===61?(e.consume(R),V):j(R)?(o=J,se(R)):W(R)?(e.consume(R),J):M(R)}function V(R){return R===null||R===60||R===61||R===62||R===96?r(R):R===34||R===39?(e.consume(R),i=R,q):j(R)?(o=V,se(R)):W(R)?(e.consume(R),V):(e.consume(R),ee)}function q(R){return R===i?(e.consume(R),i=void 0,re):R===null?r(R):j(R)?(o=q,se(R)):(e.consume(R),q)}function ee(R){return R===null||R===34||R===39||R===60||R===61||R===96?r(R):R===47||R===62||ue(R)?M(R):(e.consume(R),ee)}function re(R){return R===47||R===62||ue(R)?M(R):r(R)}function Ae(R){return R===62?(e.consume(R),e.exit("htmlTextData"),e.exit("htmlText"),t):r(R)}function se(R){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(R),e.exit("lineEnding"),Ce}function Ce(R){return W(R)?te(e,yt,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(R):yt(R)}function yt(R){return e.enter("htmlTextData"),o(R)}}var Un={name:"labelEnd",tokenize:SE,resolveTo:AE,resolveAll:kE},bE={tokenize:EE},wE={tokenize:_E},vE={tokenize:CE};function kE(e){let t=-1;for(;++t<e.length;){let r=e[t][1];(r.type==="labelImage"||r.type==="labelLink"||r.type==="labelEnd")&&(e.splice(t+1,r.type==="labelImage"?4:2),r.type="data",t++)}return e}function AE(e,t){let r=e.length,n=0,i,s,o,u;for(;r--;)if(i=e[r][1],s){if(i.type==="link"||i.type==="labelLink"&&i._inactive)break;e[r][0]==="enter"&&i.type==="labelLink"&&(i._inactive=!0)}else if(o){if(e[r][0]==="enter"&&(i.type==="labelImage"||i.type==="labelLink")&&!i._balanced&&(s=r,i.type!=="labelLink")){n=2;break}}else i.type==="labelEnd"&&(o=r);let c={type:e[s][1].type==="labelLink"?"link":"image",start:Object.assign({},e[s][1].start),end:Object.assign({},e[e.length-1][1].end)},f={type:"label",start:Object.assign({},e[s][1].start),end:Object.assign({},e[o][1].end)},h={type:"labelText",start:Object.assign({},e[s+n+2][1].end),end:Object.assign({},e[o-2][1].start)};return u=[["enter",c,t],["enter",f,t]],u=dt(u,e.slice(s+1,s+n+3)),u=dt(u,[["enter",h,t]]),u=dt(u,kn(t.parser.constructs.insideSpan.null,e.slice(s+n+4,o-3),t)),u=dt(u,[["exit",h,t],e[o-2],e[o-1],["exit",f,t]]),u=dt(u,e.slice(o+1)),u=dt(u,[["exit",c,t]]),Je(e,s,e.length,u),e}function SE(e,t,r){let n=this,i=n.events.length,s,o;for(;i--;)if((n.events[i][1].type==="labelImage"||n.events[i][1].type==="labelLink")&&!n.events[i][1]._balanced){s=n.events[i][1];break}return u;function u(m){return s?s._inactive?p(m):(o=n.parser.defined.includes(st(n.sliceSerialize({start:s.end,end:n.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(m),e.exit("labelMarker"),e.exit("labelEnd"),c):r(m)}function c(m){return m===40?e.attempt(bE,h,o?h:p)(m):m===91?e.attempt(wE,h,o?f:p)(m):o?h(m):p(m)}function f(m){return e.attempt(vE,h,p)(m)}function h(m){return t(m)}function p(m){return s._balanced=!0,r(m)}}function EE(e,t,r){return n;function n(p){return e.enter("resource"),e.enter("resourceMarker"),e.consume(p),e.exit("resourceMarker"),i}function i(p){return ue(p)?jn(e,s)(p):s(p)}function s(p){return p===41?h(p):$a(e,o,u,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(p)}function o(p){return ue(p)?jn(e,c)(p):h(p)}function u(p){return r(p)}function c(p){return p===34||p===39||p===40?Ua(e,f,r,"resourceTitle","resourceTitleMarker","resourceTitleString")(p):h(p)}function f(p){return ue(p)?jn(e,h)(p):h(p)}function h(p){return p===41?(e.enter("resourceMarker"),e.consume(p),e.exit("resourceMarker"),e.exit("resource"),t):r(p)}}function _E(e,t,r){let n=this;return i;function i(u){return ja.call(n,e,s,o,"reference","referenceMarker","referenceString")(u)}function s(u){return n.parser.defined.includes(st(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)))?t(u):r(u)}function o(u){return r(u)}}function CE(e,t,r){return n;function n(s){return e.enter("reference"),e.enter("referenceMarker"),e.consume(s),e.exit("referenceMarker"),i}function i(s){return s===93?(e.enter("referenceMarker"),e.consume(s),e.exit("referenceMarker"),e.exit("reference"),t):r(s)}}var El={name:"labelStartImage",tokenize:DE,resolveAll:Un.resolveAll};function DE(e,t,r){let n=this;return i;function i(u){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(u),e.exit("labelImageMarker"),s}function s(u){return u===91?(e.enter("labelMarker"),e.consume(u),e.exit("labelMarker"),e.exit("labelImage"),o):r(u)}function o(u){return u===94&&"_hiddenFootnoteSupport"in n.parser.constructs?r(u):t(u)}}var _l={name:"labelStartLink",tokenize:IE,resolveAll:Un.resolveAll};function IE(e,t,r){let n=this;return i;function i(o){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(o),e.exit("labelMarker"),e.exit("labelLink"),s}function s(o){return o===94&&"_hiddenFootnoteSupport"in n.parser.constructs?r(o):t(o)}}var Ws={name:"lineEnding",tokenize:TE};function TE(e,t){return r;function r(n){return e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),te(e,t,"linePrefix")}}var qn={name:"thematicBreak",tokenize:RE};function RE(e,t,r){let n=0,i;return s;function s(f){return e.enter("thematicBreak"),o(f)}function o(f){return i=f,u(f)}function u(f){return f===i?(e.enter("thematicBreakSequence"),c(f)):n>=3&&(f===null||j(f))?(e.exit("thematicBreak"),t(f)):r(f)}function c(f){return f===i?(e.consume(f),n++,c):(e.exit("thematicBreakSequence"),W(f)?te(e,u,"whitespace")(f):u(f))}}var ot={name:"list",tokenize:OE,continuation:{tokenize:FE},exit:zE},NE={tokenize:BE,partial:!0},PE={tokenize:LE,partial:!0};function OE(e,t,r){let n=this,i=n.events[n.events.length-1],s=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,o=0;return u;function u(d){let x=n.containerState.type||(d===42||d===43||d===45?"listUnordered":"listOrdered");if(x==="listUnordered"?!n.containerState.marker||d===n.containerState.marker:js(d)){if(n.containerState.type||(n.containerState.type=x,e.enter(x,{_container:!0})),x==="listUnordered")return e.enter("listItemPrefix"),d===42||d===45?e.check(qn,r,f)(d):f(d);if(!n.interrupt||d===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),c(d)}return r(d)}function c(d){return js(d)&&++o<10?(e.consume(d),c):(!n.interrupt||o<2)&&(n.containerState.marker?d===n.containerState.marker:d===41||d===46)?(e.exit("listItemValue"),f(d)):r(d)}function f(d){return e.enter("listItemMarker"),e.consume(d),e.exit("listItemMarker"),n.containerState.marker=n.containerState.marker||d,e.check(jt,n.interrupt?r:h,e.attempt(NE,m,p))}function h(d){return n.containerState.initialBlankLine=!0,s++,m(d)}function p(d){return W(d)?(e.enter("listItemPrefixWhitespace"),e.consume(d),e.exit("listItemPrefixWhitespace"),m):r(d)}function m(d){return n.containerState.size=s+n.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(d)}}function FE(e,t,r){let n=this;return n.containerState._closeFlow=void 0,e.check(jt,i,s);function i(u){return n.containerState.furtherBlankLines=n.containerState.furtherBlankLines||n.containerState.initialBlankLine,te(e,t,"listItemIndent",n.containerState.size+1)(u)}function s(u){return n.containerState.furtherBlankLines||!W(u)?(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,o(u)):(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,e.attempt(PE,t,o)(u))}function o(u){return n.containerState._closeFlow=!0,n.interrupt=void 0,te(e,e.attempt(ot,t,r),"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(u)}}function LE(e,t,r){let n=this;return te(e,i,"listItemIndent",n.containerState.size+1);function i(s){let o=n.events[n.events.length-1];return o&&o[1].type==="listItemIndent"&&o[2].sliceSerialize(o[1],!0).length===n.containerState.size?t(s):r(s)}}function zE(e){e.exit(this.containerState.type)}function BE(e,t,r){let n=this;return te(e,i,"listItemPrefixWhitespace",n.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function i(s){let o=n.events[n.events.length-1];return!W(s)&&o&&o[1].type==="listItemPrefixWhitespace"?t(s):r(s)}}var qa={name:"setextUnderline",tokenize:VE,resolveTo:ME};function ME(e,t){let r=e.length,n,i,s;for(;r--;)if(e[r][0]==="enter"){if(e[r][1].type==="content"){n=r;break}e[r][1].type==="paragraph"&&(i=r)}else e[r][1].type==="content"&&e.splice(r,1),!s&&e[r][1].type==="definition"&&(s=r);let o={type:"setextHeading",start:Object.assign({},e[i][1].start),end:Object.assign({},e[e.length-1][1].end)};return e[i][1].type="setextHeadingText",s?(e.splice(i,0,["enter",o,t]),e.splice(s+1,0,["exit",e[n][1],t]),e[n][1].end=Object.assign({},e[s][1].end)):e[n][1]=o,e.push(["exit",o,t]),e}function VE(e,t,r){let n=this,i;return s;function s(f){let h=n.events.length,p;for(;h--;)if(n.events[h][1].type!=="lineEnding"&&n.events[h][1].type!=="linePrefix"&&n.events[h][1].type!=="content"){p=n.events[h][1].type==="paragraph";break}return!n.parser.lazy[n.now().line]&&(n.interrupt||p)?(e.enter("setextHeadingLine"),i=f,o(f)):r(f)}function o(f){return e.enter("setextHeadingLineSequence"),u(f)}function u(f){return f===i?(e.consume(f),u):(e.exit("setextHeadingLineSequence"),W(f)?te(e,c,"lineSuffix")(f):c(f))}function c(f){return f===null||j(f)?(e.exit("setextHeadingLine"),t(f)):r(f)}}var $E={tokenize:QE,partial:!0};function Cl(){return{document:{91:{tokenize:ZE,continuation:{tokenize:JE},exit:GE}},text:{91:{tokenize:qE},93:{add:"after",tokenize:jE,resolveTo:UE}}}}function jE(e,t,r){let n=this,i=n.events.length,s=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]),o;for(;i--;){let c=n.events[i][1];if(c.type==="labelImage"){o=c;break}if(c.type==="gfmFootnoteCall"||c.type==="labelLink"||c.type==="label"||c.type==="image"||c.type==="link")break}return u;function u(c){if(!o||!o._balanced)return r(c);let f=st(n.sliceSerialize({start:o.end,end:n.now()}));return f.codePointAt(0)!==94||!s.includes(f.slice(1))?r(c):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(c),e.exit("gfmFootnoteCallLabelMarker"),t(c))}}function UE(e,t){let r=e.length,n;for(;r--;)if(e[r][1].type==="labelImage"&&e[r][0]==="enter"){n=e[r][1];break}e[r+1][1].type="data",e[r+3][1].type="gfmFootnoteCallLabelMarker";let i={type:"gfmFootnoteCall",start:Object.assign({},e[r+3][1].start),end:Object.assign({},e[e.length-1][1].end)},s={type:"gfmFootnoteCallMarker",start:Object.assign({},e[r+3][1].end),end:Object.assign({},e[r+3][1].end)};s.end.column++,s.end.offset++,s.end._bufferIndex++;let o={type:"gfmFootnoteCallString",start:Object.assign({},s.end),end:Object.assign({},e[e.length-1][1].start)},u={type:"chunkString",contentType:"string",start:Object.assign({},o.start),end:Object.assign({},o.end)},c=[e[r+1],e[r+2],["enter",i,t],e[r+3],e[r+4],["enter",s,t],["exit",s,t],["enter",o,t],["enter",u,t],["exit",u,t],["exit",o,t],e[e.length-2],e[e.length-1],["exit",i,t]];return e.splice(r,e.length-r+1,...c),e}function qE(e,t,r){let n=this,i=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]),s=0,o;return u;function u(p){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),c}function c(p){return p!==94?r(p):(e.enter("gfmFootnoteCallMarker"),e.consume(p),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",f)}function f(p){if(s>999||p===93&&!o||p===null||p===91||ue(p))return r(p);if(p===93){e.exit("chunkString");let m=e.exit("gfmFootnoteCallString");return i.includes(st(n.sliceSerialize(m)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):r(p)}return ue(p)||(o=!0),s++,e.consume(p),p===92?h:f}function h(p){return p===91||p===92||p===93?(e.consume(p),s++,f):f(p)}}function ZE(e,t,r){let n=this,i=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]),s,o=0,u;return c;function c(x){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(x),e.exit("gfmFootnoteDefinitionLabelMarker"),f}function f(x){return x===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(x),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",h):r(x)}function h(x){if(o>999||x===93&&!u||x===null||x===91||ue(x))return r(x);if(x===93){e.exit("chunkString");let b=e.exit("gfmFootnoteDefinitionLabelString");return s=st(n.sliceSerialize(b)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(x),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),m}return ue(x)||(u=!0),o++,e.consume(x),x===92?p:h}function p(x){return x===91||x===92||x===93?(e.consume(x),o++,h):h(x)}function m(x){return x===58?(e.enter("definitionMarker"),e.consume(x),e.exit("definitionMarker"),i.includes(s)||i.push(s),te(e,d,"gfmFootnoteDefinitionWhitespace")):r(x)}function d(x){return t(x)}}function JE(e,t,r){return e.check(jt,t,e.attempt($E,t,r))}function GE(e){e.exit("gfmFootnoteDefinition")}function QE(e,t,r){let n=this;return te(e,i,"gfmFootnoteDefinitionIndent",5);function i(s){let o=n.events[n.events.length-1];return o&&o[1].type==="gfmFootnoteDefinitionIndent"&&o[2].sliceSerialize(o[1],!0).length===4?t(s):r(s)}}function Dl(e){let r=(e||{}).singleTilde,n={tokenize:s,resolveAll:i};return r==null&&(r=!0),{text:{126:n},insideSpan:{null:[n]},attentionMarkers:{null:[126]}};function i(o,u){let c=-1;for(;++c<o.length;)if(o[c][0]==="enter"&&o[c][1].type==="strikethroughSequenceTemporary"&&o[c][1]._close){let f=c;for(;f--;)if(o[f][0]==="exit"&&o[f][1].type==="strikethroughSequenceTemporary"&&o[f][1]._open&&o[c][1].end.offset-o[c][1].start.offset===o[f][1].end.offset-o[f][1].start.offset){o[c][1].type="strikethroughSequence",o[f][1].type="strikethroughSequence";let h={type:"strikethrough",start:Object.assign({},o[f][1].start),end:Object.assign({},o[c][1].end)},p={type:"strikethroughText",start:Object.assign({},o[f][1].end),end:Object.assign({},o[c][1].start)},m=[["enter",h,u],["enter",o[f][1],u],["exit",o[f][1],u],["enter",p,u]],d=u.parser.constructs.insideSpan.null;d&&Je(m,m.length,0,kn(d,o.slice(f+1,c),u)),Je(m,m.length,0,[["exit",p,u],["enter",o[c][1],u],["exit",o[c][1],u],["exit",h,u]]),Je(o,f-1,c-f+3,m),c=f+m.length-2;break}}for(c=-1;++c<o.length;)o[c][1].type==="strikethroughSequenceTemporary"&&(o[c][1].type="data");return o}function s(o,u,c){let f=this.previous,h=this.events,p=0;return m;function m(x){return f===126&&h[h.length-1][1].type!=="characterEscape"?c(x):(o.enter("strikethroughSequenceTemporary"),d(x))}function d(x){let b=Pi(f);if(x===126)return p>1?c(x):(o.consume(x),p++,d);if(p<2&&!r)return c(x);let v=o.exit("strikethroughSequenceTemporary"),k=Pi(x);return v._open=!k||k===2&&!!b,v._close=!b||b===2&&!!k,u(x)}}}var Za=class{constructor(){this.map=[]}add(t,r,n){HE(this,t,r,n)}consume(t){if(this.map.sort((s,o)=>s[0]-o[0]),this.map.length===0)return;let r=this.map.length,n=[];for(;r>0;)r-=1,n.push(t.slice(this.map[r][0]+this.map[r][1])),n.push(this.map[r][2]),t.length=this.map[r][0];n.push([...t]),t.length=0;let i=n.pop();for(;i;)t.push(...i),i=n.pop();this.map.length=0}};function HE(e,t,r,n){let i=0;if(!(r===0&&n.length===0)){for(;i<e.map.length;){if(e.map[i][0]===t){e.map[i][1]+=r,e.map[i][2].push(...n);return}i+=1}e.map.push([t,r,n])}}function Hx(e,t){let r=!1,n=[];for(;t<e.length;){let i=e[t];if(r){if(i[0]==="enter")i[1].type==="tableContent"&&n.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(i[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){let s=n.length-1;n[s]=n[s]==="left"?"center":"right"}}else if(i[1].type==="tableDelimiterRow")break}else i[0]==="enter"&&i[1].type==="tableDelimiterRow"&&(r=!0);t+=1}return n}var Il={flow:{null:{tokenize:WE,resolveAll:KE}}};function WE(e,t,r){let n=this,i=0,s=0,o;return u;function u(P){let J=n.events.length-1;for(;J>-1;){let ee=n.events[J][1].type;if(ee==="lineEnding"||ee==="linePrefix")J--;else break}let V=J>-1?n.events[J][1].type:null,q=V==="tableHead"||V==="tableRow"?_:c;return q===_&&n.parser.lazy[n.now().line]?r(P):q(P)}function c(P){return e.enter("tableHead"),e.enter("tableRow"),f(P)}function f(P){return P===124||(o=!0,s+=1),h(P)}function h(P){return P===null?r(P):j(P)?s>1?(s=0,n.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(P),e.exit("lineEnding"),d):r(P):W(P)?te(e,h,"whitespace")(P):(s+=1,o&&(o=!1,i+=1),P===124?(e.enter("tableCellDivider"),e.consume(P),e.exit("tableCellDivider"),o=!0,h):(e.enter("data"),p(P)))}function p(P){return P===null||P===124||ue(P)?(e.exit("data"),h(P)):(e.consume(P),P===92?m:p)}function m(P){return P===92||P===124?(e.consume(P),p):p(P)}function d(P){return n.interrupt=!1,n.parser.lazy[n.now().line]?r(P):(e.enter("tableDelimiterRow"),o=!1,W(P)?te(e,x,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(P):x(P))}function x(P){return P===45||P===58?v(P):P===124?(o=!0,e.enter("tableCellDivider"),e.consume(P),e.exit("tableCellDivider"),b):I(P)}function b(P){return W(P)?te(e,v,"whitespace")(P):v(P)}function v(P){return P===58?(s+=1,o=!0,e.enter("tableDelimiterMarker"),e.consume(P),e.exit("tableDelimiterMarker"),k):P===45?(s+=1,k(P)):P===null||j(P)?g(P):I(P)}function k(P){return P===45?(e.enter("tableDelimiterFiller"),T(P)):I(P)}function T(P){return P===45?(e.consume(P),T):P===58?(o=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(P),e.exit("tableDelimiterMarker"),E):(e.exit("tableDelimiterFiller"),E(P))}function E(P){return W(P)?te(e,g,"whitespace")(P):g(P)}function g(P){return P===124?x(P):P===null||j(P)?!o||i!==s?I(P):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(P)):I(P)}function I(P){return r(P)}function _(P){return e.enter("tableRow"),D(P)}function D(P){return P===124?(e.enter("tableCellDivider"),e.consume(P),e.exit("tableCellDivider"),D):P===null||j(P)?(e.exit("tableRow"),t(P)):W(P)?te(e,D,"whitespace")(P):(e.enter("data"),O(P))}function O(P){return P===null||P===124||ue(P)?(e.exit("data"),D(P)):(e.consume(P),P===92?M:O)}function M(P){return P===92||P===124?(e.consume(P),O):O(P)}}function KE(e,t){let r=-1,n=!0,i=0,s=[0,0,0,0],o=[0,0,0,0],u=!1,c=0,f,h,p,m=new Za;for(;++r<e.length;){let d=e[r],x=d[1];d[0]==="enter"?x.type==="tableHead"?(u=!1,c!==0&&(Wx(m,t,c,f,h),h=void 0,c=0),f={type:"table",start:Object.assign({},x.start),end:Object.assign({},x.end)},m.add(r,0,[["enter",f,t]])):x.type==="tableRow"||x.type==="tableDelimiterRow"?(n=!0,p=void 0,s=[0,0,0,0],o=[0,r+1,0,0],u&&(u=!1,h={type:"tableBody",start:Object.assign({},x.start),end:Object.assign({},x.end)},m.add(r,0,[["enter",h,t]])),i=x.type==="tableDelimiterRow"?2:h?3:1):i&&(x.type==="data"||x.type==="tableDelimiterMarker"||x.type==="tableDelimiterFiller")?(n=!1,o[2]===0&&(s[1]!==0&&(o[0]=o[1],p=Ja(m,t,s,i,void 0,p),s=[0,0,0,0]),o[2]=r)):x.type==="tableCellDivider"&&(n?n=!1:(s[1]!==0&&(o[0]=o[1],p=Ja(m,t,s,i,void 0,p)),s=o,o=[s[1],r,0,0])):x.type==="tableHead"?(u=!0,c=r):x.type==="tableRow"||x.type==="tableDelimiterRow"?(c=r,s[1]!==0?(o[0]=o[1],p=Ja(m,t,s,i,r,p)):o[1]!==0&&(p=Ja(m,t,o,i,r,p)),i=0):i&&(x.type==="data"||x.type==="tableDelimiterMarker"||x.type==="tableDelimiterFiller")&&(o[3]=r)}for(c!==0&&Wx(m,t,c,f,h),m.consume(t.events),r=-1;++r<t.events.length;){let d=t.events[r];d[0]==="enter"&&d[1].type==="table"&&(d[1]._align=Hx(t.events,r))}return e}function Ja(e,t,r,n,i,s){let o=n===1?"tableHeader":n===2?"tableDelimiter":"tableData",u="tableContent";r[0]!==0&&(s.end=Object.assign({},Oi(t.events,r[0])),e.add(r[0],0,[["exit",s,t]]));let c=Oi(t.events,r[1]);if(s={type:o,start:Object.assign({},c),end:Object.assign({},c)},e.add(r[1],0,[["enter",s,t]]),r[2]!==0){let f=Oi(t.events,r[2]),h=Oi(t.events,r[3]),p={type:u,start:Object.assign({},f),end:Object.assign({},h)};if(e.add(r[2],0,[["enter",p,t]]),n!==2){let m=t.events[r[2]],d=t.events[r[3]];if(m[1].end=Object.assign({},d[1].end),m[1].type="chunkText",m[1].contentType="text",r[3]>r[2]+1){let x=r[2]+1,b=r[3]-r[2]-1;e.add(x,b,[])}}e.add(r[3]+1,0,[["exit",p,t]])}return i!==void 0&&(s.end=Object.assign({},Oi(t.events,i)),e.add(i,0,[["exit",s,t]]),s=void 0),s}function Wx(e,t,r,n,i){let s=[],o=Oi(t.events,r);i&&(i.end=Object.assign({},o),s.push(["exit",i,t])),n.end=Object.assign({},o),s.push(["exit",n,t]),e.add(r+1,0,s)}function Oi(e,t){let r=e[t],n=r[0]==="enter"?"start":"end";return r[1][n]}var XE={tokenize:YE},Tl={text:{91:XE}};function YE(e,t,r){let n=this;return i;function i(c){return n.previous!==null||!n._gfmTasklistFirstContentOfListItem?r(c):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(c),e.exit("taskListCheckMarker"),s)}function s(c){return ue(c)?(e.enter("taskListCheckValueUnchecked"),e.consume(c),e.exit("taskListCheckValueUnchecked"),o):c===88||c===120?(e.enter("taskListCheckValueChecked"),e.consume(c),e.exit("taskListCheckValueChecked"),o):r(c)}function o(c){return c===93?(e.enter("taskListCheckMarker"),e.consume(c),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),u):r(c)}function u(c){return j(c)?t(c):W(c)?e.check({tokenize:e_},t,r)(c):r(c)}}function e_(e,t,r){return te(e,n,"whitespace");function n(i){return i===null?r(i):t(i)}}function Kx(e){return Ni([hl,Cl(),Dl(e),Il,Tl])}function Fi(e,t){let r=String(e);if(typeof t!="string")throw new TypeError("Expected character");let n=0,i=r.indexOf(t);for(;i!==-1;)n++,i=r.indexOf(t,i+t.length);return n}function Rl(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}var t_={}.hasOwnProperty,Nl=function(e,t,r,n){let i,s;typeof t=="string"||t instanceof RegExp?(s=[[t,r]],i=n):(s=t,i=r),i||(i={});let o=Ti(i.ignore||[]),u=r_(s),c=-1;for(;++c<u.length;)Us(e,"text",f);return e;function f(p,m){let d=-1,x;for(;++d<m.length;){let b=m[d];if(o(b,x?x.children.indexOf(b):void 0,x))return;x=b}if(x)return h(p,m)}function h(p,m){let d=m[m.length-1],x=u[c][0],b=u[c][1],v=0,k=d.children.indexOf(p),T=!1,E=[];x.lastIndex=0;let g=x.exec(p.value);for(;g;){let I=g.index,_={index:g.index,input:g.input,stack:[...m,p]},D=b(...g,_);if(typeof D=="string"&&(D=D.length>0?{type:"text",value:D}:void 0),D!==!1&&(v!==I&&E.push({type:"text",value:p.value.slice(v,I)}),Array.isArray(D)?E.push(...D):D&&E.push(D),v=I+g[0].length,T=!0),!x.global)break;g=x.exec(p.value)}return T?(v<p.value.length&&E.push({type:"text",value:p.value.slice(v)}),d.children.splice(k,1,...E)):E=[p],k+E.length}};function r_(e){let t=[];if(typeof e!="object")throw new TypeError("Expected array or object as schema");if(Array.isArray(e)){let r=-1;for(;++r<e.length;)t.push([Xx(e[r][0]),Yx(e[r][1])])}else{let r;for(r in e)t_.call(e,r)&&t.push([Xx(r),Yx(e[r])])}return t}function Xx(e){return typeof e=="string"?new RegExp(Rl(e),"g"):e}function Yx(e){return typeof e=="function"?e:()=>e}var Pl="phrasing",Ol=["autolink","link","image","label"],Ll={transforms:[u_],enter:{literalAutolink:n_,literalAutolinkEmail:Fl,literalAutolinkHttp:Fl,literalAutolinkWww:Fl},exit:{literalAutolink:a_,literalAutolinkEmail:o_,literalAutolinkHttp:i_,literalAutolinkWww:s_}},zl={unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Pl,notInConstruct:Ol},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Pl,notInConstruct:Ol},{character:":",before:"[ps]",after:"\\/",inConstruct:Pl,notInConstruct:Ol}]};function n_(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function Fl(e){this.config.enter.autolinkProtocol.call(this,e)}function i_(e){this.config.exit.autolinkProtocol.call(this,e)}function s_(e){this.config.exit.data.call(this,e);let t=this.stack[this.stack.length-1];t.url="http://"+this.sliceSerialize(e)}function o_(e){this.config.exit.autolinkEmail.call(this,e)}function a_(e){this.exit(e)}function u_(e){Nl(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,c_],[/([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/g,l_]],{ignore:["link","linkReference"]})}function c_(e,t,r,n,i){let s="";if(!e0(i)||(/^w/i.test(t)&&(r=t+r,t="",s="http://"),!f_(r)))return!1;let o=p_(r+n);if(!o[0])return!1;let u={type:"link",title:null,url:s+t+o[0],children:[{type:"text",value:t+o[0]}]};return o[1]?[u,{type:"text",value:o[1]}]:u}function l_(e,t,r,n){return!e0(n,!0)||/[-\d_]$/.test(r)?!1:{type:"link",title:null,url:"mailto:"+t+"@"+r,children:[{type:"text",value:t+"@"+r}]}}function f_(e){let t=e.split(".");return!(t.length<2||t[t.length-1]&&(/_/.test(t[t.length-1])||!/[a-zA-Z\d]/.test(t[t.length-1]))||t[t.length-2]&&(/_/.test(t[t.length-2])||!/[a-zA-Z\d]/.test(t[t.length-2])))}function p_(e){let t=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let r=t[0],n=r.indexOf(")"),i=Fi(e,"("),s=Fi(e,")");for(;n!==-1&&i>s;)e+=r.slice(0,n+1),r=r.slice(n+1),n=r.indexOf(")"),s++;return[e,r]}function e0(e,t){let r=e.input.charCodeAt(e.index-1);return(e.index===0||Ke(r)||Mn(r))&&(!t||r!==47)}function Ga(e,t){let r=Number.parseInt(e,t);return r<9||r===11||r>13&&r<32||r>126&&r<160||r>55295&&r<57344||r>64975&&r<65008||(r&65535)===65535||(r&65535)===65534||r>1114111?"\uFFFD":String.fromCharCode(r)}var h_=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function Qa(e){return e.replace(h_,d_)}function d_(e,t,r){if(t)return t;if(r.charCodeAt(0)===35){let i=r.charCodeAt(1),s=i===120||i===88;return Ga(r.slice(s?2:1),s?16:10)}return Wr(r)||e}function Bl(e){return e.label||!e.identifier?e.label||"":Qa(e.identifier)}function t0(e,t,r){let n=t.indexStack,i=e.children||[],s=t.createTracker(r),o=[],u=-1;for(n.push(-1);++u<i.length;){let c=i[u];n[n.length-1]=u,o.push(s.move(t.handle(c,e,t,{before:`+`,after:`+`,...s.current()}))),c.type!=="list"&&(t.bulletLastUsed=void 0),u<i.length-1&&o.push(s.move(m_(c,i[u+1],e,t)))}return n.pop(),o.join("")}function m_(e,t,r,n){let i=n.join.length;for(;i--;){let s=n.join[i](e,t,r,n);if(s===!0||s===1)break;if(typeof s=="number")return`+`.repeat(1+s);if(s===!1)return`++<!---->++`}return`++`}var g_=/\r?\n|\r/g;function Ha(e,t){let r=[],n=0,i=0,s;for(;s=g_.exec(e);)o(e.slice(n,s.index)),r.push(s[0]),n=s.index+s[0].length,i++;return o(e.slice(n)),r.join("");function o(u){r.push(t(u,i,!u))}}function Wa(e){if(!e._compiled){let t=(e.atBreak?"[\\r\\n][\\t ]*":"")+(e.before?"(?:"+e.before+")":"");e._compiled=new RegExp((t?"("+t+")":"")+(/[|\\{}()[\]^$+*?.-]/.test(e.character)?"\\":"")+e.character+(e.after?"(?:"+e.after+")":""),"g")}return e._compiled}function n0(e,t){return r0(e,t.inConstruct,!0)&&!r0(e,t.notInConstruct,!1)}function r0(e,t,r){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return r;let n=-1;for(;++n<t.length;)if(e.includes(t[n]))return!0;return!1}function Ml(e,t,r){let n=(r.before||"")+(t||"")+(r.after||""),i=[],s=[],o={},u=-1;for(;++u<e.unsafe.length;){let h=e.unsafe[u];if(!n0(e.stack,h))continue;let p=Wa(h),m;for(;m=p.exec(n);){let d="before"in h||!!h.atBreak,x="after"in h,b=m.index+(d?m[1].length:0);i.includes(b)?(o[b].before&&!d&&(o[b].before=!1),o[b].after&&!x&&(o[b].after=!1)):(i.push(b),o[b]={before:d,after:x})}}i.sort(y_);let c=r.before?r.before.length:0,f=n.length-(r.after?r.after.length:0);for(u=-1;++u<i.length;){let h=i[u];h<c||h>=f||h+1<f&&i[u+1]===h+1&&o[h].after&&!o[h+1].before&&!o[h+1].after||i[u-1]===h-1&&o[h].before&&!o[h-1].before&&!o[h-1].after||(c!==h&&s.push(i0(n.slice(c,h),"\\")),c=h,/[!-/:-@[-`{-~]/.test(n.charAt(h))&&(!r.encode||!r.encode.includes(n.charAt(h)))?s.push("\\"):(s.push("&#x"+n.charCodeAt(h).toString(16).toUpperCase()+";"),c++))}return s.push(i0(n.slice(c,f),r.after)),s.join("")}function y_(e,t){return e-t}function i0(e,t){let r=/\\(?=[!-/:-@[-`{-~])/g,n=[],i=[],s=e+t,o=-1,u=0,c;for(;c=r.exec(s);)n.push(c.index);for(;++o<n.length;)u!==n[o]&&i.push(e.slice(u,n[o])),i.push("\\"),u=n[o];return i.push(e.slice(u)),i.join("")}function Or(e){let t=e||{},r=t.now||{},n=t.lineShift||0,i=r.line||1,s=r.column||1;return{move:c,current:o,shift:u};function o(){return{now:{line:i,column:s},lineShift:n}}function u(f){n+=f}function c(f){let h=f||"",p=h.split(/\r?\n|\r/g),m=p[p.length-1];return i+=p.length-1,s=p.length===1?s+m.length:1+m.length+n,h}}s0.peek=__;function Vl(){return{enter:{gfmFootnoteDefinition:x_,gfmFootnoteDefinitionLabelString:b_,gfmFootnoteCall:k_,gfmFootnoteCallString:A_},exit:{gfmFootnoteDefinition:v_,gfmFootnoteDefinitionLabelString:w_,gfmFootnoteCall:E_,gfmFootnoteCallString:S_}}}function $l(){return{unsafe:[{character:"[",inConstruct:["phrasing","label","reference"]}],handlers:{footnoteDefinition:C_,footnoteReference:s0}}}function x_(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function b_(){this.buffer()}function w_(e){let t=this.resume(),r=this.stack[this.stack.length-1];r.label=t,r.identifier=st(this.sliceSerialize(e)).toLowerCase()}function v_(e){this.exit(e)}function k_(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function A_(){this.buffer()}function S_(e){let t=this.resume(),r=this.stack[this.stack.length-1];r.label=t,r.identifier=st(this.sliceSerialize(e)).toLowerCase()}function E_(e){this.exit(e)}function s0(e,t,r,n){let i=Or(n),s=i.move("[^"),o=r.enter("footnoteReference"),u=r.enter("reference");return s+=i.move(Ml(r,Bl(e),{...i.current(),before:s,after:"]"})),u(),o(),s+=i.move("]"),s}function __(){return"["}function C_(e,t,r,n){let i=Or(n),s=i.move("[^"),o=r.enter("footnoteDefinition"),u=r.enter("label");return s+=i.move(Ml(r,Bl(e),{...i.current(),before:s,after:"]"})),u(),s+=i.move("]:"+(e.children&&e.children.length>0?" ":"")),i.shift(4),s+=i.move(Ha(t0(e,r,i.current()),D_)),o(),s}function D_(e,t,r){return t===0?e:(r?"":" ")+e}function Li(e,t,r){let n=t.indexStack,i=e.children||[],s=[],o=-1,u=r.before;n.push(-1);let c=t.createTracker(r);for(;++o<i.length;){let f=i[o],h;if(n[n.length-1]=o,o+1<i.length){let p=t.handle.handlers[i[o+1].type];p&&p.peek&&(p=p.peek),h=p?p(i[o+1],e,t,{before:"",after:"",...c.current()}).charAt(0):""}else h=r.after;s.length>0&&(u==="\r"||u===`+`)&&f.type==="html"&&(s[s.length-1]=s[s.length-1].replace(/(\r?\n|\r)$/," "),u=" ",c=t.createTracker(r),c.move(s.join(""))),s.push(c.move(t.handle(f,e,t,{...c.current(),before:u,after:h}))),u=s[s.length-1].slice(-1)}return n.pop(),s.join("")}var I_=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];o0.peek=N_;var jl={canContainEols:["delete"],enter:{strikethrough:T_},exit:{strikethrough:R_}},Ul={unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:I_}],handlers:{delete:o0}};function T_(e){this.enter({type:"delete",children:[]},e)}function R_(e){this.exit(e)}function o0(e,t,r,n){let i=Or(n),s=r.enter("strikethrough"),o=i.move("~~");return o+=Li(e,r,{...i.current(),before:o,after:"~"}),o+=i.move("~~"),s(),o}function N_(){return"~"}ql.peek=P_;function ql(e,t,r){let n=e.value||"",i="`",s=-1;for(;new RegExp("(^|[^`])"+i+"([^`]|$)").test(n);)i+="`";for(/[^ \r\n]/.test(n)&&(/^[ \r\n]/.test(n)&&/[ \r\n]$/.test(n)||/^`|`$/.test(n))&&(n=" "+n+" ");++s<r.unsafe.length;){let o=r.unsafe[s],u=Wa(o),c;if(o.atBreak)for(;c=u.exec(n);){let f=c.index;n.charCodeAt(f)===10&&n.charCodeAt(f-1)===13&&f--,n=n.slice(0,f)+" "+n.slice(c.index+1)}}return i+n+i}function P_(){return"`"}function O_(e){return e.length}function u0(e,t){let r=t||{},n=(r.align||[]).concat(),i=r.stringLength||O_,s=[],o=[],u=[],c=[],f=0,h=-1;for(;++h<e.length;){let b=[],v=[],k=-1;for(e[h].length>f&&(f=e[h].length);++k<e[h].length;){let T=F_(e[h][k]);if(r.alignDelimiters!==!1){let E=i(T);v[k]=E,(c[k]===void 0||E>c[k])&&(c[k]=E)}b.push(T)}o[h]=b,u[h]=v}let p=-1;if(typeof n=="object"&&"length"in n)for(;++p<f;)s[p]=a0(n[p]);else{let b=a0(n);for(;++p<f;)s[p]=b}p=-1;let m=[],d=[];for(;++p<f;){let b=s[p],v="",k="";b===99?(v=":",k=":"):b===108?v=":":b===114&&(k=":");let T=r.alignDelimiters===!1?1:Math.max(1,c[p]-v.length-k.length),E=v+"-".repeat(T)+k;r.alignDelimiters!==!1&&(T=v.length+T+k.length,T>c[p]&&(c[p]=T),d[p]=T),m[p]=E}o.splice(1,0,m),u.splice(1,0,d),h=-1;let x=[];for(;++h<o.length;){let b=o[h],v=u[h];p=-1;let k=[];for(;++p<f;){let T=b[p]||"",E="",g="";if(r.alignDelimiters!==!1){let I=c[p]-(v[p]||0),_=s[p];_===114?E=" ".repeat(I):_===99?I%2?(E=" ".repeat(I/2+.5),g=" ".repeat(I/2-.5)):(E=" ".repeat(I/2),g=E):g=" ".repeat(I)}r.delimiterStart!==!1&&!p&&k.push("|"),r.padding!==!1&&!(r.alignDelimiters===!1&&T==="")&&(r.delimiterStart!==!1||p)&&k.push(" "),r.alignDelimiters!==!1&&k.push(E),k.push(T),r.alignDelimiters!==!1&&k.push(g),r.padding!==!1&&k.push(" "),(r.delimiterEnd!==!1||p!==f-1)&&k.push("|")}x.push(r.delimiterEnd===!1?k.join("").replace(/ +$/,""):k.join(""))}return x.join(`+`)}function F_(e){return e==null?"":String(e)}function a0(e){let t=typeof e=="string"?e.codePointAt(0):0;return t===67||t===99?99:t===76||t===108?108:t===82||t===114?114:0}var Jl={enter:{table:L_,tableData:c0,tableHeader:c0,tableRow:B_},exit:{codeText:M_,table:z_,tableData:Zl,tableHeader:Zl,tableRow:Zl}};function L_(e){let t=e._align;this.enter({type:"table",align:t.map(r=>r==="none"?null:r),children:[]},e),this.setData("inTable",!0)}function z_(e){this.exit(e),this.setData("inTable")}function B_(e){this.enter({type:"tableRow",children:[]},e)}function Zl(e){this.exit(e)}function c0(e){this.enter({type:"tableCell",children:[]},e)}function M_(e){let t=this.resume();this.getData("inTable")&&(t=t.replace(/\\([\\|])/g,V_));let r=this.stack[this.stack.length-1];r.value=t,this.exit(e)}function V_(e,t){return t==="|"?t:e}function Gl(e){let t=e||{},r=t.tableCellPadding,n=t.tablePipeAlign,i=t.stringLength,s=r?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`+`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{table:o,tableRow:u,tableCell:c,inlineCode:m}};function o(d,x,b,v){return f(h(d,b,v),d.align)}function u(d,x,b,v){let k=p(d,b,v),T=f([k]);return T.slice(0,T.indexOf(`+`))}function c(d,x,b,v){let k=b.enter("tableCell"),T=b.enter("phrasing"),E=Li(d,b,{...v,before:s,after:s});return T(),k(),E}function f(d,x){return u0(d,{align:x,alignDelimiters:n,padding:r,stringLength:i})}function h(d,x,b){let v=d.children,k=-1,T=[],E=x.enter("table");for(;++k<v.length;)T[k]=p(v[k],x,b);return E(),T}function p(d,x,b){let v=d.children,k=-1,T=[],E=x.enter("tableRow");for(;++k<v.length;)T[k]=c(v[k],d,x,b);return E(),T}function m(d,x,b){let v=ql(d,x,b);return b.stack.includes("tableCell")&&(v=v.replace(/\|/g,"\\$&")),v}}function l0(e){let t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function f0(e){let t=e.options.listItemIndent||"tab";if(t===1||t==="1")return"one";if(t!=="tab"&&t!=="one"&&t!=="mixed")throw new Error("Cannot serialize items with `"+t+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return t}function p0(e,t,r,n){let i=f0(r),s=r.bulletCurrent||l0(r);t&&t.type==="list"&&t.ordered&&(s=(typeof t.start=="number"&&t.start>-1?t.start:1)+(r.options.incrementListMarker===!1?0:t.children.indexOf(e))+s);let o=s.length+1;(i==="tab"||i==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(o=Math.ceil(o/4)*4);let u=r.createTracker(n);u.move(s+" ".repeat(o-s.length)),u.shift(o);let c=r.enter("listItem"),f=r.indentLines(r.containerFlow(e,u.current()),h);return c(),f;function h(p,m,d){return m?(d?"":" ".repeat(o))+p:(d?s:s+" ".repeat(o-s.length))+p}}var Ql={exit:{taskListCheckValueChecked:h0,taskListCheckValueUnchecked:h0,paragraph:$_}},Hl={unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:j_}};function h0(e){let t=this.stack[this.stack.length-2];t.checked=e.type==="taskListCheckValueChecked"}function $_(e){let t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){let r=this.stack[this.stack.length-1],n=r.children[0];if(n&&n.type==="text"){let i=t.children,s=-1,o;for(;++s<i.length;){let u=i[s];if(u.type==="paragraph"){o=u;break}}o===r&&(n.value=n.value.slice(1),n.value.length===0?r.children.shift():r.position&&n.position&&typeof n.position.start.offset=="number"&&(n.position.start.column++,n.position.start.offset++,r.position.start=Object.assign({},n.position.start)))}}this.exit(e)}function j_(e,t,r,n){let i=e.children[0],s=typeof e.checked=="boolean"&&i&&i.type==="paragraph",o="["+(e.checked?"x":" ")+"] ",u=Or(n);s&&u.move(o);let c=p0(e,t,r,{...n,...u.current()});return s&&(c=c.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,f)),c;function f(h){return h+o}}function Wl(){return[Ll,Vl(),jl,Jl,Ql]}function Kl(e){return{extensions:[zl,$l(),Ul,Gl(e),Hl]}}function Xl(e={}){let t=this.data();r("micromarkExtensions",Kx(e)),r("fromMarkdownExtensions",Wl()),r("toMarkdownExtensions",Kl(e));function r(n,i){(t[n]?t[n]:t[n]=[]).push(i)}}var U_=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,78,5,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,199,7,137,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,55,9,266,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,233,0,3,0,8,1,6,0,475,6,110,6,6,9,4759,9,787719,239],b0=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,7,25,39,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,5,57,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,24,43,261,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,33,24,3,24,45,74,6,0,67,12,65,1,2,0,15,4,10,7381,42,31,98,114,8702,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,208,30,2,2,2,1,2,6,3,4,10,1,225,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4381,3,5773,3,7472,16,621,2467,541,1507,4938,6,8489],q_="\u200C\u200D\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0CF3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u180F-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1ABF-\u1ADD\u1AE0-\u1AEB\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\u30FB\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F\uFF65",w0="\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088F\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5C\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDC-\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7DC\uA7F1-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC",Yl={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},ef="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",Z_={5:ef,"5module":ef+" export import",6:ef+" const class extends export import super"},v0=/^in(stanceof)?$/,J_=new RegExp("["+w0+"]"),G_=new RegExp("["+w0+q_+"]");function rf(e,t){for(var r=65536,n=0;n<t.length;n+=2){if(r+=t[n],r>e)return!1;if(r+=t[n+1],r>=e)return!0}return!1}function Fr(e,t){return e<65?e===36:e<91?!0:e<97?e===95:e<123?!0:e<=65535?e>=170&&J_.test(String.fromCharCode(e)):t===!1?!1:rf(e,b0)}function Sn(e,t){return e<48?e===36:e<58?!0:e<65?!1:e<91?!0:e<97?e===95:e<123?!0:e<=65535?e>=170&&G_.test(String.fromCharCode(e)):t===!1?!1:rf(e,b0)||rf(e,U_)}var ke=function(t,r){r===void 0&&(r={}),this.label=t,this.keyword=r.keyword,this.beforeExpr=!!r.beforeExpr,this.startsExpr=!!r.startsExpr,this.isLoop=!!r.isLoop,this.isAssign=!!r.isAssign,this.prefix=!!r.prefix,this.postfix=!!r.postfix,this.binop=r.binop||null,this.updateContext=null};function Ut(e,t){return new ke(e,{beforeExpr:!0,binop:t})}var qt={beforeExpr:!0},kt={startsExpr:!0},af={};function we(e,t){return t===void 0&&(t={}),t.keyword=e,af[e]=new ke(e,t)}var A={num:new ke("num",kt),regexp:new ke("regexp",kt),string:new ke("string",kt),name:new ke("name",kt),privateId:new ke("privateId",kt),eof:new ke("eof"),bracketL:new ke("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new ke("]"),braceL:new ke("{",{beforeExpr:!0,startsExpr:!0}),braceR:new ke("}"),parenL:new ke("(",{beforeExpr:!0,startsExpr:!0}),parenR:new ke(")"),comma:new ke(",",qt),semi:new ke(";",qt),colon:new ke(":",qt),dot:new ke("."),question:new ke("?",qt),questionDot:new ke("?."),arrow:new ke("=>",qt),template:new ke("template"),invalidTemplate:new ke("invalidTemplate"),ellipsis:new ke("...",qt),backQuote:new ke("`",kt),dollarBraceL:new ke("${",{beforeExpr:!0,startsExpr:!0}),eq:new ke("=",{beforeExpr:!0,isAssign:!0}),assign:new ke("_=",{beforeExpr:!0,isAssign:!0}),incDec:new ke("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new ke("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:Ut("||",1),logicalAND:Ut("&&",2),bitwiseOR:Ut("|",3),bitwiseXOR:Ut("^",4),bitwiseAND:Ut("&",5),equality:Ut("==/!=/===/!==",6),relational:Ut("</>/<=/>=",7),bitShift:Ut("<</>>/>>>",8),plusMin:new ke("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:Ut("%",10),star:Ut("*",10),slash:Ut("/",10),starstar:new ke("**",{beforeExpr:!0}),coalesce:Ut("??",1),_break:we("break"),_case:we("case",qt),_catch:we("catch"),_continue:we("continue"),_debugger:we("debugger"),_default:we("default",qt),_do:we("do",{isLoop:!0,beforeExpr:!0}),_else:we("else",qt),_finally:we("finally"),_for:we("for",{isLoop:!0}),_function:we("function",kt),_if:we("if"),_return:we("return",qt),_switch:we("switch"),_throw:we("throw",qt),_try:we("try"),_var:we("var"),_const:we("const"),_while:we("while",{isLoop:!0}),_with:we("with"),_new:we("new",{beforeExpr:!0,startsExpr:!0}),_this:we("this",kt),_super:we("super",kt),_class:we("class",kt),_extends:we("extends",qt),_export:we("export"),_import:we("import",kt),_null:we("null",kt),_true:we("true",kt),_false:we("false",kt),_in:we("in",{beforeExpr:!0,binop:7}),_instanceof:we("instanceof",{beforeExpr:!0,binop:7}),_typeof:we("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:we("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:we("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},At=/\r\n?|\n|\u2028|\u2029/,Q_=new RegExp(At.source,"g");function zi(e){return e===10||e===13||e===8232||e===8233}function k0(e,t,r){r===void 0&&(r=e.length);for(var n=t;n<r;n++){var i=e.charCodeAt(n);if(zi(i))return n<r-1&&i===13&&e.charCodeAt(n+1)===10?n+2:n+1}return-1}var A0=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/,et=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g,S0=Object.prototype,H_=S0.hasOwnProperty,W_=S0.toString,Bi=Object.hasOwn||function(e,t){return H_.call(e,t)},d0=Array.isArray||function(e){return W_.call(e)==="[object Array]"},m0=Object.create(null);function An(e){return m0[e]||(m0[e]=new RegExp("^(?:"+e.replace(/ /g,"|")+")$"))}function Kr(e){return e<=65535?String.fromCharCode(e):(e-=65536,String.fromCharCode((e>>10)+55296,(e&1023)+56320))}var K_=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,Xs=function(t,r){this.line=t,this.column=r};Xs.prototype.offset=function(t){return new Xs(this.line,this.column+t)};var ru=function(t,r,n){this.start=r,this.end=n,t.sourceFile!==null&&(this.source=t.sourceFile)};function E0(e,t){for(var r=1,n=0;;){var i=k0(e,n,t);if(i<0)return new Xs(r,t-n);++r,n=i}}var nf={ecmaVersion:null,sourceType:"script",strict:!1,onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},g0=!1;function X_(e){var t={};for(var r in nf)t[r]=e&&Bi(e,r)?e[r]:nf[r];if(t.ecmaVersion==="latest"?t.ecmaVersion=1e8:t.ecmaVersion==null?(!g0&&typeof console=="object"&&console.warn&&(g0=!0,console.warn(`Since Acorn 8.0.0, options.ecmaVersion is required.+Defaulting to 2020, but this will stop working in the future.`)),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),t.allowReserved==null&&(t.allowReserved=t.ecmaVersion<5),(!e||e.allowHashBang==null)&&(t.allowHashBang=t.ecmaVersion>=14),d0(t.onToken)){var n=t.onToken;t.onToken=function(i){return n.push(i)}}if(d0(t.onComment)&&(t.onComment=Y_(t,t.onComment)),t.sourceType==="commonjs"&&t.allowAwaitOutsideFunction)throw new Error("Cannot use allowAwaitOutsideFunction with sourceType: commonjs");return t}function Y_(e,t){return function(r,n,i,s,o,u){var c={type:r?"Block":"Line",value:n,start:i,end:s};e.locations&&(c.loc=new ru(this,o,u)),e.ranges&&(c.range=[i,s]),t.push(c)}}var Zn=1,Jn=2,uf=4,_0=8,cf=16,C0=32,nu=64,D0=128,Gn=256,Ys=512,I0=1024,iu=Zn|Jn|Gn;function lf(e,t){return Jn|(e?uf:0)|(t?_0:0)}var Xa=0,ff=1,Yr=2,T0=3,R0=4,N0=5,Qe=function(t,r,n){this.options=t=X_(t),this.sourceFile=t.sourceFile,this.keywords=An(Z_[t.ecmaVersion>=6?6:t.sourceType==="module"?"5module":5]);var i="";t.allowReserved!==!0&&(i=Yl[t.ecmaVersion>=6?6:t.ecmaVersion===5?5:3],t.sourceType==="module"&&(i+=" await")),this.reservedWords=An(i);var s=(i?i+" ":"")+Yl.strict;this.reservedWordsStrict=An(s),this.reservedWordsStrictBind=An(s+" "+Yl.strictBind),this.input=String(r),this.containsEsc=!1,n?(this.pos=n,this.lineStart=this.input.lastIndexOf(`+`,n-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(At).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=A.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule=t.sourceType==="module",this.strict=this.inModule||t.strict===!0||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),this.pos===0&&t.allowHashBang&&this.input.slice(0,2)==="#!"&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(this.options.sourceType==="commonjs"?Jn:Zn),this.regexpState=null,this.privateNameStack=[]},Jt={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowReturn:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},allowUsing:{configurable:!0},inClassStaticBlock:{configurable:!0}};Qe.prototype.parse=function(){var t=this,r=this.options.program||this.startNode();return this.nextToken(),this.catchStackOverflow(function(){return t.parseTopLevel(r)})};Jt.inFunction.get=function(){return(this.currentVarScope().flags&Jn)>0};Jt.inGenerator.get=function(){return(this.currentVarScope().flags&_0)>0};Jt.inAsync.get=function(){return(this.currentVarScope().flags&uf)>0};Jt.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e],r=t.flags;if(r&(Gn|Ys))return!1;if(r&Jn)return(r&uf)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction};Jt.allowReturn.get=function(){return!!(this.inFunction||this.options.allowReturnOutsideFunction&&this.currentVarScope().flags&Zn)};Jt.allowSuper.get=function(){var e=this.currentThisScope(),t=e.flags;return(t&nu)>0||this.options.allowSuperOutsideMethod};Jt.allowDirectSuper.get=function(){return(this.currentThisScope().flags&D0)>0};Jt.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};Jt.allowNewDotTarget.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e],r=t.flags;if(r&(Gn|Ys)||r&Jn&&!(r&cf))return!0}return!1};Jt.allowUsing.get=function(){var e=this.currentScope(),t=e.flags;return!(t&I0||!this.inModule&&t&Zn)};Jt.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&Gn)>0};Qe.extend=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];for(var n=this,i=0;i<t.length;i++)n=t[i](n);return n};Qe.parse=function(t,r){return new this(r,t).parse()};Qe.parseExpressionAt=function(t,r,n){var i=new this(n,t,r);return i.nextToken(),i.parseExpression()};Qe.tokenizer=function(t,r){return new this(r,t)};Object.defineProperties(Qe.prototype,Jt);var at=Qe.prototype,eC=/^(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/;at.strictDirective=function(e){if(this.options.ecmaVersion<5)return!1;for(;;){et.lastIndex=e,e+=et.exec(this.input)[0].length;var t=eC.exec(this.input.slice(e));if(!t)return!1;if((t[1]||t[2])==="use strict"){et.lastIndex=e+t[0].length;var r=et.exec(this.input),n=r.index+r[0].length,i=this.input.charAt(n);return i===";"||i==="}"||At.test(r[0])&&!(/[(`.[+\-/*%<>=,?^&]/.test(i)||i==="!"&&this.input.charAt(n+1)==="=")}e+=t[0].length,et.lastIndex=e,e+=et.exec(this.input)[0].length,this.input[e]===";"&&e++}};at.eat=function(e){return this.type===e?(this.next(),!0):!1};at.isContextual=function(e){return this.type===A.name&&this.value===e&&!this.containsEsc};at.eatContextual=function(e){return this.isContextual(e)?(this.next(),!0):!1};at.catchStackOverflow=function(e){try{return e()}catch(t){if(t instanceof Error&&(/\bstack\b.*\b(exceeded|overflow)\b/i.test(t.message)||/\btoo much recursion\b/i.test(t.message)))this.raise(this.start,"Not enough stack space to parse input");else throw t}};at.expectContextual=function(e){this.eatContextual(e)||this.unexpected()};at.canInsertSemicolon=function(){return this.type===A.eof||this.type===A.braceR||At.test(this.input.slice(this.lastTokEnd,this.start))};at.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0};at.semicolon=function(){!this.eat(A.semi)&&!this.insertSemicolon()&&this.unexpected()};at.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0};at.expect=function(e){this.eat(e)||this.unexpected()};at.unexpected=function(e){this.raise(e??this.start,"Unexpected token")};var su=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};at.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var r=t?e.parenthesizedAssign:e.parenthesizedBind;r>-1&&this.raiseRecoverable(r,t?"Assigning to rvalue":"Parenthesized pattern")}};at.checkExpressionErrors=function(e,t){if(!e)return!1;var r=e.shorthandAssign,n=e.doubleProto;if(!t)return r>=0||n>=0;r>=0&&this.raise(r,"Shorthand property assignments are valid only in destructuring patterns"),n>=0&&this.raiseRecoverable(n,"Redefinition of __proto__ property")};at.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos<this.awaitPos)&&this.raise(this.yieldPos,"Yield expression cannot be a default value"),this.awaitPos&&this.raise(this.awaitPos,"Await expression cannot be a default value")};at.isSimpleAssignTarget=function(e){return e.type==="ParenthesizedExpression"?this.isSimpleAssignTarget(e.expression):e.type==="Identifier"||e.type==="MemberExpression"};var X=Qe.prototype;X.parseTopLevel=function(e){var t=Object.create(null);for(e.body||(e.body=[]);this.type!==A.eof;){var r=this.parseStatement(null,!0,t);e.body.push(r)}if(this.inModule)for(var n=0,i=Object.keys(this.undefinedExports);n<i.length;n+=1){var s=i[n];this.raiseRecoverable(this.undefinedExports[s].start,"Export '"+s+"' is not defined")}return this.adaptDirectivePrologue(e.body),this.next(),e.sourceType=this.options.sourceType==="commonjs"?"script":this.options.sourceType,this.finishNode(e,"Program")};var pf={kind:"loop"},tC={kind:"switch"};X.isLet=function(e){if(this.options.ecmaVersion<6||!this.isContextual("let"))return!1;et.lastIndex=this.pos;var t=et.exec(this.input),r=this.pos+t[0].length,n=this.fullCharCodeAt(r);if(n===91||n===92)return!0;if(e)return!1;if(n===123)return!0;if(Fr(n)){var i=r;do r+=n<=65535?1:2;while(Sn(n=this.fullCharCodeAt(r)));if(n===92)return!0;var s=this.input.slice(i,r);if(!v0.test(s))return!0}return!1};X.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;et.lastIndex=this.pos;var e=et.exec(this.input),t=this.pos+e[0].length,r;return!At.test(this.input.slice(this.pos,t))&&this.input.slice(t,t+8)==="function"&&(t+8===this.input.length||!(Sn(r=this.fullCharCodeAt(t+8))||r===92))};X.isUsingKeyword=function(e,t){if(this.options.ecmaVersion<17||!this.isContextual(e?"await":"using"))return!1;et.lastIndex=this.pos;var r=et.exec(this.input),n=this.pos+r[0].length;if(At.test(this.input.slice(this.pos,n)))return!1;if(e){var i=n+5,s;if(this.input.slice(n,i)!=="using"||i===this.input.length||Sn(s=this.fullCharCodeAt(i))||s===92)return!1;et.lastIndex=i;var o=et.exec(this.input);if(n=i+o[0].length,o&&At.test(this.input.slice(i,n)))return!1}var u=this.fullCharCodeAt(n);if(!Fr(u)&&u!==92)return!1;var c=n;do n+=u<=65535?1:2;while(Sn(u=this.fullCharCodeAt(n)));if(u===92)return!0;var f=this.input.slice(c,n);if(v0.test(f))return!1;if(t&&!e&&f==="of"){et.lastIndex=n;var h=et.exec(this.input);if(n=n+h[0].length,this.input.charCodeAt(n)!==61||(u=this.input.charCodeAt(n+1))===61||u===62)return!1}return!0};X.isAwaitUsing=function(e){return this.isUsingKeyword(!0,e)};X.isUsing=function(e){return this.isUsingKeyword(!1,e)};X.parseStatement=function(e,t,r){var n=this.type,i=this.startNode(),s;switch(this.isLet(e)&&(n=A._var,s="let"),n){case A._break:case A._continue:return this.parseBreakContinueStatement(i,n.keyword);case A._debugger:return this.parseDebuggerStatement(i);case A._do:return this.parseDoStatement(i);case A._for:return this.parseForStatement(i);case A._function:return e&&(this.strict||e!=="if"&&e!=="label")&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case A._class:return e&&this.unexpected(),this.parseClass(i,!0);case A._if:return this.parseIfStatement(i);case A._return:return this.parseReturnStatement(i);case A._switch:return this.parseSwitchStatement(i);case A._throw:return this.parseThrowStatement(i);case A._try:return this.parseTryStatement(i);case A._const:case A._var:return s=s||this.value,e&&s!=="var"&&this.unexpected(),this.parseVarStatement(i,s);case A._while:return this.parseWhileStatement(i);case A._with:return this.parseWithStatement(i);case A.braceL:return this.parseBlock(!0,i);case A.semi:return this.parseEmptyStatement(i);case A._export:case A._import:if(this.options.ecmaVersion>10&&n===A._import){et.lastIndex=this.pos;var o=et.exec(this.input),u=this.pos+o[0].length,c=this.input.charCodeAt(u);if(c===40||c===46)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===A._import?this.parseImport(i):this.parseExport(i,r);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!e);var f=this.isAwaitUsing(!1)?"await using":this.isUsing(!1)?"using":null;if(f)return this.allowUsing||this.raise(this.start,"Using declaration cannot appear in the top level when source type is `script` or in the bare case statement"),e&&this.raise(this.start,"Using declaration is not allowed in single-statement positions"),f==="await using"&&(this.canAwait||this.raise(this.start,"Await using cannot appear outside of async function"),this.next()),this.next(),this.parseVar(i,!1,f),this.semicolon(),this.finishNode(i,"VariableDeclaration");var h=this.value,p=this.parseExpression();return n===A.name&&p.type==="Identifier"&&this.eat(A.colon)?this.parseLabeledStatement(i,h,p,e):this.parseExpressionStatement(i,p)}};X.parseBreakContinueStatement=function(e,t){var r=t==="break";this.next(),this.eat(A.semi)||this.insertSemicolon()?e.label=null:this.type!==A.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var n=0;n<this.labels.length;++n){var i=this.labels[n];if((e.label==null||i.name===e.label.name)&&(i.kind!=null&&(r||i.kind==="loop")||e.label&&r))break}return n===this.labels.length&&this.raise(e.start,"Unsyntactic "+t),this.finishNode(e,r?"BreakStatement":"ContinueStatement")};X.parseDebuggerStatement=function(e){return this.next(),this.semicolon(),this.finishNode(e,"DebuggerStatement")};X.parseDoStatement=function(e){return this.next(),this.labels.push(pf),e.body=this.parseStatement("do"),this.labels.pop(),this.expect(A._while),e.test=this.parseParenExpression(),this.options.ecmaVersion>=6?this.eat(A.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")};X.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(pf),this.enterScope(0),this.expect(A.parenL),this.type===A.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var r=this.isLet();if(this.type===A._var||this.type===A._const||r){var n=this.startNode(),i=r?"let":this.value;return this.next(),this.parseVar(n,!0,i),this.finishNode(n,"VariableDeclaration"),this.parseForAfterInit(e,n,t)}var s=this.isContextual("let"),o=!1,u=this.isUsing(!0)?"using":this.isAwaitUsing(!0)?"await using":null;if(u){var c=this.startNode();return this.next(),u==="await using"&&(this.canAwait||this.raise(this.start,"Await using cannot appear outside of async function"),this.next()),this.parseVar(c,!0,u),this.finishNode(c,"VariableDeclaration"),this.parseForAfterInit(e,c,t)}var f=this.containsEsc,h=new su,p=this.start,m=t>-1?this.parseExprSubscripts(h,"await"):this.parseExpression(!0,h);return this.type===A._in||(o=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===A._in&&this.unexpected(t),e.await=!0):o&&this.options.ecmaVersion>=8&&(m.start===p&&!f&&m.type==="Identifier"&&m.name==="async"?this.unexpected():this.options.ecmaVersion>=9&&(e.await=!1)),s&&o&&this.raise(m.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(m,!1,h),this.checkLValPattern(m),this.parseForIn(e,m)):(this.checkExpressionErrors(h,!0),t>-1&&this.unexpected(t),this.parseFor(e,m))};X.parseForAfterInit=function(e,t,r){return(this.type===A._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&t.declarations.length===1?(this.type===A._in?((t.kind==="using"||t.kind==="await using")&&!t.declarations[0].init&&this.raise(this.start,"Using declaration is not allowed in for-in loops"),this.options.ecmaVersion>=9&&r>-1&&this.unexpected(r)):this.options.ecmaVersion>=9&&(e.await=r>-1),this.parseForIn(e,t)):(r>-1&&this.unexpected(r),this.parseFor(e,t))};X.parseFunctionStatement=function(e,t,r){return this.next(),this.parseFunction(e,Ks|(r?0:sf),!1,t)};X.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(A._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")};X.parseReturnStatement=function(e){return this.allowReturn||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(A.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")};X.parseSwitchStatement=function(e){this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(A.braceL),this.labels.push(tC),this.enterScope(I0);for(var t,r=!1;this.type!==A.braceR;)if(this.type===A._case||this.type===A._default){var n=this.type===A._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),n?t.test=this.parseExpression():(r&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),r=!0,t.test=null),this.expect(A.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")};X.parseThrowStatement=function(e){return this.next(),At.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var rC=[];X.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t=e.type==="Identifier";return this.enterScope(t?C0:0),this.checkLValPattern(e,t?R0:Yr),this.expect(A.parenR),e};X.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===A._catch){var t=this.startNode();this.next(),this.eat(A.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(A._finally)?this.parseBlock():null,!e.handler&&!e.finalizer&&this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")};X.parseVarStatement=function(e,t,r){return this.next(),this.parseVar(e,!1,t,r),this.semicolon(),this.finishNode(e,"VariableDeclaration")};X.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(pf),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")};X.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")};X.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")};X.parseLabeledStatement=function(e,t,r,n){for(var i=0,s=this.labels;i<s.length;i+=1){var o=s[i];o.name===t&&this.raise(r.start,"Label '"+t+"' is already declared")}for(var u=this.type.isLoop?"loop":this.type===A._switch?"switch":null,c=this.labels.length-1;c>=0;c--){var f=this.labels[c];if(f.statementStart===e.start)f.statementStart=this.start,f.kind=u;else break}return this.labels.push({name:t,kind:u,statementStart:this.start}),e.body=this.parseStatement(n?n.indexOf("label")===-1?n+"label":n:"label"),this.labels.pop(),e.label=r,this.finishNode(e,"LabeledStatement")};X.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")};X.parseBlock=function(e,t,r){for(e===void 0&&(e=!0),t===void 0&&(t=this.startNode()),t.body=[],this.expect(A.braceL),e&&this.enterScope(0);this.type!==A.braceR;){var n=this.parseStatement(null);t.body.push(n)}return r&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")};X.parseFor=function(e,t){return e.init=t,this.expect(A.semi),e.test=this.type===A.semi?null:this.parseExpression(),this.expect(A.semi),e.update=this.type===A.parenR?null:this.parseExpression(),this.expect(A.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")};X.parseForIn=function(e,t){var r=this.type===A._in;return this.next(),t.type==="VariableDeclaration"&&t.declarations[0].init!=null&&(!r||this.options.ecmaVersion<8||this.strict||t.kind!=="var"||t.declarations[0].id.type!=="Identifier")&&this.raise(t.start,(r?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=r?this.parseExpression():this.parseMaybeAssign(),this.expect(A.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,r?"ForInStatement":"ForOfStatement")};X.parseVar=function(e,t,r,n){for(e.declarations=[],e.kind=r;;){var i=this.startNode();if(this.parseVarId(i,r),this.eat(A.eq)?i.init=this.parseMaybeAssign(t):!n&&r==="const"&&!(this.type===A._in||this.options.ecmaVersion>=6&&this.isContextual("of"))?this.unexpected():!n&&(r==="using"||r==="await using")&&this.options.ecmaVersion>=17&&this.type!==A._in&&!this.isContextual("of")?this.raise(this.lastTokEnd,"Missing initializer in "+r+" declaration"):!n&&i.id.type!=="Identifier"&&!(t&&(this.type===A._in||this.isContextual("of")))?this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):i.init=null,e.declarations.push(this.finishNode(i,"VariableDeclarator")),!this.eat(A.comma))break}return e};X.parseVarId=function(e,t){e.id=t==="using"||t==="await using"?this.parseIdent():this.parseBindingAtom(),this.checkLValPattern(e.id,t==="var"?ff:Yr,!1)};var Ks=1,sf=2,P0=4;X.parseFunction=function(e,t,r,n,i){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!n)&&(this.type===A.star&&t&sf&&this.unexpected(),e.generator=this.eat(A.star)),this.options.ecmaVersion>=8&&(e.async=!!n),t&Ks&&(e.id=t&P0&&this.type!==A.name?null:this.parseIdent(),e.id&&!(t&sf)&&this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?ff:Yr:T0));var s=this.yieldPos,o=this.awaitPos,u=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(lf(e.async,e.generator)),t&Ks||(e.id=this.type===A.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,r,!1,i),this.yieldPos=s,this.awaitPos=o,this.awaitIdentPos=u,this.finishNode(e,t&Ks?"FunctionDeclaration":"FunctionExpression")};X.parseFunctionParams=function(e){this.expect(A.parenL),e.params=this.parseBindingList(A.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()};X.parseClass=function(e,t){this.next();var r=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var n=this.enterClassBody(),i=this.startNode(),s=!1;for(i.body=[],this.expect(A.braceL);this.type!==A.braceR;){var o=this.parseClassElement(e.superClass!==null);o&&(i.body.push(o),o.type==="MethodDefinition"&&o.kind==="constructor"?(s&&this.raiseRecoverable(o.start,"Duplicate constructor in the same class"),s=!0):o.key&&o.key.type==="PrivateIdentifier"&&nC(n,o)&&this.raiseRecoverable(o.key.start,"Identifier '#"+o.key.name+"' has already been declared"))}return this.strict=r,this.next(),e.body=this.finishNode(i,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")};X.parseClassElement=function(e){if(this.eat(A.semi))return null;var t=this.options.ecmaVersion,r=this.startNode(),n="",i=!1,s=!1,o="method",u=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(A.braceL))return this.parseClassStaticBlock(r),r;this.isClassElementNameStart()||this.type===A.star?u=!0:n="static"}if(r.static=u,!n&&t>=8&&this.eatContextual("async")&&((this.isClassElementNameStart()||this.type===A.star)&&!this.canInsertSemicolon()?s=!0:n="async"),!n&&(t>=9||!s)&&this.eat(A.star)&&(i=!0),!n&&!s&&!i){var c=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?o=c:n=c)}if(n?(r.computed=!1,r.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),r.key.name=n,this.finishNode(r.key,"Identifier")):this.parseClassElementName(r),t<13||this.type===A.parenL||o!=="method"||i||s){var f=!r.static&&Ya(r,"constructor"),h=f&&e;f&&o!=="method"&&this.raise(r.key.start,"Constructor can't have get/set modifier"),r.kind=f?"constructor":o,this.parseClassMethod(r,i,s,h)}else this.parseClassField(r);return r};X.isClassElementNameStart=function(){return this.type===A.name||this.type===A.privateId||this.type===A.num||this.type===A.string||this.type===A.bracketL||this.type.keyword};X.parseClassElementName=function(e){this.type===A.privateId?(this.value==="constructor"&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)};X.parseClassMethod=function(e,t,r,n){var i=e.key;e.kind==="constructor"?(t&&this.raise(i.start,"Constructor can't be a generator"),r&&this.raise(i.start,"Constructor can't be an async method")):e.static&&Ya(e,"prototype")&&this.raise(i.start,"Classes may not have a static property named prototype");var s=e.value=this.parseMethod(t,r,n);return e.kind==="get"&&s.params.length!==0&&this.raiseRecoverable(s.start,"getter should have no params"),e.kind==="set"&&s.params.length!==1&&this.raiseRecoverable(s.start,"setter should have exactly one param"),e.kind==="set"&&s.params[0].type==="RestElement"&&this.raiseRecoverable(s.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")};X.parseClassField=function(e){return Ya(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&Ya(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(A.eq)?(this.enterScope(Ys|nu),e.value=this.parseMaybeAssign(),this.exitScope()):e.value=null,this.semicolon(),this.finishNode(e,"PropertyDefinition")};X.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(Gn|nu);this.type!==A.braceR;){var r=this.parseStatement(null);e.body.push(r)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")};X.parseClassId=function(e,t){this.type===A.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,Yr,!1)):(t===!0&&this.unexpected(),e.id=null)};X.parseClassSuper=function(e){e.superClass=this.eat(A._extends)?this.parseExprSubscripts(null,!1):null};X.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared};X.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,r=e.used;if(this.options.checkPrivateFields)for(var n=this.privateNameStack.length,i=n===0?null:this.privateNameStack[n-1],s=0;s<r.length;++s){var o=r[s];Bi(t,o.name)||(i?i.used.push(o):this.raiseRecoverable(o.start,"Private field '#"+o.name+"' must be declared in an enclosing class"))}};function nC(e,t){var r=t.key.name,n=e[r],i="true";return t.type==="MethodDefinition"&&(t.kind==="get"||t.kind==="set")&&(i=(t.static?"s":"i")+t.kind),n==="iget"&&i==="iset"||n==="iset"&&i==="iget"||n==="sget"&&i==="sset"||n==="sset"&&i==="sget"?(e[r]="true",!1):n?!0:(e[r]=i,!1)}function Ya(e,t){var r=e.computed,n=e.key;return!r&&(n.type==="Identifier"&&n.name===t||n.type==="Literal"&&n.value===t)}X.parseExportAllDeclaration=function(e,t){return this.options.ecmaVersion>=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==A.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")};X.parseExport=function(e,t){if(this.next(),this.eat(A.star))return this.parseExportAllDeclaration(e,t);if(this.eat(A._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),e.declaration.type==="VariableDeclaration"?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null,this.options.ecmaVersion>=16&&(e.attributes=[]);else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==A.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var r=0,n=e.specifiers;r<n.length;r+=1){var i=n[r];this.checkUnreserved(i.local),this.checkLocalExport(i.local),i.local.type==="Literal"&&this.raise(i.local.start,"A string literal cannot be used as an exported binding without `from`.")}e.source=null,this.options.ecmaVersion>=16&&(e.attributes=[])}this.semicolon()}return this.finishNode(e,"ExportNamedDeclaration")};X.parseExportDeclaration=function(e){return this.parseStatement(null)};X.parseExportDefaultDeclaration=function(){var e;if(this.type===A._function||(e=this.isAsyncFunction())){var t=this.startNode();return this.next(),e&&this.next(),this.parseFunction(t,Ks|P0,!1,e)}else if(this.type===A._class){var r=this.startNode();return this.parseClass(r,"nullableID")}else{var n=this.parseMaybeAssign();return this.semicolon(),n}};X.checkExport=function(e,t,r){e&&(typeof t!="string"&&(t=t.type==="Identifier"?t.name:t.value),Bi(e,t)&&this.raiseRecoverable(r,"Duplicate export '"+t+"'"),e[t]=!0)};X.checkPatternExport=function(e,t){var r=t.type;if(r==="Identifier")this.checkExport(e,t,t.start);else if(r==="ObjectPattern")for(var n=0,i=t.properties;n<i.length;n+=1){var s=i[n];this.checkPatternExport(e,s)}else if(r==="ArrayPattern")for(var o=0,u=t.elements;o<u.length;o+=1){var c=u[o];c&&this.checkPatternExport(e,c)}else r==="Property"?this.checkPatternExport(e,t.value):r==="AssignmentPattern"?this.checkPatternExport(e,t.left):r==="RestElement"&&this.checkPatternExport(e,t.argument)};X.checkVariableExport=function(e,t){if(e)for(var r=0,n=t;r<n.length;r+=1){var i=n[r];this.checkPatternExport(e,i.id)}};X.shouldParseExportStatement=function(){return this.type.keyword==="var"||this.type.keyword==="const"||this.type.keyword==="class"||this.type.keyword==="function"||this.isLet()||this.isAsyncFunction()};X.parseExportSpecifier=function(e){var t=this.startNode();return t.local=this.parseModuleExportName(),t.exported=this.eatContextual("as")?this.parseModuleExportName():t.local,this.checkExport(e,t.exported,t.exported.start),this.finishNode(t,"ExportSpecifier")};X.parseExportSpecifiers=function(e){var t=[],r=!0;for(this.expect(A.braceL);!this.eat(A.braceR);){if(r)r=!1;else if(this.expect(A.comma),this.afterTrailingComma(A.braceR))break;t.push(this.parseExportSpecifier(e))}return t};X.parseImport=function(e){return this.next(),this.type===A.string?(e.specifiers=rC,e.source=this.parseExprAtom()):(e.specifiers=this.parseImportSpecifiers(),this.expectContextual("from"),e.source=this.type===A.string?this.parseExprAtom():this.unexpected()),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")};X.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,Yr),this.finishNode(e,"ImportSpecifier")};X.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,Yr),this.finishNode(e,"ImportDefaultSpecifier")};X.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,Yr),this.finishNode(e,"ImportNamespaceSpecifier")};X.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===A.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(A.comma)))return e;if(this.type===A.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(A.braceL);!this.eat(A.braceR);){if(t)t=!1;else if(this.expect(A.comma),this.afterTrailingComma(A.braceR))break;e.push(this.parseImportSpecifier())}return e};X.parseWithClause=function(){var e=[];if(!this.eat(A._with))return e;this.expect(A.braceL);for(var t={},r=!0;!this.eat(A.braceR);){if(r)r=!1;else if(this.expect(A.comma),this.afterTrailingComma(A.braceR))break;var n=this.parseImportAttribute(),i=n.key.type==="Identifier"?n.key.name:n.key.value;Bi(t,i)&&this.raiseRecoverable(n.key.start,"Duplicate attribute key '"+i+"'"),t[i]=!0,e.push(n)}return e};X.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===A.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never"),this.expect(A.colon),this.type!==A.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")};X.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===A.string){var e=this.parseLiteral(this.value);return K_.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)};X.adaptDirectivePrologue=function(e){for(var t=0;t<e.length&&this.isDirectiveCandidate(e[t]);++t)e[t].directive=e[t].expression.raw.slice(1,-1)};X.isDirectiveCandidate=function(e){return this.options.ecmaVersion>=5&&e.type==="ExpressionStatement"&&e.expression.type==="Literal"&&typeof e.expression.value=="string"&&(this.input[e.start]==='"'||this.input[e.start]==="'")};var Gt=Qe.prototype;Gt.toAssignable=function(e,t,r){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&e.name==="await"&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",r&&this.checkPatternErrors(r,!0);for(var n=0,i=e.properties;n<i.length;n+=1){var s=i[n];this.toAssignable(s,t),s.type==="RestElement"&&(s.argument.type==="ArrayPattern"||s.argument.type==="ObjectPattern")&&this.raise(s.argument.start,"Unexpected token")}break;case"Property":e.kind!=="init"&&this.raise(e.key.start,"Object pattern can't contain getter or setter"),this.toAssignable(e.value,t);break;case"ArrayExpression":e.type="ArrayPattern",r&&this.checkPatternErrors(r,!0),this.toAssignableList(e.elements,t);break;case"SpreadElement":e.type="RestElement",this.toAssignable(e.argument,t),e.argument.type==="AssignmentPattern"&&this.raise(e.argument.start,"Rest elements cannot have a default value");break;case"AssignmentExpression":e.operator!=="="&&this.raise(e.left.end,"Only '=' operator can be used for specifying default value."),e.type="AssignmentPattern",delete e.operator,this.toAssignable(e.left,t);break;case"ParenthesizedExpression":this.toAssignable(e.expression,t,r);break;case"ChainExpression":this.raiseRecoverable(e.start,"Optional chaining cannot appear in left-hand side");break;case"MemberExpression":if(!t)break;default:this.raise(e.start,"Assigning to rvalue")}else r&&this.checkPatternErrors(r,!0);return e};Gt.toAssignableList=function(e,t){for(var r=e.length,n=0;n<r;n++){var i=e[n];i&&this.toAssignable(i,t)}if(r){var s=e[r-1];this.options.ecmaVersion===6&&t&&s&&s.type==="RestElement"&&s.argument.type!=="Identifier"&&this.unexpected(s.argument.start)}return e};Gt.parseSpread=function(e){var t=this.startNode();return this.next(),t.argument=this.parseMaybeAssign(!1,e),this.finishNode(t,"SpreadElement")};Gt.parseRestBinding=function(){var e=this.startNode();return this.next(),this.options.ecmaVersion===6&&this.type!==A.name&&this.unexpected(),e.argument=this.parseBindingAtom(),this.finishNode(e,"RestElement")};Gt.parseBindingAtom=function(){if(this.options.ecmaVersion>=6)switch(this.type){case A.bracketL:var e=this.startNode();return this.next(),e.elements=this.parseBindingList(A.bracketR,!0,!0),this.finishNode(e,"ArrayPattern");case A.braceL:return this.parseObj(!0)}return this.parseIdent()};Gt.parseBindingList=function(e,t,r,n){for(var i=[],s=!0;!this.eat(e);)if(s?s=!1:this.expect(A.comma),t&&this.type===A.comma)i.push(null);else{if(r&&this.afterTrailingComma(e))break;if(this.type===A.ellipsis){var o=this.parseRestBinding();this.parseBindingListItem(o),i.push(o),this.type===A.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.expect(e);break}else i.push(this.parseAssignableListItem(n))}return i};Gt.parseAssignableListItem=function(e){var t=this.parseMaybeDefault(this.start,this.startLoc);return this.parseBindingListItem(t),t};Gt.parseBindingListItem=function(e){return e};Gt.parseMaybeDefault=function(e,t,r){if(r=r||this.parseBindingAtom(),this.options.ecmaVersion<6||!this.eat(A.eq))return r;var n=this.startNodeAt(e,t);return n.left=r,n.right=this.parseMaybeAssign(),this.finishNode(n,"AssignmentPattern")};Gt.checkLValSimple=function(e,t,r){t===void 0&&(t=Xa);var n=t!==Xa;switch(e.type){case"Identifier":this.strict&&this.reservedWordsStrictBind.test(e.name)&&this.raiseRecoverable(e.start,(n?"Binding ":"Assigning to ")+e.name+" in strict mode"),n&&(t===Yr&&e.name==="let"&&this.raiseRecoverable(e.start,"let is disallowed as a lexically bound name"),r&&(Bi(r,e.name)&&this.raiseRecoverable(e.start,"Argument name clash"),r[e.name]=!0),t!==N0&&this.declareName(e.name,t,e.start));break;case"ChainExpression":this.raiseRecoverable(e.start,"Optional chaining cannot appear in left-hand side");break;case"MemberExpression":n&&this.raiseRecoverable(e.start,"Binding member expression");break;case"ParenthesizedExpression":return n&&this.raiseRecoverable(e.start,"Binding parenthesized expression"),this.checkLValSimple(e.expression,t,r);default:this.raise(e.start,(n?"Binding":"Assigning to")+" rvalue")}};Gt.checkLValPattern=function(e,t,r){switch(t===void 0&&(t=Xa),e.type){case"ObjectPattern":for(var n=0,i=e.properties;n<i.length;n+=1){var s=i[n];this.checkLValInnerPattern(s,t,r)}break;case"ArrayPattern":for(var o=0,u=e.elements;o<u.length;o+=1){var c=u[o];c&&this.checkLValInnerPattern(c,t,r)}break;default:this.checkLValSimple(e,t,r)}};Gt.checkLValInnerPattern=function(e,t,r){switch(t===void 0&&(t=Xa),e.type){case"Property":this.checkLValInnerPattern(e.value,t,r);break;case"AssignmentPattern":this.checkLValPattern(e.left,t,r);break;case"RestElement":this.checkLValPattern(e.argument,t,r);break;default:this.checkLValPattern(e,t,r)}};var gr=function(t,r,n,i,s){this.token=t,this.isExpr=!!r,this.preserveSpace=!!n,this.override=i,this.generator=!!s},Me={b_stat:new gr("{",!1),b_expr:new gr("{",!0),b_tmpl:new gr("${",!1),p_stat:new gr("(",!1),p_expr:new gr("(",!0),q_tmpl:new gr("`",!0,!0,function(e){return e.tryReadTemplateToken()}),f_stat:new gr("function",!1),f_expr:new gr("function",!0),f_expr_gen:new gr("function",!0,!1,null,!0),f_gen:new gr("function",!1,!1,null,!0)},Mi=Qe.prototype;Mi.initialContext=function(){return[Me.b_stat]};Mi.curContext=function(){return this.context[this.context.length-1]};Mi.braceIsBlock=function(e){var t=this.curContext();return t===Me.f_expr||t===Me.f_stat?!0:e===A.colon&&(t===Me.b_stat||t===Me.b_expr)?!t.isExpr:e===A._return||e===A.name&&this.exprAllowed?At.test(this.input.slice(this.lastTokEnd,this.start)):e===A._else||e===A.semi||e===A.eof||e===A.parenR||e===A.arrow?!0:e===A.braceL?t===Me.b_stat:e===A._var||e===A._const||e===A.name?!1:!this.exprAllowed};Mi.inGeneratorContext=function(){for(var e=this.context.length-1;e>=1;e--){var t=this.context[e];if(t.token==="function")return t.generator}return!1};Mi.updateContext=function(e){var t,r=this.type;r.keyword&&e===A.dot?this.exprAllowed=!1:(t=r.updateContext)?t.call(this,e):this.exprAllowed=r.beforeExpr};Mi.overrideContext=function(e){this.curContext()!==e&&(this.context[this.context.length-1]=e)};A.parenR.updateContext=A.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=!0;return}var e=this.context.pop();e===Me.b_stat&&this.curContext().token==="function"&&(e=this.context.pop()),this.exprAllowed=!e.isExpr};A.braceL.updateContext=function(e){this.context.push(this.braceIsBlock(e)?Me.b_stat:Me.b_expr),this.exprAllowed=!0};A.dollarBraceL.updateContext=function(){this.context.push(Me.b_tmpl),this.exprAllowed=!0};A.parenL.updateContext=function(e){var t=e===A._if||e===A._for||e===A._with||e===A._while;this.context.push(t?Me.p_stat:Me.p_expr),this.exprAllowed=!0};A.incDec.updateContext=function(){};A._function.updateContext=A._class.updateContext=function(e){e.beforeExpr&&e!==A._else&&!(e===A.semi&&this.curContext()!==Me.p_stat)&&!(e===A._return&&At.test(this.input.slice(this.lastTokEnd,this.start)))&&!((e===A.colon||e===A.braceL)&&this.curContext()===Me.b_stat)?this.context.push(Me.f_expr):this.context.push(Me.f_stat),this.exprAllowed=!1};A.colon.updateContext=function(){this.curContext().token==="function"&&this.context.pop(),this.exprAllowed=!0};A.backQuote.updateContext=function(){this.curContext()===Me.q_tmpl?this.context.pop():this.context.push(Me.q_tmpl),this.exprAllowed=!1};A.star.updateContext=function(e){if(e===A._function){var t=this.context.length-1;this.context[t]===Me.f_expr?this.context[t]=Me.f_expr_gen:this.context[t]=Me.f_gen}this.exprAllowed=!0};A.name.updateContext=function(e){var t=!1;this.options.ecmaVersion>=6&&e!==A.dot&&(this.value==="of"&&!this.exprAllowed||this.value==="yield"&&this.inGeneratorContext())&&(t=!0),this.exprAllowed=t};var ce=Qe.prototype;ce.checkPropClash=function(e,t,r){if(!(this.options.ecmaVersion>=9&&e.type==="SpreadElement")&&!(this.options.ecmaVersion>=6&&(e.computed||e.method||e.shorthand))){var n=e.key,i;switch(n.type){case"Identifier":i=n.name;break;case"Literal":i=String(n.value);break;default:return}var s=e.kind;if(this.options.ecmaVersion>=6){i==="__proto__"&&s==="init"&&(t.proto&&(r?r.doubleProto<0&&(r.doubleProto=n.start):this.raiseRecoverable(n.start,"Redefinition of __proto__ property")),t.proto=!0);return}i="$"+i;var o=t[i];if(o){var u;s==="init"?u=this.strict&&o.init||o.get||o.set:u=o.init||o[s],u&&this.raiseRecoverable(n.start,"Redefinition of property")}else o=t[i]={init:!1,get:!1,set:!1};o[s]=!0}};ce.parseExpression=function(e,t){var r=this;return this.catchStackOverflow(function(){var n=r.start,i=r.startLoc,s=r.parseMaybeAssign(e,t);if(r.type===A.comma){var o=r.startNodeAt(n,i);for(o.expressions=[s];r.eat(A.comma);)o.expressions.push(r.parseMaybeAssign(e,t));return r.finishNode(o,"SequenceExpression")}return s})};ce.parseMaybeAssign=function(e,t,r){if(this.isContextual("yield")){if(this.inGenerator)return this.parseYield(e);this.exprAllowed=!1}var n=!1,i=-1,s=-1,o=-1;t?(i=t.parenthesizedAssign,s=t.trailingComma,o=t.doubleProto,t.parenthesizedAssign=t.trailingComma=-1):(t=new su,n=!0);var u=this.start,c=this.startLoc;(this.type===A.parenL||this.type===A.name)&&(this.potentialArrowAt=this.start,this.potentialArrowInForAwait=e==="await");var f=this.parseMaybeConditional(e,t);if(r&&(f=r.call(this,f,u,c)),this.type.isAssign){var h=this.startNodeAt(u,c);return h.operator=this.value,this.type===A.eq&&(f=this.toAssignable(f,!1,t)),n||(t.parenthesizedAssign=t.trailingComma=t.doubleProto=-1),t.shorthandAssign>=f.start&&(t.shorthandAssign=-1),this.type===A.eq?this.checkLValPattern(f):this.checkLValSimple(f),h.left=f,this.next(),h.right=this.parseMaybeAssign(e),o>-1&&(t.doubleProto=o),this.finishNode(h,"AssignmentExpression")}else n&&this.checkExpressionErrors(t,!0);return i>-1&&(t.parenthesizedAssign=i),s>-1&&(t.trailingComma=s),f};ce.parseMaybeConditional=function(e,t){var r=this.start,n=this.startLoc,i=this.parseExprOps(e,t);if(this.checkExpressionErrors(t))return i;if(!(i.type==="ArrowFunctionExpression"&&i.start===r)&&this.eat(A.question)){var s=this.startNodeAt(r,n);return s.test=i,s.consequent=this.parseMaybeAssign(),this.expect(A.colon),s.alternate=this.parseMaybeAssign(e),this.finishNode(s,"ConditionalExpression")}return i};ce.parseExprOps=function(e,t){var r=this.start,n=this.startLoc,i=this.parseMaybeUnary(t,!1,!1,e);return this.checkExpressionErrors(t)||i.start===r&&i.type==="ArrowFunctionExpression"?i:this.parseExprOp(i,r,n,-1,e)};ce.parseExprOp=function(e,t,r,n,i){var s=this.type.binop;if(s!=null&&(!i||this.type!==A._in)&&s>n){var o=this.type===A.logicalOR||this.type===A.logicalAND,u=this.type===A.coalesce;u&&(s=A.logicalAND.binop);var c=this.value;this.next();var f=this.start,h=this.startLoc,p=this.parseExprOp(this.parseMaybeUnary(null,!1,!1,i),f,h,s,i),m=this.buildBinary(t,r,e,p,c,o||u);return(o&&this.type===A.coalesce||u&&(this.type===A.logicalOR||this.type===A.logicalAND))&&this.raiseRecoverable(this.start,"Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"),this.parseExprOp(m,t,r,n,i)}return e};ce.buildBinary=function(e,t,r,n,i,s){n.type==="PrivateIdentifier"&&this.raise(n.start,"Private identifier can only be left side of binary expression");var o=this.startNodeAt(e,t);return o.left=r,o.operator=i,o.right=n,this.finishNode(o,s?"LogicalExpression":"BinaryExpression")};ce.parseMaybeUnary=function(e,t,r,n){var i=this.start,s=this.startLoc,o;if(this.isContextual("await")&&this.canAwait)o=this.parseAwait(n),t=!0;else if(this.type.prefix){var u=this.startNode(),c=this.type===A.incDec;u.operator=this.value,u.prefix=!0,this.next(),u.argument=this.parseMaybeUnary(null,!0,c,n),this.checkExpressionErrors(e,!0),c?this.checkLValSimple(u.argument):this.strict&&u.operator==="delete"&&O0(u.argument)?this.raiseRecoverable(u.start,"Deleting local variable in strict mode"):u.operator==="delete"&&of(u.argument)?this.raiseRecoverable(u.start,"Private fields can not be deleted"):t=!0,o=this.finishNode(u,c?"UpdateExpression":"UnaryExpression")}else if(!t&&this.type===A.privateId)(n||this.privateNameStack.length===0)&&this.options.checkPrivateFields&&this.unexpected(),o=this.parsePrivateIdent(),this.type!==A._in&&this.unexpected();else{if(o=this.parseExprSubscripts(e,n),this.checkExpressionErrors(e))return o;for(;this.type.postfix&&!this.canInsertSemicolon();){var f=this.startNodeAt(i,s);f.operator=this.value,f.prefix=!1,f.argument=o,this.checkLValSimple(o),this.next(),o=this.finishNode(f,"UpdateExpression")}}if(!r&&this.eat(A.starstar))if(t)this.unexpected(this.lastTokStart);else return this.buildBinary(i,s,o,this.parseMaybeUnary(null,!1,!1,n),"**",!1);else return o};function O0(e){return e.type==="Identifier"||e.type==="ParenthesizedExpression"&&O0(e.expression)}function of(e){return e.type==="MemberExpression"&&e.property.type==="PrivateIdentifier"||e.type==="ChainExpression"&&of(e.expression)||e.type==="ParenthesizedExpression"&&of(e.expression)}ce.parseExprSubscripts=function(e,t){var r=this.start,n=this.startLoc,i=this.parseExprAtom(e,t);if(i.type==="ArrowFunctionExpression"&&this.input.slice(this.lastTokStart,this.lastTokEnd)!==")")return i;var s=this.parseSubscripts(i,r,n,!1,t);return e&&s.type==="MemberExpression"&&(e.parenthesizedAssign>=s.start&&(e.parenthesizedAssign=-1),e.parenthesizedBind>=s.start&&(e.parenthesizedBind=-1),e.trailingComma>=s.start&&(e.trailingComma=-1)),s};ce.parseSubscripts=function(e,t,r,n,i){for(var s=this.options.ecmaVersion>=8&&e.type==="Identifier"&&e.name==="async"&&this.lastTokEnd===e.end&&!this.canInsertSemicolon()&&e.end-e.start===5&&this.potentialArrowAt===e.start,o=!1;;){var u=this.parseSubscript(e,t,r,n,s,o,i);if(u.optional&&(o=!0),u===e||u.type==="ArrowFunctionExpression"){if(o){var c=this.startNodeAt(t,r);c.expression=u,u=this.finishNode(c,"ChainExpression")}return u}e=u}};ce.shouldParseAsyncArrow=function(){return!this.canInsertSemicolon()&&this.eat(A.arrow)};ce.parseSubscriptAsyncArrow=function(e,t,r,n){return this.parseArrowExpression(this.startNodeAt(e,t),r,!0,n)};ce.parseSubscript=function(e,t,r,n,i,s,o){var u=this.options.ecmaVersion>=11,c=u&&this.eat(A.questionDot);n&&c&&this.raise(this.lastTokStart,"Optional chaining cannot appear in the callee of new expressions");var f=this.eat(A.bracketL);if(f||c&&this.type!==A.parenL&&this.type!==A.backQuote||this.eat(A.dot)){var h=this.startNodeAt(t,r);h.object=e,f?(h.property=this.parseExpression(),this.expect(A.bracketR)):this.type===A.privateId&&e.type!=="Super"?h.property=this.parsePrivateIdent():h.property=this.parseIdent(this.options.allowReserved!=="never"),h.computed=!!f,u&&(h.optional=c),e=this.finishNode(h,"MemberExpression")}else if(!n&&this.eat(A.parenL)){var p=new su,m=this.yieldPos,d=this.awaitPos,x=this.awaitIdentPos;this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0;var b=this.parseExprList(A.parenR,this.options.ecmaVersion>=8,!1,p);if(i&&!c&&this.shouldParseAsyncArrow())return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.awaitIdentPos>0&&this.raise(this.awaitIdentPos,"Cannot use 'await' as identifier inside an async function"),this.yieldPos=m,this.awaitPos=d,this.awaitIdentPos=x,this.parseSubscriptAsyncArrow(t,r,b,o);this.checkExpressionErrors(p,!0),this.yieldPos=m||this.yieldPos,this.awaitPos=d||this.awaitPos,this.awaitIdentPos=x||this.awaitIdentPos;var v=this.startNodeAt(t,r);v.callee=e,v.arguments=b,u&&(v.optional=c),e=this.finishNode(v,"CallExpression")}else if(this.type===A.backQuote){(c||s)&&this.raise(this.start,"Optional chaining cannot appear in the tag of tagged template expressions");var k=this.startNodeAt(t,r);k.tag=e,k.quasi=this.parseTemplate({isTagged:!0}),e=this.finishNode(k,"TaggedTemplateExpression")}return e};ce.parseExprAtom=function(e,t,r){this.type===A.slash&&this.readRegexp();var n,i=this.potentialArrowAt===this.start;switch(this.type){case A._super:return this.allowSuper||this.raise(this.start,"'super' keyword outside a method"),n=this.startNode(),this.next(),this.type===A.parenL&&!this.allowDirectSuper&&this.raise(n.start,"super() call outside constructor of a subclass"),this.type!==A.dot&&this.type!==A.bracketL&&this.type!==A.parenL&&this.unexpected(),this.finishNode(n,"Super");case A._this:return n=this.startNode(),this.next(),this.finishNode(n,"ThisExpression");case A.name:var s=this.start,o=this.startLoc,u=this.containsEsc,c=this.parseIdent(!1);if(this.options.ecmaVersion>=8&&!u&&c.name==="async"&&!this.canInsertSemicolon()&&this.eat(A._function))return this.overrideContext(Me.f_expr),this.parseFunction(this.startNodeAt(s,o),0,!1,!0,t);if(i&&!this.canInsertSemicolon()){if(this.eat(A.arrow))return this.parseArrowExpression(this.startNodeAt(s,o),[c],!1,t);if(this.options.ecmaVersion>=8&&c.name==="async"&&this.type===A.name&&!u&&(!this.potentialArrowInForAwait||this.value!=="of"||this.containsEsc))return c=this.parseIdent(!1),(this.canInsertSemicolon()||!this.eat(A.arrow))&&this.unexpected(),this.parseArrowExpression(this.startNodeAt(s,o),[c],!0,t)}return c;case A.regexp:var f=this.value;return n=this.parseLiteral(f.value),n.regex={pattern:f.pattern,flags:f.flags},n;case A.num:case A.string:return this.parseLiteral(this.value);case A._null:case A._true:case A._false:return n=this.startNode(),n.value=this.type===A._null?null:this.type===A._true,n.raw=this.type.keyword,this.next(),this.finishNode(n,"Literal");case A.parenL:var h=this.start,p=this.parseParenAndDistinguishExpression(i,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(p)&&(e.parenthesizedAssign=h),e.parenthesizedBind<0&&(e.parenthesizedBind=h)),p;case A.bracketL:return n=this.startNode(),this.next(),n.elements=this.parseExprList(A.bracketR,!0,!0,e),this.finishNode(n,"ArrayExpression");case A.braceL:return this.overrideContext(Me.b_expr),this.parseObj(!1,e);case A._function:return n=this.startNode(),this.next(),this.parseFunction(n,0);case A._class:return this.parseClass(this.startNode(),!1);case A._new:return this.parseNew();case A.backQuote:return this.parseTemplate();case A._import:return this.options.ecmaVersion>=11?this.parseExprImport(r):this.unexpected();default:return this.parseExprAtomDefault()}};ce.parseExprAtomDefault=function(){this.unexpected()};ce.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===A.parenL&&!e)return this.parseDynamicImport(t);if(this.type===A.dot){var r=this.startNodeAt(t.start,t.loc&&t.loc.start);return r.name="import",t.meta=this.finishNode(r,"Identifier"),this.parseImportMeta(t)}else this.unexpected()};ce.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(A.parenR)?e.options=null:(this.expect(A.comma),this.afterTrailingComma(A.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(A.parenR)||(this.expect(A.comma),this.afterTrailingComma(A.parenR)||this.unexpected())));else if(!this.eat(A.parenR)){var t=this.start;this.eat(A.comma)&&this.eat(A.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")};ce.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),e.property.name!=="meta"&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),this.options.sourceType!=="module"&&!this.options.allowImportExportEverywhere&&this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")};ce.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),t.raw.charCodeAt(t.raw.length-1)===110&&(t.bigint=t.value!=null?t.value.toString():t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")};ce.parseParenExpression=function(){this.expect(A.parenL);var e=this.parseExpression();return this.expect(A.parenR),e};ce.shouldParseArrow=function(e){return!this.canInsertSemicolon()};ce.parseParenAndDistinguishExpression=function(e,t){var r=this.start,n=this.startLoc,i,s=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var o=this.start,u=this.startLoc,c=[],f=!0,h=!1,p=new su,m=this.yieldPos,d=this.awaitPos,x;for(this.yieldPos=0,this.awaitPos=0;this.type!==A.parenR;)if(f?f=!1:this.expect(A.comma),s&&this.afterTrailingComma(A.parenR,!0)){h=!0;break}else if(this.type===A.ellipsis){x=this.start,c.push(this.parseParenItem(this.parseRestBinding())),this.type===A.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}else c.push(this.parseMaybeAssign(!1,p,this.parseParenItem));var b=this.lastTokEnd,v=this.lastTokEndLoc;if(this.expect(A.parenR),e&&this.shouldParseArrow(c)&&this.eat(A.arrow))return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=m,this.awaitPos=d,this.parseParenArrowList(r,n,c,t);(!c.length||h)&&this.unexpected(this.lastTokStart),x&&this.unexpected(x),this.checkExpressionErrors(p,!0),this.yieldPos=m||this.yieldPos,this.awaitPos=d||this.awaitPos,c.length>1?(i=this.startNodeAt(o,u),i.expressions=c,this.finishNodeAt(i,"SequenceExpression",b,v)):i=c[0]}else i=this.parseParenExpression();if(this.options.preserveParens){var k=this.startNodeAt(r,n);return k.expression=i,this.finishNode(k,"ParenthesizedExpression")}else return i};ce.parseParenItem=function(e){return e};ce.parseParenArrowList=function(e,t,r,n){return this.parseArrowExpression(this.startNodeAt(e,t),r,!1,n)};var iC=[];ce.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===A.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var r=this.containsEsc;return e.property=this.parseIdent(!0),e.property.name!=="target"&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),r&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var n=this.start,i=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),n,i,!0,!1),e.callee.type==="Super"&&this.raiseRecoverable(n,"Invalid use of 'super'"),this.eat(A.parenL)?e.arguments=this.parseExprList(A.parenR,this.options.ecmaVersion>=8,!1):e.arguments=iC,this.finishNode(e,"NewExpression")};ce.parseTemplateElement=function(e){var t=e.isTagged,r=this.startNode();return this.type===A.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),r.value={raw:this.value.replace(/\r\n?/g,`+`),cooked:null}):r.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,`+`),cooked:this.value},this.next(),r.tail=this.type===A.backQuote,this.finishNode(r,"TemplateElement")};ce.parseTemplate=function(e){e===void 0&&(e={});var t=e.isTagged;t===void 0&&(t=!1);var r=this.startNode();this.next(),r.expressions=[];var n=this.parseTemplateElement({isTagged:t});for(r.quasis=[n];!n.tail;)this.type===A.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(A.dollarBraceL),r.expressions.push(this.parseExpression()),this.expect(A.braceR),r.quasis.push(n=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(r,"TemplateLiteral")};ce.isAsyncProp=function(e){return!e.computed&&e.key.type==="Identifier"&&e.key.name==="async"&&(this.type===A.name||this.type===A.num||this.type===A.string||this.type===A.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===A.star)&&!At.test(this.input.slice(this.lastTokEnd,this.start))};ce.parseObj=function(e,t){var r=this.startNode(),n=!0,i={};for(r.properties=[],this.next();!this.eat(A.braceR);){if(n)n=!1;else if(this.expect(A.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(A.braceR))break;var s=this.parseProperty(e,t);e||this.checkPropClash(s,i,t),r.properties.push(s)}return this.finishNode(r,e?"ObjectPattern":"ObjectExpression")};ce.parseProperty=function(e,t){var r=this.startNode(),n,i,s,o;if(this.options.ecmaVersion>=9&&this.eat(A.ellipsis))return e?(r.argument=this.parseIdent(!1),this.type===A.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(r,"RestElement")):(r.argument=this.parseMaybeAssign(!1,t),this.type===A.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(r,"SpreadElement"));this.options.ecmaVersion>=6&&(r.method=!1,r.shorthand=!1,(e||t)&&(s=this.start,o=this.startLoc),e||(n=this.eat(A.star)));var u=this.containsEsc;return this.parsePropertyName(r),!e&&!u&&this.options.ecmaVersion>=8&&!n&&this.isAsyncProp(r)?(i=!0,n=this.options.ecmaVersion>=9&&this.eat(A.star),this.parsePropertyName(r)):i=!1,this.parsePropertyValue(r,e,n,i,s,o,t,u),this.finishNode(r,"Property")};ce.parseGetterSetter=function(e){var t=e.key.name;this.parsePropertyName(e),e.value=this.parseMethod(!1),e.kind=t;var r=e.kind==="get"?0:1;if(e.value.params.length!==r){var n=e.value.start;e.kind==="get"?this.raiseRecoverable(n,"getter should have no params"):this.raiseRecoverable(n,"setter should have exactly one param")}else e.kind==="set"&&e.value.params[0].type==="RestElement"&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")};ce.parsePropertyValue=function(e,t,r,n,i,s,o,u){(r||n)&&this.type===A.colon&&this.unexpected(),this.eat(A.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,o),e.kind="init"):this.options.ecmaVersion>=6&&this.type===A.parenL?(t&&this.unexpected(),e.method=!0,e.value=this.parseMethod(r,n),e.kind="init"):!t&&!u&&this.options.ecmaVersion>=5&&!e.computed&&e.key.type==="Identifier"&&(e.key.name==="get"||e.key.name==="set")&&this.type!==A.comma&&this.type!==A.braceR&&this.type!==A.eq?((r||n)&&this.unexpected(),this.parseGetterSetter(e)):this.options.ecmaVersion>=6&&!e.computed&&e.key.type==="Identifier"?((r||n)&&this.unexpected(),this.checkUnreserved(e.key),e.key.name==="await"&&!this.awaitIdentPos&&(this.awaitIdentPos=i),t?e.value=this.parseMaybeDefault(i,s,this.copyNode(e.key)):this.type===A.eq&&o?(o.shorthandAssign<0&&(o.shorthandAssign=this.start),e.value=this.parseMaybeDefault(i,s,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.kind="init",e.shorthand=!0):this.unexpected()};ce.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(A.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(A.bracketR),e.key;e.computed=!1}return e.key=this.type===A.num||this.type===A.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};ce.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)};ce.parseMethod=function(e,t,r){var n=this.startNode(),i=this.yieldPos,s=this.awaitPos,o=this.awaitIdentPos;return this.initFunction(n),this.options.ecmaVersion>=6&&(n.generator=e),this.options.ecmaVersion>=8&&(n.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(lf(t,n.generator)|nu|(r?D0:0)),this.expect(A.parenL),n.params=this.parseBindingList(A.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(n,!1,!0,!1),this.yieldPos=i,this.awaitPos=s,this.awaitIdentPos=o,this.finishNode(n,"FunctionExpression")};ce.parseArrowExpression=function(e,t,r,n){var i=this.yieldPos,s=this.awaitPos,o=this.awaitIdentPos;return this.enterScope(lf(r,!1)|cf),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!r),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,n),this.yieldPos=i,this.awaitPos=s,this.awaitIdentPos=o,this.finishNode(e,"ArrowFunctionExpression")};ce.parseFunctionBody=function(e,t,r,n){var i=t&&this.type!==A.braceL,s=this.strict,o=!1;if(i)e.body=this.parseMaybeAssign(n),e.expression=!0,this.checkParams(e,!1);else{var u=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);(!s||u)&&(o=this.strictDirective(this.end),o&&u&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list"));var c=this.labels;this.labels=[],o&&(this.strict=!0),this.checkParams(e,!s&&!o&&!t&&!r&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,N0),e.body=this.parseBlock(!1,void 0,o&&!s),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=c}this.exitScope()};ce.isSimpleParamList=function(e){for(var t=0,r=e;t<r.length;t+=1){var n=r[t];if(n.type!=="Identifier")return!1}return!0};ce.checkParams=function(e,t){for(var r=Object.create(null),n=0,i=e.params;n<i.length;n+=1){var s=i[n];this.checkLValInnerPattern(s,ff,t?null:r)}};ce.parseExprList=function(e,t,r,n){for(var i=[],s=!0;!this.eat(e);){if(s)s=!1;else if(this.expect(A.comma),t&&this.afterTrailingComma(e))break;var o=void 0;r&&this.type===A.comma?o=null:this.type===A.ellipsis?(o=this.parseSpread(n),n&&this.type===A.comma&&n.trailingComma<0&&(n.trailingComma=this.start)):o=this.parseMaybeAssign(!1,n),i.push(o)}return i};ce.checkUnreserved=function(e){var t=e.start,r=e.end,n=e.name;if(this.inGenerator&&n==="yield"&&this.raiseRecoverable(t,"Cannot use 'yield' as identifier inside a generator"),this.inAsync&&n==="await"&&this.raiseRecoverable(t,"Cannot use 'await' as identifier inside an async function"),!(this.currentThisScope().flags&iu)&&n==="arguments"&&this.raiseRecoverable(t,"Cannot use 'arguments' in class field initializer"),this.inClassStaticBlock&&(n==="arguments"||n==="await")&&this.raise(t,"Cannot use "+n+" in class static initialization block"),this.keywords.test(n)&&this.raise(t,"Unexpected keyword '"+n+"'"),!(this.options.ecmaVersion<6&&this.input.slice(t,r).indexOf("\\")!==-1)){var i=this.strict?this.reservedWordsStrict:this.reservedWords;i.test(n)&&(!this.inAsync&&n==="await"&&this.raiseRecoverable(t,"Cannot use keyword 'await' outside an async function"),this.raiseRecoverable(t,"The keyword '"+n+"' is reserved"))}};ce.parseIdent=function(e){var t=this.parseIdentNode();return this.next(!!e),this.finishNode(t,"Identifier"),e||(this.checkUnreserved(t),t.name==="await"&&!this.awaitIdentPos&&(this.awaitIdentPos=t.start)),t};ce.parseIdentNode=function(){var e=this.startNode();return this.type===A.name?e.name=this.value:this.type.keyword?(e.name=this.type.keyword,(e.name==="class"||e.name==="function")&&(this.lastTokEnd!==this.lastTokStart+1||this.input.charCodeAt(this.lastTokStart)!==46)&&this.context.pop(),this.type=A.name):this.unexpected(),e};ce.parsePrivateIdent=function(){var e=this.startNode();return this.type===A.privateId?e.name=this.value:this.unexpected(),this.next(),this.finishNode(e,"PrivateIdentifier"),this.options.checkPrivateFields&&(this.privateNameStack.length===0?this.raise(e.start,"Private field '#"+e.name+"' must be declared in an enclosing class"):this.privateNameStack[this.privateNameStack.length-1].used.push(e)),e};ce.parseYield=function(e){this.yieldPos||(this.yieldPos=this.start);var t=this.startNode();return this.next(),this.type===A.semi||this.canInsertSemicolon()||this.type!==A.star&&!this.type.startsExpr?(t.delegate=!1,t.argument=null):(t.delegate=this.eat(A.star),t.argument=this.parseMaybeAssign(e)),this.finishNode(t,"YieldExpression")};ce.parseAwait=function(e){this.awaitPos||(this.awaitPos=this.start);var t=this.startNode();return this.next(),t.argument=this.parseMaybeUnary(null,!0,!1,e),this.finishNode(t,"AwaitExpression")};var eu=Qe.prototype;eu.raise=function(e,t){var r=E0(this.input,e);t+=" ("+r.line+":"+r.column+")",this.sourceFile&&(t+=" in "+this.sourceFile);var n=new SyntaxError(t);throw n.pos=e,n.loc=r,n.raisedAt=this.pos,n};eu.raiseRecoverable=eu.raise;eu.curPosition=function(){if(this.options.locations)return new Xs(this.curLine,this.pos-this.lineStart)};var En=Qe.prototype,sC=function(t){this.flags=t,this.var=[],this.lexical=[],this.functions=[]};En.enterScope=function(e){this.scopeStack.push(new sC(e))};En.exitScope=function(){this.scopeStack.pop()};En.treatFunctionsAsVarInScope=function(e){return e.flags&Jn||!this.inModule&&e.flags&Zn};En.declareName=function(e,t,r){var n=!1;if(t===Yr){var i=this.currentScope();n=i.lexical.indexOf(e)>-1||i.functions.indexOf(e)>-1||i.var.indexOf(e)>-1,i.lexical.push(e),this.inModule&&i.flags&Zn&&delete this.undefinedExports[e]}else if(t===R0){var s=this.currentScope();s.lexical.push(e)}else if(t===T0){var o=this.currentScope();this.treatFunctionsAsVar?n=o.lexical.indexOf(e)>-1:n=o.lexical.indexOf(e)>-1||o.var.indexOf(e)>-1,o.functions.push(e)}else for(var u=this.scopeStack.length-1;u>=0;--u){var c=this.scopeStack[u];if(c.lexical.indexOf(e)>-1&&!(c.flags&C0&&c.lexical[0]===e)||!this.treatFunctionsAsVarInScope(c)&&c.functions.indexOf(e)>-1){n=!0;break}if(c.var.push(e),this.inModule&&c.flags&Zn&&delete this.undefinedExports[e],c.flags&iu)break}n&&this.raiseRecoverable(r,"Identifier '"+e+"' has already been declared")};En.checkLocalExport=function(e){this.scopeStack[0].lexical.indexOf(e.name)===-1&&this.scopeStack[0].var.indexOf(e.name)===-1&&(this.undefinedExports[e.name]=e)};En.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};En.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&(iu|Ys|Gn))return t}};En.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&(iu|Ys|Gn)&&!(t.flags&cf))return t}};var ou=function(t,r,n){this.type="",this.start=r,this.end=0,t.options.locations&&(this.loc=new ru(t,n)),t.options.directSourceFile&&(this.sourceFile=t.options.directSourceFile),t.options.ranges&&(this.range=[r,0])},eo=Qe.prototype;eo.startNode=function(){return new ou(this,this.start,this.startLoc)};eo.startNodeAt=function(e,t){return new ou(this,e,t)};function F0(e,t,r,n){return e.type=t,e.end=r,this.options.locations&&(e.loc.end=n),this.options.ranges&&(e.range[1]=r),e}eo.finishNode=function(e,t){return F0.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)};eo.finishNodeAt=function(e,t,r,n){return F0.call(this,e,t,r,n)};eo.copyNode=function(e){var t=new ou(this,e.start,this.startLoc);for(var r in e)t[r]=e[r];return t};var oC="Berf Beria_Erfe Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sidetic Sidt Sunu Sunuwar Tai_Yo Tayo Todhri Todr Tolong_Siki Tols Tulu_Tigalari Tutg Unknown Zzzz",L0="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",z0=L0+" Extended_Pictographic",B0=z0,M0=B0+" EBase EComp EMod EPres ExtPict",V0=M0,aC=V0,uC={9:L0,10:z0,11:B0,12:M0,13:V0,14:aC},cC="Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji",lC={9:"",10:"",11:"",12:"",13:"",14:cC},y0="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",$0="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",j0=$0+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",U0=j0+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",q0=U0+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",Z0=q0+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",fC=Z0+" "+oC,pC={9:$0,10:j0,11:U0,12:q0,13:Z0,14:fC},J0={};function hC(e){var t=J0[e]={binary:An(uC[e]+" "+y0),binaryOfStrings:An(lC[e]),nonBinary:{General_Category:An(y0),Script:An(pC[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(Ka=0,tf=[9,10,11,12,13,14];Ka<tf.length;Ka+=1)x0=tf[Ka],hC(x0);var x0,Ka,tf,K=Qe.prototype,tu=function(t,r){this.parent=t,this.base=r||this};tu.prototype.separatedFrom=function(t){for(var r=this;r;r=r.parent)for(var n=t;n;n=n.parent)if(r.base===n.base&&r!==n)return!0;return!1};tu.prototype.sibling=function(){return new tu(this.parent,this.base)};var Lr=function(t){this.parser=t,this.validFlags="gim"+(t.options.ecmaVersion>=6?"uy":"")+(t.options.ecmaVersion>=9?"s":"")+(t.options.ecmaVersion>=13?"d":"")+(t.options.ecmaVersion>=15?"v":""),this.unicodeProperties=J0[t.options.ecmaVersion>=14?14:t.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};Lr.prototype.reset=function(t,r,n){var i=n.indexOf("v")!==-1,s=n.indexOf("u")!==-1;this.start=t|0,this.source=r+"",this.flags=n,i&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=s&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=s&&this.parser.options.ecmaVersion>=9)};Lr.prototype.raise=function(t){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+t)};Lr.prototype.at=function(t,r){r===void 0&&(r=!1);var n=this.source,i=n.length;if(t>=i)return-1;var s=n.charCodeAt(t);if(!(r||this.switchU)||s<=55295||s>=57344||t+1>=i)return s;var o=n.charCodeAt(t+1);return o>=56320&&o<=57343?(s<<10)+o-56613888:s};Lr.prototype.nextIndex=function(t,r){r===void 0&&(r=!1);var n=this.source,i=n.length;if(t>=i)return i;var s=n.charCodeAt(t),o;return!(r||this.switchU)||s<=55295||s>=57344||t+1>=i||(o=n.charCodeAt(t+1))<56320||o>57343?t+1:t+2};Lr.prototype.current=function(t){return t===void 0&&(t=!1),this.at(this.pos,t)};Lr.prototype.lookahead=function(t){return t===void 0&&(t=!1),this.at(this.nextIndex(this.pos,t),t)};Lr.prototype.advance=function(t){t===void 0&&(t=!1),this.pos=this.nextIndex(this.pos,t)};Lr.prototype.eat=function(t,r){return r===void 0&&(r=!1),this.current(r)===t?(this.advance(r),!0):!1};Lr.prototype.eatChars=function(t,r){r===void 0&&(r=!1);for(var n=this.pos,i=0,s=t;i<s.length;i+=1){var o=s[i],u=this.at(n,r);if(u===-1||u!==o)return!1;n=this.nextIndex(n,r)}return this.pos=n,!0};K.validateRegExpFlags=function(e){for(var t=e.validFlags,r=e.flags,n=!1,i=!1,s=0;s<r.length;s++){var o=r.charAt(s);t.indexOf(o)===-1&&this.raise(e.start,"Invalid regular expression flag"),r.indexOf(o,s+1)>-1&&this.raise(e.start,"Duplicate regular expression flag"),o==="u"&&(n=!0),o==="v"&&(i=!0)}this.options.ecmaVersion>=15&&n&&i&&this.raise(e.start,"Invalid regular expression flag")};function dC(e){for(var t in e)return!0;return!1}K.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&dC(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))};K.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,r=e.backReferenceNames;t<r.length;t+=1){var n=r[t];e.groupNames[n]||e.raise("Invalid named capture referenced")}};K.regexp_disjunction=function(e){var t=this.options.ecmaVersion>=16;for(t&&(e.branchID=new tu(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")};K.regexp_alternative=function(e){for(;e.pos<e.source.length&&this.regexp_eatTerm(e););};K.regexp_eatTerm=function(e){return this.regexp_eatAssertion(e)?(e.lastAssertionIsQuantifiable&&this.regexp_eatQuantifier(e)&&e.switchU&&e.raise("Invalid quantifier"),!0):(e.switchU?this.regexp_eatAtom(e):this.regexp_eatExtendedAtom(e))?(this.regexp_eatQuantifier(e),!0):!1};K.regexp_eatAssertion=function(e){var t=e.pos;if(e.lastAssertionIsQuantifiable=!1,e.eat(94)||e.eat(36))return!0;if(e.eat(92)){if(e.eat(66)||e.eat(98))return!0;e.pos=t}if(e.eat(40)&&e.eat(63)){var r=!1;if(this.options.ecmaVersion>=9&&(r=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!r,!0}return e.pos=t,!1};K.regexp_eatQuantifier=function(e,t){return t===void 0&&(t=!1),this.regexp_eatQuantifierPrefix(e,t)?(e.eat(63),!0):!1};K.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)};K.regexp_eatBracedQuantifier=function(e,t){var r=e.pos;if(e.eat(123)){var n=0,i=-1;if(this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(i=e.lastIntValue),e.eat(125)))return i!==-1&&i<n&&!t&&e.raise("numbers out of order in {} quantifier"),!0;e.switchU&&!t&&e.raise("Incomplete quantifier"),e.pos=r}return!1};K.regexp_eatAtom=function(e){return this.regexp_eatPatternCharacters(e)||e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)};K.regexp_eatReverseSolidusAtomEscape=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatAtomEscape(e))return!0;e.pos=t}return!1};K.regexp_eatUncapturingGroup=function(e){var t=e.pos;if(e.eat(40)){if(e.eat(63)){if(this.options.ecmaVersion>=16){var r=this.regexp_eatModifiers(e),n=e.eat(45);if(r||n){for(var i=0;i<r.length;i++){var s=r.charAt(i);r.indexOf(s,i+1)>-1&&e.raise("Duplicate regular expression modifiers")}if(n){var o=this.regexp_eatModifiers(e);!r&&!o&&e.current()===58&&e.raise("Invalid regular expression modifiers");for(var u=0;u<o.length;u++){var c=o.charAt(u);(o.indexOf(c,u+1)>-1||r.indexOf(c)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1};K.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):e.current()===63&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1};K.regexp_eatModifiers=function(e){for(var t="",r=0;(r=e.current())!==-1&&mC(r);)t+=Kr(r),e.advance();return t};function mC(e){return e===105||e===109||e===115}K.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)};K.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1};K.regexp_eatSyntaxCharacter=function(e){var t=e.current();return G0(t)?(e.lastIntValue=t,e.advance(),!0):!1};function G0(e){return e===36||e>=40&&e<=43||e===46||e===63||e>=91&&e<=94||e>=123&&e<=125}K.regexp_eatPatternCharacters=function(e){for(var t=e.pos,r=0;(r=e.current())!==-1&&!G0(r);)e.advance();return e.pos!==t};K.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return t!==-1&&t!==36&&!(t>=40&&t<=43)&&t!==46&&t!==63&&t!==91&&t!==94&&t!==124?(e.advance(),!0):!1};K.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,r=e.groupNames[e.lastStringValue];if(r)if(t)for(var n=0,i=r;n<i.length;n+=1){var s=i[n];s.separatedFrom(e.branchID)||e.raise("Duplicate capture group name")}else e.raise("Duplicate capture group name");t?(r||(e.groupNames[e.lastStringValue]=[])).push(e.branchID):e.groupNames[e.lastStringValue]=!0}};K.regexp_eatGroupName=function(e){if(e.lastStringValue="",e.eat(60)){if(this.regexp_eatRegExpIdentifierName(e)&&e.eat(62))return!0;e.raise("Invalid capture group name")}return!1};K.regexp_eatRegExpIdentifierName=function(e){if(e.lastStringValue="",this.regexp_eatRegExpIdentifierStart(e)){for(e.lastStringValue+=Kr(e.lastIntValue);this.regexp_eatRegExpIdentifierPart(e);)e.lastStringValue+=Kr(e.lastIntValue);return!0}return!1};K.regexp_eatRegExpIdentifierStart=function(e){var t=e.pos,r=this.options.ecmaVersion>=11,n=e.current(r);return e.advance(r),n===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,r)&&(n=e.lastIntValue),gC(n)?(e.lastIntValue=n,!0):(e.pos=t,!1)};function gC(e){return Fr(e,!0)||e===36||e===95}K.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,r=this.options.ecmaVersion>=11,n=e.current(r);return e.advance(r),n===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,r)&&(n=e.lastIntValue),yC(n)?(e.lastIntValue=n,!0):(e.pos=t,!1)};function yC(e){return Sn(e,!0)||e===36||e===95||e===8204||e===8205}K.regexp_eatAtomEscape=function(e){return this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e)?!0:(e.switchU&&(e.current()===99&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)};K.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var r=e.lastIntValue;if(e.switchU)return r>e.maxBackReference&&(e.maxBackReference=r),!0;if(r<=e.numCapturingParens)return!0;e.pos=t}return!1};K.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1};K.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)};K.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1};K.regexp_eatZero=function(e){return e.current()===48&&!au(e.lookahead())?(e.lastIntValue=0,e.advance(),!0):!1};K.regexp_eatControlEscape=function(e){var t=e.current();return t===116?(e.lastIntValue=9,e.advance(),!0):t===110?(e.lastIntValue=10,e.advance(),!0):t===118?(e.lastIntValue=11,e.advance(),!0):t===102?(e.lastIntValue=12,e.advance(),!0):t===114?(e.lastIntValue=13,e.advance(),!0):!1};K.regexp_eatControlLetter=function(e){var t=e.current();return Q0(t)?(e.lastIntValue=t%32,e.advance(),!0):!1};function Q0(e){return e>=65&&e<=90||e>=97&&e<=122}K.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){t===void 0&&(t=!1);var r=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var i=e.lastIntValue;if(n&&i>=55296&&i<=56319){var s=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=(i-55296)*1024+(o-56320)+65536,!0}e.pos=s,e.lastIntValue=i}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&xC(e.lastIntValue))return!0;n&&e.raise("Invalid unicode escape"),e.pos=r}return!1};function xC(e){return e>=0&&e<=1114111}K.regexp_eatIdentityEscape=function(e){if(e.switchU)return this.regexp_eatSyntaxCharacter(e)?!0:e.eat(47)?(e.lastIntValue=47,!0):!1;var t=e.current();return t!==99&&(!e.switchN||t!==107)?(e.lastIntValue=t,e.advance(),!0):!1};K.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do e.lastIntValue=10*e.lastIntValue+(t-48),e.advance();while((t=e.current())>=48&&t<=57);return!0}return!1};var H0=0,Xr=1,Zt=2;K.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(bC(t))return e.lastIntValue=-1,e.advance(),Xr;var r=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((r=t===80)||t===112)){e.lastIntValue=-1,e.advance();var n;if(e.eat(123)&&(n=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return r&&n===Zt&&e.raise("Invalid property name"),n;e.raise("Invalid property name")}return H0};function bC(e){return e===100||e===68||e===115||e===83||e===119||e===87}K.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var r=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,r,n),Xr}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var i=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,i)}return H0};K.regexp_validateUnicodePropertyNameAndValue=function(e,t,r){Bi(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(r)||e.raise("Invalid property value")};K.regexp_validateUnicodePropertyNameOrValue=function(e,t){if(e.unicodeProperties.binary.test(t))return Xr;if(e.switchV&&e.unicodeProperties.binaryOfStrings.test(t))return Zt;e.raise("Invalid property name")};K.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";W0(t=e.current());)e.lastStringValue+=Kr(t),e.advance();return e.lastStringValue!==""};function W0(e){return Q0(e)||e===95}K.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";wC(t=e.current());)e.lastStringValue+=Kr(t),e.advance();return e.lastStringValue!==""};function wC(e){return W0(e)||au(e)}K.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)};K.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),r=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&r===Zt&&e.raise("Negated character class may contain strings"),!0}return!1};K.regexp_classContents=function(e){return e.current()===93?Xr:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),Xr)};K.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var r=e.lastIntValue;e.switchU&&(t===-1||r===-1)&&e.raise("Invalid character class"),t!==-1&&r!==-1&&t>r&&e.raise("Range out of order in character class")}}};K.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var r=e.current();(r===99||Y0(r))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var n=e.current();return n!==93?(e.lastIntValue=n,e.advance(),!0):!1};K.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)};K.regexp_classSetExpression=function(e){var t=Xr,r;if(!this.regexp_eatClassSetRange(e))if(r=this.regexp_eatClassSetOperand(e)){r===Zt&&(t=Zt);for(var n=e.pos;e.eatChars([38,38]);){if(e.current()!==38&&(r=this.regexp_eatClassSetOperand(e))){r!==Zt&&(t=Xr);continue}e.raise("Invalid character in character class")}if(n!==e.pos)return t;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(n!==e.pos)return t}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(r=this.regexp_eatClassSetOperand(e),!r)return t;r===Zt&&(t=Zt)}};K.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var n=e.lastIntValue;return r!==-1&&n!==-1&&r>n&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1};K.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?Xr:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)};K.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var r=e.eat(94),n=this.regexp_classContents(e);if(e.eat(93))return r&&n===Zt&&e.raise("Negated character class may contain strings"),n;e.pos=t}if(e.eat(92)){var i=this.regexp_eatCharacterClassEscape(e);if(i)return i;e.pos=t}return null};K.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var r=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return r}else e.raise("Invalid escape");e.pos=t}return null};K.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)this.regexp_classString(e)===Zt&&(t=Zt);return t};K.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return t===1?Xr:Zt};K.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return this.regexp_eatCharacterEscape(e)||this.regexp_eatClassSetReservedPunctuator(e)?!0:e.eat(98)?(e.lastIntValue=8,!0):(e.pos=t,!1);var r=e.current();return r<0||r===e.lookahead()&&vC(r)||kC(r)?!1:(e.advance(),e.lastIntValue=r,!0)};function vC(e){return e===33||e>=35&&e<=38||e>=42&&e<=44||e===46||e>=58&&e<=64||e===94||e===96||e===126}function kC(e){return e===40||e===41||e===45||e===47||e>=91&&e<=93||e>=123&&e<=125}K.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return AC(t)?(e.lastIntValue=t,e.advance(),!0):!1};function AC(e){return e===33||e===35||e===37||e===38||e===44||e===45||e>=58&&e<=62||e===64||e===96||e===126}K.regexp_eatClassControlLetter=function(e){var t=e.current();return au(t)||t===95?(e.lastIntValue=t%32,e.advance(),!0):!1};K.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1};K.regexp_eatDecimalDigits=function(e){var t=e.pos,r=0;for(e.lastIntValue=0;au(r=e.current());)e.lastIntValue=10*e.lastIntValue+(r-48),e.advance();return e.pos!==t};function au(e){return e>=48&&e<=57}K.regexp_eatHexDigits=function(e){var t=e.pos,r=0;for(e.lastIntValue=0;K0(r=e.current());)e.lastIntValue=16*e.lastIntValue+X0(r),e.advance();return e.pos!==t};function K0(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function X0(e){return e>=65&&e<=70?10+(e-65):e>=97&&e<=102?10+(e-97):e-48}K.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var r=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=t*64+r*8+e.lastIntValue:e.lastIntValue=t*8+r}else e.lastIntValue=t;return!0}return!1};K.regexp_eatOctalDigit=function(e){var t=e.current();return Y0(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)};function Y0(e){return e>=48&&e<=55}K.regexp_eatFixedHexDigits=function(e,t){var r=e.pos;e.lastIntValue=0;for(var n=0;n<t;++n){var i=e.current();if(!K0(i))return e.pos=r,!1;e.lastIntValue=16*e.lastIntValue+X0(i),e.advance()}return!0};var hf=function(t){this.type=t.type,this.value=t.value,this.start=t.start,this.end=t.end,t.options.locations&&(this.loc=new ru(t,t.startLoc,t.endLoc)),t.options.ranges&&(this.range=[t.start,t.end])},de=Qe.prototype;de.next=function(e){!e&&this.type.keyword&&this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword "+this.type.keyword),this.options.onToken&&this.options.onToken(new hf(this)),this.lastTokEnd=this.end,this.lastTokStart=this.start,this.lastTokEndLoc=this.endLoc,this.lastTokStartLoc=this.startLoc,this.nextToken()};de.getToken=function(){return this.next(),new hf(this)};typeof Symbol<"u"&&(de[Symbol.iterator]=function(){var e=this;return{next:function(){var t=e.getToken();return{done:t.type===A.eof,value:t}}}});de.nextToken=function(){var e=this.curContext();if((!e||!e.preserveSpace)&&this.skipSpace(),this.start=this.pos,this.options.locations&&(this.startLoc=this.curPosition()),this.pos>=this.input.length)return this.finishToken(A.eof);if(e.override)return e.override(this);this.readToken(this.fullCharCodeAtPos())};de.readToken=function(e){return Fr(e,this.options.ecmaVersion>=6)||e===92?this.readWord():this.getTokenFromCode(e)};de.fullCharCodeAt=function(e){var t=this.input.charCodeAt(e);if(t<=55295||t>=56320)return t;var r=this.input.charCodeAt(e+1);return r<=56319||r>=57344?t:(t<<10)+r-56613888};de.fullCharCodeAtPos=function(){return this.fullCharCodeAt(this.pos)};de.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,r=this.input.indexOf("*/",this.pos+=2);if(r===-1&&this.raise(this.pos-2,"Unterminated comment"),this.pos=r+2,this.options.locations)for(var n=void 0,i=t;(n=k0(this.input,i,this.pos))>-1;)++this.curLine,i=this.lineStart=n;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,r),t,this.pos,e,this.curPosition())};de.skipLineComment=function(e){for(var t=this.pos,r=this.options.onComment&&this.curPosition(),n=this.input.charCodeAt(this.pos+=e);this.pos<this.input.length&&!zi(n);)n=this.input.charCodeAt(++this.pos);this.options.onComment&&this.options.onComment(!1,this.input.slice(t+e,this.pos),t,this.pos,r,this.curPosition())};de.skipSpace=function(){e:for(;this.pos<this.input.length;){var e=this.input.charCodeAt(this.pos);switch(e){case 32:case 160:++this.pos;break;case 13:this.input.charCodeAt(this.pos+1)===10&&++this.pos;case 10:case 8232:case 8233:++this.pos,this.options.locations&&(++this.curLine,this.lineStart=this.pos);break;case 47:switch(this.input.charCodeAt(this.pos+1)){case 42:this.skipBlockComment();break;case 47:this.skipLineComment(2);break;default:break e}break;default:if(e>8&&e<14||e>=5760&&A0.test(String.fromCharCode(e)))++this.pos;else break e}}};de.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var r=this.type;this.type=e,this.value=t,this.updateContext(r)};de.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&e===46&&t===46?(this.pos+=3,this.finishToken(A.ellipsis)):(++this.pos,this.finishToken(A.dot))};de.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):e===61?this.finishOp(A.assign,2):this.finishOp(A.slash,1)};de.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),r=1,n=e===42?A.star:A.modulo;return this.options.ecmaVersion>=7&&e===42&&t===42&&(++r,n=A.starstar,t=this.input.charCodeAt(this.pos+2)),t===61?this.finishOp(A.assign,r+1):this.finishOp(n,r)};de.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(this.options.ecmaVersion>=12){var r=this.input.charCodeAt(this.pos+2);if(r===61)return this.finishOp(A.assign,3)}return this.finishOp(e===124?A.logicalOR:A.logicalAND,2)}return t===61?this.finishOp(A.assign,2):this.finishOp(e===124?A.bitwiseOR:A.bitwiseAND,1)};de.readToken_caret=function(){var e=this.input.charCodeAt(this.pos+1);return e===61?this.finishOp(A.assign,2):this.finishOp(A.bitwiseXOR,1)};de.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?t===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||At.test(this.input.slice(this.lastTokEnd,this.pos)))?(this.skipLineComment(3),this.skipSpace(),this.nextToken()):this.finishOp(A.incDec,2):t===61?this.finishOp(A.assign,2):this.finishOp(A.plusMin,1)};de.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),r=1;return t===e?(r=e===62&&this.input.charCodeAt(this.pos+2)===62?3:2,this.input.charCodeAt(this.pos+r)===61?this.finishOp(A.assign,r+1):this.finishOp(A.bitShift,r)):t===33&&e===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45?(this.skipLineComment(4),this.skipSpace(),this.nextToken()):(t===61&&(r=2),this.finishOp(A.relational,r))};de.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return t===61?this.finishOp(A.equality,this.input.charCodeAt(this.pos+2)===61?3:2):e===61&&t===62&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(A.arrow)):this.finishOp(e===61?A.eq:A.prefix,1)};de.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(t===46){var r=this.input.charCodeAt(this.pos+2);if(r<48||r>57)return this.finishOp(A.questionDot,2)}if(t===63){if(e>=12){var n=this.input.charCodeAt(this.pos+2);if(n===61)return this.finishOp(A.assign,3)}return this.finishOp(A.coalesce,2)}}return this.finishOp(A.question,1)};de.readToken_numberSign=function(){var e=this.options.ecmaVersion,t=35;if(e>=13&&(++this.pos,t=this.fullCharCodeAtPos(),Fr(t,!0)||t===92))return this.finishToken(A.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+Kr(t)+"'")};de.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(A.parenL);case 41:return++this.pos,this.finishToken(A.parenR);case 59:return++this.pos,this.finishToken(A.semi);case 44:return++this.pos,this.finishToken(A.comma);case 91:return++this.pos,this.finishToken(A.bracketL);case 93:return++this.pos,this.finishToken(A.bracketR);case 123:return++this.pos,this.finishToken(A.braceL);case 125:return++this.pos,this.finishToken(A.braceR);case 58:return++this.pos,this.finishToken(A.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(A.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(t===120||t===88)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(t===111||t===79)return this.readRadixNumber(8);if(t===98||t===66)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(A.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+Kr(e)+"'")};de.finishOp=function(e,t){var r=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,r)};de.readRegexp=function(){for(var e,t,r=this.pos;;){this.pos>=this.input.length&&this.raise(r,"Unterminated regular expression");var n=this.input.charAt(this.pos);if(At.test(n)&&this.raise(r,"Unterminated regular expression"),e)e=!1;else{if(n==="[")t=!0;else if(n==="]"&&t)t=!1;else if(n==="/"&&!t)break;e=n==="\\"}++this.pos}var i=this.input.slice(r,this.pos);++this.pos;var s=this.pos,o=this.readWord1();this.containsEsc&&this.unexpected(s);var u=this.regexpState||(this.regexpState=new Lr(this));u.reset(r,i,o),this.validateRegExpFlags(u),this.validateRegExpPattern(u);var c=null;try{c=new RegExp(i,o)}catch{}return this.finishToken(A.regexp,{pattern:i,flags:o,value:c})};de.readInt=function(e,t,r){for(var n=this.options.ecmaVersion>=12&&t===void 0,i=r&&this.input.charCodeAt(this.pos)===48,s=this.pos,o=0,u=0,c=0,f=t??1/0;c<f;++c,++this.pos){var h=this.input.charCodeAt(this.pos),p=void 0;if(n&&h===95){i&&this.raiseRecoverable(this.pos,"Numeric separator is not allowed in legacy octal numeric literals"),u===95&&this.raiseRecoverable(this.pos,"Numeric separator must be exactly one underscore"),c===0&&this.raiseRecoverable(this.pos,"Numeric separator is not allowed at the first of digits"),u=h;continue}if(h>=97?p=h-97+10:h>=65?p=h-65+10:h>=48&&h<=57?p=h-48:p=1/0,p>=e)break;u=h,o=o*e+p}return n&&u===95&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===s||t!=null&&this.pos-s!==t?null:o};function SC(e,t){return t?parseInt(e,8):parseFloat(e.replace(/_/g,""))}function eb(e){return typeof BigInt!="function"?null:BigInt(e.replace(/_/g,""))}de.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var r=this.readInt(e);return r==null&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110?(r=eb(this.input.slice(t,this.pos)),++this.pos):Fr(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(A.num,r)};de.readNumber=function(e){var t=this.pos;!e&&this.readInt(10,void 0,!0)===null&&this.raise(t,"Invalid number");var r=this.pos-t>=2&&this.input.charCodeAt(t)===48;r&&this.strict&&this.raise(t,"Invalid number");var n=this.input.charCodeAt(this.pos);if(!r&&!e&&this.options.ecmaVersion>=11&&n===110){var i=eb(this.input.slice(t,this.pos));return++this.pos,Fr(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(A.num,i)}r&&/[89]/.test(this.input.slice(t,this.pos))&&(r=!1),n===46&&!r&&(++this.pos,this.readInt(10),n=this.input.charCodeAt(this.pos)),(n===69||n===101)&&!r&&(n=this.input.charCodeAt(++this.pos),(n===43||n===45)&&++this.pos,this.readInt(10)===null&&this.raise(t,"Invalid number")),Fr(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var s=SC(this.input.slice(t,this.pos),r);return this.finishToken(A.num,s)};de.readCodePoint=function(){var e=this.input.charCodeAt(this.pos),t;if(e===123){this.options.ecmaVersion<6&&this.unexpected();var r=++this.pos;t=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,t>1114111&&this.invalidStringToken(r,"Code point out of bounds")}else t=this.readHexChar(4);return t};de.readString=function(e){for(var t="",r=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var n=this.input.charCodeAt(this.pos);if(n===e)break;n===92?(t+=this.input.slice(r,this.pos),t+=this.readEscapedChar(!1),r=this.pos):n===8232||n===8233?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(zi(n)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(r,this.pos++),this.finishToken(A.string,t)};var tb={};de.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e===tb)this.readInvalidTemplateToken();else throw e}this.inTemplateElement=!1};de.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw tb;this.raise(e,t)};de.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var r=this.input.charCodeAt(this.pos);if(r===96||r===36&&this.input.charCodeAt(this.pos+1)===123)return this.pos===this.start&&(this.type===A.template||this.type===A.invalidTemplate)?r===36?(this.pos+=2,this.finishToken(A.dollarBraceL)):(++this.pos,this.finishToken(A.backQuote)):(e+=this.input.slice(t,this.pos),this.finishToken(A.template,e));if(r===92)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(zi(r)){switch(e+=this.input.slice(t,this.pos),++this.pos,r){case 13:this.input.charCodeAt(this.pos)===10&&++this.pos;case 10:e+=`+`;break;default:e+=String.fromCharCode(r);break}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}};de.readInvalidTemplateToken=function(){for(;this.pos<this.input.length;this.pos++)switch(this.input[this.pos]){case"\\":++this.pos;break;case"$":if(this.input[this.pos+1]!=="{")break;case"`":return this.finishToken(A.invalidTemplate,this.input.slice(this.start,this.pos));case"\r":this.input[this.pos+1]===`+`&&++this.pos;case`+`:case"\u2028":case"\u2029":++this.curLine,this.lineStart=this.pos+1;break}this.raise(this.start,"Unterminated template")};de.readEscapedChar=function(e){var t=this.input.charCodeAt(++this.pos);switch(++this.pos,t){case 110:return`+`;case 114:return"\r";case 120:return String.fromCharCode(this.readHexChar(2));case 117:return Kr(this.readCodePoint());case 116:return" ";case 98:return"\b";case 118:return"\v";case 102:return"\f";case 13:this.input.charCodeAt(this.pos)===10&&++this.pos;case 10:return this.options.locations&&(this.lineStart=this.pos,++this.curLine),"";case 56:case 57:if(this.strict&&this.invalidStringToken(this.pos-1,"Invalid escape sequence"),e){var r=this.pos-1;this.invalidStringToken(r,"Invalid escape sequence in template string")}default:if(t>=48&&t<=55){var n=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],i=parseInt(n,8);return i>255&&(n=n.slice(0,-1),i=parseInt(n,8)),this.pos+=n.length-1,t=this.input.charCodeAt(this.pos),(n!=="0"||t===56||t===57)&&(this.strict||e)&&this.invalidStringToken(this.pos-1-n.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(i)}return zi(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}};de.readHexChar=function(e){var t=this.pos,r=this.readInt(16,e);return r===null&&this.invalidStringToken(t,"Bad character escape sequence"),r};de.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,r=this.pos,n=this.options.ecmaVersion>=6;this.pos<this.input.length;){var i=this.fullCharCodeAtPos();if(Sn(i,n))this.pos+=i<=65535?1:2;else if(i===92){this.containsEsc=!0,e+=this.input.slice(r,this.pos);var s=this.pos;this.input.charCodeAt(++this.pos)!==117&&this.invalidStringToken(this.pos,"Expecting Unicode escape sequence \\uXXXX"),++this.pos;var o=this.readCodePoint();(t?Fr:Sn)(o,n)||this.invalidStringToken(s,"Invalid Unicode escape"),e+=Kr(o),r=this.pos}else break;t=!1}return e+this.input.slice(r,this.pos)};de.readWord=function(){var e=this.readWord1(),t=A.name;return this.keywords.test(e)&&(t=af[e]),this.finishToken(t,e)};var EC="8.17.0";Qe.acorn={Parser:Qe,version:EC,defaultOptions:nf,Position:Xs,SourceLocation:ru,getLineInfo:E0,Node:ou,TokenType:ke,tokTypes:A,keywordTypes:af,TokContext:gr,tokContexts:Me,isIdentifierChar:Sn,isIdentifierStart:Fr,Token:hf,isNewLine:zi,lineBreak:At,lineBreakG:Q_,nonASCIIwhitespace:A0};var xb=ns(ab(),1);var TC={}.hasOwnProperty,cb=Symbol("continue"),cu=Symbol("exit"),lb=Symbol("skip");function yf(e,t){let r,n;typeof t=="function"?r=t:t&&typeof t=="object"&&(t.enter&&(r=t.enter),t.leave&&(n=t.leave)),i(e,null,null,[])();function i(s,o,u,c){return gf(s)&&(f.displayName="node ("+s.type+")"),f;function f(){let h=r?ub(r(s,o,u,c)):[];if(h[0]===cu)return h;if(h[0]!==lb){let p;for(p in s)if(TC.call(s,p)&&s[p]&&typeof s[p]=="object"&&p!=="data"&&p!=="position"){let m=c.concat(s),d=s[p];if(Array.isArray(d)){let x=d,b=0;for(;b>-1&&b<x.length;){let v=x[b];if(gf(v)){let k=i(v,p,b,m)();if(k[0]===cu)return k;b=typeof k[1]=="number"?k[1]:b+1}else b++}}else if(gf(d)){let x=i(d,p,null,m)();if(x[0]===cu)return x}}}return n?ub(n(s,o,u,c)):h}}}function ub(e){return Array.isArray(e)?e:typeof e=="number"?[cb,e]:[e]}function gf(e){return!!(e&&typeof e=="object"&&"type"in e&&typeof e.type=="string"&&e.type.length>0)}function Tt(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?fb(e.position):"start"in e||"end"in e?fb(e):"line"in e||"column"in e?xf(e):""}function xf(e){return pb(e&&e.line)+":"+pb(e&&e.column)}function fb(e){return xf(e&&e.start)+"-"+xf(e&&e.end)}function pb(e){return e&&typeof e=="number"?e:1}var me=class extends Error{constructor(t,r,n){let i=[null,null],s={start:{line:null,column:null},end:{line:null,column:null}};if(super(),typeof r=="string"&&(n=r,r=void 0),typeof n=="string"){let o=n.indexOf(":");o===-1?i[1]=n:(i[0]=n.slice(0,o),i[1]=n.slice(o+1))}r&&("type"in r||"position"in r?r.position&&(s=r.position):"start"in r||"end"in r?s=r:("line"in r||"column"in r)&&(s.start=r)),this.name=Tt(r)||"1:1",this.message=typeof t=="object"?t.message:t,this.stack="",typeof t=="object"&&t.stack&&(this.stack=t.stack),this.reason=this.message,this.fatal,this.line=s.start.line,this.column=s.start.column,this.position=s,this.source=i[0],this.ruleId=i[1],this.file,this.actual,this.expected,this.url,this.note}};me.prototype.file="";me.prototype.name="";me.prototype.reason="";me.prototype.message="";me.prototype.stack="";me.prototype.fatal=null;me.prototype.column=null;me.prototype.line=null;me.prototype.source=null;me.prototype.ruleId=null;me.prototype.position=null;function lu(e,t){let r=t.prefix||"",n=t.suffix||"",i=Object.assign({},t.acornOptions),s=[],o=[],u=i.onComment,c=i.onToken,f=!1,h,p,m=Object.assign({},i,{onComment:s,preserveParens:!0});c&&(m.onToken=o);let d=RC(e,["lineEnding","expressionChunk","mdxFlowExpressionChunk","mdxTextExpressionChunk","mdxJsxTextTagExpressionAttributeValue","mdxJsxTextTagAttributeValueExpressionValue","mdxJsxFlowTagExpressionAttributeValue","mdxJsxFlowTagAttributeValueExpressionValue","mdxjsEsmData"]),x=d.value,b=r+x+n,v=t.expression&&hb(x);if(v&&!t.allowEmpty)throw new me("Unexpected empty expression",T(0),"micromark-extension-mdx-expression:unexpected-empty-expression");try{h=t.expression&&!v?t.acorn.parseExpressionAt(b,0,m):t.acorn.parse(b,m)}catch(E){let g=E,I=T(g.pos);g.message=String(g.message).replace(/ \(\d+:\d+\)$/,""),g.pos=I.offset,g.loc={line:I.line,column:I.column-1},p=g,f=g.raisedAt>=r.length+x.length||g.message==="Unterminated comment"}if(h&&t.expression&&!v)if(hb(b.slice(h.end,b.length-n.length)))h={type:"Program",start:0,end:r.length+x.length,body:[{type:"ExpressionStatement",expression:h,start:0,end:r.length+x.length}],sourceType:"module",comments:[]};else{let E=T(h.end),g=new Error("Unexpected content after expression");g.pos=E.offset,g.loc={line:E.line,column:E.column-1},p=g,h=void 0}if(h){if(h.comments=s,yf(h,(E,g,I,_)=>{let D=_[_.length-1],O=g;E.type==="ParenthesizedExpression"&&D&&O&&(typeof I=="number"&&(D=D[O],O=I),D[O]=E.expression),k(E)}),Array.isArray(u))u.push(...s);else if(typeof u=="function")for(let E of s)u(E.type==="Block",E.value,E.start,E.end,E.loc.start,E.loc.end);for(let E of o)E.end<=r.length||E.start-r.length>=x.length||(k(E),Array.isArray(c)?c.push(E):c(E))}return{estree:h,error:p,swallow:f};function k(E){let g=T(E.start),I=T(E.end);E.start=g.offset,E.end=I.offset,E.loc={start:{line:g.line,column:g.column-1,offset:g.offset},end:{line:I.line,column:I.column-1,offset:I.offset}},E.range=[E.start,E.end]}function T(E){let g=E-r.length;g<0?g=0:g>x.length&&(g=x.length);let I=NC(d.stops,g);return I||(I={line:t.start.line,column:t.start.column,offset:t.start.offset}),I}}function hb(e){return/^\s*$/.test(e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\r\n]*(\r\n|\n|\r)/g,""))}function RC(e,t){let r={value:"",stops:[]},n=-1;for(;++n<e.length;){let i=e[n];if(i[0]==="enter"&&t.includes(i[1].type)){let s=i[2].sliceStream(i[1]);for(;s.length>0&&s[0]===-1;)s.shift();let o=PC(s);r.stops.push([r.value.length,i[1].start]),r.value+=o,r.stops.push([r.value.length,i[1].end])}}return r}function NC(e,t){let r=0;for(;r<e.length&&e[r][0]<=t;)r+=1;if(r===0)return;let[n,i]=e[r-1],s=t-n;return{line:i.line,column:i.column+s,offset:i.offset+s}}function PC(e){let t=-1,r=[],n;for(;++t<e.length;){let i=e[t],s;if(typeof i=="string")s=i;else switch(i){case-5:{s="\r";break}case-4:{s=`+`;break}case-3:{s=`\r+`;break}case-2:{s=" ";break}case-1:{if(n)continue;s=" ";break}default:s=String.fromCharCode(i)}n=i===-2,r.push(s)}return r.join("")}function Qn(e){let t=e||{},r=t.loc||{},n=t.range||[0,0],i=r.start?Vi(r.start.column):void 0,s=r.end?Vi(r.end.column):void 0;return{start:{line:r.start?Vi(r.start.line):void 0,column:i===void 0?void 0:i+1,offset:Vi(n[0]||t.start)},end:{line:r.end?Vi(r.end.line):void 0,column:s===void 0?void 0:s+1,offset:Vi(n[1]||t.end)}}}function Vi(e){return typeof e=="number"&&e>-1?e:void 0}function $i(e,t,r,n,i,s,o,u,c,f,h){let p=this,m=this.events.length+3,d=0,x,b;return v;function v(g){return e.enter(r),e.enter(n),e.consume(g),e.exit(n),x=p.now(),k}function k(g){if(g===null)throw b||new me("Unexpected end of file in expression, expected a corresponding closing brace for `{`",p.now(),"micromark-extension-mdx-expression:unexpected-eof");if(j(g))return e.enter("lineEnding"),e.consume(g),e.exit("lineEnding"),E;if(g===125&&d===0){let I=s?OC.call(p,s,o,m,x,f||!1,c||!1):{type:"ok",estree:void 0};if(I.type==="ok"){e.enter(n),e.consume(g),e.exit(n);let _=e.exit(r);return u&&I.estree&&Object.assign(_,{estree:I.estree}),t}return b=I.message,e.enter(i),e.consume(g),T}return e.enter(i),T(g)}function T(g){return g===125&&d===0||g===null||j(g)?(e.exit(i),k(g)):(g===123&&!s?d+=1:g===125&&(d-=1),e.consume(g),T)}function E(g){let I=p.now();if(I.line!==x.line&&!h&&p.parser.lazy[I.line])throw new me("Unexpected end of file in expression, expected a corresponding closing brace for `{`",p.now(),"micromark-extension-mdx-expression:unexpected-eof");return k(g)}}function OC(e,t,r,n,i,s){let o=lu(this.events.slice(r),{acorn:e,acornOptions:t,start:n,expression:!0,allowEmpty:i,prefix:s?"({":"",suffix:s?"})":""}),u=o.estree;if(s&&u){let c=u.body[0];if(c.type!=="ExpressionStatement"||c.expression.type!=="ObjectExpression")throw new me("Unexpected `"+c.type+"` in code: expected an object spread (`{...spread}`)",Qn(c).start,"micromark-extension-mdx-expression:non-spread");if(c.expression.properties[1])throw new me("Unexpected extra content in spread: only a single spread is supported",Qn(c.expression.properties[1]).start,"micromark-extension-mdx-expression:spread-extra");if(c.expression.properties[0]&&c.expression.properties[0].type!=="SpreadElement")throw new me("Unexpected `"+c.expression.properties[0].type+"` in code: only spread elements are supported",Qn(c.expression.properties[0]).start,"micromark-extension-mdx-expression:non-spread")}return o.error?{type:"nok",message:new me("Could not parse expression with acorn: "+o.error.message,{line:o.error.loc.line,column:o.error.loc.column+1,offset:o.error.pos},"micromark-extension-mdx-expression:acorn")}:{type:"ok",estree:u}}function bf(e){let t=e||{},r=t.addResult,n=t.acorn,i=t.spread,s=t.allowEmpty,o;if(s==null&&(s=!0),n){if(!n.parseExpressionAt)throw new Error("Expected a proper `acorn` instance passed in as `options.acorn`");o=Object.assign({ecmaVersion:2020,sourceType:"module"},t.acornOptions)}else if(t.acornOptions||t.addResult)throw new Error("Expected an `acorn` instance passed in as `options.acorn`");return{flow:{123:{tokenize:u,concrete:!0}},text:{123:{tokenize:c}}};function u(f,h,p){let m=this;return d;function d(k){return x(k)}function x(k){return $i.call(m,f,b,"mdxFlowExpression","mdxFlowExpressionMarker","mdxFlowExpressionChunk",n,o,r,i,s)(k)}function b(k){return W(k)?te(f,v,"whitespace")(k):v(k)}function v(k){return k===null||j(k)?h(k):p(k)}}function c(f,h){let p=this;return m;function m(d){return $i.call(p,f,h,"mdxTextExpression","mdxTextExpressionMarker","mdxTextExpressionChunk",n,o,r,i,s,!0)(d)}}}var wf=/[$A-Z_a-z\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7CA\uA7D0\uA7D1\uA7D3\uA7D5-\uA7D9\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/,db=/[\d\u00B7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0898-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0CF3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u180F-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1ABF-\u1ACE\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F]/;function Rt(e){return wf.test(String.fromCharCode(e))}function Hn(e){let t=String.fromCharCode(e);return wf.test(t)||db.test(t)}function fu(e,t,r,n,i,s,o,u,c,f,h,p,m,d,x,b,v,k,T,E,g,I,_,D,O,M,P,J,V,q,ee,re){let Ae=this,se,Ce;return yt;function yt(S){return e.enter(u),e.enter(c),e.consume(S),e.exit(c),R}function R(S){return ue(S)?r(S):(se=Ge,Ie(S))}function Ge(S){if(S===47)return e.enter(f),e.consume(S),e.exit(f),se=ut,Ie;if(S===62)return Mr(S);if(S!==null&&Rt(S))return e.enter(p),e.enter(m),e.consume(S),N;z(S,"before name","a character that can start a name, such as a letter, `$`, or `_`"+(S===33?" (note: to create a comment in MDX, use `{/* text */}`)":""))}function ut(S){if(S===62)return Mr(S);if(S!==null&&Rt(S))return e.enter(p),e.enter(m),e.consume(S),N;z(S,"before name","a character that can start a name, such as a letter, `$`, or `_`"+(S===42||S===47?" (note: JS comments in JSX tags are not supported in MDX)":""))}function N(S){if(S===45||S!==null&&Hn(S))return e.consume(S),N;if(S===46||S===47||S===58||S===62||S===123||ue(S)||Ke(S))return e.exit(m),se=Xe,Ie(S);z(S,"in name","a name character such as letters, digits, `$`, or `_`; whitespace before attributes; or the end of the tag"+(S===64?" (note: to create a link in MDX, use `[text](url)`)":""))}function Xe(S){if(S===46)return e.enter(d),e.consume(S),e.exit(d),se=Wt,Ie;if(S===58)return e.enter(b),e.consume(S),e.exit(b),se=De,Ie;if(S===47||S===62||S===123||S!==null&&Rt(S))return e.exit(p),He(S);z(S,"after name","a character that can start an attribute name, such as a letter, `$`, or `_`; whitespace before attributes; or the end of the tag")}function Wt(S){if(S!==null&&Rt(S))return e.enter(x),e.consume(S),tn;z(S,"before member name","a character that can start an attribute name, such as a letter, `$`, or `_`; whitespace before attributes; or the end of the tag")}function tn(S){if(S===45||S!==null&&Hn(S))return e.consume(S),tn;if(S===46||S===47||S===62||S===123||ue(S)||Ke(S))return e.exit(x),se=ct,Ie(S);z(S,"in member name","a name character such as letters, digits, `$`, or `_`; whitespace before attributes; or the end of the tag"+(S===64?" (note: to create a link in MDX, use `[text](url)`)":""))}function ct(S){if(S===46)return e.enter(d),e.consume(S),e.exit(d),se=Wt,Ie;if(S===47||S===62||S===123||S!==null&&Rt(S))return e.exit(p),He(S);z(S,"after member name","a character that can start an attribute name, such as a letter, `$`, or `_`; whitespace before attributes; or the end of the tag")}function De(S){if(S!==null&&Rt(S))return e.enter(v),e.consume(S),Nt;z(S,"before local name","a character that can start a name, such as a letter, `$`, or `_`"+(S===43||S!==null&&S>46&&S<58?" (note: to create a link in MDX, use `[text](url)`)":""))}function Nt(S){if(S===45||S!==null&&Hn(S))return e.consume(S),Nt;if(S===47||S===62||S===123||ue(S)||Ke(S))return e.exit(v),se=xt,Ie(S);z(S,"in local name","a name character such as letters, digits, `$`, or `_`; whitespace before attributes; or the end of the tag")}function xt(S){if(S===47||S===62||S===123||S!==null&&Rt(S))return e.exit(p),He(S);z(S,"after local name","a character that can start an attribute name, such as a letter, `$`, or `_`; whitespace before attributes; or the end of the tag")}function He(S){if(S===47)return e.enter(h),e.consume(S),e.exit(h),se=St,Ie;if(S===62)return Mr(S);if(S===123)return $i.call(Ae,e,Pt,k,T,E,n,i,s,!0,!1,o)(S);if(S!==null&&Rt(S))return e.enter(g),e.enter(I),e.enter(_),e.consume(S),Kt;z(S,"before attribute name","a character that can start an attribute name, such as a letter, `$`, or `_`; whitespace before attributes; or the end of the tag")}function Pt(S){return se=He,Ie(S)}function Kt(S){if(S===45||S!==null&&Hn(S))return e.consume(S),Kt;if(S===47||S===58||S===61||S===62||S===123||ue(S)||Ke(S))return e.exit(_),se=Kn,Ie(S);z(S,"in attribute name","an attribute name character such as letters, digits, `$`, or `_`; `=` to initialize a value; whitespace before attributes; or the end of the tag")}function Kn(S){if(S===58)return e.enter(D),e.consume(S),e.exit(D),se=Xt,Ie;if(S===61)return e.exit(I),e.enter(M),e.consume(S),e.exit(M),se=br,Ie;if(S===47||S===62||S===123||ue(S)||Ke(S)||S!==null&&Rt(S))return e.exit(I),e.exit(g),se=He,Ie(S);z(S,"after attribute name","a character that can start an attribute name, such as a letter, `$`, or `_`; `=` to initialize a value; or the end of the tag")}function Xt(S){if(S!==null&&Rt(S))return e.enter(O),e.consume(S),Yt;z(S,"before local attribute name","a character that can start an attribute name, such as a letter, `$`, or `_`; `=` to initialize a value; or the end of the tag")}function Yt(S){if(S===45||S!==null&&Hn(S))return e.consume(S),Yt;if(S===47||S===61||S===62||S===123||ue(S)||Ke(S))return e.exit(O),e.exit(I),se=In,Ie(S);z(S,"in local attribute name","an attribute name character such as letters, digits, `$`, or `_`; `=` to initialize a value; whitespace before attributes; or the end of the tag")}function In(S){if(S===61)return e.enter(M),e.consume(S),e.exit(M),se=br,Ie;if(S===47||S===62||S===123||S!==null&&Rt(S))return e.exit(g),He(S);z(S,"after local attribute name","a character that can start an attribute name, such as a letter, `$`, or `_`; `=` to initialize a value; or the end of the tag")}function br(S){if(S===34||S===39)return e.enter(P),e.enter(J),e.consume(S),e.exit(J),Ce=S,er;if(S===123)return $i.call(Ae,e,Tn,q,ee,re,n,i,s,!1,!1,o)(S);z(S,"before attribute value","a character that can start an attribute value, such as `\"`, `'`, or `{`"+(S===60?" (note: to use an element or fragment as a prop value in MDX, use `{<element />}`)":""))}function Tn(S){return e.exit(g),se=He,Ie(S)}function er(S){return S===null&&z(S,"in attribute value","a corresponding closing quote `"+String.fromCodePoint(Ce)+"`"),S===Ce?(e.enter(J),e.consume(S),e.exit(J),e.exit(P),e.exit(g),Ce=void 0,se=He,Ie):j(S)?(se=er,Ie(S)):(e.enter(V),Br(S))}function Br(S){return S===null||S===Ce||j(S)?(e.exit(V),er(S)):(e.consume(S),Br)}function St(S){if(S===62)return Mr(S);z(S,"after self-closing slash","`>` to end the tag"+(S===42||S===47?" (note: JS comments in JSX tags are not supported in MDX)":""))}function Mr(S){return e.enter(c),e.consume(S),e.exit(c),e.exit(u),t}function Ie(S){return j(S)?(e.enter("lineEnding"),e.consume(S),e.exit("lineEnding"),Te):W(S)||Ke(S)?(e.enter("esWhitespace"),Rn(S)):se(S)}function Rn(S){return j(S)?(e.exit("esWhitespace"),Ie(S)):W(S)||Ke(S)?(e.consume(S),Rn):(e.exit("esWhitespace"),se(S))}function Te(S){if(!o&&Ae.parser.lazy[Ae.now().line])throw new me("Unexpected lazy line in container, expected line to be prefixed with `>` when in a block quote, whitespace when in a list, etc",Ae.now(),"micromark-extension-mdx-jsx:unexpected-eof");return Ie(S)}function z(S,ne,ye){throw new me("Unexpected "+(S===null?"end of file":"character `"+(S===96?"` ` `":String.fromCodePoint(S))+"` ("+FC(S)+")")+" "+ne+", expected "+ye,Ae.now(),"micromark-extension-mdx-jsx:unexpected-"+(S===null?"eof":"character"))}}function FC(e){return"U+"+e.toString(16).toUpperCase().padStart(4,"0")}function mb(e,t,r){return{tokenize:n};function n(i,s,o){return fu.call(this,i,s,o,e,t,r,!0,"mdxJsxTextTag","mdxJsxTextTagMarker","mdxJsxTextTagClosingMarker","mdxJsxTextTagSelfClosingMarker","mdxJsxTextTagName","mdxJsxTextTagNamePrimary","mdxJsxTextTagNameMemberMarker","mdxJsxTextTagNameMember","mdxJsxTextTagNamePrefixMarker","mdxJsxTextTagNameLocal","mdxJsxTextTagExpressionAttribute","mdxJsxTextTagExpressionAttributeMarker","mdxJsxTextTagExpressionAttributeValue","mdxJsxTextTagAttribute","mdxJsxTextTagAttributeName","mdxJsxTextTagAttributeNamePrimary","mdxJsxTextTagAttributeNamePrefixMarker","mdxJsxTextTagAttributeNameLocal","mdxJsxTextTagAttributeInitializerMarker","mdxJsxTextTagAttributeValueLiteral","mdxJsxTextTagAttributeValueLiteralMarker","mdxJsxTextTagAttributeValueLiteralValue","mdxJsxTextTagAttributeValueExpression","mdxJsxTextTagAttributeValueExpressionMarker","mdxJsxTextTagAttributeValueExpressionValue")}}function gb(e,t,r){return{tokenize:n,concrete:!0};function n(i,s,o){let u=this;return c;function c(m){return f(m)}function f(m){return fu.call(u,i,h,o,e,t,r,!1,"mdxJsxFlowTag","mdxJsxFlowTagMarker","mdxJsxFlowTagClosingMarker","mdxJsxFlowTagSelfClosingMarker","mdxJsxFlowTagName","mdxJsxFlowTagNamePrimary","mdxJsxFlowTagNameMemberMarker","mdxJsxFlowTagNameMember","mdxJsxFlowTagNamePrefixMarker","mdxJsxFlowTagNameLocal","mdxJsxFlowTagExpressionAttribute","mdxJsxFlowTagExpressionAttributeMarker","mdxJsxFlowTagExpressionAttributeValue","mdxJsxFlowTagAttribute","mdxJsxFlowTagAttributeName","mdxJsxFlowTagAttributeNamePrimary","mdxJsxFlowTagAttributeNamePrefixMarker","mdxJsxFlowTagAttributeNameLocal","mdxJsxFlowTagAttributeInitializerMarker","mdxJsxFlowTagAttributeValueLiteral","mdxJsxFlowTagAttributeValueLiteralMarker","mdxJsxFlowTagAttributeValueLiteralValue","mdxJsxFlowTagAttributeValueExpression","mdxJsxFlowTagAttributeValueExpressionMarker","mdxJsxFlowTagAttributeValueExpressionValue")(m)}function h(m){return W(m)?te(i,p,"whitespace")(m):p(m)}function p(m){return m===60?c(m):m===null||j(m)?s(m):o(m)}}}function vf(e){let t=e||{},r=t.acorn,n;if(r){if(!r.parse||!r.parseExpressionAt)throw new Error("Expected a proper `acorn` instance passed in as `options.acorn`");n=Object.assign({ecmaVersion:2020,sourceType:"module"},t.acornOptions,{locations:!0})}else if(t.acornOptions||t.addResult)throw new Error("Expected an `acorn` instance passed in as `options.acorn`");return{flow:{60:gb(r||void 0,n,t.addResult||!1)},text:{60:mb(r||void 0,n,t.addResult||!1)}}}var yb={disable:{null:["autolink","codeIndented","htmlFlow","htmlText"]}};var LC={tokenize:BC,partial:!0},zC=new Set(["ExportAllDeclaration","ExportDefaultDeclaration","ExportNamedDeclaration","ImportDeclaration"]);function kf(e){let t={tokenize:i,concrete:!0};if(!e||!e.acorn||!e.acorn.parse)throw new Error("Expected an `acorn` instance passed in as `options.acorn`");let r=e.acorn,n=Object.assign({ecmaVersion:2020,sourceType:"module"},e.acornOptions);return{flow:{101:t,105:t}};function i(s,o,u){let c=this,f=c.parser.definedModuleSpecifiers||(c.parser.definedModuleSpecifiers=[]),h=this.events.length+1,p="";return c.interrupt?u:m;function m(T){return c.now().column>1?u(T):(s.enter("mdxjsEsm"),s.enter("mdxjsEsmData"),s.consume(T),p+=String.fromCharCode(T),d)}function d(T){return Ze(T)?(s.consume(T),p+=String.fromCharCode(T),d):(p==="import"||p==="export")&&T===32?(s.consume(T),x):u(T)}function x(T){return T===null||j(T)?(s.exit("mdxjsEsmData"),b(T)):(s.consume(T),x)}function b(T){return T===null?k(T):j(T)?s.check(LC,k,v)(T):(s.enter("mdxjsEsmData"),x(T))}function v(T){return s.enter("lineEnding"),s.consume(T),s.exit("lineEnding"),b}function k(T){let E=lu(c.events.slice(h),{acorn:r,acornOptions:n,prefix:f.length>0?"var "+f.join(",")+`+`:""});if(E.error){if(T!==null&&E.swallow)return v(T);throw new me("Could not parse import/exports with acorn: "+String(E.error),{line:E.error.loc.line,column:E.error.loc.column+1,offset:E.error.pos},"micromark-extension-mdxjs-esm:acorn")}if(f.length>0){let I=E.estree.body.shift()}let g=-1;for(;++g<E.estree.body.length;){let I=E.estree.body[g];if(!zC.has(I.type))throw new me("Unexpected `"+I.type+"` in code: only import/exports are supported",Qn(I),"micromark-extension-mdxjs-esm:non-esm");if(I.type==="ImportDeclaration"&&!c.interrupt){let _=-1;for(;++_<I.specifiers.length;){let D=I.specifiers[_];f.push(D.local.name)}}}return Object.assign(s.exit("mdxjsEsm"),e.addResult?{estree:E.estree}:void 0),o(T)}}}function BC(e,t,r){return n;function n(i){return e.enter("lineEndingBlank"),e.consume(i),e.exit("lineEndingBlank"),e.attempt(jt,t,r)}}function bb(e){let t=Object.assign({acorn:Qe.extend((0,xb.default)()),acornOptions:{ecmaVersion:2020,sourceType:"module"},addResult:!0},e);return Ni([kf(t),bf(t),vf(t),yb])}var Af={enter:{mdxFlowExpression:MC,mdxTextExpression:VC},exit:{mdxFlowExpression:wb,mdxFlowExpressionChunk:vb,mdxTextExpression:wb,mdxTextExpressionChunk:vb}},Sf={handlers:{mdxFlowExpression:kb,mdxTextExpression:kb},unsafe:[{character:"{",inConstruct:["phrasing"]},{atBreak:!0,character:"{"}]};function MC(e){this.enter({type:"mdxFlowExpression",value:""},e),this.buffer()}function VC(e){this.enter({type:"mdxTextExpression",value:""},e),this.buffer()}function wb(e){let t=this.resume(),r=e.estree,n=this.exit(e);n.value=t,r&&(n.data={estree:r})}function vb(e){this.config.enter.data.call(this,e),this.config.exit.data.call(this,e)}function kb(e){return"{"+(e.value||"")+"}"}var Ab=["AElig","AMP","Aacute","Acirc","Agrave","Aring","Atilde","Auml","COPY","Ccedil","ETH","Eacute","Ecirc","Egrave","Euml","GT","Iacute","Icirc","Igrave","Iuml","LT","Ntilde","Oacute","Ocirc","Ograve","Oslash","Otilde","Ouml","QUOT","REG","THORN","Uacute","Ucirc","Ugrave","Uuml","Yacute","aacute","acirc","acute","aelig","agrave","amp","aring","atilde","auml","brvbar","ccedil","cedil","cent","copy","curren","deg","divide","eacute","ecirc","egrave","eth","euml","frac12","frac14","frac34","gt","iacute","icirc","iexcl","igrave","iquest","iuml","laquo","lt","macr","micro","middot","nbsp","not","ntilde","oacute","ocirc","ograve","ordf","ordm","oslash","otilde","ouml","para","plusmn","pound","quot","raquo","reg","sect","shy","sup1","sup2","sup3","szlig","thorn","times","uacute","ucirc","ugrave","uml","uuml","yacute","yen","yuml"];var Ef={0:"\uFFFD",128:"\u20AC",130:"\u201A",131:"\u0192",132:"\u201E",133:"\u2026",134:"\u2020",135:"\u2021",136:"\u02C6",137:"\u2030",138:"\u0160",139:"\u2039",140:"\u0152",142:"\u017D",145:"\u2018",146:"\u2019",147:"\u201C",148:"\u201D",149:"\u2022",150:"\u2013",151:"\u2014",152:"\u02DC",153:"\u2122",154:"\u0161",155:"\u203A",156:"\u0153",158:"\u017E",159:"\u0178"};function pu(e){let t=typeof e=="string"?e.charCodeAt(0):e;return t>=48&&t<=57}function Sb(e){let t=typeof e=="string"?e.charCodeAt(0):e;return t>=97&&t<=102||t>=65&&t<=70||t>=48&&t<=57}function Eb(e){let t=typeof e=="string"?e.charCodeAt(0):e;return t>=97&&t<=122||t>=65&&t<=90}function _f(e){return Eb(e)||pu(e)}var ji=String.fromCharCode,$C=["","Named character references must be terminated by a semicolon","Numeric character references must be terminated by a semicolon","Named character references cannot be empty","Numeric character references cannot be empty","Named character references must be known","Numeric character references cannot be disallowed","Numeric character references cannot be outside the permissible Unicode range"];function Cf(e,t={}){let r=typeof t.additional=="string"?t.additional.charCodeAt(0):t.additional,n=[],i=0,s=-1,o="",u,c;t.position&&("start"in t.position||"indent"in t.position?(c=t.position.indent,u=t.position.start):u=t.position);let f=(u?u.line:0)||1,h=(u?u.column:0)||1,p=d(),m;for(i--;++i<=e.length;)if(m===10&&(h=(c?c[s]:0)||1),m=e.charCodeAt(i),m===38){let v=e.charCodeAt(i+1);if(v===9||v===10||v===12||v===32||v===38||v===60||Number.isNaN(v)||r&&v===r){o+=ji(m),h++;continue}let k=i+1,T=k,E=k,g;if(v===35){E=++T;let V=e.charCodeAt(E);V===88||V===120?(g="hexadecimal",E=++T):g="decimal"}else g="named";let I="",_="",D="",O=g==="named"?_f:g==="decimal"?pu:Sb;for(E--;++E<=e.length;){let V=e.charCodeAt(E);if(!O(V))break;D+=ji(V),g==="named"&&Ab.includes(D)&&(I=D,_=Wr(D))}let M=e.charCodeAt(E)===59;if(M){E++;let V=g==="named"?Wr(D):!1;V&&(I=D,_=V)}let P=1+E-k,J="";if(!(!M&&t.nonTerminated===!1))if(!D)g!=="named"&&x(4,P);else if(g==="named"){if(M&&!_)x(5,1);else if(I!==D&&(E=T+I.length,P=1+E-T,M=!1),!M){let V=I?1:3;if(t.attribute){let q=e.charCodeAt(E);q===61?(x(V,P),_=""):_f(q)?_="":x(V,P)}else x(V,P)}J=_}else{M||x(2,P);let V=Number.parseInt(D,g==="hexadecimal"?16:10);if(jC(V))x(7,P),J=ji(65533);else if(V in Ef)x(6,P),J=Ef[V];else{let q="";UC(V)&&x(6,P),V>65535&&(V-=65536,q+=ji(V>>>10|55296),V=56320|V&1023),J=q+ji(V)}}if(J){b(),p=d(),i=E-1,h+=E-k+1,n.push(J);let V=d();V.offset++,t.reference&&t.reference.call(t.referenceContext,J,{start:p,end:V},e.slice(k-1,E)),p=V}else D=e.slice(k-1,E),o+=D,h+=D.length,i=E-1}else m===10&&(f++,s++,h=0),Number.isNaN(m)?b():(o+=ji(m),h++);return n.join("");function d(){return{line:f,column:h,offset:i+((u?u.offset:0)||0)}}function x(v,k){let T;t.warning&&(T=d(),T.column+=k,T.offset+=k,t.warning.call(t.warningContext,$C[v],T,v))}function b(){o&&(n.push(o),t.text&&t.text.call(t.textContext,o,{start:p,end:d()}),o="")}}function jC(e){return e>=55296&&e<=57343||e>1114111}function UC(e){return e>=1&&e<=8||e===11||e>=13&&e<=31||e>=127&&e<=159||e>=64976&&e<=65007||(e&65535)===65535||(e&65535)===65534}function _b(e,t){if(e=e.replace(t.subset?qC(t.subset):/["&'<>`]/g,n),t.subset||t.escapeOnly)return e;return e.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,r).replace(/[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g,n);function r(i,s,o){return t.format((i.charCodeAt(0)-55296)*1024+i.charCodeAt(1)-56320+65536,o.charCodeAt(s+2),t)}function n(i,s,o){return t.format(i.charCodeAt(0),o.charCodeAt(s+1),t)}}function qC(e){let t=[],r=-1;for(;++r<e.length;)t.push(e[r].replace(/[|\\{}()[\]^$+*?.]/g,"\\$&"));return new RegExp("(?:"+t.join("|")+")","g")}function Cb(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Db(e,t){return _b(e,Object.assign({format:Cb},t))}var Ib=" ";function Df(){return{canContainEols:["mdxJsxTextElement"],enter:{mdxJsxFlowTag:r,mdxJsxFlowTagClosingMarker:n,mdxJsxFlowTagAttribute:h,mdxJsxFlowTagExpressionAttribute:p,mdxJsxFlowTagAttributeValueLiteral:e,mdxJsxFlowTagAttributeValueExpression:e,mdxJsxFlowTagSelfClosingMarker:s,mdxJsxTextTag:r,mdxJsxTextTagClosingMarker:n,mdxJsxTextTagAttribute:h,mdxJsxTextTagExpressionAttribute:p,mdxJsxTextTagAttributeValueLiteral:e,mdxJsxTextTagAttributeValueExpression:e,mdxJsxTextTagSelfClosingMarker:s},exit:{mdxJsxFlowTagClosingMarker:o,mdxJsxFlowTagNamePrimary:u,mdxJsxFlowTagNameMember:c,mdxJsxFlowTagNameLocal:f,mdxJsxFlowTagExpressionAttribute:m,mdxJsxFlowTagExpressionAttributeValue:t,mdxJsxFlowTagAttributeNamePrimary:d,mdxJsxFlowTagAttributeNameLocal:x,mdxJsxFlowTagAttributeValueLiteral:b,mdxJsxFlowTagAttributeValueLiteralValue:t,mdxJsxFlowTagAttributeValueExpression:v,mdxJsxFlowTagAttributeValueExpressionValue:t,mdxJsxFlowTagSelfClosingMarker:k,mdxJsxFlowTag:T,mdxJsxTextTagClosingMarker:o,mdxJsxTextTagNamePrimary:u,mdxJsxTextTagNameMember:c,mdxJsxTextTagNameLocal:f,mdxJsxTextTagExpressionAttribute:m,mdxJsxTextTagExpressionAttributeValue:t,mdxJsxTextTagAttributeNamePrimary:d,mdxJsxTextTagAttributeNameLocal:x,mdxJsxTextTagAttributeValueLiteral:b,mdxJsxTextTagAttributeValueLiteralValue:t,mdxJsxTextTagAttributeValueExpression:v,mdxJsxTextTagAttributeValueExpressionValue:t,mdxJsxTextTagSelfClosingMarker:k,mdxJsxTextTag:T}};function e(){this.buffer()}function t(_){this.config.enter.data.call(this,_),this.config.exit.data.call(this,_)}function r(_){let D={name:void 0,attributes:[],close:!1,selfClosing:!1,start:_.start,end:_.end};this.getData("mdxJsxTagStack")||this.setData("mdxJsxTagStack",[]),this.setData("mdxJsxTag",D),this.buffer()}function n(_){if(this.getData("mdxJsxTagStack").length===0)throw new me("Unexpected closing slash `/` in tag, expected an open tag first",{start:_.start,end:_.end},"mdast-util-mdx-jsx:unexpected-closing-slash")}function i(_){if(this.getData("mdxJsxTag").close)throw new me("Unexpected attribute in closing tag, expected the end of the tag",{start:_.start,end:_.end},"mdast-util-mdx-jsx:unexpected-attribute")}function s(_){if(this.getData("mdxJsxTag").close)throw new me("Unexpected self-closing slash `/` in closing tag, expected the end of the tag",{start:_.start,end:_.end},"mdast-util-mdx-jsx:unexpected-self-closing-slash")}function o(){let _=this.getData("mdxJsxTag");_.close=!0}function u(_){let D=this.getData("mdxJsxTag");D.name=this.sliceSerialize(_)}function c(_){let D=this.getData("mdxJsxTag");D.name+="."+this.sliceSerialize(_)}function f(_){let D=this.getData("mdxJsxTag");D.name+=":"+this.sliceSerialize(_)}function h(_){let D=this.getData("mdxJsxTag");i.call(this,_),D.attributes.push({type:"mdxJsxAttribute",name:"",value:null})}function p(_){let D=this.getData("mdxJsxTag");i.call(this,_),D.attributes.push({type:"mdxJsxExpressionAttribute",value:""}),this.buffer()}function m(_){let D=this.getData("mdxJsxTag"),O=D.attributes[D.attributes.length-1],M=_.estree;O.value=this.resume(),M&&(O.data={estree:M})}function d(_){let D=this.getData("mdxJsxTag"),O=D.attributes[D.attributes.length-1];O.name=this.sliceSerialize(_)}function x(_){let D=this.getData("mdxJsxTag"),O=D.attributes[D.attributes.length-1];O.name+=":"+this.sliceSerialize(_)}function b(){let _=this.getData("mdxJsxTag");_.attributes[_.attributes.length-1].value=Cf(this.resume(),{nonTerminated:!1})}function v(_){let D=this.getData("mdxJsxTag"),O=D.attributes[D.attributes.length-1],M={type:"mdxJsxAttributeValueExpression",value:this.resume()},P=_.estree;P&&(M.data={estree:P}),O.value=M}function k(){let _=this.getData("mdxJsxTag");_.selfClosing=!0}function T(_){let D=this.getData("mdxJsxTag"),O=this.getData("mdxJsxTagStack"),M=O[O.length-1];if(D.close&&M.name!==D.name)throw new me("Unexpected closing tag `"+I(D)+"`, expected corresponding closing tag for `"+I(M)+"` ("+Tt(M)+")",{start:_.start,end:_.end},"mdast-util-mdx-jsx:end-tag-mismatch");this.resume(),D.close?O.pop():this.enter({type:_.type==="mdxJsxTextTag"?"mdxJsxTextElement":"mdxJsxFlowElement",name:D.name||null,attributes:D.attributes,children:[]},_,E),D.selfClosing||D.close?this.exit(_,g):O.push(D)}function E(_,D){let O=this.getData("mdxJsxTag"),M=_?" before the end of `"+_.type+"`":"",P=_?{start:_.start,end:_.end}:void 0;throw new me("Expected a closing tag for `"+I(O)+"` ("+Tt({start:D.start,end:D.end})+")"+M,P,"mdast-util-mdx-jsx:end-tag-mismatch")}function g(_,D){let O=this.getData("mdxJsxTag");throw new me("Expected the closing tag `"+I(O)+"` either after the end of `"+D.type+"` ("+Tt(D.end)+") or another opening tag after the start of `"+D.type+"` ("+Tt(D.start)+")",{start:_.start,end:_.end},"mdast-util-mdx-jsx:end-tag-mismatch")}function I(_){return"<"+(_.close?"/":"")+(_.name||"")+">"}}function If(e){let t=e||{},r=t.quote||'"',n=t.quoteSmart||!1,i=t.tightSelfClosing||!1,s=t.printWidth||Number.POSITIVE_INFINITY,o=r==='"'?"'":'"';if(r!=='"'&&r!=="'")throw new Error("Cannot serialize attribute values with `"+r+"` for `options.quote`, expected `\"`, or `'`");return u.peek=JC,{handlers:{mdxJsxFlowElement:u,mdxJsxTextElement:u},unsafe:[{character:"<",inConstruct:["phrasing"]},{atBreak:!0,character:"<"}],fences:!0,resourceLink:!0};function u(c,f,h,p){let m=c.type==="mdxJsxFlowElement",d=c.name?!c.children||c.children.length===0:!1,x=Tb(h),b=Rb(x),v=Or(p),k=Or(p),T=[],E=(m?b:"")+"<"+(c.name||""),g=h.enter(c.type);if(v.move(E),k.move(E),c.attributes&&c.attributes.length>0){if(!c.name)throw new Error("Cannot serialize fragment w/ attributes");let M=-1;for(;++M<c.attributes.length;){let P=c.attributes[M],J;if(P.type==="mdxJsxExpressionAttribute")J="{"+(P.value||"")+"}";else{if(!P.name)throw new Error("Cannot serialize attribute w/o name");let V=P.value,q=P.name,ee="";if(V!=null)if(typeof V=="object")ee="{"+(V.value||"")+"}";else{let re=n&&Fi(V,r)>Fi(V,o)?o:r;ee=re+Db(V,{subset:[re]})+re}J=q+(ee?"=":"")+ee}T.push(J)}}let I=!1,_=T.join(" ");m&&(/\r?\n|\r/.test(_)||v.current().now.column+_.length+(d?i?2:3:1)>s)&&(I=!0);let D=v,O=E;if(I){D=k;let M=-1;for(;++M<T.length;)T[M]=b+Ib+T[M];O+=D.move(`+`+T.join(`+`)+`+`+b)}else _&&(O+=D.move(" "+_));return d&&(O+=D.move((i||I?"":" ")+"/")),O+=D.move(">"),c.children&&c.children.length>0&&(c.type==="mdxJsxTextElement"?O+=D.move(Li(c,h,{...D.current(),before:">",after:"<"})):(D.shift(2),O+=D.move(`+`),O+=D.move(ZC(c,h,D.current())),O+=D.move(`+`))),d||(O+=D.move((m?b:"")+"</"+(c.name||"")+">")),g(),O}}function ZC(e,t,r){let n=t.indexStack,i=e.children,s=t.createTracker(r),o=Rb(Tb(t)),u=[],c=-1;for(n.push(-1);++c<i.length;){let f=i[c];n[n.length-1]=c;let h={before:`+`,after:`+`,...s.current()},p=t.handle(f,e,t,h),m=f.type==="mdxJsxFlowElement"?p:Ha(p,function(d,x,b){return(b?"":o)+d});u.push(s.move(m)),f.type!=="list"&&(t.bulletLastUsed=void 0),c<i.length-1&&u.push(s.move(`++`))}return n.pop(),u.join("")}function Tb(e){let t=0;for(let r of e.stack)r==="mdxJsxFlowElement"&&t++;return t}function Rb(e){return Ib.repeat(e)}function JC(){return"<"}var Tf={enter:{mdxjsEsm:GC},exit:{mdxjsEsm:QC,mdxjsEsmData:HC}},Rf={handlers:{mdxjsEsm:WC}};function GC(e){this.enter({type:"mdxjsEsm",value:""},e),this.buffer()}function QC(e){let t=this.resume(),r=this.exit(e),n=e.estree;r.value=t,n&&(r.data={estree:n})}function HC(e){this.config.enter.data.call(this,e),this.config.exit.data.call(this,e)}function WC(e){return e.value||""}function Nb(){return[Af,Df(),Tf]}function Pb(e){return{extensions:[Sf,If(e),Rf]}}function Nf(e){let t=this.data();r("micromarkExtensions",bb(e)),r("fromMarkdownExtensions",Nb()),r("toMarkdownExtensions",Pb(e));function r(n,i){(t[n]?t[n]:t[n]=[]).push(i)}}var KC={};function Pf(e,t){let r=t||KC,n=typeof r.includeImageAlt=="boolean"?r.includeImageAlt:!0,i=typeof r.includeHtml=="boolean"?r.includeHtml:!0;return Fb(e,n,i)}function Fb(e,t,r){if(XC(e)){if("value"in e)return e.type==="html"&&!r?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return Ob(e.children,t,r)}return Array.isArray(e)?Ob(e,t,r):""}function Ob(e,t,r){let n=[],i=-1;for(;++i<e.length;)n[i]=Fb(e[i],t,r);return n.join("")}function XC(e){return!!(e&&typeof e=="object")}var Lb={tokenize:YC};function YC(e){let t=e.attempt(this.parser.constructs.contentInitial,n,i),r;return t;function n(u){if(u===null){e.consume(u);return}return e.enter("lineEnding"),e.consume(u),e.exit("lineEnding"),te(e,t,"linePrefix")}function i(u){return e.enter("paragraph"),s(u)}function s(u){let c=e.enter("chunkText",{contentType:"text",previous:r});return r&&(r.next=c),r=c,o(u)}function o(u){if(u===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(u);return}return j(u)?(e.consume(u),e.exit("chunkText"),s):(e.consume(u),o)}}var Bb={tokenize:e2},zb={tokenize:t2};function e2(e){let t=this,r=[],n=0,i,s,o;return u;function u(E){if(n<r.length){let g=r[n];return t.containerState=g[1],e.attempt(g[0].continuation,c,f)(E)}return f(E)}function c(E){if(n++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,i&&T();let g=t.events.length,I=g,_;for(;I--;)if(t.events[I][0]==="exit"&&t.events[I][1].type==="chunkFlow"){_=t.events[I][1].end;break}k(n);let D=g;for(;D<t.events.length;)t.events[D][1].end=Object.assign({},_),D++;return Je(t.events,I+1,0,t.events.slice(g)),t.events.length=D,f(E)}return u(E)}function f(E){if(n===r.length){if(!i)return m(E);if(i.currentConstruct&&i.currentConstruct.concrete)return x(E);t.interrupt=!!(i.currentConstruct&&!i._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(zb,h,p)(E)}function h(E){return i&&T(),k(n),m(E)}function p(E){return t.parser.lazy[t.now().line]=n!==r.length,o=t.now().offset,x(E)}function m(E){return t.containerState={},e.attempt(zb,d,x)(E)}function d(E){return n++,r.push([t.currentConstruct,t.containerState]),m(E)}function x(E){if(E===null){i&&T(),k(0),e.consume(E);return}return i=i||t.parser.flow(t.now()),e.enter("chunkFlow",{contentType:"flow",previous:s,_tokenizer:i}),b(E)}function b(E){if(E===null){v(e.exit("chunkFlow"),!0),k(0),e.consume(E);return}return j(E)?(e.consume(E),v(e.exit("chunkFlow")),n=0,t.interrupt=void 0,u):(e.consume(E),b)}function v(E,g){let I=t.sliceStream(E);if(g&&I.push(null),E.previous=s,s&&(s.next=E),s=E,i.defineSkip(E.start),i.write(I),t.parser.lazy[E.start.line]){let _=i.events.length;for(;_--;)if(i.events[_][1].start.offset<o&&(!i.events[_][1].end||i.events[_][1].end.offset>o))return;let D=t.events.length,O=D,M,P;for(;O--;)if(t.events[O][0]==="exit"&&t.events[O][1].type==="chunkFlow"){if(M){P=t.events[O][1].end;break}M=!0}for(k(n),_=D;_<t.events.length;)t.events[_][1].end=Object.assign({},P),_++;Je(t.events,O+1,0,t.events.slice(D)),t.events.length=_}}function k(E){let g=r.length;for(;g-- >E;){let I=r[g];t.containerState=I[1],I[0].exit.call(t,e)}r.length=E}function T(){i.write([null]),s=void 0,i=void 0,t.containerState._closeFlow=void 0}}function t2(e,t,r){return te(e,e.attempt(this.parser.constructs.document,t,r),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}var Mb={tokenize:r2};function r2(e){let t=this,r=e.attempt(jt,n,e.attempt(this.parser.constructs.flowInitial,i,te(e,e.attempt(this.parser.constructs.flow,i,e.attempt(xl,i)),"linePrefix")));return r;function n(s){if(s===null){e.consume(s);return}return e.enter("lineEndingBlank"),e.consume(s),e.exit("lineEndingBlank"),t.currentConstruct=void 0,r}function i(s){if(s===null){e.consume(s);return}return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),t.currentConstruct=void 0,r}}var Vb={resolveAll:qb()},$b=Ub("string"),jb=Ub("text");function Ub(e){return{tokenize:t,resolveAll:qb(e==="text"?n2:void 0)};function t(r){let n=this,i=this.parser.constructs[e],s=r.attempt(i,o,u);return o;function o(h){return f(h)?s(h):u(h)}function u(h){if(h===null){r.consume(h);return}return r.enter("data"),r.consume(h),c}function c(h){return f(h)?(r.exit("data"),s(h)):(r.consume(h),c)}function f(h){if(h===null)return!0;let p=i[h],m=-1;if(p)for(;++m<p.length;){let d=p[m];if(!d.previous||d.previous.call(n,n.previous))return!0}return!1}}}function qb(e){return t;function t(r,n){let i=-1,s;for(;++i<=r.length;)s===void 0?r[i]&&r[i][1].type==="data"&&(s=i,i++):(!r[i]||r[i][1].type!=="data")&&(i!==s+2&&(r[s][1].end=r[i-1][1].end,r.splice(s+2,i-s-2),i=s+2),s=void 0);return e?e(r,n):r}}function n2(e,t){let r=0;for(;++r<=e.length;)if((r===e.length||e[r][1].type==="lineEnding")&&e[r-1][1].type==="data"){let n=e[r-1][1],i=t.sliceStream(n),s=i.length,o=-1,u=0,c;for(;s--;){let f=i[s];if(typeof f=="string"){for(o=f.length;f.charCodeAt(o-1)===32;)u++,o--;if(o)break;o=-1}else if(f===-2)c=!0,u++;else if(f!==-1){s++;break}}if(u){let f={type:r===e.length||c||u<2?"lineSuffix":"hardBreakTrailing",start:{line:n.end.line,column:n.end.column-u,offset:n.end.offset-u,_index:n.start._index+s,_bufferIndex:s?o:n.start._bufferIndex+o},end:Object.assign({},n.end)};n.end=Object.assign({},f.start),n.start.offset===n.end.offset?Object.assign(n,f):(e.splice(r,0,["enter",f,t],["exit",f,t]),r+=2)}r++}return e}function Zb(e,t,r){let n=Object.assign(r?Object.assign({},r):{line:1,column:1,offset:0},{_index:0,_bufferIndex:-1}),i={},s=[],o=[],u=[],c=!0,f={consume:g,enter:I,exit:_,attempt:M(D),check:M(O),interrupt:M(O,{interrupt:!0})},h={previous:null,code:null,containerState:{},events:[],parser:e,sliceStream:b,sliceSerialize:x,now:v,defineSkip:k,write:d},p=t.tokenize.call(h,f),m;return t.resolveAll&&s.push(t),h;function d(q){return o=dt(o,q),T(),o[o.length-1]!==null?[]:(P(t,0),h.events=kn(s,h.events,h),h.events)}function x(q,ee){return s2(b(q),ee)}function b(q){return i2(o,q)}function v(){let{line:q,column:ee,offset:re,_index:Ae,_bufferIndex:se}=n;return{line:q,column:ee,offset:re,_index:Ae,_bufferIndex:se}}function k(q){i[q.line]=q.column,V()}function T(){let q;for(;n._index<o.length;){let ee=o[n._index];if(typeof ee=="string")for(q=n._index,n._bufferIndex<0&&(n._bufferIndex=0);n._index===q&&n._bufferIndex<ee.length;)E(ee.charCodeAt(n._bufferIndex));else E(ee)}}function E(q){c=void 0,m=q,p=p(q)}function g(q){j(q)?(n.line++,n.column=1,n.offset+=q===-3?2:1,V()):q!==-1&&(n.column++,n.offset++),n._bufferIndex<0?n._index++:(n._bufferIndex++,n._bufferIndex===o[n._index].length&&(n._bufferIndex=-1,n._index++)),h.previous=q,c=!0}function I(q,ee){let re=ee||{};return re.type=q,re.start=v(),h.events.push(["enter",re,h]),u.push(re),re}function _(q){let ee=u.pop();return ee.end=v(),h.events.push(["exit",ee,h]),ee}function D(q,ee){P(q,ee.from)}function O(q,ee){ee.restore()}function M(q,ee){return re;function re(Ae,se,Ce){let yt,R,Ge,ut;return Array.isArray(Ae)?Xe(Ae):"tokenize"in Ae?Xe([Ae]):N(Ae);function N(De){return Nt;function Nt(xt){let He=xt!==null&&De[xt],Pt=xt!==null&&De.null,Kt=[...Array.isArray(He)?He:He?[He]:[],...Array.isArray(Pt)?Pt:Pt?[Pt]:[]];return Xe(Kt)(xt)}}function Xe(De){return yt=De,R=0,De.length===0?Ce:Wt(De[R])}function Wt(De){return Nt;function Nt(xt){return ut=J(),Ge=De,De.partial||(h.currentConstruct=De),De.name&&h.parser.constructs.disable.null.includes(De.name)?ct(xt):De.tokenize.call(ee?Object.assign(Object.create(h),ee):h,f,tn,ct)(xt)}}function tn(De){return c=!0,q(Ge,ut),se}function ct(De){return c=!0,ut.restore(),++R<yt.length?Wt(yt[R]):Ce}}}function P(q,ee){q.resolveAll&&!s.includes(q)&&s.push(q),q.resolve&&Je(h.events,ee,h.events.length-ee,q.resolve(h.events.slice(ee),h)),q.resolveTo&&(h.events=q.resolveTo(h.events,h))}function J(){let q=v(),ee=h.previous,re=h.currentConstruct,Ae=h.events.length,se=Array.from(u);return{restore:Ce,from:Ae};function Ce(){n=q,h.previous=ee,h.currentConstruct=re,h.events.length=Ae,u=se,V()}}function V(){n.line in i&&n.column<2&&(n.column=i[n.line],n.offset+=i[n.line]-1)}}function i2(e,t){let r=t.start._index,n=t.start._bufferIndex,i=t.end._index,s=t.end._bufferIndex,o;if(r===i)o=[e[r].slice(n,s)];else{if(o=e.slice(r,i),n>-1){let u=o[0];typeof u=="string"?o[0]=u.slice(n):o.shift()}s>0&&o.push(e[i].slice(0,s))}return o}function s2(e,t){let r=-1,n=[],i;for(;++r<e.length;){let s=e[r],o;if(typeof s=="string")o=s;else switch(s){case-5:{o="\r";break}case-4:{o=`+`;break}case-3:{o=`\r+`;break}case-2:{o=t?" ":" ";break}case-1:{if(!t&&i)continue;o=" ";break}default:o=String.fromCharCode(s)}i=s===-2,n.push(o)}return n.join("")}var Of={};Dp(Of,{attentionMarkers:()=>h2,contentInitial:()=>a2,disable:()=>d2,document:()=>o2,flow:()=>c2,flowInitial:()=>u2,insideSpan:()=>p2,string:()=>l2,text:()=>f2});var o2={42:ot,43:ot,45:ot,48:ot,49:ot,50:ot,51:ot,52:ot,53:ot,54:ot,55:ot,56:ot,57:ot,62:La},a2={91:bl},u2={[-2]:Hs,[-1]:Hs,32:Hs},c2={35:vl,42:qn,45:[qa,qn],60:Al,61:qa,95:qn,96:Ma,126:Ma},l2={38:Ba,92:za},f2={[-5]:Ws,[-4]:Ws,[-3]:Ws,33:El,38:Ba,42:Qs,60:[ml,Sl],91:_l,92:[wl,za],93:Un,95:Qs,96:yl},p2={null:[Qs,Vb]},h2={null:[42,95]},d2={null:[]};function Jb(e){let r=Ni([Of,...(e||{}).extensions||[]]),n={defined:[],lazy:{},constructs:r,content:i(Lb),document:i(Bb),flow:i(Mb),string:i($b),text:i(jb)};return n;function i(s){return o;function o(u){return Zb(n,s,u)}}}var Gb=/[\0\t\n\r]/g;function Qb(){let e=1,t="",r=!0,n;return i;function i(s,o,u){let c=[],f,h,p,m,d;for(s=t+s.toString(o),p=0,t="",r&&(s.charCodeAt(0)===65279&&p++,r=void 0);p<s.length;){if(Gb.lastIndex=p,f=Gb.exec(s),m=f&&f.index!==void 0?f.index:s.length,d=s.charCodeAt(m),!f){t=s.slice(p);break}if(d===10&&p===m&&n)c.push(-3),n=void 0;else switch(n&&(c.push(-5),n=void 0),p<m&&(c.push(s.slice(p,m)),e+=m-p),d){case 0:{c.push(65533),e++;break}case 9:{for(h=Math.ceil(e/4)*4,c.push(-2);e++<h;)c.push(-1);break}case 10:{c.push(-4),e=1;break}default:n=!0,e=1}p=m+1}return u&&(n&&c.push(-5),t&&c.push(t),c.push(null)),c}}function Hb(e){for(;!Va(e););return e}var Kb={}.hasOwnProperty,Ff=function(e,t,r){return typeof t!="string"&&(r=t,t=void 0),m2(r)(Hb(Jb(r).document().write(Qb()(e,t,!0))))};function m2(e){let t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:u(er),autolinkProtocol:J,autolinkEmail:J,atxHeading:u(Yt),blockQuote:u(He),characterEscape:J,characterReference:J,codeFenced:u(Pt),codeFencedFenceInfo:c,codeFencedFenceMeta:c,codeIndented:u(Pt,c),codeText:u(Kt,c),codeTextData:J,data:J,codeFlowValue:J,definition:u(Kn),definitionDestinationString:c,definitionLabelString:c,definitionTitleString:c,emphasis:u(Xt),hardBreakEscape:u(In),hardBreakTrailing:u(In),htmlFlow:u(br,c),htmlFlowData:J,htmlText:u(br,c),htmlTextData:J,image:u(Tn),label:c,link:u(er),listItem:u(St),listItemValue:x,listOrdered:u(Br,d),listUnordered:u(Br),paragraph:u(Mr),reference:Wt,referenceString:c,resourceDestinationString:c,resourceTitleString:c,setextHeading:u(Yt),strong:u(Ie),thematicBreak:u(Te)},exit:{atxHeading:h(),atxHeadingSequence:D,autolink:h(),autolinkEmail:xt,autolinkProtocol:Nt,blockQuote:h(),characterEscapeValue:V,characterReferenceMarkerHexadecimal:ct,characterReferenceMarkerNumeric:ct,characterReferenceValue:De,codeFenced:h(T),codeFencedFence:k,codeFencedFenceInfo:b,codeFencedFenceMeta:v,codeFlowValue:V,codeIndented:h(E),codeText:h(se),codeTextData:V,data:V,definition:h(),definitionDestinationString:_,definitionLabelString:g,definitionTitleString:I,emphasis:h(),hardBreakEscape:h(ee),hardBreakTrailing:h(ee),htmlFlow:h(re),htmlFlowData:V,htmlText:h(Ae),htmlTextData:V,image:h(yt),label:Ge,labelText:R,lineEnding:q,link:h(Ce),listItem:h(),listOrdered:h(),listUnordered:h(),paragraph:h(),referenceString:tn,resourceDestinationString:ut,resourceTitleString:N,resource:Xe,setextHeading:h(P),setextHeadingLineSequence:M,setextHeadingText:O,strong:h(),thematicBreak:h()}};Xb(t,(e||{}).mdastExtensions||[]);let r={};return n;function n(z){let S={type:"root",children:[]},ne={stack:[S],tokenStack:[],config:t,enter:f,exit:p,buffer:c,resume:m,setData:s,getData:o},ye=[],U=-1;for(;++U<z.length;)if(z[U][1].type==="listOrdered"||z[U][1].type==="listUnordered")if(z[U][0]==="enter")ye.push(U);else{let lt=ye.pop();U=i(z,lt,U)}for(U=-1;++U<z.length;){let lt=t[z[U][0]];Kb.call(lt,z[U][1].type)&<[z[U][1].type].call(Object.assign({sliceSerialize:z[U][2].sliceSerialize},ne),z[U][1])}if(ne.tokenStack.length>0){let lt=ne.tokenStack[ne.tokenStack.length-1];(lt[1]||Wb).call(ne,void 0,lt[0])}for(S.position={start:_n(z.length>0?z[0][1].start:{line:1,column:1,offset:0}),end:_n(z.length>0?z[z.length-2][1].end:{line:1,column:1,offset:0})},U=-1;++U<t.transforms.length;)S=t.transforms[U](S)||S;return S}function i(z,S,ne){let ye=S-1,U=-1,lt=!1,wr,tr,rr,Vr;for(;++ye<=ne;){let ze=z[ye];if(ze[1].type==="listUnordered"||ze[1].type==="listOrdered"||ze[1].type==="blockQuote"?(ze[0]==="enter"?U++:U--,Vr=void 0):ze[1].type==="lineEndingBlank"?ze[0]==="enter"&&(wr&&!Vr&&!U&&!rr&&(rr=ye),Vr=void 0):ze[1].type==="linePrefix"||ze[1].type==="listItemValue"||ze[1].type==="listItemMarker"||ze[1].type==="listItemPrefix"||ze[1].type==="listItemPrefixWhitespace"||(Vr=void 0),!U&&ze[0]==="enter"&&ze[1].type==="listItemPrefix"||U===-1&&ze[0]==="exit"&&(ze[1].type==="listUnordered"||ze[1].type==="listOrdered")){if(wr){let Yi=ye;for(tr=void 0;Yi--;){let bt=z[Yi];if(bt[1].type==="lineEnding"||bt[1].type==="lineEndingBlank"){if(bt[0]==="exit")continue;tr&&(z[tr][1].type="lineEndingBlank",lt=!0),bt[1].type="lineEnding",tr=Yi}else if(!(bt[1].type==="linePrefix"||bt[1].type==="blockQuotePrefix"||bt[1].type==="blockQuotePrefixWhitespace"||bt[1].type==="blockQuoteMarker"||bt[1].type==="listItemIndent"))break}rr&&(!tr||rr<tr)&&(wr._spread=!0),wr.end=Object.assign({},tr?z[tr][1].start:ze[1].end),z.splice(tr||ye,0,["exit",wr,ze[2]]),ye++,ne++}ze[1].type==="listItemPrefix"&&(wr={type:"listItem",_spread:!1,start:Object.assign({},ze[1].start),end:void 0},z.splice(ye,0,["enter",wr,ze[2]]),ye++,ne++,rr=void 0,Vr=!0)}}return z[S][1]._spread=lt,ne}function s(z,S){r[z]=S}function o(z){return r[z]}function u(z,S){return ne;function ne(ye){f.call(this,z(ye),ye),S&&S.call(this,ye)}}function c(){this.stack.push({type:"fragment",children:[]})}function f(z,S,ne){return this.stack[this.stack.length-1].children.push(z),this.stack.push(z),this.tokenStack.push([S,ne]),z.position={start:_n(S.start)},z}function h(z){return S;function S(ne){z&&z.call(this,ne),p.call(this,ne)}}function p(z,S){let ne=this.stack.pop(),ye=this.tokenStack.pop();if(ye)ye[0].type!==z.type&&(S?S.call(this,z,ye[0]):(ye[1]||Wb).call(this,z,ye[0]));else throw new Error("Cannot close `"+z.type+"` ("+Tt({start:z.start,end:z.end})+"): it\u2019s not open");return ne.position.end=_n(z.end),ne}function m(){return Pf(this.stack.pop())}function d(){s("expectingFirstListItemValue",!0)}function x(z){if(o("expectingFirstListItemValue")){let S=this.stack[this.stack.length-2];S.start=Number.parseInt(this.sliceSerialize(z),10),s("expectingFirstListItemValue")}}function b(){let z=this.resume(),S=this.stack[this.stack.length-1];S.lang=z}function v(){let z=this.resume(),S=this.stack[this.stack.length-1];S.meta=z}function k(){o("flowCodeInside")||(this.buffer(),s("flowCodeInside",!0))}function T(){let z=this.resume(),S=this.stack[this.stack.length-1];S.value=z.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),s("flowCodeInside")}function E(){let z=this.resume(),S=this.stack[this.stack.length-1];S.value=z.replace(/(\r?\n|\r)$/g,"")}function g(z){let S=this.resume(),ne=this.stack[this.stack.length-1];ne.label=S,ne.identifier=st(this.sliceSerialize(z)).toLowerCase()}function I(){let z=this.resume(),S=this.stack[this.stack.length-1];S.title=z}function _(){let z=this.resume(),S=this.stack[this.stack.length-1];S.url=z}function D(z){let S=this.stack[this.stack.length-1];if(!S.depth){let ne=this.sliceSerialize(z).length;S.depth=ne}}function O(){s("setextHeadingSlurpLineEnding",!0)}function M(z){let S=this.stack[this.stack.length-1];S.depth=this.sliceSerialize(z).charCodeAt(0)===61?1:2}function P(){s("setextHeadingSlurpLineEnding")}function J(z){let S=this.stack[this.stack.length-1],ne=S.children[S.children.length-1];(!ne||ne.type!=="text")&&(ne=Rn(),ne.position={start:_n(z.start)},S.children.push(ne)),this.stack.push(ne)}function V(z){let S=this.stack.pop();S.value+=this.sliceSerialize(z),S.position.end=_n(z.end)}function q(z){let S=this.stack[this.stack.length-1];if(o("atHardBreak")){let ne=S.children[S.children.length-1];ne.position.end=_n(z.end),s("atHardBreak");return}!o("setextHeadingSlurpLineEnding")&&t.canContainEols.includes(S.type)&&(J.call(this,z),V.call(this,z))}function ee(){s("atHardBreak",!0)}function re(){let z=this.resume(),S=this.stack[this.stack.length-1];S.value=z}function Ae(){let z=this.resume(),S=this.stack[this.stack.length-1];S.value=z}function se(){let z=this.resume(),S=this.stack[this.stack.length-1];S.value=z}function Ce(){let z=this.stack[this.stack.length-1];if(o("inReference")){let S=o("referenceType")||"shortcut";z.type+="Reference",z.referenceType=S,delete z.url,delete z.title}else delete z.identifier,delete z.label;s("referenceType")}function yt(){let z=this.stack[this.stack.length-1];if(o("inReference")){let S=o("referenceType")||"shortcut";z.type+="Reference",z.referenceType=S,delete z.url,delete z.title}else delete z.identifier,delete z.label;s("referenceType")}function R(z){let S=this.sliceSerialize(z),ne=this.stack[this.stack.length-2];ne.label=Qa(S),ne.identifier=st(S).toLowerCase()}function Ge(){let z=this.stack[this.stack.length-1],S=this.resume(),ne=this.stack[this.stack.length-1];if(s("inReference",!0),ne.type==="link"){let ye=z.children;ne.children=ye}else ne.alt=S}function ut(){let z=this.resume(),S=this.stack[this.stack.length-1];S.url=z}function N(){let z=this.resume(),S=this.stack[this.stack.length-1];S.title=z}function Xe(){s("inReference")}function Wt(){s("referenceType","collapsed")}function tn(z){let S=this.resume(),ne=this.stack[this.stack.length-1];ne.label=S,ne.identifier=st(this.sliceSerialize(z)).toLowerCase(),s("referenceType","full")}function ct(z){s("characterReferenceType",z.type)}function De(z){let S=this.sliceSerialize(z),ne=o("characterReferenceType"),ye;ne?(ye=Ga(S,ne==="characterReferenceMarkerNumeric"?10:16),s("characterReferenceType")):ye=Wr(S);let U=this.stack.pop();U.value+=ye,U.position.end=_n(z.end)}function Nt(z){V.call(this,z);let S=this.stack[this.stack.length-1];S.url=this.sliceSerialize(z)}function xt(z){V.call(this,z);let S=this.stack[this.stack.length-1];S.url="mailto:"+this.sliceSerialize(z)}function He(){return{type:"blockquote",children:[]}}function Pt(){return{type:"code",lang:null,meta:null,value:""}}function Kt(){return{type:"inlineCode",value:""}}function Kn(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function Xt(){return{type:"emphasis",children:[]}}function Yt(){return{type:"heading",depth:void 0,children:[]}}function In(){return{type:"break"}}function br(){return{type:"html",value:""}}function Tn(){return{type:"image",title:null,url:"",alt:null}}function er(){return{type:"link",title:null,url:"",children:[]}}function Br(z){return{type:"list",ordered:z.type==="listOrdered",start:null,spread:z._spread,children:[]}}function St(z){return{type:"listItem",spread:z._spread,checked:null,children:[]}}function Mr(){return{type:"paragraph",children:[]}}function Ie(){return{type:"strong",children:[]}}function Rn(){return{type:"text",value:""}}function Te(){return{type:"thematicBreak"}}}function _n(e){return{line:e.line,column:e.column,offset:e.offset}}function Xb(e,t){let r=-1;for(;++r<t.length;){let n=t[r];Array.isArray(n)?Xb(e,n):g2(e,n)}}function g2(e,t){let r;for(r in t)if(Kb.call(t,r)){if(r==="canContainEols"){let n=t[r];n&&e[r].push(...n)}else if(r==="transforms"){let n=t[r];n&&e[r].push(...n)}else if(r==="enter"||r==="exit"){let n=t[r];n&&Object.assign(e[r],n)}}}function Wb(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+Tt({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+Tt({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+Tt({start:t.start,end:t.end})+") is still open")}function hu(e){Object.assign(this,{Parser:r=>{let n=this.data("settings");return Ff(r,Object.assign({},n,e,{extensions:this.data("micromarkExtensions")||[],mdastExtensions:this.data("fromMarkdownExtensions")||[]}))}})}function Lf(e){if(e)throw e}var y1=ns(zf(),1),qf=ns(u1(),1);function ro(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function c1(){let e=[],t={run:r,use:n};return t;function r(...i){let s=-1,o=i.pop();if(typeof o!="function")throw new TypeError("Expected function as last argument, not "+o);u(null,...i);function u(c,...f){let h=e[++s],p=-1;if(c){o(c);return}for(;++p<i.length;)(f[p]===null||f[p]===void 0)&&(f[p]=i[p]);i=f,h?y2(h,u)(...f):o(null,...f)}}function n(i){if(typeof i!="function")throw new TypeError("Expected `middelware` to be a function, not "+i);return e.push(i),t}}function y2(e,t){let r;return n;function n(...o){let u=e.length>o.length,c;u&&o.push(i);try{c=e.apply(this,o)}catch(f){let h=f;if(u&&r)throw h;return i(h)}u||(c instanceof Promise?c.then(s,i):c instanceof Error?i(c):s(c))}function i(o,...u){r||(r=!0,t(o,...u))}function s(o){i(null,o)}}var h1=ns(zf(),1);var yr={basename:x2,dirname:b2,extname:w2,join:v2,sep:"/"};function x2(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');no(e);let r=0,n=-1,i=e.length,s;if(t===void 0||t.length===0||t.length>e.length){for(;i--;)if(e.charCodeAt(i)===47){if(s){r=i+1;break}}else n<0&&(s=!0,n=i+1);return n<0?"":e.slice(r,n)}if(t===e)return"";let o=-1,u=t.length-1;for(;i--;)if(e.charCodeAt(i)===47){if(s){r=i+1;break}}else o<0&&(s=!0,o=i+1),u>-1&&(e.charCodeAt(i)===t.charCodeAt(u--)?u<0&&(n=i):(u=-1,n=o));return r===n?n=o:n<0&&(n=e.length),e.slice(r,n)}function b2(e){if(no(e),e.length===0)return".";let t=-1,r=e.length,n;for(;--r;)if(e.charCodeAt(r)===47){if(n){t=r;break}}else n||(n=!0);return t<0?e.charCodeAt(0)===47?"/":".":t===1&&e.charCodeAt(0)===47?"//":e.slice(0,t)}function w2(e){no(e);let t=e.length,r=-1,n=0,i=-1,s=0,o;for(;t--;){let u=e.charCodeAt(t);if(u===47){if(o){n=t+1;break}continue}r<0&&(o=!0,r=t+1),u===46?i<0?i=t:s!==1&&(s=1):i>-1&&(s=-1)}return i<0||r<0||s===0||s===1&&i===r-1&&i===n+1?"":e.slice(i,r)}function v2(...e){let t=-1,r;for(;++t<e.length;)no(e[t]),e[t]&&(r=r===void 0?e[t]:r+"/"+e[t]);return r===void 0?".":k2(r)}function k2(e){no(e);let t=e.charCodeAt(0)===47,r=A2(e,!t);return r.length===0&&!t&&(r="."),r.length>0&&e.charCodeAt(e.length-1)===47&&(r+="/"),t?"/"+r:r}function A2(e,t){let r="",n=0,i=-1,s=0,o=-1,u,c;for(;++o<=e.length;){if(o<e.length)u=e.charCodeAt(o);else{if(u===47)break;u=47}if(u===47){if(!(i===o-1||s===1))if(i!==o-1&&s===2){if(r.length<2||n!==2||r.charCodeAt(r.length-1)!==46||r.charCodeAt(r.length-2)!==46){if(r.length>2){if(c=r.lastIndexOf("/"),c!==r.length-1){c<0?(r="",n=0):(r=r.slice(0,c),n=r.length-1-r.lastIndexOf("/")),i=o,s=0;continue}}else if(r.length>0){r="",n=0,i=o,s=0;continue}}t&&(r=r.length>0?r+"/..":"..",n=2)}else r.length>0?r+="/"+e.slice(i+1,o):r=e.slice(i+1,o),n=o-i-1;i=o,s=0}else u===46&&s>-1?s++:s=-1}return r}function no(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}var l1={cwd:S2};function S2(){return"/"}function Ui(e){return e!==null&&typeof e=="object"&&e.href&&e.origin}function f1(e){if(typeof e=="string")e=new URL(e);else if(!Ui(e)){let t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){let t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return E2(e)}function E2(e){if(e.hostname!==""){let n=new TypeError('File URL host must be "localhost" or empty on darwin');throw n.code="ERR_INVALID_FILE_URL_HOST",n}let t=e.pathname,r=-1;for(;++r<t.length;)if(t.charCodeAt(r)===37&&t.charCodeAt(r+1)===50){let n=t.charCodeAt(r+2);if(n===70||n===102){let i=new TypeError("File URL path must not include encoded / characters");throw i.code="ERR_INVALID_FILE_URL_PATH",i}}return decodeURIComponent(t)}var Bf=["history","path","basename","stem","extname","dirname"],io=class{constructor(t){let r;t?typeof t=="string"||(0,h1.default)(t)?r={value:t}:Ui(t)?r={path:t}:r=t:r={},this.data={},this.messages=[],this.history=[],this.cwd=l1.cwd(),this.value,this.stored,this.result,this.map;let n=-1;for(;++n<Bf.length;){let s=Bf[n];s in r&&r[s]!==void 0&&(this[s]=s==="history"?[...r[s]]:r[s])}let i;for(i in r)Bf.includes(i)||(this[i]=r[i])}get path(){return this.history[this.history.length-1]}set path(t){Ui(t)&&(t=f1(t)),Vf(t,"path"),this.path!==t&&this.history.push(t)}get dirname(){return typeof this.path=="string"?yr.dirname(this.path):void 0}set dirname(t){p1(this.basename,"dirname"),this.path=yr.join(t||"",this.basename)}get basename(){return typeof this.path=="string"?yr.basename(this.path):void 0}set basename(t){Vf(t,"basename"),Mf(t,"basename"),this.path=yr.join(this.dirname||"",t)}get extname(){return typeof this.path=="string"?yr.extname(this.path):void 0}set extname(t){if(Mf(t,"extname"),p1(this.dirname,"extname"),t){if(t.charCodeAt(0)!==46)throw new Error("`extname` must start with `.`");if(t.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=yr.join(this.dirname,this.stem+(t||""))}get stem(){return typeof this.path=="string"?yr.basename(this.path,this.extname):void 0}set stem(t){Vf(t,"stem"),Mf(t,"stem"),this.path=yr.join(this.dirname||"",t+(this.extname||""))}toString(t){return(this.value||"").toString(t)}message(t,r,n){let i=new me(t,r,n);return this.path&&(i.name=this.path+":"+i.name,i.file=this.path),i.fatal=!1,this.messages.push(i),i}info(t,r,n){let i=this.message(t,r,n);return i.fatal=null,i}fail(t,r,n){let i=this.message(t,r,n);throw i.fatal=!0,i}};function Mf(e,t){if(e&&e.includes(yr.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+yr.sep+"`")}function Vf(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function p1(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}var Zf=b1().freeze(),x1={}.hasOwnProperty;function b1(){let e=c1(),t=[],r={},n,i=-1;return s.data=o,s.Parser=void 0,s.Compiler=void 0,s.freeze=u,s.attachers=t,s.use=c,s.parse=f,s.stringify=h,s.run=p,s.runSync=m,s.process=d,s.processSync=x,s;function s(){let b=b1(),v=-1;for(;++v<t.length;)b.use(...t[v]);return b.data((0,qf.default)(!0,{},r)),b}function o(b,v){return typeof b=="string"?arguments.length===2?(Uf("data",n),r[b]=v,s):x1.call(r,b)&&r[b]||null:b?(Uf("data",n),r=b,s):r}function u(){if(n)return s;for(;++i<t.length;){let[b,...v]=t[i];if(v[0]===!1)continue;v[0]===!0&&(v[0]=void 0);let k=b.call(s,...v);typeof k=="function"&&e.use(k)}return n=!0,i=Number.POSITIVE_INFINITY,s}function c(b,...v){let k;if(Uf("use",n),b!=null)if(typeof b=="function")I(b,...v);else if(typeof b=="object")Array.isArray(b)?g(b):E(b);else throw new TypeError("Expected usable value, not `"+b+"`");return k&&(r.settings=Object.assign(r.settings||{},k)),s;function T(_){if(typeof _=="function")I(_);else if(typeof _=="object")if(Array.isArray(_)){let[D,...O]=_;I(D,...O)}else E(_);else throw new TypeError("Expected usable value, not `"+_+"`")}function E(_){g(_.plugins),_.settings&&(k=Object.assign(k||{},_.settings))}function g(_){let D=-1;if(_!=null)if(Array.isArray(_))for(;++D<_.length;){let O=_[D];T(O)}else throw new TypeError("Expected a list of plugins, not `"+_+"`")}function I(_,D){let O=-1,M;for(;++O<t.length;)if(t[O][0]===_){M=t[O];break}M?(ro(M[1])&&ro(D)&&(D=(0,qf.default)(!0,M[1],D)),M[1]=D):t.push([...arguments])}}function f(b){s.freeze();let v=so(b),k=s.Parser;return $f("parse",k),d1(k,"parse")?new k(String(v),v).parse():k(String(v),v)}function h(b,v){s.freeze();let k=so(v),T=s.Compiler;return jf("stringify",T),m1(b),d1(T,"compile")?new T(b,k).compile():T(b,k)}function p(b,v,k){if(m1(b),s.freeze(),!k&&typeof v=="function"&&(k=v,v=void 0),!k)return new Promise(T);T(null,k);function T(E,g){e.run(b,so(v),I);function I(_,D,O){D=D||b,_?g(_):E?E(D):k(null,D,O)}}}function m(b,v){let k,T;return s.run(b,v,E),g1("runSync","run",T),k;function E(g,I){Lf(g),k=I,T=!0}}function d(b,v){if(s.freeze(),$f("process",s.Parser),jf("process",s.Compiler),!v)return new Promise(k);k(null,v);function k(T,E){let g=so(b);s.run(s.parse(g),g,(_,D,O)=>{if(_||!D||!O)I(_);else{let M=s.stringify(D,O);M==null||(D2(M)?O.value=M:O.result=M),I(_,O)}});function I(_,D){_||!D?E(_):T?T(D):v(null,D)}}}function x(b){let v;s.freeze(),$f("processSync",s.Parser),jf("processSync",s.Compiler);let k=so(b);return s.process(k,T),g1("processSync","process",v),k;function T(E){v=!0,Lf(E)}}}function d1(e,t){return typeof e=="function"&&e.prototype&&(_2(e.prototype)||t in e.prototype)}function _2(e){let t;for(t in e)if(x1.call(e,t))return!0;return!1}function $f(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `Parser`")}function jf(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `Compiler`")}function Uf(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function m1(e){if(!ro(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function g1(e,t,r){if(!r)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function so(e){return C2(e)?e:new io(e)}function C2(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function D2(e){return typeof e=="string"||(0,y1.default)(e)}var Cn=e=>typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string",oo=e=>Array.isArray(e.children)===!1?[]:e.children.filter(Cn),w1=()=>Zf().use(hu).use(fl,["yaml"]).use(Xl),I2=w1(),T2={acornOptions:{ecmaVersion:"latest",sourceType:"module"}},R2=w1().use(Nf,T2),v1=(e,t="markdown")=>(t==="mdx"?R2:I2).parse(e);var zr=class extends Error{code;nodeType;reason;sourceRange;constructor({code:t,message:r,nodeType:n,reason:i,sourceRange:s,cause:o}){super(r,{cause:o}),this.name="MdxDocumentError",this.code=t,this.nodeType=n,this.reason=i,this.sourceRange=s}},Ht=e=>typeof e=="object"&&e!==null,k1=e=>{if(Ht(e)===!1||typeof e.line!="number"||typeof e.column!="number"||Number.isInteger(e.line)===!1||Number.isInteger(e.column)===!1||e.line<1||e.column<1)return;let t={line:e.line,column:e.column};return typeof e.offset=="number"&&Number.isInteger(e.offset)&&e.offset>=0&&(t.offset=e.offset),t},Qt=e=>{if(Ht(e)===!1)return;let t=k1(e.start),r=k1(e.end);if(t!==void 0&&r!==void 0)return{start:t,end:r}},N2=e=>{if(Ht(e)===!1)return;let t=Qt(e.position);if(t!==void 0)return t;if(typeof e.name!="string")return;let[r,n]=e.name.split(":",2),i=Number(r),s=Number(n);if(Number.isInteger(i)===!1||Number.isInteger(s)===!1||i<1||s<1)return;let o={line:i,column:s};return{start:o,end:o}},_1=e=>e instanceof Error?e.message:String(e),Ve=(e,t,r)=>{throw new zr({code:"unsafe-mdx",message:t,nodeType:e.type,reason:t,sourceRange:Qt(e.position)??Qt(r?.position)})},C1=new Set(["base","link","meta","noscript","script","style","template","title"]),P2=new Set(["action","cite","data","formaction","href","poster","src","xlink:href","xlinkhref"]),O2=(e,t)=>{let r;try{r=new URL(e,"https://webstudio.invalid")}catch{return!1}return r.protocol==="http:"||r.protocol==="https:"?!0:t==="href"&&(r.protocol==="mailto:"||r.protocol==="tel:")},F2=(e,t)=>{let r=t.name.toLowerCase();(r.startsWith("on")||r==="srcdoc"||r==="dangerouslysetinnerhtml"||r==="srcset")&&Ve(e,`MDX JSX prop ${t.name} is not supported`),P2.has(r)&&typeof t.value=="string"&&O2(t.value,r)===!1&&Ve(e,`MDX JSX prop ${t.name} contains an unsafe URL`)},L2=e=>{let t=[{node:e,depth:0}],r=0,n=0;for(;t.length>0;){let i=t.pop();if(i===void 0)break;if(r+=1,r>Q.mdxNodes)throw new zr({code:"invalid-mdx",message:"MDX content exceeds the node limit",sourceRange:Qt(i.node.position)});if(i.depth>Q.mdxDepth)throw new zr({code:"invalid-mdx",message:"MDX content exceeds the nesting limit",sourceRange:Qt(i.node.position)});if(Array.isArray(i.node.attributes)&&(n+=i.node.attributes.length,n>Q.mdxProps))throw new zr({code:"invalid-mdx",message:"MDX content exceeds the prop limit",sourceRange:Qt(i.node.position)});for(let s of oo(i.node))t.push({node:s,depth:i.depth+1})}},D1=({node:e,tag:t,props:r=[],children:n,mdxMode:i,markdownListItem:s,preserveTextWhitespace:o})=>{let u=Qt(e.position);return i!==void 0?{type:"element",syntax:"mdx",tag:t,props:r,children:n,mdxMode:i,sourceRange:u}:{type:"element",syntax:"markdown",tag:t,props:r,children:n,...s===void 0?{}:{markdownListItem:s},...o===void 0?{}:{preserveTextWhitespace:o},sourceRange:u}},I1=e=>e.type==="mdxJsxTextElement"||e.type==="mdxTextExpression"?"text":"flow",Qf=(e,t)=>{e.data={...Ht(e.data)?e.data:{},...t}},z2=e=>{if(Ht(e.data)===!1||Ht(e.data.estree)===!1)return!1;let{body:t,comments:r}=e.data.estree;return Array.isArray(t)&&t.length===0&&Array.isArray(r)&&r.length>0},B2=e=>{if(Array.isArray(e.attributes)===!1)return[];let t=[],r=new Set;for(let n of e.attributes)Cn(n)===!1&&Ve(e,"MDX JSX contains an invalid attribute"),n.type==="mdxJsxExpressionAttribute"&&Ve(n,"MDX JSX attribute spreads are not supported",e),(n.type!=="mdxJsxAttribute"||typeof n.name!="string")&&Ve(n,"MDX JSX contains an unsupported attribute",e),r.has(n.name)&&Ve(n,"MDX JSX attributes must be unique",e),r.add(n.name),Ht(n.value)&&Ve(n.value.type==="mdxJsxAttributeValueExpression"?n.value:n,"MDX JSX attribute expressions are not supported",e),n.value!==null&&typeof n.value!="string"&&Ve(n,"MDX JSX attribute values must be static",e),t.push({name:n.name,value:n.value===null?!0:n.value});return t},A1=(e,t)=>{let r=t;if(z2(r)&&typeof r.value=="string"){let n={type:"comment",value:r.value,data:{mdxMode:I1(r)}};return e.patch(t,n),n}return Ve(r,"Executable MDX expressions are not supported")},S1=(e,t)=>{let r=t;if(r.name!=="ws.element")return Ve(r,"Only the ws.element component is supported in authored MDX");let n=Object.fromEntries(B2(r).map(s=>[s.name,s.value])),i=e(t,"ws.element",n,e.all(t));return Cn(i)&&Qf(i,{mdxMode:I1(r)}),i},M2=(e,t,r)=>{let n=t,i=vn.listItem(e,t,r);return Cn(i)&&Qf(i,{markdownListItem:{...typeof n.checked=="boolean"?{checked:n.checked}:{},spread:n.spread===!0||Cn(r)&&r.spread===!0}}),i},E1=e=>(t,r,n)=>{let i=e(t,r,n);return Cn(i)&&Qf(i,{preserveTextWhitespace:!0}),i},V2=(e,t)=>{let r=oo(t);return r.length===1&&r[0].type==="mdxJsxTextElement"?e.one(t.children[0],t):vn.paragraph(e,t)},Jf=(e,t)=>{let r=t;return Ve(r,`MDX node type ${r.type} is not supported`)},$2={code:E1(vn.code),html:Jf,inlineCode:E1(vn.inlineCode),mdxFlowExpression:A1,mdxJsxFlowElement:S1,mdxJsxTextElement:S1,mdxTextExpression:A1,mdxjsEsm:Jf,listItem:M2,paragraph:V2};var T1=e=>{if(Ht(e.data)&&(e.data.mdxMode==="flow"||e.data.mdxMode==="text"))return e.data.mdxMode},R1=(e,t)=>e instanceof zr&&e.code==="unsafe-mdx"&&t.shouldOmitUnsafePart?.(e)===!0,j2=(e,t)=>{if(e.properties===void 0)return{props:[],requiresMdxFallback:!1};if(Ht(e.properties)===!1)return Ve(e,"HTML properties must be an object");let r=[],n=new Set,i=!1;for(let[s,o]of Object.entries(e.properties))try{if(o==null||o===!1)continue;let u;if(o===!0)u=!0;else if(typeof o=="string"||typeof o=="number")u=String(o);else if(Array.isArray(o)&&o.every(h=>typeof h=="string"||typeof h=="number"))u=o.join(" ");else return Ve(e,`HTML property ${s} is invalid`);let c=s==="className"?"class":s;if(n.has(c))return Ve(e,"HTML properties must be unique");let f={name:c,value:u};F2(e,f),n.add(c),r.push(f)}catch(u){if(R1(u,t)){i||=e.tagName==="a"&&s==="href"||e.tagName==="img"&&s==="src";continue}throw u}return{props:r,requiresMdxFallback:i}},mu=(e,t={})=>{let r=[];for(let n of oo(e))if(!(n.position===void 0&&n.type==="text"&&n.value===`+`))try{r.push(J2(n,t))}catch(i){if(R1(i,t))continue;throw i}return r},Gf=e=>{let t=T1(e);return t!==void 0?t:Ve(e,"MDX node mode is missing")},U2=e=>{if(Ht(e.data)===!1)return;let t=e.data.markdownListItem;if(!(Ht(t)===!1||typeof t.spread!="boolean"||t.checked!==void 0&&typeof t.checked!="boolean"))return{...typeof t.checked=="boolean"?{checked:t.checked}:{},spread:t.spread}},q2=e=>Ht(e.data)&&e.data.preserveTextWhitespace===!0?!0:void 0,Z2=(e,t,r)=>{let n=t.find(o=>o.name==="ws:name"),i=t.find(o=>o.name==="ws:tag");if(n!==void 0&&i!==void 0)return Ve(e,"ws:name and ws:tag cannot be used together");if(n!==void 0)return typeof n.value!="string"||n.value.length===0?Ve(e,"ws:name must be a non-empty static string"):{type:"template",name:n.value,props:t.filter(o=>o.name!=="ws:name"),children:mu(e,r),mdxMode:Gf(e),sourceRange:Qt(e.position)};let s="div";if(i!==void 0){if(typeof i.value!="string"||i.value.length===0)return Ve(e,"ws:tag must be a non-empty static string");s=i.value}return C1.has(s.toLowerCase())?Ve(e,`Webstudio element tag ${s} is not supported`):D1({node:e,tag:s,props:t.filter(o=>o.name!=="ws:tag"),children:mu(e,r),mdxMode:Gf(e)})},J2=(e,t)=>{if(e.type==="text")return typeof e.value!="string"?Ve(e,"HTML text must contain a string value"):{type:"text",value:e.value,sourceRange:Qt(e.position)};if(e.type==="comment")return typeof e.value!="string"?Ve(e,"HTML comments must contain a string value"):{type:"comment",value:e.value,mdxMode:Gf(e),sourceRange:Qt(e.position)};if(e.type!=="element"||typeof e.tagName!="string")return Ve(e,`HTML node type ${e.type} is not supported`);let r=T1(e);if(e.tagName!=="ws.element"&&r!==void 0&&C1.has(e.tagName.toLowerCase()))return Ve(e,`Webstudio element tag ${e.tagName} is not supported`);let{props:n,requiresMdxFallback:i}=j2(e,t);if(e.tagName==="ws.element")return Z2(e,n,t);let s=r??(i?"text":void 0),o=mu(e,t),u=o.length===1?o[0]:void 0;return s===void 0&&e.tagName==="p"&&u!==void 0&&(u.type==="element"&&u.syntax==="mdx"&&u.mdxMode==="text"||u.type==="template"&&u.mdxMode==="text"||u.type==="comment"&&u.mdxMode==="text")&&(s="flow"),D1({node:e,tag:e.tagName,props:n,children:o,mdxMode:s,markdownListItem:U2(e),preserveTextWhitespace:q2(e)})},G2=e=>{let t=rl(e,{handlers:$2,unknownHandler:Jf});return Cn(t)===!1||t.type!=="root"?Ve(e,"MDX did not produce an HTML document"):mu(t)},Q2=({source:e,maximumBytes:t})=>{if(Number.isInteger(t)===!1||t<=0||t>Q.hydratedFileBytes||Mt(e)>t)throw new zr({code:"invalid-mdx",message:"MDX content exceeds the byte limit"})},H2=async(e,t)=>{let r=oo(e).find(n=>n.type==="yaml");try{return{properties:(await ka(t)).properties,sourceRange:Qt(r?.position)}}catch(n){throw new zr({code:"invalid-mdx",message:_1(n),sourceRange:Qt(r?.position),cause:n})}};var N1=async({source:e,maximumBytes:t=Q.hydratedFileBytes})=>{Q2({source:e,maximumBytes:t});let r;try{r=v1(e,"mdx")}catch(n){throw new zr({code:"invalid-mdx",message:_1(n),sourceRange:N2(n),cause:n})}return L2(r),{frontmatter:await H2(r,e),children:G2(r)}};var P1=({source:e,body:t,frontmatter:r})=>({source:e,body:t,frontmatter:r}),O1=({markdown:e,authored:t})=>Object.freeze({...e,authored:t}),K2=async(e,t)=>O1({markdown:e,authored:await N1({source:e.source,maximumBytes:t})}),F1=async({source:e,maximumBytes:t=Q.hydratedFileBytes})=>K2(await _a({source:e,maximumBytes:t}),t);var L1=({document:e,references:t,allowUnresolvedReferences:r})=>O1({markdown:Ca({document:P1(e),references:t,allowUnresolvedReferences:r}),authored:e.authored}),z1=({document:e,representation:t})=>Da({document:P1(e),representation:t});var B1=e=>{let t=e.format==="json"?e.value:e.value.frontmatter;return gi(t)?t:void 0},qi=e=>Object.freeze(e),M1=async({format:e,source:t,maximumBytes:r=Q.hydratedFileBytes})=>qi(e==="json"?{format:e,value:await ey({source:t,maximumBytes:r})}:e==="markdown"?{format:e,value:await _a({source:t,maximumBytes:r})}:{format:e,value:await F1({source:t,maximumBytes:r})});var V1=({document:e,references:t,allowUnresolvedReferences:r})=>e.format==="json"?qi({format:e.format,value:Vo({document:e.value,references:t,allowUnresolvedReferences:r})}):e.format==="markdown"?qi({format:e.format,value:Ca({document:e.value,references:t,allowUnresolvedReferences:r})}):qi({format:e.format,value:L1({document:e.value,references:t,allowUnresolvedReferences:r})}),$1=({document:e,representation:t})=>e.format==="json"?ty({document:e.value,representation:t}):e.format==="markdown"?Da({document:e.value,representation:t}):z1({document:e.value,representation:t});var gu=class extends Error{code;documentId;expectedRevision;actualRevision;expectedFormat;actualFormat;constructor({code:t,documentId:r,expectedRevision:n,actualRevision:i,expectedFormat:s,actualFormat:o}){super(`Document ${r} source ${t==="REVISION_MISMATCH"?"revision":"format"} does not match its graph`),this.name="DocumentSourceError",this.code=t,this.documentId=r,this.expectedRevision=n,this.actualRevision=i,this.expectedFormat=s,this.actualFormat=o}},Zi=({node:e,source:t})=>{if(t.revision!==e.revision)throw new gu({code:"REVISION_MISMATCH",documentId:e.id,expectedRevision:e.revision,actualRevision:t.revision});if(e.format!==void 0&&t.format!==e.format)throw new gu({code:"FORMAT_MISMATCH",documentId:e.id,expectedFormat:e.format,actualFormat:t.format});return t};var Ji=e=>{if(typeof e=="object"&&e!==null){let t=Reflect.get(e,"code");if(typeof t=="string"&&t.length>0)return t;let r=Reflect.get(e,"name");if(typeof r=="string"&&r.length>0)return r}return"UNKNOWN"},mt=(e,t)=>{try{e?.(t)}catch{}},j1=({load:e,onEvent:t})=>async(r,n)=>{let i={documentId:r.id,revision:r.revision};mt(t,{type:"document-fetch-started",...i});try{let s=await e(r,n);return mt(t,{type:"document-fetch-completed",...i}),s}catch(s){throw mt(t,{type:"document-fetch-failed",...i,errorCode:Ji(s)}),s}};var X2=le({format:wt(xs),revision:G().min(1)}),Gi=class extends Error{code;documentId;status;constructor({code:t,message:r,documentId:n,status:i,cause:s}){super(r,{cause:s}),this.name="HttpDocumentLoaderError",this.code=t,this.documentId=n,this.status=i}},U1=({fetch:e,getRequest:t,getMetadata:r,onEvent:n})=>j1({load:async(s,{signal:o})=>{let u;try{u=await e(t(s),{signal:o})}catch(h){throw new Gi({code:"REQUEST_FAILED",message:`Document ${s.id} request failed`,documentId:s.id,cause:h})}if(u.ok===!1)throw new Gi({code:"HTTP_STATUS",message:`Document ${s.id} request returned status ${u.status}`,documentId:s.id,status:u.status});let c;try{c=X2.parse(r({node:s,response:u}))}catch(h){throw new Gi({code:"INVALID_METADATA",message:`Document ${s.id} response metadata is invalid`,documentId:s.id,cause:h})}let f=u.body;if(f===null)throw new Gi({code:"BODY_MISSING",message:`Document ${s.id} response body is unavailable`,documentId:s.id});return Object.freeze({...c,source:Ig(f)})},onEvent:n});var Qi=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Z1=new Set,Hf=typeof process=="object"&&process?process:{},J1=(e,t,r,n)=>{typeof Hf.emitWarning=="function"?Hf.emitWarning(e,t,r,n):console.error(`[${r}] ${t}: ${e}`)},yu=globalThis.AbortController,q1=globalThis.AbortSignal;if(typeof yu>"u"){q1=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,i){this._onabort.push(i)}},yu=class{constructor(){t()}signal=new q1;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let i of this.signal._onabort)i(n);this.signal.onabort?.(n)}}};let e=Hf.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{e&&(e=!1,J1("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}var Y2=e=>!Z1.has(e),p7=Symbol("type"),Dn=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),G1=e=>Dn(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?Hi:null:null,Hi=class extends Array{constructor(t){super(t),this.fill(0)}},Wf=class e{heap;length;static#u=!1;static create(t){let r=G1(t);if(!r)return[];e.#u=!0;let n=new e(t,r);return e.#u=!1,n}constructor(t,r){if(!e.#u)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new r(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},Wi=class e{#u;#f;#m;#g;#T;#R;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#y;#n;#r;#e;#c;#p;#a;#s;#x;#o;#b;#w;#h;#v;#_;#l;static unsafeExposeInternals(t){return{starts:t.#w,ttls:t.#h,sizes:t.#b,keyMap:t.#n,keyList:t.#r,valList:t.#e,next:t.#c,prev:t.#p,get head(){return t.#a},get tail(){return t.#s},free:t.#x,isBackgroundFetch:r=>t.#t(r),backgroundFetch:(r,n,i,s)=>t.#O(r,n,i,s),moveToTail:r=>t.#I(r),indexes:r=>t.#k(r),rindexes:r=>t.#A(r),isStale:r=>t.#d(r)}}get max(){return this.#u}get maxSize(){return this.#f}get calculatedSize(){return this.#y}get size(){return this.#i}get fetchMethod(){return this.#T}get memoMethod(){return this.#R}get dispose(){return this.#m}get disposeAfter(){return this.#g}constructor(t){let{max:r=0,ttl:n,ttlResolution:i=1,ttlAutopurge:s,updateAgeOnGet:o,updateAgeOnHas:u,allowStale:c,dispose:f,disposeAfter:h,noDisposeOnSet:p,noUpdateTTL:m,maxSize:d=0,maxEntrySize:x=0,sizeCalculation:b,fetchMethod:v,memoMethod:k,noDeleteOnFetchRejection:T,noDeleteOnStaleGet:E,allowStaleOnFetchRejection:g,allowStaleOnFetchAbort:I,ignoreFetchAbort:_}=t;if(r!==0&&!Dn(r))throw new TypeError("max option must be a nonnegative integer");let D=r?G1(r):Array;if(!D)throw new Error("invalid max value: "+r);if(this.#u=r,this.#f=d,this.maxEntrySize=x||this.#f,this.sizeCalculation=b,this.sizeCalculation){if(!this.#f&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(k!==void 0&&typeof k!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#R=k,v!==void 0&&typeof v!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#T=v,this.#_=!!v,this.#n=new Map,this.#r=new Array(r).fill(void 0),this.#e=new Array(r).fill(void 0),this.#c=new D(r),this.#p=new D(r),this.#a=0,this.#s=0,this.#x=Wf.create(r),this.#i=0,this.#y=0,typeof f=="function"&&(this.#m=f),typeof h=="function"?(this.#g=h,this.#o=[]):(this.#g=void 0,this.#o=void 0),this.#v=!!this.#m,this.#l=!!this.#g,this.noDisposeOnSet=!!p,this.noUpdateTTL=!!m,this.noDeleteOnFetchRejection=!!T,this.allowStaleOnFetchRejection=!!g,this.allowStaleOnFetchAbort=!!I,this.ignoreFetchAbort=!!_,this.maxEntrySize!==0){if(this.#f!==0&&!Dn(this.#f))throw new TypeError("maxSize must be a positive integer if specified");if(!Dn(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#$()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!E,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!u,this.ttlResolution=Dn(i)||i===0?i:1,this.ttlAutopurge=!!s,this.ttl=n||0,this.ttl){if(!Dn(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#F()}if(this.#u===0&&this.ttl===0&&this.#f===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#u&&!this.#f){let O="LRU_CACHE_UNBOUNDED";Y2(O)&&(Z1.add(O),J1("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",O,e))}}getRemainingTTL(t){return this.#n.has(t)?1/0:0}#F(){let t=new Hi(this.#u),r=new Hi(this.#u);this.#h=t,this.#w=r,this.#L=(s,o,u=Qi.now())=>{if(r[s]=o!==0?u:0,t[s]=o,o!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#d(s)&&this.#S(this.#r[s],"expire")},o+1);c.unref&&c.unref()}},this.#C=s=>{r[s]=t[s]!==0?Qi.now():0},this.#E=(s,o)=>{if(t[o]){let u=t[o],c=r[o];if(!u||!c)return;s.ttl=u,s.start=c,s.now=n||i();let f=s.now-c;s.remainingTTL=u-f}};let n=0,i=()=>{let s=Qi.now();if(this.ttlResolution>0){n=s;let o=setTimeout(()=>n=0,this.ttlResolution);o.unref&&o.unref()}return s};this.getRemainingTTL=s=>{let o=this.#n.get(s);if(o===void 0)return 0;let u=t[o],c=r[o];if(!u||!c)return 1/0;let f=(n||i())-c;return u-f},this.#d=s=>{let o=r[s],u=t[s];return!!u&&!!o&&(n||i())-o>u}}#C=()=>{};#E=()=>{};#L=()=>{};#d=()=>!1;#$(){let t=new Hi(this.#u);this.#y=0,this.#b=t,this.#D=r=>{this.#y-=t[r],t[r]=0},this.#z=(r,n,i,s)=>{if(this.#t(n))return 0;if(!Dn(i))if(s){if(typeof s!="function")throw new TypeError("sizeCalculation must be a function");if(i=s(n,r),!Dn(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return i},this.#N=(r,n,i)=>{if(t[r]=n,this.#f){let s=this.#f-t[r];for(;this.#y>s;)this.#P(!0)}this.#y+=t[r],i&&(i.entrySize=n,i.totalCalculatedSize=this.#y)}}#D=t=>{};#N=(t,r,n)=>{};#z=(t,r,n,i)=>{if(n||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#k({allowStale:t=this.allowStale}={}){if(this.#i)for(let r=this.#s;!(!this.#B(r)||((t||!this.#d(r))&&(yield r),r===this.#a));)r=this.#p[r]}*#A({allowStale:t=this.allowStale}={}){if(this.#i)for(let r=this.#a;!(!this.#B(r)||((t||!this.#d(r))&&(yield r),r===this.#s));)r=this.#c[r]}#B(t){return t!==void 0&&this.#n.get(this.#r[t])===t}*entries(){for(let t of this.#k())this.#e[t]!==void 0&&this.#r[t]!==void 0&&!this.#t(this.#e[t])&&(yield[this.#r[t],this.#e[t]])}*rentries(){for(let t of this.#A())this.#e[t]!==void 0&&this.#r[t]!==void 0&&!this.#t(this.#e[t])&&(yield[this.#r[t],this.#e[t]])}*keys(){for(let t of this.#k()){let r=this.#r[t];r!==void 0&&!this.#t(this.#e[t])&&(yield r)}}*rkeys(){for(let t of this.#A()){let r=this.#r[t];r!==void 0&&!this.#t(this.#e[t])&&(yield r)}}*values(){for(let t of this.#k())this.#e[t]!==void 0&&!this.#t(this.#e[t])&&(yield this.#e[t])}*rvalues(){for(let t of this.#A())this.#e[t]!==void 0&&!this.#t(this.#e[t])&&(yield this.#e[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,r={}){for(let n of this.#k()){let i=this.#e[n],s=this.#t(i)?i.__staleWhileFetching:i;if(s!==void 0&&t(s,this.#r[n],this))return this.get(this.#r[n],r)}}forEach(t,r=this){for(let n of this.#k()){let i=this.#e[n],s=this.#t(i)?i.__staleWhileFetching:i;s!==void 0&&t.call(r,s,this.#r[n],this)}}rforEach(t,r=this){for(let n of this.#A()){let i=this.#e[n],s=this.#t(i)?i.__staleWhileFetching:i;s!==void 0&&t.call(r,s,this.#r[n],this)}}purgeStale(){let t=!1;for(let r of this.#A({allowStale:!0}))this.#d(r)&&(this.#S(this.#r[r],"expire"),t=!0);return t}info(t){let r=this.#n.get(t);if(r===void 0)return;let n=this.#e[r],i=this.#t(n)?n.__staleWhileFetching:n;if(i===void 0)return;let s={value:i};if(this.#h&&this.#w){let o=this.#h[r],u=this.#w[r];if(o&&u){let c=o-(Qi.now()-u);s.ttl=c,s.start=Date.now()}}return this.#b&&(s.size=this.#b[r]),s}dump(){let t=[];for(let r of this.#k({allowStale:!0})){let n=this.#r[r],i=this.#e[r],s=this.#t(i)?i.__staleWhileFetching:i;if(s===void 0||n===void 0)continue;let o={value:s};if(this.#h&&this.#w){o.ttl=this.#h[r];let u=Qi.now()-this.#w[r];o.start=Math.floor(Date.now()-u)}this.#b&&(o.size=this.#b[r]),t.unshift([n,o])}return t}load(t){this.clear();for(let[r,n]of t){if(n.start){let i=Date.now()-n.start;n.start=Qi.now()-i}this.set(r,n.value,n)}}set(t,r,n={}){if(r===void 0)return this.delete(t),this;let{ttl:i=this.ttl,start:s,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:u=this.sizeCalculation,status:c}=n,{noUpdateTTL:f=this.noUpdateTTL}=n,h=this.#z(t,r,n.size||0,u);if(this.maxEntrySize&&h>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.#S(t,"set"),this;let p=this.#i===0?void 0:this.#n.get(t);if(p===void 0)p=this.#i===0?this.#s:this.#x.length!==0?this.#x.pop():this.#i===this.#u?this.#P(!1):this.#i,this.#r[p]=t,this.#e[p]=r,this.#n.set(t,p),this.#c[this.#s]=p,this.#p[p]=this.#s,this.#s=p,this.#i++,this.#N(p,h,c),c&&(c.set="add"),f=!1;else{this.#I(p);let m=this.#e[p];if(r!==m){if(this.#_&&this.#t(m)){m.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:d}=m;d!==void 0&&!o&&(this.#v&&this.#m?.(d,t,"set"),this.#l&&this.#o?.push([d,t,"set"]))}else o||(this.#v&&this.#m?.(m,t,"set"),this.#l&&this.#o?.push([m,t,"set"]));if(this.#D(p),this.#N(p,h,c),this.#e[p]=r,c){c.set="replace";let d=m&&this.#t(m)?m.__staleWhileFetching:m;d!==void 0&&(c.oldValue=d)}}else c&&(c.set="update")}if(i!==0&&!this.#h&&this.#F(),this.#h&&(f||this.#L(p,i,s),c&&this.#E(c,p)),!o&&this.#l&&this.#o){let m=this.#o,d;for(;d=m?.shift();)this.#g?.(...d)}return this}pop(){try{for(;this.#i;){let t=this.#e[this.#a];if(this.#P(!0),this.#t(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#l&&this.#o){let t=this.#o,r;for(;r=t?.shift();)this.#g?.(...r)}}}#P(t){let r=this.#a,n=this.#r[r],i=this.#e[r];return this.#_&&this.#t(i)?i.__abortController.abort(new Error("evicted")):(this.#v||this.#l)&&(this.#v&&this.#m?.(i,n,"evict"),this.#l&&this.#o?.push([i,n,"evict"])),this.#D(r),t&&(this.#r[r]=void 0,this.#e[r]=void 0,this.#x.push(r)),this.#i===1?(this.#a=this.#s=0,this.#x.length=0):this.#a=this.#c[r],this.#n.delete(n),this.#i--,r}has(t,r={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:i}=r,s=this.#n.get(t);if(s!==void 0){let o=this.#e[s];if(this.#t(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#d(s))i&&(i.has="stale",this.#E(i,s));else return n&&this.#C(s),i&&(i.has="hit",this.#E(i,s)),!0}else i&&(i.has="miss");return!1}peek(t,r={}){let{allowStale:n=this.allowStale}=r,i=this.#n.get(t);if(i===void 0||!n&&this.#d(i))return;let s=this.#e[i];return this.#t(s)?s.__staleWhileFetching:s}#O(t,r,n,i){let s=r===void 0?void 0:this.#e[r];if(this.#t(s))return s;let o=new yu,{signal:u}=n;u?.addEventListener("abort",()=>o.abort(u.reason),{signal:o.signal});let c={signal:o.signal,options:n,context:i},f=(b,v=!1)=>{let{aborted:k}=o.signal,T=n.ignoreFetchAbort&&b!==void 0;if(n.status&&(k&&!v?(n.status.fetchAborted=!0,n.status.fetchError=o.signal.reason,T&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),k&&!T&&!v)return p(o.signal.reason);let E=d;return this.#e[r]===d&&(b===void 0?E.__staleWhileFetching?this.#e[r]=E.__staleWhileFetching:this.#S(t,"fetch"):(n.status&&(n.status.fetchUpdated=!0),this.set(t,b,c.options))),b},h=b=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=b),p(b)),p=b=>{let{aborted:v}=o.signal,k=v&&n.allowStaleOnFetchAbort,T=k||n.allowStaleOnFetchRejection,E=T||n.noDeleteOnFetchRejection,g=d;if(this.#e[r]===d&&(!E||g.__staleWhileFetching===void 0?this.#S(t,"fetch"):k||(this.#e[r]=g.__staleWhileFetching)),T)return n.status&&g.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),g.__staleWhileFetching;if(g.__returned===g)throw b},m=(b,v)=>{let k=this.#T?.(t,s,c);k&&k instanceof Promise&&k.then(T=>b(T===void 0?void 0:T),v),o.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(b(void 0),n.allowStaleOnFetchAbort&&(b=T=>f(T,!0)))})};n.status&&(n.status.fetchDispatched=!0);let d=new Promise(m).then(f,h),x=Object.assign(d,{__abortController:o,__staleWhileFetching:s,__returned:void 0});return r===void 0?(this.set(t,x,{...c.options,status:void 0}),r=this.#n.get(t)):this.#e[r]=x,x}#t(t){if(!this.#_)return!1;let r=t;return!!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof yu}async fetch(t,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:u=this.noDisposeOnSet,size:c=0,sizeCalculation:f=this.sizeCalculation,noUpdateTTL:h=this.noUpdateTTL,noDeleteOnFetchRejection:p=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:m=this.allowStaleOnFetchRejection,ignoreFetchAbort:d=this.ignoreFetchAbort,allowStaleOnFetchAbort:x=this.allowStaleOnFetchAbort,context:b,forceRefresh:v=!1,status:k,signal:T}=r;if(!this.#_)return k&&(k.fetch="get"),this.get(t,{allowStale:n,updateAgeOnGet:i,noDeleteOnStaleGet:s,status:k});let E={allowStale:n,updateAgeOnGet:i,noDeleteOnStaleGet:s,ttl:o,noDisposeOnSet:u,size:c,sizeCalculation:f,noUpdateTTL:h,noDeleteOnFetchRejection:p,allowStaleOnFetchRejection:m,allowStaleOnFetchAbort:x,ignoreFetchAbort:d,status:k,signal:T},g=this.#n.get(t);if(g===void 0){k&&(k.fetch="miss");let I=this.#O(t,g,E,b);return I.__returned=I}else{let I=this.#e[g];if(this.#t(I)){let P=n&&I.__staleWhileFetching!==void 0;return k&&(k.fetch="inflight",P&&(k.returnedStale=!0)),P?I.__staleWhileFetching:I.__returned=I}let _=this.#d(g);if(!v&&!_)return k&&(k.fetch="hit"),this.#I(g),i&&this.#C(g),k&&this.#E(k,g),I;let D=this.#O(t,g,E,b),M=D.__staleWhileFetching!==void 0&&n;return k&&(k.fetch=_?"stale":"refresh",M&&_&&(k.returnedStale=!0)),M?D.__staleWhileFetching:D.__returned=D}}async forceFetch(t,r={}){let n=await this.fetch(t,r);if(n===void 0)throw new Error("fetch() returned undefined");return n}memo(t,r={}){let n=this.#R;if(!n)throw new Error("no memoMethod provided to constructor");let{context:i,forceRefresh:s,...o}=r,u=this.get(t,o);if(!s&&u!==void 0)return u;let c=n(t,u,{options:o,context:i});return this.set(t,c,o),c}get(t,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,status:o}=r,u=this.#n.get(t);if(u!==void 0){let c=this.#e[u],f=this.#t(c);return o&&this.#E(o,u),this.#d(u)?(o&&(o.get="stale"),f?(o&&n&&c.__staleWhileFetching!==void 0&&(o.returnedStale=!0),n?c.__staleWhileFetching:void 0):(s||this.#S(t,"expire"),o&&n&&(o.returnedStale=!0),n?c:void 0)):(o&&(o.get="hit"),f?c.__staleWhileFetching:(this.#I(u),i&&this.#C(u),c))}else o&&(o.get="miss")}#M(t,r){this.#p[r]=t,this.#c[t]=r}#I(t){t!==this.#s&&(t===this.#a?this.#a=this.#c[t]:this.#M(this.#p[t],this.#c[t]),this.#M(this.#s,t),this.#s=t)}delete(t){return this.#S(t,"delete")}#S(t,r){let n=!1;if(this.#i!==0){let i=this.#n.get(t);if(i!==void 0)if(n=!0,this.#i===1)this.#V(r);else{this.#D(i);let s=this.#e[i];if(this.#t(s)?s.__abortController.abort(new Error("deleted")):(this.#v||this.#l)&&(this.#v&&this.#m?.(s,t,r),this.#l&&this.#o?.push([s,t,r])),this.#n.delete(t),this.#r[i]=void 0,this.#e[i]=void 0,i===this.#s)this.#s=this.#p[i];else if(i===this.#a)this.#a=this.#c[i];else{let o=this.#p[i];this.#c[o]=this.#c[i];let u=this.#c[i];this.#p[u]=this.#p[i]}this.#i--,this.#x.push(i)}}if(this.#l&&this.#o?.length){let i=this.#o,s;for(;s=i?.shift();)this.#g?.(...s)}return n}clear(){return this.#V("delete")}#V(t){for(let r of this.#A({allowStale:!0})){let n=this.#e[r];if(this.#t(n))n.__abortController.abort(new Error("deleted"));else{let i=this.#r[r];this.#v&&this.#m?.(n,i,t),this.#l&&this.#o?.push([n,i,t])}}if(this.#n.clear(),this.#e.fill(void 0),this.#r.fill(void 0),this.#h&&this.#w&&(this.#h.fill(0),this.#w.fill(0)),this.#b&&this.#b.fill(0),this.#a=0,this.#s=0,this.#x.length=0,this.#y=0,this.#i=0,this.#l&&this.#o){let r=this.#o,n;for(;n=r?.shift();)this.#g?.(...n)}}};var Kf=({maximumBytes:e=Q.hydratedTotalBytes*4}={})=>{if(Number.isSafeInteger(e)===!1||e<=0)throw new TypeError("Document source cache byte limit must be positive");return new Wi({maxSize:e,sizeCalculation:t=>Math.max(1,t.bytes.byteLength)})},ao=class extends Error{code="CONTENT_LIMIT_EXCEEDED";documentId;contentByteLimit;constructor({message:t,documentId:r,contentByteLimit:n,cause:i}){super(t,{cause:i}),this.name="CachedDocumentLoaderError",this.documentId=r,this.contentByteLimit=n}},xu=({contentRef:e,revision:t,format:r})=>Ct([e,t,r??null]),eD=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return Og(t.format)&&typeof t.revision=="string"&&t.revision.length>0&&t.bytes instanceof Uint8Array},Q1=e=>Object.freeze({format:e.format,revision:e.revision,source:e.bytes}),H1=({load:e,cache:t,maximumBytes:r=Q.hydratedFileBytes,onEvent:n})=>{let i=new Map;return async(s,o)=>{let u=xu(s),c=i.get(u)??new Map;i.set(u,c);let f=c.get(o.signal);if(f!==void 0)return await f;let h=(async()=>{let p;try{p=await t.get(u)}catch(b){mt(n,{type:"document-cache-read-failed",documentId:s.id,revision:s.revision,errorCode:Ji(b)})}if(eD(p)&&p.revision===s.revision&&p.bytes.byteLength<=r&&(s.format===void 0||p.format===s.format))return mt(n,{type:"document-cache-hit",documentId:s.id,revision:s.revision}),Q1(p);mt(n,{type:"document-cache-miss",documentId:s.id,revision:s.revision});let m=Zi({node:s,source:await e(s,o)}),d;try{d=await Ar(m.source,r)}catch(b){throw b instanceof pt?new ao({message:`Document ${s.id} exceeds the cache byte limit`,documentId:s.id,contentByteLimit:r,cause:b}):b}let x=Object.freeze({format:m.format,revision:m.revision,bytes:d});try{await t.set(u,x),mt(n,{type:"document-cache-stored",documentId:s.id,revision:s.revision})}catch(b){mt(n,{type:"document-cache-write-failed",documentId:s.id,revision:s.revision,errorCode:Ji(b)})}return Q1(x)})();c.set(o.signal,h);try{return await h}finally{c.delete(o.signal),c.size===0&&i.delete(u)}}};var en=class extends Error{code;documentId;referenceId;constructor({code:t,message:r,documentId:n,referenceId:i,cause:s}){super(r,{cause:s}),this.name="DocumentGraphResolutionError",this.code=t,this.documentId=n,this.referenceId=i}},bu=e=>{if(e?.aborted)throw new en({code:"REQUEST_CANCELLED",message:"Document graph resolution was cancelled",cause:e.reason})},W1=async({graph:e,rootIds:t,concurrency:r,signal:n,load:i,select:s,assemble:o})=>{bu(n);let u=Lo({graph:e,rootIds:t}),c=new Map(u.map(d=>[d.id,d])),f=new Map,h=new Map;for(let d of u){let x=h.get(d.contentRef);x===void 0?h.set(d.contentRef,{representative:d,nodes:[d]}):x.nodes.push(d)}await Mo([...h.values()],r,async d=>{bu(n);let x=d.representative;try{let b=await i(x,{signal:n});for(let v of d.nodes)f.set(v.id,b)}catch(b){throw n?.aborted&&bu(n),new en({code:"DOCUMENT_LOAD_FAILED",message:`Document ${x.id} could not be loaded`,documentId:x.id,cause:b})}});let p=mi(e.edges),m=new Map;for(let d of u){bu(n);let x=new Map;for(let v of p.get(d.id)??[]){let k=c.get(v.reference.documentId);if(k===void 0||m.has(v.reference.documentId)===!1)throw new en({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${d.id} dependency ${v.reference.documentId} is unavailable`,documentId:d.id,referenceId:v.referenceId});let T=m.get(v.reference.documentId),E;if(s===void 0){if(v.reference.representation.type!=="document")throw new en({code:"REPRESENTATION_SELECTOR_REQUIRED",message:`Document ${d.id} reference ${v.referenceId} requires a representation selector`,documentId:d.id,referenceId:v.referenceId});E=T}else try{E=await s({reference:v.reference,value:T,sourceNode:d,targetNode:k})}catch(g){throw new en({code:"DOCUMENT_SELECTION_FAILED",message:`Document ${d.id} reference ${v.referenceId} could not be selected`,documentId:d.id,referenceId:v.referenceId,cause:g})}x.set(v.referenceId,E)}if(f.has(d.id)===!1)throw new en({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${d.id} source is unavailable`,documentId:d.id});let b=f.get(d.id);try{m.set(d.id,await o({node:d,source:b,references:x}))}catch(v){throw new en({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${d.id} could not be assembled`,documentId:d.id,cause:v})}}return Object.freeze({roots:Object.freeze(t.map(d=>m.get(d))),values:m})};var Wn=class extends Error{code;documentId;documentCount;documentLimit;contentByteLimit;totalBytes;totalByteLimit;constructor({code:t,message:r,documentId:n,documentCount:i,documentLimit:s,contentByteLimit:o,totalBytes:u,totalByteLimit:c,cause:f}){super(r,{cause:f}),this.name="DocumentResolutionLimitError",this.code=t,this.documentId=n,this.documentCount=i,this.documentLimit=s,this.contentByteLimit=o,this.totalBytes=u,this.totalByteLimit=c}},tD=(e,t)=>{let r=0,n=[],i=async()=>{if(t?.throwIfAborted(),r<e){r+=1;return}await new Promise((o,u)=>{let c,f=()=>{let h=n.indexOf(c);h!==-1&&n.splice(h,1);try{t?.throwIfAborted()}catch(p){u(p)}};c={start:()=>{t?.removeEventListener("abort",f),o()}},n.push(c),t?.addEventListener("abort",f,{once:!0})})},s=()=>{let o=n.shift();if(o===void 0){r-=1;return}o.start()};return async o=>{await i();try{return await o()}finally{s()}}},rD=async({graph:e,rootIds:t,concurrency:r,maximumBytes:n,maximumTotalBytes:i=Q.hydratedTotalBytes,maximumDocuments:s=Q.hydratedFileCount,signal:o,onEvent:u,allowUnresolvedReferences:c=!1,load:f})=>{let h=Lo({graph:e,rootIds:t}).length,p={rootCount:t.length,documentCount:h};mt(u,{type:"resolution-started",...p});try{if(h>s)throw new Wn({code:"DOCUMENT_COUNT_EXCEEDED",message:"Document graph resolution exceeds the document limit",documentCount:h,documentLimit:s});let m=0,d=Promise.resolve(),x=await W1({graph:e,rootIds:t,concurrency:r,signal:o,load:async(b,v)=>{let k=d,T=()=>{};d=new Promise(g=>{T=g});let E;try{E={status:"fulfilled",value:await f(b,v)}}catch(g){E={status:"rejected",reason:g}}await k;try{if(E.status==="rejected")throw E.reason;if(E.value.byteLength>n)throw new Wn({code:"CONTENT_LIMIT_EXCEEDED",message:`Document ${b.id} exceeds the byte limit`,documentId:b.id,contentByteLimit:n,cause:new pt});let g=m+E.value.byteLength;if(g>i)throw new Wn({code:"TOTAL_BYTES_EXCEEDED",message:"Document graph resolution exceeds the total byte limit",documentId:b.id,totalBytes:g,totalByteLimit:i});return m=g,await E.value.parse()}finally{T()}},select:({reference:b,value:v})=>$1({document:v,representation:b.representation}),assemble:({source:b,references:v})=>V1({document:b,references:v,allowUnresolvedReferences:c})});return mt(u,{type:"resolution-completed",...p}),x}catch(m){throw mt(u,{type:"resolution-failed",...p,errorCode:Ji(m)}),m}},K1=({load:e,concurrency:t,signal:r,maximumDocumentBytes:n=Q.hydratedFileBytes,maximumCacheBytes:i=Q.hydratedTotalBytes*4})=>{if(Number.isSafeInteger(t)===!1||t<=0)throw new TypeError("Document resolution concurrency must be positive");if(Number.isSafeInteger(n)===!1||n<=0)throw new TypeError("Document resolution byte limit must be positive");if(Number.isSafeInteger(i)===!1||i<=0)throw new TypeError("Document resolution cache byte limit must be positive");let s=new Wi({maxSize:i,sizeCalculation:({byteLength:m})=>Math.max(1,m)}),o=new Map,u=tD(t,r),c=m=>{if(m!==void 0&&m!==r)throw new TypeError("Document resolution session signal does not match");r?.throwIfAborted()},f=async m=>(c(),r===void 0?await m:await new Promise((d,x)=>{let b=()=>r.removeEventListener("abort",v),v=()=>{b();try{r.throwIfAborted()}catch(k){x(k)}};r.addEventListener("abort",v,{once:!0}),m.then(k=>{b(),d(k)},k=>{b(),x(k)}),r.aborted&&v()})),h=async(m,d)=>{c(d.signal);let x=xu(m),b=s.get(x);if(b!==void 0)return b;let v=o.get(x);if(v!==void 0)return await f(v);let k=u(async()=>{c(d.signal);let T=Zi({node:m,source:await e(m,{signal:r})});c(d.signal);let E=await lc(T.source,n+1);c(d.signal);let g,I=Object.freeze({format:T.format,revision:T.revision,bytes:E,byteLength:E.byteLength,parse:()=>(g??=M1({format:T.format,source:E,maximumBytes:n}),g)});return I.byteLength<=i&&s.set(x,I),I});o.set(x,k);try{return await f(k)}finally{o.delete(x)}};return Object.freeze({getCached:m=>{c();let d=s.get(xu(m));if(!(d===void 0||d.byteLength>n))return Object.freeze({format:d.format,revision:d.revision,source:d.bytes.slice()})},resolve:async m=>await rD({...m,concurrency:t,maximumBytes:n,signal:r,load:h})})};var X1=e=>{if(e.output.mode==="all")return"all";let t=[];for(let{field:r}of gs(e.where))r[0]==="properties"&&t.push(r);for(let{field:r}of e.sort)r[0]==="properties"&&t.push(r);if(e.output.mode==="fields")for(let r of e.output.fields)r[0]==="properties"&&t.push(r);return t},Y1=e=>{let t;if(e==="#frontmatter")t="";else if(e.startsWith("#frontmatter/"))t=e.slice(12);else if(e==="#")t="";else if(e.startsWith("#/"))t=e.slice(1);else return;try{return["properties",...Xg(t)]}catch{return}},ew=(e,t)=>{let r=Math.min(e.length,t.length);for(let n=0;n<r;n+=1)if(e[n]!==t[n])return!1;return!0},tw=({queryPaths:e,referenceId:t})=>{let r=Y1(t);return r!==void 0&&(e==="all"||e.some(n=>ew(n,r)))},rw=({graph:e,sourceId:t,field:r})=>r[0]!=="properties"?!1:e.edges.some(n=>{if(n.sourceId!==t)return!1;let i=Y1(n.referenceId);return i!==void 0&&ew(r,i)}),nw=({graph:e,query:t})=>{let r=X1(t),n=new Set;for(let i of e.edges)tw({queryPaths:r,referenceId:i.referenceId})&&n.add(i.sourceId);return[...n]},iw=({graph:e,query:t,rootIds:r})=>{let n=X1(t),i=new Set(r),s=new Map(e.nodes.map(p=>[p.id,p])),o=mi(e.edges),u=new Set(r),c=new Set,f=new Set,h=p=>{if(u.add(p),!f.has(p)){f.add(p);for(let m of o.get(p)??[])c.add(m),h(m.reference.documentId)}};for(let p of e.edges)i.has(p.sourceId)&&tw({queryPaths:n,referenceId:p.referenceId})&&(c.add(p),h(p.reference.documentId));return bs({nodes:[...u].map(p=>{let m=s.get(p);if(m===void 0)throw new Error(`Document graph query root ${p} does not exist`);return m}),edges:[...c]})};var sw=({artifact:e})=>{if(e.documentGraph===void 0)return;let t=new Map(e.documents.map(s=>[s._id,s])),r=new Map(e.documentGraph.nodes.map(s=>[s.id,s])),n=new Map;for(let{sourceId:s}of e.documentGraph.edges){if(r.has(s))continue;let o=t.get(s);if(o?.properties===void 0)throw new Error(`Runtime document graph source ${s} is unavailable`);n.set(s,o),r.set(s,{id:s,revision:s,contentRef:s,format:"json"})}return{graph:bs({nodes:[...r.values()],edges:e.documentGraph.edges.map(({sourceId:s,referenceId:o,documentId:u,representation:c})=>{let f=r.get(u);if(f===void 0)throw new Error(`Runtime document graph target ${u} is unavailable`);return{sourceId:s,referenceId:o,reference:{documentId:u,revision:f.revision,representation:c}}})}),inlineDocuments:n}};var ow=({markdown:e,references:t,assetUrls:r})=>{let n=e.length,i=e;for(let s of[...t].sort((o,u)=>u.start-o.start)){if(s.start<0||s.end<=s.start||s.end>e.length||s.end>n)throw new Error("Markdown asset reference range is invalid");n=s.start;let o=r[s.assetId];if(o===void 0)continue;let u=il(o,s.suffix);i=`${i.slice(0,s.start)}${u}${i.slice(s.end)}`}return i};var gt=class extends Error{code;details;constructor({code:t,message:r,details:n}){super(r),this.name="AssetResourceHydrationError",this.code=t,this.details=n}},nD=e=>{if(e===null)return[];let t=Array.isArray(e)?e:[e],r=new Map;for(let n of t){if(typeof n!="object"||n===null||!("_id"in n)||typeof n._id!="string"||!("revision"in n)||typeof n.revision!="string"||!("contentRef"in n)||typeof n.contentRef!="string")throw new gt({code:"CONTENT_IDENTITY_REQUIRED",message:"Hydrated query results must retain _id, revision, and contentRef"});let i=r.get(n._id);if(i!==void 0&&(i.revision!==n.revision||i.contentRef!==n.contentRef))throw new gt({code:"CONTENT_IDENTITY_REQUIRED",message:"A selected asset ID has conflicting content identity",details:{assetId:n._id}});r.set(n._id,{_id:n._id,revision:n.revision,contentRef:n.contentRef})}return Array.from(r.values())},iD=e=>typeof e.mimeType=="string"&&(e.mimeType.startsWith("text/")||["application/json","application/javascript","application/xml","image/svg+xml"].includes(e.mimeType)),sD=async({read:e,contentRef:t,range:r,maximumBytes:n})=>{if(n===0)return new Uint8Array;let i=await e(t,r);try{return await Ar(i.data,n)}catch(s){throw s instanceof pt?new gt({code:"CONTENT_LIMIT_EXCEEDED",message:"Asset storage returned more content than requested"}):s}},oD=e=>{try{return _t(e)}catch{throw new gt({code:"CONTENT_DECODING_FAILED",message:"Selected asset content is not valid UTF-8"})}},aD=(e,t)=>{if(t.mode==="range")return Math.max(0,Math.min(t.length,e.size-t.offset));let r=t.maxBytes??Q.hydratedFileBytes;if(e.size>r)throw new gt({code:"CONTENT_LIMIT_EXCEEDED",message:"Selected asset exceeds the per-file content limit",details:{assetId:e._id,assetBytes:e.size,fileByteLimit:r}});return e.size},aw=async({result:e,documents:t,options:r,read:n,assetReferences:i,assetUrls:s})=>{if(r.mode==="none")return{content:{},hydratedFileCount:0,hydratedBytes:0};let o=nD(e);if(o.length>Q.hydratedFileCount)throw new gt({code:"CONTENT_LIMIT_EXCEEDED",message:"Too many selected assets requested content hydration",details:{fileCount:o.length,fileCountLimit:Q.hydratedFileCount}});let u=new Map(t.map(p=>[p._id,p])),c=o.map(p=>{let m=u.get(p._id);if(m===void 0||m.revision!==p.revision||m.contentRef!==p.contentRef||typeof m.size!="number"||typeof m.mimeType!="string")throw new gt({code:"CONTENT_IDENTITY_REQUIRED",message:"Selected asset content identity is stale or unavailable",details:{assetId:p._id}});let d={...m,size:m.size,mimeType:m.mimeType};if(iD(d)===!1)throw new gt({code:"CONTENT_NOT_TEXT",message:"Selected binary asset cannot be embedded as text",details:{assetId:p._id,mimeType:d.mimeType}});return{identity:p,document:d,readLength:aD(d,r)}}),f=c.reduce((p,m)=>p+m.readLength,0);if(f>Q.hydratedTotalBytes)throw new gt({code:"CONTENT_LIMIT_EXCEEDED",message:"Selected assets exceed the total hydrated-content limit",details:{totalReadBytes:f,totalByteLimit:Q.hydratedTotalBytes}});let h=await Mo(c,Q.concurrentContentReads,async p=>{let m=r.mode==="range"?{offset:r.offset,length:p.readLength}:p.readLength===0?void 0:{offset:0,length:p.readLength},d=await sD({read:n,contentRef:p.identity.contentRef,range:m,maximumBytes:p.readLength});if(d.byteLength!==p.readLength)throw new gt({code:"CONTENT_IDENTITY_REQUIRED",message:"Selected asset bytes do not match canonical metadata",details:{assetId:p.identity._id}});let x;if(r.mode==="markdown-body-ref")try{x=(await Aa(d,p.readLength||1)).body;let v=i?.[p.identity.contentRef];v!==void 0&&s!==void 0&&(x=ow({markdown:x,references:v,assetUrls:s}))}catch{throw new gt({code:"CONTENT_DECODING_FAILED",message:"Selected Markdown body could not be decoded",details:{assetId:p.identity._id}})}else x=oD(d);let b=Mt(x);return{id:p.identity._id,returnedBytes:b,content:{...p.identity,encoding:"utf-8",text:x,...r.mode==="range"?{range:{offset:r.offset,length:d.byteLength,total:p.document.size}}:{}}}});return{content:Object.fromEntries(h.map(({id:p,content:m})=>[p,m])),hydratedFileCount:c.length,hydratedBytes:h.reduce((p,{returnedBytes:m})=>p+m,0)}};var X7=G().datetime({offset:!0}).transform(e=>new Date(e).toISOString());var uD=/^[A-Za-z_][A-Za-z0-9_]*$/,uw=(e,t)=>uD.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`;var cw=({document:e,includes:t})=>{let r={};for(let n of qg){let i=e[n];i!==void 0&&t(n)&&(r[n]=i)}return r},lw=({source:e,target:t,path:r})=>{let[n,...i]=r;if(n===void 0||Object.hasOwn(e,n)===!1)return;let s=e[n];if(i.length===0){Object.defineProperty(t,n,{value:s,enumerable:!0,configurable:!0,writable:!0});return}if(typeof s!="object"||s===null||Array.isArray(s))return;let o={};if(lw({source:s,target:o,path:i}),Object.keys(o).length===0)return;let u=t[n];Object.defineProperty(t,n,{value:{...typeof u=="object"&&u!==null&&Array.isArray(u)===!1?u:{},...o},enumerable:!0,configurable:!0,writable:!0})},fw=({properties:e,fields:t})=>{let r={};for(let n of t)n[0]==="properties"&&lw({source:e,target:r,path:n.slice(1)});return r};var xr=class extends Error{constructor(t,r){super(t,r),this.name="AssetQueryExecutionError"}},uo=class extends xr{code="MULTIPLE_RESULTS";matchedCount;constructor(t){super(`Expected at most one asset, but the query matched ${t}.`),this.matchedCount=t,this.name="AssetQueryMultipleResultsError"}},Xi=class extends Error{constructor(){super("The requested asset index revision is stale"),this.name="AssetIndexRevisionError"}},pw=e=>{if(e[0]!=="properties")return e[0];let t="properties";for(let r of e.slice(1))t=uw(t,r);return t},hw=({filter:e,fieldTypes:t})=>Gg(t).includes(e.operator),dw=(e,t)=>e!==void 0&&Object.hasOwn(e.fields,t)?e.fields[t]:void 0,cD=({query:e,catalog:t})=>{let r=fn.parse(e),n=new Map,i=[];for(let s of gs(r.where)){let o=pw(s.field);if(n.set(o,s.field),s.field[0]==="properties"){let u=dw(t,o);t!==void 0&&u===void 0?i.push(`Asset field ${o} is not currently observed`):u!==void 0&&hw({filter:s,fieldTypes:u.types})===!1&&i.push(`Operator ${s.operator} is not compatible with the currently observed types of ${o}`)}else if(hw({filter:s,fieldTypes:gc[s.field[0]]})===!1)throw new xr(`Operator ${s.operator} is incompatible with ${o}`)}for(let s of r.sort){let o=pw(s.field);if(n.set(o,s.field),s.field[0]==="properties"){let u=dw(t,o);t!==void 0&&u===void 0?i.push(`Asset field ${o} is not currently observed`):u!==void 0&&u.types.some(c=>c==="object"||c==="array")&&i.push(`Asset field ${o} currently includes structured values that use deterministic JSON sort order`)}}return{query:r,referencedFieldPaths:[...n.values()],warnings:[...new Set(i)]}},Yf=(e,t,r)=>{let n=t[0]==="id"?e._id:Bo(t[0])?r?.[t[0]]:e[t[0]];for(let i of t.slice(1)){if(typeof n!="object"||n===null||Object.hasOwn(n,i)===!1)return;n=n[i]}return n},lD=e=>typeof e=="string"||Array.isArray(e)?e.length===0:typeof e=="object"&&e!==null&&Object.keys(e).length===0,fD=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e-t;if(typeof e=="string"&&typeof t=="string")return Sr(e,t)},ep=(e,t,r)=>{let n=Yf(e,t.field,r);if(t.operator==="exists")return n!=null===t.value;if(t.operator==="isEmpty")return lD(n)===t.value;if(t.operator==="eq")return ys(n,t.value);if(t.operator==="ne")return ys(n,t.value)===!1;if(t.operator==="in")return t.value.some(s=>ys(n,s));if(t.operator==="contains")return typeof n=="string"&&typeof t.value=="string"?n.includes(t.value):Array.isArray(n)&&n.some(s=>ys(s,t.value));if(t.operator==="startsWith")return typeof n=="string"&&typeof t.value=="string"&&n.startsWith(t.value);if(t.operator==="endsWith")return typeof n=="string"&&typeof t.value=="string"&&n.endsWith(t.value);let i=fD(n,t.value);return i===void 0?!1:t.operator==="gt"?i>0:t.operator==="gte"?i>=0:t.operator==="lt"?i<0:i<=0},pD=({document:e,where:t,runtimeAsset:r,filterKeys:n,filterResults:i})=>fi(t,s=>{let o=n.get(s)??Ct(s),u=i.get(o);if(u!==void 0)return u;let c=ep(e,s,r);return i.set(o,c),c})===!0,hD=({document:e,content:t})=>{if(t.mode!=="markdown-body-ref")return!0;let r=e.mimeType===void 0?void 0:Fg(e.mimeType);return r==="markdown"||r==="mdx"?!0:e.extension==="md"||e.extension==="mdx"},dD=(e,t)=>{let r=e==null,n=t==null;return r||n?r===n?0:r?1:-1:typeof e=="number"&&typeof t=="number"?e-t:(typeof e=="string"||typeof e=="boolean")&&(typeof t=="string"||typeof t=="boolean")?Sr(String(e),String(t)):Sr(Ct(e),Ct(t))},mD=({left:e,right:t,sort:r,runtimeAssets:n})=>{for(let i of r){let s=dD(Yf(e,i.field,n?.[e._id]),Yf(t,i.field,n?.[t._id]));if(s!==0)return i.direction==="asc"?s:-s}return Sr(e._id,t._id)};var gD=(e,t)=>{if(e.properties===void 0)return;if(t.mode==="all")return Object.keys(e.properties).length===0?void 0:e.properties;if(t.mode!=="fields"||t.fields.some(n=>n[0]==="properties")===!1)return;let r=fw({properties:e.properties,fields:t.fields});return Object.keys(r).length===0?void 0:r},Ki=(e,t)=>e.includeMetadata&&Zg(t)||e.mode==="fields"&&e.fields.some(r=>r.length===1&&r[0]===t),yD=e=>e.mode==="all"||e.mode==="fields"&&e.fields.some(t=>t.length===1&&t[0]==="excerpt"),xD=(e,t,r)=>{if(Ki(t,"url")&&r===void 0)throw new Error(`Asset URL is unavailable for ${e._id}`);let n=gD(e,t),i=r?.width!==void 0&&r.height!==void 0;return{...r!==void 0&&Ki(t,"url")?{url:r.url}:{},...i&&Ki(t,"width")?{width:r.width}:{},...i&&Ki(t,"height")?{height:r.height}:{},...cw({document:e,includes:s=>Ki(t,s)}),...n===void 0?{}:{properties:n},...e.excerpt===void 0||yD(t)===!1?{}:{excerpt:e.excerpt},...e.metadataError===void 0||t.includeMetadata===!1?{}:{metadataError:e.metadataError}}},tp=e=>{if(Mt(Ct(e))>Q.resultBytes)throw new xr("Asset query result exceeds the byte limit")},wu=(e,t,r)=>{e[t]={status:"rejected",reason:r}},bD=({inputs:e,catalog:t,results:r})=>{let n=new Map,i=new Map,s=[];for(let[o,u]of e.entries()){let c;try{c=cD({query:u,catalog:t}).query}catch(p){wu(r,o,p);continue}for(let p of gs(c.where))i.set(p,Ct(p));let f=Ct(c.sort),h=n.get(f);h===void 0&&(h={sort:c.sort,documents:new Set,sorted:[]},n.set(f,h)),s.push({index:o,query:c,matches:new Map,sortGroup:h})}return{filterKeys:i,preparedQueries:s,sortGroups:n}},mw=({preparedQueries:e,results:t,createReason:r})=>{for(let{index:n}of e)wu(t,n,r())},Xf=e=>e.map(t=>{if(t===void 0)throw new Error("Asset query result was not settled");return t}),wD=({preparedQueries:e,documents:t,filterKeys:r,sortGroups:n,results:i,runtimeAssets:s})=>{for(let o of t){let u=s?.[o._id],c=new Map;for(let f of e){if(i[f.index]!==void 0)continue;let{query:h}=f;try{if(hD({document:o,content:h.content})===!1||pD({document:o,where:h.where,runtimeAsset:u,filterKeys:r,filterResults:c})===!1)continue;let p=xD(o,h.output,u);if(h.content.mode==="none"&&Object.keys(p).length===0&&Ki(h.output,"id")===!1)continue;let m={document:o,item:{id:o._id,...p}};f.matches.set(o,m),f.sortGroup.documents.add(o)}catch(p){wu(i,f.index,p)}}}for(let o of n.values())o.sorted=[...o.documents].sort((u,c)=>mD({left:u,right:c,sort:o.sort,runtimeAssets:s}))},vD=async({preparedQueries:e,results:t,read:r,assetReferences:n,assetUrls:i})=>{await Promise.all(e.map(async s=>{if(t[s.index]!==void 0)return;let{query:o}=s;try{let u=s.sortGroup.sorted.flatMap(d=>{let x=s.matches.get(d);return x===void 0?[]:[x]}),c=o.result??"many";if(c==="one"&&u.length>1)throw new uo(u.length);let f=c==="many"?u.slice(o.offset,o.offset+o.limit):c==="last"?u.slice(-1):u.slice(0,1),h=f.map(({document:d})=>d),p=f.map(({item:d})=>d);if(o.content.mode!=="none"){let d=o.content;if(r===void 0)throw new xr("Asset content reader is unavailable");let x=await aw({result:h,documents:h,options:d,read:r,assetReferences:n,assetUrls:n===void 0?void 0:i});p=h.map((b,v)=>{let k=x.content[b._id];if(k===void 0)throw new xr("Selected asset content could not be read");return{...p[v],content:{encoding:k.encoding,text:k.text,...k.range===void 0?{}:{range:k.range}}}})}let m=c==="many"?{items:p,totalCount:u.length,hasMore:o.offset+f.length<u.length}:{item:p[0]??null,totalCount:u.length};tp(m),t[s.index]={status:"fulfilled",value:m}}catch(u){wu(t,s.index,u)}}))},gw=async({queries:e,catalog:t,documents:r,read:n,runtimeAssets:i,assetReferences:s,assetValueReferences:o})=>{let u=Array.from({length:e.length}),{filterKeys:c,preparedQueries:f,sortGroups:h}=bD({inputs:e,catalog:t,results:u});if(r.length>Q.candidateDocuments)return mw({preparedQueries:f,results:u,createReason:()=>new xr("Asset query document limit was exceeded")}),Xf(u);let p=Zs(i),m;try{m=r.map(d=>Ri({value:d,references:o?.[d._id],assetUrls:p}))}catch(d){return mw({preparedQueries:f,results:u,createReason:()=>d}),Xf(u)}return wD({preparedQueries:f,documents:m,filterKeys:c,sortGroups:h,results:u,runtimeAssets:i}),await vD({preparedQueries:f,results:u,read:n,assetReferences:s,assetUrls:p}),Xf(u)};var kD=async e=>await Rg(Ct(fn.parse(e)));var AD=({item:e,field:t,value:r})=>{let n=e;for(let[i,s]of t.entries()){if(i===t.length-1){Object.defineProperty(n,s,{value:r,enumerable:!0,configurable:!0,writable:!0});return}let o=Object.hasOwn(n,s)?n[s]:void 0;if(typeof o=="object"&&o!==null){n=o;continue}let u={};Object.defineProperty(n,s,{value:u,enumerable:!0,configurable:!0,writable:!0}),n=u}},SD=e=>yc.parse({items:e.rows.map(t=>{let r={};for(let[n,i]of e.fields.entries())AD({item:r,field:i,value:t[n]});return r}),totalCount:e.totalCount,hasMore:e.hasMore}),yw=async({queries:e,query:t,assetValueReferences:r,assetUrls:n={}})=>{if(e===void 0)return;let i=e[await kD(fn.parse(t))];if(i===void 0)return;let s=SD(i),o={...s,items:s.items.map(u=>Ri({value:u,references:r?.[u.id],assetUrls:n}))};return tp(o),o};var ED=(e,t)=>t===void 0?hi(e):{async*[Symbol.asyncIterator](){let r=0,n=0;for await(let i of hi(e)){if(n===t.length)return;if(r+i.byteLength<=t.offset){r+=i.byteLength;continue}let s=Math.max(0,t.offset-r),o=Math.min(i.byteLength-s,t.length-n);o>0&&(yield i.subarray(s,s+o),n+=o),r+=i.byteLength}}},_D=({graph:e,load:t,getCached:r,readFallback:n,signal:i})=>{let s=new Map(e.nodes.map(o=>[o.contentRef,o]));return async(o,u)=>{let c=s.get(o);if(c===void 0){if(n!==void 0)return await n(o,u);throw new Error(`Document content reference ${o} is unavailable`)}let f=Zi({node:c,source:r(c)??await t(c,{signal:i})});return{data:ED(f.source,u),...u===void 0?{}:{contentLength:u.length}}}},CD=({artifact:e,revision:t,catalog:r,documentGraph:n,inlineDocuments:i,readContent:s})=>{let o=new Map(e.documents.map(I=>[I._id,I])),u=I=>{if(I.indexRevision!==void 0&&I.indexRevision!==t)throw new Xi},c=I=>async(_,D)=>{let O=e.contents?.[_];if(O===void 0){let J=I??s;if(J===void 0)throw new Error("Content is not embedded in this database");return await J(_,D)}let M=pi(O),P=D===void 0?M:M.slice(D.offset,D.offset+D.length);return{data:async function*(){yield P}(),contentLength:P.byteLength}},f=I=>{if(I.status==="rejected")throw I.reason;return I.value},h=async({requests:I,queryContentReader:_,runtimeAssets:D,documents:O=e.documents})=>await gw({queries:I.map(({query:M})=>M),catalog:r,documents:O,read:c(_),runtimeAssets:D,assetReferences:e.assetReferences,assetValueReferences:e.assetValueReferences}),p=async({request:I,..._})=>f((await h({..._,requests:[I]}))[0]),m=async({requests:I,queryContentReader:_,runtimeAssets:D})=>{let O=Array.from({length:I.length}),M=Zs(D),P=[];for(let[J,V]of I.entries()){try{u(V);let q=await yw({queries:e.queries,query:V.query,assetValueReferences:e.assetValueReferences,assetUrls:M});if(q!==void 0){O[J]={status:"fulfilled",value:q};continue}}catch(q){O[J]={status:"rejected",reason:q};continue}P.push(J)}if(P.length>0){let J=await h({requests:P.map(V=>I[V]),queryContentReader:_,runtimeAssets:D});for(let[V,q]of P.entries())O[q]=J[V]}return O.map(J=>{if(J===void 0)throw new Error("Content database query was not settled");return J})},d=async(I,_,D)=>f((await m({requests:[I],queryContentReader:_,runtimeAssets:D}))[0]),x=async(...I)=>await d(...I),b=I=>async(_,D)=>{let O=i?.get(_.id);return O!==void 0?{format:"json",revision:_.revision,source:JSON.stringify(O.properties)}:await I(_,D)},v=({graph:I,query:_,runtimeAssets:D})=>{let O=Zs(D);return nw({graph:I,query:_}).filter(M=>{let P=o.get(M),J=P===void 0?void 0:Ri({value:P,references:e.assetValueReferences?.[M],assetUrls:O});return J===void 0?!1:fi(_.where,V=>{if(!rw({graph:I,sourceId:M,field:V.field}))return ep(J,V,D?.[M])})!==!1})},k=({rootIds:I,roots:_})=>{let D=new Map(I.flatMap((O,M)=>{let P=B1(_[M]);return P===void 0?[]:[[O,P]]}));return e.documents.map(O=>{let M=D.get(O._id);return M===void 0?O:mc.parse({...O,properties:M})})},T=async({request:I,graph:_,resolutionSession:D,contentReader:O,runtimeAssets:M,onEvent:P})=>{u(I);let J=fn.parse(I.query),V=v({graph:_,query:J,runtimeAssets:M});if(V.length===0)return await d(I,O,M);let q=iw({graph:_,query:J,rootIds:V});mt(P,{type:"roots-selected",rootCount:V.length});let ee=await D.resolve({graph:q,rootIds:V,onEvent:P,allowUnresolvedReferences:!0}),re=k({rootIds:V,roots:ee.roots});return await p({request:I,queryContentReader:O,runtimeAssets:M,documents:re})},E=async({requests:I,load:_,resolutionSession:D,readContent:O,runtimeAssets:M,signal:P,onEvent:J})=>{if(n===void 0)return await m({requests:I,queryContentReader:O,runtimeAssets:M});let V=b(_),q=D??K1({load:V,concurrency:Q.concurrentContentReads,signal:P}),ee=_D({graph:n,load:V,getCached:q.getCached,readFallback:O??s,signal:P});return await Promise.allSettled(I.map(re=>T({request:re,graph:n,resolutionSession:q,contentReader:ee,runtimeAssets:M,onEvent:J})))};return{query:x,queryManyWithDocumentGraph:E,queryWithDocumentGraph:async({request:I,..._})=>f((await E({..._,requests:[I]}))[0])}};var rp=({artifact:e,readContent:t})=>{let r=sw({artifact:e});return CD({artifact:e,revision:e.revision,documentGraph:r?.graph,inlineDocuments:r?.inlineDocuments,readContent:t})};var vu=class extends Error{constructor(t,r){super(t,r),this.name="AssetQueryRequestError"}},co=class extends Error{},DD=async(e,t)=>{if(Number.isSafeInteger(t)===!1||t<0)throw new TypeError("Request byte limit must be a non-negative integer");let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw new co("Request exceeds the byte limit");let n=e.body?.getReader(),i=[],s=0;if(n!==void 0)for(;;){let{done:c,value:f}=await n.read();if(c)break;if(s+=f.byteLength,s>t){try{await n.cancel()}catch{}throw new co("Request exceeds the byte limit")}i.push(f)}let o=new Uint8Array(s),u=0;for(let c of i)o.set(c,u),u+=c.byteLength;return o},xw=async e=>{let t;try{t=await DD(e,Q.requestBytes)}catch(r){throw r instanceof co?new vu("Asset query request exceeds the byte limit",{cause:r}):r}try{return Qg.parse(JSON.parse(_t(t)))}catch(r){throw new vu("Asset query request is invalid",{cause:r})}};var bw=e=>{if(e instanceof Xi)return{code:"STALE_INDEX",message:e.message,retryable:!1,status:409};if(e instanceof uo)return{code:e.code,message:e.message,retryable:!1,details:{matchedCount:e.matchedCount},status:409};if(e instanceof xr)return{code:"INVALID_REQUEST",message:e.message,retryable:!1,status:400};if(e instanceof gt)return{code:e.code,message:e.message,retryable:!1,details:e.details,status:400};let t=new Set,r=e;for(;r!==void 0&&t.has(r)===!1;){if(r instanceof Wn){let n={};for(let[i,s]of Object.entries({assetId:r.documentId,documentCount:r.documentCount,documentLimit:r.documentLimit,contentByteLimit:r.contentByteLimit,totalBytes:r.totalBytes,totalByteLimit:r.totalByteLimit}))s!==void 0&&(n[i]=s);return{code:"CONTENT_LIMIT_EXCEEDED",message:r.message,retryable:!1,details:n,status:400}}if(r instanceof ao)return{code:"CONTENT_LIMIT_EXCEEDED",message:r.message,retryable:!1,details:{assetId:r.documentId,contentByteLimit:r.contentByteLimit},status:400};t.add(r),r=r instanceof Error?r.cause:void 0}};var ID="/$resources/assets",ww=(e,t=200)=>new Response(JSON.stringify(e),{status:t,headers:{"content-type":"application/json; charset=utf-8"}}),lo=({code:e,message:t,status:r,retryable:n=!1,details:i})=>ww(Kg({code:e,message:t,retryable:n,details:i}),r),TD=(e,t,r)=>typeof e=="string"||e instanceof URL?new Request(new URL(e,t),r):new Request(e,r),RD=async({deploymentId:e,artifact:t,request:r})=>{let n=await r.clone().text(),i=r.headers.get("cache-control"),s=await pc(JSON.stringify([e,t.revision,n,i])),o=new URL(r.url);return o.searchParams.set("ws-asset-resource",s),new Request(o,{method:"GET"})},qj=({deploymentId:e,artifact:t,runtimeAssets:r,cache:n,baseUrl:i,fetchDocument:s=globalThis.fetch,onDocumentGraphEvent:o})=>{vw({artifact:t,runtimeAssets:r});let u=Kf();return kw({deploymentId:e,artifact:t,runtimeAssets:r,cache:n,baseUrl:i,database:rp({artifact:t}),fetchDocument:s,documentCache:u,onDocumentGraphEvent:o})},ND=({baseUrl:e,runtimeAssets:t,fetchDocument:r,cache:n,onEvent:i})=>H1({cache:n,onEvent:i,load:U1({fetch:r,getRequest:s=>{let o=t[s.id];if(o===void 0)throw new Error(`Published document URL is unavailable for ${s.id}`);return new URL(o.url,e)},getMetadata:({node:s})=>({format:s.format,revision:s.revision}),onEvent:i})}),vw=({artifact:e,runtimeAssets:t})=>{let r=[e.assetReferences,e.assetValueReferences].flatMap(s=>Object.values(s??{}).flat()).map(({assetId:s})=>s).find(s=>t[s]===void 0);if(r!==void 0)throw new Error(`Published referenced asset URL is unavailable for ${r}`);let n=e.documentGraph?.nodes.find(({id:s})=>t[s]===void 0)?.id;if(n!==void 0)throw new Error(`Published document URL is unavailable for ${n}`);let i=e.documentGraph?.nodes.find(({id:s,contentRef:o})=>t[s]?.contentRef!==o)?.id;if(i!==void 0)throw new Error(`Published document identity does not match graph node ${i}`)},kw=({deploymentId:e,artifact:t,runtimeAssets:r,cache:n,baseUrl:i,database:s,fetchDocument:o,documentCache:u,onDocumentGraphEvent:c})=>{let f=new URL(i).origin,h=ND({baseUrl:i,runtimeAssets:r,fetchDocument:o,cache:u,onEvent:c});return async(p,m)=>{let d=TD(p,i,m),x=new URL(d.url);if(x.origin!==f||x.pathname!==ID||d.method.toUpperCase()!=="POST")return;let b;try{b=await xw(d.clone())}catch{return lo({code:"INVALID_REQUEST",message:"Asset resource request is invalid",status:400})}let v=n===void 0||d.headers.has("cache-control")===!1?void 0:await RD({deploymentId:e,artifact:t,request:d});if(v!==void 0&&n!==void 0){let k=await n.match(v).catch(()=>{});if(k!==void 0)return new Response(k.body,k)}try{if(d.signal.aborted)return lo({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let k=ww(await s.queryWithDocumentGraph({request:b,load:h,runtimeAssets:r,signal:d.signal,onEvent:c}));return v!==void 0&&n!==void 0&&d.signal.aborted===!1&&(k.headers.set("cache-control",d.headers.get("cache-control")),await n.put(v,k.clone()).catch(()=>{})),k}catch(k){if(d.signal.aborted)return lo({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let T=bw(k);return lo(T!==void 0?T:{code:"INTERNAL_ERROR",message:"Published asset query failed",status:500,retryable:!0})}}},Zj=({deploymentId:e,artifact:t,runtimeAssets:r,onDocumentGraphEvent:n=void 0})=>{let i=globalThis.caches,s,o=()=>(s??=i.open(`webstudio-assets-${e}`),s),u=i===void 0?void 0:{match:async h=>(await o()).match(h),put:async(h,p)=>(await o()).put(h,p)};vw({artifact:t,runtimeAssets:r});let c=rp({artifact:t}),f=Kf();return async({request:h,fallback:p})=>{let m=new URL(h.url).origin,d=kw({deploymentId:e,artifact:t,runtimeAssets:r,cache:u,baseUrl:m,database:c,fetchDocument:p,documentCache:f,onDocumentGraphEvent:n});return async(x,b)=>await d(x,b)??p(x,b)}};export{Zj as createGeneratedAssetResourceRuntime,qj as createPublishedAssetResourceFetch};+/*! Bundled license information:++is-buffer/index.js:+ (*!+ * Determine if an object is a Buffer+ *+ * @author Feross Aboukhadijeh <https://feross.org>+ * @license MIT+ *)+*/diff --git a/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.server.tsxindex 908255b01e..59e808545c 100644--- a/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[_route_with_symbols_]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[animations]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[animations]._index.server.tsxindex 8fd5e5c714..324b645289 100644--- a/fixtures/webstudio-features/app/__generated__/[animations]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[animations]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[assets1]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[assets1]._index.server.tsxindex 19d72d077f..3cec61be47 100644--- a/fixtures/webstudio-features/app/__generated__/[assets1]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[assets1]._index.server.tsx@@ -4,7 +4,7 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const assets_1: ResourceRequest = {name: "assets",control: "system",@@ -38,9 +38,10 @@ export const getResources = (_props: { system: System }) => {const _data = new Map<string, ResourceRequest>([["assets_1", assets_1],])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[class-names]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[class-names]._index.server.tsxindex 8fd5e5c714..324b645289 100644--- a/fixtures/webstudio-features/app/__generated__/[class-names]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[class-names]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[content-block]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[content-block]._index.server.tsxindex 8fd5e5c714..324b645289 100644--- a/fixtures/webstudio-features/app/__generated__/[content-block]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[content-block]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[duration]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[duration]._index.server.tsxindex 07a3cfbb2a..8ccd45a432 100644--- a/fixtures/webstudio-features/app/__generated__/[duration]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[duration]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[expressions]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[expressions]._index.server.tsxindex 07695cd8b1..d2f7281338 100644--- a/fixtures/webstudio-features/app/__generated__/[expressions]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[expressions]._index.server.tsx@@ -4,7 +4,7 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const jsonResourceVariable_1: ResourceRequest = {name: "jsonResourceVariable",url: "https://httpbin.org/get?hello=world",@@ -17,9 +17,10 @@ export const getResources = (_props: { system: System }) => {const _data = new Map<string, ResourceRequest>([["jsonResourceVariable_1", jsonResourceVariable_1],])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[form]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[form]._index.server.tsxindex 4c3f3c98ae..8ab770bac1 100644--- a/fixtures/webstudio-features/app/__generated__/[form]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[form]._index.server.tsx@@ -4,7 +4,7 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const action: ResourceRequest = {name: "action",url: "/custom",@@ -17,10 +17,11 @@ export const getResources = (_props: { system: System }) => {}const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([["action", action],])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[head-tag]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[head-tag]._index.server.tsxindex 8fd5e5c714..324b645289 100644--- a/fixtures/webstudio-features/app/__generated__/[head-tag]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[head-tag]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.server.tsxindex 52fd99106b..8bfd9038ef 100644--- a/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[heading-with-id]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.server.tsxindex aaaee6f246..a9d43cecfa 100644--- a/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[nested].[nested-page]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[radix]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[radix]._index.server.tsxindex 49d91d7a44..e2d727acc8 100644--- a/fixtures/webstudio-features/app/__generated__/[radix]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[radix]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[resources]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[resources]._index.server.tsxindex 0058dccf45..05d6e3c411 100644--- a/fixtures/webstudio-features/app/__generated__/[resources]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[resources]._index.server.tsx@@ -4,7 +4,7 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const list_1: ResourceRequest = {name: "list",url: "https://gist.githubusercontent.com/TrySound/56507c301ec85669db5f1541406a9259/raw/a49548730ab592c86b9e7781f5b29beec4765494/collection.json",@@ -17,9 +17,10 @@ export const getResources = (_props: { system: System }) => {const _data = new Map<string, ResourceRequest>([["list_1", list_1],])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.server.tsxindex 8fd5e5c714..324b645289 100644--- a/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/[text-duration]._index.server.tsx b/fixtures/webstudio-features/app/__generated__/[text-duration]._index.server.tsxindex 07a3cfbb2a..8ccd45a432 100644--- a/fixtures/webstudio-features/app/__generated__/[text-duration]._index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/[text-duration]._index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/__generated__/_index.server.tsx b/fixtures/webstudio-features/app/__generated__/_index.server.tsxindex 1b005258f3..09e9e94c2e 100644--- a/fixtures/webstudio-features/app/__generated__/_index.server.tsx+++ b/fixtures/webstudio-features/app/__generated__/_index.server.tsx@@ -4,12 +4,13 @@import type { PageMeta } from "@webstudio-is/sdk";import type { System, ResourceRequest } from "@webstudio-is/sdk";-export const getResources = (_props: { system: System }) => {+export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}diff --git a/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx b/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsxindex 14e31beba9..428f178f5f 100644--- a/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[_route_with_symbols_]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[animations]._index.tsx b/fixtures/webstudio-features/app/routes/[animations]._index.tsxindex c148140643..4d7a8cabe7 100644--- a/fixtures/webstudio-features/app/routes/[animations]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[animations]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[assets1]._index.tsx b/fixtures/webstudio-features/app/routes/[assets1]._index.tsxindex 8d4dc03b5c..9e7756bad4 100644--- a/fixtures/webstudio-features/app/routes/[assets1]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[assets1]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[class-names]._index.tsx b/fixtures/webstudio-features/app/routes/[class-names]._index.tsxindex 45945d1444..0308c5e763 100644--- a/fixtures/webstudio-features/app/routes/[class-names]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[class-names]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[content-block]._index.tsx b/fixtures/webstudio-features/app/routes/[content-block]._index.tsxindex 26f1edfbd9..33f448e723 100644--- a/fixtures/webstudio-features/app/routes/[content-block]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[content-block]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[duration]._index.tsx b/fixtures/webstudio-features/app/routes/[duration]._index.tsxindex 5960aa5eea..a608d788bb 100644--- a/fixtures/webstudio-features/app/routes/[duration]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[duration]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[expressions]._index.tsx b/fixtures/webstudio-features/app/routes/[expressions]._index.tsxindex 0719819103..b8d1388763 100644--- a/fixtures/webstudio-features/app/routes/[expressions]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[expressions]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[form]._index.tsx b/fixtures/webstudio-features/app/routes/[form]._index.tsxindex af34978760..0265ddf86b 100644--- a/fixtures/webstudio-features/app/routes/[form]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[form]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx b/fixtures/webstudio-features/app/routes/[head-tag]._index.tsxindex 353d2435ff..e41b127f35 100644--- a/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[head-tag]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx b/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsxindex 7babde7a97..06bbc49a55 100644--- a/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[heading-with-id]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx b/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsxindex 6c3f7cb0be..d98ea2626d 100644--- a/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[nested].[nested-page]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[radix]._index.tsx b/fixtures/webstudio-features/app/routes/[radix]._index.tsxindex 0204454424..8051d66e26 100644--- a/fixtures/webstudio-features/app/routes/[radix]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[radix]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[resources]._index.tsx b/fixtures/webstudio-features/app/routes/[resources]._index.tsxindex dd03504701..87bba1d8b4 100644--- a/fixtures/webstudio-features/app/routes/[resources]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[resources]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[sitemap.xml]._index.tsx b/fixtures/webstudio-features/app/routes/[sitemap.xml]._index.tsxindex 7f252952d7..fc038e96b5 100644--- a/fixtures/webstudio-features/app/routes/[sitemap.xml]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[sitemap.xml]._index.tsx@@ -103,6 +103,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx b/fixtures/webstudio-features/app/routes/[text-duration]._index.tsxindex 89b4a62206..e9cae60a18 100644--- a/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx+++ b/fixtures/webstudio-features/app/routes/[text-duration]._index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/fixtures/webstudio-features/app/routes/_index.tsx b/fixtures/webstudio-features/app/routes/_index.tsxindex d8fe87ddaa..eb717f372f 100644--- a/fixtures/webstudio-features/app/routes/_index.tsx+++ b/fixtures/webstudio-features/app/routes/_index.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/packages/asset-uploader/package.json b/packages/asset-uploader/package.jsonindex 41dde00db9..6b2a964f82 100644--- a/packages/asset-uploader/package.json+++ b/packages/asset-uploader/package.json@@ -40,6 +40,16 @@"./patch-assets-core.server": {"webstudio": "./src/asset-patch-core.ts","import": "./src/asset-patch-core.ts"+ },+ "./content-revision": {+ "webstudio": "./src/content-revision.ts",+ "import": "./src/content-revision.ts",+ "default": "./src/content-revision.ts"+ },+ "./content-repository": {+ "webstudio": "./src/content-repository.ts",+ "import": "./src/content-repository.ts",+ "default": "./src/content-repository.ts"}},"license": "AGPL-3.0-or-later",diff --git a/packages/asset-uploader/src/asset-repository.test.ts b/packages/asset-uploader/src/asset-repository.test.tsindex fdf62bba29..9f5be25dec 100644--- a/packages/asset-uploader/src/asset-repository.test.ts+++ b/packages/asset-uploader/src/asset-repository.test.ts@@ -379,6 +379,56 @@ describe("PostgresAssetRepository", () => {expect(dependencies.uploadFile).not.toHaveBeenCalled();});+ test("cleans up only the reserved Asset when upload completion fails", async () => {+ const dependencies = createDependencies();+ const deleteAssetByProject = vi.fn(async () => ({ error: null }));+ const deleteAssetById = vi.fn(() => ({ eq: deleteAssetByProject }));+ const deleteFileByName = vi.fn(async () => ({ error: null }));+ const client = {+ from: vi.fn((table: string) => ({+ delete: () => ({+ eq: table === "Asset" ? deleteAssetById : deleteFileByName,+ }),+ })),+ };+ const uploadContext = {+ postgrest: { client },+ } as unknown as AppContext;+ dependencies.uploadFile.mockImplementation(+ async (+ name,+ _data,+ _assetStore,+ callContext,+ _assetInfoFallback,+ _assetDataOverride,+ onUploadError+ ) => {+ await onUploadError?.(name, callContext);+ throw new Error("Storage upload failed");+ }+ );+ const repository = new PostgresAssetRepository({+ projectId: "project-1",+ context: uploadContext,+ assetStore: assetClient,+ dependencies,+ });++ await expect(+ repository.completeUpload({+ name: "post_reserved.mdx",+ data: new Blob(["post"]).stream(),+ assetInfoFallback: undefined,+ assetId: "destination-1",+ })+ ).rejects.toThrow("Storage upload failed");++ expect(deleteAssetById).toHaveBeenCalledWith("id", "destination-1");+ expect(deleteAssetByProject).toHaveBeenCalledWith("projectId", "project-1");+ expect(deleteFileByName).toHaveBeenCalledWith("name", "post_reserved.mdx");+ });+test("does not read or parse stored content during ordinary mutations", async () => {const dependencies = createDependencies();const asset = {diff --git a/packages/asset-uploader/src/asset-repository.ts b/packages/asset-uploader/src/asset-repository.tsindex 265c61fb22..ca9bd98140 100644--- a/packages/asset-uploader/src/asset-repository.ts+++ b/packages/asset-uploader/src/asset-repository.ts@@ -105,10 +105,15 @@ import {type AssetQueryPerformanceObserver,type AssetQueryPerformancePhase,} from "./query-performance";+import type { AssetContentRead as SharedAssetContentRead } from "./content-repository";type CreateId = () => Asset["id"];type RepositoryObjectStore = AssetObjectReader & Partial<AssetObjectWriter>;+export type AssetContentRead = Omit<SharedAssetContentRead, "asset"> & {+ asset: Asset;+};+type ContentBytesReference = {contentRef: string;revision: string;@@ -189,12 +194,6 @@ export class AssetIndexPreparationError extends Error {}}-export type AssetContentRead = {- asset: Asset;- data: AsyncIterable<Uint8Array>;- contentLength?: number;-};-type AssetQueryPreviewOptions = {databasePlan?: ContentCompilationPlan;diagnosticsPlan?: ContentCompilationPlan;diff --git a/packages/asset-uploader/src/canonical-metadata-backfill.ts b/packages/asset-uploader/src/canonical-metadata-backfill.tsindex ddf763acda..4b8b9ae581 100644--- a/packages/asset-uploader/src/canonical-metadata-backfill.ts+++ b/packages/asset-uploader/src/canonical-metadata-backfill.ts@@ -23,7 +23,7 @@ import type { Client } from "@webstudio-is/postgrest/index.server";import type { AssetObjectStore } from "./client";import { loadAssetFoldersByProjectWithClient } from "./folder-persistence";import { assertPostgrestSuccess } from "./patch-utils";-import { isContentHash } from "./content-hash";+import { createAssetContentRevision } from "./content-revision";import {deleteCanonicalAssetFileEntryIfMatches,deleteInvalidCanonicalAssetFileEntryIfMatches,@@ -46,21 +46,6 @@ export type CanonicalAssetSynchronizationIssue = {const getErrorMessage = (error: unknown) =>error instanceof Error ? error.message : "Unknown asset indexing failure";-const createAssetContentRevision = ({- storageName,- updatedAt,- size,- contentHash,-}: {- storageName: string;- updatedAt: string;- size: number;- contentHash?: string | null;-}) =>- isContentHash(contentHash)- ? `sha256:${contentHash}`- : `file:${encodeURIComponent(storageName)}:${updatedAt}:${size}`;-type UploadedAssetRow = {id: string;projectId: string;diff --git a/packages/asset-uploader/src/content-repository.ts b/packages/asset-uploader/src/content-repository.tsnew file mode 100644index 0000000000..a3b3f1ad75--- /dev/null+++ b/packages/asset-uploader/src/content-repository.ts@@ -0,0 +1,160 @@+import type { Asset } from "@webstudio-is/sdk";+import { contentEngineLimits } from "@webstudio-is/content-engine/limits";+import {+ readableStreamToAsyncIterable,+ readBoundedBytes,+} from "@webstudio-is/content-engine/compiler";++export type AssetContentDescriptor = Pick<+ Asset,+ | "id"+ | "projectId"+ | "name"+ | "type"+ | "format"+ | "size"+ | "createdAt"+ | "updatedAt"+>;++export type AssetContentRead = {+ asset: AssetContentDescriptor;+ data: AsyncIterable<Uint8Array>;+ contentLength?: number;+};++export interface AssetContentRepository {+ readContent(input: {+ assetId: Asset["id"];+ range?: { offset: number; length: number };+ }): Promise<AssetContentRead>;+ updateContent(input: {+ assetId: Asset["id"];+ expectedName: string;+ data: ReadableStream<Uint8Array>;+ }): Promise<AssetContentDescriptor>;+}++export class AssetRevisionConflictError extends Error {}++export class AssetContentAuthorizationError extends Error {}++const cancelBody = async (response: Response) => {+ try {+ await response.body?.cancel();+ } catch {+ // Keep the protocol failure that required cancellation.+ }+};++const mapError = (error: unknown): never => {+ const status =+ typeof error === "object" && error !== null && "status" in error+ ? error.status+ : undefined;+ if (status === 401 || status === 403) {+ throw new AssetContentAuthorizationError(+ "This Asset is not authorized for content access",+ { cause: error }+ );+ }+ if (status === 409) {+ throw new AssetRevisionConflictError(+ "This file changed since it was opened. Reload it before saving again.",+ { cause: error }+ );+ }+ throw error;+};++export const createHttpAssetContentRepository = ({+ projectId,+ read,+ update,+ parseAsset,+}: {+ projectId: string;+ read: (input: {+ assetId: string;+ range?: { offset: number; length: number };+ }) => Promise<Response>;+ update: (input: {+ assetId: string;+ expectedName: string;+ data: Uint8Array;+ }) => Promise<AssetContentDescriptor>;+ parseAsset: (response: Response) => AssetContentDescriptor;+}): AssetContentRepository => ({+ readContent: async ({ assetId, range }) => {+ try {+ const response = await read({ assetId, range });+ const expectedStatus = range === undefined ? 200 : 206;+ if (response.status !== expectedStatus) {+ await cancelBody(response);+ throw Object.assign(+ new Error(+ `Asset content response has unexpected status ${response.status}`+ ),+ { status: response.status }+ );+ }+ let asset: AssetContentDescriptor;+ try {+ asset = parseAsset(response);+ } catch (error) {+ await cancelBody(response);+ throw error;+ }+ if (asset.id !== assetId || asset.projectId !== projectId) {+ await cancelBody(response);+ throw new Error(+ "Asset content response does not match the requested Asset"+ );+ }+ if (+ range === undefined &&+ asset.size > contentEngineLimits.hydratedFileBytes+ ) {+ await cancelBody(response);+ throw new Error("Asset content exceeds the MDX editing limit");+ }+ if (response.body === null) {+ throw new Error("Asset content response has no body");+ }+ const contentLengthHeader = response.headers.get("content-length");+ const contentLength =+ contentLengthHeader === null ? undefined : Number(contentLengthHeader);+ if (+ contentLength !== undefined &&+ (Number.isSafeInteger(contentLength) === false || contentLength < 0)+ ) {+ await cancelBody(response);+ throw new Error("Asset content response has an invalid content length");+ }+ return {+ asset,+ data: readableStreamToAsyncIterable(response.body),+ contentLength,+ };+ } catch (error) {+ return mapError(error);+ }+ },+ updateContent: async ({ assetId, expectedName, data }) => {+ try {+ const bytes = await readBoundedBytes(+ readableStreamToAsyncIterable(data),+ contentEngineLimits.hydratedFileBytes+ );+ const descriptor = await update({ assetId, expectedName, data: bytes });+ if (descriptor.id !== assetId || descriptor.projectId !== projectId) {+ throw new Error(+ "Asset content update does not match the requested Asset"+ );+ }+ return descriptor;+ } catch (error) {+ return mapError(error);+ }+ },+});diff --git a/packages/asset-uploader/src/content-revision.ts b/packages/asset-uploader/src/content-revision.tsnew file mode 100644index 0000000000..97d1ad94c1--- /dev/null+++ b/packages/asset-uploader/src/content-revision.ts@@ -0,0 +1,16 @@+import { isContentHash } from "./content-hash";++export const createAssetContentRevision = ({+ storageName,+ updatedAt,+ size,+ contentHash,+}: {+ storageName: string;+ updatedAt: string;+ size: number;+ contentHash?: string | null;+}) =>+ isContentHash(contentHash)+ ? `sha256:${contentHash}`+ : `file:${encodeURIComponent(storageName)}:${updatedAt}:${size}`;diff --git a/packages/asset-uploader/src/markdown-to-mdx.test.ts b/packages/asset-uploader/src/markdown-to-mdx.test.tsnew file mode 100644index 0000000000..51a6108bb7--- /dev/null+++ b/packages/asset-uploader/src/markdown-to-mdx.test.ts@@ -0,0 +1,230 @@+import { describe, expect, test, vi } from "vitest";+import { contentEngineLimits } from "@webstudio-is/content-engine";+import type { FileAsset } from "@webstudio-is/sdk";+import {+ convertMarkdownAssetToMdx,+ type MarkdownAssetConversionRepository,+} from "./markdown-to-mdx";++const encoder = new TextEncoder();+const decoder = new TextDecoder();++const createAsset = (overrides: Partial<FileAsset> = {}): FileAsset => ({+ id: "source",+ projectId: "project",+ type: "file",+ name: "post_source.md",+ filename: "post",+ format: "text/markdown",+ size: 7,+ meta: {},+ description: null,+ folderId: "articles",+ createdAt: "2026-08-14T00:00:00.000Z",+ ...overrides,+});++const readStream = async (stream: ReadableStream<Uint8Array>) => {+ const chunks: Uint8Array[] = [];+ let length = 0;+ for await (const chunk of stream) {+ chunks.push(chunk);+ length += chunk.byteLength;+ }+ const bytes = new Uint8Array(length);+ let offset = 0;+ for (const chunk of chunks) {+ bytes.set(chunk, offset);+ offset += chunk.byteLength;+ }+ return decoder.decode(bytes);+};++const createRepository = ({+ source = "# Hello",+ asset = createAsset(),+}: {+ source?: string | Uint8Array;+ asset?: FileAsset;+} = {}) => {+ let upload = 0;+ const uploadedSources: string[] = [];+ const readContent = vi.fn(async () => ({+ asset,+ data: {+ async *[Symbol.asyncIterator]() {+ yield typeof source === "string" ? encoder.encode(source) : source;+ },+ },+ contentLength:+ typeof source === "string"+ ? encoder.encode(source).byteLength+ : source.byteLength,+ }));+ const createUploadTicket = vi.fn(async () => {+ upload += 1;+ return {+ assetId: `destination-${upload}`,+ name: `post_${upload}.mdx`,+ deduplicated: false as const,+ };+ });+ const completeUpload = vi.fn(+ async ({+ name,+ data,+ assetId,+ }: Parameters<MarkdownAssetConversionRepository["completeUpload"]>[0]) => {+ const uploadedSource = await readStream(data);+ uploadedSources.push(uploadedSource);+ return createAsset({+ id: assetId,+ name,+ filename: "post",+ format: "mdx",+ size: encoder.encode(uploadedSource).byteLength,+ });+ }+ );+ return {+ repository: {+ readContent,+ createUploadTicket,+ completeUpload,+ } satisfies MarkdownAssetConversionRepository,+ readContent,+ createUploadTicket,+ completeUpload,+ uploadedSources,+ };+};++describe("convertMarkdownAssetToMdx", () => {+ test("creates a separate MDX Asset after conversion succeeds", async () => {+ const {+ repository,+ readContent,+ createUploadTicket,+ completeUpload,+ uploadedSources,+ } = createRepository({+ source: "---\ntitle: Post\n---\n# Hello\n",+ });++ const result = await convertMarkdownAssetToMdx({+ repository,+ sourceAssetId: "source",+ });++ expect(readContent).toHaveBeenCalledWith({ assetId: "source" });+ expect(createUploadTicket).toHaveBeenCalledWith({+ type: "text/mdx",+ filename: "post.mdx",+ displayFilename: "post",+ description: undefined,+ folderId: "articles",+ });+ expect(completeUpload).toHaveBeenCalledWith({+ name: "post_1.mdx",+ data: expect.any(ReadableStream),+ assetInfoFallback: undefined,+ assetId: "destination-1",+ });+ expect(result.sourceAsset.id).toBe("source");+ expect(result.asset).toMatchObject({+ id: "destination-1",+ name: "post_1.mdx",+ format: "mdx",+ });+ expect(result.preview.document.frontmatter.properties).toEqual({+ title: "Post",+ });+ expect(uploadedSources).toEqual([result.preview.source]);+ });++ test("allocates a new destination on repeated conversion", async () => {+ const { repository, createUploadTicket } = createRepository();++ const first = await convertMarkdownAssetToMdx({+ repository,+ sourceAssetId: "source",+ });+ const second = await convertMarkdownAssetToMdx({+ repository,+ sourceAssetId: "source",+ });++ expect(first.asset.id).toBe("destination-1");+ expect(second.asset.id).toBe("destination-2");+ expect(createUploadTicket).toHaveBeenCalledTimes(2);+ });++ test("does not reserve a destination when conversion cannot start", async () => {+ const { repository, createUploadTicket, completeUpload } = createRepository(+ {+ asset: createAsset({ name: "post_source.mdx", format: "text/mdx" }),+ }+ );++ await expect(+ convertMarkdownAssetToMdx({+ repository,+ sourceAssetId: "source",+ })+ ).rejects.toThrow("Only Markdown Assets can be converted to MDX");+ expect(createUploadTicket).not.toHaveBeenCalled();+ expect(completeUpload).not.toHaveBeenCalled();+ });++ test("does not reserve a destination when source validation fails", async () => {+ const { repository, createUploadTicket, completeUpload } = createRepository(+ {+ source: "x".repeat(contentEngineLimits.hydratedFileBytes + 1),+ }+ );++ await expect(+ convertMarkdownAssetToMdx({+ repository,+ sourceAssetId: "source",+ })+ ).rejects.toMatchObject({ code: "CONTENT_LIMIT_EXCEEDED" });+ expect(createUploadTicket).not.toHaveBeenCalled();+ expect(completeUpload).not.toHaveBeenCalled();+ });++ test("uses the shared Markdown UTF-8 validation", async () => {+ const { repository, createUploadTicket, completeUpload } = createRepository(+ {+ source: new Uint8Array([0xff]),+ }+ );++ await expect(+ convertMarkdownAssetToMdx({+ repository,+ sourceAssetId: "source",+ })+ ).rejects.toMatchObject({ code: "CONTENT_DECODING_FAILED" });+ expect(createUploadTicket).not.toHaveBeenCalled();+ expect(completeUpload).not.toHaveBeenCalled();+ });++ test("pins completion cleanup to the newly reserved Asset", async () => {+ const { repository, completeUpload } = createRepository();+ completeUpload.mockRejectedValueOnce(new Error("storage unavailable"));++ await expect(+ convertMarkdownAssetToMdx({+ repository,+ sourceAssetId: "source",+ })+ ).rejects.toThrow("storage unavailable");+ expect(completeUpload).toHaveBeenCalledWith({+ name: "post_1.mdx",+ data: expect.any(ReadableStream),+ assetInfoFallback: undefined,+ assetId: "destination-1",+ });+ });+});diff --git a/packages/asset-uploader/src/markdown-to-mdx.ts b/packages/asset-uploader/src/markdown-to-mdx.tsnew file mode 100644index 0000000000..0804bca78b--- /dev/null+++ b/packages/asset-uploader/src/markdown-to-mdx.ts@@ -0,0 +1,58 @@+import { parseMarkdownDocumentSource } from "@webstudio-is/content-engine";+import {+ previewMarkdownToMdxConversion,+ type MarkdownToMdxConversionPreview,+} from "@webstudio-is/content-engine/mdx-conversion";+import { getAssetDisplayNameParts, type Asset } from "@webstudio-is/sdk";+import type { AssetRepository } from "./asset-repository";++export type MarkdownAssetConversionRepository = Pick<+ AssetRepository,+ "readContent" | "createUploadTicket" | "completeUpload"+>;++export type MarkdownAssetConversionResult = Readonly<{+ sourceAsset: Asset;+ asset: Asset;+ preview: MarkdownToMdxConversionPreview;+}>;++/** Validates and converts a Markdown Asset before reserving a separate MDX Asset. */+export const convertMarkdownAssetToMdx = async ({+ repository,+ sourceAssetId,+}: {+ repository: MarkdownAssetConversionRepository;+ sourceAssetId: Asset["id"];+}): Promise<MarkdownAssetConversionResult> => {+ const { asset: sourceAsset, data } = await repository.readContent({+ assetId: sourceAssetId,+ });+ const { basename, ext } = getAssetDisplayNameParts(sourceAsset);+ if (sourceAsset.type !== "file" || ext.toLowerCase() !== "md") {+ throw new Error("Only Markdown Assets can be converted to MDX");+ }++ const markdown = await parseMarkdownDocumentSource({ source: data });+ const preview = await previewMarkdownToMdxConversion({+ source: markdown.source,+ });+ const ticket = await repository.createUploadTicket({+ type: "text/mdx",+ filename: `${basename}.mdx`,+ displayFilename: basename,+ description: sourceAsset.description ?? undefined,+ folderId: sourceAsset.folderId,+ });+ if (ticket.deduplicated) {+ throw new Error("MDX conversion must create a separate Asset");+ }++ const asset = await repository.completeUpload({+ name: ticket.name,+ data: new Blob([preview.source]).stream(),+ assetInfoFallback: undefined,+ assetId: ticket.assetId,+ });+ return { sourceAsset, asset, preview };+};diff --git a/packages/asset-uploader/src/publication.test.ts b/packages/asset-uploader/src/publication.test.tsindex 5a54e66d73..c9fdff8a29 100644--- a/packages/asset-uploader/src/publication.test.ts+++ b/packages/asset-uploader/src/publication.test.ts@@ -93,4 +93,44 @@ describe("published asset data", () => {expect(prepareIndex).toHaveBeenCalledTimes(2);expect(loadAssetDataByProject).toHaveBeenCalledTimes(4);});++ test("recompiles and validates bounded dynamic publication dependencies", async () => {+ const preliminaryArtifact = { documents: [{ _id: "post" }] } as never;+ const finalArtifact = {+ documents: [{ _id: "post" }, { _id: "article.mdx" }],+ } as never;+ const initialPlan = { queries: [{ id: "posts" }] } as never;+ const resolvedPlan = {+ queries: [{ id: "posts" }, { id: "mdx:article" }],+ } as never;+ const prepareIndex = vi+ .fn()+ .mockResolvedValueOnce(preliminaryArtifact)+ .mockResolvedValueOnce(finalArtifact);+ const resolvePlan = vi.fn(() => resolvedPlan);+ const assetData = { assets: [], assetFolders: [] };++ const result = await preparePublishedAssetData(+ {+ projectId: "project-1",+ context: {} as never,+ assetStore: {} as never,+ contentDatabaseMaxBytes: 512_000,+ plan: initialPlan,+ retainedAssetIds: [],+ resolvePlan,+ },+ {+ createRepository: vi.fn(() => ({ prepareIndex })),+ loadAssetDataByProject: vi.fn().mockResolvedValue(assetData),+ } as never+ );++ expect(result.artifact).toBe(finalArtifact);+ expect(prepareIndex.mock.calls).toEqual([[initialPlan], [resolvedPlan]]);+ expect(resolvePlan.mock.calls).toEqual([+ [preliminaryArtifact],+ [finalArtifact],+ ]);+ });});diff --git a/packages/asset-uploader/src/publication.ts b/packages/asset-uploader/src/publication.tsindex 24b795a39d..a6a78de071 100644--- a/packages/asset-uploader/src/publication.ts+++ b/packages/asset-uploader/src/publication.ts@@ -1,6 +1,7 @@import {getContentArtifactRuntimeAssetIds,type ContentCompilationPlan,+ type ContentArtifactV1,} from "@webstudio-is/content-engine";import type { Asset } from "@webstudio-is/sdk";import type { AppContext } from "@webstudio-is/trpc-interface/index.server";@@ -23,6 +24,7 @@ export const preparePublishedAssetData = async (contentDatabaseMaxBytes,plan,retainedAssetIds,+ resolvePlan,}: {projectId: string;context: AppContext;@@ -30,6 +32,9 @@ export const preparePublishedAssetData = async (contentDatabaseMaxBytes: number;plan: ContentCompilationPlan;retainedAssetIds: Iterable<string>;+ resolvePlan?: (+ artifact: ContentArtifactV1+ ) => ContentCompilationPlan | Promise<ContentCompilationPlan>;},dependencies = defaultDependencies) => {@@ -44,7 +49,23 @@ export const preparePublishedAssetData = async (projectId,context);- const artifact = await repository.prepareIndex(plan);+ let artifact = await repository.prepareIndex(plan);+ if (resolvePlan !== undefined) {+ let resolvedPlan = await resolvePlan(artifact);+ for (let dependencyPass = 0; dependencyPass < 20; dependencyPass += 1) {+ artifact = await repository.prepareIndex(resolvedPlan);+ const validatedPlan = await resolvePlan(artifact);+ if (JSON.stringify(resolvedPlan) === JSON.stringify(validatedPlan)) {+ break;+ }+ if (dependencyPass === 19) {+ throw new Error(+ "Dynamic MDX dependency closure exceeds the safe publication depth"+ );+ }+ resolvedPlan = validatedPlan;+ }+ }const assetDataAfter = await dependencies.loadAssetDataByProject(projectId,contextdiff --git a/packages/asset-uploader/src/revision.ts b/packages/asset-uploader/src/revision.tsindex b2ce16388e..6e45b58c6c 100644--- a/packages/asset-uploader/src/revision.ts+++ b/packages/asset-uploader/src/revision.ts@@ -15,8 +15,8 @@ import { createUniqueAssetFilename } from "./utils/get-unique-filename";import { sanitizeS3Key } from "./utils/sanitize-s3-key";import { formatAsset } from "./utils/format-asset";import { assertPostgrestSuccess } from "./patch-utils";--export class AssetRevisionConflictError extends Error {}+export { AssetRevisionConflictError } from "./content-repository";+import { AssetRevisionConflictError } from "./content-repository";const getRevisionFilename = ({name,diff --git a/packages/asset-uploader/src/server.ts b/packages/asset-uploader/src/server.tsindex 3bb26c4d70..d037d200e9 100644--- a/packages/asset-uploader/src/server.ts+++ b/packages/asset-uploader/src/server.ts@@ -9,6 +9,7 @@ export * from "./patch";export * from "./asset-patch-core";export * from "./folder-persistence";export * from "./revision";+export * from "./markdown-to-mdx";export * from "./field-catalog";export * from "./query-preview";export * from "./query-performance";diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex 613e37e6af..5bf6b88991 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -23,7 +23,7 @@"scripts": {"typecheck": "tsc --noEmit","generate-docs": "tsx scripts/generate-docs.ts && oxfmt src/docs.generated.ts",- "build:content-runtime": "esbuild @webstudio-is/content-engine/runtime --bundle --format=esm --platform=browser --target=es2022 --conditions=webstudio --minify --outfile=lib/content-runtime.js",+ "build:content-runtime": "esbuild @webstudio-is/content-engine/runtime --bundle --format=esm --platform=browser --target=es2022 --conditions=webstudio,worker --minify --outfile=lib/content-runtime.js","fixtures:build": "pnpm build:content-runtime","build": "pnpm generate-docs && rm -rf lib && vite build && pnpm build:content-runtime","pretest": "mkdir -p lib && pnpm build:content-runtime",@@ -95,6 +95,7 @@"@types/yargs": "^17.0.33","@vercel/react-router": "^1.1.0","@vitejs/plugin-react": "^4.4.1",+ "@webstudio-is/asset-uploader": "workspace:*","@webstudio-is/css-engine": "workspace:*","@webstudio-is/content-engine": "workspace:*","@webstudio-is/expression": "workspace:*",diff --git a/packages/cli/src/commands/mcp.test.ts b/packages/cli/src/commands/mcp.test.tsindex 0527b25e7c..468191c833 100644--- a/packages/cli/src/commands/mcp.test.ts+++ b/packages/cli/src/commands/mcp.test.ts@@ -144,7 +144,9 @@ test("keeps every MCP API tool aligned with its public API contract", () => {const schema = getDetailedProjectSessionMcpInputSchema(tool);const transportFields = [- ...(operation.method === "mutation" && operation.localCapable+ ...(operation.method === "mutation" &&+ operation.localCapable &&+ operation.inputFields.includes("dryRun") === false? ["dryRun"]: []),...(operation.requiresConfirm && operation.localCapable@@ -165,7 +167,11 @@ test("keeps every MCP API tool aligned with its public API contract", () => {const isRepresentationOverride =(operation.command === "insert-fragment" &&["parentInstanceId", "fragment"].includes(field)) ||- (operation.command === "insert-collection" && field === "itemFragment");+ (operation.command === "insert-collection" &&+ field === "itemFragment") ||+ (field === "dryRun" &&+ operation.method === "mutation" &&+ operation.localCapable);if (isRepresentationOverride) {continue;}diff --git a/packages/cli/src/commands/schema.test.ts b/packages/cli/src/commands/schema.test.tsindex 0ef2be5211..31d63e6f3d 100644--- a/packages/cli/src/commands/schema.test.ts+++ b/packages/cli/src/commands/schema.test.ts@@ -249,6 +249,7 @@ test("prints full mcp tool input schemas when requested", () => {"contentMode","mode","insertIndex",+ "templateNameConfirmation","dryRun",]);const fragmentSchema = insertFragmentTool.inputSchema.properties.fragment;diff --git a/packages/cli/src/content-engine-reference.ts b/packages/cli/src/content-engine-reference.tsindex 3610008faf..bf7f01205f 100644--- a/packages/cli/src/content-engine-reference.ts+++ b/packages/cli/src/content-engine-reference.ts@@ -80,7 +80,7 @@ const contentRows = [},{value: "markdown-body-ref",- description: `Stores a reference to a Markdown body. Webstudio filters and paginates first, then reads only the selected bodies from Assets. \`maxBytes\` defaults to ${formatBytes(contentEngineLimits.hydratedFileBytes)} and cannot be set higher. The query fails if a selected source file is larger.`,+ description: `Stores a reference to a Markdown or MDX body. Webstudio filters and paginates first, then reads only the selected bodies from Assets. \`maxBytes\` defaults to ${formatBytes(contentEngineLimits.hydratedFileBytes)} and cannot be set higher. The query fails if a selected source file is larger.`,},] as const satisfies readonly ReferenceRow[];@@ -127,6 +127,9 @@ const documentedLimitKeys = ["jsonStringBytes","indexedPropertiesBytes","excerptBytes",+ "mdxDepth",+ "mdxNodes",+ "mdxProps","hydratedFileBytes","hydratedTotalBytes","hydratedFileCount",@@ -268,6 +271,9 @@ const contentLimitsTable = table({formatBytes(contentEngineLimits.indexedPropertiesBytes),],["Generated excerpt", formatBytes(contentEngineLimits.excerptBytes)],+ ["MDX nesting depth", String(contentEngineLimits.mdxDepth)],+ ["MDX nodes", String(contentEngineLimits.mdxNodes)],+ ["MDX JSX props", String(contentEngineLimits.mdxProps)],["Loaded file", formatBytes(contentEngineLimits.hydratedFileBytes)],["Loaded content per query",@@ -294,7 +300,31 @@ export const renderContentEngineReferenceMarkdown = ({return [`${"#".repeat(headingLevel)} Content Engine reference`,"",- "Assets resources query Markdown and JSON files stored in the Assets panel. The Builder and Webstudio MCP use the same structured query contract.",+ "Assets resources query Markdown, MDX, and JSON files stored in the Assets panel. The Builder and Webstudio MCP use the same structured query contract.",+ "",+ heading(1, "Document formats"),+ "",+ "Content Engine indexes frontmatter from both `.md` and `.mdx` files and can return either body with `markdown-body-ref`. Their body grammars remain different:",+ "",+ table({+ headings: ["Extension", "Body behavior"],+ rows: [+ [+ "`.md`",+ "Standard Markdown, including its normal embedded HTML behavior. It is not an editable Content Block source.",+ ],+ [+ "`.mdx`",+ "Safe MDX: Markdown plus restricted `<ws.element>` JSX. It can be an editable Content Block source.",+ ],+ [+ "`.json`",+ "A JSON object whose root fields are indexed under `properties`.",+ ],+ ],+ }),+ "",+ "Do not treat `.md` and `.mdx` as equivalent extensions. Use the Content Block conversion preview to create a new `.mdx` file from Markdown; unsupported or unsafe HTML is skipped and reported, and the original file remains unchanged.","",heading(1, "MCP workflow"),"",@@ -310,7 +340,7 @@ export const renderContentEngineReferenceMarkdown = ({"",heading(1, "Fields"),"",- "Every asset has the standard fields below. Markdown frontmatter and JSON root fields appear under `properties`, for example `properties.slug` or `properties.author.name`. The field catalog reports their observed types, occurrence counts, optionality, and mixed-type state. A JSON content file must contain an object at its root.",+ "Every asset has the standard fields below. Markdown and MDX frontmatter and JSON root fields appear under `properties`, for example `properties.slug` or `properties.author.name`. The field catalog reports their observed types, occurrence counts, optionality, and mixed-type state. A JSON content file must contain an object at its root.","",standardFieldsTable,"",@@ -364,7 +394,7 @@ export const renderContentEngineReferenceMarkdown = ({"",renderRows(contentRows),"",- "Returned content has `encoding` and `text`. A range also reports its `offset`, returned `length`, and total file size. Use `markdown-body-ref` for article pages. It keeps article bodies out of the published content database and resolves relative Markdown links when the selected body is loaded.",+ "Returned content has `encoding` and `text`. A range also reports its `offset`, returned `length`, and total file size. Use `markdown-body-ref` for article pages. It keeps Markdown and MDX bodies out of the published content database and resolves their relative links when the selected body is loaded.","",heading(1, "Preview diagnostics"),"",@@ -390,7 +420,7 @@ export const renderContentEngineReferenceMarkdown = ({'{ "$ref": "<relative-path>[#<fragment>]" }',"```","",- "Markdown references can appear in YAML frontmatter. JSON references can appear anywhere in the document. Either format can reference Markdown or JSON. References do not run inside a Markdown body.",+ "Markdown and MDX references can appear in YAML frontmatter. JSON references can appear anywhere in the document. Any format can reference Markdown, MDX, or JSON. References do not run inside a Markdown or MDX body.","",table({headings: ["Reference", "Inserted value"],diff --git a/packages/cli/src/docs.generated.ts b/packages/cli/src/docs.generated.tsindex 796c67f197..5457c5bd5a 100644--- a/packages/cli/src/docs.generated.ts+++ b/packages/cli/src/docs.generated.ts@@ -8,7 +8,7 @@ export const cliDocs = {"manual-llm":'# Webstudio CLI Manual for LLMs\n\nUse this order. Stop only when a command returns ok:false.\n\nIf you are inside the Webstudio monorepo, the first command discovery should use\nthe local CLI exactly as `node packages/cli/local.js ...` from the repo root. Do\nnot use `packages/cli/bin.js` for local source-tree work; it is the packaged\nbuild entry and may use stale built output. Do not use `pnpm exec webstudio`,\n`pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can\nresolve an older binary.\n\nFor delegated design-system or “use every component” tasks, skip the generic warm-up sequence and start with exactly one MCP command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`. Report that returned checkpoint to the parent/user and stop until continued.\n\n## Use MCP locally or optionally connect a client\n\nDo not install, register, or connect an MCP server merely because the user asks\nyou to edit a Webstudio project. If Webstudio MCP tools are already available,\nuse them. If you have shell access, use the local CLI shortcuts such as\n`webstudio meta.index` and `webstudio list-pages`; they expose the same project\noperations without changing client configuration or restarting the app.\n\nOnly when the user explicitly asks for persistent native MCP integration, run\nthe command for their client:\n\n- Claude Code: `webstudio connect claude`\n- Codex: `webstudio connect codex`\n- Cursor: `webstudio connect cursor`\n- VS Code or GitHub Copilot: `webstudio connect vscode`\n\nRun project operations from the linked project root. If the folder is not\nlinked, ask for an editable Builder share link and run\n`webstudio init --link <share-link> --json`. You can then use local CLI\nshortcuts immediately. Do not run `webstudio sync`, `webstudio connect`, or\nrestart the app unless the user specifically wants native MCP registration:\nMCP reads and edits the latest editable Builder build directly, including for\nprojects that have never been published. Treat the share link as a credential\nand do not include it in committed files, logs, screenshots, or issue reports.\n\nThe optional `connect` command verifies project access before changing client configuration. For\nClaude Code, Cursor, and VS Code it safely merges the `webstudio` server into\nthe client\'s project configuration. For Codex it runs both `codex mcp add` and\n`codex mcp get webstudio`; do not repeat those commands separately. Follow the\nreload, restart, or approval instruction printed by `connect`, then verify the\nloaded MCP connection by asking the client to use Webstudio MCP and list the\nproject pages. Use `--print` only to inspect the generated setup without\nchanging configuration or requiring project access.\n\n## Always\n\n1. webstudio permissions --json\n2. For bounded shell workflows, call MCP tools directly through the CLI shortcut, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and useful when you need to make the MCP boundary obvious. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for multiple calls in one shared CLI session. Use a normal JSON file path for large batches. Use long-running `webstudio mcp` only when your environment is a real MCP client. Do not manually send raw JSON-RPC to `webstudio mcp` from a shell or PTY.\n3. Read MCP `meta.index`, for example `webstudio meta.index`.\n4. Use focused MCP calls with concrete JSON: `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.coverage-plan`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`.\n5. Read overview resources `webstudio://project/tools-overview` or `webstudio://project/components-overview` when useful. Read full resources `webstudio://project/tools` or `webstudio://project/components` only when focused tools are insufficient.\n6. Pick focused MCP read tool.\n7. Pick semantic MCP write tool.\n\nUse `webstudio schema mcp` for a compact MCP tool overview. Add `--verbose` only when exact input schemas for all tools are truly needed; otherwise prefer focused `meta.get-more-tools` and `components.*` calls.\n\nRun these commands from the linked project root. Use the MCP startup status line\'s absolute root for local files; write temporary scripts and artifacts under `<project root>/.temp`, not under a parent workspace.\n\nMonorepo quick path for a simple styled section:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nSave the readable payload in `.temp/insert-fragment.json`:\n\n```json\n{\n "parentInstanceId": "parent-id",\n "fragment": "<ws.element ws:tag=\'section\' ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag=\'h2\'>Launch Kit</ws.element><ws.element ws:tag=\'p\'>A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag=\'button\'>Get started</ws.element></ws.element>"\n}\n```\n\nSingle quotes inside the JSX keep the JSON valid without backslash-escaped attributes. The same local shortcut form is shorter and preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nFor this simple path, do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only to get the target `parentInstanceId`.\n\nWhen authoring JSX for `insert-fragment`, use Webstudio component helpers and Webstudio style syntax. Use `ws:style={css\\`...\\`}`for Webstudio-native CSS. For simpler cases, use React-style object syntax such as`style={{ padding: 24 }}`. Both forms create editable Webstudio style data.\n\nWhen the task says another user will edit a page in Content mode, use a Content Block (`ws:block`) around every editable region. Content-mode users can edit text and supported props only in descendants of that block; content outside it is read-only. Put reusable insertable options in the block\'s `ws:block-template` child. Do not put intended editor content inside that template container: templates are protected source material, while an inserted template copy becomes an editable direct child of the Content Block. Verify this structure before handoff.\n\nDo not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`. JSX fragments are declarative project data; use the built-in Webstudio helpers instead.\n\nUse Webstudio prop names in JSX: `class`, `for`, `aria-label`, and other HTML/Webstudio names. Do not use React-only aliases such as `className` or `htmlFor`; the runtime rejects them with the Webstudio prop name to use.\n\nUse Webstudio actions for event/action props. Do not pass JavaScript functions such as `onClick={() => ...}`; the runtime rejects them because functions cannot be persisted as Webstudio project data.\n\n```tsx\n<ws.element\n ws:tag="button"\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n>\n Open\n</ws.element>\n```\n\nPlain JSX prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n\nIf a component has a registered template with required parts, JSX must include those parts explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want Webstudio to apply one component template automatically.\n\n## Animation Components\n\nBefore creating animation examples, inspect the exact components with focused discovery:\n\n```sh\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateChildren"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateText"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:StaggerAnimation"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:VideoAnimation"}\'\n```\n\nUse Animation Group (`AnimateChildren`) as the controller. Put normal instances directly inside it, or put Text Animation, Stagger Animation, or Video Animation directly inside it. Text, Stagger, and Video are helper components with `contentModel.category: "none"` and should not be used as standalone section roots.\n\nDefine timing and CSS changes on the Animation Group `action` prop. Use `type:"view"` for viewport entry/exit progress and `type:"scroll"` for scroll-progress timelines. For in animations, keep the canvas styles as the final state and use `fill:"backwards"` with keyframes that describe the starting state. For out animations, use `fill:"forwards"` with keyframes that describe the ending state.\n\nText Animation settings: `slidingWindow` defaults to `5`, `easing` defaults to `linear`, and `splitBy` defaults to `char`. Use `splitBy:"space"` for word-by-word animation. The parent Animation Group keyframes provide the actual opacity, translate, scale, or other styles.\n\nStagger Animation settings: `slidingWindow` defaults to `1` and `easing` defaults to `linear`. It applies parent Animation Group progress across its direct children. Use `slidingWindow:0` for instant sequential steps, `1` for one child at a time, and values above `1` for overlapping waves.\n\nVideo Animation settings: `timeline` is a boolean. Prefer `insert-component` for Video Animation so the Video child template is inserted, then configure the Video child asset/source. Use short, seek-friendly videos for smooth scroll-linked playback.\n\nUse JSX fragments for authored animation structures when you need styled, editable examples. Put the final visual state in `ws:style` and put the starting or ending animated state in the Animation Group `action` keyframes. Include an explicit `offset` on every keyframe: use `offset: 0` for starting-state keyframes with `fill:"backwards"` and `offset: 1` for ending-state keyframes with `fill:"forwards"`.\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n axis: "block",\n animations: [\n {\n name: "Fade up on entry",\n timing: {\n fill: "backwards",\n rangeStart: ["entry", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["entry", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 24, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n ],\n }}\n>\n <ws.element\n ws:tag="section"\n ws:style={css`\n display: grid;\n gap: 16px;\n padding: 48px;\n border-radius: 24px;\n background: #111827;\n color: white;\n `}\n >\n <ws.element ws:tag="h2">Launch metrics</ws.element>\n <ws.element ws:tag="p">\n A polished card that fades up as it enters the viewport.\n </ws.element>\n </ws.element>\n</animation.AnimateChildren>\n```\n\nFor Text Animation, keep `animation.AnimateText` as the direct child of Animation Group and place the text-containing element inside it:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Parallax In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 100, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Opacity In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n {\n name: "Scale In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Parallax Out",\n timing: {\n fill: "forwards",\n rangeStart: ["cover", { type: "unit", value: 50, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 1,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: -100, unit: "px" },\n ],\n },\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n insetStart: { type: "unit", value: 5, unit: "%" },\n insetEnd: { type: "unit", value: 5, unit: "%" },\n isPinned: true,\n }}\n>\n <animation.AnimateText\n splitBy="space"\n slidingWindow={5}\n easing="easeOutQuart"\n >\n <ws.element ws:tag="h2">Animate words with controlled rhythm</ws.element>\n </animation.AnimateText>\n</animation.AnimateChildren>\n```\n\nFor Stagger Animation, put the repeated cards or rows directly inside `animation.StaggerAnimation`:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n timing: {\n fill: "backwards",\n rangeStart: ["contain", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["contain", { type: "unit", value: 30, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n }}\n>\n <animation.StaggerAnimation>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Plan\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Build\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Launch\n </ws.element>\n </animation.StaggerAnimation>\n</animation.AnimateChildren>\n```\n\nFor Video Animation, use the registered template via `insert-component` when possible. If you author JSX, include the Video child explicitly:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Video progress",\n timing: {\n fill: "both",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [{ offset: 0, styles: {} }],\n },\n ],\n }}\n>\n <animation.VideoAnimation timeline={true}>\n <$.Video\n preload="auto"\n autoPlay={true}\n muted={true}\n playsInline={true}\n crossOrigin="anonymous"\n />\n </animation.VideoAnimation>\n</animation.AnimateChildren>\n```\n\n## Command Surface Boundary\n\n- Use top-level `webstudio ...` shell commands for setup, sync/import/build/preview/screenshot, permissions, publish/domains, schema, registry inspection, man, and starting MCP.\n- Use MCP tools for Builder project data manipulation: pages, instances/components, props, text, styles, tokens, variables, resources, assets, breakpoints, redirects, and raw patches.\n- From a shell, call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio insert-fragment \'<json>\' --dry-run`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n- Inside the Webstudio monorepo, call the local CLI as its own command: `node packages/cli/local.js ...`. Do not wrap the CLI call in `pwd && ...`, command substitution, `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`.\n- For experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- Read `meta.session.commitStatus` before interpreting durability. Read-only results report `not-applicable` and retain `committed:false` for compatibility; dry-run plans report `planned`; failed mutations report `failed`; no-op mutations report `unchanged`; durable mutations report `committed` with `meta.session.committed:true`.\n- For bounded multi-step shell work, run inline JSON with `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For large batches, write `{ "calls": [{ "tool": "..." }] }` to a normal JSON file and run `webstudio mcp run .temp/mcp-calls.json`.\n- Use JSON strings for `brief` fields. Never pass boolean flags such as `{"brief":true}`.\n- Treat `webstudio mcp single-op-call` and `webstudio mcp run` stderr lines as progress checkpoints; stdout remains JSON on both success and failure. On failure, parse stdout for `{ "ok": false, "error": { "code": "...", "message": "..." } }` before deciding what to fix.\n- If a CLI/MCP tool crashes, hangs, gives a confusing error, needs an undocumented workaround, or forces source-code inspection for normal usage, ask the user to report it in Discord `#help` at https://wstd.us/community. Give them a complete copy-paste report with the goal, expected behavior, actual error, exact command/tool call, stdout JSON, stderr/lifecycle logs, environment, workaround, and secrets redacted.\n- Run one-shot `webstudio mcp single-op-call` commands sequentially against a linked `.webstudio` folder. If a command returns `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- In delegated or non-streaming agent environments, do not batch many MCP calls silently and do not wrap many shortcut or `webstudio mcp single-op-call` commands in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report that command/result, then wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with `workflow.next {"goal":"design-system-page","phase":"presentation-pass"}`. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world examples, not raw unstyled component dumps.\n- For design-system or “use every component” tasks, start with compact `webstudio components.coverage-plan`, checkpoint, then request component coverage details with `webstudio components.coverage-plan \'{"detail":"roots","offset":20}\'` or `{"detail":"parts"}` only when needed. Do not pass `detail` to `list-pages`; use `list-pages {}` or `get-page-by-path` for page lookup.\n- MCP tool shortcuts are only for MCP tools. If a shortcut is ambiguous with a real top-level command, the real top-level command wins; use `webstudio mcp single-op-call <tool> \'<json>\'` to force the MCP path.\n\n## LLM Implementation Process\n\nUse this process for user requests that change Webstudio content, layout, styles, assets, pages, redirects, resources, or publishing state:\n\n1. Discover capabilities with `webstudio man --json`, `webstudio schema api`, `webstudio schema mcp`, MCP `meta.index`, `meta.guide`, `meta.get-more-tools`, `components.list`, `components.summary`, `components.coverage-plan`, `components.search`, `components.get`, `templates.list`, and `templates.get`. From a shell, prefer shortcut calls such as `webstudio meta.index` and `webstudio components.search \'{"brief":"button"}\'` for these focused tool calls; use `webstudio mcp single-op-call` when you need the explicit MCP form. Read full resources such as `webstudio://project/tools` and `webstudio://project/components` only when needed. Do not write scripts to parse full MCP discovery JSON for normal lookup.\n2. When a value or id is known, call `search-project` once instead of passing broad snapshots or several lists to the model. Use semantic list/get reads such as `get-project-settings`, `list-pages`, `get-page-by-path`, `list-instances`, `inspect-instance`, `get-styles`, `list-assets`, and `list-breakpoints` when the structure or target is not known. Use `snapshot` only when exact raw patch paths are needed. Before changing a project, read `get-project-settings` and follow any non-empty `meta.agentInstructions`. These are shared project instructions, not a place for secrets.\n3. Mutate the Webstudio project with semantic MCP write tools first. Prefer MCP `insert-fragment` for authored/styled sections, use `insert-component` only for one automatic component template, then `update-text`, `update-props`, `update-styles`, `upload-asset`, `create-page`, and page/project settings tools over raw patches.\n4. Use `apply-patch` only when no semantic tool covers the required change, and only after reading the latest snapshot/version.\n5. For visual/design work, regenerate or preview the generated app, capture a screenshot, inspect it with vision, and iterate before final response.\n6. Report what changed and what verification ran.\n\n## Visual Design Workflow\n\nFor requests involving visible HTML/CSS, layout, typography, colors, imagery, responsive behavior, or screenshots:\n\n1. Read editable Webstudio structure first: pages, instances, props, styles, breakpoints, assets, and relevant text.\n2. Do not use generated route/component files as the source of truth for editable content.\n3. Make edits through Webstudio semantic commands/MCP tools so the result stays editable in Builder and survives the next `webstudio build`.\n4. Keep generated project files current, start preview, and capture the changed page with `screenshot`.\n5. Use `screenshot.diff` when a baseline exists and inspect screenshot/diff artifacts with vision before finishing.\n6. If vision or screenshot tooling is unavailable, state that explicitly and explain what fallback verification was used.\n\n## Responsive Verification Workflow\n\nFor responsive page work, use Builder breakpoints as the source of truth:\n\n1. Read breakpoints with `list-breakpoints` before deciding responsive behavior.\n2. Apply responsive styles with existing Builder breakpoint ids; do not invent CSS media queries or breakpoint names when Webstudio breakpoint data exists.\n3. Pick screenshot viewport widths from the project breakpoints: include a desktop width, each defined max-width or min-width edge, and a narrow mobile width.\n4. Capture each viewport with `screenshot`, for example `{"path":"/","output":"home-375.png","viewport":{"width":375,"height":812}}` and `{"path":"/","output":"home-1440.png","viewport":{"width":1440,"height":900}}`.\n5. Inspect every viewport screenshot with vision before finishing, checking layout, overflow, hidden content, text wrapping, and breakpoint-specific style changes.\n6. If any viewport fails, update styles through semantic Webstudio tools and repeat screenshots for the affected breakpoints.\n\n## Generated Files Guardrails\n\n- Do not edit `app/__generated__`, generated route files, generated page files, generated CSS, or build output for normal Webstudio content/design requests.\n- Do not replace generated page components with handcrafted app code unless the user explicitly asks for code-only export customization.\n- Generated files are build artifacts and may be overwritten by `webstudio build`.\n- If a task truly requires generated app customization, keep it outside `app/__generated__` where possible and explain that it is not editable Webstudio content.\n\n## Values vs Bindings\n\nBefore authoring unfamiliar expressions, read `webstudio://project/expressions` with MCP `resources/read` or `webstudio mcp read-resource webstudio://project/expressions`. It documents the supported expression subset, method allowlist, scope, Collection context, and validation limits.\n\n- Use direct value tools for fixed content. For one visible text child, use `update-text` with plain `text`. For a bounded multi-instance literal replacement, use `replace-text` with `find`, `replace`, `pagePath` or `pageId`, and `limit`; it does not change expression children. Use `replace-prop-text` for bounded changes inside static string props, optionally limited to prop names or instance ids; it never changes dynamic bindings. For static props such as `aria-label`, `alt`, `id`, `class`, `href`, or button labels stored as props, use `update-props` with the prop\'s direct type/value.\n- Use `bind-props` only when the prop must stay dynamic: an expression, resource result, action, or existing scoped runtime context such as `system`. Do not use `bind-props` just to set a fixed string.\n- Direct prop string example: `{"updates":[{"instanceId":"button-id","name":"aria-label","type":"string","value":"Open menu"}]}`.\n- Expression binding example: `{"bindings":[{"instanceId":"link-id","name":"href","binding":{"type":"expression","value":"currentPost.url"}}]}`.\n- Page metadata fields such as `title`, `description`, `language`, `redirect`, and custom meta content accept plain fixed text. For computed values, pass JavaScript expression code such as `pageTitle ?? "Pricing | Acme"`.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599, for example `302`. For a dynamic status, pass JavaScript expression code such as `system.status`.\n- Page metadata update example: use `update-page` with `{"pageId":"page-id","values":{"title":"Pricing | Acme","meta":{"description":"Plans for teams"}}}`.\n- Draft a page with `update-page` and `{"pageId":"page-id","values":{"isDraft":true}}`. It remains editable and previewable but is omitted from every publish target, including staging, and from sitemap output.\n- Stage a draft page for a future publish with `{"pageId":"page-id","values":{"isDraft":false}}`. This clears draft state but does not deploy the site. The home page and `/*` catch-all page cannot be drafts.\n- Resource `url` accepts plain fixed URLs and paths. For computed URLs, pass JavaScript expression code such as `"https://api.example.com/items?tag=" + filters.tag`. Resource header values, search parameter values, and text bodies accept expressions for dynamic values; for fixed text, use `{ "type": "literal", "value": "application/json" }`.\n- Resource update example: use `update-resource` with `{"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}`.\n- Assets is one system resource that always executes a structured query. `result:"many"` returns the existing ID-keyed collection shape and is the backward-compatible default. `result:"one"`, `result:"first"`, and `result:"last"` return one direct item or `null`; first and last require explicit sorting. `create-assets-resource` without `query` uses the default URL and optional image-dimensions output.\n- For a Markdown-backed blog, create exactly two Builder page definitions: a fixed `/blog` overview and one `/blog/:slug` detail page. Both pages load content through Assets resources. Never create one Builder page per post or duplicate Markdown content into static page structures. Read `get-asset-field-catalog`, validate each structured query with `validate-asset-query`, then call `create-assets-resource` or `update-assets-resource`. Set `values.query:null` to restore the default query.\n- Optimize every explicit Assets query for the deployed content-database size. Use `output.mode:"fields"` and select only fields that are actually rendered or otherwise required by the query. Keep `includeMetadata:false` unless the rendered value needs file metadata; diagnostics are returned separately. Do not use `output.mode:"all"` as a convenience default.\n- Every reachable Assets data source contributes to the shared database. Keep one final resource per rendered query. Update an existing scoped resource instead of creating a placeholder, preview copy, or repair replacement, and remove obsolete duplicate resources and data sources.\n- Make a bounded overview fully static: use literal values for its filters, limit, and offset, add a deterministic ID tie-breaker to its sort, and use `content.mode:"none"`. This lets compilation materialize the small overview result instead of retaining overview-only fields across every candidate article. Reserve runtime expressions for values that are truly dynamic, such as `system.params.slug` on the detail route.\n- Query Markdown files directly and use `content.mode:"markdown-body-ref"` when rendering their bodies. The published database keeps only metadata and document references, filters and paginates first, and fetches the selected Markdown bodies from Asset storage at runtime. Do not create companion JSON descriptors merely to avoid embedding Markdown.\n- `full` and bounded `range` request embedded file bytes. Use them only when the caller explicitly requires the complete source or a byte range.\n- Deferred Markdown bodies exclude frontmatter and resolve conventional relative links and images such as `../images/hero.png` to matching Assets. Markdown Embed permits sanitized figures, audio, video, and iframes, but removes scripts, inline event handlers, and unsafe URLs.\n- For `result:"many"`, Assets expose an ID-keyed map at `<dataSourceName>.data` and `totalCount`/`hasMore` at `<dataSourceName>.meta`; bind a listing Collection to `posts.data`. Single-result modes expose the selected item or `null` directly at `<dataSourceName>.data`, always include its `id`, and expose `totalCount` in meta. Bind detail components and page settings directly from expressions such as `post.data.properties.title`, `post.data.content.text`, and `post.data ? 200 : 404` without a Collection.\n- Use `preview-asset-query` with concrete values before binding expressions in the saved resource. Inspect `__diagnostics__.query` for the temporary query-only footprint and `__diagnostics__.database` for the merged database built from all reachable Assets queries. Only `database.usedBytes` counts toward `database.maxBytes`; query sizes are not separate allowances and must not be summed. Compare `usedBytes`, `unboundedBytes`, and `truncated` within both scopes. A finished Markdown blog must include every source document without truncation, contain no embedded Markdown bodies, and retain only the intended materialized overview query. When merged usage approaches the limit, remove duplicate reachable resources first, then unused output fields, then narrow candidate files. Inspect saved mode and configuration with `list-assets-resources` or `get-assets-resource`; shared index maintenance is automatic.\n- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays, objects, filters, and nested data.\n- Parameters are internal scoped runtime values from pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Public tools should preserve existing parameter records and may reference documented context values such as `system` in expressions where they are already in scope.\n- Use scoped resources for read data. A GET resource created with `scopeInstanceId`/`dataSourceName` defaults to `exposeAsDataSource:true`, becomes a scoped resource data variable, is generated into the page resource `data` map, and may be loaded while rendering the page. Read the loaded resource result from its wrapper, usually `.data`.\n- Use prop-bound resources for actions. A resource created without `scopeInstanceId` and bound to a component prop such as Form `action` with `bind-props` and `binding.type: "resource"` becomes an action resource in the page resource `action` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and anything that should run only from an explicit form/action flow.\n- POST, PUT, and DELETE resources default to `exposeAsDataSource:false`, even with a scope. Set `exposeAsDataSource:true` only for an intentional render-time read such as a GraphQL POST query; provide `scopeInstanceId` and inspect the returned warning. Set it to `false` during `update-resource` to detach existing render-time exposure.\n- For dynamic resource query parameters prefer `searchParams`, for example `{"name":"tag","value":"filters.tag"}`. Use `{"type":"literal","value":"website"}` for fixed request text. Header values can use an expression such as `"Bearer " + auth.token`. Body can be an object expression, including GraphQL payloads such as `{ query: "...", variables: { slug: system.params.slug } }`.\n- Resource methods are `get`, `post`, `put`, and `delete`. Optional resource controls are `graphql` and `system`. Use `control:"graphql"` for GraphQL POST resources with query bodies. Use `control:"system"` for built-in local resource URLs such as `"/$resources/current-date"` and for resources reading the built-in `system` parameter. The built-in system fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`; do not use `system.path`.\n- Whenever an array or object from a resource or data variable should render repeated UI, call `insert-collection` with the complete iterable and one repeated-item JSX root. The command creates the Collection, private item parameters, iterable binding, and descendant item bindings atomically. Use `collectionItem` and `collectionItemKey` expressions in the item JSX. Wrap multiple repeated siblings in one Element, and give repeated Radix items stable unique `value` bindings.\n- Expressions are single JavaScript expressions, not statements or functions. Functions, arrow functions, classes, `new`, `this`, `await`, imports, arbitrary calls, increment/decrement, and assignment outside actions are unsupported. Property and index access are made safe automatically, so write direct access without optional chaining. Use nullish coalescing when a fallback is required.\n\n## Pick Read Command\n\n{{readFirst}}\n\n## Pick Write Command\n\n{{taskRecipeIndex}}\n\n## Raw Patch Only If Needed\n\n1. Use MCP tool: snapshot.\n2. Write BuildPatchTransaction[].\n3. Use MCP tool: apply-patch.\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects, not CLI flags. Use these shapes:\n\n{{mcpArgumentExampleIndex}}\n\n## Rules\n\n- Never guess ids for existing records. Read them first.\n- Never use project ids from user input. Commands use the configured project.\n- Use --refresh before a local-capable command when cached data may be stale.\n- Pass --json only to commands whose help/schema documents it. Do not add --json to top-level commands such as sync unless supported.\n- On VERSION_CONFLICT, read MCP snapshot again, regenerate the patch, then retry.\n- Treat stdout JSON as the API contract and stderr as diagnostics.\n- For visual/design work, verify the rendered result with vision before finishing.\n- Do not edit generated files for normal Webstudio content/design requests.\n- Use direct values for static strings and bindings only for dynamic expressions/resources/actions.\n- Use plain fixed text where documented. Only encode a quoted JavaScript string literal when a field is explicitly documented as an expression-only value.\n- Confirm destructive commands with --confirm only when user requested deletion/unpublish/replacement.\n- Use webstudio schema api for machine-readable top-level command metadata and webstudio schema mcp for MCP tool schemas.\n\n## Known Gaps\n\n{{knownCliGapIndex}}\n',"manual-mcp":- '# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for real MCP clients. Shell users can call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. `webstudio mcp single-op-call` is the explicit equivalent and prints the structured JSON result. `webstudio mcp run` runs multiple MCP tool calls from inline JSON or a normal JSON file in one shared CLI session. Do not manually type or pipe raw JSON-RPC frames into `webstudio mcp` from an interactive shell or PTY.\n\n## Startup\n\nIf you are already working with a shell-capable agent, it can use the local CLI\ndirectly. Native MCP client registration is optional. Give the editable Builder\nshare link only when the trusted agent asks for it. Treat the share link as a\ncredential: do not include it in committed files, screenshots, logs, or issue\nreports.\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Check capabilities with `webstudio permissions --json`.\n3. Use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> \'<json>\'` when you need to force the MCP path, or `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.\n4. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'`.\n\nDo not run `webstudio sync`, install an MCP server, change client configuration,\nor restart the app for this local CLI workflow.\n\nWhen the user explicitly wants persistent native MCP integration, run\n`webstudio connect claude`, `webstudio connect codex`, `webstudio connect\ncursor`, or `webstudio connect vscode`. This optional command changes client\nconfiguration, so follow its client-specific reload or restart instruction.\nUse `--print` to inspect the generated setup without changing configuration or\nrequiring project access. For Codex, `connect` registers and verifies the server\nthrough the Codex CLI. Before changing client configuration, `connect` verifies\nthat the saved project endpoint is reachable and its credential is accepted.\n\nStart MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.\n\nWhen developing inside the Webstudio monorepo, start the local CLI exactly as `node packages/cli/local.js mcp` from the repo root. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can resolve an older binary.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process. The server advertises MCP `logging` capability and emits sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`; stderr also mirrors these sparse lifecycle fallback lines prefixed with `[webstudio mcp]`.\n\n## One-Shot Tool Calls\n\nUse the shortcut `webstudio <tool> \'<json>\'` when you are operating from a shell and need one MCP tool result. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and avoids writing temporary Node.js stdio client scripts.\n\nExamples:\n\n```sh\nwebstudio mcp single-op-call meta.index\nwebstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nwebstudio mcp single-op-call components.list \'{"source":"all"}\'\nwebstudio mcp single-op-call components.coverage-plan\nwebstudio mcp single-op-call components.search \'{"brief":"radix select"}\'\nwebstudio mcp single-op-call components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call templates.list\nwebstudio mcp single-op-call templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json\n```\n\nShortcut equivalents:\n\n```sh\nwebstudio meta.index\nwebstudio meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nwebstudio components.list \'{"source":"all"}\'\nwebstudio components.coverage-plan\nwebstudio components.search \'{"brief":"radix select"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio templates.list\nwebstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio insert-fragment --input-file .temp/insert-fragment.json\n```\n\n### Tool name convention\n\nMCP tool names are opaque strings, not JavaScript property access. A dot separates a namespace from its tool name, and every segment uses lowercase kebab-case. For example, `components.coverage-insert-next` is the `coverage-insert-next` tool in the `components` namespace. Pass the complete name as one CLI argument: `webstudio components.coverage-insert-next`. Batch `mcp run` calls also accept the underscore form advertised by MCP protocol discovery, such as `components_coverage_insert_next`. Unknown names return near matches and direct you to `meta.index`.\n\n### Readable fragment inputs\n\nPrefer `--input-file` for JSX so JSON and shell quoting do not obscure the fragment. For example, save this as `.temp/insert-fragment.json`:\n\n```json\n{\n "parentInstanceId": "root-id",\n "fragment": "<ws.element ws:tag=\'section\' ws:style={css`padding: 32px; display: grid; gap: 16px;`}><ws.element ws:tag=\'h2\'>Northstar Product OS</ws.element><ws.element ws:tag=\'p\'>Reusable patterns for teams.</ws.element></ws.element>"\n}\n```\n\nThen run `webstudio insert-fragment --input-file .temp/insert-fragment.json`. Single quotes inside the JSX keep the JSON valid and readable without backslash-escaped attributes.\n\nWrite and review larger fragments as JSX before placing them in the `fragment` field. Common patterns:\n\n```tsx\n<ws.element\n ws:tag="section"\n style={{ padding: 32, borderRadius: 16 }}\n>\n <ws.element ws:tag="h2">Operations Console</ws.element>\n <ws.element ws:tag="p">\n React-style object styles become editable Webstudio styles.\n </ws.element>\n</ws.element>\n\n<ws.element\n ws:tag="section"\n ws:tokens={[token("accent", css`color: #0f766e;`)]}\n>\n <ws.element\n ws:tag="button"\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n >\n Track launch\n </ws.element>\n</ws.element>\n\n<ws.element ws:tag="section">\n <radix.Switch>\n <radix.SwitchThumb />\n </radix.Switch>\n</ws.element>\n```\n\nRules:\n\n- Inside the Webstudio monorepo, replace `webstudio` in the examples above with `node packages/cli/local.js`, for example `node packages/cli/local.js meta.index`.\n- For a simple authored/styled section, run `meta.index`, then `meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, then `insert-fragment`. Do not grep source files, dump full MCP resources, or write parser scripts first.\n- In `insert-fragment` JSX, use ``ws:style={css`...`}`` for Webstudio-native CSS, or use React-style object syntax such as `style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- `css` templates accept declarations and `@media` rules. Do not put selectors or unsupported at-rules such as `@keyframes` inside them. `animation` is the component namespace for JSX such as `<animation.AnimateChildren>`; it is not a callable CSS keyframes helper.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want one automatic registered component template.\n- The positional input is JSON and defaults to `{}`.\n- Use `--input-file` for large mutation payloads.\n- Use `--dry-run` with local-capable mutation tools when you need a patch plan without committing. The computed transaction is returned in `meta.session.transaction`, and `meta.session.version` is its base build version. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- The command prints JSON to stdout for both success and failure. Success uses the same `structuredContent` shape MCP tools return: `{ "ok": true, "data": ..., "meta": ... }`. Failure prints `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` and exits nonzero.\n- The command writes sparse progress to stderr, including start, success/failure, elapsed time, and committed status when the tool returns session metadata.\n- Invalid argument types fail loudly with path-specific messages, for example `meta.guide input.brief must be a string when provided`.\n- Run one-shot shortcut or `mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- To work with another previously linked project without changing the directory\'s default link, start MCP or a shell call with `--project <projectId>`, for example `webstudio mcp --project <projectId>` or `webstudio mcp single-op-call list-pages --project <projectId>`. Selected projects use isolated local session and checkpoint files.\n- If you are a delegated agent and your parent cannot see live stderr/stdout, do not run a long sequence of shortcut or `mcp single-op-call` commands silently and do not wrap many calls in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one `webstudio <tool>` or `webstudio mcp single-op-call` command, report that command/result, then wait before the next MCP command. For all-component design-system pages, checkpoint after discovery, checkpoint after page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase. Coverage alone is not completion; organize examples into styled sections/cards.\n\n## Reporting CLI/MCP Issues\n\nIf a CLI/MCP tool gives a confusing error, crashes, hangs, produces invalid output, requires an undocumented workaround, or makes you inspect source code to understand normal usage, ask the user to report it in the Webstudio Discord `#help` channel: https://wstd.us/community.\n\nGive the user a complete copy-paste report. Include only non-secret values: never include auth tokens, private URLs, cookies, API keys, passwords, or proprietary project data. Redact them as `<redacted>`.\n\nCopy-paste template:\n\n````md\nWebstudio CLI/MCP issue report\n\nWhat I was trying to do:\n<short user goal, for example "Create a resource from an external API and render it in a collection">\n\nWhat I expected:\n<what should have happened>\n\nWhat happened instead:\n<exact error, confusing behavior, hang, missing docs, or workaround required>\n\nCommand/tool used:\n\n```sh\n<exact command or MCP tool call, with tokens/secrets redacted>\n```\n\nStructured output / error:\n\n```json\n<stdout JSON or MCP structuredContent, if available, with secrets redacted>\n```\n\nStderr / lifecycle logs:\n\n```txt\n<stderr lines, timings, checkpoint messages, or stack trace, with secrets redacted>\n```\n\nEnvironment:\n\n- CLI command path: <webstudio / node packages/cli/local.js / other>\n- Webstudio CLI version: <from command output if known>\n- OS: <macOS / Windows / Linux / unknown>\n- Node version: <node -v if known>\n- Project/session state: <linked project, local .webstudio session, preview, MCP server, or unknown>\n\nWorkaround tried:\n<what the agent/user tried next, and whether it worked>\n\nWhy this should be improved:\n<one sentence: better error message, docs, schema, tool behavior, etc.>\n````\n\n## Shared-Session Shell Runs\n\nUse `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` when you are operating from a shell and need several MCP tool calls to share one CLI session without hand-writing JSON-RPC. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nUse `mcp run` for long-lived tools such as `preview.start`. A one-shot `mcp single-op-call preview.start` cannot keep ownership of a preview server for a later screenshot or stop call. Put `preview.start`, `screenshot`, and `preview.stop` in one shared `mcp run` process, or use a real long-running MCP client.\n\nInput shape:\n\n```json\n{\n "calls": [\n { "tool": "meta.index" },\n { "tool": "components.find", "input": { "brief": "radix select" } }\n ]\n}\n```\n\nRules:\n\n- The command prints JSON to stdout for both success and failure. It stops at the first failed call and prints partial results in `{ "ok": false, "error": ..., "data": { "completedCalls": ..., "results": [...] }, "meta": ... }`, then exits nonzero.\n- If a call returns `checkpoint.required`, read-only discovery and inspection remain available, but mutations and state-changing session tools return `CHECKPOINT_REQUIRED`. Stop and report the checkpoint to the parent/user. Only after the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}` before continuing mutations.\n- For `mcp single-op-call`, checkpoint requirements persist across later one-shot CLI processes until you call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`.\n- Use this instead of manually sending JSON-RPC frames to `webstudio mcp` from a shell.\n\n### Cross-project batches\n\nAdd `projects` to the same `mcp run` manifest to run focused reads, audits, or dry runs across independently linked project roots:\n\n```json\n{\n "concurrency": 2,\n "calls": [\n { "tool": "status" },\n { "tool": "audit", "input": {} },\n {\n "tool": "update-project-settings",\n "input": { "meta": { "siteName": "Reviewed" } },\n "dryRun": true\n }\n ],\n "projects": [\n { "id": "site-a", "root": "../site-a" },\n { "id": "site-b", "root": "../site-b" }\n ]\n}\n```\n\nProject roots and an optional `progressFile` are resolved relative to the manifest file. Each project may provide its own `calls` instead of using the top-level calls. Each root must already be linked with its own `.webstudio/config.json`; the runner creates an independently authenticated ProjectSession and uses root-scoped session, audit, preview-data, and checkpoint paths without changing the process working directory.\n\nConcurrency defaults to 2, is capped at 16, and can be set in the manifest or overridden with `--concurrency`. A failure is reported for that project while other projects continue. Progress is saved after every successful call; rerunning with the default `--resume` skips completed projects and starts failed projects after their last confirmed successful call. Reads and dry runs may be retried. A committed mutation interrupted after dispatch is marked `AMBIGUOUS_MUTATION_RESULT` and is never replayed automatically; inspect that project before deciding how to continue. Use `--no-resume` only to intentionally start the complete manifest over.\n\nCommitted mutation tools are rejected in a projects batch unless the command includes `--approve-mutations`. Review the complete manifest before granting approval. `--dry-run` applies to every call and does not require mutation approval. The final stdout object is compact: project counts, one status/error record per project, elapsed time, and the progress-file path rather than every tool result.\n\n## Discovery\n\nUse MCP itself after startup, or call the same tools with `webstudio mcp single-op-call`:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available overview and full JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal; call with a string brief such as `{"brief":"Create a pricing page"}`\n- `meta.get-more-tools`: detailed params, examples, namespaces, and local/server behavior; prefer exact names such as `{"tools":["insert-fragment"]}` when you know them\n- `components.list`: compact registry metadata for visible components and templates; use a focused get tool for complete details\n- `components.summary`: component counts by default; use `{"detail":"components","limit":20}` for paginated entries\n- `components.coverage-plan`: compact paged plan for design-system coverage tasks that need every component; default returns counts plus the first root page, use `{"detail":"roots"}`, `{"detail":"parts"}`, or `{"detail":"full"}` for more\n- `components.coverage-status`: page-specific covered/missing component report with `missingRoots` and `missingParts`\n- `components.search`: focused component/template search by id, namespace, label, category, or content model\n- `components.find`: compatibility alias for focused component search\n- `components.get`: full metadata for one component id\n- `templates.list`: compact metadata for template-backed insertions only\n- `templates.get`: full registry item and payload metadata for one template\n- `search-project`: find a known value or id with `webstudio search-project \'{"query":"pricing"}\'` or MCP `search-project {"query":"pricing"}`; use focused list/get tools when the target structure is unknown\n\n`search-project` follows normal ProjectSession synchronization, then searches in the CLI process. Namespace filters limit values matched; related namespaces may still supply route and reference context, and synchronization is unchanged. Only paged matches enter model context. Recognized credential fields and asset binary or document bodies are excluded.\n\nComponent and template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. Use `meta.runtime` for component ids, props, states, content model, and source identity; `meta.authoring` for composition and accessibility guidance; and `meta.builder` for template insertion details and expected project-data namespaces. These items are for Builder/MCP discovery and are not a published shadcn install registry yet.\n\nPrefer the focused `components.*` tools over dumping `webstudio://project/components`. Do not write local scripts to parse full MCP discovery JSON for common component lookup.\nFor “use every component” or design-system pages, start with compact `components.coverage-plan`, checkpoint, then page through roots/parts instead of dumping the full catalog.\n\n## Consumer Capabilities\n\nMCP lets agents work on one configured Webstudio project at a time. In consumer\nterms, agents can:\n\n- Check which project they are connected to.\n- Check what the share link is allowed to do.\n- Inspect project metadata and the latest editable build.\n- Read selected project data for audits and repair.\n- Search all Builder namespaces for a known value or id without putting complete namespace data in model context.\n- Apply precise project changes against a known version.\n- List, inspect, create, update, delete, duplicate, copy, and reorder pages.\n- Set the home page.\n- Preserve old page paths for redirects or history.\n- Read and update page titles, descriptions, metadata, auth settings, and SEO fields.\n- List, create, update, duplicate, move, and delete page folders.\n- List, create, update, delete, duplicate, reorder, and reuse page templates.\n- Create pages from reusable templates.\n- Read and update project site settings.\n- Read and update marketplace product metadata.\n- List, create, update, delete, and replace redirects.\n- List, create, update, and delete responsive breakpoints.\n- List and inspect page elements.\n- Insert registered components.\n- Insert styled JSX fragments.\n- Move, reparent, clone, duplicate, wrap, unwrap, convert, rename, retag, and delete elements.\n- Fill grid cells.\n- List and update text children.\n- Update plain text and expression text.\n- Update structured rich text.\n- Add, update, delete, and bind element props.\n- Bind props to expressions, resources, actions, and runtime system values.\n- Read, add, update, delete, and replace local styles.\n- Update selected style-source styles.\n- List, create, update, attach, detach, extract, duplicate, rename, lock, unlock, reorder, clear, and delete design tokens and style sources.\n- List, define, rename, delete, and rewrite CSS variables.\n- List, create, update, and delete static data variables.\n- Create string, number, boolean, and JSON variables. Arrays use JSON.\n- Delete unused data variables.\n- List, create, update, upsert, bind, and delete resources.\n- Create HTTP resources.\n- Create GraphQL resources.\n- Create system resources.\n- Use built-in system resources for sitemap, current date, and assets.\n- List and inspect complete asset metadata; upload, download, update, move, duplicate, find usage for, replace, and delete assets.\n- List, create, rename, move, recursively duplicate, and recursively delete nested asset folders.\n- Publish to staging or production.\n- Publish to selected domains.\n- List publish builds.\n- Check publish job status.\n- Unpublish staging or production deployments.\n- List, create, update, delete, and verify custom domains.\n- Start and stop preview.\n- Capture screenshots of generated pages.\n- Compare screenshots against baselines.\n- Install OCR support for richer visual checks.\n\nUseful resources:\n\n- `webstudio://project/status`: compact current ProjectSession status\n- `webstudio://project/tools-overview`: small operation overview by capability area\n- `webstudio://project/components-overview`: small component overview with ids, labels, namespaces, and categories\n- `webstudio://project/tools`: full operation catalog; read only when focused metadata is insufficient\n- `webstudio://project/components`: full component catalog with props, states, and content model composition constraints; read only when `components.summary`, `components.find`, and `components.get` are insufficient\n- `webstudio://project/guide`: concise discovery guide\n- `webstudio://project/expressions`: expression syntax, scope, supported methods, bindings, Collection iteration context, and verification\n- `webstudio://project/accessibility-review`: evidence-based LLM accessibility-review workflow using project checks, preview, and screenshots\n\n## MCP SDK Client Imports\n\nWhen writing a local Node.js MCP client script, use the official MCP SDK package and these exact ESM imports:\n\nInside the Webstudio monorepo this package is available at the repo root. In another project, install it first with `pnpm add -D @modelcontextprotocol/sdk`.\n\n```js\nimport { Client } from "@modelcontextprotocol/sdk/client/index.js";\nimport { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";\nimport { LoggingMessageNotificationSchema } from "@modelcontextprotocol/sdk/types.js";\n```\n\nMinimal stdio client for the local Webstudio CLI:\n\n```js\nconst client = new Client({ name: "webstudio-agent", version: "1.0.0" });\n\nclient.setNotificationHandler(\n LoggingMessageNotificationSchema,\n (notification) => {\n console.error(`[mcp] ${notification.params.data}`);\n }\n);\n\nconst transport = new StdioClientTransport({\n command: "node",\n args: ["packages/cli/local.js", "mcp"],\n cwd: process.cwd(),\n stderr: "inherit",\n});\n\nawait client.connect(transport);\n\nconst index = await client.callTool({\n name: "meta.index",\n arguments: {},\n});\nconsole.log(JSON.stringify(index.structuredContent, null, 2));\n\nawait client.close();\n```\n\nUse `node packages/cli/local.js mcp` from the Webstudio monorepo root for local development, or `webstudio mcp` from a linked project where the CLI is installed. Keep stdout for JSON-RPC/structured results and surface MCP logging notifications or stderr lifecycle lines as progress.\n\n## Core Rules\n\n- stdout is reserved for MCP JSON-RPC while the server is running.\n- Operate on the configured project only.\n- Read ids before writing.\n- Prefer semantic tools over `apply-patch`.\n- Use `status` and `refresh` when cached namespaces may be stale. Pass `status {"verbose":true}` only when debugging full namespace arrays, freshness, compatibility, or diagnostic details.\n- Read `meta.session.commitStatus` before interpreting durability. Read-only results report `not-applicable` and retain `committed:false` for compatibility; dry-run plans report `planned`; failed mutations report `failed`; no-op mutations report `unchanged`; durable mutations report `committed` with `meta.session.committed:true`.\n- For visual/design work, verify the rendered result with vision before finishing.\n\n## Vision Verification Loop\n\nVision-capable AI can use MCP to see what it is building:\n\n{{mcpVisionVerificationLoopMarkdown}}\n\nGenerated app setup:\n\n{{mcpGeneratedAppDependencyNotes}}\n\n## MCP argument examples\n\nExamples below show meaningful argument combinations. Tool schemas are the\nsource of truth. For tools with no required arguments, pass `{}`.\n\n{{mcpArgumentExampleIndex}}\n\n{{contentEngineReferenceMarkdown}}\n\n## Screenshot Verification\n\n{{screenshotVerificationSummary}}\n',+ '# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for real MCP clients. Shell users can call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. `webstudio mcp single-op-call` is the explicit equivalent and prints the structured JSON result. `webstudio mcp run` runs multiple MCP tool calls from inline JSON or a normal JSON file in one shared CLI session. Do not manually type or pipe raw JSON-RPC frames into `webstudio mcp` from an interactive shell or PTY.\n\n## Startup\n\nIf you are already working with a shell-capable agent, it can use the local CLI\ndirectly. Native MCP client registration is optional. Give the editable Builder\nshare link only when the trusted agent asks for it. Treat the share link as a\ncredential: do not include it in committed files, screenshots, logs, or issue\nreports.\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Check capabilities with `webstudio permissions --json`.\n3. Use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> \'<json>\'` when you need to force the MCP path, or `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.\n4. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'`.\n\nDo not run `webstudio sync`, install an MCP server, change client configuration,\nor restart the app for this local CLI workflow.\n\nWhen the user explicitly wants persistent native MCP integration, run\n`webstudio connect claude`, `webstudio connect codex`, `webstudio connect\ncursor`, or `webstudio connect vscode`. This optional command changes client\nconfiguration, so follow its client-specific reload or restart instruction.\nUse `--print` to inspect the generated setup without changing configuration or\nrequiring project access. For Codex, `connect` registers and verifies the server\nthrough the Codex CLI. Before changing client configuration, `connect` verifies\nthat the saved project endpoint is reachable and its credential is accepted.\n\nStart MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.\n\nWhen developing inside the Webstudio monorepo, start the local CLI exactly as `node packages/cli/local.js mcp` from the repo root. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can resolve an older binary.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process. The server advertises MCP `logging` capability and emits sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`; stderr also mirrors these sparse lifecycle fallback lines prefixed with `[webstudio mcp]`.\n\n## One-Shot Tool Calls\n\nUse the shortcut `webstudio <tool> \'<json>\'` when you are operating from a shell and need one MCP tool result. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and avoids writing temporary Node.js stdio client scripts.\n\nExamples:\n\n```sh\nwebstudio mcp single-op-call meta.index\nwebstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nwebstudio mcp single-op-call components.list \'{"source":"all"}\'\nwebstudio mcp single-op-call components.coverage-plan\nwebstudio mcp single-op-call components.search \'{"brief":"radix select"}\'\nwebstudio mcp single-op-call components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call templates.list\nwebstudio mcp single-op-call templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json\n```\n\nShortcut equivalents:\n\n```sh\nwebstudio meta.index\nwebstudio meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nwebstudio components.list \'{"source":"all"}\'\nwebstudio components.coverage-plan\nwebstudio components.search \'{"brief":"radix select"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio templates.list\nwebstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio insert-fragment --input-file .temp/insert-fragment.json\n```\n\n### Tool name convention\n\nMCP tool names are opaque strings, not JavaScript property access. A dot separates a namespace from its tool name, and every segment uses lowercase kebab-case. For example, `components.coverage-insert-next` is the `coverage-insert-next` tool in the `components` namespace. Pass the complete name as one CLI argument: `webstudio components.coverage-insert-next`. Batch `mcp run` calls also accept the underscore form advertised by MCP protocol discovery, such as `components_coverage_insert_next`. Unknown names return near matches and direct you to `meta.index`.\n\n### Readable fragment inputs\n\nPrefer `--input-file` for JSX so JSON and shell quoting do not obscure the fragment. For example, save this as `.temp/insert-fragment.json`:\n\n```json\n{\n "parentInstanceId": "root-id",\n "fragment": "<ws.element ws:tag=\'section\' ws:style={css`padding: 32px; display: grid; gap: 16px;`}><ws.element ws:tag=\'h2\'>Northstar Product OS</ws.element><ws.element ws:tag=\'p\'>Reusable patterns for teams.</ws.element></ws.element>"\n}\n```\n\nThen run `webstudio insert-fragment --input-file .temp/insert-fragment.json`. Single quotes inside the JSX keep the JSON valid and readable without backslash-escaped attributes.\n\nWrite and review larger fragments as JSX before placing them in the `fragment` field. Common patterns:\n\n```tsx\n<ws.element\n ws:tag="section"\n style={{ padding: 32, borderRadius: 16 }}\n>\n <ws.element ws:tag="h2">Operations Console</ws.element>\n <ws.element ws:tag="p">\n React-style object styles become editable Webstudio styles.\n </ws.element>\n</ws.element>\n\n<ws.element\n ws:tag="section"\n ws:tokens={[token("accent", css`color: #0f766e;`)]}\n>\n <ws.element\n ws:tag="button"\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n >\n Track launch\n </ws.element>\n</ws.element>\n\n<ws.element ws:tag="section">\n <radix.Switch>\n <radix.SwitchThumb />\n </radix.Switch>\n</ws.element>\n```\n\nRules:\n\n- Inside the Webstudio monorepo, replace `webstudio` in the examples above with `node packages/cli/local.js`, for example `node packages/cli/local.js meta.index`.\n- For a simple authored/styled section, run `meta.index`, then `meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, then `insert-fragment`. Do not grep source files, dump full MCP resources, or write parser scripts first.\n- In `insert-fragment` JSX, use ``ws:style={css`...`}`` for Webstudio-native CSS, or use React-style object syntax such as `style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- `css` templates accept declarations and `@media` rules. Do not put selectors or unsupported at-rules such as `@keyframes` inside them. `animation` is the component namespace for JSX such as `<animation.AnimateChildren>`; it is not a callable CSS keyframes helper.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want one automatic registered component template.\n- The positional input is JSON and defaults to `{}`.\n- Use `--input-file` for large mutation payloads.\n- Use `--dry-run` with local-capable mutation tools when you need a patch plan without committing. The computed transaction is returned in `meta.session.transaction`, and `meta.session.version` is its base build version. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- The command prints JSON to stdout for both success and failure. Success uses the same `structuredContent` shape MCP tools return: `{ "ok": true, "data": ..., "meta": ... }`. Failure prints `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` and exits nonzero.\n- The command writes sparse progress to stderr, including start, success/failure, elapsed time, and committed status when the tool returns session metadata.\n- Invalid argument types fail loudly with path-specific messages, for example `meta.guide input.brief must be a string when provided`.\n- Run one-shot shortcut or `mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- To work with another previously linked project without changing the directory\'s default link, start MCP or a shell call with `--project <projectId>`, for example `webstudio mcp --project <projectId>` or `webstudio mcp single-op-call list-pages --project <projectId>`. Selected projects use isolated local session and checkpoint files.\n- If you are a delegated agent and your parent cannot see live stderr/stdout, do not run a long sequence of shortcut or `mcp single-op-call` commands silently and do not wrap many calls in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one `webstudio <tool>` or `webstudio mcp single-op-call` command, report that command/result, then wait before the next MCP command. For all-component design-system pages, checkpoint after discovery, checkpoint after page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase. Coverage alone is not completion; organize examples into styled sections/cards.\n\n## Reporting CLI/MCP Issues\n\nIf a CLI/MCP tool gives a confusing error, crashes, hangs, produces invalid output, requires an undocumented workaround, or makes you inspect source code to understand normal usage, ask the user to report it in the Webstudio Discord `#help` channel: https://wstd.us/community.\n\nGive the user a complete copy-paste report. Include only non-secret values: never include auth tokens, private URLs, cookies, API keys, passwords, or proprietary project data. Redact them as `<redacted>`.\n\nCopy-paste template:\n\n````md\nWebstudio CLI/MCP issue report\n\nWhat I was trying to do:\n<short user goal, for example "Create a resource from an external API and render it in a collection">\n\nWhat I expected:\n<what should have happened>\n\nWhat happened instead:\n<exact error, confusing behavior, hang, missing docs, or workaround required>\n\nCommand/tool used:\n\n```sh\n<exact command or MCP tool call, with tokens/secrets redacted>\n```\n\nStructured output / error:\n\n```json\n<stdout JSON or MCP structuredContent, if available, with secrets redacted>\n```\n\nStderr / lifecycle logs:\n\n```txt\n<stderr lines, timings, checkpoint messages, or stack trace, with secrets redacted>\n```\n\nEnvironment:\n\n- CLI command path: <webstudio / node packages/cli/local.js / other>\n- Webstudio CLI version: <from command output if known>\n- OS: <macOS / Windows / Linux / unknown>\n- Node version: <node -v if known>\n- Project/session state: <linked project, local .webstudio session, preview, MCP server, or unknown>\n\nWorkaround tried:\n<what the agent/user tried next, and whether it worked>\n\nWhy this should be improved:\n<one sentence: better error message, docs, schema, tool behavior, etc.>\n````\n\n## Shared-Session Shell Runs\n\nUse `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` when you are operating from a shell and need several MCP tool calls to share one CLI session without hand-writing JSON-RPC. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nUse `mcp run` for long-lived tools such as `preview.start`. A one-shot `mcp single-op-call preview.start` cannot keep ownership of a preview server for a later screenshot or stop call. Put `preview.start`, `screenshot`, and `preview.stop` in one shared `mcp run` process, or use a real long-running MCP client.\n\nInput shape:\n\n```json\n{\n "calls": [\n { "tool": "meta.index" },\n { "tool": "components.find", "input": { "brief": "radix select" } }\n ]\n}\n```\n\nRules:\n\n- The command prints JSON to stdout for both success and failure. It stops at the first failed call and prints partial results in `{ "ok": false, "error": ..., "data": { "completedCalls": ..., "results": [...] }, "meta": ... }`, then exits nonzero.\n- If a call returns `checkpoint.required`, read-only discovery and inspection remain available, but mutations and state-changing session tools return `CHECKPOINT_REQUIRED`. Stop and report the checkpoint to the parent/user. Only after the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}` before continuing mutations.\n- For `mcp single-op-call`, checkpoint requirements persist across later one-shot CLI processes until you call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`.\n- Use this instead of manually sending JSON-RPC frames to `webstudio mcp` from a shell.\n\n### Cross-project batches\n\nAdd `projects` to the same `mcp run` manifest to run focused reads, audits, or dry runs across independently linked project roots:\n\n```json\n{\n "concurrency": 2,\n "calls": [\n { "tool": "status" },\n { "tool": "audit", "input": {} },\n {\n "tool": "update-project-settings",\n "input": { "meta": { "siteName": "Reviewed" } },\n "dryRun": true\n }\n ],\n "projects": [\n { "id": "site-a", "root": "../site-a" },\n { "id": "site-b", "root": "../site-b" }\n ]\n}\n```\n\nProject roots and an optional `progressFile` are resolved relative to the manifest file. Each project may provide its own `calls` instead of using the top-level calls. Each root must already be linked with its own `.webstudio/config.json`; the runner creates an independently authenticated ProjectSession and uses root-scoped session, audit, preview-data, and checkpoint paths without changing the process working directory.\n\nConcurrency defaults to 2, is capped at 16, and can be set in the manifest or overridden with `--concurrency`. A failure is reported for that project while other projects continue. Progress is saved after every successful call; rerunning with the default `--resume` skips completed projects and starts failed projects after their last confirmed successful call. Reads and dry runs may be retried. A committed mutation interrupted after dispatch is marked `AMBIGUOUS_MUTATION_RESULT` and is never replayed automatically; inspect that project before deciding how to continue. Use `--no-resume` only to intentionally start the complete manifest over.\n\nCommitted mutation tools are rejected in a projects batch unless the command includes `--approve-mutations`. Review the complete manifest before granting approval. `--dry-run` applies to every call and does not require mutation approval. The final stdout object is compact: project counts, one status/error record per project, elapsed time, and the progress-file path rather than every tool result.\n\n## Discovery\n\nUse MCP itself after startup, or call the same tools with `webstudio mcp single-op-call`:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available overview and full JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal; call with a string brief such as `{"brief":"Create a pricing page"}`\n- `meta.get-more-tools`: detailed params, examples, namespaces, and local/server behavior; prefer exact names such as `{"tools":["insert-fragment"]}` when you know them\n- `components.list`: compact registry metadata for visible components and templates; use a focused get tool for complete details\n- `components.summary`: component counts by default; use `{"detail":"components","limit":20}` for paginated entries\n- `components.coverage-plan`: compact paged plan for design-system coverage tasks that need every component; default returns counts plus the first root page, use `{"detail":"roots"}`, `{"detail":"parts"}`, or `{"detail":"full"}` for more\n- `components.coverage-status`: page-specific covered/missing component report with `missingRoots` and `missingParts`\n- `components.search`: focused component/template search by id, namespace, label, category, or content model\n- `components.find`: compatibility alias for focused component search\n- `components.get`: full metadata for one component id\n- `templates.list`: compact metadata for template-backed insertions only\n- `templates.get`: full registry item and payload metadata for one template\n- `search-project`: find a known value or id with `webstudio search-project \'{"query":"pricing"}\'` or MCP `search-project {"query":"pricing"}`; use focused list/get tools when the target structure is unknown\n\n`search-project` follows normal ProjectSession synchronization, then searches in the CLI process. Namespace filters limit values matched; related namespaces may still supply route and reference context, and synchronization is unchanged. Only paged matches enter model context. Recognized credential fields and asset binary or document bodies are excluded.\n\nComponent and template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. Use `meta.runtime` for component ids, props, states, content model, and source identity; `meta.authoring` for composition and accessibility guidance; and `meta.builder` for template insertion details and expected project-data namespaces. These items are for Builder/MCP discovery and are not a published shadcn install registry yet.\n\nPrefer the focused `components.*` tools over dumping `webstudio://project/components`. Do not write local scripts to parse full MCP discovery JSON for common component lookup.\nFor “use every component” or design-system pages, start with compact `components.coverage-plan`, checkpoint, then page through roots/parts instead of dumping the full catalog.\n\n## MDX Content Block workflow\n\nContent Blocks can store their editable body in an `.mdx` Asset. The Builder,\ndirect CLI, HTTP API, and MCP use the same source resolver, safe MDX parser,\nContent mode permissions, serializer, diagnostics, Asset authorization, and\nrevision checks.\n\nUse the focused tools instead of downloading and rewriting the file as text:\n\n1. Call `inspect-content-block-source` with the Content Block ID and exact\n render scope. For a dynamic source, also pass the bounded route, detail, or\n Collection variables required to resolve it. Inspect the configured source,\n resolved Asset/revision/scope, capabilities, pending session state,\n diagnostics, and repair routes.\n2. Use `connect-content-block-source` or `switch-content-block-source`. When\n both sides contain body content, choose exactly `use-file-content` or\n `replace-file-body-with-block-content`; content is never merged implicitly.\n3. Use `edit-content-block-source` for semantic text, prop, insert, move,\n reorder, or delete operations against the materialized MDX instances. Do not\n edit generated instance IDs in the file.\n4. Use `disconnect-content-block-source` to copy the resolved file content into\n ordinary project instances and remove the source. The file remains\n unchanged; disconnect never discards the visible body.\n5. If inspection reports a recoverable state, use\n `recover-content-block-source` only for an advertised action: retry, reload\n the remote revision, or copy unsaved local MDX. Recovery must run in the same\n live MCP or `mcp run` session that owns that state. A fresh one-shot CLI\n process or stateless HTTP request returns `content-source-not-loaded` rather\n than reconstructing unsaved in-memory content.\n\nRun replacement and migration operations with `--dry-run` first. A required\napproval returns a short-lived confirmation token bound to the inspected\nproject, Content Block, files, and revisions. Review the plan, then repeat the\noperation with that token. Stale or replayed tokens and changed Asset revisions\nare rejected. Disconnect also requires confirmation because it copies the file\nbody into project storage and removes the source, although it leaves the file\nitself unchanged.\n\nUse `migrate-content-block-template-references` to preview a `ws:name` rename\nor removal across the bounded `.mdx` files discovered from one Content Block\nand template. When automatic discovery cannot prove the complete candidate set,\npass no more than 100 explicitly reviewed Asset IDs. The tool parses the MDX\nAST; it does not use search-and-replace. Review the selected files, update and\nomission counts, and per-file diagnostics before confirmation. Each file uses\nan exact revision check, and partial failures are returned explicitly without\noverwriting newer content. Finite direct, detail, and repeated candidate sets\nare supported; an unbounded or truncated candidate graph blocks automatic\napply until the reviewed set is supplied.\n\nRead the machine-readable `status`, `code`, diagnostics, and source inspection\nafter every call. Lifecycle and semantic edits validate their targets, then\npersist them in a deterministic order. A partial result lists saved, failed,\nand not-attempted steps; completed writes are not rolled back. Reinspect the\ncurrent revisions and retry only unfinished steps. Template migration also\ncommits reviewed files one at a time and reports partial results. See [Content Block](core-components/content-block.md#use-an-mdx-file-as-the-content-source)\nfor the file grammar and Builder workflow.\n\n## Consumer Capabilities\n\nMCP lets agents work on one configured Webstudio project at a time. In consumer\nterms, agents can:\n\n- Check which project they are connected to.\n- Check what the share link is allowed to do.\n- Inspect project metadata and the latest editable build.\n- Read selected project data for audits and repair.\n- Search all Builder namespaces for a known value or id without putting complete namespace data in model context.\n- Apply precise project changes against a known version.\n- List, inspect, create, update, delete, duplicate, copy, and reorder pages.\n- Set the home page.\n- Preserve old page paths for redirects or history.\n- Read and update page titles, descriptions, metadata, auth settings, and SEO fields.\n- List, create, update, duplicate, move, and delete page folders.\n- List, create, update, delete, duplicate, reorder, and reuse page templates.\n- Create pages from reusable templates.\n- Read and update project site settings.\n- Read and update marketplace product metadata.\n- List, create, update, delete, and replace redirects.\n- List, create, update, and delete responsive breakpoints.\n- List and inspect page elements.\n- Insert registered components.\n- Insert styled JSX fragments.\n- Move, reparent, clone, duplicate, wrap, unwrap, convert, rename, retag, and delete elements.\n- Fill grid cells.\n- List and update text children.\n- Update plain text and expression text.\n- Update structured rich text.\n- Add, update, delete, and bind element props.\n- Inspect, connect, switch, disconnect, recover, and semantically edit\n MDX-backed Content Blocks.\n- Preview and apply bounded template-name migrations across reachable MDX\n Assets.\n- Bind props to expressions, resources, actions, and runtime system values.\n- Read, add, update, delete, and replace local styles.\n- Update selected style-source styles.\n- List, create, update, attach, detach, extract, duplicate, rename, lock, unlock, reorder, clear, and delete design tokens and style sources.\n- List, define, rename, delete, and rewrite CSS variables.\n- List, create, update, and delete static data variables.\n- Create string, number, boolean, and JSON variables. Arrays use JSON.\n- Delete unused data variables.\n- List, create, update, upsert, bind, and delete resources.\n- Create HTTP resources.\n- Create GraphQL resources.\n- Create system resources.\n- Use built-in system resources for sitemap, current date, and assets.\n- List and inspect complete asset metadata; upload, download, update, move, duplicate, find usage for, replace, and delete assets.\n- List, create, rename, move, recursively duplicate, and recursively delete nested asset folders.\n- Publish to staging or production.\n- Publish to selected domains.\n- List publish builds.\n- Check publish job status.\n- Unpublish staging or production deployments.\n- List, create, update, delete, and verify custom domains.\n- Start and stop preview.\n- Capture screenshots of generated pages.\n- Compare screenshots against baselines.\n- Install OCR support for richer visual checks.\n\nUseful resources:\n\n- `webstudio://project/status`: compact current ProjectSession status\n- `webstudio://project/tools-overview`: small operation overview by capability area\n- `webstudio://project/components-overview`: small component overview with ids, labels, namespaces, and categories\n- `webstudio://project/tools`: full operation catalog; read only when focused metadata is insufficient\n- `webstudio://project/components`: full component catalog with props, states, and content model composition constraints; read only when `components.summary`, `components.find`, and `components.get` are insufficient\n- `webstudio://project/guide`: concise discovery guide\n- `webstudio://project/expressions`: expression syntax, scope, supported methods, bindings, Collection iteration context, and verification\n- `webstudio://project/accessibility-review`: evidence-based LLM accessibility-review workflow using project checks, preview, and screenshots\n\n## MCP SDK Client Imports\n\nWhen writing a local Node.js MCP client script, use the official MCP SDK package and these exact ESM imports:\n\nInside the Webstudio monorepo this package is available at the repo root. In another project, install it first with `pnpm add -D @modelcontextprotocol/sdk`.\n\n```js\nimport { Client } from "@modelcontextprotocol/sdk/client/index.js";\nimport { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";\nimport { LoggingMessageNotificationSchema } from "@modelcontextprotocol/sdk/types.js";\n```\n\nMinimal stdio client for the local Webstudio CLI:\n\n```js\nconst client = new Client({ name: "webstudio-agent", version: "1.0.0" });\n\nclient.setNotificationHandler(\n LoggingMessageNotificationSchema,\n (notification) => {\n console.error(`[mcp] ${notification.params.data}`);\n }\n);\n\nconst transport = new StdioClientTransport({\n command: "node",\n args: ["packages/cli/local.js", "mcp"],\n cwd: process.cwd(),\n stderr: "inherit",\n});\n\nawait client.connect(transport);\n\nconst index = await client.callTool({\n name: "meta.index",\n arguments: {},\n});\nconsole.log(JSON.stringify(index.structuredContent, null, 2));\n\nawait client.close();\n```\n\nUse `node packages/cli/local.js mcp` from the Webstudio monorepo root for local development, or `webstudio mcp` from a linked project where the CLI is installed. Keep stdout for JSON-RPC/structured results and surface MCP logging notifications or stderr lifecycle lines as progress.\n\n## Core Rules\n\n- stdout is reserved for MCP JSON-RPC while the server is running.\n- Operate on the configured project only.\n- Read ids before writing.\n- Prefer semantic tools over `apply-patch`.\n- Use `status` and `refresh` when cached namespaces may be stale. Pass `status {"verbose":true}` only when debugging full namespace arrays, freshness, compatibility, or diagnostic details.\n- Read `meta.session.commitStatus` before interpreting durability. Read-only results report `not-applicable` and retain `committed:false` for compatibility; dry-run plans report `planned`; failed mutations report `failed`; no-op mutations report `unchanged`; durable mutations report `committed` with `meta.session.committed:true`.\n- For visual/design work, verify the rendered result with vision before finishing.\n\n## Vision Verification Loop\n\nVision-capable AI can use MCP to see what it is building:\n\n{{mcpVisionVerificationLoopMarkdown}}\n\nGenerated app setup:\n\n{{mcpGeneratedAppDependencyNotes}}\n\n## MCP argument examples\n\nExamples below show meaningful argument combinations. Tool schemas are the\nsource of truth. For tools with no required arguments, pass `{}`.\n\n{{mcpArgumentExampleIndex}}\n\n{{contentEngineReferenceMarkdown}}\n\n## Screenshot Verification\n\n{{screenshotVerificationSummary}}\n',"mcp-startup-epilogue":'If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output.\n\nPlain `webstudio mcp` starts the stdio MCP server for real MCP clients. Do not manually type or pipe raw JSON-RPC frames into it from an interactive shell or PTY. From a shell, use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for one bounded tool call. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for small multi-call batches in one shared CLI session. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nPut each local CLI call in its own shell command; do not chain helper commands with `&&`, `;`, command substitution, or shell wrappers around the CLI when reporting a CLI step. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`; those can resolve an older binary. For example:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nSave the input as `.temp/insert-fragment.json`; use single quotes for JSX attributes so the JSON needs no backslash escaping:\n\n```json\n{\n "parentInstanceId": "parent-id",\n "fragment": "<ws.element ws:tag=\'section\' ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag=\'h2\'>Launch Kit</ws.element><ws.element ws:tag=\'p\'>A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag=\'button\'>Get started</ws.element></ws.element>"\n}\n```\n\nThe shorter local shortcut form is preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nFor simple authored/styled sections, run the three commands above. Do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only when you still need the target `parentInstanceId`.\n\nWhen building for a Content-mode editor, use a Content Block (`ws:block`) around every region that editor must change. Content-mode text and supported props are editable only in Content Block descendants; content outside is read-only. Keep reusable insertable source options in the block\'s `ws:block-template` child. Templates themselves are protected; an editor\'s inserted copy becomes an editable direct child of the Content Block. Verify this structure before handoff.\n\nRun it from the linked Webstudio project root. The startup status line prints that absolute root; use it for local files such as `<project root>/.temp/script.mjs`, screenshots, and generated artifacts.\n\nFor experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n\nStartup marks cached ProjectSession data stale so MCP tools read the current Builder dev build.\n\nAfter startup, use focused discovery tools with concrete JSON. For delegated design-system or “use every component” tasks, start with exactly one command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`; report the returned checkpoint to the parent/user and stop until continued. For other tasks, read `meta.index` first. From a shell, `webstudio mcp list-tools` is a concise alias for the initial tool catalog. Then call shortcuts such as `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio workflow.next \'{"goal":"design-system-page"}\'`, `webstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.summary`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`. Use `webstudio mcp single-op-call` when you need the explicit MCP form. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. In JSX, use `ws:style={css\\`...\\`}`for styles,`class`/`for`instead of`className`/`htmlFor`, `ActionValue`for actions instead of JavaScript functions such as`onClick={() => ...}`, only JSON-compatible plain prop values, and no host globals or dynamic code APIs. For bounded multi-step shell work, run inline JSON like `webstudio mcp run \'[{"tool":"meta.index"},{"tool":"components.search","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For larger batches, write `{ "calls": [{ "tool": "..." }] }`to`.temp/mcp-calls.json`and run`webstudio mcp run .temp/mcp-calls.json`. If any call returns `checkpoint.required`, `mcp run`stops immediately before later calls; report the checkpoint and call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`before continuing. For design-system or “use every component” tasks, call`workflow.next {"goal":"design-system-page"}`for the next bounded phase, report its checkpoint, wait until the parent/user continues, call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, then run only that phase. Start coverage phases with compact`webstudio components.coverage-plan`, checkpoint, then request component coverage details with `components.coverage-plan {"detail":"roots"}`or`components.coverage-plan {"detail":"parts"}`. Do not pass `detail`to`list-pages`; use `list-pages {}`or`get-page-by-path`for page lookup. Read MCP overview resources`webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview`when useful. Read full resources`webstudio://project/tools`and`webstudio://project/components` only when focused tools are insufficient; do not dump or parse full discovery JSON for common lookup.\n\nAfter startup, MCP clients discover capabilities with `tools/list`, `resources/list`, `meta.index`, `meta.guide`, and `meta.get-more-tools`.\n\nstdout is reserved for MCP JSON-RPC messages while the server is running.\n\nThe server advertises MCP `logging` capability and sends sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`. It also writes the same sparse lifecycle status lines to stderr, prefixed with `[webstudio mcp]`, including a final ready line. Treat the process as healthy and long-running after either ready signal; surface tool lifecycle logs as progress checkpoints and interact through MCP JSON-RPC on stdin/stdout.\n\n`webstudio mcp single-op-call` also writes sparse lifecycle lines to stderr for each one-shot call. Use those stderr lines as progress checkpoints and parse stdout as JSON on both success and failure. Failed one-shot calls print `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` to stdout and exit nonzero. If a one-shot call returns checkpoint.required, read-only discovery remains available, while later mutations fail with `CHECKPOINT_REQUIRED` until you report the checkpoint and call `webstudio mcp single-op-call checkpoint.ack \'{"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}\'`.\n\n`webstudio mcp run` also writes sparse lifecycle lines to stderr and prints one JSON result on success or failure. It stops at the first failed call or checkpoint requirement, including `CHECKPOINT_REQUIRED`, and preserves partial results so delegated agents can report exactly where they stopped.\n\nWhen `report-issue` is available, use it when the user explicitly asks to report a problem. Also use it automatically after a Webstudio-controlled tool crash, hang, malformed result, misleading success, repeated failure of the same documented operation, failed documented recovery, or required undocumented workaround. Do not automatically report expected confirmation/checkpoint flow, a clearly explained invalid input, missing permissions, `PROJECT_SESSION_BUSY`, a recovered version conflict, rate limiting, cancellation, or an offline environment. Write a complete anonymous report with the generalized user story, attempted workflow, expected behavior, actual result, recovery attempts, impact, technical context, acceptance criteria, exact model identifier, and reasoning effort. Never include names, usernames, emails, phone numbers, organizations, project or resource ids, domains, URLs, IP addresses, local paths, credentials, tokens, customer content, exact unique values, or raw contextual tool data.\n\nIf you are running as a delegated or non-streaming agent whose parent cannot see live stderr/stdout, do not batch many MCP calls silently and do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, return a concise checkpoint with that command/result, and wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase.\n',"mcp-vision":diff --git a/packages/cli/src/docs/manual-mcp.md b/packages/cli/src/docs/manual-mcp.mdindex bd321cd104..de061c443e 100644--- a/packages/cli/src/docs/manual-mcp.md+++ b/packages/cli/src/docs/manual-mcp.md@@ -270,6 +270,63 @@ Component and template registry items use a shadcn-compatible top-level shape plPrefer the focused `components.*` tools over dumping `webstudio://project/components`. Do not write local scripts to parse full MCP discovery JSON for common component lookup.For “use every component” or design-system pages, start with compact `components.coverage-plan`, checkpoint, then page through roots/parts instead of dumping the full catalog.+## MDX Content Block workflow++Content Blocks can store their editable body in an `.mdx` Asset. The Builder,+direct CLI, HTTP API, and MCP use the same source resolver, safe MDX parser,+Content mode permissions, serializer, diagnostics, Asset authorization, and+revision checks.++Use the focused tools instead of downloading and rewriting the file as text:++1. Call `inspect-content-block-source` with the Content Block ID and exact+ render scope. For a dynamic source, also pass the bounded route, detail, or+ Collection variables required to resolve it. Inspect the configured source,+ resolved Asset/revision/scope, capabilities, pending session state,+ diagnostics, and repair routes.+2. Use `connect-content-block-source` or `switch-content-block-source`. When+ both sides contain body content, choose exactly `use-file-content` or+ `replace-file-body-with-block-content`; content is never merged implicitly.+3. Use `edit-content-block-source` for semantic text, prop, insert, move,+ reorder, or delete operations against the materialized MDX instances. Do not+ edit generated instance IDs in the file.+4. Use `disconnect-content-block-source` to copy the resolved file content into+ ordinary project instances and remove the source. The file remains+ unchanged; disconnect never discards the visible body.+5. If inspection reports a recoverable state, use+ `recover-content-block-source` only for an advertised action: retry, reload+ the remote revision, or copy unsaved local MDX. Recovery must run in the same+ live MCP or `mcp run` session that owns that state. A fresh one-shot CLI+ process or stateless HTTP request returns `content-source-not-loaded` rather+ than reconstructing unsaved in-memory content.++Run replacement and migration operations with `--dry-run` first. A required+approval returns a short-lived confirmation token bound to the inspected+project, Content Block, files, and revisions. Review the plan, then repeat the+operation with that token. Stale or replayed tokens and changed Asset revisions+are rejected. Disconnect also requires confirmation because it copies the file+body into project storage and removes the source, although it leaves the file+itself unchanged.++Use `migrate-content-block-template-references` to preview a `ws:name` rename+or removal across the bounded `.mdx` files discovered from one Content Block+and template. When automatic discovery cannot prove the complete candidate set,+pass no more than 100 explicitly reviewed Asset IDs. The tool parses the MDX+AST; it does not use search-and-replace. Review the selected files, update and+omission counts, and per-file diagnostics before confirmation. Each file uses+an exact revision check, and partial failures are returned explicitly without+overwriting newer content. Finite direct, detail, and repeated candidate sets+are supported; an unbounded or truncated candidate graph blocks automatic+apply until the reviewed set is supplied.++Read the machine-readable `status`, `code`, diagnostics, and source inspection+after every call. Lifecycle and semantic edits validate their targets, then+persist them in a deterministic order. A partial result lists saved, failed,+and not-attempted steps; completed writes are not rolled back. Reinspect the+current revisions and retry only unfinished steps. Template migration also+commits reviewed files one at a time and reports partial results. See [Content Block](core-components/content-block.md#use-an-mdx-file-as-the-content-source)+for the file grammar and Builder workflow.+## Consumer CapabilitiesMCP lets agents work on one configured Webstudio project at a time. In consumer@@ -301,6 +358,10 @@ terms, agents can:- Update plain text and expression text.- Update structured rich text.- Add, update, delete, and bind element props.+- Inspect, connect, switch, disconnect, recover, and semantically edit+ MDX-backed Content Blocks.+- Preview and apply bounded template-name migrations across reachable MDX+ Assets.- Bind props to expressions, resources, actions, and runtime system values.- Read, add, update, delete, and replace local styles.- Update selected style-source styles.diff --git a/packages/cli/src/prebuild.test.ts b/packages/cli/src/prebuild.test.tsindex 45c049fe67..18dfd94f42 100644--- a/packages/cli/src/prebuild.test.ts+++ b/packages/cli/src/prebuild.test.ts@@ -23,7 +23,14 @@ import {import { build } from "esbuild";import { loadConfigFromFile } from "vite";import { bundleVersion } from "@webstudio-is/protocol";-import type { Asset, Instance, Prop } from "@webstudio-is/sdk";+import type {+ Asset,+ Instance,+ Prop,+ StyleDecl,+ StyleSource,+ StyleSourceSelection,+} from "@webstudio-is/sdk";import {createDocumentGraph,type AssetFileDocument,@@ -237,6 +244,9 @@ const createSiteData = (}>;instances?: Array<[string, Omit<Instance, "type">]>;props?: Array<[string, Prop]>;+ styleSources?: Array<[string, StyleSource]>;+ styleSourceSelections?: Array<[string, StyleSourceSelection]>;+ styles?: Array<[string, StyleDecl]>;pageMeta?: Record<string, unknown>;redirects?: Redirects;} = {}@@ -331,9 +341,9 @@ const createSiteData = ().map(([id, instance]) => [id, { type: "instance", ...instance }]),dataSources: [],resources: [],- styleSources: [],- styleSourceSelections: [],- styles: [],+ styleSources: overrides.styleSources ?? [],+ styleSourceSelections: overrides.styleSourceSelections ?? [],+ styles: overrides.styles ?? [],breakpoints: [],},};@@ -781,6 +791,337 @@ test("hydrates encoded filenames from an embedded SSG database", async () => {});describe("prebuild", () => {+ test("materializes direct MDX Content Blocks into generated page code", async () => {+ const source = "# Published from MDX";+ const article: AssetFileDocument = {+ ...indexedDocument,+ _id: "article",+ name: "article.mdx",+ path: "article.mdx",+ key: "article",+ extension: "mdx",+ mimeType: "text/mdx",+ size: new TextEncoder().encode(source).byteLength,+ revision: "article-revision",+ contentRef: "article.mdx",+ properties: {},+ };+ const siteData = createSiteData({+ assets: [createAssetForIndexedDocument(article)],+ instances: [+ [+ "root",+ {+ id: "root",+ component: "Box",+ children: [{ type: "id", value: "content" }],+ },+ ],+ [+ "content",+ {+ id: "content",+ component: "ws:block",+ children: [],+ },+ ],+ ],+ props: [+ [+ "content-src",+ {+ id: "content-src",+ instanceId: "content",+ name: "src",+ type: "asset",+ value: "article",+ },+ ],+ ],+ });+ const siteDataWithIndex = {+ ...siteData,+ assetIndex: await createTestAssetIndex(article, {+ "article.mdx": source,+ }),+ };+ await writeSiteData(siteDataWithIndex);++ await prebuild({ assets: false, template: ["react-router"] });++ const generatedPage = await readFile(+ "app/__generated__/_index.tsx",+ "utf8"+ );+ expect(generatedPage).toContain("Published from MDX");+ expect(generatedPage).not.toContain("fetch(");+ expect(generatedPage).not.toContain("unresolved-template");+ });++ test("includes font preloads from an MDX-selected template", async () => {+ const source = '<ws.element ws:name="Hero" />';+ const article: AssetFileDocument = {+ ...indexedDocument,+ _id: "article",+ name: "article.mdx",+ path: "article.mdx",+ key: "article",+ extension: "mdx",+ mimeType: "text/mdx",+ size: source.length,+ revision: "article-revision",+ contentRef: "article.mdx",+ properties: {},+ };+ const font: Asset = {+ id: "hero-font",+ projectId: "project-id",+ name: "hero.woff2",+ type: "font",+ format: "woff2",+ size: 1,+ meta: { family: "Hero Font", style: "normal", weight: 400 },+ description: "",+ createdAt: "2024-01-01T00:00:00.000Z",+ };+ const unusedFont: Asset = {+ ...font,+ id: "unused-font",+ name: "unused.woff2",+ meta: { ...font.meta, family: "Unused Font" },+ };+ const siteData = createSiteData({+ assets: [createAssetForIndexedDocument(article), font, unusedFont],+ instances: [+ [+ "root",+ {+ id: "root",+ component: "Box",+ children: [{ type: "id", value: "content" }],+ },+ ],+ [+ "content",+ {+ id: "content",+ component: "ws:block",+ children: [{ type: "id", value: "templates" }],+ },+ ],+ [+ "templates",+ {+ id: "templates",+ component: "ws:block-template",+ children: [+ { type: "id", value: "hero" },+ { type: "id", value: "unused" },+ ],+ },+ ],+ [+ "unused",+ {+ id: "unused",+ component: "ws:element",+ tag: "section",+ label: "Unused",+ children: [],+ },+ ],+ [+ "hero",+ {+ id: "hero",+ component: "ws:element",+ tag: "section",+ label: "Hero",+ children: [],+ },+ ],+ ],+ props: [+ [+ "content-src",+ {+ id: "content-src",+ instanceId: "content",+ name: "src",+ type: "asset",+ value: "article",+ },+ ],+ ],+ styleSources: [+ ["hero-style", { type: "local", id: "hero-style" }],+ ["unused-style", { type: "local", id: "unused-style" }],+ ],+ styleSourceSelections: [+ ["hero", { instanceId: "hero", values: ["hero-style"] }],+ ["unused", { instanceId: "unused", values: ["unused-style"] }],+ ],+ styles: [+ [+ "hero-style:base:fontFamily:",+ {+ styleSourceId: "hero-style",+ breakpointId: "base",+ property: "fontFamily",+ value: { type: "fontFamily", value: ["Hero Font"] },+ },+ ],+ [+ "unused-style:base:fontFamily:",+ {+ styleSourceId: "unused-style",+ breakpointId: "base",+ property: "fontFamily",+ value: { type: "fontFamily", value: ["Unused Font"] },+ },+ ],+ ],+ });+ const siteDataWithIndex = {+ ...siteData,+ assetIndex: await createTestAssetIndex(article, {+ "article.mdx": source,+ }),+ };+ await writeSiteData(siteDataWithIndex);++ await prebuild({ assets: false, template: ["react-router"] });++ const generatedPage = await readFile(+ "app/__generated__/_index.tsx",+ "utf8"+ );+ expect(generatedPage).toContain(+ 'export const pageFontAssets: string[] =\n ["hero.woff2"]'+ );+ expect(generatedPage).not.toContain("unused.woff2");+ });++ test("materializes finite dynamic MDX candidates without publishing unrelated files", async () => {+ const createDocument = (+ id: string,+ extension: "json" | "mdx",+ properties?: Record<string, string>+ ): AssetFileDocument => ({+ ...indexedDocument,+ _id: id,+ name: `${id}.${extension}`,+ path: `${id}.${extension}`,+ key: id,+ extension,+ mimeType: extension === "mdx" ? "text/mdx" : "application/json",+ revision: `${id}-revision`,+ contentRef: `${id}.${extension}`,+ properties: properties ?? {},+ });+ const post = createDocument("post", "json", {+ category: "published",+ mdx: "article",+ });+ const privatePost = createDocument("private-post", "json", {+ category: "private",+ mdx: "private",+ });+ const article = createDocument("article", "mdx");+ const privateArticle = createDocument("private", "mdx");+ const documents = [post, privatePost, article, privateArticle];+ const sourceExpression = `${encodeDataSourceVariable(+ "posts-data"+ )}.data.properties.mdx`;+ const siteData = createSiteData({+ assets: documents.map(createAssetForIndexedDocument),+ instances: [+ [+ "root",+ {+ id: "root",+ component: "Box",+ children: [{ type: "id", value: "content" }],+ },+ ],+ [+ "content",+ {+ id: "content",+ component: "ws:block",+ children: [],+ },+ ],+ ],+ props: [+ [+ "content-src",+ {+ id: "content-src",+ instanceId: "content",+ name: "src",+ type: "expression",+ value: sourceExpression,+ },+ ],+ ],+ });+ siteData.build.dataSources = [+ [+ "posts-data",+ {+ type: "resource",+ id: "posts-data",+ scopeInstanceId: "root",+ name: "posts",+ resourceId: "posts",+ },+ ],+ ] as never;+ siteData.build.resources = [+ [+ "posts",+ {+ ...createQueryResource(),+ body: createStructuredAssetQueryResourceBody({+ where: {+ all: [+ {+ field: ["properties", "category"],+ operator: "eq",+ value: '"published"',+ },+ ],+ },+ sort: [],+ limit: "100",+ offset: "0",+ output: { mode: "all", includeMetadata: true },+ content: { mode: "none" },+ }),+ },+ ],+ ] as never;+ const siteDataWithIndex = {+ ...siteData,+ assetIndex: await createTestAssetIndex(documents, {+ "article.mdx": "# Public article",+ "private.mdx": "# Private article",+ }),+ };+ await writeSiteData(siteDataWithIndex);++ await prebuild({ assets: false, template: ["react-router"] });++ const generatedPage = await readFile(+ "app/__generated__/_index.tsx",+ "utf8"+ );+ expect(generatedPage).toContain("Public article");+ expect(generatedPage).not.toContain("Private article");+ expect(generatedPage).toContain('=== "article"');+ });+test("imports only configured Code Text language and theme assets", async () => {await writeSiteData(createCodeTextSiteData([@@ -2454,7 +2795,9 @@ sitemap.map((page) => page.path);`{field: ["properties", "slug"],operator: "eq",- value: `${encodeDataSourceVariable(SYSTEM_VARIABLE_ID)}.params.slug`,+ value: `${encodeDataSourceVariable(+ SYSTEM_VARIABLE_ID+ )}.params.slug`,},],},diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.tsindex 68aad6a96c..e88df61383 100644--- a/packages/cli/src/prebuild.ts+++ b/packages/cli/src/prebuild.ts@@ -14,8 +14,10 @@ import { fileURLToPath } from "node:url";import { parse } from "acorn";import { log, spinner } from "@clack/prompts";import merge from "deepmerge";+import deepEqual from "fast-deep-equal";import {generateWebstudioComponent,+ type PublishedContentBlock,type Params,normalizeProps,generateRemixRoute,@@ -37,11 +39,13 @@ import {decodeDataSourceVariable,SYSTEM_VARIABLE_ID,generateCss,+ getStyleDeclKey,ROOT_INSTANCE_ID,elementComponent,toRuntimeAsset,matchPathnameParams,- createReachableAssetContentCompilationPlan,+ blockComponent,+ blockTemplateComponent,parseStructuredAssetQueryResourceBody,type StructuredAssetQueryFilterBinding,type StructuredAssetQueryWhereBinding,@@ -57,7 +61,16 @@ import {type ComponentBuildContribution,} from "@webstudio-is/sdk";import { migratePages } from "@webstudio-is/project-migrations/pages";-import { collectFontFamiliesFromStyleDecls } from "@webstudio-is/project-build/runtime";+import {+ collectFontFamiliesFromStyleDecls,+ createPublishedMdxMaterializationCache,+ materializePublishedMdx,+} from "@webstudio-is/project-build/runtime";+import {+ createPublishedBuildContentCompilationPlan,+ hasDynamicPublishedMdxSources,+ resolvePublishedMdxAssetCandidates,+} from "@webstudio-is/project-build";import {assetQueryFilter,type AssetQueryFilter,@@ -130,6 +143,7 @@ type SiteDataByPage = {assets: Array<Asset>;params?: Params;pages: Array<Page>;+ publishedContentBlocks?: ReadonlyMap<string, PublishedContentBlock>;};};@@ -922,6 +936,32 @@ export const prebuild = async (options: {);}const siteData = parsedSiteData.data;+ const pages = migratePages(siteData.build.pages);+ const publicationBuild = { ...siteData.build, pages };+ const verifiedAssetIndex =+ siteData.assetIndex === undefined+ ? undefined+ : await verifyContentArtifact(siteData.assetIndex);+ let dynamicMdxCandidates: ReadonlyMap<string, readonly string[]> | undefined;+ if (hasDynamicPublishedMdxSources(publicationBuild)) {+ if (verifiedAssetIndex === undefined) {+ throw new Error(+ "Dynamic MDX dependencies are unavailable in the Asset artifact"+ );+ }+ dynamicMdxCandidates = resolvePublishedMdxAssetCandidates({+ build: publicationBuild,+ artifact: verifiedAssetIndex,+ });+ }+ const assetCompilationPlan = createPublishedBuildContentCompilationPlan(+ publicationBuild,+ dynamicMdxCandidates+ );+ const hasPublishedMdxSources =+ assetCompilationPlan?.queries.some(({ id }) =>+ id.startsWith("__content-block-mdx__:")+ ) ?? false;await configureSsgAssetResourceFetch({enabled: siteData.assetIndex !== undefined,});@@ -929,7 +969,6 @@ export const prebuild = async (options: {const usedMetas = new Map<Instance["component"], WsComponentMeta>(Object.entries(coreMetas));- const pages = migratePages(siteData.build.pages);const publishablePages = getPublishablePages(pages);const generatedPages = options.includeDraftPages? getAllPages(pages)@@ -1014,78 +1053,344 @@ export const prebuild = async (options: {page,assets: siteData.assets,};+ }- // Extract background SVGs and Font assets- const styleSourceSelections = siteData.build?.styleSourceSelections ?? [];- const pageStyleSourceIds = new Set(- styleSourceSelections- .filter(([, { instanceId }]) => pageInstanceSet.has(instanceId))- .map(([, { values }]) => values)- .flat()- );+ if (options.assets === true) {+ const assetOrigin = siteData.origin;- const pageStyles =- siteData.build?.styles- ?.filter(([, { styleSourceId }]) =>- pageStyleSourceIds.has(styleSourceId)+ if (!assetOrigin) {+ console.warn("Warning: Asset origin is not defined in project bundle.");+ }+ }++ const assets = new Map(siteData.assets.map((asset) => [asset.id, asset]));++ const publishedInstances = new Map(siteData.build.instances);+ const publishedProps = new Map(siteData.build.props);+ const publishedStyleSources = new Map(siteData.build.styleSources);+ const publishedStyleSourceSelections = new Map(+ siteData.build.styleSourceSelections+ );+ const publishedStyles = new Map(siteData.build.styles);+ const publishedBreakpoints = new Map(siteData.build.breakpoints);+ if (hasPublishedMdxSources && siteData.assetIndex === undefined) {+ throw new Error(+ "Published Content Block MDX dependencies are unavailable in the Asset artifact"+ );+ }+ if (verifiedAssetIndex !== undefined) {+ const publishedMdxCache = createPublishedMdxMaterializationCache();+ const mergeRecord = <Value>(+ target: Map<string, Value>,+ key: string,+ value: Value,+ namespace: string+ ) => {+ const existing = target.get(key);+ if (existing !== undefined && deepEqual(existing, value)) {+ return;+ }+ if (existing !== undefined) {+ throw new Error(+ `Published MDX ${namespace} collision for ${JSON.stringify(key)}`+ );+ }+ target.set(key, value);+ };+ for (const page of generatedPages) {+ const pageData = siteDataByPage[page.id];+ const pageInstances = new Map(pageData.build.instances);+ const pageProps = new Map(pageData.build.props);+ const materializationProps = new Map(+ siteData.build.props.filter(([, prop]) =>+ pageInstances.has(prop.instanceId))- .map(([, style]) => style) ?? [];+ );+ const pageDataSources = new Map(pageData.build.dataSources);+ const pageResources = new Map(pageData.build.resources);+ const candidatesByBlock = new Map<string, PublishedContentBlock>();+ const processedBlockIds = new Set<string>();+ const getRenderedBlockIds = () => {+ const blockIds = new Set<string>();+ const visited = new Set<string>();+ const visit = (instanceId: string) => {+ if (visited.has(instanceId)) {+ return;+ }+ visited.add(instanceId);+ const instance = pageInstances.get(instanceId);+ if (+ instance === undefined ||+ instance.component === blockTemplateComponent+ ) {+ return;+ }+ if (instance.component === blockComponent) {+ blockIds.add(instance.id);+ }+ for (const child of instance.children) {+ if (child.type === "id") {+ visit(child.value);+ }+ }+ };+ visit(page.rootInstanceId);+ return blockIds;+ };+ for (;;) {+ const pendingBlockIds = new Set(+ Array.from(getRenderedBlockIds()).filter(+ (blockId) => processedBlockIds.has(blockId) === false+ )+ );+ if (pendingBlockIds.size === 0) {+ break;+ }+ for (const blockId of pendingBlockIds) {+ processedBlockIds.add(blockId);+ }+ const pageBuild = {+ instances: Array.from(pageInstances.values()),+ props: Array.from(materializationProps.values()),+ dataSources: Array.from(pageDataSources.values()),+ resources: Array.from(pageResources.values()),+ };+ const pageDynamicCandidates = hasDynamicPublishedMdxSources(+ pageBuild,+ pendingBlockIds+ )+ ? resolvePublishedMdxAssetCandidates({+ build: pageBuild,+ artifact: verifiedAssetIndex,+ blockInstanceIds: pendingBlockIds,+ })+ : undefined;+ const materialized = await materializePublishedMdx({+ route: getPagePath(page.id, pages),+ data: {+ instances: pageInstances,+ props: materializationProps,+ dataSources: pageDataSources,+ resources: pageResources,+ styleSources: publishedStyleSources,+ styleSourceSelections: publishedStyleSourceSelections,+ styles: publishedStyles,+ breakpoints: publishedBreakpoints,+ assets,+ },+ artifact: verifiedAssetIndex,+ metas: usedMetas,+ projectId: siteData.build.projectId,+ cache: publishedMdxCache,+ dynamicAssetIdsByBlock: pageDynamicCandidates,+ blockInstanceIds: pendingBlockIds,+ });+ for (const root of materialized.roots) {+ if (root.dynamic && root.fragment.resources.length > 0) {+ const sourcePath =+ root.source.type === "expression"+ ? parseStaticMemberPath(root.source.value)+ : undefined;+ const sourceDataSourceId =+ sourcePath === undefined+ ? undefined+ : decodeDataSourceVariable(sourcePath[0]);+ if (+ sourceDataSourceId !== undefined &&+ pageDataSources.get(sourceDataSourceId)?.type === "parameter"+ ) {+ throw new Error(+ `Dynamic published MDX Asset "${root.identity.assetId}" uses a Collection-scoped Resource that cannot be selected once per route`+ );+ }+ }+ const actionResourceIds = new Set(+ [...materializationProps.values(), ...root.fragment.props].flatMap(+ (prop) => (prop.type === "resource" ? [prop.value] : [])+ )+ );+ if (+ root.dynamic &&+ root.fragment.resources.some(({ id }) => actionResourceIds.has(id))+ ) {+ throw new Error(+ `Dynamic published MDX Asset "${root.identity.assetId}" contains an action Resource that cannot be selected safely at submission time`+ );+ }+ for (const instance of root.fragment.instances) {+ mergeRecord(pageInstances, instance.id, instance, "instance");+ mergeRecord(publishedInstances, instance.id, instance, "instance");+ }+ for (const prop of root.fragment.props) {+ mergeRecord(materializationProps, prop.id, prop, "authored prop");+ }+ const normalizedFragmentProps = normalizeProps({+ props: root.fragment.props,+ assetBaseUrl,+ assets,+ uploadingImageAssets: [],+ pages,+ source: "prebuild",+ });+ for (const prop of normalizedFragmentProps) {+ mergeRecord(pageProps, prop.id, prop, "prop");+ mergeRecord(publishedProps, prop.id, prop, "prop");+ }+ for (const dataSource of root.fragment.dataSources) {+ mergeRecord(+ pageDataSources,+ dataSource.id,+ dataSource,+ "data source"+ );+ }+ for (const resource of root.fragment.resources) {+ mergeRecord(pageResources, resource.id, resource, "resource");+ }+ for (const styleSource of root.fragment.styleSources) {+ mergeRecord(+ publishedStyleSources,+ styleSource.id,+ styleSource,+ "style source"+ );+ }+ for (const selection of root.fragment.styleSourceSelections) {+ mergeRecord(+ publishedStyleSourceSelections,+ selection.instanceId,+ selection,+ "style source selection"+ );+ }+ for (const style of root.fragment.styles) {+ mergeRecord(+ publishedStyles,+ getStyleDeclKey(style),+ style,+ "style declaration"+ );+ }+ for (const breakpoint of root.fragment.breakpoints) {+ mergeRecord(+ publishedBreakpoints,+ breakpoint.id,+ breakpoint,+ "breakpoint"+ );+ }+ const previous = candidatesByBlock.get(root.identity.blockInstanceId);+ candidatesByBlock.set(root.identity.blockInstanceId, {+ ...(root.source.type === "expression"+ ? { sourceExpression: root.source.value }+ : {}),+ candidates: [+ ...(previous?.candidates ?? []),+ {+ assetId: root.identity.assetId,+ dependencyRevision: root.dependencyRevision,+ children: root.fragment.children,+ resourceIds: root.fragment.resources.map(({ id }) => id),+ },+ ],+ });+ }+ for (const warning of materialized.warnings) {+ console.warn(+ JSON.stringify({+ type: "webstudio-build-warning",+ feature: "content-block-mdx",+ route: warning.route,+ ...warning.diagnostic,+ })+ );+ }+ }+ pageData.build.instances = Array.from(pageInstances);+ pageData.build.props = Array.from(pageProps);+ pageData.build.dataSources = Array.from(pageDataSources);+ pageData.build.resources = Array.from(pageResources);+ pageData.publishedContentBlocks = candidatesByBlock;+ }+ }- // Extract fonts+ // Collect preload dependencies after MDX projection. Filtering selections by+ // each page's projected instances prevents unused candidates from leaking+ // font or background preloads onto other routes.+ for (const page of generatedPages) {+ const pageInstances = new Map(siteDataByPage[page.id].build.instances);+ const pageInstanceIds = new Set<string>();+ const visitRenderedInstance = (instanceId: string) => {+ if (pageInstanceIds.has(instanceId)) {+ return;+ }+ pageInstanceIds.add(instanceId);+ const instance = pageInstances.get(instanceId);+ if (+ instance === undefined ||+ instance.component === blockTemplateComponent+ ) {+ return;+ }+ for (const child of instance.children) {+ if (child.type === "id") {+ visitRenderedInstance(child.value);+ }+ }+ };+ visitRenderedInstance(page.rootInstanceId);+ for (const block of siteDataByPage[+ page.id+ ].publishedContentBlocks?.values() ?? []) {+ if (block.sourceExpression !== undefined) {+ continue;+ }+ for (const candidate of block.candidates) {+ for (const child of candidate.children) {+ if (child.type === "id") {+ visitRenderedInstance(child.value);+ }+ }+ }+ }+ const pageStyleSourceIds = new Set(+ Array.from(publishedStyleSourceSelections.values())+ .filter(({ instanceId }) => pageInstanceIds.has(instanceId))+ .flatMap(({ values }) => values)+ );+ const pageStyles = Array.from(publishedStyles.values()).filter(+ ({ styleSourceId }) => pageStyleSourceIds.has(styleSourceId)+ );const pageFontFamilies = collectFontFamiliesFromStyleDecls(pageStyles);-- const pageFontAssets = siteData.assets+ fontAssetsByPage[page.id] = siteData.assets.filter((asset) => asset.type === "font")- .filter((fontAsset) => pageFontFamilies.has(fontAsset.meta.family))+ .filter((asset) => pageFontFamilies.has(asset.meta.family)).map((asset) => asset.name);- fontAssetsByPage[page.id] = pageFontAssets;-- // Extract background images- // backgroundImage => "value.type=="layers" => value.type == "image" => .value (assetId)- const backgroundImageAssetIdSet = new Set(- pageStyles- .filter(({ property }) => property === "backgroundImage")- .map(({ value }) =>- value.type === "layers"- ? value.value.map((layer) =>- layer.type === "image"- ? layer.value.type === "asset"- ? layer.value.value- : undefined- : undefined- )- : undefined- )- .flat()- .filter(<T>(value: T): value is NonNullable<T> => value !== undefined)+ const backgroundImageAssetIds = new Set(+ pageStyles.flatMap(({ property, value }) =>+ property === "backgroundImage" && value.type === "layers"+ ? value.value.flatMap((layer) =>+ layer.type === "image" && layer.value.type === "asset"+ ? [layer.value.value]+ : []+ )+ : []+ ));-- const backgroundImageAssets = siteData.assets+ backgroundImageAssetsByPage[page.id] = siteData.assets.filter((asset) => asset.type === "image")- .filter((imageAsset) => backgroundImageAssetIdSet.has(imageAsset.id))+ .filter((asset) => backgroundImageAssetIds.has(asset.id)).map((asset) => asset.name);-- backgroundImageAssetsByPage[page.id] = backgroundImageAssets;}- if (options.assets === true) {- const assetOrigin = siteData.origin;-- if (!assetOrigin) {- console.warn("Warning: Asset origin is not defined in project bundle.");- }- }-- const assets = new Map(siteData.assets.map((asset) => [asset.id, asset]));-const { cssText, classes } = generateCss({- instances: new Map(siteData.build.instances),- props: new Map(siteData.build.props),+ instances: publishedInstances,+ props: publishedProps,assets,- breakpoints: new Map(siteData.build?.breakpoints),- styles: new Map(siteData.build?.styles),- styleSourceSelections: new Map(siteData.build?.styleSourceSelections),+ breakpoints: publishedBreakpoints,+ styles: publishedStyles,+ styleSourceSelections: publishedStyleSourceSelections,// pass only used metas to not generate unused preset stylescomponentMetas: usedMetas,assetBaseUrl,@@ -1235,6 +1540,7 @@ export const prebuild = async (options: {classesMap: classes,metas: usedMetas,tagsOverrides: framework.tags,+ publishedContentBlocks: pageData.publishedContentBlocks,});const projectMeta = siteData.build.projectSettings?.meta ?? pages.meta;@@ -1333,6 +1639,23 @@ export const prebuild = async (options: {dataSources,props,resources,+ contentBlockResourceSelections: Array.from(+ pageData.publishedContentBlocks?.values() ?? []+ ).flatMap((block) =>+ block.sourceExpression === undefined+ ? []+ : [+ {+ sourceExpression: block.sourceExpression,+ candidates: block.candidates.map(+ ({ assetId, resourceIds = [] }) => ({+ assetId,+ resourceIds,+ })+ ),+ },+ ]+ ),})}${generatePageMeta({@@ -1450,12 +1773,6 @@ export const prebuild = async (options: {];}));- const assetCompilationPlan = createReachableAssetContentCompilationPlan({- props: siteData.build.props.map(([, prop]) => prop),- dataSources: siteData.build.dataSources.map(([, dataSource]) => dataSource),- resources: siteData.build.resources.map(([, resource]) => resource),- });-await materializeAssetIndex({index: siteData.assetIndex,runtimeAssets: assetsById,diff --git a/packages/cli/src/project-session.test.ts b/packages/cli/src/project-session.test.tsindex fbfc8df306..d967e7bd1c 100644--- a/packages/cli/src/project-session.test.ts+++ b/packages/cli/src/project-session.test.ts@@ -5,12 +5,17 @@ import { afterEach, describe, expect, test, vi } from "vitest";import { createBuilderStateFromSnapshot } from "@webstudio-is/project-build/state";import { createBuilderStateFreshness } from "@webstudio-is/project-build/state";import { builderNamespaces } from "@webstudio-is/project-build/contracts";-import { createStructuredAssetQueryResourceBody } from "@webstudio-is/sdk";+import {+ blockComponent,+ blockTemplateComponent,+ createStructuredAssetQueryResourceBody,+} from "@webstudio-is/sdk";import {createLocalProjectBundleFromSessionSnapshot,createCliProjectRestorePointStorage,createCliProjectSessionStorage,createCliProjectSessionTransport,+ createCliProjectSession,addIssueReportRuntime,getCliServerApiContract,getCliProjectSessionFile,@@ -615,6 +620,239 @@ test("rejects incomplete project session snapshots before preview generation", (});describe("cli project session transport", () => {+ test("loads exact MDX source identity for MCP inspection", async () => {+ const source = "# CLI content";+ const bytes = new TextEncoder().encode(source);+ const state = createBuilderStateFromSnapshot({+ pages: {+ homePageId: "home",+ rootFolderId: "root-folder",+ pages: new Map([+ [+ "home",+ {+ id: "home",+ name: "Home",+ title: "Home",+ path: "",+ rootInstanceId: "block",+ meta: {},+ },+ ],+ ]),+ folders: new Map([+ [+ "root-folder",+ {+ id: "root-folder",+ name: "Root",+ slug: "",+ children: ["home"],+ },+ ],+ ]),+ },+ instances: [+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: "templates" }],+ },+ ],+ [+ "templates",+ {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [],+ },+ ],+ ],+ props: [+ [+ "src",+ {+ id: "src",+ instanceId: "block",+ name: "src",+ type: "asset",+ value: "article",+ },+ ],+ ],+ assets: [+ [+ "article",+ {+ id: "article",+ type: "file",+ format: "mdx",+ name: "article.mdx",+ description: "",+ projectId: "project",+ size: bytes.byteLength,+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ ],+ ],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSources: [],+ styleSourceSelections: [],+ styles: [],+ } as never);+ const executeServerOperation = vi.fn(async (_request: unknown) => ({+ version: 1,+ status: "confirmation-required",+ discoveryComplete: true,+ updateCount: 1,+ omissionCount: 0,+ changedAsset: false,+ files: [],+ confirmationToken: "migration-token",+ confirmationExpiresAt: "2026-01-01T00:05:00.000Z",+ }));+ const transport = {+ getCompatibility: async () => ({+ sessionVersion: "test-session",+ runtimeContractVersion: "test-runtime",+ projectSchemaVersion: "test-project",+ apiCompatibilityVersion: "test-api",+ }),+ fetchNamespaces: async () => ({+ projectId: "project",+ buildId: "build",+ version: 1,+ state,+ }),+ commitPatch: async () => ({ version: 2 }),+ commitRestorePoint: async () => ({ version: 2 }),+ executeServerOperation: async <Result>(request: {+ operationId: string;+ input: unknown;+ }) => (await executeServerOperation(request)) as Result,+ getPermissions: async () => ({+ canView: true,+ canEdit: true,+ canBuild: true,+ canAdmin: true,+ canUseApi: true,+ }),+ };+ const session = createCliProjectSession({+ connection: previewConnection,+ transport,+ storage: {+ load: async () => undefined,+ save: async () => undefined,+ clear: async () => undefined,+ },+ assetContentRepository: {+ readContent: async () => ({+ asset: {+ id: "article",+ projectId: "project",+ type: "file",+ format: "mdx",+ name: "article-revision.mdx",+ size: bytes.byteLength,+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ data: {+ async *[Symbol.asyncIterator]() {+ yield bytes;+ },+ },+ }),+ updateContent: async () => {+ throw new Error("Unexpected write");+ },+ },+ });+ await session.initialize();++ const result = await session.read("contentBlocks.inspectSource", {+ blockInstanceId: "block",+ renderScope: "page:/",+ });+ expect(result).toMatchObject({+ source: "local",+ result: {+ configuredSource: { type: "asset", assetId: "article" },+ resolvedIdentity: {+ assetId: "article",+ contentRef: "article-revision.mdx",+ renderScope: "page:/",+ },+ sessionStatus: "saved",+ capabilities: { canEdit: true },+ },+ });++ await expect(+ session.mutate("contentBlocks.migrateTemplateReferences", {+ templateInstanceId: "template",+ migration: { type: "remove" },+ renderScope: "page:/",+ dryRun: true,+ })+ ).resolves.toMatchObject({+ result: {+ status: "confirmation-required",+ confirmation: { token: "migration-token" },+ },+ });+ expect(executeServerOperation).toHaveBeenCalledWith({+ operationId: "contentBlocks.migrateTemplateReferences",+ input: expect.objectContaining({ templateInstanceId: "template" }),+ });++ const disconnectPreview = await session.mutate(+ "contentBlocks.disconnectSource",+ {+ blockInstanceId: "block",+ renderScope: "page:/",+ },+ { dryRun: true }+ );+ expect(disconnectPreview.result).toMatchObject({+ status: "confirmation-required",+ confirmation: { token: expect.any(String) },+ });+ const disconnected = await session.mutate(+ "contentBlocks.disconnectSource",+ {+ blockInstanceId: "block",+ renderScope: "page:/",+ confirmationToken: (+ disconnectPreview.result as {+ confirmation: { token: string };+ }+ ).confirmation.token,+ }+ );+ expect(disconnected).toMatchObject({+ source: "local",+ state: { committed: true },+ result: {+ status: "complete",+ source: { sessionStatus: "disconnected" },+ plan: { action: "disconnect", changesProject: true },+ },+ });+ expect(+ Array.from(session.snapshot?.state.props?.values() ?? []).some(+ (prop) => prop.instanceId === "block" && prop.name === "src"+ )+ ).toBe(false);+ expect(session.snapshot?.state.instances?.size).toBeGreaterThan(2);+ });+test("adapts public API build snapshots into project-session state", async () => {const transport = createCliProjectSessionTransport({connection: {diff --git a/packages/cli/src/project-session.ts b/packages/cli/src/project-session.tsindex f83f791e9e..9e13cdbb0f 100644--- a/packages/cli/src/project-session.ts+++ b/packages/cli/src/project-session.ts@@ -10,6 +10,11 @@ import {serializePages,} from "@webstudio-is/project-migrations/pages";import * as httpClient from "@webstudio-is/http-client";+import {+ assetContentDescriptor,+ assetContentDescriptorHeader,+ parseAssetContentDescriptor,+} from "@webstudio-is/protocol/asset-resource-api";import {bundleVersion,getPublicBuildIncludes,@@ -22,7 +27,8 @@ import {} from "@webstudio-is/protocol";import packageJson from "../package.json";import {- createReachableAssetContentCompilationPlan,+ blockComponent,+ getContentBlockSource,getHomePage,} from "@webstudio-is/sdk";import {@@ -52,7 +58,21 @@ import {type BuilderBuildDataSnapshot,type SerializedBuilderStateSnapshot,} from "@webstudio-is/project-build/state";-import { removeLegacyProjectSettingsFromPages } from "@webstudio-is/project-build";+import {+ createBuildContentCompilationPlan,+ createPublishedBuildContentCompilationPlan,+ getDynamicPublishedMdxSourceBlockIds,+ getPublishedMdxContentDatabaseMaxBytes,+ removeLegacyProjectSettingsFromPages,+ resolvePublishedMdxAssetCandidates,+ resolvePublishedMdxDependencyClosure,+} from "@webstudio-is/project-build";+import {+ computeExpression,+ createContentBlockApplicationOperations,+ createMdxAssetEditingSession,+} from "@webstudio-is/project-build/runtime";+import { createHttpAssetContentRepository } from "@webstudio-is/asset-uploader/content-repository";import type { BuilderStateFreshness } from "@webstudio-is/project-build/state";import { getLocalProjectStateDirectory, LOCAL_DATA_FILE } from "./config";import type { ApiConnection } from "./api-connection";@@ -519,6 +539,37 @@ export const createCliProjectSessionTransport = ({)) as Result),});+export const createCliAssetContentRepository = ({+ connection,+}: {+ connection: ApiConnection;+}) =>+ createHttpAssetContentRepository({+ projectId: connection.projectId,+ read: ({ assetId, range }) =>+ httpClient.readProjectAssetContent({+ ...connection,+ requestOrigin: connection.origin,+ assetId,+ range,+ }),+ update: async ({ assetId, expectedName, data }) => {+ const bytes = Uint8Array.from(data);+ const { asset } = await httpClient.updateProjectAssetContent({+ ...connection,+ requestOrigin: connection.origin,+ assetId,+ expectedName,+ readAssetData: async () => bytes,+ });+ return assetContentDescriptor.parse(asset);+ },+ parseAsset: (response) =>+ parseAssetContentDescriptor(+ response.headers.get(assetContentDescriptorHeader)+ ),+ });+export const createCliProjectSession = ({connection,storage,@@ -526,6 +577,9 @@ export const createCliProjectSession = ({sessionProjectId,executeServerOperation,getPermissions,+ assetContentRepository = createCliAssetContentRepository({ connection }),+ resolveExpressionAssetId,+ transport,}: {connection: ApiConnection;storage?: ProjectSessionStorage;@@ -533,21 +587,105 @@ export const createCliProjectSession = ({sessionProjectId?: string;executeServerOperation?: ProjectSessionTransport["executeServerOperation"];getPermissions?: ProjectSessionTransport["getPermissions"];-}) =>- createProjectSession({- projectId: connection.projectId,- transport: createCliProjectSessionTransport({+ assetContentRepository?: ReturnType<typeof createCliAssetContentRepository>;+ resolveExpressionAssetId?: (input: {+ expression: string;+ blockInstanceId: string;+ renderScope: string;+ variables?: Readonly<Record<string, unknown>>;+ }) => string | undefined | Promise<string | undefined>;+ transport?: ProjectSessionTransport;+}) => {+ let projectSession: ReturnType<typeof createProjectSession>;+ const sessionTransport =+ transport ??+ createCliProjectSessionTransport({connection,executeServerOperation,getPermissions,- }),+ });+ const mdxSession = createMdxAssetEditingSession({+ repository: assetContentRepository,+ authorizeAsset: async ({ operation }) => {+ const permissions = await projectSession.getPermissions();+ return (+ permissions.canUseApi &&+ permissions.canView &&+ (operation === "read" || permissions.canEdit)+ );+ },+ resolveExpressionAssetId:+ resolveExpressionAssetId ??+ (({ expression, variables: scopedVariables }) => {+ const snapshot = projectSession.snapshot;+ const variables = new Map<string, unknown>();+ for (const dataSource of snapshot?.state.dataSources?.values() ?? []) {+ if (dataSource.type === "variable") {+ variables.set(dataSource.name, dataSource.value.value);+ }+ }+ for (const [name, value] of Object.entries(scopedVariables ?? {})) {+ variables.set(name, value);+ }+ const value = computeExpression(expression, variables);+ return typeof value === "string" && value !== "" ? value : undefined;+ }),+ });+ const application = createContentBlockApplicationOperations({+ projectId: connection.projectId,+ session: mdxSession,+ getState: () => {+ const state = projectSession.snapshot?.state;+ if (state === undefined) {+ throw new Error("Project session is not initialized");+ }+ return state;+ },+ getProjectVersion: () => projectSession.snapshot?.version,+ context: {+ projectId: connection.projectId,+ createId: () => crypto.randomUUID(),+ },+ });+ const contentStorageApplication = {+ ...application,+ migrateTemplateReferences: async (+ input: Parameters<typeof application.migrateTemplateReferences>[0]+ ) => {+ if (sessionTransport.executeServerOperation === undefined) {+ return application.migrateTemplateReferences(input);+ }+ const response = await sessionTransport.executeServerOperation<+ Awaited<ReturnType<typeof application.migrateTemplateReferences>> & {+ version?: number;+ }+ >({+ operationId: "contentBlocks.migrateTemplateReferences",+ input,+ });+ const { version: _version, ...result } = response;+ return result as Awaited<+ ReturnType<typeof application.migrateTemplateReferences>+ >;+ },+ };+ projectSession = createProjectSession({+ projectId: connection.projectId,+ transport: sessionTransport,storage:storage ??createCliProjectSessionStorage(getCliProjectSessionFile(projectRoot, sessionProjectId)),compatibilityVersion,+ runtimeContext: {+ projectId: connection.projectId,+ createId: () => crypto.randomUUID(),+ contentStorageApplication,+ },});+ return projectSession;+};export type CliProjectSession = ReturnType<typeof createCliProjectSession>;@@ -566,12 +704,53 @@ export const loadCliProjectSessionAssetIndex = async (if (connection.projectId !== snapshot.projectId) {throw new Error("CLI connection does not match the project session");}- const plan = createReachableAssetContentCompilationPlan({- props: snapshot.state.props?.values() ?? [],- dataSources: snapshot.state.dataSources?.values() ?? [],- resources: snapshot.state.resources?.values() ?? [],- });+ const build = {+ instances: Array.from(snapshot.state.instances?.values() ?? []),+ props: Array.from(snapshot.state.props?.values() ?? []),+ dataSources: Array.from(snapshot.state.dataSources?.values() ?? []),+ resources: Array.from(snapshot.state.resources?.values() ?? []),+ };+ const hasMdxSource = build.instances.some(+ (instance) =>+ instance.component === blockComponent &&+ getContentBlockSource({+ blockInstanceId: instance.id,+ props: build.props,+ }) !== undefined+ );+ const basePlan = createBuildContentCompilationPlan(build);+ let publicationBuild:+ | (typeof build & { pages: NonNullable<typeof snapshot.state.pages> })+ | undefined;+ let needsCandidateDiscovery = false;+ let plan = basePlan;+ if (hasMdxSource) {+ if (snapshot.state.pages === undefined) {+ throw new Error("Project session pages namespace is missing");+ }+ publicationBuild = { ...build, pages: snapshot.state.pages };+ const dynamicBlockIds =+ getDynamicPublishedMdxSourceBlockIds(publicationBuild);+ const projectCandidates = resolvePublishedMdxAssetCandidates({+ build: publicationBuild,+ allowUnresolved: true,+ });+ needsCandidateDiscovery = dynamicBlockIds.some(+ (blockId) => projectCandidates.has(blockId) === false+ );+ plan = needsCandidateDiscovery+ ? basePlan+ : createPublishedBuildContentCompilationPlan(+ publicationBuild,+ projectCandidates+ );+ }if (plan === undefined) {+ if (needsCandidateDiscovery) {+ throw new Error(+ "Dynamic MDX preview requires a finite Assets query dependency"+ );+ }return;}const assets = Array.from(snapshot.state.assets?.values() ?? []);@@ -590,19 +769,54 @@ export const loadCliProjectSessionAssetIndex = async ({ code: "PREVIEW_ASSET_DOWNLOAD_FAILED" });}- const { artifact } = await compileContentSource({- source: createFileSystemContentSource({- projectId: snapshot.projectId,- assets,- folders: snapshot.state.assetFolders ?? new Map(),- assetsDirectory,- }),+ const source = createFileSystemContentSource({projectId: snapshot.projectId,- plan,- maxBytes: parseContentDatabaseMaxBytes(+ assets,+ folders: snapshot.state.assetFolders ?? new Map(),+ assetsDirectory,+ });+ const maxBytes = getPublishedMdxContentDatabaseMaxBytes({+ baseBytes: parseContentDatabaseMaxBytes(process.env.CONTENT_DATABASE_MAX_BYTES),+ assets,+ });+ let { artifact } = await compileContentSource({+ source,+ projectId: snapshot.projectId,+ plan,+ maxBytes,});+ if (hasMdxSource) {+ if (publicationBuild === undefined) {+ throw new Error("Dynamic MDX preview build is unavailable");+ }+ let resolvedPlan = await resolvePublishedMdxDependencyClosure({+ build: publicationBuild,+ artifact,+ });+ for (let dependencyPass = 0; dependencyPass < 20; dependencyPass += 1) {+ ({ artifact } = await compileContentSource({+ source,+ projectId: snapshot.projectId,+ plan: resolvedPlan,+ maxBytes,+ }));+ const validatedPlan = await resolvePublishedMdxDependencyClosure({+ build: publicationBuild,+ artifact,+ });+ if (JSON.stringify(resolvedPlan) === JSON.stringify(validatedPlan)) {+ break;+ }+ if (dependencyPass === 19) {+ throw new Error(+ "MDX dependency closure exceeds the safe preview depth"+ );+ }+ resolvedPlan = validatedPlan;+ }+ }return artifact;};diff --git a/packages/cli/templates/defaults/app/route-templates/html.tsx b/packages/cli/templates/defaults/app/route-templates/html.tsxindex 318f55ed13..d6b368d7a4 100644--- a/packages/cli/templates/defaults/app/route-templates/html.tsx+++ b/packages/cli/templates/defaults/app/route-templates/html.tsx@@ -128,6 +128,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/packages/cli/templates/defaults/app/route-templates/text.tsx b/packages/cli/templates/defaults/app/route-templates/text.tsxindex 843fc771d8..08d07f9766 100644--- a/packages/cli/templates/defaults/app/route-templates/text.tsx+++ b/packages/cli/templates/defaults/app/route-templates/text.tsx@@ -87,6 +87,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/packages/cli/templates/defaults/app/route-templates/xml.tsx b/packages/cli/templates/defaults/app/route-templates/xml.tsxindex 5697d3cbd2..468bbc3dfd 100644--- a/packages/cli/templates/defaults/app/route-templates/xml.tsx+++ b/packages/cli/templates/defaults/app/route-templates/xml.tsx@@ -95,6 +95,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/packages/cli/templates/react-router/app/route-templates/html.tsx b/packages/cli/templates/react-router/app/route-templates/html.tsxindex 193b5f5e6e..14328c3bbc 100644--- a/packages/cli/templates/react-router/app/route-templates/html.tsx+++ b/packages/cli/templates/react-router/app/route-templates/html.tsx@@ -127,6 +127,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/packages/cli/templates/react-router/app/route-templates/text.tsx b/packages/cli/templates/react-router/app/route-templates/text.tsxindex 47aa3e535e..c92494ed40 100644--- a/packages/cli/templates/react-router/app/route-templates/text.tsx+++ b/packages/cli/templates/react-router/app/route-templates/text.tsx@@ -87,6 +87,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/packages/cli/templates/react-router/app/route-templates/xml.tsx b/packages/cli/templates/react-router/app/route-templates/xml.tsxindex 29a6545d32..3cc5f5a93c 100644--- a/packages/cli/templates/react-router/app/route-templates/xml.tsx+++ b/packages/cli/templates/react-router/app/route-templates/xml.tsx@@ -95,6 +95,15 @@ export const loader = async (arg: LoaderFunctionArgs) => {url,{ signal: arg.request.signal });+ Object.assign(+ resources,+ await loadResources(+ generatedFetch,+ getResources({ system, resources }).contentData,+ url,+ { signal: arg.request.signal }+ )+ );const pageMeta = getPageMeta({ system, resources });if (pageMeta.redirect) {diff --git a/packages/cli/templates/ssg/app/route-templates/html/+data.ts b/packages/cli/templates/ssg/app/route-templates/html/+data.tsindex 7362c216e4..7ac8a4500c 100644--- a/packages/cli/templates/ssg/app/route-templates/html/+data.ts+++ b/packages/cli/templates/ssg/app/route-templates/html/+data.ts@@ -67,6 +67,14 @@ export const data = async (pageContext: PageContextServer) => {getResources({ system }).data,url);+ Object.assign(+ resources,+ await loadResources(+ customFetch,+ getResources({ system, resources }).contentData,+ url+ )+ );const pageMeta = getPageMeta({ system, resources });return {diff --git a/packages/content-engine/package.json b/packages/content-engine/package.jsonindex 7ce2534af1..01cabd0f10 100644--- a/packages/content-engine/package.json+++ b/packages/content-engine/package.json@@ -10,7 +10,7 @@"scripts": {"benchmark:index": "NODE_OPTIONS=--conditions=webstudio pnpm tsx scripts/benchmark-index.mjs","benchmark:scale": "NODE_OPTIONS=--conditions=webstudio pnpm tsx scripts/benchmark-scale.mjs",- "build": "rm -rf lib && esbuild src/index.ts src/compiler.ts src/limits.ts src/markdown-assets.ts src/markdown-references.ts src/published-runtime.ts --outdir=lib --bundle --format=esm --packages=external",+ "build": "rm -rf lib && esbuild src/index.ts src/compiler.ts src/limits.ts src/markdown-assets.ts src/markdown-references.ts src/mdx.ts src/mdx-conversion.ts src/published-runtime.ts --outdir=lib --bundle --format=esm --packages=external","dts": "tsc --project tsconfig.dts.json","test": "vitest run","typecheck": "tsc --noEmit"@@ -20,11 +20,23 @@"@webstudio-is/expression": "workspace:*","@webstudio-is/query-builder": "workspace:*","canonicalize": "3.0.0",+ "hast-util-raw": "7.2.3",+ "hast-util-to-mdast": "9.0.0","lru-cache": "10.4.3",+ "mdast-util-gfm": "2.0.2",+ "mdast-util-mdx-expression": "1.3.2",+ "mdast-util-mdx-jsx": "2.1.4",+ "mdast-util-to-hast": "12.3.0",+ "mdast-util-to-markdown": "1.5.0","micromark": "4.0.2","micromark-util-decode-string": "2.0.1",+ "property-information": "6.2.0",+ "remark-frontmatter": "4.0.1",+ "remark-gfm": "3.0.1",+ "remark-mdx": "2.3.0","remark-parse": "10.0.2","unified": "10.1.2",+ "vfile": "5.3.6","yaml": "2.9.0","zod": "^4.4.3"},@@ -69,6 +81,18 @@"types": "./lib/types/markdown-references.d.ts","import": "./lib/markdown-references.js","default": "./src/markdown-references.ts"+ },+ "./mdx": {+ "webstudio": "./src/mdx.ts",+ "types": "./lib/types/mdx.d.ts",+ "import": "./lib/mdx.js",+ "default": "./src/mdx.ts"+ },+ "./mdx-conversion": {+ "webstudio": "./src/mdx-conversion.ts",+ "types": "./lib/types/mdx-conversion.d.ts",+ "import": "./lib/mdx-conversion.js",+ "default": "./src/mdx-conversion.ts"}},"files": [diff --git a/packages/content-engine/src/asset-reference-utils.ts b/packages/content-engine/src/asset-reference-utils.tsnew file mode 100644index 0000000000..e02cb1e1f2--- /dev/null+++ b/packages/content-engine/src/asset-reference-utils.ts@@ -0,0 +1,38 @@+import { createAssetIdResolver } from "./asset-path-resolution";++export type ResolvedAssetReference = {+ assetId: string;+ suffix?: string;+};++const getAssetReferenceSuffix = (value: string) => {+ let parsed: URL;+ try {+ parsed = new URL(value, "https://content.webstudio.invalid/");+ } catch {+ return;+ }+ const suffix = `${parsed.search}${parsed.hash}`;+ return suffix === "" ? undefined : suffix;+};++export const createAssetReferenceResolver = ({+ sourcePath,+ assetIdsByPath,+}: {+ sourcePath: string;+ assetIdsByPath: ReadonlyMap<string, string>;+}) => {+ const resolveAssetId = createAssetIdResolver(assetIdsByPath, sourcePath);+ return (value: string): ResolvedAssetReference | undefined => {+ const assetId = resolveAssetId(value);+ if (assetId === undefined) {+ return;+ }+ const suffix = getAssetReferenceSuffix(value);+ return {+ assetId,+ ...(suffix === undefined ? {} : { suffix }),+ };+ };+};diff --git a/packages/content-engine/src/asset-value-references.test.ts b/packages/content-engine/src/asset-value-references.test.tsindex 8495e9f4b3..685df3368f 100644--- a/packages/content-engine/src/asset-value-references.test.ts+++ b/packages/content-engine/src/asset-value-references.test.ts@@ -147,5 +147,8 @@ describe("structured asset value references", () => {"?download=1#section")).toBe("https://cdn.example.com/guide.pdf?format=raw&download=1#section");+ expect(mergeAssetUrlSuffix("assets/hero.png", "?width=1200#cover")).toBe(+ "assets/hero.png?width=1200#cover"+ );});});diff --git a/packages/content-engine/src/asset-value-references.ts b/packages/content-engine/src/asset-value-references.tsindex d4fcc4d49a..d5085806c1 100644--- a/packages/content-engine/src/asset-value-references.ts+++ b/packages/content-engine/src/asset-value-references.ts@@ -1,9 +1,10 @@-import { createAssetIdResolver } from "./asset-path-resolution";+import {+ createAssetReferenceResolver,+ type ResolvedAssetReference,+} from "./asset-reference-utils";-export type AssetValueReference = {+export type AssetValueReference = ResolvedAssetReference & {path: Array<string | number>;- assetId: string;- suffix?: string;};export type AssetValueReferences = Record<string, AssetValueReference[]>;@@ -15,38 +16,27 @@ export const getRuntimeAssetUrls = (Object.entries(runtimeAssets ?? {}).map(([id, asset]) => [id, asset.url]));-const getUrlSuffix = (value: string) => {- let parsed: URL;- try {- parsed = new URL(value, "https://content.webstudio.invalid/");- } catch {- return;- }- const suffix = `${parsed.search}${parsed.hash}`;- return suffix === "" ? undefined : suffix;-};-export const discoverAssetValueReferences = ({properties,sourcePath,assetIdsByPath,+ rootPath = ["properties"],}: {properties: Readonly<Record<string, unknown>>;sourcePath: string;assetIdsByPath: ReadonlyMap<string, string>;+ rootPath?: Array<string | number>;}): AssetValueReference[] => {- const resolveAssetId = createAssetIdResolver(assetIdsByPath, sourcePath);+ const resolveAssetReference = createAssetReferenceResolver({+ sourcePath,+ assetIdsByPath,+ });const references: AssetValueReference[] = [];const visit = (value: unknown, path: Array<string | number>) => {if (typeof value === "string") {- const assetId = resolveAssetId(value);- if (assetId !== undefined) {- const suffix = getUrlSuffix(value);- references.push({- path,- assetId,- ...(suffix === undefined ? {} : { suffix }),- });+ const reference = resolveAssetReference(value);+ if (reference !== undefined) {+ references.push({ path, ...reference });}return;}@@ -63,17 +53,17 @@ export const discoverAssetValueReferences = ({visit(item, [...path, key]);}};- visit(properties, ["properties"]);+ visit(properties, rootPath);return references;};export const mergeAssetUrlSuffix = (url: string, suffix?: string) => {- if (suffix === undefined) {+ if (suffix === undefined || suffix.length === 0) {return url;}- const base = "https://content.webstudio.invalid";- const canonical = new URL(url, `${base}/`);- const authored = new URL(suffix, `${base}/`);+ const base = new URL("https://content.webstudio.invalid/__assets__/");+ const canonical = new URL(url, base);+ const authored = new URL(suffix, base);for (const [key, value] of authored.searchParams) {canonical.searchParams.append(key, value);}@@ -86,7 +76,13 @@ export const mergeAssetUrlSuffix = (url: string, suffix?: string) => {if (url.startsWith("/")) {return `${canonical.pathname}${canonical.search}${canonical.hash}`;}- return canonical.href;+ if (URL.canParse(url)) {+ return canonical.href;+ }+ const pathname = canonical.pathname.startsWith(base.pathname)+ ? canonical.pathname.slice(base.pathname.length)+ : canonical.pathname;+ return `${pathname}${canonical.search}${canonical.hash}`;};const replaceValueAtPath = ({diff --git a/packages/content-engine/src/byte-stream.ts b/packages/content-engine/src/byte-stream.tsindex e44ea0d655..dd255926a9 100644--- a/packages/content-engine/src/byte-stream.ts+++ b/packages/content-engine/src/byte-stream.ts@@ -42,6 +42,34 @@ export const toByteChunks = (source: ByteSource): AsyncIterable<Uint8Array> => {return source;};+export const readableStreamToAsyncIterable = (+ stream: ReadableStream<Uint8Array>+): AsyncIterable<Uint8Array> => ({+ async *[Symbol.asyncIterator]() {+ const reader = stream.getReader();+ let completed = false;+ try {+ for (;;) {+ const result = await reader.read();+ if (result.done) {+ completed = true;+ return;+ }+ yield result.value;+ }+ } finally {+ if (completed === false) {+ try {+ await reader.cancel();+ } catch {+ // Preserve the consumer error that stopped the stream.+ }+ }+ reader.releaseLock();+ }+ },+});+export const readBytePrefix = async (source: ByteSource,maximumBytes: numberdiff --git a/packages/content-engine/src/canonical.ts b/packages/content-engine/src/canonical.tsindex e807d42e6e..4178dc1ded 100644--- a/packages/content-engine/src/canonical.ts+++ b/packages/content-engine/src/canonical.ts@@ -40,11 +40,11 @@ export type CanonicalAssetMetadataRequirements = {};/**- * Generation of the Markdown/JSON extraction behavior used by persistent+ * Generation of the Markdown/MDX/JSON extraction behavior used by persistent* metadata caches. Increment only when unchanged source files must be parsed* again because extraction semantics changed.*/-export const canonicalAssetMetadataExtractorGeneration = 1;+export const canonicalAssetMetadataExtractorGeneration = 2;export const fullCanonicalAssetMetadataRequirements = {structuredProperties: true,diff --git a/packages/content-engine/src/compiler.ts b/packages/content-engine/src/compiler.tsindex fbab8fd608..457ac1aa89 100644--- a/packages/content-engine/src/compiler.ts+++ b/packages/content-engine/src/compiler.ts@@ -8,5 +8,10 @@ export * from "./content-source";export * from "./document-metadata";export * from "./asset-value-references";export { serializeJsonDeterministically } from "./canonical-json";-export { decodeUtf8, readBoundedBytes, readBytePrefix } from "./byte-stream";+export {+ decodeUtf8,+ readableStreamToAsyncIterable,+ readBoundedBytes,+ readBytePrefix,+} from "./byte-stream";export { mapBounded } from "./async-utils";diff --git a/packages/content-engine/src/content-source.test.ts b/packages/content-engine/src/content-source.test.tsindex df5c782d5e..2d5f2dea39 100644--- a/packages/content-engine/src/content-source.test.ts+++ b/packages/content-engine/src/content-source.test.ts@@ -1,5 +1,6 @@import { describe, expect, test } from "vitest";import { createCanonicalAssetFileEntry } from "./canonical";+import { getContentArtifactReferencedAssetIds } from "./content-artifact";import {compileContentSource,ContentSourceChangedError,@@ -119,6 +120,69 @@ const createDocumentSource = ({});describe("content source snapshots", () => {+ test("compiles MDX sources into the document graph", async () => {+ const mdx =+ '---\nauthor:\n $ref: ./author.json#/profile\n---\n<ws.element ws:name="Hero">Hello</ws.element>\n';+ const post = createFile({+ id: "post",+ path: "blog/post.mdx",+ contentType: "text/mdx",+ contentRef: "revisions/post.mdx",+ size: new TextEncoder().encode(mdx).byteLength,+ });+ const author = createFile({+ id: "author",+ path: "blog/author.json",+ contentType: "application/json",+ });+ const source = createDocumentSource({+ files: [post, author],+ sources: {+ post: mdx,+ author: '{"profile":{"name":"Ada"}}',+ },+ });++ const result = await compileContentSource({+ source,+ projectId,+ plan: {+ standardFields: [],+ structuredPropertyPaths: [["properties", "author"]],+ excerpt: false,+ metadataError: false,+ queries: [+ {+ id: "posts",+ where: { all: [] },+ sort: [],+ limit: { type: "literal", value: 1 },+ offset: { type: "literal", value: 0 },+ output: {+ mode: "fields",+ includeMetadata: false,+ fields: [["properties", "author"]],+ },+ content: { mode: "none" },+ },+ ],+ },+ });++ expect(+ result.documentGraph?.nodes.map(({ id, format }) => [id, format])+ ).toEqual([+ ["author", "json"],+ ["post", "mdx"],+ ]);+ expect(result.documentGraph?.edges).toEqual([+ expect.objectContaining({+ sourceId: "post",+ referenceId: "#frontmatter/author",+ }),+ ]);+ });+test("analyzes only query roots and their reachable document targets", async () => {const post = createFile({ id: "post", path: "blog/post.md" });const author = createFile({@@ -585,6 +649,89 @@ describe("content source snapshots", () => {});});+ test("exposes MDX frontmatter and authored Asset references", async () => {+ const mdx = createFile({+ id: "post",+ path: "blog/post.mdx",+ contentType: "text/mdx",+ contentRef: "revisions/post.mdx",+ });+ const cover = createFile({+ id: "cover",+ path: "blog/cover.png",+ contentType: "image/png",+ });+ const hero = createFile({+ id: "hero",+ path: "blog/hero.png",+ contentType: "image/png",+ });+ const video = createFile({+ id: "video",+ path: "blog/video.jpg",+ contentType: "image/jpeg",+ });+ const content = `---+cover: ./cover.png+---+++<ws.element ws:name="Card" poster="./video.jpg" />+`;+ const source: ContentSource = {+ async openSnapshot() {+ return {+ revision: "snapshot",+ files: [mdx, cover, hero, video],+ async loadEntries() {+ const entry = createEntry(mdx);+ return [+ {+ ...entry,+ document: {+ ...entry.document,+ properties: { cover: "./cover.png" },+ },+ content,+ } as typeof entry & { content: string },+ ];+ },+ async isCurrent() {+ return true;+ },+ };+ },+ };++ const result = await compileContentSource({ source, projectId });++ expect(result.artifact.documents[0]?.properties).toEqual({+ cover: "./cover.png",+ });+ expect(result.artifact.assetValueReferences).toEqual({+ post: [+ {+ path: ["properties", "cover"],+ assetId: "cover",+ },+ {+ path: ["children", 0, "children", 0, "props", 0, "value"],+ assetId: "hero",+ suffix: "#crop",+ },+ {+ path: ["children", 1, "props", 0, "value"],+ assetId: "video",+ },+ ],+ });+ expect(getContentArtifactReferencedAssetIds(result.artifact)).toEqual([+ "cover",+ "hero",+ "video",+ ]);+ });+test("resolves the same relative URL independently for each Markdown folder", async () => {const firstPost = createFile({id: "first-post",@@ -717,77 +864,95 @@ describe("content source snapshots", () => {).toEqual({ "revisions/post.md": ["hero"] });});- test("keeps Markdown body content in storage for graph-backed queries", async () => {- const markdown = "---\ntitle: Post\nslug: post\n---\nStored body\n";- const post = createFile({- id: "post",- path: "blog/post.md",- size: new TextEncoder().encode(markdown).byteLength,- });- const source: ContentSource = {- async openSnapshot() {- return {- revision: "snapshot",- files: [post],- async loadEntries() {- return [{ ...createEntry(post), content: markdown }];- },- async loadDocumentSources() {- return [{ id: post.id, source: markdown }];- },- async isCurrent() {- return true;- },- };- },- };+ test.each([+ {+ label: "Markdown",+ extension: "md",+ contentType: "text/markdown",+ format: "markdown",+ },+ {+ label: "MDX",+ extension: "mdx",+ contentType: "text/mdx",+ format: "mdx",+ },+ ] as const)(+ "keeps $label body content in storage for graph-backed queries",+ async ({ extension, contentType, format }) => {+ const markdown = "---\ntitle: Post\nslug: post\n---\nStored body\n";+ const post = createFile({+ id: "post",+ path: `blog/post.${extension}`,+ contentType,+ contentRef: `revisions/post.${extension}`,+ size: new TextEncoder().encode(markdown).byteLength,+ });+ const source: ContentSource = {+ async openSnapshot() {+ return {+ revision: "snapshot",+ files: [post],+ async loadEntries() {+ return [{ ...createEntry(post), content: markdown }];+ },+ async loadDocumentSources() {+ return [{ id: post.id, source: markdown }];+ },+ async isCurrent() {+ return true;+ },+ };+ },+ };- const result = await compileContentSource({- source,- projectId,- plan: {- standardFields: [["extension"], ["mimeType"], ["revision"], ["size"]],- structuredPropertyPaths: [["properties", "slug"]],- excerpt: false,- metadataError: false,- queries: [+ const result = await compileContentSource({+ source,+ projectId,+ plan: {+ standardFields: [["extension"], ["mimeType"], ["revision"], ["size"]],+ structuredPropertyPaths: [["properties", "slug"]],+ excerpt: false,+ metadataError: false,+ queries: [+ {+ id: "post",+ where: {+ all: [+ {+ field: ["properties", "slug"],+ operator: "eq",+ value: { type: "dynamic" },+ },+ ],+ },+ sort: [],+ limit: { type: "literal", value: 1 },+ offset: { type: "literal", value: 0 },+ output: {+ mode: "fields",+ includeMetadata: false,+ fields: [["properties", "slug"]],+ },+ content: { mode: "markdown-body-ref" },+ },+ ],+ },+ });++ expect(result.artifact.contents).toBeUndefined();+ expect(result.artifact.documentGraph).toMatchObject({+ nodes: [{id: "post",- where: {- all: [- {- field: ["properties", "slug"],- operator: "eq",- value: { type: "dynamic" },- },- ],- },- sort: [],- limit: { type: "literal", value: 1 },- offset: { type: "literal", value: 0 },- output: {- mode: "fields",- includeMetadata: false,- fields: [["properties", "slug"]],- },- content: { mode: "markdown-body-ref" },+ contentRef: `revisions/post.${extension}`,+ format,},],- },- });-- expect(result.artifact.contents).toBeUndefined();- expect(result.artifact.documentGraph).toMatchObject({- nodes: [- {- id: "post",- contentRef: "revisions/post.md",- format: "markdown",- },- ],- edges: [],- });- });+ edges: [],+ });+ }+ );test("does not resolve an ambiguous Asset path", async () => {const post = createFile({ id: "post", path: "blog/post.md" });diff --git a/packages/content-engine/src/content-source.ts b/packages/content-engine/src/content-source.tsindex 0b72b66d6e..a552be2d08 100644--- a/packages/content-engine/src/content-source.ts+++ b/packages/content-engine/src/content-source.ts@@ -21,6 +21,7 @@ import { compareStrings } from "./canonical-json";import { encodeUtf8, type ByteSource } from "./byte-stream";import { extractMarkdownBody } from "./markdown-body";import { contentEngineLimits } from "./limits";+import { discoverMdxBodyAssetReferences, parseMdxDocument } from "./mdx";import {compileDocumentSourceGraph,getDocumentFormatByContentType,@@ -215,13 +216,13 @@ const discoverSnapshotAssetReferences = async ({return references;};-const discoverSnapshotAssetValueReferences = ({+const discoverSnapshotAssetValueReferences = async ({snapshot,entries,}: {snapshot: ContentSourceSnapshot;entries: readonly ContentCompilerInput[];-}): AssetValueReferences => {+}): Promise<AssetValueReferences> => {const assetIdsByPath = createUniqueAssetIdsByPath(snapshot.files);const references: AssetValueReferences = {};for (const entry of [...entries].sort((left, right) =>@@ -232,6 +233,19 @@ const discoverSnapshotAssetValueReferences = ({sourcePath: entry.document.path,assetIdsByPath,});+ if (+ entry.content !== undefined &&+ getDocumentFormatByContentType(entry.document.mimeType) === "mdx"+ ) {+ const document = await parseMdxDocument({ source: entry.content });+ discovered.push(+ ...discoverMdxBodyAssetReferences({+ document,+ sourcePath: entry.document.path,+ assetIdsByPath,+ })+ );+ }if (discovered.length > 0) {references[entry.assetId] = discovered;}@@ -359,7 +373,7 @@ export const materializeContentSnapshot = async ({operation: () =>discoverSnapshotAssetReferences({ snapshot, entries, plan }),});- const assetValueReferences = discoverSnapshotAssetValueReferences({+ const assetValueReferences = await discoverSnapshotAssetValueReferences({snapshot,entries,});diff --git a/packages/content-engine/src/document-graph/cached-document-loader.test.ts b/packages/content-engine/src/document-graph/cached-document-loader.test.tsindex 9ce5095a8a..e16f40e9a2 100644--- a/packages/content-engine/src/document-graph/cached-document-loader.test.ts+++ b/packages/content-engine/src/document-graph/cached-document-loader.test.ts@@ -87,6 +87,38 @@ describe("cached document source loader", () => {});});+ test("reuses cached MDX sources", async () => {+ const cached: CachedDocumentSource = {+ format: "mdx",+ revision: "post-r1",+ bytes: new TextEncoder().encode("# Cached"),+ };+ const load = vi.fn(async () => {+ throw new Error("source loader must not run");+ });+ const result = await createCachedDocumentSourceLoader({+ cache: {+ get: async () => cached,+ set: async () => undefined,+ },+ load,+ })(+ {+ id: "post",+ revision: "post-r1",+ contentRef: "content:post",+ format: "mdx",+ },+ {}+ );++ expect(result.format).toBe("mdx");+ expect(load).not.toHaveBeenCalled();+ await expect(parseDocumentSource(result)).resolves.toMatchObject({+ format: "mdx",+ });+ });+test("does not reuse a cached source with a different format", async () => {const load = vi.fn(async () => ({format: "json" as const,diff --git a/packages/content-engine/src/document-graph/cached-document-loader.ts b/packages/content-engine/src/document-graph/cached-document-loader.tsindex 780e126b2a..22ff5cef9e 100644--- a/packages/content-engine/src/document-graph/cached-document-loader.ts+++ b/packages/content-engine/src/document-graph/cached-document-loader.ts@@ -2,7 +2,7 @@ import { LRUCache } from "lru-cache";import { ByteLimitExceededError, readBoundedBytes } from "../byte-stream";import { serializeJsonDeterministically } from "../canonical-json";import { contentEngineLimits } from "../limits";-import type { DocumentFormat } from "./document-adapter";+import { isDocumentFormat, type DocumentFormat } from "./document-format";import type { DocumentGraphNode } from "./graph";import {assertDocumentSourceIdentity,@@ -83,7 +83,7 @@ const isCachedDocumentSource = (}const value = input as Partial<CachedDocumentSource>;return (- (value.format === "json" || value.format === "markdown") &&+ isDocumentFormat(value.format) &&typeof value.revision === "string" &&value.revision.length > 0 &&value.bytes instanceof Uint8Arraydiff --git a/packages/content-engine/src/document-graph/compiler.ts b/packages/content-engine/src/document-graph/compiler.tsindex 2e42bb7817..d9e3bcdceb 100644--- a/packages/content-engine/src/document-graph/compiler.ts+++ b/packages/content-engine/src/document-graph/compiler.ts@@ -1,4 +1,5 @@import { compareStrings } from "../canonical-json";+import type { DocumentFormat } from "./document-format";import {createDocumentGraph,DocumentGraphError,@@ -12,7 +13,7 @@ export type DocumentDescriptor = Readonly<{documentUrl: string;revision: string;contentRef: string;- format?: "json" | "markdown";+ format?: DocumentFormat;}>;export type DocumentGraphCompilationErrorCode =diff --git a/packages/content-engine/src/document-graph/document-adapter.test.ts b/packages/content-engine/src/document-graph/document-adapter.test.tsindex dc7e1aff7f..33342e1189 100644--- a/packages/content-engine/src/document-graph/document-adapter.test.ts+++ b/packages/content-engine/src/document-graph/document-adapter.test.ts@@ -2,8 +2,10 @@ import { describe, expect, test } from "vitest";import {analyzeDocumentSource,assembleDocument,+ parseDocumentSource,selectDocumentRepresentation,} from "./document-adapter";+import { getDocumentFormatByContentType } from "./document-format";const documentUrl = "https://content.webstudio.test/posts/hello";@@ -19,6 +21,12 @@ describe("document adapter", () => {source: "---\nauthor:\n $ref: ../authors/ada.json\n---\n# Hello\n",referenceId: "#frontmatter/author",},+ {+ format: "mdx" as const,+ source:+ '---\nauthor:\n $ref: ../authors/ada.json\n---\n<ws.element ws:name="Hero">Hello</ws.element>\n',+ referenceId: "#frontmatter/author",+ },])("analyzes $format sources through one contract", async (fixture) => {const analyzed = await analyzeDocumentSource({format: fixture.format,@@ -33,6 +41,13 @@ describe("document adapter", () => {]);});+ test("maps MDX content types without changing Markdown", () => {+ expect(getDocumentFormatByContentType("text/mdx; charset=utf-8")).toBe(+ "mdx"+ );+ expect(getDocumentFormatByContentType("text/markdown")).toBe("markdown");+ });+test("assembles and selects JSON representations without losing the format", async () => {const analyzed = await analyzeDocumentSource({format: "json",@@ -83,4 +98,52 @@ describe("document adapter", () => {})).toBe("# Hello\n");});++ test("parses safe MDX while reusing Markdown representations", async () => {+ const source =+ '---\ntitle: Hello\n---\n<ws.element ws:name="Hero">Body</ws.element>\n';+ const parsed = await parseDocumentSource({ format: "mdx", source });++ expect(parsed.format).toBe("mdx");+ if (parsed.format !== "mdx") {+ throw new Error("Expected an MDX document");+ }+ expect(parsed.value.authored.children).toEqual([+ expect.objectContaining({ type: "template", name: "Hero" }),+ ]);+ expect(+ selectDocumentRepresentation({+ document: parsed,+ representation: { type: "markdown-frontmatter" },+ })+ ).toEqual({ title: "Hello" });+ expect(+ selectDocumentRepresentation({+ document: parsed,+ representation: { type: "markdown-body" },+ })+ ).toBe('<ws.element ws:name="Hero">Body</ws.element>\n');+ });++ test("resolves MDX frontmatter without changing the authored tree", async () => {+ const analyzed = await analyzeDocumentSource({+ format: "mdx",+ source: "---\nauthor:\n $ref: ../authors/ada.json\n---\n# Hello\n",+ sourceDocumentId: "post",+ documentUrl,+ });+ const assembled = assembleDocument({+ document: analyzed,+ references: new Map([["#frontmatter/author", { name: "Ada" }]]),+ });++ expect(assembled.format).toBe("mdx");+ if (assembled.format !== "mdx") {+ throw new Error("Expected an MDX document");+ }+ expect(assembled.value.frontmatter).toEqual({ author: { name: "Ada" } });+ expect(assembled.value.authored.frontmatter.properties).toEqual({+ author: { $ref: "../authors/ada.json" },+ });+ });});diff --git a/packages/content-engine/src/document-graph/document-adapter.ts b/packages/content-engine/src/document-graph/document-adapter.tsindex 7d3790c9c6..9eb355182a 100644--- a/packages/content-engine/src/document-graph/document-adapter.ts+++ b/packages/content-engine/src/document-graph/document-adapter.ts@@ -14,27 +14,22 @@ import {selectMarkdownDocumentRepresentation,type MarkdownDocument,} from "./markdown-document";+import {+ analyzeMdxDocument,+ assembleMdxDocument,+ parseMdxDocumentSource,+ selectMdxDocumentRepresentation,+ type MdxAdaptedDocument,+} from "./mdx-document";import type { DocumentRepresentation } from "./reference";import type { SourceReferenceOccurrence } from "./reference-codec";import { isJsonObject } from "./document-utils";--export type DocumentFormat = "json" | "markdown";--export const getDocumentFormatByContentType = (- contentType: string-): DocumentFormat | undefined => {- const mimeType = contentType.split(";", 1)[0].trim().toLowerCase();- if (mimeType === "application/json") {- return "json";- }- if (mimeType === "text/markdown") {- return "markdown";- }-};+import type { DocumentFormat } from "./document-format";export type AdaptedDocument =| Readonly<{ format: "json"; value: JsonValue }>- | Readonly<{ format: "markdown"; value: MarkdownDocument }>;+ | Readonly<{ format: "markdown"; value: MarkdownDocument }>+ | Readonly<{ format: "mdx"; value: MdxAdaptedDocument }>;export type AnalyzedDocument =| Readonly<{@@ -46,13 +41,16 @@ export type AnalyzedDocument =format: "markdown";value: MarkdownDocument;references: readonly SourceReferenceOccurrence[];+ }>+ | Readonly<{+ format: "mdx";+ value: MdxAdaptedDocument;+ references: readonly SourceReferenceOccurrence[];}>;export const getAdaptedDocumentProperties = (document: AdaptedDocument) => {const value =- document.format === "markdown"- ? document.value.frontmatter- : document.value;+ document.format === "json" ? document.value : document.value.frontmatter;return isJsonObject(value) ? value : undefined;};@@ -76,9 +74,15 @@ export const parseDocumentSource = async ({value: await parseJsonDocumentSource({ source, maximumBytes }),});}+ if (format === "markdown") {+ return freezeDocument({+ format,+ value: await parseMarkdownDocumentSource({ source, maximumBytes }),+ });+ }return freezeDocument({format,- value: await parseMarkdownDocumentSource({ source, maximumBytes }),+ value: await parseMdxDocumentSource({ source, maximumBytes }),});};@@ -109,7 +113,20 @@ export const analyzeDocumentSource = async ({references: analyzed.references,});}- const analyzed = await analyzeMarkdownDocument({+ if (format === "markdown") {+ const analyzed = await analyzeMarkdownDocument({+ source,+ sourceDocumentId,+ documentUrl,+ maximumBytes,+ });+ return freezeDocument({+ format,+ value: analyzed.document,+ references: analyzed.references,+ });+ }+ const analyzed = await analyzeMdxDocument({source,sourceDocumentId,documentUrl,@@ -141,9 +158,19 @@ export const assembleDocument = ({}),});}+ if (document.format === "markdown") {+ return freezeDocument({+ format: document.format,+ value: assembleMarkdownDocument({+ document: document.value,+ references,+ allowUnresolvedReferences,+ }),+ });+ }return freezeDocument({format: document.format,- value: assembleMarkdownDocument({+ value: assembleMdxDocument({document: document.value,references,allowUnresolvedReferences,@@ -164,7 +191,13 @@ export const selectDocumentRepresentation = ({representation,});}- return selectMarkdownDocumentRepresentation({+ if (document.format === "markdown") {+ return selectMarkdownDocumentRepresentation({+ document: document.value,+ representation,+ });+ }+ return selectMdxDocumentRepresentation({document: document.value,representation,});diff --git a/packages/content-engine/src/document-graph/document-format.ts b/packages/content-engine/src/document-graph/document-format.tsnew file mode 100644index 0000000000..fd9a6c26d8--- /dev/null+++ b/packages/content-engine/src/document-graph/document-format.ts@@ -0,0 +1,21 @@+export const documentFormats = ["json", "markdown", "mdx"] as const;+export type DocumentFormat = (typeof documentFormats)[number];++export const isDocumentFormat = (value: unknown): value is DocumentFormat =>+ typeof value === "string" &&+ documentFormats.includes(value as DocumentFormat);++export const getDocumentFormatByContentType = (+ contentType: string+): DocumentFormat | undefined => {+ const mimeType = contentType.split(";", 1)[0].trim().toLowerCase();+ if (mimeType === "application/json") {+ return "json";+ }+ if (mimeType === "text/markdown") {+ return "markdown";+ }+ if (mimeType === "text/mdx") {+ return "mdx";+ }+};diff --git a/packages/content-engine/src/document-graph/document-resolution.ts b/packages/content-engine/src/document-graph/document-resolution.tsindex fd0420b4bc..389883bd1e 100644--- a/packages/content-engine/src/document-graph/document-resolution.ts+++ b/packages/content-engine/src/document-graph/document-resolution.ts@@ -6,8 +6,8 @@ import {parseDocumentSource,selectDocumentRepresentation,type AdaptedDocument,- type DocumentFormat,} from "./document-adapter";+import type { DocumentFormat } from "./document-format";import {getDocumentGraphClosure,type DocumentGraph,diff --git a/packages/content-engine/src/document-graph/document-source.ts b/packages/content-engine/src/document-graph/document-source.tsindex 053d011d79..aea52b8b31 100644--- a/packages/content-engine/src/document-graph/document-source.ts+++ b/packages/content-engine/src/document-graph/document-source.ts@@ -1,5 +1,5 @@import type { ByteSource } from "../byte-stream";-import type { DocumentFormat } from "./document-adapter";+import type { DocumentFormat } from "./document-format";import type { DocumentGraphNode } from "./graph";export type DocumentSource = Readonly<{diff --git a/packages/content-engine/src/document-graph/graph-schema.ts b/packages/content-engine/src/document-graph/graph-schema.tsindex 1308bf2d2e..8d21304e64 100644--- a/packages/content-engine/src/document-graph/graph-schema.ts+++ b/packages/content-engine/src/document-graph/graph-schema.ts@@ -1,11 +1,12 @@import { enum as zEnum, strictObject, string } from "zod";+import { documentFormats } from "./document-format";import { documentReference } from "./reference";export const documentGraphNodeSchema = strictObject({id: string().min(1),revision: string().min(1),contentRef: string().min(1),- format: zEnum(["json", "markdown"]).optional(),+ format: zEnum(documentFormats).optional(),});export const documentGraphEdgeSchema = strictObject({diff --git a/packages/content-engine/src/document-graph/graph.test.ts b/packages/content-engine/src/document-graph/graph.test.tsindex 41cb94e8a3..c449bc0142 100644--- a/packages/content-engine/src/document-graph/graph.test.ts+++ b/packages/content-engine/src/document-graph/graph.test.ts@@ -34,6 +34,22 @@ const edges = [];describe("document graph", () => {+ test("accepts MDX document identities", () => {+ expect(+ createDocumentGraph({+ nodes: [+ {+ id: "post",+ revision: "post-r1",+ contentRef: "content:post",+ format: "mdx",+ },+ ],+ edges: [],+ }).nodes[0]?.format+ ).toBe("mdx");+ });+test("rejects conflicting revisions for one content reference", () => {expect(() =>createDocumentGraph({diff --git a/packages/content-engine/src/document-graph/graph.ts b/packages/content-engine/src/document-graph/graph.tsindex 65c63b0a77..a3003f542d 100644--- a/packages/content-engine/src/document-graph/graph.ts+++ b/packages/content-engine/src/document-graph/graph.ts@@ -1,4 +1,5 @@import { compareStrings } from "../canonical-json";+import type { DocumentFormat } from "./document-format";import { createDocumentReference, type DocumentReference } from "./reference";import {documentGraphEdgeSchema,@@ -10,7 +11,7 @@ export type DocumentGraphNode = Readonly<{id: string;revision: string;contentRef: string;- format?: "json" | "markdown";+ format?: DocumentFormat;}>;export type DocumentGraphEdge = Readonly<{diff --git a/packages/content-engine/src/document-graph/http-document-loader.test.ts b/packages/content-engine/src/document-graph/http-document-loader.test.tsindex 3691fea9f6..e490823b90 100644--- a/packages/content-engine/src/document-graph/http-document-loader.test.ts+++ b/packages/content-engine/src/document-graph/http-document-loader.test.ts@@ -36,6 +36,20 @@ describe("HTTP document loader", () => {});});+ test("accepts MDX response metadata", async () => {+ const load = createHttpDocumentSourceLoader({+ fetch: async () => new Response("# Hello"),+ getRequest: () => "https://cdn.webstudio.test/post.mdx",+ getMetadata: () => ({ format: "mdx", revision: "post-r1" }),+ });++ const loaded = await load(node, {});+ expect(loaded.format).toBe("mdx");+ await expect(parseDocumentSource(loaded)).resolves.toMatchObject({+ format: "mdx",+ });+ });+test("reports non-success responses without consuming their body", async () => {let bodyRead = false;const response = {diff --git a/packages/content-engine/src/document-graph/http-document-loader.ts b/packages/content-engine/src/document-graph/http-document-loader.tsindex 604a02b19d..0f170481dd 100644--- a/packages/content-engine/src/document-graph/http-document-loader.ts+++ b/packages/content-engine/src/document-graph/http-document-loader.ts@@ -1,4 +1,6 @@import { enum as zEnum, strictObject, string } from "zod";+import { readableStreamToAsyncIterable } from "../byte-stream";+import { documentFormats } from "./document-format";import type { DocumentGraphNode } from "./graph";import type { DocumentSourceLoader } from "./document-source";import {@@ -7,7 +9,7 @@ import {} from "./observability";const documentSourceMetadata = strictObject({- format: zEnum(["json", "markdown"]),+ format: zEnum(documentFormats),revision: string().min(1),});@@ -43,34 +45,6 @@ export class HttpDocumentLoaderError extends Error {}}-const streamResponseBody = (- body: ReadableStream<Uint8Array>-): AsyncIterable<Uint8Array> => ({- async *[Symbol.asyncIterator]() {- const reader = body.getReader();- let completed = false;- try {- while (true) {- const chunk = await reader.read();- if (chunk.done) {- completed = true;- return;- }- yield chunk.value;- }- } finally {- if (completed === false) {- try {- await reader.cancel();- } catch {- // Preserve the consumer error that stopped the stream.- }- }- reader.releaseLock();- }- },-});-/** Adapts an injected HTTP/CDN transport to the revisioned source contract. */export const createHttpDocumentSourceLoader = ({fetch: fetchResponse,@@ -127,7 +101,7 @@ export const createHttpDocumentSourceLoader = ({}return Object.freeze({...metadata,- source: streamResponseBody(body),+ source: readableStreamToAsyncIterable(body),});};return observeDocumentSourceLoader({ load, onEvent });diff --git a/packages/content-engine/src/document-graph/index.ts b/packages/content-engine/src/document-graph/index.tsindex c3c58232ea..15dcb8326a 100644--- a/packages/content-engine/src/document-graph/index.ts+++ b/packages/content-engine/src/document-graph/index.ts@@ -6,6 +6,8 @@ export * from "./compiler";export * from "./source-compiler";export * from "./json-document";export * from "./markdown-document";+export * from "./mdx-document";+export * from "./document-format";export * from "./document-adapter";export * from "./document-source";export * from "./http-document-loader";diff --git a/packages/content-engine/src/document-graph/mdx-document.ts b/packages/content-engine/src/document-graph/mdx-document.tsnew file mode 100644index 0000000000..f118e5d7db--- /dev/null+++ b/packages/content-engine/src/document-graph/mdx-document.ts@@ -0,0 +1,113 @@+import type { ByteSource } from "../byte-stream";+import type { MdxDocument } from "../mdx";+import { parseMdxDocument } from "../mdx";+import { contentEngineLimits } from "../limits";+import {+ analyzeMarkdownDocument,+ assembleMarkdownDocument,+ parseMarkdownDocumentSource,+ selectMarkdownDocumentRepresentation,+ type MarkdownDocument,+} from "./markdown-document";+import type { DocumentRepresentation } from "./reference";+import type { SourceReferenceOccurrence } from "./reference-codec";++export type MdxAdaptedDocument = MarkdownDocument &+ Readonly<{ authored: MdxDocument }>;++const toMarkdownDocument = ({+ source,+ body,+ frontmatter,+}: MdxAdaptedDocument): MarkdownDocument => ({ source, body, frontmatter });++const createMdxAdaptedDocument = ({+ markdown,+ authored,+}: {+ markdown: MarkdownDocument;+ authored: MdxDocument;+}): MdxAdaptedDocument =>+ Object.freeze({+ ...markdown,+ authored,+ });++const parseAuthoredDocument = async (+ markdown: MarkdownDocument,+ maximumBytes: number+) =>+ createMdxAdaptedDocument({+ markdown,+ authored: await parseMdxDocument({ source: markdown.source, maximumBytes }),+ });++export const parseMdxDocumentSource = async ({+ source,+ maximumBytes = contentEngineLimits.hydratedFileBytes,+}: {+ source: ByteSource;+ maximumBytes?: number;+}) =>+ parseAuthoredDocument(+ await parseMarkdownDocumentSource({ source, maximumBytes }),+ maximumBytes+ );++export const analyzeMdxDocument = async ({+ source,+ sourceDocumentId,+ documentUrl,+ maximumBytes = contentEngineLimits.hydratedFileBytes,+}: {+ source: ByteSource;+ sourceDocumentId: string;+ documentUrl: string | URL;+ maximumBytes?: number;+}): Promise<+ Readonly<{+ document: MdxAdaptedDocument;+ references: readonly SourceReferenceOccurrence[];+ }>+> => {+ const analyzed = await analyzeMarkdownDocument({+ source,+ sourceDocumentId,+ documentUrl,+ maximumBytes,+ });+ return Object.freeze({+ document: await parseAuthoredDocument(analyzed.document, maximumBytes),+ references: analyzed.references,+ });+};++export const assembleMdxDocument = ({+ document,+ references,+ allowUnresolvedReferences,+}: {+ document: MdxAdaptedDocument;+ references: ReadonlyMap<string, unknown>;+ allowUnresolvedReferences?: boolean;+}) =>+ createMdxAdaptedDocument({+ markdown: assembleMarkdownDocument({+ document: toMarkdownDocument(document),+ references,+ allowUnresolvedReferences,+ }),+ authored: document.authored,+ });++export const selectMdxDocumentRepresentation = ({+ document,+ representation,+}: {+ document: MdxAdaptedDocument;+ representation: DocumentRepresentation;+}) =>+ selectMarkdownDocumentRepresentation({+ document: toMarkdownDocument(document),+ representation,+ });diff --git a/packages/content-engine/src/document-graph/source-compiler.ts b/packages/content-engine/src/document-graph/source-compiler.tsindex 4d7b115ddd..af280981e7 100644--- a/packages/content-engine/src/document-graph/source-compiler.ts+++ b/packages/content-engine/src/document-graph/source-compiler.ts@@ -3,7 +3,8 @@ import type { ByteSource } from "../byte-stream";import { contentEngineLimits } from "../limits";import { compareStrings } from "../canonical-json";import { compileDocumentGraph, type DocumentDescriptor } from "./compiler";-import { analyzeDocumentSource, type DocumentFormat } from "./document-adapter";+import { analyzeDocumentSource } from "./document-adapter";+import type { DocumentFormat } from "./document-format";import type { DocumentGraph } from "./graph";import type { SourceReferenceOccurrence } from "./reference-codec";diff --git a/packages/content-engine/src/document-metadata.test.ts b/packages/content-engine/src/document-metadata.test.tsindex 7762a8dced..9c3d0fffb0 100644--- a/packages/content-engine/src/document-metadata.test.ts+++ b/packages/content-engine/src/document-metadata.test.ts@@ -7,11 +7,15 @@ const createEntry = ({properties = {},excerpt,prepared = false,+ format = "markdown",+ size = 44,}: {revision?: string;properties?: Record<string, string>;excerpt?: string;prepared?: boolean;+ format?: "markdown" | "mdx";+ size?: number;} = {}) =>createCanonicalAssetFileEntry({projectId: "project",@@ -22,20 +26,37 @@ const createEntry = ({document: {_id: "post",_type: "asset.file",- name: "post.md",- path: "blog/post.md",+ name: `post.${format === "markdown" ? "md" : "mdx"}`,+ path: `blog/post.${format === "markdown" ? "md" : "mdx"}`,key: "post",- extension: "md",- mimeType: "text/markdown",- size: 44,+ extension: format === "markdown" ? "md" : "mdx",+ mimeType: format === "markdown" ? "text/markdown" : "text/mdx",+ size,revision,- contentRef: "post.md",+ contentRef: `post.${format === "markdown" ? "md" : "mdx"}`,properties,...(excerpt === undefined ? {} : { excerpt }),},});describe("content metadata cache", () => {+ test("indexes MDX frontmatter without generating a Markdown excerpt", async () => {+ const bytes = new TextEncoder().encode(+ "---\ntitle: MDX post\n---\n<ws.element>Body</ws.element>"+ );+ const readBytes = vi.fn(async () => bytes);++ const prepared = await prepareCanonicalContentMetadata({+ base: createEntry({ format: "mdx", size: bytes.byteLength }),+ requirements: { structuredProperties: true, excerpt: true },+ readBytes,+ });++ expect(prepared.document.properties).toEqual({ title: "MDX post" });+ expect(prepared.document).not.toHaveProperty("excerpt");+ expect(readBytes).toHaveBeenCalledWith(bytes.byteLength);+ });+test("reuses a matching prepared entry without reading source bytes", async () => {const cached = createEntry({properties: { title: "Cached" },diff --git a/packages/content-engine/src/document-metadata.ts b/packages/content-engine/src/document-metadata.tsindex 3a9a44f9bd..e5875c97d0 100644--- a/packages/content-engine/src/document-metadata.ts+++ b/packages/content-engine/src/document-metadata.ts@@ -16,6 +16,9 @@ import { markdownFrontmatterEnvelopeBytes } from "./markdown-scanner";const isMarkdown = (entry: CanonicalAssetFileEntry) =>entry.document.extension.toLowerCase() === "md";+const hasMarkdownFrontmatter = (entry: CanonicalAssetFileEntry) =>+ isMarkdown(entry) || entry.document.extension.toLowerCase() === "mdx";+const isJson = (entry: CanonicalAssetFileEntry) =>entry.document.extension.toLowerCase() === "json";@@ -108,14 +111,23 @@ export const prepareCanonicalContentMetadata = async ({const needsExcerpt =requirements.excerpt && cachedRequirements.excerpt === false;- if (isMarkdown(base) && (needsProperties || needsExcerpt)) {- // Frontmatter discovery needs only the bounded opening block. Excerpt- // generation still receives the larger Markdown body budget.- const maximumBytes = needsExcerpt- ? contentEngineLimits.hydratedFileBytes- : contentEngineLimits.frontmatterBytes + markdownFrontmatterEnvelopeBytes;+ if (+ (hasMarkdownFrontmatter(base) && needsProperties) ||+ (isMarkdown(base) && needsExcerpt)+ ) {+ // Frontmatter discovery needs only the bounded opening block. Markdown+ // excerpt generation still receives the larger body budget.+ const maximumBytes =+ isMarkdown(base) && needsExcerpt+ ? contentEngineLimits.hydratedFileBytes+ : contentEngineLimits.frontmatterBytes ++ markdownFrontmatterEnvelopeBytes;let bytes = await readBytes(Math.min(base.document.size, maximumBytes));- if (needsExcerpt && base.document.size > bytes.byteLength) {+ if (+ isMarkdown(base) &&+ needsExcerpt &&+ base.document.size > bytes.byteLength+ ) {bytes = trimIncompleteUtf8Suffix(bytes);}if (needsProperties) {@@ -128,7 +140,7 @@ export const prepareCanonicalContentMetadata = async ({metadataError = { code: error.code, message: error.message };}}- if (needsExcerpt) {+ if (isMarkdown(base) && needsExcerpt) {try {excerpt = (await extractMarkdownBodyAndExcerpt(bytes)).excerpt;} catch (error) {diff --git a/packages/content-engine/src/limits.ts b/packages/content-engine/src/limits.tsindex 77247b2e27..5fc0ac2f92 100644--- a/packages/content-engine/src/limits.ts+++ b/packages/content-engine/src/limits.ts@@ -21,6 +21,9 @@ export const contentEngineLimits = {jsonStringBytes: 16 * 1024,indexedPropertiesBytes: 64 * 1024,excerptBytes: 2 * 1024,+ mdxDepth: 100,+ mdxNodes: 20_000,+ mdxProps: 4_000,hydratedFileBytes: 1024 * 1024,hydratedTotalBytes: 2 * 1024 * 1024,hydratedFileCount: 20,diff --git a/packages/content-engine/src/markdown-assets.ts b/packages/content-engine/src/markdown-assets.tsindex a469a3c3a8..d384435fd2 100644--- a/packages/content-engine/src/markdown-assets.ts+++ b/packages/content-engine/src/markdown-assets.ts@@ -1,10 +1,8 @@import { parse, postprocess, preprocess } from "micromark";import { decodeString } from "micromark-util-decode-string";import { createCanonicalAssetPath } from "./asset-path";-import {- createAssetIdResolver,- createUniqueAssetIdsByPath,-} from "./asset-path-resolution";+import { createUniqueAssetIdsByPath } from "./asset-path-resolution";+import { createAssetReferenceResolver } from "./asset-reference-utils";import type { MarkdownAssetReference } from "./markdown-references";const getMarkdownUrlTokens = (markdown: string) => {@@ -41,15 +39,16 @@ export const discoverMarkdownAssetReferenceRanges = ({sourcePath: string;assetIdsByPath: ReadonlyMap<string, string>;}): MarkdownAssetReference[] => {- const resolveAssetId = createAssetIdResolver(assetIdsByPath, sourcePath);+ const resolveAssetReference = createAssetReferenceResolver({+ assetIdsByPath,+ sourcePath,+ });return getMarkdownUrlTokens(markdown).flatMap(({ start, end, url }) => {- const assetId = resolveAssetId(url);- if (assetId === undefined) {+ const reference = resolveAssetReference(url);+ if (reference === undefined) {return [];}- const parsed = new URL(url, "https://content.webstudio.invalid/");- const suffix = `${parsed.search}${parsed.hash}`;- return [{ start, end, assetId, ...(suffix === "" ? {} : { suffix }) }];+ return [{ start, end, ...reference }];});};diff --git a/packages/content-engine/src/markdown-ast.ts b/packages/content-engine/src/markdown-ast.tsnew file mode 100644index 0000000000..cffa77a0cf--- /dev/null+++ b/packages/content-engine/src/markdown-ast.ts@@ -0,0 +1,52 @@+import remarkFrontmatter from "remark-frontmatter";+import remarkGfm from "remark-gfm";+import remarkMdx, { type Options as RemarkMdxOptions } from "remark-mdx";+import remarkParse from "remark-parse";+import { unified } from "unified";++export type SyntaxTreeNode = {+ type: string;+ children?: unknown;+ position?: unknown;+ data?: unknown;+ [key: string]: unknown;+};++export const isSyntaxTreeNode = (value: unknown): value is SyntaxTreeNode =>+ typeof value === "object" &&+ value !== null &&+ "type" in value &&+ typeof value.type === "string";++export const getSyntaxTreeChildren = (node: SyntaxTreeNode) => {+ if (Array.isArray(node.children) === false) {+ return [];+ }+ return node.children.filter(isSyntaxTreeNode);+};++const createMarkdownAstParser = () =>+ unified().use(remarkParse).use(remarkFrontmatter, ["yaml"]).use(remarkGfm);++const markdownAstParser = createMarkdownAstParser();+// Match standalone Webstudio JSX. remark-mdx 2 exposes obsolete types but+// uses Acorn 8 at runtime.+const mdxOptions = {+ acornOptions: {+ ecmaVersion: "latest",+ sourceType: "module",+ },+} as unknown as RemarkMdxOptions;+const mdxAstParser = createMarkdownAstParser().use(remarkMdx, mdxOptions);++/**+ * Parses CommonMark, GFM, and frontmatter consistently. MDX syntax additionally+ * interprets HTML-shaped input as JSX.+ */+export const parseMarkdownAst = (+ source: string,+ syntax: "markdown" | "mdx" = "markdown"+): SyntaxTreeNode =>+ (syntax === "mdx" ? mdxAstParser : markdownAstParser).parse(+ source+ ) as SyntaxTreeNode;diff --git a/packages/content-engine/src/markdown-references.ts b/packages/content-engine/src/markdown-references.tsindex ff1adc9a9c..e917844a9c 100644--- a/packages/content-engine/src/markdown-references.ts+++ b/packages/content-engine/src/markdown-references.ts@@ -1,46 +1,15 @@-export type MarkdownAssetReference = {+import { mergeAssetUrlSuffix } from "./asset-value-references";+import type { ResolvedAssetReference } from "./asset-reference-utils";++export type MarkdownAssetReference = ResolvedAssetReference & {start: number;end: number;- assetId: string;- suffix?: string;};export type MarkdownAssetReferences = Readonly<Record<string, readonly MarkdownAssetReference[]>>;-const appendMarkdownReferenceSuffix = (- assetUrl: string,- suffix: string | undefined-) => {- if (suffix === undefined || suffix.length === 0) {- return assetUrl;- }- const base = new URL("https://content.webstudio.invalid/__assets__/");- const target = new URL(assetUrl, base);- const reference = new URL(suffix, base);- for (const [name, value] of reference.searchParams) {- target.searchParams.append(name, value);- }- if (reference.hash !== "") {- target.hash = reference.hash;- }- if (URL.canParse(assetUrl)) {- return target.href;- }- if (assetUrl.startsWith("//")) {- return `//${target.host}${target.pathname}${target.search}${target.hash}`;- }- if (assetUrl.startsWith("/")) {- return `${target.pathname}${target.search}${target.hash}`;- }- const basePath = base.pathname;- const pathname = target.pathname.startsWith(basePath)- ? target.pathname.slice(basePath.length)- : target.pathname;- return `${pathname}${target.search}${target.hash}`;-};-export const rewriteMarkdownAssetReferenceRanges = ({markdown,references,@@ -68,10 +37,7 @@ export const rewriteMarkdownAssetReferenceRanges = ({if (assetUrl === undefined) {continue;}- const resolvedUrl = appendMarkdownReferenceSuffix(- assetUrl,- reference.suffix- );+ const resolvedUrl = mergeAssetUrlSuffix(assetUrl, reference.suffix);result = `${result.slice(0, reference.start)}${resolvedUrl}${result.slice(reference.end)}`;}return result;diff --git a/packages/content-engine/src/markdown.test.ts b/packages/content-engine/src/markdown.test.tsindex 2d2729df59..f9688eb777 100644--- a/packages/content-engine/src/markdown.test.ts+++ b/packages/content-engine/src/markdown.test.ts@@ -215,6 +215,12 @@ describe("Markdown body and excerpt extraction", () => {).toBe("Hello world Use code and links.");});+ test("uses GFM semantics in plain-text excerpts", () => {+ expect(extractMarkdownExcerpt("- [x] Ready\n\n~~obsolete~~")).toBe(+ "Ready obsolete"+ );+ });+test("truncates excerpts at a valid UTF-8 character boundary", () => {expect(extractMarkdownExcerpt("Hello 🌍 world", 10)).toBe("Hello 🌍");expect(diff --git a/packages/content-engine/src/markdown.ts b/packages/content-engine/src/markdown.tsindex 1356d49e5a..967874a4bc 100644--- a/packages/content-engine/src/markdown.ts+++ b/packages/content-engine/src/markdown.ts@@ -1,9 +1,12 @@import { contentEngineLimits } from "./limits";-import remarkParse from "remark-parse";-import { unified } from "unified";import { getUtf8ByteLength, type ByteSource } from "./byte-stream";import { MarkdownMetadataError } from "./markdown-errors";import { extractMarkdownBody } from "./markdown-body";+import {+ getSyntaxTreeChildren,+ parseMarkdownAst,+ type SyntaxTreeNode,+} from "./markdown-ast";export {MarkdownMetadataError,@@ -15,12 +18,6 @@ export {type MarkdownFrontmatter,} from "./frontmatter";-type MarkdownNode = {- type: string;- value?: unknown;- children?: MarkdownNode[];-};-const textNodeTypes = new Set(["text", "inlineCode", "code"]);const separatingNodeTypes = new Set(["paragraph",@@ -31,16 +28,16 @@ const separatingNodeTypes = new Set([]);const markdownToPlainText = (body: string) => {- const tree = unified().use(remarkParse).parse(body) as MarkdownNode;+ const tree = parseMarkdownAst(body);const parts: string[] = [];- const visit = (node: MarkdownNode) => {+ const visit = (node: SyntaxTreeNode) => {if (textNodeTypes.has(node.type) && typeof node.value === "string") {parts.push(node.value);}if (node.type === "html" || node.type === "yaml") {return;}- for (const child of node.children ?? []) {+ for (const child of getSyntaxTreeChildren(node)) {visit(child);}if (separatingNodeTypes.has(node.type)) {diff --git a/packages/content-engine/src/mdx-conversion.ts b/packages/content-engine/src/mdx-conversion.tsnew file mode 100644index 0000000000..ebf5c38796--- /dev/null+++ b/packages/content-engine/src/mdx-conversion.ts@@ -0,0 +1,194 @@+import { raw } from "hast-util-raw";+import {+ find as findHtmlProperty,+ html as htmlSchema,+} from "property-information";+import { VFile } from "vfile";+import { contentEngineLimits } from "./limits";+import {+ getSyntaxTreeChildren,+ isSyntaxTreeNode,+ type SyntaxTreeNode,+} from "./markdown-ast";+import {+ createMdxDocumentFromMarkdown,+ MdxDocumentError,+ parseMdxDocument,+ type MdxDocument,+ type MdxMode,+ type MdxSourceRange,+} from "./mdx";+import { serializeMdxDocument } from "./mdx-serialization";++const markdownElementNodeType = "webstudioMarkdownElement";+const markdownHtmlModeData = "webstudioMarkdownHtmlMode";+const phrasingMarkdownNodeTypes = new Set([+ "delete",+ "emphasis",+ "heading",+ "link",+ "linkReference",+ "paragraph",+ "strong",+ "tableCell",+]);++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === "object" && value !== null && Array.isArray(value) === false;++const getOffset = (node: SyntaxTreeNode) => {+ if (+ isRecord(node.position) === false ||+ isRecord(node.position.start) === false+ ) {+ return;+ }+ const { offset } = node.position.start;+ return typeof offset === "number" ? offset : undefined;+};++const setData = (node: SyntaxTreeNode, values: Record<string, unknown>) => {+ node.data = { ...(isRecord(node.data) ? node.data : {}), ...values };+};++const collectMarkdownHtmlModes = (root: SyntaxTreeNode) => {+ const modes = new Map<number, MdxMode>();+ const visit = (node: SyntaxTreeNode, parent?: SyntaxTreeNode) => {+ const offset = getOffset(node);+ if (node.type === "html" && offset !== undefined) {+ modes.set(+ offset,+ parent !== undefined && phrasingMarkdownNodeTypes.has(parent.type)+ ? "text"+ : "flow"+ );+ return;+ }+ for (const child of getSyntaxTreeChildren(node)) {+ visit(child, node);+ }+ };+ visit(root);+ return modes;+};++const prepareMarkdownElements = (+ node: SyntaxTreeNode,+ modes: ReadonlyMap<number, MdxMode>+) => {+ for (const child of getSyntaxTreeChildren(node)) {+ prepareMarkdownElements(child, modes);+ }+ if (node.type !== "element") {+ return;+ }+ node.type = markdownElementNodeType;+ const directModes = new Set(+ getSyntaxTreeChildren(node).flatMap((child) => {+ const offset = getOffset(child);+ const mode = offset === undefined ? undefined : modes.get(offset);+ return mode === undefined ? [] : [mode];+ })+ );+ if (directModes.size === 1) {+ setData(node, { [markdownHtmlModeData]: [...directModes][0] });+ }+};++const restoreMarkdownElements = (+ node: SyntaxTreeNode,+ inheritedMode: MdxMode = "flow"+) => {+ let childMode = inheritedMode;+ if (node.type === markdownElementNodeType) {+ node.type = "element";+ if (+ isRecord(node.data) &&+ (node.data[markdownHtmlModeData] === "flow" ||+ node.data[markdownHtmlModeData] === "text")+ ) {+ childMode = node.data[markdownHtmlModeData];+ delete node.data[markdownHtmlModeData];+ }+ } else if (node.type === "element" || node.type === "comment") {+ setData(node, { mdxMode: inheritedMode });+ if (node.type === "element" && isRecord(node.properties)) {+ node.properties = Object.fromEntries(+ Object.entries(node.properties).map(([name, value]) => [+ findHtmlProperty(htmlSchema, name).attribute,+ value,+ ])+ );+ }+ }+ for (const child of getSyntaxTreeChildren(node)) {+ restoreMarkdownElements(child, childMode);+ }+};++export type MarkdownToMdxConversionPreview = Readonly<{+ source: string;+ document: MdxDocument;+ omissions: readonly MarkdownToMdxConversionOmission[];+}>;++export type MarkdownToMdxConversionOmission = Readonly<{+ nodeType: string;+ reason: string;+ sourceRange: MdxSourceRange;+}>;++/** Converts Markdown without writing or allocating a destination Asset. */+export const previewMarkdownToMdxConversion = async ({+ source,+ maximumBytes = contentEngineLimits.hydratedFileBytes,+}: {+ source: string;+ maximumBytes?: number;+}): Promise<MarkdownToMdxConversionPreview> => {+ const omissions: MarkdownToMdxConversionOmission[] = [];+ const convertedDocument = await createMdxDocumentFromMarkdown({+ source,+ maximumBytes,+ transformHast: ({ sourceRoot, hastRoot }) => {+ prepareMarkdownElements(hastRoot, collectMarkdownHtmlModes(sourceRoot));+ const parsed = raw(+ hastRoot as Parameters<typeof raw>[0],+ new VFile(source),+ { passThrough: [markdownElementNodeType] }+ );+ if (isSyntaxTreeNode(parsed) === false || parsed.type !== "root") {+ throw new MdxDocumentError({+ code: "invalid-mdx",+ message: "Markdown did not produce an HTML document",+ });+ }+ restoreMarkdownElements(parsed);+ return parsed;+ },+ shouldOmitUnsafePart: (error) => {+ if (+ error.nodeType === undefined ||+ error.reason === undefined ||+ error.sourceRange === undefined+ ) {+ return false;+ }+ omissions.push({+ nodeType: error.nodeType,+ reason: error.reason,+ sourceRange: error.sourceRange,+ });+ return true;+ },+ });+ const convertedSource = serializeMdxDocument(convertedDocument);+ return {+ source: convertedSource,+ document: await parseMdxDocument({+ source: convertedSource,+ maximumBytes,+ }),+ omissions,+ };+};diff --git a/packages/content-engine/src/mdx-serialization.ts b/packages/content-engine/src/mdx-serialization.tsnew file mode 100644index 0000000000..c9c8b93b85--- /dev/null+++ b/packages/content-engine/src/mdx-serialization.ts@@ -0,0 +1,221 @@+import {+ defaultHandlers,+ toMdast,+ type Handle,+ type NodeHandle,+} from "hast-util-to-mdast";+import { gfmToMarkdown } from "mdast-util-gfm";+import { mdxExpressionToMarkdown } from "mdast-util-mdx-expression";+import {+ mdxJsxToMarkdown,+ type MdxJsxAttribute,+ type MdxJsxFlowElement,+ type MdxJsxTextElement,+} from "mdast-util-mdx-jsx";+import { toMarkdown } from "mdast-util-to-markdown";+import { stringify as stringifyYaml } from "yaml";+import type {+ MdxAuthoredNode,+ MdxAuthoredProp,+ MdxDocument,+ MdxMarkdownListItem,+ MdxMode,+} from "./mdx";++type SerializationNode = {+ type: string;+ tagName?: string;+ properties?: Record<string, unknown>;+ value?: string;+ children?: SerializationNode[];+ data?: {+ listItem?: MdxMarkdownListItem;+ mode?: MdxMode;+ props?: readonly MdxAuthoredProp[];+ rawText?: string;+ };+};++const protectTextWhitespace = (value: string) =>+ value.replace(/[\t\n\v\f\r ]/g, "\uE000");++const toHastProperties = (props: readonly MdxAuthoredProp[]) =>+ Object.fromEntries(+ props.map(({ name, value }) => [+ name === "class" ? "className" : name,+ name === "class" && typeof value === "string" ? value.split(" ") : value,+ ])+ );++const toTextNode = (+ value: string,+ protectWhitespace = true+): SerializationNode =>+ protectWhitespace+ ? {+ type: "text",+ value: protectTextWhitespace(value),+ data: { rawText: value },+ }+ : { type: "text", value };++const toWebstudioElement = ({+ mode,+ props,+ children,+}: {+ mode: MdxMode;+ props: readonly MdxAuthoredProp[];+ children: readonly MdxAuthoredNode[];+}): SerializationNode => ({+ type: "element",+ tagName: "ws.element",+ properties: {},+ children: children.map((child) => toSerializationNode(child)),+ data: { mode, props },+});++const toSerializationNode = (+ node: MdxAuthoredNode,+ hastPreservesWhitespace = false+): SerializationNode => {+ if (node.type === "text") {+ return toTextNode(node.value, hastPreservesWhitespace === false);+ }+ if (node.type === "comment") {+ return { type: "comment", value: node.value, data: { mode: node.mdxMode } };+ }+ if (node.type === "template") {+ return toWebstudioElement({+ mode: node.mdxMode,+ props: [{ name: "ws:name", value: node.name }, ...node.props],+ children: node.children,+ });+ }+ if (node.syntax === "mdx") {+ return toWebstudioElement({+ mode: node.mdxMode,+ props: [{ name: "ws:tag", value: node.tag }, ...node.props],+ children: node.children,+ });+ }++ let children = node.children.map((child) =>+ toSerializationNode(+ child,+ hastPreservesWhitespace || node.preserveTextWhitespace === true+ )+ );+ if (+ node.markdownListItem?.checked !== undefined &&+ node.markdownListItem.spread === false+ ) {+ children = [{ type: "element", tagName: "p", properties: {}, children }];+ }+ return {+ type: "element",+ tagName: node.tag,+ properties: toHastProperties(node.props),+ children,+ data:+ node.markdownListItem === undefined+ ? undefined+ : { listItem: node.markdownListItem },+ };+};++const getSerializationData = (node: { data?: unknown }) =>+ node.data as SerializationNode["data"];++const mapWebstudioElement: Handle = (state, node) => {+ const data = getSerializationData(node);+ const attributes: MdxJsxAttribute[] = (data?.props ?? []).map((prop) => ({+ type: "mdxJsxAttribute",+ name: prop.name,+ value: prop.value === true ? null : prop.value,+ }));+ const children = state.all(node as never);+ if (data?.mode === "text") {+ return {+ type: "mdxJsxTextElement",+ name: "ws.element",+ attributes,+ children,+ } as MdxJsxTextElement;+ }+ return {+ type: "mdxJsxFlowElement",+ name: "ws.element",+ attributes,+ children: state.toFlow(children),+ } as MdxJsxFlowElement;+};++const mapComment: NodeHandle = (_state, node) => ({+ type:+ getSerializationData(node)?.mode === "text"+ ? "mdxTextExpression"+ : "mdxFlowExpression",+ value: typeof node.value === "string" ? node.value : "",+});++const mapText: NodeHandle = (_state, node) => ({+ type: "text",+ value:+ getSerializationData(node)?.rawText ??+ (typeof node.value === "string" ? node.value : ""),+});++const mapListItem: Handle = (state, node) => {+ const result = defaultHandlers.li(state, node);+ const listItem = getSerializationData(node)?.listItem;+ if (+ listItem !== undefined &&+ result !== undefined &&+ Array.isArray(result) === false &&+ result.type === "listItem"+ ) {+ result.spread = listItem.spread;+ }+ return result;+};++const serializeFrontmatter = (document: MdxDocument) => {+ if (+ document.frontmatter.sourceRange === undefined &&+ Object.keys(document.frontmatter.properties).length === 0+ ) {+ return "";+ }+ const yaml = stringifyYaml(document.frontmatter.properties, {+ aliasDuplicateObjects: false,+ lineWidth: 0,+ sortMapEntries: true,+ }).trimEnd();+ return `---\n${yaml}\n---\n\n`;+};++export const serializeMdxDocument = (document: MdxDocument) => {+ const hast = {+ type: "root",+ children: document.children.map((node) => toSerializationNode(node)),+ } as Parameters<typeof toMdast>[0];+ const mdast = toMdast(hast, {+ document: true,+ handlers: { li: mapListItem, "ws.element": mapWebstudioElement },+ nodeHandlers: { comment: mapComment, text: mapText },+ });+ return (+ serializeFrontmatter(document) ++ toMarkdown(mdast, {+ bullet: "-",+ emphasis: "_",+ extensions: [+ gfmToMarkdown(),+ mdxExpressionToMarkdown,+ mdxJsxToMarkdown({ quote: '"' }),+ ],+ fences: true,+ })+ );+};diff --git a/packages/content-engine/src/mdx.test.ts b/packages/content-engine/src/mdx.test.tsnew file mode 100644index 0000000000..cf6d08a05d--- /dev/null+++ b/packages/content-engine/src/mdx.test.ts@@ -0,0 +1,909 @@+import { describe, expect, test } from "vitest";+import { resolveAssetValueReferences } from "./asset-value-references";+import { parseMarkdownAst } from "./markdown-ast";+import { previewMarkdownToMdxConversion } from "./mdx-conversion";+import {+ discoverMdxAssetReferences,+ MdxDocumentError,+ parseMdxDocument,+ serializeMdxDocument,+} from "./mdx";++const omitSourceRanges = (value: unknown): unknown => {+ if (Array.isArray(value)) {+ return value.map(omitSourceRanges);+ }+ if (typeof value !== "object" || value === null) {+ return value;+ }+ return Object.fromEntries(+ Object.entries(value).flatMap(([key, item]) =>+ key === "sourceRange" ? [] : [[key, omitSourceRanges(item)]]+ )+ );+};++describe("parseMdxDocument", () => {+ test("parses Markdown-only input identically through Markdown and MDX", () => {+ const source = `---+title: Shared grammar+---+# Heading *with emphasis*++Paragraph with **strong**, ~~deleted~~, [inline](/docs), [reference][docs], and https://example.com.++> Blockquote++- [x] Task+- Item++1. Ordered+2. List++| Name | Ready |+| :--- | ---: |+| Ada | Yes |++\`inline code\`++\`\`\`ts+const ready = true;+\`\`\`++++---++[docs]: /guide "Guide"+`;++ expect(parseMarkdownAst(source, "mdx")).toEqual(parseMarkdownAst(source));+ });++ test("parses frontmatter and semantic Markdown with source ranges", async () => {+ const document = await parseMdxDocument({+ source: `---+title: Hello+author:+ $ref: ./author.json+---+# Hello **world**++[Read more](/docs)+`,+ });++ expect(document.frontmatter).toEqual({+ properties: {+ title: "Hello",+ author: { $ref: "./author.json" },+ },+ sourceRange: {+ start: { line: 1, column: 1, offset: 0 },+ end: { line: 5, column: 4, offset: 50 },+ },+ });+ expect(document.children).toEqual([+ {+ type: "element",+ syntax: "markdown",+ tag: "h1",+ props: [],+ children: [+ {+ type: "text",+ value: "Hello ",+ sourceRange: {+ start: { line: 6, column: 3, offset: 53 },+ end: { line: 6, column: 9, offset: 59 },+ },+ },+ {+ type: "element",+ syntax: "markdown",+ tag: "strong",+ props: [],+ children: [+ expect.objectContaining({ type: "text", value: "world" }),+ ],+ sourceRange: {+ start: { line: 6, column: 9, offset: 59 },+ end: { line: 6, column: 18, offset: 68 },+ },+ },+ ],+ sourceRange: {+ start: { line: 6, column: 1, offset: 51 },+ end: { line: 6, column: 18, offset: 68 },+ },+ },+ {+ type: "element",+ syntax: "markdown",+ tag: "p",+ props: [],+ children: [+ {+ type: "element",+ syntax: "markdown",+ tag: "a",+ props: [{ name: "href", value: "/docs" }],+ children: [+ expect.objectContaining({ type: "text", value: "Read more" }),+ ],+ sourceRange: {+ start: { line: 8, column: 1, offset: 70 },+ end: { line: 8, column: 19, offset: 88 },+ },+ },+ ],+ sourceRange: {+ start: { line: 8, column: 1, offset: 70 },+ end: { line: 8, column: 19, offset: 88 },+ },+ },+ ]);+ });++ test("maps GFM tables and inline marks to semantic elements", async () => {+ const document = await parseMdxDocument({+ source: `| Name | Ready |+| :--- | ---: |+| **Ada** | ~~No~~ |+`,+ });++ expect(document.children[0]).toMatchObject({+ type: "element",+ tag: "table",+ children: [+ {+ type: "element",+ tag: "thead",+ children: [+ {+ type: "element",+ tag: "tr",+ children: [+ {+ type: "element",+ tag: "th",+ props: [{ name: "align", value: "left" }],+ },+ {+ type: "element",+ tag: "th",+ props: [{ name: "align", value: "right" }],+ },+ ],+ },+ ],+ },+ {+ type: "element",+ tag: "tbody",+ children: [+ {+ type: "element",+ tag: "tr",+ children: [+ {+ type: "element",+ tag: "td",+ children: [{ type: "element", tag: "strong" }],+ },+ {+ type: "element",+ tag: "td",+ children: [{ type: "element", tag: "del" }],+ },+ ],+ },+ ],+ },+ ],+ });+ });++ test("parses generic elements, template usages, and nested Markdown", async () => {+ const document = await parseMdxDocument({+ source: `<ws.element ws:tag="section" data-kind="hero" hidden>+ <ws.element ws:name="Hero Card" tone="quiet">+ ## Nested title+ </ws.element>+</ws.element>+`,+ });++ expect(document.children).toEqual([+ expect.objectContaining({+ type: "element",+ syntax: "mdx",+ mdxMode: "flow",+ tag: "section",+ props: [+ { name: "data-kind", value: "hero" },+ { name: "hidden", value: true },+ ],+ children: [+ expect.objectContaining({+ type: "template",+ mdxMode: "flow",+ name: "Hero Card",+ props: [{ name: "tone", value: "quiet" }],+ children: [expect.objectContaining({ type: "element", tag: "h2" })],+ }),+ ],+ }),+ ]);+ });++ test("preserves non-executable MDX comments", async () => {+ const document = await parseMdxDocument({+ source: `{/* keep this note */}++<ws.element ws:tag="p">Text {/* inline note */}</ws.element>+`,+ });++ expect(document.children).toEqual([+ expect.objectContaining({+ type: "comment",+ mdxMode: "flow",+ value: "/* keep this note */",+ }),+ expect.objectContaining({+ type: "element",+ tag: "p",+ children: [+ expect.objectContaining({ type: "text", value: "Text " }),+ expect.objectContaining({+ type: "comment",+ mdxMode: "text",+ value: "/* inline note */",+ }),+ ],+ }),+ ]);+ });++ test("resolves reference-style links and images", async () => {+ const document = await parseMdxDocument({+ source: `[Read][docs] and ![Cover][image]++[docs]: /guide "Guide"+[image]: /cover.png+`,+ });++ expect(document.children[0]).toMatchObject({+ type: "element",+ tag: "p",+ children: [+ {+ type: "element",+ tag: "a",+ props: [+ { name: "href", value: "/guide" },+ { name: "title", value: "Guide" },+ ],+ },+ { type: "text", value: " and " },+ {+ type: "element",+ tag: "img",+ props: [+ { name: "src", value: "/cover.png" },+ { name: "alt", value: "Cover" },+ ],+ },+ ],+ });+ });++ test("preserves tight and loose list rendering semantics", async () => {+ const tight = await parseMdxDocument({ source: "- one\n- two\n" });+ const loose = await parseMdxDocument({ source: "- one\n\n- two\n" });++ expect(tight.children[0]).toMatchObject({+ type: "element",+ tag: "ul",+ children: [+ {+ type: "element",+ tag: "li",+ children: [{ type: "text", value: "one" }],+ },+ {+ type: "element",+ tag: "li",+ children: [{ type: "text", value: "two" }],+ },+ ],+ });+ expect(loose.children[0]).toMatchObject({+ type: "element",+ tag: "ul",+ children: [+ {+ type: "element",+ tag: "li",+ children: [{ type: "element", tag: "p" }],+ },+ {+ type: "element",+ tag: "li",+ children: [{ type: "element", tag: "p" }],+ },+ ],+ });+ });++ test("preserves standard GFM output details", async () => {+ const document = await parseMdxDocument({+ source: `[missing][reference]++- [x] Done++\`\`\`js+const ready = true;+\`\`\`+`,+ });++ expect(document.children).toMatchObject([+ {+ type: "element",+ tag: "p",+ children: [{ type: "text", value: "[missing][reference]" }],+ },+ {+ type: "element",+ tag: "ul",+ props: [{ name: "class", value: "contains-task-list" }],+ children: [+ {+ type: "element",+ syntax: "markdown",+ tag: "li",+ props: [{ name: "class", value: "task-list-item" }],+ markdownListItem: { checked: true, spread: false },+ children: [+ { type: "element", tag: "input" },+ { type: "text", value: " " },+ { type: "text", value: "Done" },+ ],+ },+ ],+ },+ {+ type: "element",+ tag: "pre",+ children: [+ {+ type: "element",+ tag: "code",+ props: [{ name: "class", value: "language-js" }],+ children: [{ type: "text", value: "const ready = true;\n" }],+ },+ ],+ },+ ]);+ });++ test("discovers and rewrites frontmatter and authored prop Asset references", async () => {+ const document = await parseMdxDocument({+ source: `---+cover: ./cover.png?size=2+---+++<ws.element ws:name="Card" poster="./video.jpg">+ Text containing ./ignored.png+</ws.element>+`,+ });+ const references = discoverMdxAssetReferences({+ document,+ sourcePath: "posts/post.mdx",+ assetIdsByPath: new Map([+ ["posts/cover.png", "cover"],+ ["posts/hero.png", "hero"],+ ["posts/video.jpg", "video"],+ ["posts/ignored.png", "ignored"],+ ]),+ });++ expect(references).toEqual([+ {+ path: ["frontmatter", "properties", "cover"],+ assetId: "cover",+ suffix: "?size=2",+ },+ {+ path: ["children", 0, "children", 0, "props", 0, "value"],+ assetId: "hero",+ suffix: "#crop",+ },+ {+ path: ["children", 1, "props", 0, "value"],+ assetId: "video",+ },+ ]);++ expect(+ resolveAssetValueReferences({+ value: document,+ references,+ assetUrls: {+ cover: "/assets/cover.png",+ hero: "/assets/hero.png",+ video: "/assets/video.jpg",+ },+ })+ ).toMatchObject({+ frontmatter: { properties: { cover: "/assets/cover.png?size=2" } },+ children: [+ {+ children: [+ {+ props: [+ { name: "src", value: "/assets/hero.png#crop" },+ { name: "alt", value: "Hero" },+ ],+ },+ ],+ },+ { props: [{ name: "poster", value: "/assets/video.jpg" }] },+ ],+ });+ expect(document.frontmatter.properties.cover).toBe("./cover.png?size=2");+ });++ test("serializes supported documents deterministically with semantic round trips", async () => {+ const document = await parseMdxDocument({+ source: `---+title: Example+author:+ $ref: ./author.json+---+# Hello **world**++- [x] Ready++| Name | State |+| --- | --- |+| Ada | ~~Done~~ |++<ws.element ws:tag="section" data-kind="hero">+ <ws.element ws:name="Hero Card" tone="quiet">+ ## Nested title+ </ws.element>+</ws.element>++Paragraph with <ws.element ws:tag="span">inline</ws.element> content.++{/* keep this note */}+`,+ });++ const serialized = serializeMdxDocument(document);+ expect(serializeMdxDocument(document)).toBe(serialized);+ expect(serialized).toContain("$ref: ./author.json");+ expect(serialized.indexOf("author:")).toBeLessThan(+ serialized.indexOf("title:")+ );+ expect(serialized).toContain('<ws.element ws:tag="section"');+ expect(serialized).toContain('<ws.element ws:name="Hero Card"');+ expect(serialized).toContain("{/* keep this note */}");++ const reparsed = await parseMdxDocument({ source: serialized });+ expect(omitSourceRanges(reparsed)).toEqual(omitSourceRanges(document));+ });++ test("preserves elements that Markdown cannot represent losslessly", async () => {+ const document = await parseMdxDocument({+ source: `<ws.element ws:tag="input" type="checkbox" disabled />++<ws.element ws:tag="code" class="custom">+ <ws.element ws:tag="strong">Nested</ws.element>+</ws.element>++<ws.element ws:tag="ul">+ <ws.element ws:tag="div">Not a list item</ws.element>+</ws.element>++<ws.element ws:tag="p" />++<ws.element ws:tag="table" />++<ws.element ws:tag="li">Standalone item</ws.element>++<ws.element ws:tag="div">line+next</ws.element>++<ws.element ws:tag="div">before {/* inline */} after</ws.element>++<ws.element ws:tag="pre"><ws.element ws:tag="code" /></ws.element>++<ws.element ws:tag="ol" start="007">+ <ws.element ws:tag="li">Leading zero</ws.element>+</ws.element>++<ws.element ws:tag="table">+ <ws.element ws:tag="thead">+ <ws.element ws:tag="tr">+ <ws.element ws:tag="th">+ <ws.element ws:tag="p">Invalid cell block</ws.element>+ </ws.element>+ </ws.element>+ </ws.element>+</ws.element>+`,+ });++ const serialized = serializeMdxDocument(document);+ const reparsed = await parseMdxDocument({ source: serialized });+ expect(omitSourceRanges(reparsed)).toEqual(omitSourceRanges(document));+ });++ test.each([+ ["empty content", ""],+ ["ordered task lists", "1. [x] Done\n2. [ ] Pending\n"],+ ["loose task lists", "- [x] Done\n\n- [ ] Pending\n"],+ ["nested lists", "- Parent\n 1. Child\n"],+ ["ordered list starts", "7. Seven\n8. Eight\n"],+ ["fenced code without a language", "```\nvalue\n```\n"],+ ])("round trips %s", async (_name, source) => {+ const document = await parseMdxDocument({ source });+ const reparsed = await parseMdxDocument({+ source: serializeMdxDocument(document),+ });++ expect(omitSourceRanges(reparsed)).toEqual(omitSourceRanges(document));+ });++ test.each([+ ['<ws.element ws:tag="script">alert(1)</ws.element>', "unsafe tag"],+ ['<ws.element ws:name="Card" ws:tag="div" />', "conflicting selectors"],+ [+ '<ws.element ws:tag="div" class="one" className="two" />',+ "conflicting property names",+ ],+ ['<ws.element ws:tag="div" onclick="alert(1)" />', "event prop"],+ ['<ws.element ws:tag="iframe" srcdoc="<script />" />', "srcdoc"],+ ['<ws.element ws:tag="a" href="javascript:alert(1)" />', "unsafe link URL"],+ [+ '<ws.element ws:tag="img" src="data:text/html,<script />" />',+ "unsafe source URL",+ ],+ [+ '<ws.element ws:tag="use" xlinkHref="javascript:alert(1)" />',+ "unsafe SVG link URL",+ ],+ ["[unsafe](javascript:alert(1))", "unsafe Markdown link URL"],+ ["", "unsafe Markdown image URL"],+ [+ "[unsafe][target]\n\n[target]: javascript:alert(1)",+ "unsafe reference URL",+ ],+ ])("rejects %s", async (source) => {+ await expect(parseMdxDocument({ source })).rejects.toMatchObject({+ code: "unsafe-mdx",+ sourceRange: expect.objectContaining({+ start: expect.objectContaining({ line: 1 }),+ }),+ } satisfies Partial<MdxDocumentError>);+ });++ test("rejects documents that exceed structural limits", async () => {+ const deepSource =+ "<ws.element>".repeat(101) + "text" + "</ws.element>".repeat(101);+ const nodeHeavySource = "paragraph\n\n".repeat(10_001);+ const propHeavySource = `<ws.element ${Array.from(+ { length: 4_001 },+ (_, index) => `data-${index}="value"`+ ).join(" ")} />`;++ for (const source of [deepSource, nodeHeavySource, propHeavySource]) {+ await expect(parseMdxDocument({ source })).rejects.toMatchObject({+ code: "invalid-mdx",+ } satisfies Partial<MdxDocumentError>);+ }+ });++ test.each([+ ["imports", 'import Card from "./card"', "mdxjsEsm"],+ ["exports", "export const value = 1", "mdxjsEsm"],+ ["flow expressions", "{call()}", "mdxFlowExpression"],+ ["text expressions", "Hello {name}", "mdxTextExpression"],+ [+ "attribute expressions",+ '<ws.element ws:tag="div" value={1_000} />',+ "mdxJsxAttributeValueExpression",+ ],+ [+ "attribute spreads",+ '<ws.element ws:tag="div" {...props} />',+ "mdxJsxExpressionAttribute",+ ],+ ["arbitrary components", "<Card />", "mdxJsxFlowElement"],+ ["HTML-looking JSX", "<div>Unsafe</div>", "mdxJsxTextElement"],+ ])("rejects %s", async (_name, source, nodeType) => {+ await expect(parseMdxDocument({ source })).rejects.toMatchObject({+ code: "unsafe-mdx",+ nodeType,+ sourceRange: expect.objectContaining({+ start: expect.objectContaining({ line: 1 }),+ }),+ } satisfies Partial<MdxDocumentError>);+ });++ test("reports malformed JSX as invalid MDX", async () => {+ await expect(+ parseMdxDocument({ source: "<ws.element>" })+ ).rejects.toMatchObject({+ code: "invalid-mdx",+ sourceRange: {+ start: { line: 1, column: 1 },+ end: { line: 1, column: 1 },+ },+ } satisfies Partial<MdxDocumentError>);+ });+});++describe("previewMarkdownToMdxConversion", () => {+ test("converts Markdown and embedded HTML through the shared authored tree", async () => {+ const source = `---+title: Existing post+cover: ./cover.png+---+# Heading++Before <span class="accent">inline</span> after.++<figure data-kind="hero"><img src="./hero.png" alt="Hero"></figure>+`;++ const preview = await previewMarkdownToMdxConversion({ source });++ expect(preview.document.frontmatter.properties).toEqual({+ title: "Existing post",+ cover: "./cover.png",+ });+ expect(omitSourceRanges(preview.document.children)).toEqual([+ {+ type: "element",+ syntax: "markdown",+ tag: "h1",+ props: [],+ children: [{ type: "text", value: "Heading" }],+ },+ {+ type: "element",+ syntax: "markdown",+ tag: "p",+ props: [],+ children: [+ { type: "text", value: "Before " },+ {+ type: "element",+ syntax: "mdx",+ tag: "span",+ props: [{ name: "class", value: "accent" }],+ children: [{ type: "text", value: "inline" }],+ mdxMode: "text",+ },+ { type: "text", value: " after." },+ ],+ },+ {+ type: "element",+ syntax: "mdx",+ tag: "figure",+ props: [{ name: "data-kind", value: "hero" }],+ children: [+ {+ type: "element",+ syntax: "mdx",+ tag: "img",+ props: [+ { name: "src", value: "./hero.png" },+ { name: "alt", value: "Hero" },+ ],+ children: [],+ mdxMode: "flow",+ },+ ],+ mdxMode: "flow",+ },+ ]);+ expect(+ omitSourceRanges(await parseMdxDocument({ source: preview.source }))+ ).toEqual(omitSourceRanges(preview.document));+ expect(source).toContain('<span class="accent">');+ });++ test("rejects source-level errors that cannot be isolated", async () => {+ await expect(+ previewMarkdownToMdxConversion({+ source: "too large",+ maximumBytes: 1,+ })+ ).rejects.toMatchObject({+ code: "invalid-mdx",+ message: "MDX content exceeds the byte limit",+ } satisfies Partial<MdxDocumentError>);+ });++ test("keeps embedded HTML inline inside GFM table cells", async () => {+ const preview = await previewMarkdownToMdxConversion({+ source: "| Value |\n| --- |\n| <span>Cell</span> |\n",+ });++ expect(preview.source).toBe(`| Value |+| ------------------------------------------- |+| <ws.element ws:tag="span">Cell</ws.element> |+`);+ });++ test("repairs malformed embedded HTML with the HTML parser", async () => {+ const preview = await previewMarkdownToMdxConversion({+ source: "<section><strong>Kept</section>\n\nAfter\n",+ });++ expect(preview.source).toBe(`<ws.element ws:tag="section">+ <ws.element ws:tag="strong">+ Kept+ </ws.element>+</ws.element>++<ws.element ws:tag="strong">+ After+</ws.element>+`);+ expect(preview.omissions).toEqual([]);+ });++ test("omits isolatable unsafe HTML subtrees and reports their locations", async () => {+ const source = `---+title: Existing post+---+# Kept++<script>alert(1)</script>++Before <span onclick="alert(1)">omitted</span> after.++<footer>Also kept</footer>+`;++ const preview = await previewMarkdownToMdxConversion({ source });++ expect(preview.document.frontmatter.properties).toEqual({+ title: "Existing post",+ });+ expect(omitSourceRanges(preview.document.children)).toEqual([+ {+ type: "element",+ syntax: "markdown",+ tag: "h1",+ props: [],+ children: [{ type: "text", value: "Kept" }],+ },+ {+ type: "element",+ syntax: "markdown",+ tag: "p",+ props: [],+ children: [+ { type: "text", value: "Before " },+ {+ type: "element",+ syntax: "mdx",+ tag: "span",+ props: [],+ children: [{ type: "text", value: "omitted" }],+ mdxMode: "text",+ },+ { type: "text", value: " after." },+ ],+ },+ {+ type: "element",+ syntax: "mdx",+ tag: "footer",+ props: [],+ children: [+ {+ type: "element",+ syntax: "markdown",+ tag: "p",+ props: [],+ children: [{ type: "text", value: "Also kept" }],+ },+ ],+ mdxMode: "flow",+ },+ ]);+ expect(preview.omissions).toEqual([+ {+ nodeType: "element",+ reason: "Webstudio element tag script is not supported",+ sourceRange: {+ start: { line: 6, column: 1, offset: 37 },+ end: { line: 6, column: 26, offset: 62 },+ },+ },+ {+ nodeType: "element",+ reason: "MDX JSX prop onclick is not supported",+ sourceRange: {+ start: { line: 8, column: 8, offset: 71 },+ end: { line: 8, column: 47, offset: 110 },+ },+ },+ ]);+ expect(+ omitSourceRanges(await parseMdxDocument({ source: preview.source }))+ ).toEqual(omitSourceRanges(preview.document));+ });++ test("preserves Markdown link and image nodes after omitting unsafe destinations", async () => {+ const preview = await previewMarkdownToMdxConversion({+ source:+ "[Unsafe link](javascript:alert(1))\n\n\n",+ });++ expect(omitSourceRanges(preview.document.children)).toEqual([+ {+ type: "element",+ syntax: "mdx",+ tag: "p",+ props: [],+ children: [+ {+ type: "element",+ syntax: "mdx",+ tag: "a",+ props: [],+ children: [{ type: "text", value: "Unsafe link" }],+ mdxMode: "text",+ },+ ],+ mdxMode: "flow",+ },+ {+ type: "element",+ syntax: "mdx",+ tag: "p",+ props: [],+ children: [+ {+ type: "element",+ syntax: "mdx",+ tag: "img",+ props: [{ name: "alt", value: "Unsafe image" }],+ children: [],+ mdxMode: "flow",+ },+ ],+ mdxMode: "flow",+ },+ ]);+ expect(preview.omissions.map(({ reason }) => reason)).toEqual([+ "MDX JSX prop href contains an unsafe URL",+ "MDX JSX prop src contains an unsafe URL",+ ]);+ });++ test("reports an omitted subtree once without nested property omissions", async () => {+ const preview = await previewMarkdownToMdxConversion({+ source: '<script onclick="alert(1)">unsafe</script>\n',+ });++ expect(preview.omissions.map(({ reason }) => reason)).toEqual([+ "Webstudio element tag script is not supported",+ ]);+ });+});diff --git a/packages/content-engine/src/mdx.ts b/packages/content-engine/src/mdx.tsnew file mode 100644index 0000000000..865a2ae341--- /dev/null+++ b/packages/content-engine/src/mdx.ts@@ -0,0 +1,952 @@+import {+ defaultHandlers,+ toHast,+ type Handler,+ type Handlers,+} from "mdast-util-to-hast";+import {+ discoverAssetValueReferences,+ type AssetValueReference,+} from "./asset-value-references";+import { createAssetReferenceResolver } from "./asset-reference-utils";+import { getUtf8ByteLength } from "./byte-stream";+import { extractMarkdownFrontmatter } from "./frontmatter";+import { contentEngineLimits } from "./limits";+import {+ getSyntaxTreeChildren,+ isSyntaxTreeNode,+ parseMarkdownAst,+ type SyntaxTreeNode,+} from "./markdown-ast";++export type MdxSourcePoint = Readonly<{+ line: number;+ column: number;+ offset?: number;+}>;++export type MdxSourceRange = Readonly<{+ start: MdxSourcePoint;+ end: MdxSourcePoint;+}>;++export type MdxAuthoredProp = Readonly<{+ name: string;+ value: string | true;+}>;++export type MdxMode = "flow" | "text";++export type MdxMarkdownListItem = Readonly<{+ checked?: boolean;+ spread: boolean;+}>;++export type MdxAuthoredNode =+ | Readonly<{+ type: "text";+ value: string;+ sourceRange?: MdxSourceRange;+ }>+ | Readonly<{+ type: "comment";+ value: string;+ mdxMode: MdxMode;+ sourceRange?: MdxSourceRange;+ }>+ | Readonly<{+ type: "element";+ syntax: "markdown";+ tag: string;+ props: readonly MdxAuthoredProp[];+ children: readonly MdxAuthoredNode[];+ markdownListItem?: MdxMarkdownListItem;+ preserveTextWhitespace?: true;+ sourceRange?: MdxSourceRange;+ }>+ | Readonly<{+ type: "element";+ syntax: "mdx";+ tag: string;+ props: readonly MdxAuthoredProp[];+ children: readonly MdxAuthoredNode[];+ mdxMode: MdxMode;+ sourceRange?: MdxSourceRange;+ }>+ | Readonly<{+ type: "template";+ name: string;+ props: readonly MdxAuthoredProp[];+ children: readonly MdxAuthoredNode[];+ mdxMode: MdxMode;+ sourceRange?: MdxSourceRange;+ }>;++export type MdxDocument = Readonly<{+ frontmatter: Readonly<{+ properties: Readonly<Record<string, unknown>>;+ sourceRange?: MdxSourceRange;+ }>;+ children: readonly MdxAuthoredNode[];+}>;++export type MdxDocumentErrorCode = "invalid-mdx" | "unsafe-mdx";++export class MdxDocumentError extends Error {+ readonly code: MdxDocumentErrorCode;+ readonly nodeType?: string;+ readonly reason?: string;+ readonly sourceRange?: MdxSourceRange;++ constructor({+ code,+ message,+ nodeType,+ reason,+ sourceRange,+ cause,+ }: {+ code: MdxDocumentErrorCode;+ message: string;+ nodeType?: string;+ reason?: string;+ sourceRange?: MdxSourceRange;+ cause?: unknown;+ }) {+ super(message, { cause });+ this.name = "MdxDocumentError";+ this.code = code;+ this.nodeType = nodeType;+ this.reason = reason;+ this.sourceRange = sourceRange;+ }+}++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === "object" && value !== null;++const toSourcePoint = (value: unknown): MdxSourcePoint | undefined => {+ if (+ isRecord(value) === false ||+ typeof value.line !== "number" ||+ typeof value.column !== "number" ||+ Number.isInteger(value.line) === false ||+ Number.isInteger(value.column) === false ||+ value.line < 1 ||+ value.column < 1+ ) {+ return;+ }+ const point: { line: number; column: number; offset?: number } = {+ line: value.line,+ column: value.column,+ };+ if (+ typeof value.offset === "number" &&+ Number.isInteger(value.offset) &&+ value.offset >= 0+ ) {+ point.offset = value.offset;+ }+ return point;+};++const toSourceRange = (position: unknown): MdxSourceRange | undefined => {+ if (isRecord(position) === false) {+ return;+ }+ const start = toSourcePoint(position.start);+ const end = toSourcePoint(position.end);+ if (start !== undefined && end !== undefined) {+ return { start, end };+ }+};++const getParserErrorSourceRange = (error: unknown) => {+ if (isRecord(error) === false) {+ return;+ }+ const sourceRange = toSourceRange(error.position);+ if (sourceRange !== undefined) {+ return sourceRange;+ }+ if (typeof error.name !== "string") {+ return;+ }+ const [lineSource, columnSource] = error.name.split(":", 2);+ const line = Number(lineSource);+ const column = Number(columnSource);+ if (+ Number.isInteger(line) === false ||+ Number.isInteger(column) === false ||+ line < 1 ||+ column < 1+ ) {+ return;+ }+ const point = { line, column };+ return { start: point, end: point };+};++const getErrorMessage = (error: unknown) =>+ error instanceof Error ? error.message : String(error);++const throwUnsafeNode = (+ node: SyntaxTreeNode,+ reason: string,+ fallbackNode?: SyntaxTreeNode+): never => {+ throw new MdxDocumentError({+ code: "unsafe-mdx",+ message: reason,+ nodeType: node.type,+ reason,+ sourceRange:+ toSourceRange(node.position) ?? toSourceRange(fallbackNode?.position),+ });+};++const unsupportedElementTags = new Set([+ "base",+ "link",+ "meta",+ "noscript",+ "script",+ "style",+ "template",+ "title",+]);++const urlPropNames = new Set([+ "action",+ "cite",+ "data",+ "formaction",+ "href",+ "poster",+ "src",+ "xlink:href",+ "xlinkhref",+]);++const isSafeStaticUrl = (value: string, propName: string) => {+ let url: URL;+ try {+ url = new URL(value, "https://webstudio.invalid");+ } catch {+ return false;+ }+ if (url.protocol === "http:" || url.protocol === "https:") {+ return true;+ }+ return (+ propName === "href" &&+ (url.protocol === "mailto:" || url.protocol === "tel:")+ );+};++const validateStaticProp = (node: SyntaxTreeNode, prop: MdxAuthoredProp) => {+ const normalizedName = prop.name.toLowerCase();+ if (+ normalizedName.startsWith("on") ||+ normalizedName === "srcdoc" ||+ normalizedName === "dangerouslysetinnerhtml" ||+ normalizedName === "srcset"+ ) {+ throwUnsafeNode(node, `MDX JSX prop ${prop.name} is not supported`);+ }+ if (+ urlPropNames.has(normalizedName) &&+ typeof prop.value === "string" &&+ isSafeStaticUrl(prop.value, normalizedName) === false+ ) {+ throwUnsafeNode(node, `MDX JSX prop ${prop.name} contains an unsafe URL`);+ }+};++const validateAstLimits = (root: SyntaxTreeNode) => {+ const pending: Array<{ node: SyntaxTreeNode; depth: number }> = [+ { node: root, depth: 0 },+ ];+ let nodeCount = 0;+ let propCount = 0;+ while (pending.length > 0) {+ const current = pending.pop();+ if (current === undefined) {+ break;+ }+ nodeCount += 1;+ if (nodeCount > contentEngineLimits.mdxNodes) {+ throw new MdxDocumentError({+ code: "invalid-mdx",+ message: "MDX content exceeds the node limit",+ sourceRange: toSourceRange(current.node.position),+ });+ }+ if (current.depth > contentEngineLimits.mdxDepth) {+ throw new MdxDocumentError({+ code: "invalid-mdx",+ message: "MDX content exceeds the nesting limit",+ sourceRange: toSourceRange(current.node.position),+ });+ }+ if (Array.isArray(current.node.attributes)) {+ propCount += current.node.attributes.length;+ if (propCount > contentEngineLimits.mdxProps) {+ throw new MdxDocumentError({+ code: "invalid-mdx",+ message: "MDX content exceeds the prop limit",+ sourceRange: toSourceRange(current.node.position),+ });+ }+ }+ for (const child of getSyntaxTreeChildren(current.node)) {+ pending.push({ node: child, depth: current.depth + 1 });+ }+ }+};++const createElement = ({+ node,+ tag,+ props = [],+ children,+ mdxMode,+ markdownListItem,+ preserveTextWhitespace,+}: {+ node: SyntaxTreeNode;+ tag: string;+ props?: readonly MdxAuthoredProp[];+ children: readonly MdxAuthoredNode[];+ mdxMode?: MdxMode;+ markdownListItem?: MdxMarkdownListItem;+ preserveTextWhitespace?: true;+}): MdxAuthoredNode => {+ const sourceRange = toSourceRange(node.position);+ if (mdxMode !== undefined) {+ return {+ type: "element",+ syntax: "mdx",+ tag,+ props,+ children,+ mdxMode,+ sourceRange,+ };+ }+ return {+ type: "element",+ syntax: "markdown",+ tag,+ props,+ children,+ ...(markdownListItem === undefined ? {} : { markdownListItem }),+ ...(preserveTextWhitespace === undefined ? {} : { preserveTextWhitespace }),+ sourceRange,+ };+};++const getMdxMode = (node: SyntaxTreeNode): MdxMode =>+ node.type === "mdxJsxTextElement" || node.type === "mdxTextExpression"+ ? "text"+ : "flow";++const setHastData = (node: SyntaxTreeNode, data: Record<string, unknown>) => {+ node.data = { ...(isRecord(node.data) ? node.data : {}), ...data };+};++const isCommentExpression = (node: SyntaxTreeNode) => {+ if (isRecord(node.data) === false || isRecord(node.data.estree) === false) {+ return false;+ }+ const { body, comments } = node.data.estree;+ return (+ Array.isArray(body) &&+ body.length === 0 &&+ Array.isArray(comments) &&+ comments.length > 0+ );+};++const mapStaticProps = (node: SyntaxTreeNode) => {+ if (Array.isArray(node.attributes) === false) {+ return [];+ }+ const props: MdxAuthoredProp[] = [];+ const names = new Set<string>();+ for (const attribute of node.attributes) {+ if (isSyntaxTreeNode(attribute) === false) {+ throwUnsafeNode(node, "MDX JSX contains an invalid attribute");+ }+ if (attribute.type === "mdxJsxExpressionAttribute") {+ throwUnsafeNode(+ attribute,+ "MDX JSX attribute spreads are not supported",+ node+ );+ }+ if (+ attribute.type !== "mdxJsxAttribute" ||+ typeof attribute.name !== "string"+ ) {+ throwUnsafeNode(+ attribute,+ "MDX JSX contains an unsupported attribute",+ node+ );+ }+ if (names.has(attribute.name)) {+ throwUnsafeNode(attribute, "MDX JSX attributes must be unique", node);+ }+ names.add(attribute.name);+ if (isRecord(attribute.value)) {+ throwUnsafeNode(+ attribute.value.type === "mdxJsxAttributeValueExpression"+ ? (attribute.value as SyntaxTreeNode)+ : attribute,+ "MDX JSX attribute expressions are not supported",+ node+ );+ }+ if (attribute.value !== null && typeof attribute.value !== "string") {+ throwUnsafeNode(+ attribute,+ "MDX JSX attribute values must be static",+ node+ );+ }+ props.push({+ name: attribute.name,+ value: attribute.value === null ? true : attribute.value,+ });+ }+ return props;+};++const mapMdxExpression: Handler = (state, value) => {+ const node = value as SyntaxTreeNode;+ if (isCommentExpression(node) && typeof node.value === "string") {+ const comment = {+ type: "comment",+ value: node.value,+ data: { mdxMode: getMdxMode(node) },+ } as const;+ state.patch(value, comment);+ return comment;+ }+ return throwUnsafeNode(node, "Executable MDX expressions are not supported");+};++const mapMdxJsxElement: Handler = (state, value) => {+ const node = value as SyntaxTreeNode;+ if (node.name !== "ws.element") {+ return throwUnsafeNode(+ node,+ "Only the ws.element component is supported in authored MDX"+ );+ }+ const properties = Object.fromEntries(+ mapStaticProps(node).map((prop) => [prop.name, prop.value])+ );+ const result = state(value, "ws.element", properties, state.all(value));+ if (isSyntaxTreeNode(result)) {+ setHastData(result, { mdxMode: getMdxMode(node) });+ }+ return result;+};++const mapListItem: Handler = (state, value, parent) => {+ const node = value as SyntaxTreeNode;+ const result = defaultHandlers.listItem(state, value, parent);+ if (isSyntaxTreeNode(result)) {+ setHastData(result, {+ markdownListItem: {+ ...(typeof node.checked === "boolean" ? { checked: node.checked } : {}),+ spread:+ node.spread === true ||+ (isSyntaxTreeNode(parent) && parent.spread === true),+ },+ });+ }+ return result;+};++const preserveWhitespace =+ (handler: Handler): Handler =>+ (state, value, parent) => {+ const result = handler(state, value, parent);+ if (isSyntaxTreeNode(result)) {+ setHastData(result, { preserveTextWhitespace: true });+ }+ return result;+ };++const mapParagraph: Handler = (state, value) => {+ const children = getSyntaxTreeChildren(value as SyntaxTreeNode);+ if (children.length === 1 && children[0].type === "mdxJsxTextElement") {+ return state.one(value.children[0], value);+ }+ return defaultHandlers.paragraph(state, value);+};++const rejectUnsupportedNode: Handler = (_state, value) => {+ const node = value as SyntaxTreeNode;+ return throwUnsafeNode(node, `MDX node type ${node.type} is not supported`);+};++const mdxHandlers: Handlers = {+ code: preserveWhitespace(defaultHandlers.code),+ html: rejectUnsupportedNode,+ inlineCode: preserveWhitespace(defaultHandlers.inlineCode),+ mdxFlowExpression: mapMdxExpression,+ mdxJsxFlowElement: mapMdxJsxElement,+ mdxJsxTextElement: mapMdxJsxElement,+ mdxTextExpression: mapMdxExpression,+ mdxjsEsm: rejectUnsupportedNode,+ listItem: mapListItem,+ paragraph: mapParagraph,+};++const createMarkdownHastForMdx = (root: SyntaxTreeNode) => {+ const hast = toHast(root as Parameters<typeof toHast>[0], {+ allowDangerousHtml: true,+ handlers: {+ code: mdxHandlers.code,+ inlineCode: mdxHandlers.inlineCode,+ listItem: mdxHandlers.listItem,+ },+ unknownHandler: rejectUnsupportedNode,+ });+ if (isSyntaxTreeNode(hast) === false) {+ return throwUnsafeNode(root, "Markdown did not produce an HTML document");+ }+ return hast;+};++const findHastMdxMode = (node: SyntaxTreeNode): MdxMode | undefined => {+ if (+ isRecord(node.data) &&+ (node.data.mdxMode === "flow" || node.data.mdxMode === "text")+ ) {+ return node.data.mdxMode;+ }+};++type MapHastOptions = {+ shouldOmitUnsafePart?: (error: MdxDocumentError) => boolean;+};++const canOmitUnsafePart = (error: unknown, options: MapHastOptions) =>+ error instanceof MdxDocumentError &&+ error.code === "unsafe-mdx" &&+ options.shouldOmitUnsafePart?.(error) === true;++const mapHastProperties = (node: SyntaxTreeNode, options: MapHastOptions) => {+ if (node.properties === undefined) {+ return { props: [], requiresMdxFallback: false };+ }+ if (isRecord(node.properties) === false) {+ return throwUnsafeNode(node, "HTML properties must be an object");+ }+ const props: MdxAuthoredProp[] = [];+ const propertyNames = new Set<string>();+ let requiresMdxFallback = false;+ for (const [propertyName, value] of Object.entries(node.properties)) {+ try {+ if (value === undefined || value === null || value === false) {+ continue;+ }+ let propValue: MdxAuthoredProp["value"];+ if (value === true) {+ propValue = true;+ } else if (typeof value === "string" || typeof value === "number") {+ propValue = String(value);+ } else if (+ Array.isArray(value) &&+ value.every(+ (item) => typeof item === "string" || typeof item === "number"+ )+ ) {+ propValue = value.join(" ");+ } else {+ return throwUnsafeNode(+ node,+ `HTML property ${propertyName} is invalid`+ );+ }+ const name = propertyName === "className" ? "class" : propertyName;+ if (propertyNames.has(name)) {+ return throwUnsafeNode(node, "HTML properties must be unique");+ }+ const prop: MdxAuthoredProp = { name, value: propValue };+ validateStaticProp(node, prop);+ propertyNames.add(name);+ props.push(prop);+ } catch (error) {+ if (canOmitUnsafePart(error, options)) {+ requiresMdxFallback ||=+ (node.tagName === "a" && propertyName === "href") ||+ (node.tagName === "img" && propertyName === "src");+ continue;+ }+ throw error;+ }+ }+ return { props, requiresMdxFallback };+};++const mapHastChildren = (+ node: SyntaxTreeNode,+ options: MapHastOptions = {}+): MdxAuthoredNode[] => {+ const children: MdxAuthoredNode[] = [];+ for (const child of getSyntaxTreeChildren(node)) {+ if (+ child.position === undefined &&+ child.type === "text" &&+ child.value === "\n"+ ) {+ continue;+ }+ try {+ children.push(mapHastNode(child, options));+ } catch (error) {+ if (canOmitUnsafePart(error, options)) {+ continue;+ }+ throw error;+ }+ }+ return children;+};++const getHastMdxMode = (node: SyntaxTreeNode) => {+ const mode = findHastMdxMode(node);+ if (mode !== undefined) {+ return mode;+ }+ return throwUnsafeNode(node, "MDX node mode is missing");+};++const getMarkdownListItem = (+ node: SyntaxTreeNode+): MdxMarkdownListItem | undefined => {+ if (isRecord(node.data) === false) {+ return;+ }+ const value = node.data.markdownListItem;+ if (+ isRecord(value) === false ||+ typeof value.spread !== "boolean" ||+ (value.checked !== undefined && typeof value.checked !== "boolean")+ ) {+ return;+ }+ return {+ ...(typeof value.checked === "boolean" ? { checked: value.checked } : {}),+ spread: value.spread,+ };+};++const preservesTextWhitespace = (node: SyntaxTreeNode) =>+ isRecord(node.data) && node.data.preserveTextWhitespace === true+ ? true+ : undefined;++const mapWebstudioElement = (+ node: SyntaxTreeNode,+ props: readonly MdxAuthoredProp[],+ options: MapHastOptions+): MdxAuthoredNode => {+ const nameProp = props.find((prop) => prop.name === "ws:name");+ const tagProp = props.find((prop) => prop.name === "ws:tag");+ if (nameProp !== undefined && tagProp !== undefined) {+ return throwUnsafeNode(node, "ws:name and ws:tag cannot be used together");+ }+ if (nameProp !== undefined) {+ if (typeof nameProp.value !== "string" || nameProp.value.length === 0) {+ return throwUnsafeNode(node, "ws:name must be a non-empty static string");+ }+ return {+ type: "template",+ name: nameProp.value,+ props: props.filter((prop) => prop.name !== "ws:name"),+ children: mapHastChildren(node, options),+ mdxMode: getHastMdxMode(node),+ sourceRange: toSourceRange(node.position),+ };+ }++ let tag = "div";+ if (tagProp !== undefined) {+ if (typeof tagProp.value !== "string" || tagProp.value.length === 0) {+ return throwUnsafeNode(node, "ws:tag must be a non-empty static string");+ }+ tag = tagProp.value;+ }+ if (unsupportedElementTags.has(tag.toLowerCase())) {+ return throwUnsafeNode(+ node,+ `Webstudio element tag ${tag} is not supported`+ );+ }+ return createElement({+ node,+ tag,+ props: props.filter((prop) => prop.name !== "ws:tag"),+ children: mapHastChildren(node, options),+ mdxMode: getHastMdxMode(node),+ });+};++const mapHastNode = (+ node: SyntaxTreeNode,+ options: MapHastOptions+): MdxAuthoredNode => {+ if (node.type === "text") {+ if (typeof node.value !== "string") {+ return throwUnsafeNode(node, "HTML text must contain a string value");+ }+ return {+ type: "text",+ value: node.value,+ sourceRange: toSourceRange(node.position),+ };+ }+ if (node.type === "comment") {+ if (typeof node.value !== "string") {+ return throwUnsafeNode(node, "HTML comments must contain a string value");+ }+ return {+ type: "comment",+ value: node.value,+ mdxMode: getHastMdxMode(node),+ sourceRange: toSourceRange(node.position),+ };+ }+ if (node.type !== "element" || typeof node.tagName !== "string") {+ return throwUnsafeNode(+ node,+ `HTML node type ${node.type} is not supported`+ );+ }+ const authoredMdxMode = findHastMdxMode(node);+ if (+ node.tagName !== "ws.element" &&+ authoredMdxMode !== undefined &&+ unsupportedElementTags.has(node.tagName.toLowerCase())+ ) {+ return throwUnsafeNode(+ node,+ `Webstudio element tag ${node.tagName} is not supported`+ );+ }+ const { props, requiresMdxFallback } = mapHastProperties(node, options);+ if (node.tagName === "ws.element") {+ return mapWebstudioElement(node, props, options);+ }+ let mdxMode = authoredMdxMode ?? (requiresMdxFallback ? "text" : undefined);+ const children = mapHastChildren(node, options);+ const onlyChild = children.length === 1 ? children[0] : undefined;+ if (+ mdxMode === undefined &&+ node.tagName === "p" &&+ onlyChild !== undefined &&+ ((onlyChild.type === "element" &&+ onlyChild.syntax === "mdx" &&+ onlyChild.mdxMode === "text") ||+ (onlyChild.type === "template" && onlyChild.mdxMode === "text") ||+ (onlyChild.type === "comment" && onlyChild.mdxMode === "text"))+ ) {+ mdxMode = "flow";+ }+ return createElement({+ node,+ tag: node.tagName,+ props,+ children,+ mdxMode,+ markdownListItem: getMarkdownListItem(node),+ preserveTextWhitespace: preservesTextWhitespace(node),+ });+};++const mapAuthoredChildren = (root: SyntaxTreeNode) => {+ const hast = toHast(root as Parameters<typeof toHast>[0], {+ handlers: mdxHandlers,+ unknownHandler: rejectUnsupportedNode,+ });+ if (isSyntaxTreeNode(hast) === false || hast.type !== "root") {+ return throwUnsafeNode(root, "MDX did not produce an HTML document");+ }+ return mapHastChildren(hast);+};++const validateMdxSourceBytes = ({+ source,+ maximumBytes,+}: {+ source: string;+ maximumBytes: number;+}) => {+ if (+ Number.isInteger(maximumBytes) === false ||+ maximumBytes <= 0 ||+ maximumBytes > contentEngineLimits.hydratedFileBytes ||+ getUtf8ByteLength(source) > maximumBytes+ ) {+ throw new MdxDocumentError({+ code: "invalid-mdx",+ message: "MDX content exceeds the byte limit",+ });+ }+};++const parseMdxFrontmatter = async (+ root: SyntaxTreeNode,+ source: string+): Promise<MdxDocument["frontmatter"]> => {+ const frontmatterNode = getSyntaxTreeChildren(root).find(+ (node) => node.type === "yaml"+ );+ try {+ return {+ properties: (await extractMarkdownFrontmatter(source)).properties,+ sourceRange: toSourceRange(frontmatterNode?.position),+ };+ } catch (cause) {+ throw new MdxDocumentError({+ code: "invalid-mdx",+ message: getErrorMessage(cause),+ sourceRange: toSourceRange(frontmatterNode?.position),+ cause,+ });+ }+};++/** Converts bounded Markdown through a caller-supplied structural HAST transform. */+export const createMdxDocumentFromMarkdown = async ({+ source,+ maximumBytes = contentEngineLimits.hydratedFileBytes,+ transformHast,+ shouldOmitUnsafePart,+}: {+ source: string;+ maximumBytes?: number;+ transformHast: (input: {+ sourceRoot: SyntaxTreeNode;+ hastRoot: SyntaxTreeNode;+ }) => SyntaxTreeNode | Promise<SyntaxTreeNode>;+ shouldOmitUnsafePart?: (error: MdxDocumentError) => boolean;+}): Promise<MdxDocument> => {+ validateMdxSourceBytes({ source, maximumBytes });+ const sourceRoot = parseMarkdownAst(source);+ validateAstLimits(sourceRoot);+ const hastRoot = await transformHast({+ sourceRoot,+ hastRoot: createMarkdownHastForMdx(sourceRoot),+ });+ validateAstLimits(hastRoot);+ return {+ frontmatter: await parseMdxFrontmatter(sourceRoot, source),+ children: mapHastChildren(hastRoot, { shouldOmitUnsafePart }),+ };+};++export const discoverMdxBodyAssetReferences = ({+ document,+ sourcePath,+ assetIdsByPath,+}: {+ document: MdxDocument;+ sourcePath: string;+ assetIdsByPath: ReadonlyMap<string, string>;+}): AssetValueReference[] => {+ const references: AssetValueReference[] = [];+ const resolveAssetReference = createAssetReferenceResolver({+ sourcePath,+ assetIdsByPath,+ });+ const visit = (+ nodes: readonly MdxAuthoredNode[],+ parentPath: Array<string | number>+ ) => {+ for (const [nodeIndex, node] of nodes.entries()) {+ if (node.type === "text" || node.type === "comment") {+ continue;+ }+ const nodePath = [...parentPath, nodeIndex];+ for (const [propIndex, prop] of node.props.entries()) {+ if (+ typeof prop.value !== "string" ||+ urlPropNames.has(prop.name.toLowerCase()) === false+ ) {+ continue;+ }+ const reference = resolveAssetReference(prop.value);+ if (reference !== undefined) {+ references.push({+ path: [...nodePath, "props", propIndex, "value"],+ ...reference,+ });+ }+ }+ visit(node.children, [...nodePath, "children"]);+ }+ };+ visit(document.children, ["children"]);+ return references;+};++export const discoverMdxAssetReferences = ({+ document,+ sourcePath,+ assetIdsByPath,+}: {+ document: MdxDocument;+ sourcePath: string;+ assetIdsByPath: ReadonlyMap<string, string>;+}): AssetValueReference[] => [+ ...discoverAssetValueReferences({+ properties: document.frontmatter.properties,+ sourcePath,+ assetIdsByPath,+ rootPath: ["frontmatter", "properties"],+ }),+ ...discoverMdxBodyAssetReferences({+ document,+ sourcePath,+ assetIdsByPath,+ }),+];++export const parseMdxDocument = async ({+ source,+ maximumBytes = contentEngineLimits.hydratedFileBytes,+}: {+ source: string;+ maximumBytes?: number;+}): Promise<MdxDocument> => {+ validateMdxSourceBytes({ source, maximumBytes });++ let root: SyntaxTreeNode;+ try {+ root = parseMarkdownAst(source, "mdx");+ } catch (cause) {+ throw new MdxDocumentError({+ code: "invalid-mdx",+ message: getErrorMessage(cause),+ sourceRange: getParserErrorSourceRange(cause),+ cause,+ });+ }+ validateAstLimits(root);++ return {+ frontmatter: await parseMdxFrontmatter(root, source),+ children: mapAuthoredChildren(root),+ };+};++export { serializeMdxDocument } from "./mdx-serialization";diff --git a/packages/content-engine/src/structured-query.test.ts b/packages/content-engine/src/structured-query.test.tsindex b2cac43061..af9595c399 100644--- a/packages/content-engine/src/structured-query.test.ts+++ b/packages/content-engine/src/structured-query.test.ts@@ -8,6 +8,7 @@ import {executeAssetQuery,executeAssetQueries,getAssetQueryFieldValue,+ supportsAssetQueryContent,validateAssetQueryAgainstCatalog,} from "./structured-query";@@ -72,6 +73,25 @@ const documents = [}),];+test("supports referenced bodies for Markdown and MDX documents", () => {+ const content = { mode: "markdown-body-ref" } as const;+ expect(supportsAssetQueryContent({ document: documents[0], content })).toBe(+ true+ );+ expect(+ supportsAssetQueryContent({+ document: {+ ...documents[0],+ name: "alpha.mdx",+ path: "blog/alpha.mdx",+ extension: "mdx",+ mimeType: "text/mdx",+ },+ content,+ })+ ).toBe(true);+});+const catalog: BuilderAssetFieldCatalog = {format: "webstudio-builder-asset-field-catalog",version: 1,diff --git a/packages/content-engine/src/structured-query.ts b/packages/content-engine/src/structured-query.tsindex 748ffb97a5..741788098e 100644--- a/packages/content-engine/src/structured-query.ts+++ b/packages/content-engine/src/structured-query.ts@@ -33,6 +33,7 @@ import {hydrateAssetResourceResult,type AssetResourceContentReader,} from "./hydration";+import { getDocumentFormatByContentType } from "./document-graph/document-format";import { appendAssetFieldPath } from "./canonical";import { selectAssetDocumentFields, selectAssetProperties } from "./projection";import { getUtf8ByteLength } from "./byte-stream";@@ -313,10 +314,20 @@ export const supportsAssetQueryContent = ({}: {document: ContentDatabaseDocument;content: AssetResourceContentOptions;-}) =>- content.mode !== "markdown-body-ref" ||- document.mimeType === "text/markdown" ||- document.extension === "md";+}) => {+ if (content.mode !== "markdown-body-ref") {+ return true;+ }+ const format =+ document.mimeType === undefined+ ? undefined+ : getDocumentFormatByContentType(document.mimeType);+ if (format === "markdown" || format === "mdx") {+ return true;+ }+ // Preserve extension fallback for legacy documents with missing MIME metadata.+ return document.extension === "md" || document.extension === "mdx";+};const compareAssetQuerySortValues = (left: unknown, right: unknown) => {const leftMissing = left === undefined || left === null;diff --git a/packages/http-client/src/index.ts b/packages/http-client/src/index.tsindex 4efec8b74d..2ef52e8e72 100644--- a/packages/http-client/src/index.ts+++ b/packages/http-client/src/index.ts@@ -1312,6 +1312,35 @@ export const setTextContent = runtimeProjectMutation("set-text-content");export const updateTextTree = runtimeProjectMutation("update-text-tree");+export const inspectContentBlockSource =+ projectQueryInput<RuntimeOperationParams>("inspect-content-block-source");++export const connectContentBlockSource = runtimeProjectMutation(+ "connect-content-block-source"+);++export const switchContentBlockSource = runtimeProjectMutation(+ "switch-content-block-source"+);++export const disconnectContentBlockSource = runtimeProjectMutation(+ "disconnect-content-block-source"+);++export const recoverContentBlockSource = runtimeProjectMutation(+ "recover-content-block-source"+);++export const migrateContentBlockTemplateReferences = runtimeProjectMutation(+ "migrate-content-block-template-references"+);++export const editContentBlockSource = runtimeProjectMutation(+ "edit-content-block-source"+);++export const insertMdxText = runtimeProjectMutation("insert-mdx-text");+export const setInstanceTag = runtimeProjectMutation("set-instance-tag");export const setInstanceLabel = runtimeProjectMutation("set-instance-label");diff --git a/packages/project-build/package.json b/packages/project-build/package.jsonindex 8609491805..ce25fb8403 100644--- a/packages/project-build/package.json+++ b/packages/project-build/package.json@@ -67,6 +67,7 @@"dependencies": {"@emotion/hash": "^0.9.2","@modelcontextprotocol/sdk": "^1.10.0",+ "@webstudio-is/asset-uploader": "workspace:*","@webstudio-is/content-engine": "workspace:*","@webstudio-is/authorization-token": "workspace:*","@webstudio-is/css-data": "workspace:*",@@ -75,6 +76,7 @@"@webstudio-is/fonts": "workspace:*","@webstudio-is/html-data": "workspace:*","@webstudio-is/postgrest": "workspace:*",+ "@webstudio-is/protocol": "workspace:*","@webstudio-is/project": "workspace:*","@webstudio-is/project-migrations": "workspace:*","@webstudio-is/query-builder": "workspace:*",diff --git a/packages/project-build/src/build-integrity.test.ts b/packages/project-build/src/build-integrity.test.tsindex 50d2649715..fbd68d587b 100644--- a/packages/project-build/src/build-integrity.test.ts+++ b/packages/project-build/src/build-integrity.test.ts@@ -1,5 +1,12 @@import { describe, expect, test } from "vitest";-import type { DataSource, Prop, Resource } from "@webstudio-is/sdk";+import {+ blockComponent,+ type DataSource,+ type FileAsset,+ type Instance,+ type Prop,+ type Resource,+} from "@webstudio-is/sdk";import {assertBuildIntegrity,formatBuildIntegrityError,@@ -16,6 +23,55 @@ const resource: Resource = {};describe("getBuildIntegrityIssues", () => {+ test("reports invalid Content Block source references", () => {+ const block: Instance = {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [],+ };+ const source: Prop = {+ id: "source",+ instanceId: block.id,+ name: "src",+ type: "asset",+ value: "post",+ };+ const markdownAsset: FileAsset = {+ id: "post",+ projectId: "project",+ type: "file",+ name: "post_hash.md",+ filename: "post",+ format: "md",+ size: 1,+ meta: {},+ description: null,+ createdAt: "2026-08-14T00:00:00.000Z",+ };++ const issues = getBuildIntegrityIssues({+ dataSources: [],+ props: [source],+ resources: [],+ instances: [block],+ assets: [markdownAsset],+ });++ expect(issues).toEqual([+ {+ type: "incompatibleContentBlockSourceAsset",+ blockInstanceId: "block",+ propId: "source",+ assetId: "post",+ assetName: "post_hash.md",+ },+ ]);+ expect(formatBuildIntegrityIssue(issues[0])).toBe(+ 'Content Block source prop "source" references Asset "post" (post_hash.md), which is not an MDX file.'+ );+ });+test("reports resource variables referencing missing resources", () => {const dataSource: DataSource = {type: "resource",@@ -28,6 +84,7 @@ describe("getBuildIntegrityIssues", () => {dataSources: [dataSource],props: [],resources: [],+ instances: [],});expect(issues).toEqual([@@ -51,6 +108,7 @@ describe("getBuildIntegrityIssues", () => {dataSources: [dataSource],props: [],resources: [],+ instances: [],},{ messagePrefix: "Cannot publish" })@@ -72,6 +130,7 @@ describe("getBuildIntegrityIssues", () => {dataSources: [],props: [prop],resources: [],+ instances: [],});expect(issues).toEqual([@@ -108,6 +167,7 @@ describe("getBuildIntegrityIssues", () => {dataSources: [dataSource],props: [prop],resources: [resource],+ instances: [],})).toEqual([]);});diff --git a/packages/project-build/src/build-integrity.ts b/packages/project-build/src/build-integrity.tsindex d7b4ebc89b..97f86f7c57 100644--- a/packages/project-build/src/build-integrity.ts+++ b/packages/project-build/src/build-integrity.ts@@ -1,4 +1,13 @@-import type { DataSource, Prop, Resource } from "@webstudio-is/sdk";+import {+ formatContentBlockSourceIntegrityIssue,+ getContentBlockSourceIntegrityIssues,+ type Asset,+ type ContentBlockSourceIntegrityIssue,+ type DataSource,+ type Instance,+ type Prop,+ type Resource,+} from "@webstudio-is/sdk";export type BuildIntegrityIssue =| {@@ -14,18 +23,30 @@ export type BuildIntegrityIssue =propId: string;propName: string;resourceId: string;- };+ }+ | ContentBlockSourceIntegrityIssue;export const getBuildIntegrityIssues = ({dataSources,props,resources,+ instances = [],+ assets,}: {dataSources: Iterable<DataSource>;props: Iterable<Prop>;resources: Iterable<Resource>;+ instances?: Iterable<Instance>;+ assets?: Iterable<Asset>;}): BuildIntegrityIssue[] => {- const issues: BuildIntegrityIssue[] = [];+ const propsList = Array.from(props);+ const issues: BuildIntegrityIssue[] = [+ ...getContentBlockSourceIntegrityIssues({+ instances,+ props: propsList,+ assets,+ }),+ ];const resourceIds = new Set<string>();for (const resource of resources) {@@ -47,7 +68,7 @@ export const getBuildIntegrityIssues = ({}}- for (const prop of props) {+ for (const prop of propsList) {if (prop.type === "resource" && resourceIds.has(prop.value) === false) {issues.push({type: "missingResource",@@ -65,6 +86,9 @@ export const getBuildIntegrityIssues = ({export const formatBuildIntegrityIssue = (issue: BuildIntegrityIssue): string => {+ if (issue.type !== "missingResource") {+ return formatContentBlockSourceIntegrityIssue(issue);+ }if (issue.source === "dataSource") {return `resource variable "${issue.dataSourceName}" (${issue.dataSourceId}) references missing resource "${issue.resourceId}".`;}@@ -83,6 +107,8 @@ export const assertBuildIntegrity = (dataSources: Iterable<DataSource>;props: Iterable<Prop>;resources: Iterable<Resource>;+ instances?: Iterable<Instance>;+ assets?: Iterable<Asset>;},options: { messagePrefix?: string } = {}) => {@@ -94,3 +120,19 @@ export const assertBuildIntegrity = ();}};++export const assertContentBlockSourceIntegrity = (+ data: {+ instances: Iterable<Instance>;+ props: Iterable<Prop>;+ assets?: Iterable<Asset>;+ },+ options: { messagePrefix?: string } = {}+) => {+ const firstIssue = getContentBlockSourceIntegrityIssues(data)[0];+ if (firstIssue !== undefined) {+ throw new Error(+ formatBuildIntegrityError(firstIssue, options.messagePrefix)+ );+ }+};diff --git a/packages/project-build/src/content-database.test.ts b/packages/project-build/src/content-database.test.tsnew file mode 100644index 0000000000..a3b14413f8--- /dev/null+++ b/packages/project-build/src/content-database.test.ts@@ -0,0 +1,426 @@+import { describe, expect, test } from "vitest";+import type { ContentArtifactV1 } from "@webstudio-is/content-engine";+import {+ createStructuredAssetQueryResourceBody,+ encodeDataVariableId,+ type DataSource,+ type Instance,+ type Pages,+ type Prop,+ type Resource,+} from "@webstudio-is/sdk";+import {+ createBuildContentCompilationPlan,+ createPublishedBuildContentCompilationPlan,+ getDynamicPublishedMdxSourceBlockIds,+ getPublishedMdxContentDatabaseMaxBytes,+ resolvePublishedMdxAssetCandidates,+ resolvePublishedMdxDependencyClosure,+} from "./content-database";++const createBuild = ({+ component = "ws:block",+ sourceType = "asset",+}: {+ component?: string;+ sourceType?: "asset" | "expression" | "string";+}): {+ instances: Instance[];+ props: Prop[];+ dataSources: DataSource[];+ resources: Resource[];+ pages: Pages;+} => ({+ instances: [+ {+ type: "instance" as const,+ id: "block",+ component,+ children: [],+ },+ ],+ props: [+ {+ id: "source",+ instanceId: "block",+ name: "src",+ type: sourceType,+ value: sourceType === "expression" ? '"article.mdx"' : "article.mdx",+ },+ ],+ dataSources: [],+ resources: [],+ pages: {+ meta: {},+ homePageId: "home",+ rootFolderId: "root-folder",+ pages: new Map([+ [+ "home",+ {+ id: "home",+ path: "",+ name: "Home",+ title: "Home",+ rootInstanceId: "block",+ meta: {},+ },+ ],+ ]),+ folders: new Map(),+ },+});++describe("Content Block MDX compilation", () => {+ test("adds a separately bounded MDX body budget", () => {+ expect(+ getPublishedMdxContentDatabaseMaxBytes({+ baseBytes: 500,+ assets: [+ { type: "file", format: "mdx", size: 10_000_000 },+ { type: "file", format: "mdx", size: 30_000_000 },+ { type: "file", format: "md", size: 10_000_000 },+ ],+ })+ ).toBe(32 * 1024 * 1024 + 500);+ });+ test.each(["asset", "expression"] as const)(+ "retains the exact MDX dependency for a %s source",+ (sourceType) => {+ const plan = createPublishedBuildContentCompilationPlan(+ createBuild({ sourceType })+ );++ expect(plan?.queries).toContainEqual({+ id: "__content-block-mdx__:article.mdx",+ result: "many",+ where: {+ all: [+ {+ field: ["extension"],+ operator: "eq",+ value: { type: "literal", value: "mdx" },+ },+ {+ field: ["id"],+ operator: "eq",+ value: { type: "literal", value: "article.mdx" },+ },+ ],+ },+ sort: [],+ limit: { type: "dynamic" },+ offset: { type: "literal", value: 0 },+ output: {+ mode: "fields",+ includeMetadata: false,+ fields: [["url"], ["width"], ["height"]],+ },+ content: { mode: "full" },+ });+ }+ );++ test("does not retain MDX for unrelated src props", () => {+ expect(+ createPublishedBuildContentCompilationPlan(+ createBuild({ component: "ws:element" })+ )+ ).toBeUndefined();+ });++ test("does not retain MDX for an invalid Content Block source type", () => {+ expect(+ createPublishedBuildContentCompilationPlan(+ createBuild({ sourceType: "string" })+ )+ ).toBeUndefined();+ });++ test("does not retain conflicting duplicate Content Block sources", () => {+ const build = createBuild({});+ build.props.push({+ id: "duplicate-source",+ instanceId: "block",+ name: "src",+ type: "asset",+ value: "private.mdx",+ });++ expect(createPublishedBuildContentCompilationPlan(build)).toBeUndefined();+ expect(getDynamicPublishedMdxSourceBlockIds(build)).toEqual([]);+ expect(resolvePublishedMdxAssetCandidates({ build })).toEqual(new Map());+ });++ test("does not retain MDX used only by a draft page", () => {+ const build = createBuild({});+ build.instances.push({+ type: "instance",+ id: "draft-block",+ component: "ws:block",+ children: [],+ });+ build.props.push({+ id: "draft-source",+ instanceId: "draft-block",+ name: "src",+ type: "asset",+ value: "private-draft.mdx",+ });+ build.pages.pages.set("draft", {+ id: "draft",+ path: "draft",+ name: "Draft",+ title: "Draft",+ rootInstanceId: "draft-block",+ meta: {},+ isDraft: true,+ });++ const plan = createPublishedBuildContentCompilationPlan(build);++ expect(plan?.queries.map(({ id }) => id)).not.toContain(+ "__content-block-mdx__:private-draft.mdx"+ );+ });++ test("retains nested sources only through referenced templates", async () => {+ const build = createBuild({});+ build.instances[0].children = [{ type: "id", value: "templates" }];+ build.instances.push(+ {+ type: "instance",+ id: "templates",+ component: "ws:block-template",+ children: [+ { type: "id", value: "hero" },+ { type: "id", value: "unused" },+ ],+ },+ {+ type: "instance",+ id: "hero",+ component: "ws:element",+ tag: "section",+ label: "Hero",+ children: [{ type: "id", value: "nested" }],+ },+ {+ type: "instance",+ id: "nested",+ component: "ws:block",+ children: [],+ },+ {+ type: "instance",+ id: "unused",+ component: "ws:block",+ label: "Unused",+ children: [],+ }+ );+ build.props.push(+ {+ id: "nested-source",+ instanceId: "nested",+ name: "src",+ type: "asset",+ value: "nested.mdx",+ },+ {+ id: "unused-source",+ instanceId: "unused",+ name: "src",+ type: "asset",+ value: "private.mdx",+ }+ );+ const source = '<ws.element ws:name="Hero" />';+ const artifact = {+ format: "webstudio-content-database",+ version: 1,+ documents: [+ {+ _id: "article.mdx",+ _type: "asset.file",+ name: "article.mdx",+ path: "article.mdx",+ key: "article",+ extension: "mdx",+ mimeType: "text/mdx",+ size: source.length,+ revision: "article-revision",+ contentRef: "article.mdx",+ },+ ],+ contents: { "article.mdx": source },+ } as unknown as ContentArtifactV1;++ const plan = await resolvePublishedMdxDependencyClosure({+ build,+ artifact,+ });+ const queryIds = plan?.queries.map(({ id }) => id);++ expect(queryIds).toContain("__content-block-mdx__:nested.mdx");+ expect(queryIds).not.toContain("__content-block-mdx__:private.mdx");+ });++ test("keeps internal MDX retention out of Assets Resource plans", () => {+ expect(createBuildContentCompilationPlan(createBuild({}))).toBeUndefined();+ });++ test("rejects an expression without a bounded publication dependency set", () => {+ const build = createBuild({ sourceType: "expression" });+ build.props[0].value = "post.body";++ expect(() => createPublishedBuildContentCompilationPlan(build)).toThrow(+ "exact Asset dependencies cannot be determined safely"+ );+ });++ test.each(["detail", "collection"] as const)(+ "derives finite %s candidates while excluding unrelated MDX",+ (kind) => {+ const resourceVariable = encodeDataVariableId("posts-data");+ const itemVariable = encodeDataVariableId("collection-item");+ const build = createBuild({ sourceType: "expression" });+ build.instances.unshift({+ type: "instance",+ id: "collection",+ component: "ws:collection",+ children: [{ type: "id", value: "block" }],+ });+ build.props[0].value =+ kind === "detail"+ ? `${resourceVariable}.data.properties.mdx`+ : `${itemVariable}.properties.mdx`;+ if (kind === "collection") {+ build.props.push({+ id: "collection-data",+ instanceId: "collection",+ name: "data",+ type: "expression",+ value: `${resourceVariable}.data`,+ });+ build.props.push({+ id: "collection-item-prop",+ instanceId: "collection",+ name: "item",+ type: "parameter",+ value: "collection-item",+ });+ build.dataSources.push({+ type: "parameter",+ id: "collection-item",+ scopeInstanceId: "collection",+ name: "collectionItem",+ });+ }+ build.dataSources.push({+ type: "resource",+ id: "posts-data",+ scopeInstanceId: "collection",+ name: "posts",+ resourceId: "posts",+ });+ build.resources.push({+ id: "posts",+ name: "Posts",+ control: "system",+ method: "post",+ url: '"/$resources/assets"',+ headers: [],+ body: createStructuredAssetQueryResourceBody({+ where: {+ all: [+ {+ field: ["properties", "category"],+ operator: "eq",+ value: '"published"',+ },+ ],+ },+ sort: [],+ limit: "1",+ offset: "0",+ output: { mode: "all", includeMetadata: true },+ content: { mode: "none" },+ }),+ });+ const artifact = {+ documents: [+ {+ _id: "post",+ _type: "asset.file",+ name: "post.json",+ path: "post.json",+ key: "post",+ extension: "json",+ mimeType: "application/json",+ size: 1,+ properties: { category: "published", mdx: "article.mdx" },+ },+ {+ _id: "private-post",+ _type: "asset.file",+ name: "private.json",+ path: "private.json",+ key: "private",+ extension: "json",+ mimeType: "application/json",+ size: 1,+ properties: { category: "private", mdx: "private.mdx" },+ },+ {+ _id: "second-post",+ _type: "asset.file",+ name: "second.json",+ path: "second.json",+ key: "second",+ extension: "json",+ mimeType: "application/json",+ size: 1,+ properties: { category: "published", mdx: "second.mdx" },+ },+ ],+ } as unknown as ContentArtifactV1;++ const candidates = resolvePublishedMdxAssetCandidates({+ build,+ artifact,+ });+ const plan = createPublishedBuildContentCompilationPlan(+ build,+ candidates+ );++ expect(candidates.get("block")).toEqual(["article.mdx"]);+ expect(plan?.queries.map(({ id }) => id)).toContain(+ "__content-block-mdx__:article.mdx"+ );+ expect(plan?.queries.map(({ id }) => id)).not.toContain(+ "__content-block-mdx__:private.mdx"+ );+ expect(plan?.queries.map(({ id }) => id)).not.toContain(+ "__content-block-mdx__:second.mdx"+ );+ }+ );++ test("rejects a mutable project variable as an incomplete candidate set", () => {+ const build = createBuild({ sourceType: "expression" });+ build.props[0].value = encodeDataVariableId("article-source");+ build.dataSources.push({+ type: "variable",+ id: "article-source",+ scopeInstanceId: "block",+ name: "articleSource",+ value: { type: "string", value: "article.mdx" },+ });++ expect(() => resolvePublishedMdxAssetCandidates({ build })).toThrow(+ 'Content Block "block" has no finite dynamic MDX Asset candidates'+ );+ });+});diff --git a/packages/project-build/src/content-database.ts b/packages/project-build/src/content-database.tsindex cc67d0d778..5601121b84 100644--- a/packages/project-build/src/content-database.ts+++ b/packages/project-build/src/content-database.ts@@ -2,23 +2,109 @@ import {assetQuery,createContentDatabase,createContentCompilationPlan,+ createDocumentGraph,createLiteralContentCompilationQuery,+ getDocumentGraphQueryRootIds,hasDynamicContentCompilationValues,type AssetQueryInput,type ContentCompilationPlan,type ContentArtifactV1,+ defaultAssetResourceOutputSelection,+ getAssetQueryFieldValue,+ selectContentHydrationCandidates,+ type AssetFileDocument,} from "@webstudio-is/content-engine";import {+ blockComponent,+ collectionComponent,createReachableAssetContentCompilationPlan,+ decodeDataSourceVariable,+ getContentBlockSource,+ getPublishablePages,+ blockTemplateComponent,type DataSource,+ type Instance,type Prop,type Resource,} from "@webstudio-is/sdk";-import type { Build, CompactBuild } from "./types";+import {+ parseJsonExpression,+ parseStaticMemberPath,+} from "@webstudio-is/expression";+import type { Pages } from "@webstudio-is/sdk";+import { parseMdxDocument } from "@webstudio-is/content-engine/mdx";+import { resolveMdxTemplates } from "./runtime/mdx-template-resolution";++type BuildValues<Value> =+ | readonly Value[]+ | readonly (readonly [string, Value])[];-type ContentDatabaseBuild =- | Pick<Build, "props" | "dataSources" | "resources">- | Pick<CompactBuild, "props" | "dataSources" | "resources">;+type ContentDatabaseBuild = {+ props: BuildValues<Prop>;+ dataSources: BuildValues<DataSource>;+ resources: BuildValues<Resource>;+};++type PublishedContentDatabaseBuild = ContentDatabaseBuild & {+ instances: BuildValues<Instance>;+ pages?: Pages;+};++const publishedMdxTotalBytes = 32 * 1024 * 1024;++export const getPublishedMdxContentDatabaseMaxBytes = ({+ baseBytes,+ assets,+}: {+ baseBytes: number;+ assets: readonly Readonly<{+ type: string;+ format: string;+ size: number;+ }>[];+}) =>+ baseBytes ++ Math.min(+ publishedMdxTotalBytes,+ assets+ .filter(({ type, format }) => type === "file" && format === "mdx")+ .reduce((total, { size }) => total + size, 0)+ );++const getPublishedInstanceIds = (build: PublishedContentDatabaseBuild) => {+ if (build.pages === undefined) {+ throw new Error("Published Content Block discovery requires page roots");+ }+ const instances = new Map(+ getBuildValues<Instance>(build.instances).map((instance) => [+ instance.id,+ instance,+ ])+ );+ const instanceIds = new Set<string>();+ const visit = (instanceId: string) => {+ if (instanceIds.has(instanceId)) {+ return;+ }+ instanceIds.add(instanceId);+ const instance = instances.get(instanceId);+ if (+ instance === undefined ||+ instance.component === blockTemplateComponent+ ) {+ return;+ }+ for (const child of instance.children) {+ if (child.type === "id") {+ visit(child.value);+ }+ }+ };+ for (const page of getPublishablePages(build.pages)) {+ visit(page.rootInstanceId);+ }+ return instanceIds;+};const getBuildValues = <Item>(values: readonly Item[] | readonly (readonly [string, Item])[]@@ -36,6 +122,466 @@ export const createBuildContentCompilationPlan = (resources: getBuildValues<Resource>(build.resources),});+const getPublishedContentBlockSources = (+ build: PublishedContentDatabaseBuild,+ publishedInstanceIds: ReadonlySet<string> = getPublishedInstanceIds(build)+) => {+ const props = getBuildValues<Prop>(build.props);+ const blockIds = new Set(+ getBuildValues<Instance>(build.instances).flatMap((instance) =>+ instance.component === blockComponent &&+ publishedInstanceIds.has(instance.id)+ ? [instance.id]+ : []+ )+ );+ const propsByBlock = new Map<string, Prop[]>();+ for (const prop of props) {+ if (blockIds.has(prop.instanceId)) {+ const blockProps = propsByBlock.get(prop.instanceId) ?? [];+ blockProps.push(prop);+ propsByBlock.set(prop.instanceId, blockProps);+ }+ }+ return Array.from(blockIds).flatMap((blockInstanceId) => {+ const source = getContentBlockSource({+ blockInstanceId,+ props: propsByBlock.get(blockInstanceId) ?? [],+ });+ return source === undefined ? [] : [{ blockInstanceId, source }];+ });+};++export const getDynamicPublishedMdxSourceBlockIds = (+ build: PublishedContentDatabaseBuild,+ publishedInstanceIds: ReadonlySet<string> = getPublishedInstanceIds(build)+) =>+ getPublishedContentBlockSources(build, publishedInstanceIds).flatMap(+ ({ blockInstanceId, source }) =>+ source.type === "expression" &&+ source.value.length > 0 &&+ typeof parseJsonExpression(source.value) !== "string"+ ? [blockInstanceId]+ : []+ );++export const hasDynamicPublishedMdxSources = (+ build: PublishedContentDatabaseBuild,+ publishedInstanceIds?: ReadonlySet<string>+) =>+ getDynamicPublishedMdxSourceBlockIds(build, publishedInstanceIds).length > 0;++export const createPublishedBuildContentCompilationPlan = (+ build: PublishedContentDatabaseBuild,+ dynamicAssetIdsByBlock: ReadonlyMap<string, readonly string[]> = new Map(),+ publishedInstanceIds: ReadonlySet<string> = getPublishedInstanceIds(build)+) => {+ const sources = getPublishedContentBlockSources(build, publishedInstanceIds);+ const directAssetIds = new Set(+ sources.flatMap(({ blockInstanceId, source }) => {+ if (source.type === "asset") {+ return source.assetId.length > 0 ? [source.assetId] : [];+ }+ const value = parseJsonExpression(source.value);+ if (typeof value === "string" && value.length > 0) {+ return [value];+ }+ return dynamicAssetIdsByBlock.get(blockInstanceId) ?? [];+ })+ );+ const dynamicSource = sources.find(+ ({ blockInstanceId, source }) =>+ source.type === "expression" &&+ source.value.length > 0 &&+ typeof parseJsonExpression(source.value) !== "string" &&+ dynamicAssetIdsByBlock.has(blockInstanceId) === false+ );+ if (dynamicSource !== undefined) {+ throw new Error(+ `Content Block "${dynamicSource.blockInstanceId}" uses a dynamic MDX source whose exact Asset dependencies cannot be determined safely for publication`+ );+ }+ const createMdxQuery = ({+ id,+ assetId,+ }: {+ id: string;+ assetId: string;+ }) => ({+ id,+ result: "many" as const,+ where: {+ all: [+ {+ field: ["extension"],+ operator: "eq" as const,+ value: { type: "literal" as const, value: "mdx" },+ },+ {+ field: ["id"],+ operator: "eq" as const,+ value: { type: "literal" as const, value: assetId },+ },+ ],+ },+ sort: [],+ // Keep content in the revisioned runtime artifact instead of folding it+ // into a materialized query result that the page compiler cannot consume.+ limit: { type: "dynamic" as const },+ offset: { type: "literal" as const, value: 0 },+ output: defaultAssetResourceOutputSelection,+ content: { mode: "full" as const },+ });+ return createContentCompilationPlan([+ ...(createBuildContentCompilationPlan(build)?.queries ?? []),+ ...Array.from(directAssetIds)+ .sort()+ .map((assetId) =>+ createMdxQuery({+ id: `__content-block-mdx__:${assetId}`,+ assetId,+ })+ ),+ ]);+};++/** Expands publication reachability through only the templates referenced by MDX. */+export const resolvePublishedMdxDependencyClosure = async ({+ build,+ artifact,+}: {+ build: PublishedContentDatabaseBuild;+ artifact: ContentArtifactV1;+}) => {+ const instances = new Map(+ getBuildValues<Instance>(build.instances).map((instance) => [+ instance.id,+ instance,+ ])+ );+ const props = getBuildValues<Prop>(build.props);+ const reachableIds = getPublishedInstanceIds(build);+ const pending = Array.from(reachableIds).filter(+ (id) => instances.get(id)?.component === blockComponent+ );+ const processed = new Set<string>();+ const visitTemplateSubtree = (instanceId: string) => {+ if (reachableIds.has(instanceId)) {+ return;+ }+ reachableIds.add(instanceId);+ const instance = instances.get(instanceId);+ if (+ instance === undefined ||+ instance.component === blockTemplateComponent+ ) {+ return;+ }+ if (instance.component === blockComponent) {+ pending.push(instance.id);+ }+ for (const child of instance.children) {+ if (child.type === "id") {+ visitTemplateSubtree(child.value);+ }+ }+ };++ while (pending.length > 0) {+ const blockId = pending.shift()!;+ if (processed.has(blockId)) {+ continue;+ }+ processed.add(blockId);+ const source = getContentBlockSource({ blockInstanceId: blockId, props });+ if (source === undefined) {+ continue;+ }+ const staticValue =+ source.type === "asset"+ ? source.assetId+ : parseJsonExpression(source.value);+ const assetIds =+ typeof staticValue === "string"+ ? [staticValue]+ : (resolvePublishedMdxAssetCandidates({+ build,+ artifact,+ blockInstanceIds: new Set([blockId]),+ }).get(blockId) ?? []);+ for (const assetId of assetIds) {+ const documentEntry = artifact.documents.find(+ ({ _id }) => _id === assetId+ );+ const sourceText =+ documentEntry?.contentRef === undefined+ ? undefined+ : artifact.contents?.[documentEntry.contentRef];+ if (+ documentEntry?.revision === undefined ||+ documentEntry.contentRef === undefined ||+ sourceText === undefined+ ) {+ continue;+ }+ const document = await parseMdxDocument({ source: sourceText });+ const resolution = resolveMdxTemplates({+ document,+ identity: {+ blockInstanceId: blockId,+ assetId,+ revision: documentEntry.revision,+ contentRef: documentEntry.contentRef,+ format: "mdx",+ renderScope: "publication-dependency-discovery",+ },+ instances,+ metas: new Map(),+ });+ for (const reference of resolution.references) {+ if (reference.type === "resolved-template") {+ visitTemplateSubtree(reference.templateInstanceId);+ }+ }+ }+ }+ const candidates = resolvePublishedMdxAssetCandidates({+ build,+ artifact,+ blockInstanceIds: reachableIds,+ });+ return createPublishedBuildContentCompilationPlan(+ build,+ candidates,+ reachableIds+ );+};++const candidateDocumentKey = Symbol("candidate-document");+type CandidateDocument = Readonly<{+ [candidateDocumentKey]: AssetFileDocument;+}>;++const isCandidateDocument = (value: unknown): value is CandidateDocument =>+ typeof value === "object" && value !== null && candidateDocumentKey in value;++const getValueAtPath = (+ value: unknown | CandidateDocument,+ path: readonly string[]+): unknown => {+ if (isCandidateDocument(value)) {+ return path.length === 0+ ? value[candidateDocumentKey]._id+ : getAssetQueryFieldValue(value[candidateDocumentKey], [...path]);+ }+ let current = value;+ for (const segment of path) {+ if (typeof current !== "object" || current === null) {+ return;+ }+ current = (current as Record<string, unknown>)[segment];+ }+ return current;+};++/** Resolves a finite dynamic src candidate set from compiled query records. */+export const resolvePublishedMdxAssetCandidates = ({+ build,+ artifact,+ allowUnresolved = false,+ blockInstanceIds = getPublishedInstanceIds(build),+}: {+ build: PublishedContentDatabaseBuild;+ artifact?: ContentArtifactV1;+ allowUnresolved?: boolean;+ blockInstanceIds?: ReadonlySet<string>;+}) => {+ const instances = new Map(+ getBuildValues<Instance>(build.instances).map((instance) => [+ instance.id,+ instance,+ ])+ );+ const props = getBuildValues<Prop>(build.props);+ const propsByInstance = new Map<string, Prop[]>();+ for (const prop of props) {+ const values = propsByInstance.get(prop.instanceId) ?? [];+ values.push(prop);+ propsByInstance.set(prop.instanceId, values);+ }+ const dataSources = new Map(+ getBuildValues<DataSource>(build.dataSources).map((dataSource) => [+ dataSource.id,+ dataSource,+ ])+ );+ const basePlan = createBuildContentCompilationPlan(build);+ const documents = (artifact?.documents ?? []).filter(+ (document): document is AssetFileDocument => document._type === "asset.file"+ );++ const evaluateDataSource = (+ dataSourceId: string,+ path: readonly string[],+ visiting = new Set<string>()+ ): unknown[] => {+ if (visiting.has(dataSourceId)) {+ throw new Error("Dynamic MDX source data dependency is cyclic");+ }+ const dataSource = dataSources.get(dataSourceId);+ if (dataSource === undefined) {+ return [];+ }+ if (dataSource.type === "variable") {+ // Project variables can be changed by actions after publication. Their+ // initial value is therefore not a complete dependency set.+ return [];+ }+ if (dataSource.type === "resource") {+ if (artifact === undefined) {+ return [];+ }+ const includedDocumentCount =+ artifact.database?.includedDocumentCount ?? artifact.documents.length;+ const sourceDocumentCount =+ artifact.database?.sourceDocumentCount ?? includedDocumentCount;+ if (includedDocumentCount < sourceDocumentCount) {+ throw new Error(+ "Dynamic MDX source candidates cannot be proven from a truncated content database"+ );+ }+ const query = basePlan?.queries.find(+ (candidate) => candidate.id === dataSource.resourceId+ );+ if (query === undefined || basePlan === undefined) {+ return [];+ }+ if (artifact.documentGraph !== undefined) {+ const graph = createDocumentGraph(artifact.documentGraph);+ if (getDocumentGraphQueryRootIds({ graph, query }).length > 0) {+ throw new Error(+ "Dynamic MDX source candidates through resolved document references are not supported safely for publication"+ );+ }+ }+ const candidateIds = selectContentHydrationCandidates({+ documents,+ plan: {+ ...basePlan,+ queries: [+ {+ ...query,+ content: { mode: "full" },+ },+ ],+ },+ });+ const fieldPath = path[0] === "data" ? path.slice(1) : path;+ return documents+ .filter(({ _id }) => candidateIds.has(_id))+ .map((document) =>+ fieldPath.length === 0+ ? ({+ [candidateDocumentKey]: document,+ } satisfies CandidateDocument)+ : getAssetQueryFieldValue(document, [...fieldPath])+ );+ }+ const collection = instances.get(dataSource.scopeInstanceId ?? "");+ if (collection?.component !== collectionComponent) {+ return [];+ }+ const dataProp = propsByInstance+ .get(collection.id)+ ?.find((prop) => prop.name === "data");+ const parameterProp = propsByInstance+ .get(collection.id)+ ?.find(+ (prop) => prop.type === "parameter" && prop.value === dataSource.id+ );+ if (parameterProp?.name !== "item" && parameterProp?.name !== "itemKey") {+ return [];+ }+ let iterables: unknown[] = [];+ if (dataProp?.type === "json") {+ iterables = [dataProp.value];+ } else if (dataProp?.type === "expression") {+ const dataPath = parseStaticMemberPath(dataProp.value);+ const dependencyId =+ dataPath === undefined+ ? undefined+ : decodeDataSourceVariable(dataPath[0]);+ if (dependencyId !== undefined && dataPath !== undefined) {+ visiting.add(dataSourceId);+ iterables = evaluateDataSource(+ dependencyId,+ dataPath.slice(1),+ visiting+ );+ visiting.delete(dataSourceId);+ }+ }+ const items = iterables.flatMap((iterable) => {+ if (Array.isArray(iterable)) {+ return parameterProp.name === "itemKey"+ ? iterable.map((_, index) => index)+ : iterable;+ }+ if (+ typeof iterable === "object" &&+ iterable !== null &&+ isCandidateDocument(iterable) === false+ ) {+ return parameterProp.name === "itemKey"+ ? Object.keys(iterable)+ : Object.values(iterable);+ }+ return [iterable];+ });+ return items.map((item) => getValueAtPath(item, path));+ };++ const candidatesByBlock = new Map<string, readonly string[]>();+ for (const blockInstanceId of blockInstanceIds) {+ if (instances.get(blockInstanceId)?.component !== blockComponent) {+ continue;+ }+ const source = getContentBlockSource({+ blockInstanceId,+ props: propsByInstance.get(blockInstanceId) ?? [],+ });+ if (+ source?.type !== "expression" ||+ typeof parseJsonExpression(source.value) === "string"+ ) {+ continue;+ }+ const path = parseStaticMemberPath(source.value);+ const dataSourceId =+ path === undefined ? undefined : decodeDataSourceVariable(path[0]);+ const assetIds =+ dataSourceId === undefined || path === undefined+ ? []+ : evaluateDataSource(dataSourceId, path.slice(1)).filter(+ (value): value is string =>+ typeof value === "string" && value.length > 0+ );+ if (assetIds.length === 0) {+ if (allowUnresolved) {+ continue;+ }+ throw new Error(+ `Content Block "${blockInstanceId}" has no finite dynamic MDX Asset candidates`+ );+ }+ candidatesByBlock.set(+ blockInstanceId,+ Array.from(new Set(assetIds)).sort()+ );+ }+ return candidatesByBlock;+};+export const createAssetQueryPreviewCompilationPlan = ({databasePlan,query,diff --git a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.tsindex ae84761994..8eb2ccf4f9 100644--- a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts+++ b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts@@ -3,1390 +3,10862 @@export const runtimeOperationContractData = [{- id: "pages.list",- command: "list-pages",- client: "listPages",+ id: "contentBlocks.inspectSource",+ command: "inspect-content-block-source",+ client: "inspectContentBlockSource",+ permit: "view",kind: "read",inputSchema: {type: "object",properties: {- cursor: {+ blockInstanceId: {type: "string",+ minLength: 1,},- limit: {- type: "integer",- minimum: 1,- maximum: 200,+ renderScope: {+ type: "string",+ minLength: 1,},- verbose: {- description:- "Expand the same result with complete records and diagnostics. Omit for compact output.",+ load: {type: "boolean",},- },- required: [],- },- outputSchema: {- type: "object",- properties: {- pages: {- type: "array",- items: {- type: "object",- properties: {- id: {- type: "string",- },- name: {- type: "string",- },- path: {- type: "string",- },- localPath: {- type: "string",- },- title: {- type: "string",- },- rootInstanceId: {- type: "string",- },- parentFolderId: {- type: "string",- },- isHome: {- type: "boolean",- },- isDraft: {- description:- "True when the page is a draft. Missing or false means the page is publishable.",- type: "boolean",- },- },- required: [- "id",- "name",- "path",- "localPath",- "title",- "rootInstanceId",- "isHome",- ],- additionalProperties: {},+ variables: {+ type: "object",+ propertyNames: {+ type: "string",+ minLength: 1,+ },+ additionalProperties: {+ $ref: "#/$defs/__schema0",},},- detail: {- type: "string",- enum: ["compact", "verbose"],- },- total: {- type: "integer",- minimum: 0,- maximum: 9007199254740991,- },- returnedCount: {- type: "integer",- minimum: 0,- maximum: 9007199254740991,- },- nextCursor: {+ },+ required: ["blockInstanceId", "renderScope"],+ $defs: {+ __schema0: {anyOf: [{type: "string",},+ {+ type: "number",+ },+ {+ type: "boolean",+ },{type: "null",},+ {+ type: "array",+ items: {+ $ref: "#/$defs/__schema0",+ },+ },+ {+ type: "object",+ propertyNames: {+ type: "string",+ },+ additionalProperties: {+ $ref: "#/$defs/__schema0",+ },+ },],},- filters: {- type: "object",- properties: {},- additionalProperties: {},- required: [],- },- },- required: [- "pages",- "detail",- "total",- "returnedCount",- "nextCursor",- "filters",- ],- additionalProperties: {},- },- readNamespaces: ["pages"],- writeNamespaces: [],- invalidatesNamespaces: [],- retryOnConflict: false,- },- {- id: "pages.get",- command: "get-page",- client: "getPage",- kind: "read",- inputSchema: {- type: "object",- properties: {- pageId: {- type: "string",- },},- required: ["pageId"],},outputSchema: {type: "object",properties: {- id: {- type: "string",- },- name: {- type: "string",- },- path: {- type: "string",- },- localPath: {- type: "string",- },- title: {- type: "string",- },- rootInstanceId: {+ blockInstanceId: {type: "string",},- parentFolderId: {+ renderScope: {type: "string",},- isHome: {- type: "boolean",- },- isDraft: {- description:- "True when the page is a draft. Missing or false means the page is publishable.",- type: "boolean",- },- meta: {- type: "object",- properties: {- description: {- type: "string",- },- language: {- type: "string",- },- redirect: {- type: "string",- },- status: {- type: "string",- },- socialImageUrl: {- type: "string",- },- socialImageAssetId: {- type: "string",- },- excludePageFromSearch: {- type: "boolean",- },- documentType: {- type: "string",- enum: ["html", "xml", "text"],- },- content: {- type: "string",- },- auth: {- anyOf: [- {- type: "object",- properties: {- method: {- type: "string",- const: "basic",- },- login: {- type: "string",- },- password: {- type: "string",- },- },- required: ["method", "login", "password"],+ configuredSource: {+ oneOf: [+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "asset",},- {- type: "object",- properties: {- type: {- type: "string",- const: "basic",- },- login: {- type: "string",- },- password: {- type: "string",- },- },- required: ["type", "login", "password"],+ assetId: {+ type: "string",+ minLength: 1,},- ],+ },+ required: ["type", "assetId"],+ additionalProperties: false,},- custom: {- type: "array",- items: {- type: "object",- properties: {- property: {- type: "string",- },- content: {- type: "string",- },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "expression",+ },+ value: {+ type: "string",+ minLength: 1,},- required: ["property", "content"],- additionalProperties: {},},+ required: ["type", "value"],+ additionalProperties: false,},- },- required: ["documentType"],- additionalProperties: {},- },- },- required: [- "id",- "name",- "path",- "localPath",- "title",- "rootInstanceId",- "isHome",- "meta",- ],- additionalProperties: {},- },- readNamespaces: ["pages", "instances"],- writeNamespaces: [],- invalidatesNamespaces: [],- retryOnConflict: false,- },- {- id: "pages.getByPath",- command: "get-page-by-path",- client: "getPageByPath",- kind: "read",- inputSchema: {- type: "object",- properties: {- path: {- type: "string",+ ],},- },- required: ["path"],- },- outputSchema: {- anyOf: [- {+ resolvedIdentity: {type: "object",properties: {- id: {- type: "string",- },- name: {+ blockInstanceId: {type: "string",+ minLength: 1,},- path: {+ assetId: {type: "string",+ minLength: 1,},- localPath: {+ revision: {type: "string",+ minLength: 1,},- title: {+ contentRef: {type: "string",+ minLength: 1,},- rootInstanceId: {+ format: {type: "string",+ const: "mdx",},- parentFolderId: {+ renderScope: {type: "string",+ minLength: 1,},- isHome: {- type: "boolean",- },- isDraft: {- description:- "True when the page is a draft. Missing or false means the page is publishable.",- type: "boolean",- },- meta: {- type: "object",- properties: {- description: {- type: "string",- },- language: {- type: "string",- },- redirect: {- type: "string",- },- status: {- type: "string",- },- socialImageUrl: {- type: "string",- },- socialImageAssetId: {- type: "string",- },- excludePageFromSearch: {- type: "boolean",- },- documentType: {- type: "string",- enum: ["html", "xml", "text"],- },- content: {- type: "string",- },- auth: {- anyOf: [- {- type: "object",- properties: {- method: {- type: "string",- const: "basic",- },- login: {- type: "string",- },- password: {- type: "string",+ },+ required: [+ "blockInstanceId",+ "assetId",+ "revision",+ "contentRef",+ "format",+ "renderScope",+ ],+ additionalProperties: false,+ },+ sessionStatus: {+ type: "string",+ enum: [+ "disconnected",+ "saved",+ "pending",+ "conflicting",+ "cancelled",+ "recoverable",+ "failed",+ ],+ },+ pending: {+ type: "boolean",+ },+ diagnostics: {+ type: "array",+ items: {+ oneOf: [+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },},+ required: ["line", "column"],+ additionalProperties: false,},- required: ["method", "login", "password"],- },- {- type: "object",- properties: {- type: {- type: "string",- const: "basic",- },- login: {- type: "string",- },- password: {- type: "string",+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },},+ required: ["line", "column"],+ additionalProperties: false,},- required: ["type", "login", "password"],},- ],+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "invalid-mdx",+ },+ severity: {+ type: "string",+ const: "error",+ },+ message: {+ type: "string",+ minLength: 1,+ },},- custom: {- type: "array",- items: {+ required: ["blockInstanceId", "code", "severity", "message"],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {type: "object",properties: {- property: {- type: "string",- },- content: {- type: "string",+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,},- },- required: ["property", "content"],- additionalProperties: {},+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unsafe-mdx",+ },+ severity: {+ type: "string",+ const: "error",+ },+ nodeType: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ minLength: 1,},},+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "nodeType",+ "reason",+ ],+ additionalProperties: false,},- required: ["documentType"],- additionalProperties: {},- },- requestedPath: {- type: "string",- },- found: {- type: "boolean",- },- exactMatch: {- type: "boolean",- },- matchedPattern: {- type: "boolean",- },- matchedFallback: {- type: "boolean",- },- },- required: [- "id",- "name",- "path",- "localPath",- "title",- "rootInstanceId",- "isHome",- "meta",- "requestedPath",- "found",- "exactMatch",- "matchedPattern",- "matchedFallback",- ],- additionalProperties: {},- },- {- type: "object",- properties: {- requestedPath: {- type: "string",- },- found: {- type: "boolean",- },- exactMatch: {- type: "boolean",- },- matchedPattern: {- type: "boolean",- },- matchedFallback: {- type: "boolean",- },- fallbackPage: {- type: "object",- properties: {- id: {- type: "string",- },- name: {- type: "string",- },- path: {- type: "string",- },- localPath: {- type: "string",- },- title: {- type: "string",- },- rootInstanceId: {- type: "string",- },- parentFolderId: {- type: "string",- },- isHome: {- type: "boolean",- },- isDraft: {- description:- "True when the page is a draft. Missing or false means the page is publishable.",- type: "boolean",- },- meta: {- type: "object",- properties: {- description: {- type: "string",- },- language: {- type: "string",- },- redirect: {- type: "string",- },- status: {- type: "string",- },- socialImageUrl: {- type: "string",- },- socialImageAssetId: {- type: "string",- },- excludePageFromSearch: {- type: "boolean",- },- documentType: {- type: "string",- enum: ["html", "xml", "text"],- },- content: {- type: "string",- },- auth: {- anyOf: [- {- type: "object",- properties: {- method: {- type: "string",- const: "basic",- },- login: {- type: "string",- },- password: {- type: "string",- },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,},- required: ["method", "login", "password"],- },- {- type: "object",- properties: {- type: {- type: "string",- const: "basic",- },- login: {- type: "string",- },- password: {- type: "string",- },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,},- required: ["type", "login", "password"],},- ],- },- custom: {- type: "array",- items: {+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {type: "object",properties: {- property: {- type: "string",+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,},- content: {- type: "string",+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,},},- required: ["property", "content"],- additionalProperties: {},+ required: ["line", "column"],+ additionalProperties: false,},},+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unresolved-template",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,},- required: ["documentType"],- additionalProperties: {},},+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ ],+ additionalProperties: false,},- required: [- "id",- "name",- "path",- "localPath",- "title",- "rootInstanceId",- "isHome",- "meta",- ],- additionalProperties: {},- },- guidance: {- type: "string",- },- },- required: [- "requestedPath",- "found",- "exactMatch",- "matchedPattern",- "matchedFallback",- "fallbackPage",- "guidance",- ],- additionalProperties: {},- },- ],- },- readNamespaces: ["pages", "instances"],- writeNamespaces: [],- invalidatesNamespaces: [],- retryOnConflict: false,- },- {- id: "pages.create",- command: "create-page",- client: "createPage",- kind: "mutation",- inputSchema: {- type: "object",- properties: {- name: {- type: "string",- minLength: 1,- },- path: {- type: "string",- description:- 'Plain page path. For a new non-home page, start with "/", for example "/pricing". Use colon-prefixed dynamic segments such as "/blog/:slug" when one page definition must render many concrete routes; do not create a separate page for every route value. The home page path is the empty string ""; do not use an empty path when creating a new page.',- },- title: {- description:- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',- type: "string",- },- parentFolderId: {- type: "string",- },- meta: {- type: "object",- properties: {- description: {- description:- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',- type: "string",- },- language: {- description:- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',- type: "string",- },- redirect: {- description:- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',- type: "string",- },- socialImageUrl: {- description:- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',- type: "string",- },- socialImageAssetId: {- type: "string",- },- excludePageFromSearch: {- anyOf: [- {- type: "boolean",- },- {- description:- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',- type: "string",- },- ],- },- documentType: {- type: "string",- enum: ["html", "xml", "text"],- },- content: {- description:- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',- type: "string",- },- status: {- anyOf: [- {- type: "number",- },- {- type: "string",- },- ],- description:- "Pass a fixed HTTP status code as a number from 200 through 599, for example 302. For a dynamic status, pass one Webstudio JavaScript expression as a string, for example `system.status`.",- },- auth: {- anyOf: [- {- type: "object",- properties: {- method: {- type: "string",- const: "basic",- },- login: {- type: "string",- },- password: {- type: "string",- },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,},- required: ["method", "login", "password"],- },- {- type: "object",- properties: {- type: {- type: "string",- const: "basic",- },- login: {- type: "string",- },- password: {- type: "string",+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },},+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "ignored-template-prop",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ propName: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ enum: ["unknown", "incompatible", "design-only", "stale"],},- required: ["type", "login", "password"],},- ],- },- custom: {- type: "array",- items: {+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ "propName",+ "reason",+ ],+ additionalProperties: false,+ },+ {type: "object",properties: {- property: {+ blockInstanceId: {type: "string",+ minLength: 1,},- content: {- description:- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',+ assetId: {type: "string",+ minLength: 1,},- },- required: ["property", "content"],- },- },- },- required: [],- },- },- required: ["name", "path"],- },- outputSchema: {- type: "object",- properties: {- pageId: {- type: "string",- },- rootInstanceId: {- type: "string",- },- },- required: ["pageId", "rootInstanceId"],- additionalProperties: {},- },- readNamespaces: ["pages", "instances", "dataSources"],- writeNamespaces: ["pages", "instances"],- invalidatesNamespaces: ["pages", "instances"],- retryOnConflict: false,- },- {- id: "pages.update",- command: "update-page",- client: "updatePage",- kind: "mutation",- inputSchema: {- type: "object",- properties: {- pageId: {- type: "string",- },- values: {- type: "object",- properties: {- name: {- type: "string",- minLength: 1,- },- path: {- anyOf: [- {- type: "string",- },- {- type: "string",- },- ],- description:- 'Plain page path. For a new non-home page, start with "/", for example "/pricing". Use colon-prefixed dynamic segments such as "/blog/:slug" when one page definition must render many concrete routes; do not create a separate page for every route value. The home page path is the empty string ""; do not use an empty path when creating a new page.',- },- title: {- description:- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',- type: "string",- },- isDraft: {- type: "boolean",- description:- "Set true to mark the page as draft. Draft pages remain editable and previewable in Builder but are omitted from every publish target, including staging, and from sitemap output. Set false to stage the page for a future publish; this does not deploy the site. The home page and /* catch-all page cannot be drafts.",- },- parentFolderId: {- type: "string",- },- meta: {- type: "object",- properties: {- description: {- description:- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',- type: "string",- },- language: {- description:- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',- type: "string",- },- redirect: {- description:- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',- type: "string",- },- socialImageUrl: {- description:- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',- type: "string",- },- socialImageAssetId: {- type: "string",- },- excludePageFromSearch: {- anyOf: [- {- type: "boolean",- },- {- description:- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',- type: "string",- },- ],- },- documentType: {- type: "string",- enum: ["html", "xml", "text"],- },- content: {- description:- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',- type: "string",- },- status: {- anyOf: [- {- type: "number",- },- {- type: "string",- },- ],- description:- "Pass a fixed HTTP status code as a number from 200 through 599, for example 302. For a dynamic status, pass one Webstudio JavaScript expression as a string, for example `system.status`.",- },- auth: {- anyOf: [- {- type: "object",- properties: {- method: {- type: "string",- const: "basic",- },- login: {- type: "string",+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },},- password: {- type: "string",+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },},+ required: ["line", "column"],+ additionalProperties: false,},- required: ["method", "login", "password"],},- {- type: "object",- properties: {- type: {- type: "string",- const: "basic",- },- login: {- type: "string",+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "stale-revision",+ },+ severity: {+ type: "string",+ const: "error",+ },+ expectedRevision: {+ type: "string",+ minLength: 1,+ },+ actualRevision: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "expectedRevision",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },},- password: {- type: "string",+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },},+ required: ["line", "column"],+ additionalProperties: false,},- required: ["type", "login", "password"],},- ],+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "changed-binding",+ },+ severity: {+ type: "string",+ const: "error",+ },+ loadedAssetId: {+ type: "string",+ minLength: 1,+ },+ resolvedAssetId: {+ type: "string",+ minLength: 1,+ },},- custom: {- type: "array",- items: {+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "loadedAssetId",+ "resolvedAssetId",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {type: "object",properties: {- property: {- type: "string",+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,},- content: {- description:- 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',- type: "string",+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,},},- required: ["property", "content"],+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "pending-writes",+ },+ severity: {+ type: "string",+ const: "error",+ },+ pendingMutationCount: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,},},+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "pendingMutationCount",+ ],+ additionalProperties: false,},- required: [],- },- },- required: [],- },- },- required: ["pageId", "values"],- },- outputSchema: {- type: "object",- properties: {- pageId: {- type: "string",- },- },- required: ["pageId"],- additionalProperties: {},- },- readNamespaces: ["pages", "instances", "dataSources"],- writeNamespaces: ["pages"],- invalidatesNamespaces: ["pages"],- retryOnConflict: true,- },- {- id: "pages.updateSettings",- command: "update-page-settings",- client: "updatePageSettings",- kind: "mutation",- inputSchema: {- type: "object",- properties: {- pageId: {- type: "string",- },- values: {- type: "object",- properties: {- name: {- type: "string",- },- parentFolderId: {- type: "string",- },- path: {- type: "string",- },- isHomePage: {- type: "boolean",- },- title: {- type: "string",- },- description: {- type: "string",- },- excludePageFromSearch: {- type: "string",- },- language: {- type: "string",- },- socialImageUrl: {- type: "string",- },- socialImageAssetId: {- type: "string",- },- status: {- type: "string",- },- redirect: {- type: "string",- },- documentType: {- type: "string",- enum: ["html", "xml", "text"],- },- content: {- type: "string",- },- auth: {- type: "object",- properties: {- login: {- type: "string",- },- password: {- type: "string",- },- },- required: ["login", "password"],- },- customMetas: {- type: "array",- items: {+ {type: "object",properties: {- property: {+ blockInstanceId: {type: "string",+ minLength: 1,},- content: {+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "authorization-failed",+ },+ severity: {+ type: "string",+ const: "error",+ },+ operation: {type: "string",+ enum: ["read", "write"],},},- required: ["property", "content"],+ required: ["blockInstanceId", "code", "severity", "operation"],+ additionalProperties: false,},- },- marketplace: {- type: "object",- properties: {- include: {- type: "boolean",- },- category: {- type: "string",- },- thumbnailAssetId: {- type: "string",+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "partial-recovery",+ },+ severity: {+ type: "string",+ const: "error",+ },+ completedStorageRoots: {+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ },+ failedStorageRoots: {+ minItems: 1,+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ },},+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "completedStorageRoots",+ "failedStorageRoots",+ ],+ additionalProperties: false,},- required: ["include", "category", "thumbnailAssetId"],- },+ ],},- required: [],- },- },- required: ["pageId", "values"],- },- outputSchema: {- type: "object",- properties: {- pageId: {- type: "string",- },- },- required: ["pageId"],- additionalProperties: {},- },- readNamespaces: ["pages", "instances", "dataSources"],- writeNamespaces: ["pages"],- invalidatesNamespaces: ["pages"],- retryOnConflict: true,- },- {- id: "pages.updateMarketplace",- command: "update-page-marketplace",- client: "updatePageMarketplace",- kind: "mutation",- inputSchema: {- type: "object",- properties: {- pageId: {- type: "string",},- marketplace: {+ capabilities: {type: "object",properties: {- include: {+ canConnect: {type: "boolean",},- category: {- type: "string",+ canSwitch: {+ type: "boolean",},- thumbnailAssetId: {- type: "string",+ canDisconnectWithCopy: {+ type: "boolean",},- },- required: [],- },- },- required: ["pageId", "marketplace"],- },- outputSchema: {- type: "object",- properties: {- pageId: {- type: "string",- },- marketplace: {- type: "object",- properties: {- include: {+ canEdit: {type: "boolean",},- category: {- type: "string",+ canRetry: {+ type: "boolean",},- thumbnailAssetId: {- type: "string",+ canReloadRemote: {+ type: "boolean",+ },+ canCopyUnsavedSource: {+ type: "boolean",},},- additionalProperties: {},- required: [],- },- },- required: ["pageId", "marketplace"],- additionalProperties: {},- },- readNamespaces: ["pages"],- writeNamespaces: ["pages"],- invalidatesNamespaces: ["pages"],- retryOnConflict: true,- },- {- id: "pages.savePathInHistory",- command: "save-page-path-history",- client: "savePagePathInHistory",- kind: "mutation",- inputSchema: {- type: "object",- properties: {- pageId: {- type: "string",+ required: [+ "canConnect",+ "canSwitch",+ "canDisconnectWithCopy",+ "canEdit",+ "canRetry",+ "canReloadRemote",+ "canCopyUnsavedSource",+ ],},- path: {- type: "string",+ repairRoutes: {+ type: "array",+ items: {+ type: "string",+ enum: [+ "open-file",+ "retry",+ "reload-remote",+ "copy-unsaved-mdx",+ "disconnect-with-copy",+ ],+ },},},- required: ["pageId", "path"],- },- outputSchema: {- type: "object",- properties: {},- additionalProperties: {},- required: [],+ required: [+ "blockInstanceId",+ "renderScope",+ "sessionStatus",+ "pending",+ "diagnostics",+ "capabilities",+ "repairRoutes",+ ],},- readNamespaces: ["pages"],- writeNamespaces: ["pages"],- invalidatesNamespaces: ["pages"],- retryOnConflict: true,+ readNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+ requiresAssets: true,},{- id: "pages.setHome",- command: "set-home-page",- client: "setHomePage",- kind: "mutation",+ id: "contentBlocks.connectSource",+ command: "connect-content-block-source",+ client: "connectContentBlockSource",+ permit: "edit",+ kind: "application",inputSchema: {type: "object",properties: {- pageId: {+ blockInstanceId: {type: "string",+ minLength: 1,},- },- required: ["pageId"],- },- outputSchema: {- type: "object",- properties: {- pageId: {+ renderScope: {type: "string",+ minLength: 1,},- },- required: ["pageId"],- additionalProperties: {},- },- readNamespaces: ["pages"],- writeNamespaces: ["pages"],- invalidatesNamespaces: ["pages"],- retryOnConflict: true,- },- {- id: "projectSettings.get",- command: "get-project-settings",- client: "getProjectSettings",- kind: "read",- inputSchema: {- type: "object",- properties: {- verbose: {- description:- "Expand the same result with complete records and diagnostics. Omit for compact output.",+ variables: {+ type: "object",+ propertyNames: {+ type: "string",+ minLength: 1,+ },+ additionalProperties: {+ $ref: "#/$defs/__schema0",+ },+ },+ dryRun: {type: "boolean",},- },- required: [],- },- outputSchema: {- type: "object",- properties: {- meta: {- type: "object",- properties: {- siteName: {- type: "string",- },- contactEmail: {- type: "string",- },- faviconAssetId: {- type: "string",+ confirmationToken: {+ type: "string",+ minLength: 1,+ },+ source: {+ oneOf: [+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "asset",+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["type", "assetId"],+ additionalProperties: false,},- code: {- type: "string",+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "expression",+ },+ value: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["type", "value"],+ additionalProperties: false,},- agentInstructions: {+ ],+ },+ authority: {+ type: "string",+ enum: ["use-file-content", "replace-file-body-with-block-content"],+ },+ },+ required: ["blockInstanceId", "renderScope", "source"],+ $defs: {+ __schema0: {+ anyOf: [+ {type: "string",},- auth: {- type: "string",+ {+ type: "number",},- },- additionalProperties: {},- required: [],- },- compiler: {- type: "object",- properties: {- atomicStyles: {+ {type: "boolean",},- },- additionalProperties: {},- required: [],- },- redirects: {- type: "array",- items: {- type: "object",- properties: {- old: {- type: "string",+ {+ type: "null",+ },+ {+ type: "array",+ items: {+ $ref: "#/$defs/__schema0",},- new: {+ },+ {+ type: "object",+ propertyNames: {type: "string",- minLength: 1,},- status: {- type: "string",- enum: ["301", "302"],+ additionalProperties: {+ $ref: "#/$defs/__schema0",},},- required: ["old", "new"],- additionalProperties: {},- },+ ],},},- required: ["meta", "compiler"],- additionalProperties: {},},- readNamespaces: ["pages", "projectSettings"],- writeNamespaces: [],- invalidatesNamespaces: [],- retryOnConflict: false,- },- {- id: "projectSettings.update",- command: "update-project-settings",- client: "updateProjectSettings",- kind: "mutation",- inputSchema: {+ outputSchema: {type: "object",properties: {- meta: {+ status: {+ type: "string",+ enum: ["complete", "partial", "confirmation-required", "blocked"],+ },+ code: {+ type: "string",+ },+ message: {+ type: "string",+ },+ source: {type: "object",properties: {- siteName: {- anyOf: [- {- type: "string",- },- {- type: "null",- },- ],+ blockInstanceId: {+ type: "string",},- contactEmail: {- anyOf: [- {- type: "string",- },- {- type: "null",- },- ],+ renderScope: {+ type: "string",},- faviconAssetId: {- anyOf: [+ configuredSource: {+ oneOf: [{- type: "string",+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "asset",+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["type", "assetId"],+ additionalProperties: false,},{- type: "null",+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "expression",+ },+ value: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["type", "value"],+ additionalProperties: false,},],},- code: {- anyOf: [- {+ resolvedIdentity: {+ type: "object",+ properties: {+ blockInstanceId: {type: "string",+ minLength: 1,},- {- type: "null",+ assetId: {+ type: "string",+ minLength: 1,},- ],- },- agentInstructions: {- anyOf: [- {+ revision: {type: "string",+ minLength: 1,},- {- type: "null",+ contentRef: {+ type: "string",+ minLength: 1,},- ],- },- auth: {- anyOf: [- {+ format: {type: "string",+ const: "mdx",},- {- type: "null",+ renderScope: {+ type: "string",+ minLength: 1,},+ },+ required: [+ "blockInstanceId",+ "assetId",+ "revision",+ "contentRef",+ "format",+ "renderScope",],+ additionalProperties: false,},- },- additionalProperties: false,- required: [],- },- compiler: {- type: "object",- properties: {- atomicStyles: {- anyOf: [- {- type: "boolean",- },- {- type: "null",- },+ sessionStatus: {+ type: "string",+ enum: [+ "disconnected",+ "saved",+ "pending",+ "conflicting",+ "cancelled",+ "recoverable",+ "failed",],},- },- additionalProperties: false,- required: [],- },- },- additionalProperties: false,- description:- "Update at least one supported project meta or compiler setting. Null removes a setting.",- required: [],- },- outputSchema: {- type: "object",- properties: {- updated: {- type: "boolean",- },- },- required: ["updated"],- additionalProperties: {},- },- readNamespaces: ["projectSettings"],- writeNamespaces: ["projectSettings"],- invalidatesNamespaces: ["projectSettings"],- retryOnConflict: true,- },+ pending: {+ type: "boolean",+ },+ diagnostics: {+ type: "array",+ items: {+ oneOf: [+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "invalid-mdx",+ },+ severity: {+ type: "string",+ const: "error",+ },+ message: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "message",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unsafe-mdx",+ },+ severity: {+ type: "string",+ const: "error",+ },+ nodeType: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "nodeType",+ "reason",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unresolved-template",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "ignored-template-prop",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ propName: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ enum: [+ "unknown",+ "incompatible",+ "design-only",+ "stale",+ ],+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ "propName",+ "reason",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "stale-revision",+ },+ severity: {+ type: "string",+ const: "error",+ },+ expectedRevision: {+ type: "string",+ minLength: 1,+ },+ actualRevision: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "expectedRevision",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "changed-binding",+ },+ severity: {+ type: "string",+ const: "error",+ },+ loadedAssetId: {+ type: "string",+ minLength: 1,+ },+ resolvedAssetId: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "loadedAssetId",+ "resolvedAssetId",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "pending-writes",+ },+ severity: {+ type: "string",+ const: "error",+ },+ pendingMutationCount: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "pendingMutationCount",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "authorization-failed",+ },+ severity: {+ type: "string",+ const: "error",+ },+ operation: {+ type: "string",+ enum: ["read", "write"],+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "operation",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "partial-recovery",+ },+ severity: {+ type: "string",+ const: "error",+ },+ completedStorageRoots: {+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ },+ failedStorageRoots: {+ minItems: 1,+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "completedStorageRoots",+ "failedStorageRoots",+ ],+ additionalProperties: false,+ },+ ],+ },+ },+ capabilities: {+ type: "object",+ properties: {+ canConnect: {+ type: "boolean",+ },+ canSwitch: {+ type: "boolean",+ },+ canDisconnectWithCopy: {+ type: "boolean",+ },+ canEdit: {+ type: "boolean",+ },+ canRetry: {+ type: "boolean",+ },+ canReloadRemote: {+ type: "boolean",+ },+ canCopyUnsavedSource: {+ type: "boolean",+ },+ },+ required: [+ "canConnect",+ "canSwitch",+ "canDisconnectWithCopy",+ "canEdit",+ "canRetry",+ "canReloadRemote",+ "canCopyUnsavedSource",+ ],+ },+ repairRoutes: {+ type: "array",+ items: {+ type: "string",+ enum: [+ "open-file",+ "retry",+ "reload-remote",+ "copy-unsaved-mdx",+ "disconnect-with-copy",+ ],+ },+ },+ },+ required: [+ "blockInstanceId",+ "renderScope",+ "sessionStatus",+ "pending",+ "diagnostics",+ "capabilities",+ "repairRoutes",+ ],+ },+ plan: {+ type: "object",+ properties: {+ action: {+ type: "string",+ enum: ["connect", "switch", "disconnect"],+ },+ changesProject: {+ type: "boolean",+ },+ storageWrites: {+ type: "array",+ items: {+ type: "object",+ properties: {+ identity: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ revision: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ format: {+ type: "string",+ const: "mdx",+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "assetId",+ "revision",+ "contentRef",+ "format",+ "renderScope",+ ],+ additionalProperties: false,+ },+ expectedRevision: {+ type: "string",+ },+ },+ required: ["identity", "expectedRevision"],+ },+ },+ diagnostics: {+ type: "array",+ items: {+ oneOf: [+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "invalid-mdx",+ },+ severity: {+ type: "string",+ const: "error",+ },+ message: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "message",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unsafe-mdx",+ },+ severity: {+ type: "string",+ const: "error",+ },+ nodeType: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "nodeType",+ "reason",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unresolved-template",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "ignored-template-prop",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ propName: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ enum: [+ "unknown",+ "incompatible",+ "design-only",+ "stale",+ ],+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ "propName",+ "reason",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "stale-revision",+ },+ severity: {+ type: "string",+ const: "error",+ },+ expectedRevision: {+ type: "string",+ minLength: 1,+ },+ actualRevision: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "expectedRevision",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "changed-binding",+ },+ severity: {+ type: "string",+ const: "error",+ },+ loadedAssetId: {+ type: "string",+ minLength: 1,+ },+ resolvedAssetId: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "loadedAssetId",+ "resolvedAssetId",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "pending-writes",+ },+ severity: {+ type: "string",+ const: "error",+ },+ pendingMutationCount: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "pendingMutationCount",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "authorization-failed",+ },+ severity: {+ type: "string",+ const: "error",+ },+ operation: {+ type: "string",+ enum: ["read", "write"],+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "operation",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "partial-recovery",+ },+ severity: {+ type: "string",+ const: "error",+ },+ completedStorageRoots: {+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ },+ failedStorageRoots: {+ minItems: 1,+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "completedStorageRoots",+ "failedStorageRoots",+ ],+ additionalProperties: false,+ },+ ],+ },+ },+ persistenceOrder: {+ type: "string",+ enum: ["none", "storage-before-project"],+ },+ persistence: {+ type: "object",+ properties: {+ status: {+ type: "string",+ enum: ["complete", "partial", "failed"],+ },+ steps: {+ type: "array",+ items: {+ type: "object",+ properties: {+ type: {+ type: "string",+ enum: ["asset", "project"],+ },+ status: {+ type: "string",+ enum: ["saved", "failed", "not-attempted"],+ },+ root: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ revision: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ format: {+ type: "string",+ const: "mdx",+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "assetId",+ "revision",+ "contentRef",+ "format",+ "renderScope",+ ],+ additionalProperties: false,+ },+ code: {+ type: "string",+ },+ message: {+ type: "string",+ },+ },+ required: ["type", "status"],+ },+ },+ retry: {+ type: "object",+ properties: {+ replan: {+ type: "boolean",+ const: true,+ },+ roots: {+ type: "array",+ items: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ revision: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ format: {+ type: "string",+ const: "mdx",+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "assetId",+ "revision",+ "contentRef",+ "format",+ "renderScope",+ ],+ additionalProperties: false,+ },+ },+ project: {+ type: "boolean",+ },+ },+ required: ["replan", "roots", "project"],+ },+ },+ required: ["status", "steps", "retry"],+ },+ },+ required: [+ "action",+ "changesProject",+ "storageWrites",+ "diagnostics",+ "persistenceOrder",+ ],+ },+ confirmation: {+ type: "object",+ properties: {+ token: {+ type: "string",+ },+ expiresAt: {+ type: "string",+ },+ },+ required: ["token", "expiresAt"],+ },+ },+ required: ["status", "source"],+ },+ readNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ writeNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ invalidatesNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ retryOnConflict: false,+ requiresAssets: true,+ },+ {+ id: "contentBlocks.switchSource",+ command: "switch-content-block-source",+ client: "switchContentBlockSource",+ permit: "edit",+ kind: "application",+ inputSchema: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ variables: {+ type: "object",+ propertyNames: {+ type: "string",+ minLength: 1,+ },+ additionalProperties: {+ $ref: "#/$defs/__schema0",+ },+ },+ dryRun: {+ type: "boolean",+ },+ confirmationToken: {+ type: "string",+ minLength: 1,+ },+ source: {+ oneOf: [+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "asset",+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["type", "assetId"],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "expression",+ },+ value: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["type", "value"],+ additionalProperties: false,+ },+ ],+ },+ authority: {+ type: "string",+ enum: ["use-file-content", "replace-file-body-with-block-content"],+ },+ },+ required: ["blockInstanceId", "renderScope", "source"],+ $defs: {+ __schema0: {+ anyOf: [+ {+ type: "string",+ },+ {+ type: "number",+ },+ {+ type: "boolean",+ },+ {+ type: "null",+ },+ {+ type: "array",+ items: {+ $ref: "#/$defs/__schema0",+ },+ },+ {+ type: "object",+ propertyNames: {+ type: "string",+ },+ additionalProperties: {+ $ref: "#/$defs/__schema0",+ },+ },+ ],+ },+ },+ },+ outputSchema: {+ type: "object",+ properties: {+ status: {+ type: "string",+ enum: ["complete", "partial", "confirmation-required", "blocked"],+ },+ code: {+ type: "string",+ },+ message: {+ type: "string",+ },+ source: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ },+ renderScope: {+ type: "string",+ },+ configuredSource: {+ oneOf: [+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "asset",+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["type", "assetId"],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "expression",+ },+ value: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["type", "value"],+ additionalProperties: false,+ },+ ],+ },+ resolvedIdentity: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ revision: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ format: {+ type: "string",+ const: "mdx",+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "assetId",+ "revision",+ "contentRef",+ "format",+ "renderScope",+ ],+ additionalProperties: false,+ },+ sessionStatus: {+ type: "string",+ enum: [+ "disconnected",+ "saved",+ "pending",+ "conflicting",+ "cancelled",+ "recoverable",+ "failed",+ ],+ },+ pending: {+ type: "boolean",+ },+ diagnostics: {+ type: "array",+ items: {+ oneOf: [+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "invalid-mdx",+ },+ severity: {+ type: "string",+ const: "error",+ },+ message: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "message",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unsafe-mdx",+ },+ severity: {+ type: "string",+ const: "error",+ },+ nodeType: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "nodeType",+ "reason",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unresolved-template",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "ignored-template-prop",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ propName: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ enum: [+ "unknown",+ "incompatible",+ "design-only",+ "stale",+ ],+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ "propName",+ "reason",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "stale-revision",+ },+ severity: {+ type: "string",+ const: "error",+ },+ expectedRevision: {+ type: "string",+ minLength: 1,+ },+ actualRevision: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "expectedRevision",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "changed-binding",+ },+ severity: {+ type: "string",+ const: "error",+ },+ loadedAssetId: {+ type: "string",+ minLength: 1,+ },+ resolvedAssetId: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "loadedAssetId",+ "resolvedAssetId",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "pending-writes",+ },+ severity: {+ type: "string",+ const: "error",+ },+ pendingMutationCount: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "pendingMutationCount",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "authorization-failed",+ },+ severity: {+ type: "string",+ const: "error",+ },+ operation: {+ type: "string",+ enum: ["read", "write"],+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "operation",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "partial-recovery",+ },+ severity: {+ type: "string",+ const: "error",+ },+ completedStorageRoots: {+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ },+ failedStorageRoots: {+ minItems: 1,+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "completedStorageRoots",+ "failedStorageRoots",+ ],+ additionalProperties: false,+ },+ ],+ },+ },+ capabilities: {+ type: "object",+ properties: {+ canConnect: {+ type: "boolean",+ },+ canSwitch: {+ type: "boolean",+ },+ canDisconnectWithCopy: {+ type: "boolean",+ },+ canEdit: {+ type: "boolean",+ },+ canRetry: {+ type: "boolean",+ },+ canReloadRemote: {+ type: "boolean",+ },+ canCopyUnsavedSource: {+ type: "boolean",+ },+ },+ required: [+ "canConnect",+ "canSwitch",+ "canDisconnectWithCopy",+ "canEdit",+ "canRetry",+ "canReloadRemote",+ "canCopyUnsavedSource",+ ],+ },+ repairRoutes: {+ type: "array",+ items: {+ type: "string",+ enum: [+ "open-file",+ "retry",+ "reload-remote",+ "copy-unsaved-mdx",+ "disconnect-with-copy",+ ],+ },+ },+ },+ required: [+ "blockInstanceId",+ "renderScope",+ "sessionStatus",+ "pending",+ "diagnostics",+ "capabilities",+ "repairRoutes",+ ],+ },+ plan: {+ type: "object",+ properties: {+ action: {+ type: "string",+ enum: ["connect", "switch", "disconnect"],+ },+ changesProject: {+ type: "boolean",+ },+ storageWrites: {+ type: "array",+ items: {+ type: "object",+ properties: {+ identity: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ revision: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ format: {+ type: "string",+ const: "mdx",+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "assetId",+ "revision",+ "contentRef",+ "format",+ "renderScope",+ ],+ additionalProperties: false,+ },+ expectedRevision: {+ type: "string",+ },+ },+ required: ["identity", "expectedRevision"],+ },+ },+ diagnostics: {+ type: "array",+ items: {+ oneOf: [+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "invalid-mdx",+ },+ severity: {+ type: "string",+ const: "error",+ },+ message: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "message",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unsafe-mdx",+ },+ severity: {+ type: "string",+ const: "error",+ },+ nodeType: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "nodeType",+ "reason",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unresolved-template",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "ignored-template-prop",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ propName: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ enum: [+ "unknown",+ "incompatible",+ "design-only",+ "stale",+ ],+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ "propName",+ "reason",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "stale-revision",+ },+ severity: {+ type: "string",+ const: "error",+ },+ expectedRevision: {+ type: "string",+ minLength: 1,+ },+ actualRevision: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "expectedRevision",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "changed-binding",+ },+ severity: {+ type: "string",+ const: "error",+ },+ loadedAssetId: {+ type: "string",+ minLength: 1,+ },+ resolvedAssetId: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "loadedAssetId",+ "resolvedAssetId",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "pending-writes",+ },+ severity: {+ type: "string",+ const: "error",+ },+ pendingMutationCount: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "pendingMutationCount",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "authorization-failed",+ },+ severity: {+ type: "string",+ const: "error",+ },+ operation: {+ type: "string",+ enum: ["read", "write"],+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "operation",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "partial-recovery",+ },+ severity: {+ type: "string",+ const: "error",+ },+ completedStorageRoots: {+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ },+ failedStorageRoots: {+ minItems: 1,+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "completedStorageRoots",+ "failedStorageRoots",+ ],+ additionalProperties: false,+ },+ ],+ },+ },+ persistenceOrder: {+ type: "string",+ enum: ["none", "storage-before-project"],+ },+ persistence: {+ type: "object",+ properties: {+ status: {+ type: "string",+ enum: ["complete", "partial", "failed"],+ },+ steps: {+ type: "array",+ items: {+ type: "object",+ properties: {+ type: {+ type: "string",+ enum: ["asset", "project"],+ },+ status: {+ type: "string",+ enum: ["saved", "failed", "not-attempted"],+ },+ root: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ revision: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ format: {+ type: "string",+ const: "mdx",+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "assetId",+ "revision",+ "contentRef",+ "format",+ "renderScope",+ ],+ additionalProperties: false,+ },+ code: {+ type: "string",+ },+ message: {+ type: "string",+ },+ },+ required: ["type", "status"],+ },+ },+ retry: {+ type: "object",+ properties: {+ replan: {+ type: "boolean",+ const: true,+ },+ roots: {+ type: "array",+ items: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ revision: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ format: {+ type: "string",+ const: "mdx",+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "assetId",+ "revision",+ "contentRef",+ "format",+ "renderScope",+ ],+ additionalProperties: false,+ },+ },+ project: {+ type: "boolean",+ },+ },+ required: ["replan", "roots", "project"],+ },+ },+ required: ["status", "steps", "retry"],+ },+ },+ required: [+ "action",+ "changesProject",+ "storageWrites",+ "diagnostics",+ "persistenceOrder",+ ],+ },+ confirmation: {+ type: "object",+ properties: {+ token: {+ type: "string",+ },+ expiresAt: {+ type: "string",+ },+ },+ required: ["token", "expiresAt"],+ },+ },+ required: ["status", "source"],+ },+ readNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ writeNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ invalidatesNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ retryOnConflict: false,+ requiresAssets: true,+ },+ {+ id: "contentBlocks.disconnectSource",+ command: "disconnect-content-block-source",+ client: "disconnectContentBlockSource",+ permit: "edit",+ kind: "application",+ inputSchema: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ variables: {+ type: "object",+ propertyNames: {+ type: "string",+ minLength: 1,+ },+ additionalProperties: {+ $ref: "#/$defs/__schema0",+ },+ },+ dryRun: {+ type: "boolean",+ },+ confirmationToken: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["blockInstanceId", "renderScope"],+ $defs: {+ __schema0: {+ anyOf: [+ {+ type: "string",+ },+ {+ type: "number",+ },+ {+ type: "boolean",+ },+ {+ type: "null",+ },+ {+ type: "array",+ items: {+ $ref: "#/$defs/__schema0",+ },+ },+ {+ type: "object",+ propertyNames: {+ type: "string",+ },+ additionalProperties: {+ $ref: "#/$defs/__schema0",+ },+ },+ ],+ },+ },+ },+ outputSchema: {+ type: "object",+ properties: {+ status: {+ type: "string",+ enum: ["complete", "partial", "confirmation-required", "blocked"],+ },+ code: {+ type: "string",+ },+ message: {+ type: "string",+ },+ source: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ },+ renderScope: {+ type: "string",+ },+ configuredSource: {+ oneOf: [+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "asset",+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["type", "assetId"],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "expression",+ },+ value: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["type", "value"],+ additionalProperties: false,+ },+ ],+ },+ resolvedIdentity: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ revision: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ format: {+ type: "string",+ const: "mdx",+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "assetId",+ "revision",+ "contentRef",+ "format",+ "renderScope",+ ],+ additionalProperties: false,+ },+ sessionStatus: {+ type: "string",+ enum: [+ "disconnected",+ "saved",+ "pending",+ "conflicting",+ "cancelled",+ "recoverable",+ "failed",+ ],+ },+ pending: {+ type: "boolean",+ },+ diagnostics: {+ type: "array",+ items: {+ oneOf: [+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "invalid-mdx",+ },+ severity: {+ type: "string",+ const: "error",+ },+ message: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "message",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unsafe-mdx",+ },+ severity: {+ type: "string",+ const: "error",+ },+ nodeType: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "nodeType",+ "reason",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unresolved-template",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "ignored-template-prop",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ propName: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ enum: [+ "unknown",+ "incompatible",+ "design-only",+ "stale",+ ],+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ "propName",+ "reason",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "stale-revision",+ },+ severity: {+ type: "string",+ const: "error",+ },+ expectedRevision: {+ type: "string",+ minLength: 1,+ },+ actualRevision: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "expectedRevision",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "changed-binding",+ },+ severity: {+ type: "string",+ const: "error",+ },+ loadedAssetId: {+ type: "string",+ minLength: 1,+ },+ resolvedAssetId: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "loadedAssetId",+ "resolvedAssetId",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "pending-writes",+ },+ severity: {+ type: "string",+ const: "error",+ },+ pendingMutationCount: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "pendingMutationCount",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "authorization-failed",+ },+ severity: {+ type: "string",+ const: "error",+ },+ operation: {+ type: "string",+ enum: ["read", "write"],+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "operation",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "partial-recovery",+ },+ severity: {+ type: "string",+ const: "error",+ },+ completedStorageRoots: {+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ },+ failedStorageRoots: {+ minItems: 1,+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "completedStorageRoots",+ "failedStorageRoots",+ ],+ additionalProperties: false,+ },+ ],+ },+ },+ capabilities: {+ type: "object",+ properties: {+ canConnect: {+ type: "boolean",+ },+ canSwitch: {+ type: "boolean",+ },+ canDisconnectWithCopy: {+ type: "boolean",+ },+ canEdit: {+ type: "boolean",+ },+ canRetry: {+ type: "boolean",+ },+ canReloadRemote: {+ type: "boolean",+ },+ canCopyUnsavedSource: {+ type: "boolean",+ },+ },+ required: [+ "canConnect",+ "canSwitch",+ "canDisconnectWithCopy",+ "canEdit",+ "canRetry",+ "canReloadRemote",+ "canCopyUnsavedSource",+ ],+ },+ repairRoutes: {+ type: "array",+ items: {+ type: "string",+ enum: [+ "open-file",+ "retry",+ "reload-remote",+ "copy-unsaved-mdx",+ "disconnect-with-copy",+ ],+ },+ },+ },+ required: [+ "blockInstanceId",+ "renderScope",+ "sessionStatus",+ "pending",+ "diagnostics",+ "capabilities",+ "repairRoutes",+ ],+ },+ plan: {+ type: "object",+ properties: {+ action: {+ type: "string",+ enum: ["connect", "switch", "disconnect"],+ },+ changesProject: {+ type: "boolean",+ },+ storageWrites: {+ type: "array",+ items: {+ type: "object",+ properties: {+ identity: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ revision: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ format: {+ type: "string",+ const: "mdx",+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "assetId",+ "revision",+ "contentRef",+ "format",+ "renderScope",+ ],+ additionalProperties: false,+ },+ expectedRevision: {+ type: "string",+ },+ },+ required: ["identity", "expectedRevision"],+ },+ },+ diagnostics: {+ type: "array",+ items: {+ oneOf: [+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "invalid-mdx",+ },+ severity: {+ type: "string",+ const: "error",+ },+ message: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "message",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unsafe-mdx",+ },+ severity: {+ type: "string",+ const: "error",+ },+ nodeType: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "nodeType",+ "reason",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unresolved-template",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "ignored-template-prop",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ propName: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ enum: [+ "unknown",+ "incompatible",+ "design-only",+ "stale",+ ],+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ "propName",+ "reason",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "stale-revision",+ },+ severity: {+ type: "string",+ const: "error",+ },+ expectedRevision: {+ type: "string",+ minLength: 1,+ },+ actualRevision: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "expectedRevision",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "changed-binding",+ },+ severity: {+ type: "string",+ const: "error",+ },+ loadedAssetId: {+ type: "string",+ minLength: 1,+ },+ resolvedAssetId: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "loadedAssetId",+ "resolvedAssetId",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "pending-writes",+ },+ severity: {+ type: "string",+ const: "error",+ },+ pendingMutationCount: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "pendingMutationCount",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "authorization-failed",+ },+ severity: {+ type: "string",+ const: "error",+ },+ operation: {+ type: "string",+ enum: ["read", "write"],+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "operation",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "partial-recovery",+ },+ severity: {+ type: "string",+ const: "error",+ },+ completedStorageRoots: {+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ },+ failedStorageRoots: {+ minItems: 1,+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "completedStorageRoots",+ "failedStorageRoots",+ ],+ additionalProperties: false,+ },+ ],+ },+ },+ persistenceOrder: {+ type: "string",+ enum: ["none", "storage-before-project"],+ },+ persistence: {+ type: "object",+ properties: {+ status: {+ type: "string",+ enum: ["complete", "partial", "failed"],+ },+ steps: {+ type: "array",+ items: {+ type: "object",+ properties: {+ type: {+ type: "string",+ enum: ["asset", "project"],+ },+ status: {+ type: "string",+ enum: ["saved", "failed", "not-attempted"],+ },+ root: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ revision: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ format: {+ type: "string",+ const: "mdx",+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "assetId",+ "revision",+ "contentRef",+ "format",+ "renderScope",+ ],+ additionalProperties: false,+ },+ code: {+ type: "string",+ },+ message: {+ type: "string",+ },+ },+ required: ["type", "status"],+ },+ },+ retry: {+ type: "object",+ properties: {+ replan: {+ type: "boolean",+ const: true,+ },+ roots: {+ type: "array",+ items: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ revision: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ format: {+ type: "string",+ const: "mdx",+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "assetId",+ "revision",+ "contentRef",+ "format",+ "renderScope",+ ],+ additionalProperties: false,+ },+ },+ project: {+ type: "boolean",+ },+ },+ required: ["replan", "roots", "project"],+ },+ },+ required: ["status", "steps", "retry"],+ },+ },+ required: [+ "action",+ "changesProject",+ "storageWrites",+ "diagnostics",+ "persistenceOrder",+ ],+ },+ confirmation: {+ type: "object",+ properties: {+ token: {+ type: "string",+ },+ expiresAt: {+ type: "string",+ },+ },+ required: ["token", "expiresAt"],+ },+ },+ required: ["status", "source"],+ },+ readNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ writeNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ invalidatesNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ retryOnConflict: false,+ requiresAssets: true,+ },+ {+ id: "contentBlocks.recoverSource",+ command: "recover-content-block-source",+ client: "recoverContentBlockSource",+ permit: "edit",+ kind: "application",+ inputSchema: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ action: {+ type: "string",+ enum: ["retry", "reload-remote", "copy-unsaved-mdx"],+ },+ },+ required: ["blockInstanceId", "renderScope", "action"],+ },+ outputSchema: {+ type: "object",+ properties: {+ status: {+ type: "string",+ enum: ["complete", "partial", "blocked"],+ },+ code: {+ type: "string",+ },+ message: {+ type: "string",+ },+ source: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ },+ renderScope: {+ type: "string",+ },+ configuredSource: {+ oneOf: [+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "asset",+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["type", "assetId"],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "expression",+ },+ value: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["type", "value"],+ additionalProperties: false,+ },+ ],+ },+ resolvedIdentity: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ revision: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ format: {+ type: "string",+ const: "mdx",+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "assetId",+ "revision",+ "contentRef",+ "format",+ "renderScope",+ ],+ additionalProperties: false,+ },+ sessionStatus: {+ type: "string",+ enum: [+ "disconnected",+ "saved",+ "pending",+ "conflicting",+ "cancelled",+ "recoverable",+ "failed",+ ],+ },+ pending: {+ type: "boolean",+ },+ diagnostics: {+ type: "array",+ items: {+ oneOf: [+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "invalid-mdx",+ },+ severity: {+ type: "string",+ const: "error",+ },+ message: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "message",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unsafe-mdx",+ },+ severity: {+ type: "string",+ const: "error",+ },+ nodeType: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "nodeType",+ "reason",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unresolved-template",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "ignored-template-prop",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ propName: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ enum: [+ "unknown",+ "incompatible",+ "design-only",+ "stale",+ ],+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ "propName",+ "reason",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "stale-revision",+ },+ severity: {+ type: "string",+ const: "error",+ },+ expectedRevision: {+ type: "string",+ minLength: 1,+ },+ actualRevision: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "expectedRevision",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "changed-binding",+ },+ severity: {+ type: "string",+ const: "error",+ },+ loadedAssetId: {+ type: "string",+ minLength: 1,+ },+ resolvedAssetId: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "loadedAssetId",+ "resolvedAssetId",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "pending-writes",+ },+ severity: {+ type: "string",+ const: "error",+ },+ pendingMutationCount: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "pendingMutationCount",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "authorization-failed",+ },+ severity: {+ type: "string",+ const: "error",+ },+ operation: {+ type: "string",+ enum: ["read", "write"],+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "operation",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "partial-recovery",+ },+ severity: {+ type: "string",+ const: "error",+ },+ completedStorageRoots: {+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ },+ failedStorageRoots: {+ minItems: 1,+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "completedStorageRoots",+ "failedStorageRoots",+ ],+ additionalProperties: false,+ },+ ],+ },+ },+ capabilities: {+ type: "object",+ properties: {+ canConnect: {+ type: "boolean",+ },+ canSwitch: {+ type: "boolean",+ },+ canDisconnectWithCopy: {+ type: "boolean",+ },+ canEdit: {+ type: "boolean",+ },+ canRetry: {+ type: "boolean",+ },+ canReloadRemote: {+ type: "boolean",+ },+ canCopyUnsavedSource: {+ type: "boolean",+ },+ },+ required: [+ "canConnect",+ "canSwitch",+ "canDisconnectWithCopy",+ "canEdit",+ "canRetry",+ "canReloadRemote",+ "canCopyUnsavedSource",+ ],+ },+ repairRoutes: {+ type: "array",+ items: {+ type: "string",+ enum: [+ "open-file",+ "retry",+ "reload-remote",+ "copy-unsaved-mdx",+ "disconnect-with-copy",+ ],+ },+ },+ },+ required: [+ "blockInstanceId",+ "renderScope",+ "sessionStatus",+ "pending",+ "diagnostics",+ "capabilities",+ "repairRoutes",+ ],+ },+ localMdx: {+ type: "string",+ },+ changedAsset: {+ type: "boolean",+ },+ },+ required: ["status", "source", "changedAsset"],+ },+ readNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ writeNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ invalidatesNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ retryOnConflict: false,+ requiresAssets: true,+ },+ {+ id: "contentBlocks.migrateTemplateReferences",+ command: "migrate-content-block-template-references",+ client: "migrateContentBlockTemplateReferences",+ permit: "edit",+ kind: "application",+ inputSchema: {+ type: "object",+ properties: {+ templateInstanceId: {+ type: "string",+ minLength: 1,+ },+ migration: {+ oneOf: [+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "rename",+ },+ to: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["type", "to"],+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "remove",+ },+ },+ required: ["type"],+ },+ ],+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ variables: {+ type: "object",+ propertyNames: {+ type: "string",+ minLength: 1,+ },+ additionalProperties: {+ $ref: "#/$defs/__schema0",+ },+ },+ selectedAssetIds: {+ maxItems: 100,+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ },+ dryRun: {+ type: "boolean",+ },+ confirmationToken: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["templateInstanceId", "migration", "renderScope"],+ $defs: {+ __schema0: {+ anyOf: [+ {+ type: "string",+ },+ {+ type: "number",+ },+ {+ type: "boolean",+ },+ {+ type: "null",+ },+ {+ type: "array",+ items: {+ $ref: "#/$defs/__schema0",+ },+ },+ {+ type: "object",+ propertyNames: {+ type: "string",+ },+ additionalProperties: {+ $ref: "#/$defs/__schema0",+ },+ },+ ],+ },+ },+ },+ outputSchema: {+ type: "object",+ properties: {+ status: {+ type: "string",+ enum: ["complete", "partial", "blocked", "confirmation-required"],+ },+ code: {+ type: "string",+ },+ message: {+ type: "string",+ },+ discoveryComplete: {+ type: "boolean",+ },+ updateCount: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ omissionCount: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ changedAsset: {+ type: "boolean",+ },+ files: {+ type: "array",+ items: {+ type: "object",+ properties: {+ assetId: {+ type: "string",+ },+ revision: {+ type: "string",+ },+ contentRef: {+ type: "string",+ },+ changed: {+ type: "boolean",+ },+ status: {+ type: "string",+ enum: ["updated", "unchanged", "failed"],+ },+ updateCount: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ omissionCount: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ diagnostics: {+ type: "array",+ items: {+ type: "object",+ properties: {+ code: {+ type: "string",+ },+ message: {+ type: "string",+ },+ },+ required: ["code", "message"],+ additionalProperties: {},+ },+ },+ },+ required: [+ "assetId",+ "contentRef",+ "updateCount",+ "omissionCount",+ "diagnostics",+ ],+ },+ },+ diagnostics: {+ type: "array",+ items: {+ type: "object",+ properties: {+ code: {+ type: "string",+ },+ message: {+ type: "string",+ },+ },+ required: ["code", "message"],+ additionalProperties: {},+ },+ },+ confirmation: {+ type: "object",+ properties: {+ token: {+ type: "string",+ },+ expiresAt: {+ type: "string",+ },+ },+ required: ["token", "expiresAt"],+ },+ },+ required: [+ "status",+ "discoveryComplete",+ "updateCount",+ "omissionCount",+ "changedAsset",+ "files",+ ],+ },+ readNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ writeNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ invalidatesNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ retryOnConflict: false,+ requiresAssets: true,+ },+ {+ id: "contentBlocks.semanticEdit",+ command: "edit-content-block-source",+ client: "editContentBlockSource",+ permit: "edit",+ kind: "application",+ inputSchema: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ variables: {+ type: "object",+ propertyNames: {+ type: "string",+ minLength: 1,+ },+ additionalProperties: {+ $ref: "#/$defs/__schema0",+ },+ },+ operationId: {+ type: "string",+ minLength: 1,+ },+ input: {+ $ref: "#/$defs/__schema1",+ },+ dryRun: {+ type: "boolean",+ },+ },+ required: ["blockInstanceId", "renderScope", "operationId", "input"],+ $defs: {+ __schema0: {+ anyOf: [+ {+ type: "string",+ },+ {+ type: "number",+ },+ {+ type: "boolean",+ },+ {+ type: "null",+ },+ {+ type: "array",+ items: {+ $ref: "#/$defs/__schema0",+ },+ },+ {+ type: "object",+ propertyNames: {+ type: "string",+ },+ additionalProperties: {+ $ref: "#/$defs/__schema0",+ },+ },+ ],+ },+ __schema1: {+ anyOf: [+ {+ type: "string",+ },+ {+ type: "number",+ },+ {+ type: "boolean",+ },+ {+ type: "null",+ },+ {+ type: "array",+ items: {+ $ref: "#/$defs/__schema1",+ },+ },+ {+ type: "object",+ propertyNames: {+ type: "string",+ },+ additionalProperties: {+ $ref: "#/$defs/__schema1",+ },+ },+ ],+ },+ },+ },+ outputSchema: {+ type: "object",+ properties: {+ status: {+ type: "string",+ enum: ["complete", "partial", "blocked"],+ },+ code: {+ type: "string",+ },+ message: {+ type: "string",+ },+ result: {+ type: "object",+ properties: {+ result: {+ type: "object",+ properties: {},+ additionalProperties: {},+ required: [],+ },+ noop: {+ type: "boolean",+ },+ },+ required: ["result", "noop"],+ },+ changedAsset: {+ type: "boolean",+ },+ persistence: {+ type: "object",+ properties: {+ status: {+ type: "string",+ enum: ["complete", "partial", "failed"],+ },+ steps: {+ type: "array",+ items: {+ type: "object",+ properties: {},+ additionalProperties: {},+ required: [],+ },+ },+ retry: {+ type: "object",+ properties: {+ replan: {+ type: "boolean",+ const: true,+ },+ roots: {+ type: "array",+ items: {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ revision: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ format: {+ type: "string",+ const: "mdx",+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "assetId",+ "revision",+ "contentRef",+ "format",+ "renderScope",+ ],+ additionalProperties: false,+ },+ },+ project: {+ type: "boolean",+ },+ },+ required: ["replan", "roots", "project"],+ },+ },+ required: ["status", "steps", "retry"],+ },+ },+ required: ["status", "changedAsset"],+ },+ readNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ writeNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ invalidatesNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ retryOnConflict: false,+ requiresAssets: true,+ },+ {+ id: "pages.list",+ command: "list-pages",+ client: "listPages",+ kind: "read",+ inputSchema: {+ type: "object",+ properties: {+ cursor: {+ type: "string",+ },+ limit: {+ type: "integer",+ minimum: 1,+ maximum: 200,+ },+ verbose: {+ description:+ "Expand the same result with complete records and diagnostics. Omit for compact output.",+ type: "boolean",+ },+ },+ required: [],+ },+ outputSchema: {+ type: "object",+ properties: {+ pages: {+ type: "array",+ items: {+ type: "object",+ properties: {+ id: {+ type: "string",+ },+ name: {+ type: "string",+ },+ path: {+ type: "string",+ },+ localPath: {+ type: "string",+ },+ title: {+ type: "string",+ },+ rootInstanceId: {+ type: "string",+ },+ parentFolderId: {+ type: "string",+ },+ isHome: {+ type: "boolean",+ },+ isDraft: {+ description:+ "True when the page is a draft. Missing or false means the page is publishable.",+ type: "boolean",+ },+ },+ required: [+ "id",+ "name",+ "path",+ "localPath",+ "title",+ "rootInstanceId",+ "isHome",+ ],+ additionalProperties: {},+ },+ },+ detail: {+ type: "string",+ enum: ["compact", "verbose"],+ },+ total: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ returnedCount: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ nextCursor: {+ anyOf: [+ {+ type: "string",+ },+ {+ type: "null",+ },+ ],+ },+ filters: {+ type: "object",+ properties: {},+ additionalProperties: {},+ required: [],+ },+ },+ required: [+ "pages",+ "detail",+ "total",+ "returnedCount",+ "nextCursor",+ "filters",+ ],+ additionalProperties: {},+ },+ readNamespaces: ["pages"],+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+ },+ {+ id: "pages.get",+ command: "get-page",+ client: "getPage",+ kind: "read",+ inputSchema: {+ type: "object",+ properties: {+ pageId: {+ type: "string",+ },+ },+ required: ["pageId"],+ },+ outputSchema: {+ type: "object",+ properties: {+ id: {+ type: "string",+ },+ name: {+ type: "string",+ },+ path: {+ type: "string",+ },+ localPath: {+ type: "string",+ },+ title: {+ type: "string",+ },+ rootInstanceId: {+ type: "string",+ },+ parentFolderId: {+ type: "string",+ },+ isHome: {+ type: "boolean",+ },+ isDraft: {+ description:+ "True when the page is a draft. Missing or false means the page is publishable.",+ type: "boolean",+ },+ meta: {+ type: "object",+ properties: {+ description: {+ type: "string",+ },+ language: {+ type: "string",+ },+ redirect: {+ type: "string",+ },+ status: {+ type: "string",+ },+ socialImageUrl: {+ type: "string",+ },+ socialImageAssetId: {+ type: "string",+ },+ excludePageFromSearch: {+ type: "boolean",+ },+ documentType: {+ type: "string",+ enum: ["html", "xml", "text"],+ },+ content: {+ type: "string",+ },+ auth: {+ anyOf: [+ {+ type: "object",+ properties: {+ method: {+ type: "string",+ const: "basic",+ },+ login: {+ type: "string",+ },+ password: {+ type: "string",+ },+ },+ required: ["method", "login", "password"],+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "basic",+ },+ login: {+ type: "string",+ },+ password: {+ type: "string",+ },+ },+ required: ["type", "login", "password"],+ },+ ],+ },+ custom: {+ type: "array",+ items: {+ type: "object",+ properties: {+ property: {+ type: "string",+ },+ content: {+ type: "string",+ },+ },+ required: ["property", "content"],+ additionalProperties: {},+ },+ },+ },+ required: ["documentType"],+ additionalProperties: {},+ },+ },+ required: [+ "id",+ "name",+ "path",+ "localPath",+ "title",+ "rootInstanceId",+ "isHome",+ "meta",+ ],+ additionalProperties: {},+ },+ readNamespaces: ["pages", "instances"],+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+ },+ {+ id: "pages.getByPath",+ command: "get-page-by-path",+ client: "getPageByPath",+ kind: "read",+ inputSchema: {+ type: "object",+ properties: {+ path: {+ type: "string",+ },+ },+ required: ["path"],+ },+ outputSchema: {+ anyOf: [+ {+ type: "object",+ properties: {+ id: {+ type: "string",+ },+ name: {+ type: "string",+ },+ path: {+ type: "string",+ },+ localPath: {+ type: "string",+ },+ title: {+ type: "string",+ },+ rootInstanceId: {+ type: "string",+ },+ parentFolderId: {+ type: "string",+ },+ isHome: {+ type: "boolean",+ },+ isDraft: {+ description:+ "True when the page is a draft. Missing or false means the page is publishable.",+ type: "boolean",+ },+ meta: {+ type: "object",+ properties: {+ description: {+ type: "string",+ },+ language: {+ type: "string",+ },+ redirect: {+ type: "string",+ },+ status: {+ type: "string",+ },+ socialImageUrl: {+ type: "string",+ },+ socialImageAssetId: {+ type: "string",+ },+ excludePageFromSearch: {+ type: "boolean",+ },+ documentType: {+ type: "string",+ enum: ["html", "xml", "text"],+ },+ content: {+ type: "string",+ },+ auth: {+ anyOf: [+ {+ type: "object",+ properties: {+ method: {+ type: "string",+ const: "basic",+ },+ login: {+ type: "string",+ },+ password: {+ type: "string",+ },+ },+ required: ["method", "login", "password"],+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "basic",+ },+ login: {+ type: "string",+ },+ password: {+ type: "string",+ },+ },+ required: ["type", "login", "password"],+ },+ ],+ },+ custom: {+ type: "array",+ items: {+ type: "object",+ properties: {+ property: {+ type: "string",+ },+ content: {+ type: "string",+ },+ },+ required: ["property", "content"],+ additionalProperties: {},+ },+ },+ },+ required: ["documentType"],+ additionalProperties: {},+ },+ requestedPath: {+ type: "string",+ },+ found: {+ type: "boolean",+ },+ exactMatch: {+ type: "boolean",+ },+ matchedPattern: {+ type: "boolean",+ },+ matchedFallback: {+ type: "boolean",+ },+ },+ required: [+ "id",+ "name",+ "path",+ "localPath",+ "title",+ "rootInstanceId",+ "isHome",+ "meta",+ "requestedPath",+ "found",+ "exactMatch",+ "matchedPattern",+ "matchedFallback",+ ],+ additionalProperties: {},+ },+ {+ type: "object",+ properties: {+ requestedPath: {+ type: "string",+ },+ found: {+ type: "boolean",+ },+ exactMatch: {+ type: "boolean",+ },+ matchedPattern: {+ type: "boolean",+ },+ matchedFallback: {+ type: "boolean",+ },+ fallbackPage: {+ type: "object",+ properties: {+ id: {+ type: "string",+ },+ name: {+ type: "string",+ },+ path: {+ type: "string",+ },+ localPath: {+ type: "string",+ },+ title: {+ type: "string",+ },+ rootInstanceId: {+ type: "string",+ },+ parentFolderId: {+ type: "string",+ },+ isHome: {+ type: "boolean",+ },+ isDraft: {+ description:+ "True when the page is a draft. Missing or false means the page is publishable.",+ type: "boolean",+ },+ meta: {+ type: "object",+ properties: {+ description: {+ type: "string",+ },+ language: {+ type: "string",+ },+ redirect: {+ type: "string",+ },+ status: {+ type: "string",+ },+ socialImageUrl: {+ type: "string",+ },+ socialImageAssetId: {+ type: "string",+ },+ excludePageFromSearch: {+ type: "boolean",+ },+ documentType: {+ type: "string",+ enum: ["html", "xml", "text"],+ },+ content: {+ type: "string",+ },+ auth: {+ anyOf: [+ {+ type: "object",+ properties: {+ method: {+ type: "string",+ const: "basic",+ },+ login: {+ type: "string",+ },+ password: {+ type: "string",+ },+ },+ required: ["method", "login", "password"],+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "basic",+ },+ login: {+ type: "string",+ },+ password: {+ type: "string",+ },+ },+ required: ["type", "login", "password"],+ },+ ],+ },+ custom: {+ type: "array",+ items: {+ type: "object",+ properties: {+ property: {+ type: "string",+ },+ content: {+ type: "string",+ },+ },+ required: ["property", "content"],+ additionalProperties: {},+ },+ },+ },+ required: ["documentType"],+ additionalProperties: {},+ },+ },+ required: [+ "id",+ "name",+ "path",+ "localPath",+ "title",+ "rootInstanceId",+ "isHome",+ "meta",+ ],+ additionalProperties: {},+ },+ guidance: {+ type: "string",+ },+ },+ required: [+ "requestedPath",+ "found",+ "exactMatch",+ "matchedPattern",+ "matchedFallback",+ "fallbackPage",+ "guidance",+ ],+ additionalProperties: {},+ },+ ],+ },+ readNamespaces: ["pages", "instances"],+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+ },+ {+ id: "pages.create",+ command: "create-page",+ client: "createPage",+ kind: "mutation",+ inputSchema: {+ type: "object",+ properties: {+ name: {+ type: "string",+ minLength: 1,+ },+ path: {+ type: "string",+ description:+ 'Plain page path. For a new non-home page, start with "/", for example "/pricing". Use colon-prefixed dynamic segments such as "/blog/:slug" when one page definition must render many concrete routes; do not create a separate page for every route value. The home page path is the empty string ""; do not use an empty path when creating a new page.',+ },+ title: {+ description:+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',+ type: "string",+ },+ parentFolderId: {+ type: "string",+ },+ meta: {+ type: "object",+ properties: {+ description: {+ description:+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',+ type: "string",+ },+ language: {+ description:+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',+ type: "string",+ },+ redirect: {+ description:+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',+ type: "string",+ },+ socialImageUrl: {+ description:+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',+ type: "string",+ },+ socialImageAssetId: {+ type: "string",+ },+ excludePageFromSearch: {+ anyOf: [+ {+ type: "boolean",+ },+ {+ description:+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',+ type: "string",+ },+ ],+ },+ documentType: {+ type: "string",+ enum: ["html", "xml", "text"],+ },+ content: {+ description:+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',+ type: "string",+ },+ status: {+ anyOf: [+ {+ type: "number",+ },+ {+ type: "string",+ },+ ],+ description:+ "Pass a fixed HTTP status code as a number from 200 through 599, for example 302. For a dynamic status, pass one Webstudio JavaScript expression as a string, for example `system.status`.",+ },+ auth: {+ anyOf: [+ {+ type: "object",+ properties: {+ method: {+ type: "string",+ const: "basic",+ },+ login: {+ type: "string",+ },+ password: {+ type: "string",+ },+ },+ required: ["method", "login", "password"],+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "basic",+ },+ login: {+ type: "string",+ },+ password: {+ type: "string",+ },+ },+ required: ["type", "login", "password"],+ },+ ],+ },+ custom: {+ type: "array",+ items: {+ type: "object",+ properties: {+ property: {+ type: "string",+ },+ content: {+ description:+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',+ type: "string",+ },+ },+ required: ["property", "content"],+ },+ },+ },+ required: [],+ },+ },+ required: ["name", "path"],+ },+ outputSchema: {+ type: "object",+ properties: {+ pageId: {+ type: "string",+ },+ rootInstanceId: {+ type: "string",+ },+ },+ required: ["pageId", "rootInstanceId"],+ additionalProperties: {},+ },+ readNamespaces: ["pages", "instances", "dataSources"],+ writeNamespaces: ["pages", "instances"],+ invalidatesNamespaces: ["pages", "instances"],+ retryOnConflict: false,+ },+ {+ id: "pages.update",+ command: "update-page",+ client: "updatePage",+ kind: "mutation",+ inputSchema: {+ type: "object",+ properties: {+ pageId: {+ type: "string",+ },+ values: {+ type: "object",+ properties: {+ name: {+ type: "string",+ minLength: 1,+ },+ path: {+ anyOf: [+ {+ type: "string",+ },+ {+ type: "string",+ },+ ],+ description:+ 'Plain page path. For a new non-home page, start with "/", for example "/pricing". Use colon-prefixed dynamic segments such as "/blog/:slug" when one page definition must render many concrete routes; do not create a separate page for every route value. The home page path is the empty string ""; do not use an empty path when creating a new page.',+ },+ title: {+ description:+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',+ type: "string",+ },+ isDraft: {+ type: "boolean",+ description:+ "Set true to mark the page as draft. Draft pages remain editable and previewable in Builder but are omitted from every publish target, including staging, and from sitemap output. Set false to stage the page for a future publish; this does not deploy the site. The home page and /* catch-all page cannot be drafts.",+ },+ parentFolderId: {+ type: "string",+ },+ meta: {+ type: "object",+ properties: {+ description: {+ description:+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',+ type: "string",+ },+ language: {+ description:+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',+ type: "string",+ },+ redirect: {+ description:+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',+ type: "string",+ },+ socialImageUrl: {+ description:+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',+ type: "string",+ },+ socialImageAssetId: {+ type: "string",+ },+ excludePageFromSearch: {+ anyOf: [+ {+ type: "boolean",+ },+ {+ description:+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',+ type: "string",+ },+ ],+ },+ documentType: {+ type: "string",+ enum: ["html", "xml", "text"],+ },+ content: {+ description:+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',+ type: "string",+ },+ status: {+ anyOf: [+ {+ type: "number",+ },+ {+ type: "string",+ },+ ],+ description:+ "Pass a fixed HTTP status code as a number from 200 through 599, for example 302. For a dynamic status, pass one Webstudio JavaScript expression as a string, for example `system.status`.",+ },+ auth: {+ anyOf: [+ {+ type: "object",+ properties: {+ method: {+ type: "string",+ const: "basic",+ },+ login: {+ type: "string",+ },+ password: {+ type: "string",+ },+ },+ required: ["method", "login", "password"],+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "basic",+ },+ login: {+ type: "string",+ },+ password: {+ type: "string",+ },+ },+ required: ["type", "login", "password"],+ },+ ],+ },+ custom: {+ type: "array",+ items: {+ type: "object",+ properties: {+ property: {+ type: "string",+ },+ content: {+ description:+ 'Plain fixed text is accepted, for example "Plans for teams". For computed values, pass one Webstudio JavaScript expression such as `pageTitle ?? "Plans for teams"`. Read webstudio://project/expressions for syntax and scope rules.',+ type: "string",+ },+ },+ required: ["property", "content"],+ },+ },+ },+ required: [],+ },+ },+ required: [],+ },+ },+ required: ["pageId", "values"],+ },+ outputSchema: {+ type: "object",+ properties: {+ pageId: {+ type: "string",+ },+ },+ required: ["pageId"],+ additionalProperties: {},+ },+ readNamespaces: ["pages", "instances", "dataSources"],+ writeNamespaces: ["pages"],+ invalidatesNamespaces: ["pages"],+ retryOnConflict: true,+ },+ {+ id: "pages.updateSettings",+ command: "update-page-settings",+ client: "updatePageSettings",+ kind: "mutation",+ inputSchema: {+ type: "object",+ properties: {+ pageId: {+ type: "string",+ },+ values: {+ type: "object",+ properties: {+ name: {+ type: "string",+ },+ parentFolderId: {+ type: "string",+ },+ path: {+ type: "string",+ },+ isHomePage: {+ type: "boolean",+ },+ title: {+ type: "string",+ },+ description: {+ type: "string",+ },+ excludePageFromSearch: {+ type: "string",+ },+ language: {+ type: "string",+ },+ socialImageUrl: {+ type: "string",+ },+ socialImageAssetId: {+ type: "string",+ },+ status: {+ type: "string",+ },+ redirect: {+ type: "string",+ },+ documentType: {+ type: "string",+ enum: ["html", "xml", "text"],+ },+ content: {+ type: "string",+ },+ auth: {+ type: "object",+ properties: {+ login: {+ type: "string",+ },+ password: {+ type: "string",+ },+ },+ required: ["login", "password"],+ },+ customMetas: {+ type: "array",+ items: {+ type: "object",+ properties: {+ property: {+ type: "string",+ },+ content: {+ type: "string",+ },+ },+ required: ["property", "content"],+ },+ },+ marketplace: {+ type: "object",+ properties: {+ include: {+ type: "boolean",+ },+ category: {+ type: "string",+ },+ thumbnailAssetId: {+ type: "string",+ },+ },+ required: ["include", "category", "thumbnailAssetId"],+ },+ },+ required: [],+ },+ },+ required: ["pageId", "values"],+ },+ outputSchema: {+ type: "object",+ properties: {+ pageId: {+ type: "string",+ },+ },+ required: ["pageId"],+ additionalProperties: {},+ },+ readNamespaces: ["pages", "instances", "dataSources"],+ writeNamespaces: ["pages"],+ invalidatesNamespaces: ["pages"],+ retryOnConflict: true,+ },+ {+ id: "pages.updateMarketplace",+ command: "update-page-marketplace",+ client: "updatePageMarketplace",+ kind: "mutation",+ inputSchema: {+ type: "object",+ properties: {+ pageId: {+ type: "string",+ },+ marketplace: {+ type: "object",+ properties: {+ include: {+ type: "boolean",+ },+ category: {+ type: "string",+ },+ thumbnailAssetId: {+ type: "string",+ },+ },+ required: [],+ },+ },+ required: ["pageId", "marketplace"],+ },+ outputSchema: {+ type: "object",+ properties: {+ pageId: {+ type: "string",+ },+ marketplace: {+ type: "object",+ properties: {+ include: {+ type: "boolean",+ },+ category: {+ type: "string",+ },+ thumbnailAssetId: {+ type: "string",+ },+ },+ additionalProperties: {},+ required: [],+ },+ },+ required: ["pageId", "marketplace"],+ additionalProperties: {},+ },+ readNamespaces: ["pages"],+ writeNamespaces: ["pages"],+ invalidatesNamespaces: ["pages"],+ retryOnConflict: true,+ },+ {+ id: "pages.savePathInHistory",+ command: "save-page-path-history",+ client: "savePagePathInHistory",+ kind: "mutation",+ inputSchema: {+ type: "object",+ properties: {+ pageId: {+ type: "string",+ },+ path: {+ type: "string",+ },+ },+ required: ["pageId", "path"],+ },+ outputSchema: {+ type: "object",+ properties: {},+ additionalProperties: {},+ required: [],+ },+ readNamespaces: ["pages"],+ writeNamespaces: ["pages"],+ invalidatesNamespaces: ["pages"],+ retryOnConflict: true,+ },+ {+ id: "pages.setHome",+ command: "set-home-page",+ client: "setHomePage",+ kind: "mutation",+ inputSchema: {+ type: "object",+ properties: {+ pageId: {+ type: "string",+ },+ },+ required: ["pageId"],+ },+ outputSchema: {+ type: "object",+ properties: {+ pageId: {+ type: "string",+ },+ },+ required: ["pageId"],+ additionalProperties: {},+ },+ readNamespaces: ["pages"],+ writeNamespaces: ["pages"],+ invalidatesNamespaces: ["pages"],+ retryOnConflict: true,+ },+ {+ id: "projectSettings.get",+ command: "get-project-settings",+ client: "getProjectSettings",+ kind: "read",+ inputSchema: {+ type: "object",+ properties: {+ verbose: {+ description:+ "Expand the same result with complete records and diagnostics. Omit for compact output.",+ type: "boolean",+ },+ },+ required: [],+ },+ outputSchema: {+ type: "object",+ properties: {+ meta: {+ type: "object",+ properties: {+ siteName: {+ type: "string",+ },+ contactEmail: {+ type: "string",+ },+ faviconAssetId: {+ type: "string",+ },+ code: {+ type: "string",+ },+ agentInstructions: {+ type: "string",+ },+ auth: {+ type: "string",+ },+ },+ additionalProperties: {},+ required: [],+ },+ compiler: {+ type: "object",+ properties: {+ atomicStyles: {+ type: "boolean",+ },+ },+ additionalProperties: {},+ required: [],+ },+ redirects: {+ type: "array",+ items: {+ type: "object",+ properties: {+ old: {+ type: "string",+ },+ new: {+ type: "string",+ minLength: 1,+ },+ status: {+ type: "string",+ enum: ["301", "302"],+ },+ },+ required: ["old", "new"],+ additionalProperties: {},+ },+ },+ },+ required: ["meta", "compiler"],+ additionalProperties: {},+ },+ readNamespaces: ["pages", "projectSettings"],+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+ },+ {+ id: "projectSettings.update",+ command: "update-project-settings",+ client: "updateProjectSettings",+ kind: "mutation",+ inputSchema: {+ type: "object",+ properties: {+ meta: {+ type: "object",+ properties: {+ siteName: {+ anyOf: [+ {+ type: "string",+ },+ {+ type: "null",+ },+ ],+ },+ contactEmail: {+ anyOf: [+ {+ type: "string",+ },+ {+ type: "null",+ },+ ],+ },+ faviconAssetId: {+ anyOf: [+ {+ type: "string",+ },+ {+ type: "null",+ },+ ],+ },+ code: {+ anyOf: [+ {+ type: "string",+ },+ {+ type: "null",+ },+ ],+ },+ agentInstructions: {+ anyOf: [+ {+ type: "string",+ },+ {+ type: "null",+ },+ ],+ },+ auth: {+ anyOf: [+ {+ type: "string",+ },+ {+ type: "null",+ },+ ],+ },+ },+ additionalProperties: false,+ required: [],+ },+ compiler: {+ type: "object",+ properties: {+ atomicStyles: {+ anyOf: [+ {+ type: "boolean",+ },+ {+ type: "null",+ },+ ],+ },+ },+ additionalProperties: false,+ required: [],+ },+ },+ additionalProperties: false,+ description:+ "Update at least one supported project meta or compiler setting. Null removes a setting.",+ required: [],+ },+ outputSchema: {+ type: "object",+ properties: {+ updated: {+ type: "boolean",+ },+ },+ required: ["updated"],+ additionalProperties: {},+ },+ readNamespaces: ["projectSettings"],+ writeNamespaces: ["projectSettings"],+ invalidatesNamespaces: ["projectSettings"],+ retryOnConflict: true,+ },{id: "projectSettings.getMarketplaceProduct",command: "get-marketplace-product",@@ -46016,6 +55488,36 @@ export const runtimeOperationContractData = [minimum: 0,maximum: 9007199254740991,},+ templateNameConfirmation: {+ type: "object",+ properties: {+ action: {+ type: "string",+ enum: ["rename", "delete"],+ },+ templates: {+ type: "array",+ items: {+ type: "object",+ properties: {+ instanceId: {+ type: "string",+ },+ oldName: {+ type: "string",+ },+ newName: {+ type: "string",+ },+ },+ required: ["instanceId", "oldName"],+ },+ },+ },+ required: ["action", "templates"],+ description:+ "Retry with the exact confirmation example returned by template_name_change_requires_confirmation after user approval.",+ },},required: ["parentInstanceId", "component"],},@@ -49139,6 +58641,36 @@ export const runtimeOperationContractData = [minimum: 0,maximum: 9007199254740991,},+ templateNameConfirmation: {+ type: "object",+ properties: {+ action: {+ type: "string",+ enum: ["rename", "delete"],+ },+ templates: {+ type: "array",+ items: {+ type: "object",+ properties: {+ instanceId: {+ type: "string",+ },+ oldName: {+ type: "string",+ },+ newName: {+ type: "string",+ },+ },+ required: ["instanceId", "oldName"],+ },+ },+ },+ required: ["action", "templates"],+ description:+ "Retry with the exact confirmation example returned by template_name_change_requires_confirmation after user approval.",+ },},required: ["parentInstanceId", "data", "itemFragment"],$defs: {@@ -50766,58 +60298,174 @@ export const runtimeOperationContractData = [type: "boolean",},},- required: ["type", "value"],+ required: ["type", "value"],+ },+ ],+ },+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "value"],+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "function",+ },+ name: {+ type: "string",+ },+ args: {+ $ref: "#/$defs/__schema0",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "name", "args"],+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "guaranteedInvalid",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type"],+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "invalid",+ },+ value: {+ type: "string",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "value"],+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "unset",+ },+ value: {+ type: "string",+ const: "",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "value"],+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "var",+ },+ value: {+ type: "string",+ },+ fallback: {+ anyOf: [+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "unparsed",+ },+ value: {+ type: "string",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "value"],+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "keyword",+ },+ value: {+ type: "string",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "value"],+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "unit",+ },+ unit: {+ type: "string",+ },+ value: {+ type: "number",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "unit", "value"],+ },+ {+ $ref: "#/$defs/__schema1",+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "rgb",+ },+ r: {+ type: "number",+ },+ g: {+ type: "number",+ },+ b: {+ type: "number",+ },+ alpha: {+ type: "number",+ },+ hidden: {+ type: "boolean",+ },},- ],- },- },- hidden: {- type: "boolean",- },- },- required: ["type", "value"],- },- {- type: "object",- properties: {- type: {- type: "string",- const: "function",- },- name: {- type: "string",- },- args: {- $ref: "#/$defs/__schema0",- },- hidden: {- type: "boolean",- },- },- required: ["type", "name", "args"],- },- {- type: "object",- properties: {- type: {- type: "string",- const: "guaranteedInvalid",- },- hidden: {- type: "boolean",- },- },- required: ["type"],- },- {- type: "object",- properties: {- type: {- type: "string",- const: "invalid",- },- value: {- type: "string",+ required: ["type", "r", "g", "b", "alpha"],+ },+ ],},hidden: {type: "boolean",@@ -50830,62 +60478,391 @@ export const runtimeOperationContractData = [properties: {type: {type: "string",- const: "unset",- },- value: {- type: "string",- const: "",+ const: "shadow",},hidden: {type: "boolean",},- },- required: ["type", "value"],- },- {- type: "object",- properties: {- type: {- type: "string",- const: "var",+ position: {+ anyOf: [+ {+ type: "string",+ const: "inset",+ },+ {+ type: "string",+ const: "outset",+ },+ ],},- value: {- type: "string",+ offsetX: {+ anyOf: [+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "unit",+ },+ unit: {+ type: "string",+ },+ value: {+ type: "number",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "unit", "value"],+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "var",+ },+ value: {+ type: "string",+ },+ fallback: {+ anyOf: [+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "unparsed",+ },+ value: {+ type: "string",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "value"],+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "keyword",+ },+ value: {+ type: "string",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "value"],+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "unit",+ },+ unit: {+ type: "string",+ },+ value: {+ type: "number",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "unit", "value"],+ },+ {+ $ref: "#/$defs/__schema1",+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "rgb",+ },+ r: {+ type: "number",+ },+ g: {+ type: "number",+ },+ b: {+ type: "number",+ },+ alpha: {+ type: "number",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "r", "g", "b", "alpha"],+ },+ ],+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "value"],+ },+ ],},- fallback: {+ offsetY: {anyOf: [{type: "object",properties: {type: {type: "string",- const: "unparsed",+ const: "unit",+ },+ unit: {+ type: "string",+ },+ value: {+ type: "number",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "unit", "value"],+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "var",},value: {type: "string",},+ fallback: {+ anyOf: [+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "unparsed",+ },+ value: {+ type: "string",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "value"],+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "keyword",+ },+ value: {+ type: "string",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "value"],+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "unit",+ },+ unit: {+ type: "string",+ },+ value: {+ type: "number",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "unit", "value"],+ },+ {+ $ref: "#/$defs/__schema1",+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "rgb",+ },+ r: {+ type: "number",+ },+ g: {+ type: "number",+ },+ b: {+ type: "number",+ },+ alpha: {+ type: "number",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "r", "g", "b", "alpha"],+ },+ ],+ },hidden: {type: "boolean",},},required: ["type", "value"],},+ ],+ },+ blur: {+ anyOf: [{type: "object",properties: {type: {type: "string",- const: "keyword",+ const: "unit",+ },+ unit: {+ type: "string",+ },+ value: {+ type: "number",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "unit", "value"],+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "var",},value: {type: "string",},+ fallback: {+ anyOf: [+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "unparsed",+ },+ value: {+ type: "string",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "value"],+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "keyword",+ },+ value: {+ type: "string",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "value"],+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "unit",+ },+ unit: {+ type: "string",+ },+ value: {+ type: "number",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "unit", "value"],+ },+ {+ $ref: "#/$defs/__schema1",+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "rgb",+ },+ r: {+ type: "number",+ },+ g: {+ type: "number",+ },+ b: {+ type: "number",+ },+ alpha: {+ type: "number",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "r", "g", "b", "alpha"],+ },+ ],+ },hidden: {type: "boolean",},},required: ["type", "value"],},+ ],+ },+ spread: {+ anyOf: [{type: "object",properties: {@@ -50903,8 +60880,111 @@ export const runtimeOperationContractData = [type: "boolean",},},- required: ["type", "unit", "value"],+ required: ["type", "unit", "value"],+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "var",+ },+ value: {+ type: "string",+ },+ fallback: {+ anyOf: [+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "unparsed",+ },+ value: {+ type: "string",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "value"],+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "keyword",+ },+ value: {+ type: "string",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "value"],+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "unit",+ },+ unit: {+ type: "string",+ },+ value: {+ type: "number",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "unit", "value"],+ },+ {+ $ref: "#/$defs/__schema1",+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "rgb",+ },+ r: {+ type: "number",+ },+ g: {+ type: "number",+ },+ b: {+ type: "number",+ },+ alpha: {+ type: "number",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "r", "g", "b", "alpha"],+ },+ ],+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "value"],},+ ],+ },+ color: {+ anyOf: [{$ref: "#/$defs/__schema1",},@@ -50933,56 +61013,21 @@ export const runtimeOperationContractData = [},required: ["type", "r", "g", "b", "alpha"],},- ],- },- hidden: {- type: "boolean",- },- },- required: ["type", "value"],- },- {- type: "object",- properties: {- type: {- type: "string",- const: "shadow",- },- hidden: {- type: "boolean",- },- position: {- anyOf: [- {- type: "string",- const: "inset",- },- {- type: "string",- const: "outset",- },- ],- },- offsetX: {- anyOf: [{type: "object",properties: {type: {type: "string",- const: "unit",- },- unit: {- type: "string",+ const: "keyword",},value: {- type: "number",+ type: "string",},hidden: {type: "boolean",},},- required: ["type", "unit", "value"],+ required: ["type", "value"],},{type: "object",@@ -51085,819 +61130,1294 @@ export const runtimeOperationContractData = [},],},- offsetY: {- anyOf: [- {- type: "object",- properties: {- type: {- type: "string",- const: "unit",+ },+ required: ["type", "position", "offsetX", "offsetY"],+ },+ ],+ },+ __schema1: {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "color",+ },+ colorSpace: {+ anyOf: [+ {+ type: "string",+ const: "hex",+ },+ {+ type: "string",+ const: "srgb",+ },+ {+ type: "string",+ const: "p3",+ },+ {+ type: "string",+ const: "srgb-linear",+ },+ {+ type: "string",+ const: "hsl",+ },+ {+ type: "string",+ const: "hwb",+ },+ {+ type: "string",+ const: "lab",+ },+ {+ type: "string",+ const: "lch",+ },+ {+ type: "string",+ const: "oklab",+ },+ {+ type: "string",+ const: "oklch",+ },+ {+ type: "string",+ const: "a98rgb",+ },+ {+ type: "string",+ const: "prophoto",+ },+ {+ type: "string",+ const: "rec2020",+ },+ {+ type: "string",+ const: "xyz-d65",+ },+ {+ type: "string",+ const: "xyz-d50",+ },+ ],+ },+ components: {+ type: "array",+ prefixItems: [+ {+ type: "number",+ },+ {+ type: "number",+ },+ {+ type: "number",+ },+ ],+ minItems: 3,+ maxItems: 3,+ },+ alpha: {+ anyOf: [+ {+ type: "number",+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "var",+ },+ value: {+ type: "string",+ },+ fallback: {+ anyOf: [+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "unparsed",+ },+ value: {+ type: "string",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "value"],},- unit: {- type: "string",+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "keyword",+ },+ value: {+ type: "string",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "value"],},- value: {- type: "number",+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "unit",+ },+ unit: {+ type: "string",+ },+ value: {+ type: "number",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "unit", "value"],},- hidden: {- type: "boolean",+ {+ $ref: "#/$defs/__schema1",+ },+ {+ type: "object",+ properties: {+ type: {+ type: "string",+ const: "rgb",+ },+ r: {+ type: "number",+ },+ g: {+ type: "number",+ },+ b: {+ type: "number",+ },+ alpha: {+ type: "number",+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "r", "g", "b", "alpha"],+ },+ ],+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "value"],+ },+ ],+ },+ hidden: {+ type: "boolean",+ },+ },+ required: ["type", "colorSpace", "components", "alpha"],+ },+ },+ },+ outputSchema: {+ type: "object",+ properties: {+ instanceIds: {+ type: "array",+ items: {+ type: "string",+ },+ },+ rootInstanceIds: {+ type: "array",+ items: {+ type: "string",+ },+ },+ removedInstanceIds: {+ type: "array",+ items: {+ type: "string",+ },+ },+ parentInstanceId: {+ type: "string",+ },+ didMergeBreakpointsDueToLimit: {+ type: "boolean",+ const: true,+ },+ collectionInstanceId: {+ type: "string",+ },+ itemRootInstanceId: {+ type: "string",+ },+ itemParameterId: {+ type: "string",+ },+ itemKeyParameterId: {+ type: "string",+ },+ warnings: {+ type: "array",+ items: {+ type: "object",+ properties: {+ severity: {+ type: "string",+ const: "warning",+ },+ code: {+ type: "string",+ },+ path: {+ type: "array",+ items: {+ type: "string",+ },+ },+ message: {+ type: "string",+ },+ range: {+ type: "object",+ properties: {+ from: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ to: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["from", "to"],+ },+ remediation: {+ type: "string",+ },+ instanceId: {+ type: "string",+ },+ resourceId: {+ type: "string",+ },+ },+ required: [+ "severity",+ "code",+ "path",+ "message",+ "range",+ "remediation",+ ],+ },+ },+ },+ required: [+ "instanceIds",+ "rootInstanceIds",+ "removedInstanceIds",+ "parentInstanceId",+ "collectionInstanceId",+ "itemRootInstanceId",+ "itemParameterId",+ "itemKeyParameterId",+ ],+ },+ readNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ writeNamespaces: [+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ invalidatesNamespaces: [+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSources",+ "styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",+ ],+ retryOnConflict: false,+ requiresAssets: true,+ },+ {+ id: "instances.insertMdxText",+ command: "insert-mdx-text",+ client: "insertMdxText",+ kind: "mutation",+ inputSchema: {+ type: "object",+ properties: {+ parentInstanceId: {+ type: "string",+ minLength: 1,+ },+ source: {+ type: "string",+ minLength: 1,+ },+ mode: {+ type: "string",+ enum: ["append", "prepend", "replace"],+ },+ insertIndex: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ templateNameConfirmation: {+ type: "object",+ properties: {+ action: {+ type: "string",+ enum: ["rename", "delete"],+ },+ templates: {+ type: "array",+ items: {+ type: "object",+ properties: {+ instanceId: {+ type: "string",+ },+ oldName: {+ type: "string",+ },+ newName: {+ type: "string",+ },+ },+ required: ["instanceId", "oldName"],+ },+ },+ },+ required: ["action", "templates"],+ description:+ "Retry with the exact confirmation example returned by template_name_change_requires_confirmation after user approval.",+ },+ },+ required: ["parentInstanceId", "source"],+ },+ outputSchema: {+ type: "object",+ properties: {+ instanceIds: {+ type: "array",+ items: {+ type: "string",+ },+ },+ rootInstanceIds: {+ type: "array",+ items: {+ type: "string",+ },+ },+ removedInstanceIds: {+ type: "array",+ items: {+ type: "string",+ },+ },+ parentInstanceId: {+ type: "string",+ },+ didMergeBreakpointsDueToLimit: {+ type: "boolean",+ const: true,+ },+ diagnostics: {+ type: "array",+ items: {+ oneOf: [+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },},+ required: ["line", "column"],+ additionalProperties: false,},- required: ["type", "unit", "value"],- },- {- type: "object",- properties: {- type: {- type: "string",- const: "var",- },- value: {- type: "string",- },- fallback: {- anyOf: [- {- type: "object",- properties: {- type: {- type: "string",- const: "unparsed",- },- value: {- type: "string",- },- hidden: {- type: "boolean",- },- },- required: ["type", "value"],- },- {- type: "object",- properties: {- type: {- type: "string",- const: "keyword",- },- value: {- type: "string",- },- hidden: {- type: "boolean",- },- },- required: ["type", "value"],- },- {- type: "object",- properties: {- type: {- type: "string",- const: "unit",- },- unit: {- type: "string",- },- value: {- type: "number",- },- hidden: {- type: "boolean",- },- },- required: ["type", "unit", "value"],- },- {- $ref: "#/$defs/__schema1",- },- {- type: "object",- properties: {- type: {- type: "string",- const: "rgb",- },- r: {- type: "number",- },- g: {- type: "number",- },- b: {- type: "number",- },- alpha: {- type: "number",- },- hidden: {- type: "boolean",- },- },- required: ["type", "r", "g", "b", "alpha"],- },- ],- },- hidden: {- type: "boolean",+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },},+ required: ["line", "column"],+ additionalProperties: false,},- required: ["type", "value"],},- ],+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "invalid-mdx",+ },+ severity: {+ type: "string",+ const: "error",+ },+ message: {+ type: "string",+ minLength: 1,+ },},- blur: {- anyOf: [- {- type: "object",- properties: {- type: {- type: "string",- const: "unit",- },- unit: {- type: "string",- },- value: {- type: "number",- },- hidden: {- type: "boolean",+ required: ["blockInstanceId", "code", "severity", "message"],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },},+ required: ["line", "column"],+ additionalProperties: false,},- required: ["type", "unit", "value"],- },- {- type: "object",- properties: {- type: {- type: "string",- const: "var",- },- value: {- type: "string",- },- fallback: {- anyOf: [- {- type: "object",- properties: {- type: {- type: "string",- const: "unparsed",- },- value: {- type: "string",- },- hidden: {- type: "boolean",- },- },- required: ["type", "value"],- },- {- type: "object",- properties: {- type: {- type: "string",- const: "keyword",- },- value: {- type: "string",- },- hidden: {- type: "boolean",- },- },- required: ["type", "value"],- },- {- type: "object",- properties: {- type: {- type: "string",- const: "unit",- },- unit: {- type: "string",- },- value: {- type: "number",- },- hidden: {- type: "boolean",- },- },- required: ["type", "unit", "value"],- },- {- $ref: "#/$defs/__schema1",- },- {- type: "object",- properties: {- type: {- type: "string",- const: "rgb",- },- r: {- type: "number",- },- g: {- type: "number",- },- b: {- type: "number",- },- alpha: {- type: "number",- },- hidden: {- type: "boolean",- },- },- required: ["type", "r", "g", "b", "alpha"],- },- ],- },- hidden: {- type: "boolean",+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },},+ required: ["line", "column"],+ additionalProperties: false,},- required: ["type", "value"],},- ],+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unsafe-mdx",+ },+ severity: {+ type: "string",+ const: "error",+ },+ nodeType: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ minLength: 1,+ },},- spread: {- anyOf: [- {- type: "object",- properties: {- type: {- type: "string",- const: "unit",- },- unit: {- type: "string",- },- value: {- type: "number",+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "nodeType",+ "reason",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },},- hidden: {- type: "boolean",+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },},+ required: ["line", "column"],+ additionalProperties: false,},- required: ["type", "unit", "value"],},- {- type: "object",- properties: {- type: {- type: "string",- const: "var",- },- value: {- type: "string",- },- fallback: {- anyOf: [- {- type: "object",- properties: {- type: {- type: "string",- const: "unparsed",- },- value: {- type: "string",- },- hidden: {- type: "boolean",- },- },- required: ["type", "value"],- },- {- type: "object",- properties: {- type: {- type: "string",- const: "keyword",- },- value: {- type: "string",- },- hidden: {- type: "boolean",- },- },- required: ["type", "value"],- },- {- type: "object",- properties: {- type: {- type: "string",- const: "unit",- },- unit: {- type: "string",- },- value: {- type: "number",- },- hidden: {- type: "boolean",- },- },- required: ["type", "unit", "value"],- },- {- $ref: "#/$defs/__schema1",- },- {- type: "object",- properties: {- type: {- type: "string",- const: "rgb",- },- r: {- type: "number",- },- g: {- type: "number",- },- b: {- type: "number",- },- alpha: {- type: "number",- },- hidden: {- type: "boolean",- },- },- required: ["type", "r", "g", "b", "alpha"],- },- ],+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "unresolved-template",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },},- hidden: {- type: "boolean",+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },},+ required: ["line", "column"],+ additionalProperties: false,},- required: ["type", "value"],},- ],+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "ignored-template-prop",+ },+ severity: {+ type: "string",+ const: "warning",+ },+ templateName: {+ type: "string",+ minLength: 1,+ },+ propName: {+ type: "string",+ minLength: 1,+ },+ reason: {+ type: "string",+ enum: ["unknown", "incompatible", "design-only", "stale"],+ },},- color: {- anyOf: [- {- $ref: "#/$defs/__schema1",- },- {- type: "object",- properties: {- type: {- type: "string",- const: "rgb",- },- r: {- type: "number",- },- g: {- type: "number",- },- b: {- type: "number",- },- alpha: {- type: "number",- },- hidden: {- type: "boolean",+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "templateName",+ "propName",+ "reason",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },},+ required: ["line", "column"],+ additionalProperties: false,},- required: ["type", "r", "g", "b", "alpha"],- },- {- type: "object",- properties: {- type: {- type: "string",- const: "keyword",- },- value: {- type: "string",- },- hidden: {- type: "boolean",+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },},+ required: ["line", "column"],+ additionalProperties: false,},- required: ["type", "value"],},- {- type: "object",- properties: {- type: {- type: "string",- const: "var",- },- value: {- type: "string",- },- fallback: {- anyOf: [- {- type: "object",- properties: {- type: {- type: "string",- const: "unparsed",- },- value: {- type: "string",- },- hidden: {- type: "boolean",- },- },- required: ["type", "value"],- },- {- type: "object",- properties: {- type: {- type: "string",- const: "keyword",- },- value: {- type: "string",- },- hidden: {- type: "boolean",- },- },- required: ["type", "value"],- },- {- type: "object",- properties: {- type: {- type: "string",- const: "unit",- },- unit: {- type: "string",- },- value: {- type: "number",- },- hidden: {- type: "boolean",- },- },- required: ["type", "unit", "value"],- },- {- $ref: "#/$defs/__schema1",- },- {- type: "object",- properties: {- type: {- type: "string",- const: "rgb",- },- r: {- type: "number",- },- g: {- type: "number",- },- b: {- type: "number",- },- alpha: {- type: "number",- },- hidden: {- type: "boolean",- },- },- required: ["type", "r", "g", "b", "alpha"],- },- ],+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "stale-revision",+ },+ severity: {+ type: "string",+ const: "error",+ },+ expectedRevision: {+ type: "string",+ minLength: 1,+ },+ actualRevision: {+ type: "string",+ minLength: 1,+ },+ },+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "expectedRevision",+ ],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },},- hidden: {- type: "boolean",+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },},+ required: ["line", "column"],+ additionalProperties: false,},- required: ["type", "value"],},- ],+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "changed-binding",+ },+ severity: {+ type: "string",+ const: "error",+ },+ loadedAssetId: {+ type: "string",+ minLength: 1,+ },+ resolvedAssetId: {+ type: "string",+ minLength: 1,+ },},+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "loadedAssetId",+ "resolvedAssetId",+ ],+ additionalProperties: false,},- required: ["type", "position", "offsetX", "offsetY"],- },- ],- },- __schema1: {- type: "object",- properties: {- type: {- type: "string",- const: "color",- },- colorSpace: {- anyOf: [- {- type: "string",- const: "hex",- },- {- type: "string",- const: "srgb",- },- {- type: "string",- const: "p3",- },- {- type: "string",- const: "srgb-linear",- },- {- type: "string",- const: "hsl",- },- {- type: "string",- const: "hwb",- },- {- type: "string",- const: "lab",- },- {- type: "string",- const: "lch",- },- {- type: "string",- const: "oklab",- },- {- type: "string",- const: "oklch",- },- {- type: "string",- const: "a98rgb",- },- {- type: "string",- const: "prophoto",- },- {- type: "string",- const: "rec2020",- },- {- type: "string",- const: "xyz-d65",- },- {- type: "string",- const: "xyz-d50",- },- ],- },- components: {- type: "array",- prefixItems: [- {- type: "number",- },- {- type: "number",- },- {- type: "number",- },- ],- minItems: 3,- maxItems: 3,- },- alpha: {- anyOf: [- {- type: "number",- },- {- type: "object",- properties: {- type: {- type: "string",- const: "var",- },- value: {- type: "string",- },- fallback: {- anyOf: [- {- type: "object",- properties: {- type: {- type: "string",- const: "unparsed",- },- value: {- type: "string",- },- hidden: {- type: "boolean",- },- },- required: ["type", "value"],- },- {- type: "object",- properties: {- type: {- type: "string",- const: "keyword",- },- value: {- type: "string",- },- hidden: {- type: "boolean",- },+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,},- required: ["type", "value"],- },- {- type: "object",- properties: {- type: {- type: "string",- const: "unit",- },- unit: {- type: "string",- },- value: {- type: "number",- },- hidden: {- type: "boolean",- },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,},- required: ["type", "unit", "value"],- },- {- $ref: "#/$defs/__schema1",},- {- type: "object",- properties: {- type: {- type: "string",- const: "rgb",- },- r: {- type: "number",- },- g: {- type: "number",- },- b: {- type: "number",- },- alpha: {- type: "number",- },- hidden: {- type: "boolean",- },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,},- required: ["type", "r", "g", "b", "alpha"],},- ],- },- hidden: {- type: "boolean",+ required: ["line", "column"],+ additionalProperties: false,+ },},+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "pending-writes",+ },+ severity: {+ type: "string",+ const: "error",+ },+ pendingMutationCount: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,},- required: ["type", "value"],},- ],- },- hidden: {- type: "boolean",- },- },- required: ["type", "colorSpace", "components", "alpha"],- },- },- },- outputSchema: {- type: "object",- properties: {- instanceIds: {- type: "array",- items: {- type: "string",- },- },- rootInstanceIds: {- type: "array",- items: {- type: "string",- },- },- removedInstanceIds: {- type: "array",- items: {- type: "string",- },- },- parentInstanceId: {- type: "string",- },- didMergeBreakpointsDueToLimit: {- type: "boolean",- const: true,- },- collectionInstanceId: {- type: "string",- },- itemRootInstanceId: {- type: "string",- },- itemParameterId: {- type: "string",- },- itemKeyParameterId: {- type: "string",- },- warnings: {- type: "array",- items: {- type: "object",- properties: {- severity: {- type: "string",- const: "warning",- },- code: {- type: "string",+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "pendingMutationCount",+ ],+ additionalProperties: false,},- path: {- type: "array",- items: {- type: "string",+ {+ type: "object",+ properties: {+ blockInstanceId: {+ type: "string",+ minLength: 1,+ },+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "authorization-failed",+ },+ severity: {+ type: "string",+ const: "error",+ },+ operation: {+ type: "string",+ enum: ["read", "write"],+ },},+ required: ["blockInstanceId", "code", "severity", "operation"],+ additionalProperties: false,},- message: {- type: "string",- },- range: {+ {type: "object",properties: {- from: {- type: "integer",- minimum: 0,- maximum: 9007199254740991,+ blockInstanceId: {+ type: "string",+ minLength: 1,},- to: {- type: "integer",- minimum: 0,- maximum: 9007199254740991,+ assetId: {+ type: "string",+ minLength: 1,+ },+ contentRef: {+ type: "string",+ minLength: 1,+ },+ renderScope: {+ type: "string",+ minLength: 1,+ },+ sourceRange: {+ type: "object",+ properties: {+ start: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ end: {+ type: "object",+ properties: {+ line: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ column: {+ type: "integer",+ exclusiveMinimum: 0,+ maximum: 9007199254740991,+ },+ offset: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ },+ required: ["line", "column"],+ additionalProperties: false,+ },+ },+ required: ["start", "end"],+ additionalProperties: false,+ },+ code: {+ type: "string",+ const: "partial-recovery",+ },+ severity: {+ type: "string",+ const: "error",+ },+ completedStorageRoots: {+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ },+ failedStorageRoots: {+ minItems: 1,+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },},},- required: ["from", "to"],- },- remediation: {- type: "string",- },- instanceId: {- type: "string",- },- resourceId: {- type: "string",+ required: [+ "blockInstanceId",+ "code",+ "severity",+ "completedStorageRoots",+ "failedStorageRoots",+ ],+ additionalProperties: false,},- },- required: [- "severity",- "code",- "path",- "message",- "range",- "remediation",],},},@@ -51907,10 +62427,7 @@ export const runtimeOperationContractData = ["rootInstanceIds","removedInstanceIds","parentInstanceId",- "collectionInstanceId",- "itemRootInstanceId",- "itemParameterId",- "itemKeyParameterId",+ "diagnostics",],},readNamespaces: [@@ -54961,6 +65478,36 @@ export const runtimeOperationContractData = [minimum: 0,maximum: 9007199254740991,},+ templateNameConfirmation: {+ type: "object",+ properties: {+ action: {+ type: "string",+ enum: ["rename", "delete"],+ },+ templates: {+ type: "array",+ items: {+ type: "object",+ properties: {+ instanceId: {+ type: "string",+ },+ oldName: {+ type: "string",+ },+ newName: {+ type: "string",+ },+ },+ required: ["instanceId", "oldName"],+ },+ },+ },+ required: ["action", "templates"],+ description:+ "Retry with the exact confirmation example returned by template_name_change_requires_confirmation after user approval.",+ },},required: ["fragment"],$defs: {@@ -58093,6 +68640,36 @@ export const runtimeOperationContractData = [type: "string",minLength: 1,},+ templateNameConfirmation: {+ type: "object",+ properties: {+ action: {+ type: "string",+ enum: ["rename", "delete"],+ },+ templates: {+ type: "array",+ items: {+ type: "object",+ properties: {+ instanceId: {+ type: "string",+ },+ oldName: {+ type: "string",+ },+ newName: {+ type: "string",+ },+ },+ required: ["instanceId", "oldName"],+ },+ },+ },+ required: ["action", "templates"],+ description:+ "Retry with the exact confirmation example returned by template_name_change_requires_confirmation after user approval.",+ },},required: ["instanceSelector", "component"],},@@ -58225,9 +68802,11 @@ export const runtimeOperationContractData = ["props","dataSources","resources",- "styles","styleSources","styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",],writeNamespaces: ["pages",@@ -58235,9 +68814,11 @@ export const runtimeOperationContractData = ["props","dataSources","resources",- "styles","styleSources","styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",],invalidatesNamespaces: ["pages",@@ -58245,11 +68826,14 @@ export const runtimeOperationContractData = ["props","dataSources","resources",- "styles","styleSources","styleSourceSelections",+ "styles",+ "breakpoints",+ "assets",],retryOnConflict: false,+ requiresAssets: true,},{id: "instances.duplicateAfterItself",@@ -58335,6 +68919,36 @@ export const runtimeOperationContractData = [type: "string",},},+ templateNameConfirmation: {+ type: "object",+ properties: {+ action: {+ type: "string",+ enum: ["rename", "delete"],+ },+ templates: {+ type: "array",+ items: {+ type: "object",+ properties: {+ instanceId: {+ type: "string",+ },+ oldName: {+ type: "string",+ },+ newName: {+ type: "string",+ },+ },+ required: ["instanceId", "oldName"],+ },+ },+ },+ required: ["action", "templates"],+ description:+ "Retry with the exact confirmation example returned by template_name_change_requires_confirmation after user approval.",+ },},required: ["instanceIds"],},@@ -58399,6 +69013,36 @@ export const runtimeOperationContractData = [type: "string",},},+ templateNameConfirmation: {+ type: "object",+ properties: {+ action: {+ type: "string",+ enum: ["rename", "delete"],+ },+ templates: {+ type: "array",+ items: {+ type: "object",+ properties: {+ instanceId: {+ type: "string",+ },+ oldName: {+ type: "string",+ },+ newName: {+ type: "string",+ },+ },+ required: ["instanceId", "oldName"],+ },+ },+ },+ required: ["action", "templates"],+ description:+ "Retry with the exact confirmation example returned by template_name_change_requires_confirmation after user approval.",+ },},required: ["instanceSelector"],},@@ -60817,7 +71461,7 @@ export const runtimeOperationContractData = [required: ["propIds"],additionalProperties: {},},- readNamespaces: ["instances", "props", "dataSources"],+ readNamespaces: ["instances", "props", "dataSources", "resources"],writeNamespaces: ["props"],invalidatesNamespaces: ["props"],retryOnConflict: false,@@ -60919,7 +71563,7 @@ export const runtimeOperationContractData = [required: ["changedCount", "matchingPropCount", "truncated", "matches"],additionalProperties: {},},- readNamespaces: ["instances", "props"],+ readNamespaces: ["instances", "props", "dataSources", "resources"],writeNamespaces: ["props"],invalidatesNamespaces: ["props"],retryOnConflict: true,@@ -60966,7 +71610,7 @@ export const runtimeOperationContractData = [required: ["propIds"],additionalProperties: {},},- readNamespaces: ["instances", "props"],+ readNamespaces: ["instances", "props", "dataSources", "resources"],writeNamespaces: ["props", "resources"],invalidatesNamespaces: ["props", "resources"],retryOnConflict: false,@@ -61400,7 +72044,15 @@ export const runtimeOperationContractData = [required: ["instanceId", "childIndex", "mode"],additionalProperties: {},},- readNamespaces: ["instances", "dataSources"],+ readNamespaces: [+ "instances",+ "props",+ "dataSources",+ "styles",+ "styleSources",+ "styleSourceSelections",+ "breakpoints",+ ],writeNamespaces: ["instances"],invalidatesNamespaces: ["instances"],retryOnConflict: true,@@ -61490,7 +72142,16 @@ export const runtimeOperationContractData = [required: ["changedCount", "matchingChildCount", "truncated", "matches"],additionalProperties: {},},- readNamespaces: ["pages", "instances"],+ readNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "styles",+ "styleSources",+ "styleSourceSelections",+ "breakpoints",+ ],writeNamespaces: ["instances"],invalidatesNamespaces: ["instances"],retryOnConflict: true,@@ -61659,7 +72320,15 @@ export const runtimeOperationContractData = [required: ["instanceId", "operation"],additionalProperties: {},},- readNamespaces: ["instances", "dataSources"],+ readNamespaces: [+ "instances",+ "props",+ "dataSources",+ "styles",+ "styleSources",+ "styleSourceSelections",+ "breakpoints",+ ],writeNamespaces: ["instances"],invalidatesNamespaces: ["instances"],retryOnConflict: true,@@ -61792,6 +72461,7 @@ export const runtimeOperationContractData = ["styleSources","styleSourceSelections","styles",+ "breakpoints",],writeNamespaces: ["instances",@@ -61831,6 +72501,36 @@ export const runtimeOperationContractData = [legacyPropName: {type: "string",},+ templateNameConfirmation: {+ type: "object",+ properties: {+ action: {+ type: "string",+ enum: ["rename", "delete"],+ },+ templates: {+ type: "array",+ items: {+ type: "object",+ properties: {+ instanceId: {+ type: "string",+ },+ oldName: {+ type: "string",+ },+ newName: {+ type: "string",+ },+ },+ required: ["instanceId", "oldName"],+ },+ },+ },+ required: ["action", "templates"],+ description:+ "Retry with the exact confirmation example returned by template_name_change_requires_confirmation after user approval.",+ },},required: ["instanceId", "tag"],},@@ -61867,6 +72567,36 @@ export const runtimeOperationContractData = [label: {type: "string",},+ templateNameConfirmation: {+ type: "object",+ properties: {+ action: {+ type: "string",+ enum: ["rename", "delete"],+ },+ templates: {+ type: "array",+ items: {+ type: "object",+ properties: {+ instanceId: {+ type: "string",+ },+ oldName: {+ type: "string",+ },+ newName: {+ type: "string",+ },+ },+ required: ["instanceId", "oldName"],+ },+ },+ },+ required: ["action", "templates"],+ description:+ "Retry with the exact confirmation example returned by template_name_change_requires_confirmation after user approval.",+ },},required: ["instanceId", "label"],},@@ -61886,7 +72616,7 @@ export const runtimeOperationContractData = [required: ["instanceIds", "label"],additionalProperties: {},},- readNamespaces: ["instances"],+ readNamespaces: ["instances", "props"],writeNamespaces: ["instances"],invalidatesNamespaces: ["instances"],retryOnConflict: true,diff --git a/packages/project-build/src/contracts/builder-runtime.ts b/packages/project-build/src/contracts/builder-runtime.tsindex 4d64be1be7..801c7430f8 100644--- a/packages/project-build/src/contracts/builder-runtime.ts+++ b/packages/project-build/src/contracts/builder-runtime.ts@@ -3,7 +3,7 @@ import type { InputJsonSchema } from "@webstudio-is/sdk";import type { BuilderNamespace } from "./namespaces";import type { BuilderApiCapability } from "./permissions";-export type RuntimeOperationKind = "read" | "mutation";+export type RuntimeOperationKind = "read" | "mutation" | "application";export type RuntimeOperationPublicApiPermit = BuilderApiCapability;diff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.tsindex bb379fbf76..43d00a042a 100644--- a/packages/project-build/src/mcp.test.ts+++ b/packages/project-build/src/mcp.test.ts@@ -1043,6 +1043,7 @@ describe("project session mcp adapter", () => {"contentMode","mode","insertIndex",+ "templateNameConfirmation","dryRun",]);const fragmentSchema = insertFragmentTool?.inputSchema.properties?.fragment;@@ -4708,12 +4709,9 @@ describe("project session mcp adapter", () => {}).tools;expect(- designInputGuideTools.every((tool) => {- const keys = Object.keys(tool).join(",");- return tool.name === "update-styles"- ? keys === "name,inputSchema"- : keys === "name";- })+ designInputGuideTools.every(+ (tool) => Object.keys(tool).join(",") === "name"+ )).toBe(true);const getComponentToolNames = (getComponentDetails.structuredContent.data as {@@ -4999,17 +4997,20 @@ describe("project session mcp adapter", () => {expect.objectContaining({ name: "insert-fragment-verified" }),expect.objectContaining({ name: "attach-design-token" }),expect.objectContaining({ name: "verify-page-responsive" }),- expect.objectContaining({- name: "update-styles",- inputSchema: expect.objectContaining({- properties: expect.objectContaining({- updates: expect.objectContaining({ type: "array" }),- }),- }),- }),+ expect.objectContaining({ name: "update-styles" }),]),}));+ expect(+ (+ designInputGuide.structuredContent.data as {+ tools: Array<{ name: string; inputSchema?: unknown }>;+ }+ ).tools.find(({ name }) => name === "update-styles")+ ).not.toHaveProperty("inputSchema");+ expect(designInputGuide.structuredContent.data).not.toHaveProperty(+ "slowOperation"+ );expect(craftGuide.structuredContent.data).toEqual(expect.objectContaining({workflow: expect.arrayContaining([diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.tsindex d84dc9ce55..8c463d691d 100644--- a/packages/project-build/src/mcp.ts+++ b/packages/project-build/src/mcp.ts@@ -652,7 +652,7 @@ const constrainUnconstrainedInputSchemas = <Schema extends InputJsonSchema>(return result as Schema;};-const maxInlineMcpInputSchemaSize = 20_000;+const maxInlineMcpInputSchemaSize = 1_000;const getCompactSchemaProperty = (schema: InputJsonSchema): InputJsonSchema => {const description =@@ -3440,6 +3440,7 @@ const mcpOperationSchemaInlineSizes = new Map<string, number>([["update-assets-resource", 2_500],["validate-asset-query", 2_500],["preview-asset-query", 2_500],+ ["create-page", 15_000],]);const detailedMcpInputSchemas = new WeakMap<@@ -5910,7 +5911,6 @@ const metaGoalGuides = [},] as const;-const metaGuideDetailedInputSchemaTools = new Set(["update-styles"]);const metaGuideExampleTools = new Set(["upload-assets"]);const taskScopes = [@@ -5968,18 +5968,12 @@ const serializeMetaGuideTool = (inputFields: tool.annotations.inputFields,requiredInputFields: tool.annotations.requiredInputFields,mcpExamples: tool.mcpExamples ?? [],- ...(metaGuideDetailedInputSchemaTools.has(tool.name)- ? { inputSchema: getDetailedProjectSessionMcpInputSchema(tool) }- : {}),}: {name: tool.name,...(metaGuideExampleTools.has(tool.name)? { mcpExamples: tool.mcpExamples ?? [] }: {}),- ...(metaGuideDetailedInputSchemaTools.has(tool.name)- ? { inputSchema: getDetailedProjectSessionMcpInputSchema(tool) }- : {}),};const getMetaGuide = (@@ -6055,18 +6049,22 @@ const getMetaGuide = (includeDiff: canDiffScreenshots,}): [],- slowOperation: {- confirmationRequired: true,- operation: "full production preview",- estimatedDuration: "30–60 seconds",- reason:- "Builds complete rendered output and is unnecessary for a focused value correction unless the requested outcome depends on layout or runtime behavior.",- fasterAlternative: {- operation: "targeted route validation",- estimatedDuration: "2–5 seconds",- limitations: "Does not visually inspect layout.",- },- },+ ...(goalGuide === undefined+ ? {+ slowOperation: {+ confirmationRequired: true,+ operation: "full production preview",+ estimatedDuration: "30–60 seconds",+ reason:+ "Builds complete rendered output and is unnecessary for a focused value correction unless the requested outcome depends on layout or runtime behavior.",+ fasterAlternative: {+ operation: "targeted route validation",+ estimatedDuration: "2–5 seconds",+ limitations: "Does not visually inspect layout.",+ },+ },+ }+ : {}),tools: matches.map((tool) =>serializeMetaGuideTool(tool, goalGuide === undefined)),diff --git a/packages/project-build/src/project-session.test.ts b/packages/project-build/src/project-session.test.tsindex a0ce1c6d0f..cc4797767b 100644--- a/packages/project-build/src/project-session.test.ts+++ b/packages/project-build/src/project-session.test.ts@@ -1,5 +1,11 @@-import { describe, expect, test } from "vitest";-import { encodeDataVariableId } from "@webstudio-is/sdk";+import { describe, expect, test, vi } from "vitest";+import {+ blockComponent,+ blockTemplateComponent,+ elementComponent,+ encodeDataVariableId,+ type WebstudioFragment,+} from "@webstudio-is/sdk";import type { BuilderNamespace } from "./contracts/namespaces";import type { BuilderPatchTransaction } from "./contracts/patch";import {@@ -21,12 +27,19 @@ import type {ProjectSessionTransport,} from "./project-session";import { createBuilderStateFromSnapshot } from "./state/adapters";-import { createBuilderStateFreshness } from "./state/freshness";+import {+ createBuilderStateFreshness,+ getBuilderStateNamespaceFreshness,+} from "./state/freshness";import { applyBuilderPatchTransactions } from "./state/patch";import { build } from "./state/fixtures.test-utils";import { parseWebstudioJsxFragment } from "./runtime/jsx";import { executeBuilderRuntimeOperation } from "./runtime/registry";import type { BuilderRuntimeMutation } from "./runtime/mutation";+import type {+ BuilderRuntimeContext,+ ContentStorageApplication,+} from "./runtime/context";const compatibilityVersion = "test-session";const compatibility: ProjectSessionCompatibility = {@@ -214,9 +227,11 @@ const createMutableTransport = (const createSession = ({storage = createStorage(),transport = createTransport(),+ runtimeContext,}: {storage?: ProjectSessionStorage;transport?: ProjectSessionTransport;+ runtimeContext?: BuilderRuntimeContext;} = {}) => {let generatedId = 0;return createProjectSession({@@ -226,6 +241,7 @@ const createSession = ({compatibilityVersion,runtimeContext: {createId: () => `generated-id-${generatedId++}`,+ ...runtimeContext,},});};@@ -816,6 +832,345 @@ describe("project session", () => {).toMatchObject({ component: "ws:collection" });});+ test("routes MCP semantic mutations to exact loaded MDX storage", async () => {+ const state = createSnapshot().state;+ state.instances?.set("instance-root", {+ type: "instance",+ id: "instance-root",+ component: blockComponent,+ children: [{ type: "id", value: "templates" }],+ });+ state.instances?.set("templates", {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [],+ });+ state.instances?.set("project-parent", {+ type: "instance",+ id: "project-parent",+ component: elementComponent,+ tag: "main",+ children: [],+ });+ state.props?.set("content-source", {+ id: "content-source",+ instanceId: "instance-root",+ name: "src",+ type: "asset",+ value: "article",+ });+ const identity = {+ blockInstanceId: "instance-root",+ assetId: "article",+ revision: "sha256:article",+ contentRef: "article-revision.mdx",+ format: "mdx" as const,+ renderScope: "page:/",+ };+ const fragment: WebstudioFragment = {+ children: [{ type: "id", value: "external-heading" }],+ instances: [+ {+ type: "instance",+ id: "external-heading",+ component: elementComponent,+ tag: "h1",+ children: [{ type: "text", value: "Original" }],+ },+ ],+ props: [],+ assets: [],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ };+ const saveStorageChanges = vi.fn(async () => ({+ status: "complete" as const,+ persistence: {+ status: "complete" as const,+ steps: [+ { type: "asset" as const, status: "saved" as const, root: identity },+ ],+ retry: { replan: true as const, roots: [], project: false },+ },+ }));+ const preflightStorageChanges = vi.fn<+ ContentStorageApplication["preflightStorageChanges"]+ >(async () => ({ status: "ready" }));+ const transport = createTransport(createSnapshot({ state }));+ const session = createSession({+ transport,+ storage: createStorage(createPersistedSnapshot({ state })),+ runtimeContext: {+ createId: () => "unused",+ contentStorageApplication: {+ getMaterializedContent: () => [{ identity, fragment }],+ preflightStorageChanges,+ saveStorageChanges,+ },+ },+ });+ await session.initialize();++ const planned = await session.mutate(+ "instances.updateText",+ {+ instanceId: "external-heading",+ childIndex: 0,+ text: "Updated",+ },+ { dryRun: true }+ );+ expect(planned).toMatchObject({ source: "dry-run" });+ expect(planned.state.committed).toBe(false);+ expect(planned.result).not.toHaveProperty("storageChanges");+ expect(saveStorageChanges).not.toHaveBeenCalled();+ expect(preflightStorageChanges).not.toHaveBeenCalled();++ const committed = await session.mutate("instances.updateText", {+ instanceId: "external-heading",+ childIndex: 0,+ text: "Updated",+ });+ expect(committed.state.committed).toBe(true);+ expect(committed.result).toMatchObject({+ persistence: {+ status: "complete",+ steps: [{ type: "asset", status: "saved", root: identity }],+ },+ });+ expect(saveStorageChanges).toHaveBeenCalledTimes(1);+ expect(preflightStorageChanges).toHaveBeenCalledTimes(1);+ expect(transport.commits).toEqual([]);+ expect(state.instances?.has("external-heading")).toBe(false);+ expect(+ getBuilderStateNamespaceFreshness(session.snapshot!.freshness, "assets")+ .status+ ).toBe("stale");++ preflightStorageChanges.mockResolvedValueOnce({+ status: "failed",+ code: "content-source-write-conflict",+ message: "The exact MDX revision changed",+ persistence: {+ status: "failed",+ steps: [+ {+ type: "asset",+ status: "failed",+ root: identity,+ code: "content-source-write-conflict",+ },+ ],+ retry: { replan: true, roots: [identity], project: false },+ },+ });+ const blocked = await session.mutate("instances.updateText", {+ instanceId: "external-heading",+ childIndex: 0,+ text: "Blocked",+ });+ expect(blocked.state.committed).toBe(false);+ expect(blocked.result).toMatchObject({+ persistence: {+ status: "failed",+ steps: [{ type: "asset", status: "failed", root: identity }],+ },+ });+ expect(saveStorageChanges).toHaveBeenCalledTimes(1);+ expect(preflightStorageChanges).toHaveBeenCalledTimes(2);++ const projectCommitted = await session.mutate("instances.setLabel", {+ instanceId: "instance-root",+ label: "Article body",+ });+ expect(projectCommitted.state.committed).toBe(true);+ expect(transport.commits).toHaveLength(1);+ expect(saveStorageChanges).toHaveBeenCalledTimes(1);++ transport.commitPatch = async () => {+ throw new Error("Project version changed");+ };+ const failedMove = await session.mutate("instances.move", {+ moves: [+ {+ instanceId: "external-heading",+ parentInstanceId: "project-parent",+ position: "end",+ },+ ],+ });+ expect(failedMove.state.committed).toBe(false);+ expect(failedMove.result).toMatchObject({+ persistence: {+ status: "failed",+ steps: [+ { type: "project", status: "failed" },+ { type: "asset", status: "not-attempted", root: identity },+ ],+ retry: { replan: true, roots: [identity], project: true },+ },+ });+ expect(failedMove.result).not.toHaveProperty("storageChanges");+ expect(saveStorageChanges).toHaveBeenCalledTimes(1);+ });++ test("commits generated Content Block application operations with the pinned project version", async () => {+ const snapshot = createSnapshot();+ const inspectSource = vi.fn(async ({ blockInstanceId, renderScope }) => ({+ blockInstanceId,+ renderScope,+ sessionStatus: "saved" as const,+ pending: false,+ diagnostics: [],+ capabilities: {+ canConnect: false,+ canSwitch: true,+ canDisconnectWithCopy: true,+ canEdit: true,+ canRetry: false,+ canReloadRemote: false,+ canCopyUnsavedSource: false,+ },+ repairRoutes: ["disconnect-with-copy" as const],+ }));+ const application = {+ getMaterializedContent: () => [],+ preflightStorageChanges: async () => ({ status: "ready" as const }),+ saveStorageChanges: async () => ({+ status: "complete" as const,+ persistence: {+ status: "complete" as const,+ steps: [],+ retry: { replan: true as const, roots: [], project: false },+ },+ }),+ inspectSource,+ recover: async () => ({+ status: "blocked" as const,+ code: "content-source-not-loaded",+ message: "not loaded",+ }),+ applyLifecycle: async (+ input: { action: "connect" | "switch" | "disconnect" },+ execution?: {+ commitProjectPayload?: (+ payload: BuilderPatchTransaction["payload"]+ ) => void | Promise<void>;+ }+ ) => {+ await execution?.commitProjectPayload?.([+ {+ namespace: "instances",+ patches: [+ {+ op: "add",+ path: ["instance-root", "label"],+ value: "Connected content",+ },+ ],+ },+ ]);+ return {+ status: "complete" as const,+ result: {+ action: input.action,+ changesProject: true,+ storageWrites: [],+ diagnostics: [],+ persistenceOrder: "none" as const,+ },+ };+ },+ };+ const transport = createTransport(snapshot);+ const session = createSession({+ transport,+ storage: createStorage(createPersistedSnapshot(snapshot)),+ runtimeContext: {+ createId: () => "application-transaction",+ contentStorageApplication: application,+ },+ });+ await session.initialize();++ const result = await session.mutate("contentBlocks.connectSource", {+ blockInstanceId: "instance-root",+ renderScope: "page:/",+ source: { type: "asset", assetId: "article" },+ authority: "use-file-content",+ });++ expect(result.state.committed).toBe(true);+ expect(result.transaction?.id).toBe("application-transaction");+ expect(session.snapshot?.state.instances?.get("instance-root")?.label).toBe(+ "Connected content"+ );+ expect(transport.commits).toHaveLength(1);+ });++ test("records partial Asset application writes and marks Asset data stale", async () => {+ const snapshot = createSnapshot();+ const session = createSession({+ transport: createTransport(snapshot),+ storage: createStorage(createPersistedSnapshot(snapshot)),+ runtimeContext: {+ createId: () => "application-transaction",+ contentStorageApplication: {+ getMaterializedContent: () => [],+ preflightStorageChanges: async () => ({ status: "ready" as const }),+ saveStorageChanges: async () => ({+ status: "complete" as const,+ persistence: {+ status: "complete" as const,+ steps: [],+ retry: { replan: true as const, roots: [], project: false },+ },+ }),+ migrateTemplateReferences: async () => ({+ status: "partial",+ discoveryComplete: true,+ updateCount: 1,+ omissionCount: 0,+ changedAsset: true,+ files: [+ {+ assetId: "article",+ revision: "revision",+ contentRef: "article.mdx",+ status: "updated",+ updateCount: 1,+ omissionCount: 0,+ diagnostics: [],+ },+ ],+ }),+ },+ },+ });+ await session.initialize();++ const result = await session.mutate(+ "contentBlocks.migrateTemplateReferences",+ {+ templateInstanceId: "template",+ migration: { type: "remove" },+ renderScope: "page:/",+ confirmationToken: "confirmed",+ }+ );++ expect(result.state.committed).toBe(true);+ expect(+ getBuilderStateNamespaceFreshness(session.snapshot!.freshness, "assets")+ .status+ ).toBe("stale");+ });+test("plans and commits one runtime UI integration that survives refresh", async () => {let remote = createSnapshot();const storage = createStorage(createPersistedSnapshot());@@ -1209,7 +1564,7 @@ describe("project session", () => {expect.objectContaining({ code: "CONFLICT_REFRESHED" }),]);expect(transport.loadedNamespaces).toEqual([- ["instances", "props", "dataSources"],+ ["instances", "props", "dataSources", "resources"],]);});diff --git a/packages/project-build/src/project-session.ts b/packages/project-build/src/project-session.tsindex 5445763e53..2e316a80cf 100644--- a/packages/project-build/src/project-session.ts+++ b/packages/project-build/src/project-session.ts@@ -17,6 +17,8 @@ import { projectOutput } from "./runtime/output";import {builderRuntimeContext,type BuilderRuntimeContext,+ type ContentBlockPersistenceResult,+ type ContentBlockPersistenceStep,} from "./runtime/context";import {BuilderRuntimeError,@@ -24,7 +26,11 @@ import {sanitizeValidationDetail,type SemanticValidationIssue,} from "./runtime/errors";-import type { BuilderRuntimeMutation } from "./runtime/mutation";+import {+ getRuntimeMutationPersistenceOrder,+ type BuilderRuntimeMutation,+} from "./runtime/mutation";+import { getContentStorageIdentityKey } from "./runtime/content-storage";import { executeBuilderRuntimeOperation } from "./runtime/registry";import type { BuilderState } from "./state/builder-state";import { getMissingBuilderStateNamespaces } from "./state/builder-state";@@ -705,6 +711,46 @@ export const hasProjectSessionPermit = (return permissions.canAdmin;};+const addProjectPersistenceStep = ({+ persistence,+ step,+ order,+}: {+ persistence: ContentBlockPersistenceResult;+ step: ContentBlockPersistenceStep;+ order: "before" | "after";+}): ContentBlockPersistenceResult => {+ const steps =+ order === "before"+ ? [step, ...persistence.steps]+ : [...persistence.steps, step];+ const hasFailure = steps.some(({ status }) => status === "failed");+ const hasSaved = steps.some(({ status }) => status === "saved");+ return {+ status: hasFailure ? (hasSaved ? "partial" : "failed") : "complete",+ steps,+ retry: {+ ...persistence.retry,+ project: step.type === "project" && step.status !== "saved",+ },+ };+};++const markPersistedAssetChangesStale = (+ snapshot: ProjectSessionSnapshot,+ persistence: ContentBlockPersistenceResult+) =>+ persistence.steps.some(+ ({ type, status }) => type === "asset" && status === "saved"+ )+ ? {+ ...snapshot,+ freshness: markBuilderStateNamespacesStale(snapshot.freshness, [+ "assets",+ ]),+ }+ : snapshot;+export class ProjectSession {#snapshot: ProjectSessionSnapshot | undefined;#revision: string | undefined;@@ -979,6 +1025,9 @@ export class ProjectSession {context: {...this.#options.runtimeContext,projectVersion: snapshot.version,+ materializedContent:+ this.#options.runtimeContext.contentStorageApplication?.getMaterializedContent() ??+ this.#options.runtimeContext.materializedContent,},});return this.createEnvelope({@@ -1256,7 +1305,7 @@ export class ProjectSession {options: ProjectSessionMutationOptions) {const contract = getRuntimeOperationContract(operationId);- if (contract.kind !== "mutation") {+ if (contract.kind === "read") {throw new Error(`Runtime operation "${operationId}" is not a mutation.`);}const requiredNamespaces = mergeNamespaces(@@ -1266,13 +1315,21 @@ export class ProjectSession {const snapshot = await this.ensureNamespaces(requiredNamespaces);try {await this.assertPermit(options.permit);- return await this.commitMutation({- operationId,- input,- options,- contract,- snapshot,- });+ return contract.kind === "application"+ ? await this.commitApplicationOperation({+ operationId,+ input,+ options,+ contract,+ snapshot,+ })+ : await this.commitMutation({+ operationId,+ input,+ options,+ contract,+ snapshot,+ });} catch (error) {this.clearPermissionsAfterAuthorizationError(error);let latestSnapshot = snapshot;@@ -1287,6 +1344,7 @@ export class ProjectSession {"Remote build changed. Required namespaces were refreshed; rerun the operation against the latest snapshot.",});if (+ contract.kind === "mutation" &&contract.retryOnConflict &&options.dryRun !== true &&getCommitConfirmationFailureCode(error) === undefined@@ -1323,6 +1381,135 @@ export class ProjectSession {}}+ async #commitApplicationProjectPayload({+ payload,+ expectedVersion,+ operationId,+ invalidatesNamespaces,+ }: {+ payload: readonly BuilderPatchTransaction["payload"][number][];+ expectedVersion: number;+ operationId: string;+ invalidatesNamespaces: readonly BuilderNamespace[];+ }) {+ const snapshot = this.#snapshot;+ if (snapshot === undefined || snapshot.version !== expectedVersion) {+ throw new BuilderRuntimeError(+ "CONFLICT",+ "Project changed after the Content Block operation was prepared"+ );+ }+ const transaction: BuilderPatchTransaction = {+ id: this.#options.runtimeContext.createId(),+ payload: [...payload],+ };+ const commit = await this.#options.transport.commitPatch({+ projectId: snapshot.projectId,+ buildId: snapshot.buildId,+ baseVersion: expectedVersion,+ transactions: [transaction],+ });+ const applied = applyBuilderPatchTransactions(snapshot.state, [+ transaction,+ ]);+ const updatedNamespaces = [+ ...new Set(payload.map(({ namespace }) => namespace)),+ ];+ const committedSnapshot: ProjectSessionSnapshot = {+ ...snapshot,+ version: commit.version,+ state: applied.state,+ freshness: markBuilderStateNamespacesInvalidated(+ mergeFreshness({+ current: snapshot.freshness,+ state: applied.state,+ namespaces: updatedNamespaces,+ version: commit.version,+ loadedAt: new Date().toISOString(),+ source: "local",+ }),+ invalidatesNamespaces,+ operationId+ ),+ };+ await this.saveSnapshot(committedSnapshot);+ return { version: commit.version, transaction };+ }++ async commitApplicationOperation<+ Result extends Record<string, unknown> = Record<string, unknown>,+ >({+ operationId,+ input,+ options,+ contract,+ snapshot,+ }: {+ operationId: RuntimeOperationId;+ input: unknown;+ options: ProjectSessionMutationOptions;+ contract: RuntimeOperationContract;+ snapshot: ProjectSessionSnapshot;+ }) {+ let transaction: BuilderPatchTransaction | undefined;+ const result = await executeBuilderRuntimeOperation<Result>({+ id: operationId,+ state: snapshot.state,+ input,+ context: {+ ...this.#options.runtimeContext,+ projectVersion: snapshot.version,+ applicationDryRun: options.dryRun,+ commitApplicationProjectPayload: async (commitInput) => {+ const committed =+ await this.#commitApplicationProjectPayload(commitInput);+ transaction = committed.transaction;+ return { version: committed.version };+ },+ },+ });+ const status = result.status;+ const plan = result.plan;+ const changedAsset = result.changedAsset === true;+ const committed =+ options.dryRun !== true &&+ (transaction !== undefined ||+ changedAsset ||+ (status === "complete" &&+ typeof plan === "object" &&+ plan !== null &&+ "storageWrites" in plan &&+ Array.isArray(plan.storageWrites) &&+ plan.storageWrites.length > 0));+ let resultSnapshot = this.#snapshot ?? snapshot;+ if (options.dryRun !== true && changedAsset) {+ resultSnapshot = {+ ...resultSnapshot,+ freshness: markBuilderStateNamespacesStale(resultSnapshot.freshness, [+ "assets",+ ]),+ };+ await this.saveSnapshot(resultSnapshot);+ }+ return this.createEnvelope({+ source: options.dryRun ? "dry-run" : "local",+ result,+ committed,+ contract,+ snapshot: resultSnapshot,+ transaction,+ diagnostics: options.dryRun+ ? [+ {+ level: "info",+ code: "DRY_RUN",+ message: "Application operation was planned and not committed.",+ },+ ]+ : [],+ });+ }+async commitMutation<Result extends Record<string, unknown> = Record<string, unknown>,>({@@ -1349,6 +1536,12 @@ export class ProjectSession {context: {...this.#options.runtimeContext,projectVersion: snapshot.version,+ materializedContent:+ this.#options.runtimeContext.contentStorageApplication?.getMaterializedContent() ??+ this.#options.runtimeContext.materializedContent,+ returnStorageChanges:+ this.#options.runtimeContext.contentStorageApplication !==+ undefined || this.#options.runtimeContext.returnStorageChanges,},});if (mutation.noop) {@@ -1365,10 +1558,11 @@ export class ProjectSession {id: this.#options.runtimeContext.createId(),payload: mutation.payload,};+ let result = mutation.result;if (options.dryRun) {return this.createEnvelope({source: "dry-run",- result: mutation.result,+ result,committed: false,contract,snapshot,@@ -1383,7 +1577,100 @@ export class ProjectSession {],});}- if (hasGeneratedRecordWritePatch(mutation.payload)) {+ const storageChanges = mutation.storageChanges ?? [];+ const application = this.#options.runtimeContext.contentStorageApplication;+ if (storageChanges.length > 0 && application === undefined) {+ return this.createEnvelope({+ source: "local",+ result,+ committed: false,+ contract,+ snapshot,+ diagnostics: [+ ...diagnostics,+ {+ level: "error",+ code: "CONTENT_STORAGE_SESSION_UNAVAILABLE",+ message:+ "The exact MDX Asset revision and render scope are not loaded.",+ },+ ],+ });+ }+ const projectFirst =+ storageChanges.length > 0 &&+ mutation.payload.length > 0 &&+ getRuntimeMutationPersistenceOrder(mutation) === "project-first";+ if (storageChanges.length > 0) {+ const preflight =+ await application!.preflightStorageChanges(storageChanges);+ if (preflight.status === "failed") {+ result = { ...result, persistence: preflight.persistence } as Result;+ return this.createEnvelope({+ source: "local",+ result,+ committed: false,+ contract,+ snapshot,+ diagnostics: [+ ...diagnostics,+ {+ level: "error",+ code: preflight.code,+ message: preflight.message,+ },+ ],+ });+ }+ }+ const saveStorage = () => application!.saveStorageChanges(storageChanges);+ let persistedStorage: ContentBlockPersistenceResult | undefined;+ if (storageChanges.length > 0 && projectFirst === false) {+ const saved = await saveStorage();+ persistedStorage = saved.persistence;+ result = { ...result, persistence: saved.persistence } as Result;+ if (saved.status !== "complete") {+ const resultSnapshot = markPersistedAssetChangesStale(+ snapshot,+ saved.persistence+ );+ if (resultSnapshot !== snapshot) {+ await this.saveSnapshot(resultSnapshot);+ }+ return this.createEnvelope({+ source: "local",+ result,+ committed: saved.status === "partial",+ contract,+ snapshot: resultSnapshot,+ diagnostics: [+ ...diagnostics,+ { level: "error", code: saved.code, message: saved.message },+ ],+ });+ }+ if (mutation.payload.length === 0) {+ const resultSnapshot = markPersistedAssetChangesStale(+ snapshot,+ saved.persistence+ );+ if (resultSnapshot !== snapshot) {+ await this.saveSnapshot(resultSnapshot);+ }+ return this.createEnvelope({+ source: "local",+ result,+ committed: true,+ contract,+ snapshot: resultSnapshot,+ diagnostics,+ });+ }+ }+ if (+ storageChanges.length === 0 &&+ hasGeneratedRecordWritePatch(mutation.payload)+ ) {return await this.executeServerOperation<Result>({id: operationId,@@ -1400,14 +1687,148 @@ export class ProjectSession {baseVersion: snapshot.version,transactions: [transaction],};- const { result: commit, confirmedAfterRetry } =- await commitWithConflictConfirmation({- commit: (input) => this.#options.transport.commitPatch(input),- input: commitInput,+ let commit: ProjectSessionCommitResult;+ let confirmedAfterRetry: boolean;+ try {+ ({ result: commit, confirmedAfterRetry } =+ await commitWithConflictConfirmation({+ commit: (input) => this.#options.transport.commitPatch(input),+ input: commitInput,+ }));+ } catch (error) {+ if (storageChanges.length === 0) {+ throw error;+ }+ if (projectFirst) {+ const roots = [+ ...new Map(+ storageChanges.map(+ (change) =>+ [+ getContentStorageIdentityKey(change.root.identity),+ change.root.identity,+ ] as const+ )+ ).values(),+ ];+ const persistence: ContentBlockPersistenceResult = {+ status: "failed",+ steps: [+ {+ type: "project",+ status: "failed",+ code: "CONTENT_STORAGE_PERSISTENCE_FAILED",+ message:+ error instanceof Error+ ? error.message+ : "Project persistence failed",+ },+ ...roots.map((root) => ({+ type: "asset" as const,+ status: "not-attempted" as const,+ root,+ })),+ ],+ retry: { replan: true, roots, project: true },+ };+ result = { ...result, persistence } as Result;+ return this.createEnvelope({+ source: "local",+ result,+ committed: false,+ contract,+ snapshot,+ diagnostics: [+ ...diagnostics,+ {+ level: "error",+ code: "CONTENT_STORAGE_PERSISTENCE_FAILED",+ message:+ error instanceof Error+ ? error.message+ : "Project persistence failed",+ },+ ],+ });+ }+ const persistence = addProjectPersistenceStep({+ persistence: (+ result as Result & {+ persistence: ContentBlockPersistenceResult;+ }+ ).persistence,+ step: {+ type: "project",+ status: "failed",+ code: "CONTENT_STORAGE_PARTIAL_PERSISTENCE",+ message:+ error instanceof Error+ ? error.message+ : "Project persistence failed",+ },+ order: "after",+ });+ result = { ...result, persistence } as Result;+ const resultSnapshot = markPersistedAssetChangesStale(+ snapshot,+ persistence+ );+ if (resultSnapshot !== snapshot) {+ await this.saveSnapshot(resultSnapshot);+ }+ return this.createEnvelope({+ source: "local",+ result,+ committed: true,+ contract,+ snapshot: resultSnapshot,+ diagnostics: [+ ...diagnostics,+ {+ level: "error",+ code: "CONTENT_STORAGE_PARTIAL_PERSISTENCE",+ message:+ error instanceof Error+ ? `MDX files were saved, but the project change failed: ${error.message}`+ : "MDX files were saved, but the project change failed.",+ },+ ],});- const commitDiagnostics = confirmedAfterRetry+ }+ let commitDiagnostics = confirmedAfterRetry? [...diagnostics, commitRetryConfirmedDiagnostic]: diagnostics;+ if (projectFirst) {+ const saved = await saveStorage();+ persistedStorage = saved.persistence;+ const persistence = addProjectPersistenceStep({+ persistence: saved.persistence,+ step: { type: "project", status: "saved" },+ order: "before",+ });+ result = { ...result, persistence } as Result;+ if (saved.status !== "complete") {+ commitDiagnostics = [+ ...commitDiagnostics,+ {+ level: "error",+ code: saved.code,+ message: `The project destination was saved, but an MDX source step failed: ${saved.message}`,+ },+ ];+ }+ } else if (storageChanges.length > 0) {+ const persistence = addProjectPersistenceStep({+ persistence: (+ result as Result & {+ persistence: ContentBlockPersistenceResult;+ }+ ).persistence,+ step: { type: "project", status: "saved" },+ order: "after",+ });+ result = { ...result, persistence } as Result;+ }const applied = applyBuilderPatchTransactions(snapshot.state, [transaction,]);@@ -1415,7 +1836,7 @@ export class ProjectSession {const updatedNamespaces = [...new Set(mutation.payload.map((change) => change.namespace)),];- const committedSnapshot: ProjectSessionSnapshot = {+ const committedSnapshotBase: ProjectSessionSnapshot = {...snapshot,version: commit.version,state: applied.state,@@ -1432,6 +1853,13 @@ export class ProjectSession {operationId),};+ const committedSnapshot =+ persistedStorage === undefined+ ? committedSnapshotBase+ : markPersistedAssetChangesStale(+ committedSnapshotBase,+ persistedStorage+ );const persisted = await this.#synchronizeAfterCommit({snapshot: committedSnapshot,namespaces: mergeNamespaces(@@ -1443,7 +1871,7 @@ export class ProjectSession {});return this.createEnvelope({source: "local",- result: mutation.result,+ result,committed: true,contract: {...contract,diff --git a/packages/project-build/src/runtime.ts b/packages/project-build/src/runtime.tsindex 899367a47b..2e5c953da8 100644--- a/packages/project-build/src/runtime.ts+++ b/packages/project-build/src/runtime.ts@@ -8,9 +8,12 @@ export * from "./runtime/block";export * from "./runtime/breakpoints";export * from "./runtime/component-catalog";export * from "./runtime/component-template";+export * from "./runtime/content-block-source-lifecycle";+export * from "./runtime/content-block-application";export * from "./runtime/content-mode-copy-policy";export * from "./runtime/content-mode-permissions";export * from "./runtime/content-model";+export * from "./runtime/content-storage";export * from "./runtime/pre-publish-audit";export * from "./runtime/context";export * from "./runtime/data";@@ -26,6 +29,14 @@ export * from "./runtime/instance-duplicate";export * from "./runtime/instances";export * from "./runtime/lookup";export * from "./runtime/matcher";+export * from "./runtime/mdx-authored-content";+export * from "./runtime/mdx-asset-session";+export * from "./runtime/mdx-materialization";+export * from "./runtime/mdx-paste";+export * from "./runtime/mdx-storage-adapter";+export * from "./runtime/mdx-template-resolution";+export * from "./runtime/mdx-template-migration";+export * from "./runtime/published-mdx";export * from "./runtime/mutation";export * from "./runtime/output";export * from "./runtime/page-copy";diff --git a/packages/project-build/src/runtime/block.test.ts b/packages/project-build/src/runtime/block.test.tsindex ac61fa1cf7..fdd6bb93d1 100644--- a/packages/project-build/src/runtime/block.test.ts+++ b/packages/project-build/src/runtime/block.test.ts@@ -2,14 +2,18 @@ import { describe, expect, test } from "vitest";import {blockComponent,blockTemplateComponent,+ contentBlockSourceProp,type Instance,} from "@webstudio-is/sdk";import {+ assignUniqueBlockTemplateNamesMutable,canDeleteInstanceInContentMode,+ findBlockTemplateNameCollision,findBlockChildSelector,findBlockSelector,findBlockTemplates,getBlockTemplateInsertionIndex,+ getBlockTemplateNameConfirmation,} from "./block";const createInstance = (@@ -159,3 +163,161 @@ describe("block tree helpers", () => {).toBe(false);});});++describe("block template names", () => {+ const createBlockInstances = () =>+ new Map<Instance["id"], Instance>([+ [+ "block",+ createInstance("block", blockComponent, [+ { type: "id", value: "templates" },+ ]),+ ],+ [+ "templates",+ createInstance("templates", blockTemplateComponent, [+ { type: "id", value: "hero" },+ { type: "id", value: "card" },+ ]),+ ],+ ["hero", { ...createInstance("hero", "Box"), label: "Hero Card" }],+ ["card", createInstance("card", "Box")],+ ]);+ test("assigns unique names to newly inserted template entries", () => {+ const instances = createBlockInstances();+ instances.set("card-copy", createInstance("card-copy", "Box"));+ instances.set("card-copy-2", createInstance("card-copy-2", "Box"));+ instances.get("card-copy-2")!.label = "Box 2";++ assignUniqueBlockTemplateNamesMutable({+ instanceIds: ["card-copy", "card-copy-2"],+ parent: instances.get("templates")!,+ instances,+ });++ expect(instances.get("card-copy")?.label).toBe("Box 2");+ expect(instances.get("card-copy-2")?.label).toBe("Box 3");+ });++ test("finds exact name collisions in the same flat list", () => {+ const instances = createBlockInstances();++ expect(+ findBlockTemplateNameCollision({+ instance: instances.get("card")!,+ nextInstance: { ...instances.get("card")!, label: "Hero Card" },+ instances,+ })?.instance.id+ ).toBe("hero");+ expect(+ findBlockTemplateNameCollision({+ instance: instances.get("card")!,+ nextInstance: { ...instances.get("card")!, label: "hero card" },+ instances,+ })+ ).toBeUndefined();+ });++ test.each([+ {+ source: {+ id: "src",+ instanceId: "block",+ name: contentBlockSourceProp,+ type: "asset" as const,+ value: "article.mdx",+ },+ label: "direct",+ },+ {+ source: {+ id: "src",+ instanceId: "block",+ name: contentBlockSourceProp,+ type: "expression" as const,+ value: "articleAssetId",+ },+ label: "dynamic",+ },+ ])("requires confirmation for a $label source", ({ source }) => {+ const instances = createBlockInstances();+ const instance = instances.get("card")!;+ const hero = instances.get("hero")!;++ expect(+ getBlockTemplateNameConfirmation({+ changes: [+ { instance, nextInstance: { ...instance, label: "Article Card" } },+ { instance: hero, nextInstance: { ...hero, label: "Article Hero" } },+ ],+ instances,+ props: new Map([[source.id, source]]).values(),+ })+ ).toEqual({+ action: "rename",+ templates: [+ { instanceId: "card", oldName: "Box", newName: "Article Card" },+ {+ instanceId: "hero",+ oldName: "Hero Card",+ newName: "Article Hero",+ },+ ],+ });+ expect(+ getBlockTemplateNameConfirmation({+ changes: [{ instance }],+ instances,+ props: [source],+ })+ ).toEqual({+ action: "delete",+ templates: [{ instanceId: "card", oldName: "Box" }],+ });+ });++ test("does not warn for nested, unchanged, or non-source templates", () => {+ const instances = createBlockInstances();+ const instance = instances.get("card")!;+ instances.set(+ "nested",+ createInstance("nested", "Box", [{ type: "id", value: "card" }])+ );+ instances.get("templates")!.children = [+ { type: "id", value: "hero" },+ { type: "id", value: "nested" },+ ];+ const source = {+ id: "src",+ instanceId: "block",+ name: contentBlockSourceProp,+ type: "asset" as const,+ value: "article.mdx",+ };++ expect(+ getBlockTemplateNameConfirmation({+ changes: [{ instance, nextInstance: { ...instance, label: "Card" } }],+ instances,+ props: [source],+ })+ ).toBeUndefined();+ instances.get("templates")!.children.push({ type: "id", value: "card" });+ expect(+ getBlockTemplateNameConfirmation({+ changes: [{ instance, nextInstance: { ...instance } }],+ instances,+ props: [source],+ })+ ).toBeUndefined();+ expect(+ getBlockTemplateNameConfirmation({+ changes: [+ { instance, nextInstance: { ...instance, label: "Article Card" } },+ ],+ instances,+ props: [],+ })+ ).toBeUndefined();+ });+});diff --git a/packages/project-build/src/runtime/block.ts b/packages/project-build/src/runtime/block.tsindex b597be49ae..fcf0d5f803 100644--- a/packages/project-build/src/runtime/block.ts+++ b/packages/project-build/src/runtime/block.ts@@ -1,11 +1,192 @@import {+ allocateUniqueContentBlockTemplateName,blockComponent,blockTemplateComponent,+ findParentInstanceReference,+ getContentBlockSource,+ getInstanceName,type Instance,type Instances,+ type Prop,} from "@webstudio-is/sdk";+import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";import type { InstanceSelector } from "./tree";+export const assignUniqueBlockTemplateNamesMutable = ({+ instanceIds,+ parent,+ replacedInstanceIds = [],+ instances,+}: {+ instanceIds: readonly Instance["id"][];+ parent: Instance;+ replacedInstanceIds?: readonly Instance["id"][];+ instances: Instances;+}) => {+ if (parent.component !== blockTemplateComponent) {+ return;+ }+ const ignoredIds = new Set([...instanceIds, ...replacedInstanceIds]);+ const existingNames = new Set<string>();+ for (const child of parent.children) {+ const instance =+ child.type === "id" ? instances.get(child.value) : undefined;+ if (instance !== undefined && ignoredIds.has(instance.id) === false) {+ existingNames.add(getInstanceName({ instance, metas: componentMetas }));+ }+ }++ for (const instanceId of instanceIds) {+ const instance = instances.get(instanceId);+ if (instance === undefined) {+ continue;+ }+ const currentName = getInstanceName({ instance, metas: componentMetas });+ const uniqueName = allocateUniqueContentBlockTemplateName({+ name: currentName,+ existingNames,+ });+ if (uniqueName !== currentName) {+ instance.label = uniqueName;+ }+ existingNames.add(uniqueName);+ }+};++export const findBlockTemplateNameCollision = ({+ instance,+ nextInstance,+ instances,+}: {+ instance: Instance;+ nextInstance: Instance;+ instances: Instances;+}) => {+ const name = getInstanceName({+ instance: nextInstance,+ metas: componentMetas,+ });+ if (name === getInstanceName({ instance, metas: componentMetas })) {+ return;+ }+ const parent = findParentInstanceReference(instances, instance.id)?.instance;+ if (parent?.component !== blockTemplateComponent) {+ return;+ }+ for (const child of parent.children) {+ if (child.type !== "id" || child.value === instance.id) {+ continue;+ }+ const sibling = instances.get(child.value);+ if (+ sibling !== undefined &&+ getInstanceName({ instance: sibling, metas: componentMetas }) === name+ ) {+ return { instance: sibling, name };+ }+ }+};++export type BlockTemplateNameConfirmation = {+ action: "rename" | "delete";+ templates: Array<{+ instanceId: Instance["id"];+ oldName: string;+ newName?: string;+ }>;+};++export const getSourceBackedBlockTemplateContext = ({+ templateInstanceId,+ instances,+ props,+}: {+ templateInstanceId: Instance["id"];+ instances: Instances;+ props: Iterable<Prop>;+}) => {+ const template = instances.get(templateInstanceId);+ const templates = findParentInstanceReference(+ instances,+ templateInstanceId+ )?.instance;+ if (+ template === undefined ||+ templates?.component !== blockTemplateComponent+ ) {+ return;+ }+ const block = findParentInstanceReference(instances, templates.id)?.instance;+ if (block?.component !== blockComponent) {+ return;+ }+ const source = getContentBlockSource({+ blockInstanceId: block.id,+ props,+ });+ if (source === undefined) {+ return;+ }+ return {+ blockInstanceId: block.id,+ templatesInstanceId: templates.id,+ templateInstanceId,+ templateName: getInstanceName({+ instance: template,+ metas: componentMetas,+ }),+ source,+ };+};++export const getBlockTemplateNameConfirmation = ({+ changes,+ instances,+ props,+}: {+ changes: ReadonlyArray<{+ instance: Instance;+ nextInstance?: Instance;+ }>;+ instances: Instances;+ props: Iterable<Prop>;+}): BlockTemplateNameConfirmation | undefined => {+ const templates: BlockTemplateNameConfirmation["templates"] = [];+ const sourceProps = Array.from(props);+ for (const { instance, nextInstance } of changes) {+ const context = getSourceBackedBlockTemplateContext({+ templateInstanceId: instance.id,+ instances,+ props: sourceProps,+ });+ if (context === undefined) {+ continue;+ }+ const oldName = context.templateName;+ const newName =+ nextInstance === undefined+ ? undefined+ : getInstanceName({ instance: nextInstance, metas: componentMetas });+ if (newName === oldName) {+ continue;+ }+ templates.push({+ instanceId: instance.id,+ oldName,+ ...(newName === undefined ? {} : { newName }),+ });+ }+ if (templates.length === 0) {+ return;+ }+ return {+ action: changes.some(({ nextInstance }) => nextInstance === undefined)+ ? "delete"+ : "rename",+ templates,+ };+};+export const findBlockChildSelector = ({instanceSelector,instances,diff --git a/packages/project-build/src/runtime/collection.ts b/packages/project-build/src/runtime/collection.tsindex 39d4d70e41..4bef225d45 100644--- a/packages/project-build/src/runtime/collection.ts+++ b/packages/project-build/src/runtime/collection.ts@@ -12,7 +12,11 @@ import type { ComponentTemplateRegistry } from "./component-template";import { bindExpressionToInstanceScope } from "./data";import { throwBuilderRuntimeError } from "./errors";import { webstudioFragmentMutationInput } from "./fragment";-import { insertIndexInput, instanceInsertModeInput } from "./instances";+import {+ blockTemplateNameConfirmationInput,+ insertIndexInput,+ instanceInsertModeInput,+} from "./instances";const collectionDataInput = z.discriminatedUnion("type", [z.object({@@ -40,6 +44,7 @@ export const insertCollectionInput = z.object({),mode: instanceInsertModeInput.optional(),insertIndex: insertIndexInput.optional(),+ templateNameConfirmation: blockTemplateNameConfirmationInput.optional(),});export const insertCollectionResult = componentInsertResult.extend({diff --git a/packages/project-build/src/runtime/components.test.ts b/packages/project-build/src/runtime/components.test.tsindex a15aeed63f..8a2692a19f 100644--- a/packages/project-build/src/runtime/components.test.ts+++ b/packages/project-build/src/runtime/components.test.ts@@ -1,5 +1,8 @@import { expect, test } from "vitest";import {+ blockComponent,+ blockTemplateComponent,+ contentBlockSourceProp,collectionComponent,elementComponent,encodeDataVariableId,@@ -22,6 +25,7 @@ import {insertFragmentInput,} from "./components";import { getZodValidationIssues } from "./errors";+import { BuilderRuntimeError } from "./errors";import { getComponentTemplates } from "./component-templates";import { createEmptyWebstudioFragment } from "./component-template";import { insertCollectionInput } from "./collection";@@ -154,6 +158,81 @@ test("validates component ids with canonical instance schema", () => {).toBe(false);});+test("requires confirmation when replacing source-backed template entries", () => {+ const body: Instance = {+ type: "instance",+ id: "body",+ component: "Body",+ children: [{ type: "id", value: "block" }],+ };+ const state = createState(body);+ state.instances.set("block", {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: "templates" }],+ });+ state.instances.set("templates", {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [{ type: "id", value: "hero" }],+ });+ state.instances.set("hero", {+ type: "instance",+ id: "hero",+ component: "Box",+ label: "Hero Card",+ children: [],+ });+ state.props.set("src", {+ id: "src",+ instanceId: "block",+ name: contentBlockSourceProp,+ type: "asset",+ value: "article.mdx",+ });+ let confirmation: unknown;+ try {+ insertComponent(+ state,+ {+ parentInstanceId: "templates",+ component: "Box",+ mode: "replace",+ },+ { createId: createIdFactory() }+ );+ } catch (error) {+ expect(error).toBeInstanceOf(BuilderRuntimeError);+ confirmation = (error as BuilderRuntimeError).issues?.[0]?.example;+ }+ expect(confirmation).toEqual({+ action: "rename",+ templates: [{ instanceId: "hero", oldName: "Hero Card", newName: "Box" }],+ });++ expect(+ insertComponent(+ state,+ {+ parentInstanceId: "templates",+ component: "Box",+ mode: "replace",+ templateNameConfirmation: confirmation as {+ action: "rename";+ templates: Array<{+ instanceId: string;+ oldName: string;+ newName?: string;+ }>;+ },+ },+ { createId: createIdFactory() }+ ).result.removedInstanceIds+ ).toEqual(["hero"]);+});+test("explains the required parent for fragments with children", () => {const result = insertFragmentInput.safeParse({fragment: {@@ -577,6 +656,37 @@ test("inserts fragment into page template", async () => {);});+test("assigns a unique name when inserting into a Content Block Templates list", async () => {+ const parent: Instance = {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [{ type: "id", value: "existing" }],+ };+ const state = createState(parent);+ state.instances.set("existing", {+ type: "instance",+ id: "existing",+ component: "Box",+ children: [],+ });+ const fragment = await parseWebstudioJsxFragment("<$.Box />");++ const mutation = insertFragment(+ state,+ { parentInstanceId: parent.id, fragment },+ { createId: createIdFactory() }+ );++ expect(getAddedValues<Instance>(mutation, "instances")).toContainEqual(+ expect.objectContaining({+ id: "generated-0",+ component: "Box",+ label: "Box 2",+ })+ );+});+test("rejects invalid HtmlEmbed code from externally authored fragments", async () => {const parent = createParent();const fragment = await parseWebstudioJsxFragment(@@ -1322,6 +1432,21 @@ test("inspects webstudio jsx fragment syntax without evaluation", () => {).not.toThrow();});+test("preserves standalone JSX grammar and security inspection", async () => {+ await expect(parseWebstudioJsxFragment("< $ . Box />")).resolves.toEqual(+ expect.objectContaining({ children: expect.any(Array) })+ );+ await expect(+ parseWebstudioJsxFragment("<$.Box data-count={1_000} />")+ ).resolves.toEqual(expect.objectContaining({ children: expect.any(Array) }));+ await expect(+ parseWebstudioJsxFragment("< $ . Box data-secret={process.env} />")+ ).rejects.toThrow('Do not access "process" in JSX fragments');+ await expect(+ parseWebstudioJsxFragment("`{process.env}`<$.Box />")+ ).rejects.toThrow('Do not access "process" in JSX fragments');+});+test("rejects unsupported css rules after interpolation", async () => {await expect(parseWebstudioJsxFragment(diff --git a/packages/project-build/src/runtime/components.ts b/packages/project-build/src/runtime/components.tsindex 91a360363a..a551f16a47 100644--- a/packages/project-build/src/runtime/components.ts+++ b/packages/project-build/src/runtime/components.ts@@ -1,5 +1,6 @@import equal from "fast-deep-equal";import {+ blockTemplateComponent,elementComponent,instanceComponent,ROOT_INSTANCE_ID,@@ -47,14 +48,17 @@ import { findAvailableVariables } from "./data";import { addZodValidationIssue, throwBuilderRuntimeError } from "./errors";import {detectFragmentTokenConflicts,+ extractWebstudioFragment,insertWebstudioFragmentCopy,webstudioFragmentMutationInput,} from "./fragment";import {+ blockTemplateNameConfirmationInput,createInstanceAppendPayload,createInstanceChild,insertIndexInput,instanceInsertModeInput,+ requireBlockTemplateNameConfirmation,} from "./instances";import { createRuntimeMutation, type BuilderRuntimeMutation } from "./mutation";import { getSlotFragmentDropTargetMutable } from "./slot";@@ -66,6 +70,11 @@ import {getNewFragmentContentModelWarnings,} from "./matcher";import { z } from "zod";+import {+ assignUniqueBlockTemplateNamesMutable,+ getBlockTemplateNameConfirmation,+ type BlockTemplateNameConfirmation,+} from "./block";const conflictResolutionInput = z.enum(["ours", "theirs", "merge"])@@ -85,6 +94,7 @@ export const insertComponentInput = z.object({.describe('Required when component is "ws:element"; omit otherwise.'),mode: instanceInsertModeInput.optional(),insertIndex: insertIndexInput.optional(),+ templateNameConfirmation: blockTemplateNameConfirmationInput.optional(),});export const insertFragmentInput = z@@ -102,6 +112,7 @@ export const insertFragmentInput = z),mode: instanceInsertModeInput.optional(),insertIndex: insertIndexInput.optional(),+ templateNameConfirmation: blockTemplateNameConfirmationInput.optional(),}).superRefine((input, context) => {if (@@ -245,19 +256,39 @@ const getRequiredComponentInsertState = (state: ComponentInsertState) => {};};+export const getRequiredComponentInsertData = (+ state: ComponentInsertState+): Omit<WebstudioData, "pages"> => {+ const required = getRequiredComponentInsertState(state);+ return {+ instances: required.instances,+ props: required.props,+ dataSources: required.dataSources,+ resources: required.resources,+ styleSources: required.styleSources,+ styleSourceSelections: required.styleSourceSelections,+ styles: required.styles,+ breakpoints: required.breakpoints,+ assets: required.assets,+ };+};+const cloneFragmentData = (state: ReturnType<typeof getRequiredComponentInsertState>-): Omit<WebstudioData, "pages"> => ({- instances: cloneMap(state.instances),- props: cloneMap(state.props),- dataSources: cloneMap(state.dataSources),- resources: cloneMap(state.resources),- styleSources: cloneMap(state.styleSources),- styleSourceSelections: cloneMap(state.styleSourceSelections),- styles: cloneMap(state.styles),- breakpoints: cloneMap(state.breakpoints),- assets: cloneMap(state.assets),-});+): Omit<WebstudioData, "pages"> => {+ const data = getRequiredComponentInsertData(state);+ return {+ instances: cloneMap(data.instances),+ props: cloneMap(data.props),+ dataSources: cloneMap(data.dataSources),+ resources: cloneMap(data.resources),+ styleSources: cloneMap(data.styleSources),+ styleSourceSelections: cloneMap(data.styleSourceSelections),+ styles: cloneMap(data.styles),+ breakpoints: cloneMap(data.breakpoints),+ assets: cloneMap(data.assets),+ };+};const cloneMap = <Key, Value>(map: Map<Key, Value>) =>new Map(@@ -684,9 +715,13 @@ const createInsertFragmentMutation = <insertIndex: explicitInsertIndex,conflictResolution,contentMode = false,+ includeDataResources,+ reusePortalContent,additionalAvailableVariables = [],getResultDetails,validateContentModel = true,+ protectedChildCount = 0,+ confirm,context,}: {state: ComponentInsertState;@@ -697,12 +732,16 @@ const createInsertFragmentMutation = <insertIndex?: z.infer<typeof insertIndexInput>;conflictResolution?: ConflictResolution;contentMode?: boolean;+ includeDataResources?: boolean;+ reusePortalContent?: boolean;additionalAvailableVariables?: DataSource[];getResultDetails?: (ids: {newInstanceIds: Map<string, string>;newDataSourceIds: Map<string, string>;}) => Details;validateContentModel?: boolean;+ protectedChildCount?: number;+ confirm?: BlockTemplateNameConfirmation;context: BuilderRuntimeContext;}) => {const mutationState = getRequiredComponentInsertState(state);@@ -736,10 +775,12 @@ const createInsertFragmentMutation = <const parentChildren = parent.children ?? [];const insertIndex =mode === "replace"- ? 0+ ? protectedChildCount: mode === "prepend"- ? 0- : (explicitInsertIndex ?? parentChildren.length);+ ? protectedChildCount+ : explicitInsertIndex === undefined+ ? parentChildren.length+ : protectedChildCount + explicitInsertIndex;if (insertIndex > parentChildren.length) {return throwBuilderRuntimeError("BAD_REQUEST",@@ -765,6 +806,8 @@ const createInsertFragmentMutation = <metas: componentMetas,contentModeCopyableProp: isFragmentContentModeCopyableProp,contentMode,+ includeDataResources,+ reusePortalContent,});for (const instanceId of newInstanceIds.values()) {if (@@ -787,6 +830,44 @@ const createInsertFragmentMutation = <return child;});+ assignUniqueBlockTemplateNamesMutable({+ instanceIds: insertedChildren.flatMap((child) =>+ child.type === "id" ? [child.value] : []+ ),+ parent,+ replacedInstanceIds:+ mode === "replace"+ ? parentChildren+ .slice(protectedChildCount)+ .flatMap((child) => (child.type === "id" ? [child.value] : []))+ : [],+ instances: nextData.instances,+ });+ let requiredTemplateNameConfirmation:+ | BlockTemplateNameConfirmation+ | undefined;+ if (mode === "replace" && parent.component === blockTemplateComponent) {+ const insertedInstanceIds = insertedChildren.flatMap((child) =>+ child.type === "id" ? [child.value] : []+ );+ const replacedInstances = parentChildren+ .slice(protectedChildCount)+ .flatMap((child) => {+ if (child.type !== "id") {+ return [];+ }+ const instance = mutationState.instances.get(child.value);+ return instance === undefined ? [] : [instance];+ });+ requiredTemplateNameConfirmation = getBlockTemplateNameConfirmation({+ changes: replacedInstances.map((instance, index) => ({+ instance,+ nextInstance: nextData.instances.get(insertedInstanceIds[index] ?? ""),+ })),+ instances: mutationState.instances,+ props: mutationState.props.values(),+ });+ }if (validateContentModel) {const validationInstances = new Map(nextData.instances);@@ -831,6 +912,11 @@ const createInsertFragmentMutation = <return throwBuilderRuntimeError("BAD_REQUEST", contentModelError.message);}}+ requireBlockTemplateNameConfirmation({+ required: requiredTemplateNameConfirmation,+ confirm,+ path: "mode",+ });const createResult = (parentInstanceId: string,@@ -893,6 +979,7 @@ const createInsertFragmentMutation = <styleSources: mutationState.styleSources.values(),styleSourceSelections: mutationState.styleSourceSelections.values(),styles: mutationState.styles.values(),+ protectedChildCount,});const insertPayload = createFragmentInsertPayload({before: mutationState,@@ -914,7 +1001,8 @@ const createInsertFragmentMutation = <export const insertComponent = (state: ComponentInsertState,input: z.infer<typeof insertComponentInput>,- context: BuilderRuntimeContext+ context: BuilderRuntimeContext,+ options: { protectedChildCount?: number } = {}) => {const mutationState = getRequiredComponentInsertState(state);const parent = mutationState.instances.get(input.parentInstanceId);@@ -1000,6 +1088,8 @@ export const insertComponent = (mode: input.mode,insertIndex: input.insertIndex,validateContentModel: false,+ protectedChildCount: options.protectedChildCount,+ confirm: input.templateNameConfirmation,context,});};@@ -1007,7 +1097,8 @@ export const insertComponent = (export const insertCollection = (state: ComponentInsertState,input: z.infer<typeof insertCollectionInput>,- context: BuilderRuntimeContext+ context: BuilderRuntimeContext,+ options: { protectedChildCount?: number } = {}) => {const mutationState = getRequiredComponentInsertState(state);if (mutationState.instances.has(input.parentInstanceId) === false) {@@ -1057,6 +1148,8 @@ export const insertCollection = (collection.itemKeyParameterId),}),+ protectedChildCount: options.protectedChildCount,+ confirm: input.templateNameConfirmation,context,});};@@ -1102,7 +1195,8 @@ const createInsertTokenFragmentMutation = ({export const insertFragment = (state: ComponentInsertState,input: z.infer<typeof insertFragmentInput>,- context: BuilderRuntimeContext+ context: BuilderRuntimeContext,+ options: { protectedChildCount?: number } = {}): BuilderRuntimeMutation<FragmentInsertResult> => {const htmlEmbedError = validateFragmentHtmlEmbedCode(input.fragment);if (htmlEmbedError !== undefined) {@@ -1146,6 +1240,52 @@ export const insertFragment = (insertIndex: input.insertIndex,conflictResolution: input.conflictResolution,contentMode: input.contentMode,+ protectedChildCount: options.protectedChildCount,+ confirm: input.templateNameConfirmation,+ context,+ });+};++export const insertInstanceCopy = (+ state: ComponentInsertState,+ input: {+ sourceInstanceId: Instance["id"];+ parentInstanceId: Instance["id"];+ insertIndex?: number;+ contentMode?: boolean;+ },+ context: BuilderRuntimeContext,+ options: { protectedChildCount?: number } = {}+) => {+ const mutationState = getRequiredComponentInsertState(state);+ if (mutationState.instances.has(input.sourceInstanceId) === false) {+ return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");+ }+ const fragment = extractWebstudioFragment(+ mutationState,+ input.sourceInstanceId+ );+ if (+ fragment.instances.some(+ (instance) => instance.component === blockTemplateComponent+ )+ ) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "A subtree containing Content Block Templates cannot be copied across storage roots."+ );+ }+ return createInsertFragmentMutation({+ state: mutationState,+ parentInstanceId: input.parentInstanceId,+ fragment,+ templates: getComponentTemplates(),+ insertIndex: input.insertIndex,+ conflictResolution: "ours",+ contentMode: input.contentMode,+ includeDataResources: true,+ reusePortalContent: false,+ protectedChildCount: options.protectedChildCount,context,});};diff --git a/packages/project-build/src/runtime/content-block-application.test.ts b/packages/project-build/src/runtime/content-block-application.test.tsnew file mode 100644index 0000000000..bf4b100fd9--- /dev/null+++ b/packages/project-build/src/runtime/content-block-application.test.ts@@ -0,0 +1,1123 @@+import type { AssetRepository } from "@webstudio-is/asset-uploader/server";+import {+ blockComponent,+ blockTemplateComponent,+ createStructuredAssetQueryResourceBody,+ elementComponent,+ encodeDataVariableId,+ type Instance,+} from "@webstudio-is/sdk";+import type { ContentArtifactV1 } from "@webstudio-is/content-engine";+import { describe, expect, test, vi } from "vitest";+import type { BuilderState } from "../state/builder-state";+import { createDefaultPages } from "../shared/pages-utils";+import {+ createContentBlockApplicationOperations,+ executeContentBlockPersistencePlan,+ persistContentBlockStorageChangesSerially,+ recoverContentBlockSession,+} from "./content-block-application";+import { createMdxAssetEditingSession } from "./mdx-asset-session";++const encoder = new TextEncoder();++const createState = (+ source: "asset" | "expression" | undefined = "asset",+ body = false+): BuilderState => ({+ pages: createDefaultPages({ rootInstanceId: "block" }),+ instances: new Map([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [+ { type: "id", value: "templates" },+ ...(body ? ([{ type: "id", value: "body" }] as const) : []),+ ],+ },+ ],+ [+ "templates",+ {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [],+ },+ ],+ ...(body+ ? ([+ [+ "body",+ {+ type: "instance" as const,+ id: "body",+ component: elementComponent,+ tag: "p",+ children: [{ type: "text" as const, value: "Persisted body" }],+ },+ ],+ ] as [string, Instance][])+ : []),+ ]),+ props: new Map(+ source === undefined+ ? []+ : [+ [+ "src",+ source === "asset"+ ? {+ id: "src",+ instanceId: "block",+ name: "src",+ type: "asset" as const,+ value: "article",+ }+ : {+ id: "src",+ instanceId: "block",+ name: "src",+ type: "expression" as const,+ value: "article.body",+ },+ ],+ ]+ ),+ dataSources: new Map(),+ resources: new Map(),+ styleSources: new Map(),+ styleSourceSelections: new Map(),+ styles: new Map(),+ breakpoints: new Map(),+ assets: new Map(),+});++const createRepository = (initialSource = "# Original") => {+ let source = initialSource;+ let name = "article-initial.mdx";+ const updateContent = vi.fn(+ async ({+ assetId,+ data,+ }: Parameters<AssetRepository["updateContent"]>[0]) => {+ source = await new Response(data).text();+ name = "article-updated.mdx";+ return {+ id: assetId,+ projectId: "project",+ type: "file" as const,+ format: "file",+ name,+ filename: "article.mdx",+ size: encoder.encode(source).byteLength,+ description: null,+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-02T00:00:00.000Z",+ meta: {},+ };+ }+ );+ return {+ repository: {+ readContent: async ({+ assetId,+ }: Parameters<AssetRepository["readContent"]>[0]) => {+ const bytes = encoder.encode(source);+ return {+ asset: {+ id: assetId,+ projectId: "project",+ type: "file" as const,+ format: "file",+ name,+ filename: `${assetId}.mdx`,+ size: bytes.byteLength,+ description: null,+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-02T00:00:00.000Z",+ meta: {},+ },+ data: {+ async *[Symbol.asyncIterator]() {+ yield bytes;+ },+ },+ };+ },+ updateContent,+ },+ updateContent,+ getSource: () => source,+ setSource: (value: string) => {+ source = value;+ },+ };+};++describe("Content Block application operations", () => {+ test("preflights the complete serial plan and stops after the first durable failure", async () => {+ const events: string[] = [];+ const createStep = (+ name: string,+ status: "saved" | "failed" = "saved"+ ) => ({+ type: name === "project" ? ("project" as const) : ("asset" as const),+ preflight: async () => {+ events.push(`preflight:${name}`);+ return { status: "ready" as const };+ },+ persist: async () => {+ events.push(`persist:${name}`);+ return status === "saved"+ ? { status }+ : {+ status,+ code: "content-source-write-conflict",+ message: "Source changed",+ };+ },+ });++ await expect(+ executeContentBlockPersistencePlan([+ createStep("destination"),+ createStep("source", "failed"),+ createStep("project"),+ ])+ ).resolves.toMatchObject({+ status: "partial",+ steps: [+ { type: "asset", status: "saved" },+ { type: "asset", status: "failed" },+ { type: "project", status: "not-attempted" },+ ],+ retry: { replan: true, project: true },+ });+ expect(events).toEqual([+ "preflight:destination",+ "preflight:source",+ "preflight:project",+ "persist:destination",+ "persist:source",+ ]);+ });++ test("preflights every storage root before saving the first one", async () => {+ const firstIdentity = {+ blockInstanceId: "first-block",+ assetId: "first",+ revision: "sha256:first",+ contentRef: "first.mdx",+ format: "mdx" as const,+ renderScope: "page:/first",+ };+ const secondIdentity = {+ ...firstIdentity,+ blockInstanceId: "second-block",+ assetId: "second",+ revision: "sha256:second",+ contentRef: "second.mdx",+ renderScope: "page:/second",+ };+ const queueSave = vi.fn();+ const preflightSave = vi.fn(async ({ key }: { key: string }) =>+ key.includes("second")+ ? { status: "blocked" as const, reason: "Second Asset is stale" }+ : { status: "ready" as const }+ );+ const changes = [firstIdentity, secondIdentity].map((identity) => ({+ root: { type: "external" as const, identity },+ payload: [+ {+ namespace: "instances" as const,+ patches: [+ {+ op: "replace" as const,+ path: ["content", "children", 0, "value"],+ value: "Updated",+ },+ ],+ },+ ],+ }));++ await expect(+ persistContentBlockStorageChangesSerially({+ session: {+ list: () =>+ [firstIdentity, secondIdentity].map((identity) => ({+ status: "saved",+ key: JSON.stringify([+ identity.blockInstanceId,+ identity.assetId,+ identity.revision,+ identity.contentRef,+ identity.format,+ identity.renderScope,+ ]),+ identity,+ source: "# Original",+ diagnostics: [],+ })),+ preflightSave,+ queueSave,+ } as never,+ changes,+ })+ ).resolves.toMatchObject({+ status: "failed",+ steps: [+ { status: "not-attempted", root: firstIdentity },+ { status: "failed", root: secondIdentity },+ ],+ retry: {+ replan: true,+ roots: [firstIdentity, secondIdentity],+ },+ });+ expect(preflightSave).toHaveBeenCalledTimes(2);+ expect(queueSave).not.toHaveBeenCalled();+ });++ test("combines accumulated changes for one root into one revisioned write", async () => {+ const identity = {+ blockInstanceId: "block",+ assetId: "article",+ revision: "sha256:article",+ contentRef: "article.mdx",+ format: "mdx" as const,+ renderScope: "page:/",+ };+ const key = JSON.stringify([+ identity.blockInstanceId,+ identity.assetId,+ identity.revision,+ identity.contentRef,+ identity.format,+ identity.renderScope,+ ]);+ const changes = ["First", "Second"].map((value) => ({+ root: { type: "external" as const, identity },+ payload: [+ {+ namespace: "instances" as const,+ patches: [+ {+ op: "replace" as const,+ path: ["content", "children", 0, "value"],+ value,+ },+ ],+ },+ ],+ }));+ const preflightSave = vi.fn(async () => ({ status: "ready" as const }));+ const queueSave = vi.fn(async () => ({+ status: "pending" as const,+ key,+ identity,+ localSource: "# Second",+ diagnostics: [],+ }));+ const flush = vi.fn(async () => ({+ status: "saved" as const,+ key,+ identity,+ source: "# Second",+ diagnostics: [],+ }));++ await expect(+ persistContentBlockStorageChangesSerially({+ session: {+ list: () => [+ {+ status: "saved",+ key,+ identity,+ source: "# Original",+ diagnostics: [],+ },+ ],+ preflightSave,+ queueSave,+ flush,+ } as never,+ changes,+ })+ ).resolves.toMatchObject({+ status: "complete",+ steps: [{ type: "asset", status: "saved", root: identity }],+ });+ expect(preflightSave).toHaveBeenCalledOnce();+ expect(preflightSave).toHaveBeenCalledWith({ key, changes });+ expect(queueSave).toHaveBeenCalledOnce();+ expect(queueSave).toHaveBeenCalledWith({ key, changes });+ expect(flush).toHaveBeenCalledOnce();+ });++ test("marks successful remote recovery as an Asset refresh", async () => {+ const conflicting = {+ status: "conflicting",+ key: "article",+ diagnostics: [],+ } as const;+ const saved = {+ status: "saved",+ key: "article-remote",+ source: "# Remote",+ diagnostics: [],+ } as const;++ await expect(+ recoverContentBlockSession({+ session: {+ reloadRemote: vi.fn(async () => saved),+ } as never,+ state: conflicting as never,+ action: "reload-remote",+ })+ ).resolves.toEqual({+ status: "complete",+ state: saved,+ changedAsset: true,+ });+ });++ test("dry-run rejects recovery actions that the live session cannot run", async () => {+ await expect(+ recoverContentBlockSession({+ session: {} as never,+ state: {+ status: "saved",+ key: "article",+ source: "# Saved",+ diagnostics: [],+ } as never,+ action: "reload-remote",+ dryRun: true,+ })+ ).resolves.toMatchObject({+ status: "blocked",+ code: "content-source-session-failed",+ });+ });++ test("discovers exact dynamic render scopes and their repair capabilities", async () => {+ const { repository } = createRepository();+ const resolveExpressionAssetId = vi.fn(() => "article");+ const session = createMdxAssetEditingSession({+ repository,+ authorizeAsset: () => true,+ resolveExpressionAssetId,+ });+ const operations = createContentBlockApplicationOperations({+ projectId: "project",+ session,+ getState: () => createState("expression"),+ context: { createId: () => "generated" },+ });++ const first = await operations.inspectSource({+ blockInstanceId: "block",+ renderScope: "page:/posts:item:one",+ variables: { "article.body": "article" },+ });+ const second = await operations.inspectSource({+ blockInstanceId: "block",+ renderScope: "page:/posts:item:two",+ });++ expect(first).toMatchObject({+ sessionStatus: "saved",+ resolvedIdentity: {+ assetId: "article",+ renderScope: "page:/posts:item:one",+ },+ capabilities: { canEdit: true, canDisconnectWithCopy: true },+ repairRoutes: ["open-file", "disconnect-with-copy"],+ });+ expect(second.resolvedIdentity?.renderScope).toBe("page:/posts:item:two");+ expect(resolveExpressionAssetId).toHaveBeenCalledTimes(2);+ expect(resolveExpressionAssetId).toHaveBeenNthCalledWith(1, {+ expression: "article.body",+ blockInstanceId: "block",+ renderScope: "page:/posts:item:one",+ variables: { "article.body": "article" },+ });+ });++ test("routes semantic edits through the shared runtime and persists only MDX", async () => {+ const { repository, updateContent, getSource } = createRepository();+ const state = createState();+ const session = createMdxAssetEditingSession({+ repository,+ authorizeAsset: () => true,+ debounceMilliseconds: 0,+ });+ const commitProjectPayload = vi.fn();+ const operations = createContentBlockApplicationOperations({+ projectId: "project",+ session,+ getState: () => state,+ commitProjectPayload,+ context: { createId: () => "generated" },+ });+ await operations.inspectSource({+ blockInstanceId: "block",+ renderScope: "page:/",+ });+ const loaded = session.list()[0];+ if (!("root" in loaded)) {+ throw new Error("Expected loaded root");+ }+ const headingId = loaded.root.fragment.instances[0].id;++ const result = await operations.semanticEdit({+ operationId: "instances.updateText",+ input: { instanceId: headingId, childIndex: 0, text: "Updated" },+ blockInstanceId: "block",+ renderScope: "page:/",+ });++ expect(result.status).toBe("complete");+ expect(updateContent).toHaveBeenCalledTimes(1);+ expect(commitProjectPayload).not.toHaveBeenCalled();+ expect(getSource()).toContain("# Updated");+ expect(state.instances?.has(headingId)).toBe(false);+ });++ test("reports a committed semantic edit when projection recovery is needed", async () => {+ const storage = createRepository();+ const state = createState();+ const updateContent = storage.repository.updateContent;+ const session = createMdxAssetEditingSession({+ repository: {+ ...storage.repository,+ updateContent: async (input) => {+ const result = await updateContent(input);+ state.assets = undefined;+ return result;+ },+ },+ authorizeAsset: () => true,+ debounceMilliseconds: 0,+ });+ const operations = createContentBlockApplicationOperations({+ projectId: "project",+ session,+ getState: () => state,+ context: { createId: () => "generated" },+ });+ await operations.inspectSource({+ blockInstanceId: "block",+ renderScope: "page:/",+ });+ const loaded = session.list()[0];+ if (!("root" in loaded)) {+ throw new Error("Expected loaded root");+ }++ await expect(+ operations.semanticEdit({+ operationId: "instances.updateText",+ input: {+ instanceId: loaded.root.fragment.instances[0].id,+ childIndex: 0,+ text: "Updated",+ },+ blockInstanceId: "block",+ renderScope: "page:/",+ })+ ).resolves.toMatchObject({ status: "complete" });+ expect(session.list()).toEqual([+ expect.objectContaining({+ status: "recoverable",+ committedSource: expect.stringContaining("Updated"),+ }),+ ]);+ });++ test("returns a stale-safe confirmation before replacing persisted body", async () => {+ const { repository } = createRepository();+ const state = createState("asset", true);+ state.props?.clear();+ const session = createMdxAssetEditingSession({+ repository,+ authorizeAsset: () => true,+ });+ let id = 0;+ const operations = createContentBlockApplicationOperations({+ projectId: "project",+ session,+ getState: () => state,+ commitProjectPayload: vi.fn(),+ context: { createId: () => `generated-${id++}`, projectVersion: 1 },+ });+ const preview = await operations.applyLifecycle({+ action: "connect",+ blockInstanceId: "block",+ renderScope: "page:/",+ source: { type: "asset", assetId: "article" },+ authority: "use-file-content",+ dryRun: true,+ });+ expect(preview).toMatchObject({+ status: "confirmation-required",+ code: "content-source-confirmation-required",+ result: { action: "connect", storageWrites: [] },+ });+ if (preview.status !== "confirmation-required") {+ throw new Error("Expected confirmation");+ }+ const stale = await operations.applyLifecycle({+ action: "connect",+ blockInstanceId: "block",+ renderScope: "page:/",+ source: { type: "asset", assetId: "article" },+ authority: "use-file-content",+ confirmationToken: `${preview.confirmationToken}changed`,+ });+ expect(stale.status).toBe("confirmation-required");+ });++ test("previews a lossless connection without requiring confirmation", async () => {+ const { repository } = createRepository();+ const state = createState();+ state.props?.clear();+ const session = createMdxAssetEditingSession({+ repository,+ authorizeAsset: () => true,+ });+ const commitProjectPayload = vi.fn();+ const operations = createContentBlockApplicationOperations({+ projectId: "project",+ session,+ getState: () => state,+ commitProjectPayload,+ context: { createId: () => "generated" },+ });++ await expect(+ operations.applyLifecycle({+ action: "connect",+ blockInstanceId: "block",+ renderScope: "page:/",+ source: { type: "asset", assetId: "article" },+ authority: "use-file-content",+ dryRun: true,+ })+ ).resolves.toMatchObject({+ status: "complete",+ result: { action: "connect", changesProject: true, storageWrites: [] },+ });+ expect(commitProjectPayload).not.toHaveBeenCalled();+ });++ test("requires confirmation for disconnect and rejects unavailable recovery actions", async () => {+ const { repository } = createRepository();+ const state = createState();+ const session = createMdxAssetEditingSession({+ repository,+ authorizeAsset: () => true,+ });+ const commitProjectPayload = vi.fn();+ const operations = createContentBlockApplicationOperations({+ projectId: "project",+ session,+ getState: () => state,+ commitProjectPayload,+ context: { createId: () => "generated", projectVersion: 1 },+ });+ await operations.inspectSource({+ blockInstanceId: "block",+ renderScope: "page:/",+ });++ await expect(+ operations.recover({+ blockInstanceId: "block",+ renderScope: "page:/",+ action: "copy-unsaved-mdx",+ })+ ).resolves.toMatchObject({+ status: "blocked",+ code: "content-source-session-failed",+ });+ const preview = await operations.applyLifecycle({+ action: "disconnect",+ blockInstanceId: "block",+ renderScope: "page:/",+ dryRun: true,+ });+ expect(preview.status).toBe("confirmation-required");+ expect(commitProjectPayload).not.toHaveBeenCalled();+ if (preview.status !== "confirmation-required") {+ throw new Error("Expected disconnect confirmation");+ }+ await expect(+ operations.applyLifecycle({+ action: "disconnect",+ blockInstanceId: "block",+ renderScope: "page:/",+ confirmationToken: preview.confirmationToken,+ })+ ).resolves.toMatchObject({ status: "complete" });+ expect(commitProjectPayload).toHaveBeenCalledTimes(1);+ });++ test("retries a recoverable parse failure through the configured source", async () => {+ const { repository, setSource } = createRepository('{alert("unsafe")}');+ const state = createState();+ const session = createMdxAssetEditingSession({+ repository,+ authorizeAsset: () => true,+ });+ const operations = createContentBlockApplicationOperations({+ projectId: "project",+ session,+ getState: () => state,+ context: { createId: () => "generated" },+ });+ await expect(+ operations.inspectSource({+ blockInstanceId: "block",+ renderScope: "page:/",+ })+ ).resolves.toMatchObject({ sessionStatus: "recoverable" });+ setSource("# Repaired");++ await expect(+ operations.recover({+ blockInstanceId: "block",+ renderScope: "page:/",+ action: "retry",+ })+ ).resolves.toMatchObject({+ status: "complete",+ result: { inspection: { sessionStatus: "saved" } },+ });+ });++ test("persists a replacement before connecting the Content Block", async () => {+ const { repository, updateContent } = createRepository();+ const state = createState("asset", true);+ state.props?.clear();+ const session = createMdxAssetEditingSession({+ repository,+ authorizeAsset: () => true,+ });+ const commitProjectPayload = vi.fn(async () => {});+ const operations = createContentBlockApplicationOperations({+ projectId: "project",+ session,+ getState: () => state,+ context: { createId: () => "generated" },+ commitProjectPayload,+ });++ const confirmation = await operations.applyLifecycle({+ action: "connect",+ blockInstanceId: "block",+ renderScope: "page:/",+ source: { type: "asset", assetId: "article" },+ authority: "replace-file-body-with-block-content",+ });+ expect(confirmation.status).toBe("confirmation-required");+ if (confirmation.status !== "confirmation-required") {+ throw new Error("Expected replacement confirmation");+ }+ await expect(+ operations.applyLifecycle({+ action: "connect",+ blockInstanceId: "block",+ renderScope: "page:/",+ source: { type: "asset", assetId: "article" },+ authority: "replace-file-body-with-block-content",+ confirmationToken: confirmation.confirmationToken,+ })+ ).resolves.toMatchObject({+ status: "complete",+ result: {+ persistence: {+ status: "complete",+ steps: [+ { type: "asset", status: "saved" },+ { type: "project", status: "saved" },+ ],+ },+ },+ });+ expect(session.list()).toEqual([+ expect.objectContaining({+ status: "saved",+ source: '<ws.element ws:tag="p">Persisted body</ws.element>\n',+ }),+ ]);+ expect(updateContent).toHaveBeenCalledOnce();+ expect(commitProjectPayload).toHaveBeenCalledOnce();+ });++ test("does not attempt the project step when the Asset replacement fails", async () => {+ const storage = createRepository();+ const state = createState("asset", true);+ state.props?.clear();+ const session = createMdxAssetEditingSession({+ repository: {+ ...storage.repository,+ updateContent: async () => {+ throw new Error("Asset write failed");+ },+ },+ authorizeAsset: () => true,+ });+ const commitProjectPayload = vi.fn();+ const operations = createContentBlockApplicationOperations({+ projectId: "project",+ session,+ getState: () => state,+ context: { createId: () => "generated" },+ commitProjectPayload,+ });+ const confirmation = await operations.applyLifecycle({+ action: "connect",+ blockInstanceId: "block",+ renderScope: "page:/",+ source: { type: "asset", assetId: "article" },+ authority: "replace-file-body-with-block-content",+ });+ if (confirmation.status !== "confirmation-required") {+ throw new Error("Expected replacement confirmation");+ }++ await expect(+ operations.applyLifecycle({+ action: "connect",+ blockInstanceId: "block",+ renderScope: "page:/",+ source: { type: "asset", assetId: "article" },+ authority: "replace-file-body-with-block-content",+ confirmationToken: confirmation.confirmationToken,+ })+ ).resolves.toMatchObject({+ status: "blocked",+ result: {+ persistence: {+ status: "failed",+ steps: [+ { type: "asset", status: "failed" },+ { type: "project", status: "not-attempted" },+ ],+ retry: { replan: true, roots: [expect.any(Object)], project: true },+ },+ },+ });+ expect(commitProjectPayload).not.toHaveBeenCalled();+ expect(storage.getSource()).toBe("# Original");+ });++ test("keeps a saved Asset replacement when the project step fails", async () => {+ const storage = createRepository();+ const state = createState("asset", true);+ state.props?.clear();+ const session = createMdxAssetEditingSession({+ repository: storage.repository,+ authorizeAsset: () => true,+ });+ const operations = createContentBlockApplicationOperations({+ projectId: "project",+ session,+ getState: () => state,+ context: { createId: () => "generated" },+ commitProjectPayload: async () => {+ throw new Error("Project write failed");+ },+ });+ const confirmation = await operations.applyLifecycle({+ action: "connect",+ blockInstanceId: "block",+ renderScope: "page:/",+ source: { type: "asset", assetId: "article" },+ authority: "replace-file-body-with-block-content",+ });+ if (confirmation.status !== "confirmation-required") {+ throw new Error("Expected replacement confirmation");+ }++ await expect(+ operations.applyLifecycle({+ action: "connect",+ blockInstanceId: "block",+ renderScope: "page:/",+ source: { type: "asset", assetId: "article" },+ authority: "replace-file-body-with-block-content",+ confirmationToken: confirmation.confirmationToken,+ })+ ).resolves.toMatchObject({+ status: "partial",+ result: {+ persistence: {+ status: "partial",+ steps: [+ { type: "asset", status: "saved" },+ { type: "project", status: "failed" },+ ],+ retry: { replan: true, roots: [], project: true },+ },+ },+ });+ expect(storage.getSource()).toBe(+ '<ws.element ws:tag="p">Persisted body</ws.element>\n'+ );+ });++ test("discovers the owning direct source and migrates template references through the pinned session", async () => {+ const { repository, updateContent, getSource } = createRepository(+ '<ws.element ws:name="Card" />'+ );+ const state = createState();+ const templates = state.instances?.get("templates");+ if (templates === undefined) {+ throw new Error("Expected Templates instance");+ }+ templates.children.push({ type: "id", value: "card" });+ state.instances?.set("card", {+ type: "instance",+ id: "card",+ component: elementComponent,+ tag: "div",+ label: "Card",+ children: [],+ });+ const session = createMdxAssetEditingSession({+ repository,+ authorizeAsset: ({ assetId }) => assetId !== "missing",+ debounceMilliseconds: 0,+ });+ const operations = createContentBlockApplicationOperations({+ projectId: "project",+ session,+ getState: () => state,+ context: { createId: () => "generated" },+ });++ await expect(+ operations.migrateTemplateReferences({+ templateInstanceId: "card",+ migration: { type: "remove" },+ renderScope: "page:/selected",+ selectedAssetIds: ["reviewed"],+ dryRun: true,+ })+ ).resolves.toMatchObject({+ discoveryComplete: true,+ files: [{ assetId: "reviewed" }],+ });+ await expect(+ operations.migrateTemplateReferences({+ templateInstanceId: "card",+ migration: { type: "remove" },+ renderScope: "page:/selected-with-failure",+ selectedAssetIds: ["article", "missing"],+ dryRun: true,+ })+ ).resolves.toMatchObject({+ status: "confirmation-required",+ files: [+ { assetId: "article" },+ {+ assetId: "missing",+ status: "failed",+ diagnostics: [{ code: "asset-authorization-failed" }],+ },+ ],+ });++ const preview = await operations.migrateTemplateReferences({+ templateInstanceId: "card",+ migration: { type: "rename", to: "Feature Card" },+ renderScope: "page:/",+ dryRun: true,+ });+ expect(preview).toMatchObject({+ status: "confirmation-required",+ discoveryComplete: true,+ updateCount: 1,+ files: [{ assetId: "article", changed: true }],+ });+ if (preview.status !== "confirmation-required") {+ throw new Error("Expected migration confirmation");+ }+ state.props?.set("src", {+ id: "src",+ instanceId: "block",+ name: "src",+ type: "expression",+ value: '"article"',+ });+ await expect(+ operations.migrateTemplateReferences({+ templateInstanceId: "card",+ migration: { type: "rename", to: "Feature Card" },+ renderScope: "page:/static-expression",+ dryRun: true,+ })+ ).resolves.toMatchObject({+ status: "confirmation-required",+ discoveryComplete: true,+ files: [{ assetId: "article" }],+ });++ const result = await operations.migrateTemplateReferences({+ templateInstanceId: "card",+ migration: { type: "rename", to: "Feature Card" },+ renderScope: "page:/",+ confirmationToken: preview.confirmationToken,+ });+ expect(result).toMatchObject({+ status: "complete",+ updateCount: 1,+ files: [{ assetId: "article", status: "updated" }],+ });+ expect(updateContent).toHaveBeenCalledTimes(1);+ expect(getSource()).toContain('ws:name="Feature Card"');+ });++ test("discovers finite query candidates without loading unrelated MDX", async () => {+ const state = createState("expression");+ const resourceVariable = encodeDataVariableId("posts-data");+ const sourceProp = state.props?.get("src");+ if (sourceProp?.type !== "expression") {+ throw new Error("Expected expression source");+ }+ sourceProp.value = `${resourceVariable}.data.properties.mdx`;+ state.dataSources?.set("posts-data", {+ type: "resource",+ id: "posts-data",+ scopeInstanceId: "block",+ name: "posts",+ resourceId: "posts",+ });+ state.resources?.set("posts", {+ id: "posts",+ name: "Posts",+ control: "system",+ method: "post",+ url: '"/$resources/assets"',+ headers: [],+ body: createStructuredAssetQueryResourceBody({+ where: {+ all: [+ {+ field: ["properties", "category"],+ operator: "eq",+ value: '"published"',+ },+ ],+ },+ sort: [],+ limit: "1",+ offset: "0",+ output: { mode: "all", includeMetadata: true },+ content: { mode: "none" },+ }),+ });+ const templates = state.instances?.get("templates")!;+ templates.children.push({ type: "id", value: "card" });+ state.instances?.set("card", {+ type: "instance",+ id: "card",+ component: elementComponent,+ tag: "div",+ label: "Card",+ children: [],+ });+ const readIds: string[] = [];+ const source = '<ws.element ws:name="Card" />';+ const session = createMdxAssetEditingSession({+ repository: {+ readContent: async ({ assetId }) => {+ readIds.push(assetId);+ const bytes = encoder.encode(source);+ return {+ asset: {+ id: assetId,+ projectId: "project",+ type: "file" as const,+ format: "file",+ name: `${assetId}-revision.mdx`,+ filename: assetId,+ size: bytes.byteLength,+ description: null,+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-01T00:00:00.000Z",+ meta: {},+ },+ data: {+ async *[Symbol.asyncIterator]() {+ yield bytes;+ },+ },+ };+ },+ updateContent: async () => {+ throw new Error("Dry-run must not write");+ },+ },+ authorizeAsset: () => true,+ resolveExpressionAssetId: () => "article.mdx",+ });+ const migrationContentArtifact = {+ documents: [+ {+ _id: "post",+ _type: "asset.file",+ name: "post.json",+ path: "post.json",+ key: "post",+ extension: "json",+ mimeType: "application/json",+ size: 1,+ properties: { category: "published", mdx: "article.mdx" },+ },+ {+ _id: "private-post",+ _type: "asset.file",+ name: "private.json",+ path: "private.json",+ key: "private",+ extension: "json",+ mimeType: "application/json",+ size: 1,+ properties: { category: "private", mdx: "private.mdx" },+ },+ ],+ } as unknown as ContentArtifactV1;+ const operations = createContentBlockApplicationOperations({+ projectId: "project",+ session,+ getState: () => state,+ migrationContentArtifact,+ context: { createId: () => "generated" },+ });++ const result = await operations.migrateTemplateReferences({+ templateInstanceId: "card",+ migration: { type: "remove" },+ renderScope: "page:/posts/one",+ dryRun: true,+ });++ expect(result).toMatchObject({+ status: "confirmation-required",+ discoveryComplete: true,+ files: [{ assetId: "article.mdx", omissionCount: 1 }],+ });+ expect(readIds).toEqual(["article.mdx"]);+ expect(readIds).not.toContain("private.mdx");+ });+});diff --git a/packages/project-build/src/runtime/content-block-application.ts b/packages/project-build/src/runtime/content-block-application.tsnew file mode 100644index 0000000000..2c89ab74ff--- /dev/null+++ b/packages/project-build/src/runtime/content-block-application.ts@@ -0,0 +1,1660 @@+import {+ blockTemplateComponent,+ getContentBlockSource,+ type ContentBlockSource,+} from "@webstudio-is/sdk";+import {+ createConfirmationToken,+ validateConfirmationToken,+} from "../confirmation-token";+import type { BuilderPatchChange } from "../contracts/patch";+import type { BuilderState } from "../state/builder-state";+import type { ContentArtifactV1 } from "@webstudio-is/content-engine";+import { parseJsonExpression } from "@webstudio-is/expression";+import { resolvePublishedMdxAssetCandidates } from "../content-database";+import {+ ContentBlockSourceAuthorityRequiredError,+ prepareContentBlockConnect,+ prepareContentBlockDisconnect,+ prepareContentBlockSwitch,+ type ContentBlockSourceAuthority,+ type PreparedContentBlockSourceLifecycle,+} from "./content-block-source-lifecycle";+import type {+ BuilderRuntimeContext,+ ContentBlockPersistenceResult,+ ContentBlockPersistenceStep,+ ContentBlockSourceInspection,+} from "./context";+import {+ getContentBlockSessionSource,+ isContentBlockSessionSourceCommitted,+ type createMdxAssetEditingSession,+ type MdxAssetEditingSessionState,+} from "./mdx-asset-session";+import type { PendingMdxContentStorageWrite } from "./mdx-storage-adapter";+import {+ getRuntimeMutationPersistenceOrder,+ type BuilderRuntimeMutation,+ type ContentStorageChange,+} from "./mutation";+import {+ getContentBlockRenderScopeKey,+ getContentStorageIdentityKey,+} from "./content-storage";+import { getSourceBackedBlockTemplateContext } from "./block";+import {+ planMdxTemplateMigration,+ validateMdxTemplateMigrationConfirmation,+ type MdxTemplateMigration,+ type MdxTemplateMigrationDiagnostic,+} from "./mdx-template-migration";+import {+ executeBuilderRuntimeOperation,+ getBuilderRuntimeOperation,+ type BuilderRuntimeOperationId,+} from "./registry";++export type MdxAssetEditingSession = ReturnType<+ typeof createMdxAssetEditingSession+>;++export type ContentBlockApplicationErrorCode =+ | "content-source-not-configured"+ | "content-source-not-loaded"+ | "content-source-authority-required"+ | "content-source-confirmation-required"+ | "content-source-stale-confirmation"+ | "content-source-session-failed"+ | "content-source-write-conflict"+ | "content-source-authorization-failed"+ | "content-source-partial-persistence";++export type ContentBlockApplicationResult<Result = unknown> =+ | Readonly<{ status: "complete"; result: Result }>+ | Readonly<{+ status: "confirmation-required";+ code: "content-source-confirmation-required";+ confirmationToken: string;+ confirmationExpiresAt: string;+ result: Result;+ }>+ | Readonly<{+ status: "blocked";+ code: ContentBlockApplicationErrorCode;+ message: string;+ result?: Result;+ }>+ | Readonly<{+ status: "partial";+ code: "content-source-partial-persistence";+ message: string;+ result: Result;+ }>;++const lifecycleConfirmationTtlMs = 5 * 60_000;++const getConfiguredSource = (state: BuilderState, blockInstanceId: string) =>+ getContentBlockSource({+ blockInstanceId,+ props: state.props?.values() ?? [],+ });++export const getContentBlockSessionErrorCode = (+ state: MdxAssetEditingSessionState+): ContentBlockApplicationErrorCode => {+ if (state.status === "conflicting") {+ return "content-source-write-conflict";+ }+ if (+ state.diagnostics.some(+ (diagnostic) => diagnostic.code === "authorization-failed"+ )+ ) {+ return "content-source-authorization-failed";+ }+ return "content-source-session-failed";+};++export const getContentBlockSessionMessage = (+ state: MdxAssetEditingSessionState+) =>+ "error" in state+ ? state.error.message+ : state.status === "conflicting"+ ? "The MDX Asset changed remotely"+ : `The MDX Asset session is ${state.status}`;++export type { ContentBlockPersistenceResult, ContentBlockPersistenceStep };++export type ContentBlockPersistencePlanStep = Readonly<{+ type: "asset" | "project";+ root?: PendingMdxContentStorageWrite["root"]["identity"];+ preflight: () => Promise<+ | Readonly<{ status: "ready" }>+ | Readonly<{ status: "failed"; code: string; message: string }>+ >;+ persist: () => Promise<+ | Readonly<{ status: "saved" }>+ | Readonly<{ status: "failed"; code: string; message: string }>+ >;+}>;++export const executeContentBlockPersistencePlan = async (+ plan: readonly ContentBlockPersistencePlanStep[]+): Promise<ContentBlockPersistenceResult> => {+ for (const [index, planned] of plan.entries()) {+ let preflight: Awaited<ReturnType<typeof planned.preflight>>;+ try {+ preflight = await planned.preflight();+ } catch {+ preflight = {+ status: "failed",+ code: "content-source-session-failed",+ message: "Content persistence preflight failed",+ };+ }+ if (preflight.status === "ready") {+ continue;+ }+ return {+ status: "failed",+ steps: plan.map((step, stepIndex) => ({+ type: step.type,+ status: stepIndex === index ? "failed" : "not-attempted",+ ...(step.root === undefined ? {} : { root: step.root }),+ ...(stepIndex === index+ ? { code: preflight.code, message: preflight.message }+ : {}),+ })),+ retry: {+ replan: true,+ roots: plan.flatMap(({ type, root }) =>+ type === "asset" && root !== undefined ? [root] : []+ ),+ project: plan.some(({ type }) => type === "project"),+ },+ };+ }+ const steps: ContentBlockPersistenceStep[] = [];+ for (const [index, planned] of plan.entries()) {+ let persisted: Awaited<ReturnType<typeof planned.persist>>;+ try {+ persisted = await planned.persist();+ } catch {+ persisted = {+ status: "failed",+ code: "content-source-session-failed",+ message: "Content persistence failed",+ };+ }+ steps.push({+ type: planned.type,+ status: persisted.status,+ ...(planned.root === undefined ? {} : { root: planned.root }),+ ...(persisted.status === "failed"+ ? { code: persisted.code, message: persisted.message }+ : {}),+ });+ if (persisted.status === "saved") {+ continue;+ }+ for (const remaining of plan.slice(index + 1)) {+ steps.push({+ type: remaining.type,+ status: "not-attempted",+ ...(remaining.root === undefined ? {} : { root: remaining.root }),+ });+ }+ return {+ status: index === 0 ? "failed" : "partial",+ steps,+ retry: {+ replan: true,+ roots: plan+ .slice(index)+ .flatMap(({ type, root }) =>+ type === "asset" && root !== undefined ? [root] : []+ ),+ project: plan.slice(index).some(({ type }) => type === "project"),+ },+ };+ }+ return {+ status: "complete",+ steps,+ retry: { replan: true, roots: [], project: false },+ };+};++type ContentBlockSemanticMutation<Result extends Record<string, unknown>> =+ BuilderRuntimeMutation<Result> &+ Readonly<{ persistence?: ContentBlockPersistenceResult }>;++const getContentStorageSessionState = (+ session: MdxAssetEditingSession,+ identity: ContentStorageChange["root"]["identity"]+) => {+ const identityKey = getContentStorageIdentityKey(identity);+ return session+ .list()+ .find(+ (state) =>+ "identity" in state &&+ getContentStorageIdentityKey(state.identity) === identityKey+ );+};++export const persistPreparedContentBlockLifecycle = async ({+ prepared,+ session,+ commitProjectPayload,+ canCommitProjectPayload = () => true,+}: {+ prepared: PreparedContentBlockSourceLifecycle;+ session: MdxAssetEditingSession;+ commitProjectPayload?: (+ payload: readonly BuilderPatchChange[]+ ) => void | Promise<void>;+ canCommitProjectPayload?: () => boolean;+}): Promise<+ Readonly<{+ status: "complete" | "partial" | "failed";+ state?: MdxAssetEditingSessionState;+ persistence: ContentBlockPersistenceResult;+ }>+> => {+ let state = prepared.sourceState;+ const owners: Array<{ key: string; expectedSource: string } | undefined> = [];+ const assetPlan = prepared.storageWrites.map((write, index) => ({+ type: "asset" as const,+ root: write.root.identity,+ preflight: async () => {+ const owner = getContentStorageSessionState(session, write.root.identity);+ const expectedSource = getContentBlockSessionSource(owner);+ if (+ owner === undefined ||+ !("key" in owner) ||+ expectedSource === undefined+ ) {+ return {+ status: "failed" as const,+ code: "content-source-not-loaded",+ message: "The MDX Asset is not loaded",+ };+ }+ const preflight = await session.prepareSourceReplacement({+ key: owner.key,+ expectedSource,+ source: write.source,+ });+ if (preflight.status === "blocked") {+ state = preflight.state;+ return {+ status: "failed" as const,+ code: getContentBlockSessionErrorCode(preflight.state),+ message: getContentBlockSessionMessage(preflight.state),+ };+ }+ owners[index] = { key: owner.key, expectedSource };+ return { status: "ready" as const };+ },+ persist: async () => {+ const owner = owners[index];+ if (owner === undefined) {+ return {+ status: "failed" as const,+ code: "content-source-session-failed",+ message: "The MDX Asset persistence plan is stale",+ };+ }+ const persisted = await session.persistSourceReplacement({+ key: owner.key,+ expectedSource: owner.expectedSource,+ source: write.source,+ });+ state = persisted.state;+ return persisted.status === "applied"+ ? { status: "saved" as const }+ : {+ status: "failed" as const,+ code: getContentBlockSessionErrorCode(persisted.state),+ message: getContentBlockSessionMessage(persisted.state),+ };+ },+ }));+ const projectPlan =+ prepared.projectPayload.length === 0+ ? []+ : [+ {+ type: "project" as const,+ preflight: async () =>+ canCommitProjectPayload() && commitProjectPayload !== undefined+ ? { status: "ready" as const }+ : {+ status: "failed" as const,+ code: "content-source-session-failed",+ message:+ commitProjectPayload === undefined+ ? "Project persistence is not available"+ : "The project changed while preparing this source update.",+ },+ persist: async () => {+ if (canCommitProjectPayload() === false) {+ return {+ status: "failed" as const,+ code: "content-source-session-failed",+ message: "The project changed before its persistence step.",+ };+ }+ if (commitProjectPayload === undefined) {+ return {+ status: "failed" as const,+ code: "content-source-session-failed",+ message: "Project persistence is not available",+ };+ }+ try {+ await commitProjectPayload(prepared.projectPayload);+ return { status: "saved" as const };+ } catch (error) {+ return {+ status: "failed" as const,+ code: "content-source-partial-persistence",+ message:+ error instanceof Error+ ? error.message+ : "Project persistence failed",+ };+ }+ },+ },+ ];+ const persistence = await executeContentBlockPersistencePlan([+ ...assetPlan,+ ...projectPlan,+ ]);+ return {+ status: persistence.status,+ state,+ persistence,+ };+};++export const recoverContentBlockSession = async ({+ session,+ state,+ action,+ dryRun = false,+ reopen,+}: {+ session: MdxAssetEditingSession;+ state: MdxAssetEditingSessionState;+ action: "retry" | "reload-remote" | "copy-unsaved-mdx";+ dryRun?: boolean;+ reopen?: () => Promise<MdxAssetEditingSessionState>;+}): Promise<+ | Readonly<{+ status: "complete";+ state: MdxAssetEditingSessionState;+ source?: string;+ changedAsset: boolean;+ }>+ | Readonly<{+ status: "blocked";+ code: ContentBlockApplicationErrorCode;+ message: string;+ state: MdxAssetEditingSessionState;+ }>+> => {+ if (action === "copy-unsaved-mdx") {+ const source =+ "key" in state ? session.copyUnsavedSource(state.key) : undefined;+ return source === undefined+ ? {+ status: "blocked",+ code: "content-source-session-failed",+ message: "The MDX Asset session has no unsaved local source",+ state,+ }+ : { status: "complete", state, source, changedAsset: false };+ }+ if (!("key" in state)) {+ return {+ status: "blocked",+ code: "content-source-not-loaded",+ message: "The MDX Asset is not loaded",+ state,+ };+ }+ if (action === "retry") {+ if (+ (state.status !== "failed" || !("localSource" in state)) &&+ (state.status !== "recoverable" || reopen === undefined)+ ) {+ return {+ status: "blocked",+ code: "content-source-session-failed",+ message: `Retry is not available while the MDX Asset session is ${state.status}`,+ state,+ };+ }+ } else if (state.status !== "conflicting") {+ return {+ status: "blocked",+ code: "content-source-session-failed",+ message: `Remote reload is not available while the MDX Asset session is ${state.status}`,+ state,+ };+ }+ if (dryRun) {+ return { status: "complete", state, changedAsset: false };+ }+ const next =+ action === "reload-remote"+ ? await session.reloadRemote(state.key)+ : state.status === "recoverable" && reopen !== undefined+ ? await reopen()+ : await session.retry(state.key);+ const committedRetry =+ action === "retry" &&+ "localSource" in state &&+ isContentBlockSessionSourceCommitted({+ state: next,+ source: state.localSource,+ });+ return next.status === "saved" || committedRetry+ ? {+ status: "complete",+ state: next,+ changedAsset: action === "reload-remote" || committedRetry,+ }+ : {+ status: "blocked",+ code: getContentBlockSessionErrorCode(next),+ message: getContentBlockSessionMessage(next),+ state: next,+ };+};++export const persistContentBlockStorageChanges = async ({+ session,+ key,+ changes,+ publishState,+}: {+ session: MdxAssetEditingSession;+ key: string;+ changes: readonly ContentStorageChange[];+ publishState?: (state: MdxAssetEditingSessionState) => void;+}): Promise<+ | Readonly<{+ status: "complete";+ state: MdxAssetEditingSessionState;+ }>+ | Readonly<{+ status: "blocked";+ code: ContentBlockApplicationErrorCode;+ message: string;+ state: MdxAssetEditingSessionState;+ }>+> => {+ const queued = await session.queueSave({ key, changes });+ publishState?.(queued);+ const expectedSource = getContentBlockSessionSource(queued);+ const saved =+ queued.status === "pending" ? await session.flush(queued.key) : queued;+ if (saved !== queued) {+ publishState?.(saved);+ }+ return expectedSource !== undefined &&+ isContentBlockSessionSourceCommitted({+ state: saved,+ source: expectedSource,+ })+ ? { status: "complete", state: saved }+ : {+ status: "blocked",+ code: getContentBlockSessionErrorCode(saved),+ message: getContentBlockSessionMessage(saved),+ state: saved,+ };+};++const groupExternalStorageChanges = (+ changes: readonly ContentStorageChange[]+) => {+ const groups = new Map<+ string,+ {+ identity: ContentStorageChange["root"]["identity"];+ changes: ContentStorageChange[];+ }+ >();+ for (const change of changes) {+ const key = getContentStorageIdentityKey(change.root.identity);+ const group = groups.get(key) ?? {+ identity: change.root.identity,+ changes: [],+ };+ group.changes.push(change);+ groups.set(key, group);+ }+ return [...groups.values()];+};++export const preflightContentBlockStorageChanges = async ({+ session,+ changes,+}: {+ session: MdxAssetEditingSession;+ changes: readonly ContentStorageChange[];+}): Promise<+ | Readonly<{ status: "ready" }>+ | Readonly<{+ status: "failed";+ code: ContentBlockApplicationErrorCode;+ message: string;+ persistence: ContentBlockPersistenceResult;+ }>+> => {+ const groups = groupExternalStorageChanges(changes);+ for (const [index, group] of groups.entries()) {+ const owner = getContentStorageSessionState(session, group.identity);+ const preflight =+ owner !== undefined && "key" in owner+ ? await session.preflightSave({+ key: owner.key,+ changes: group.changes,+ })+ : {+ status: "blocked" as const,+ reason: "The exact MDX Asset render scope is not loaded",+ };+ if (preflight.status === "ready") {+ continue;+ }+ const persistence: ContentBlockPersistenceResult = {+ status: "failed",+ steps: groups.map((candidate, candidateIndex) => ({+ type: "asset" as const,+ status:+ candidateIndex === index+ ? ("failed" as const)+ : ("not-attempted" as const),+ root: candidate.identity,+ ...(candidateIndex === index+ ? {+ code: "content-source-session-failed",+ message: preflight.reason,+ }+ : {}),+ })),+ retry: {+ replan: true,+ roots: groups.map(({ identity }) => identity),+ project: false,+ },+ };+ return {+ status: "failed",+ code: "content-source-session-failed",+ message: preflight.reason,+ persistence,+ };+ }+ return { status: "ready" };+};++export const persistContentBlockStorageChangesSerially = async ({+ session,+ changes,+ publishState,+ projectStep,+ persistenceOrder = "storage-first",+}: {+ session: MdxAssetEditingSession;+ changes: readonly ContentStorageChange[];+ publishState?: (state: MdxAssetEditingSessionState) => void;+ projectStep?: ContentBlockPersistencePlanStep;+ persistenceOrder?: "storage-first" | "project-first";+}): Promise<ContentBlockPersistenceResult> => {+ const groups = groupExternalStorageChanges(changes);+ const assetPlan = groups.map((group) => ({+ type: "asset" as const,+ root: group.identity,+ preflight: async () => {+ const owner = getContentStorageSessionState(session, group.identity);+ if (owner === undefined || !("key" in owner)) {+ return {+ status: "failed" as const,+ code: "content-source-not-loaded",+ message: "The exact MDX Asset render scope is not loaded",+ };+ }+ const preflight = await session.preflightSave({+ key: owner.key,+ changes: group.changes,+ });+ return preflight.status === "ready"+ ? preflight+ : {+ status: "failed" as const,+ code: "content-source-session-failed",+ message: preflight.reason,+ };+ },+ persist: async () => {+ const owner = getContentStorageSessionState(session, group.identity);+ if (owner === undefined || !("key" in owner)) {+ return {+ status: "failed" as const,+ code: "content-source-not-loaded",+ message: "The exact MDX Asset render scope is not loaded",+ };+ }+ const persisted = await persistContentBlockStorageChanges({+ session,+ key: owner.key,+ changes: group.changes,+ publishState,+ });+ return persisted.status === "complete"+ ? { status: "saved" as const }+ : {+ status: "failed" as const,+ code: persisted.code,+ message: persisted.message,+ };+ },+ }));+ return executeContentBlockPersistencePlan(+ projectStep === undefined+ ? assetPlan+ : persistenceOrder === "project-first"+ ? [projectStep, ...assetPlan]+ : [...assetPlan, projectStep]+ );+};++const getLifecycleConfirmationPayload = ({+ projectId,+ projectVersion,+ prepared,+ blockInstanceId,+ renderScope,+ source,+ authority,+}: {+ projectId: string;+ projectVersion?: number;+ prepared: PreparedContentBlockSourceLifecycle;+ blockInstanceId: string;+ renderScope: string;+ source?: ContentBlockSource;+ authority?: ContentBlockSourceAuthority;+}) => ({+ operation: `content-block-${prepared.action}`,+ projectId,+ projectVersion,+ blockInstanceId,+ renderScope,+ source,+ authority,+ changesProject: prepared.projectPayload.length > 0,+ storageWrites: prepared.storageWrites.map((write) => ({+ identity: write.root.identity,+ expectedContentRef: write.root.identity.contentRef,+ expectedRevision: write.expectedRevision,+ source: write.source,+ })),+});++export type ContentBlockLifecyclePlan = Readonly<{+ action: PreparedContentBlockSourceLifecycle["action"];+ changesProject: boolean;+ storageWrites: readonly Readonly<{+ identity: PendingMdxContentStorageWrite["root"]["identity"];+ expectedRevision: string;+ }>[];+ diagnostics: PreparedContentBlockSourceLifecycle["diagnostics"];+ persistenceOrder: PreparedContentBlockSourceLifecycle["persistenceOrder"];+ persistence?: ContentBlockPersistenceResult;+}>;++const serializeLifecyclePlan = (+ prepared: PreparedContentBlockSourceLifecycle+): ContentBlockLifecyclePlan => ({+ action: prepared.action,+ changesProject: prepared.projectPayload.length > 0,+ storageWrites: prepared.storageWrites.map((write) => ({+ identity: write.root.identity,+ expectedRevision: write.expectedRevision,+ })),+ diagnostics: prepared.diagnostics,+ persistenceOrder: prepared.persistenceOrder,+});++export const createContentBlockApplicationOperations = ({+ projectId,+ session,+ getState,+ getProjectVersion,+ commitProjectPayload,+ migrationContentArtifact,+ context,+}: {+ projectId: string;+ session: MdxAssetEditingSession;+ getState: () => BuilderState;+ getProjectVersion?: () => number | undefined;+ commitProjectPayload?: (+ payload: readonly BuilderPatchChange[]+ ) => void | Promise<void>;+ migrationContentArtifact?: ContentArtifactV1;+ context: BuilderRuntimeContext;+}) => {+ const activeKeys = new Map<string, string>();+ const publishSession = (state: MdxAssetEditingSessionState) => {+ if ("identity" in state && "key" in state) {+ activeKeys.set(+ getContentBlockRenderScopeKey(+ state.identity.blockInstanceId,+ state.identity.renderScope+ ),+ state.key+ );+ }+ return state;+ };+ const getActiveState = (blockInstanceId: string, renderScope: string) => {+ const key = activeKeys.get(+ getContentBlockRenderScopeKey(blockInstanceId, renderScope)+ );+ return key === undefined ? undefined : session.get(key);+ };++ const inspectSource = async ({+ blockInstanceId,+ renderScope,+ load = true,+ variables,+ }: {+ blockInstanceId: string;+ renderScope: string;+ load?: boolean;+ variables?: Readonly<Record<string, unknown>>;+ }): Promise<ContentBlockSourceInspection> => {+ const state = getState();+ const configuredSource = getConfiguredSource(state, blockInstanceId);+ let sourceState = getActiveState(blockInstanceId, renderScope);+ if (sourceState === undefined && configuredSource !== undefined && load) {+ sourceState = publishSession(+ await session.open({+ blockInstanceId,+ source: configuredSource,+ renderScope,+ state,+ projectId,+ variables,+ })+ );+ }+ const diagnostics = sourceState?.diagnostics ?? [];+ const canEdit =+ sourceState?.status === "saved" || sourceState?.status === "pending";+ const repairRoutes: ContentBlockSourceInspection["repairRoutes"][number][] =+ [];+ if (sourceState !== undefined && "identity" in sourceState) {+ repairRoutes.push("open-file");+ }+ if (sourceState?.status === "failed") {+ repairRoutes.push("retry");+ }+ if (sourceState?.status === "conflicting") {+ repairRoutes.push("reload-remote");+ }+ if (sourceState !== undefined && "localSource" in sourceState) {+ repairRoutes.push("copy-unsaved-mdx");+ }+ if (configuredSource !== undefined) {+ repairRoutes.push("disconnect-with-copy");+ }+ return {+ blockInstanceId,+ renderScope,+ configuredSource,+ resolvedIdentity:+ sourceState !== undefined && "identity" in sourceState+ ? sourceState.identity+ : undefined,+ sessionStatus: sourceState?.status ?? "disconnected",+ pending: sourceState?.status === "pending",+ diagnostics,+ capabilities: {+ canConnect: configuredSource === undefined,+ canSwitch: configuredSource !== undefined,+ canDisconnectWithCopy: configuredSource !== undefined && canEdit,+ canEdit,+ canRetry: sourceState?.status === "failed",+ canReloadRemote: sourceState?.status === "conflicting",+ canCopyUnsavedSource:+ sourceState !== undefined && "localSource" in sourceState,+ },+ repairRoutes,+ };+ };++ const prepareLifecycle = async ({+ action,+ blockInstanceId,+ renderScope,+ source,+ authority,+ variables,+ }: {+ action: "connect" | "switch" | "disconnect";+ blockInstanceId: string;+ renderScope: string;+ source?: ContentBlockSource;+ authority?: ContentBlockSourceAuthority;+ variables?: Readonly<Record<string, unknown>>;+ }) => {+ const state = getState();+ if (action === "connect") {+ if (source === undefined) {+ throw new Error("Connect requires a Content Block source");+ }+ return await prepareContentBlockConnect({+ state,+ blockInstanceId,+ source,+ renderScope,+ projectId,+ authority,+ session,+ context,+ variables,+ });+ }+ let active = getActiveState(blockInstanceId, renderScope);+ if (active === undefined) {+ await inspectSource({+ blockInstanceId,+ renderScope,+ variables,+ });+ active = getActiveState(blockInstanceId, renderScope);+ }+ if (active === undefined || !("key" in active)) {+ throw new Error("The Content Block source is not loaded");+ }+ if (action === "switch") {+ if (source === undefined) {+ throw new Error("Switch requires a Content Block source");+ }+ return await prepareContentBlockSwitch({+ state,+ blockInstanceId,+ currentSessionKey: active.key,+ source,+ renderScope,+ projectId,+ authority,+ session,+ context,+ variables,+ });+ }+ return await prepareContentBlockDisconnect({+ state,+ blockInstanceId,+ currentSessionKey: active.key,+ renderScope,+ session,+ context,+ });+ };++ const applyLifecycle = async (+ {+ action,+ blockInstanceId,+ renderScope,+ source,+ authority,+ dryRun = false,+ confirmationToken,+ variables,+ }: {+ action: "connect" | "switch" | "disconnect";+ blockInstanceId: string;+ renderScope: string;+ source?: ContentBlockSource;+ authority?: ContentBlockSourceAuthority;+ dryRun?: boolean;+ confirmationToken?: string;+ variables?: Readonly<Record<string, unknown>>;+ },+ execution?: {+ commitProjectPayload?: (+ payload: readonly BuilderPatchChange[]+ ) => void | Promise<void>;+ }+ ): Promise<ContentBlockApplicationResult<ContentBlockLifecyclePlan>> => {+ const projectVersionBeforePreparation =+ getProjectVersion?.() ?? context.projectVersion;+ const stateBeforePreparation = getState();+ const blockBeforePreparation =+ stateBeforePreparation.instances?.get(blockInstanceId);+ const hadPersistedBody =+ blockBeforePreparation?.children.some(+ (child) =>+ child.type !== "id" ||+ stateBeforePreparation.instances?.get(child.value)?.component !==+ blockTemplateComponent+ ) === true;+ const hadConfiguredSource =+ getConfiguredSource(stateBeforePreparation, blockInstanceId) !==+ undefined;+ let prepared: PreparedContentBlockSourceLifecycle;+ try {+ prepared = await prepareLifecycle({+ action,+ blockInstanceId,+ renderScope,+ source,+ authority,+ variables,+ });+ } catch (error) {+ if (error instanceof ContentBlockSourceAuthorityRequiredError) {+ return {+ status: "blocked",+ code: "content-source-authority-required",+ message: error.message,+ };+ }+ return {+ status: "blocked",+ code: "content-source-session-failed",+ message:+ error instanceof Error ? error.message : "Source update failed",+ };+ }+ const confirmationPayload = getLifecycleConfirmationPayload({+ projectId,+ projectVersion: projectVersionBeforePreparation,+ prepared,+ blockInstanceId,+ renderScope,+ source,+ authority,+ });+ const destructive =+ prepared.storageWrites.length > 0 ||+ (action === "connect" && hadPersistedBody) ||+ (action === "switch" && authority === "use-file-content") ||+ (action === "disconnect" && hadConfiguredSource);+ const confirmed =+ destructive === false+ ? true+ : await validateConfirmationToken(+ confirmationToken,+ confirmationPayload+ );+ if (destructive && (dryRun || confirmed === false)) {+ const confirmation = await createConfirmationToken(+ confirmationPayload,+ lifecycleConfirmationTtlMs+ );+ return {+ status: "confirmation-required",+ code: "content-source-confirmation-required",+ confirmationToken: confirmation.token,+ confirmationExpiresAt: new Date(confirmation.expiresAt).toISOString(),+ result: serializeLifecyclePlan(prepared),+ };+ }+ if (dryRun) {+ return { status: "complete", result: serializeLifecyclePlan(prepared) };+ }+ const projectCommit =+ execution?.commitProjectPayload ?? commitProjectPayload;+ const persisted = await persistPreparedContentBlockLifecycle({+ prepared,+ session,+ commitProjectPayload: projectCommit,+ canCommitProjectPayload: () =>+ prepared.projectPayload.length === 0 ||+ (projectCommit !== undefined &&+ (getProjectVersion?.() ?? context.projectVersion) ===+ projectVersionBeforePreparation),+ });+ const plan = {+ ...serializeLifecyclePlan(prepared),+ persistence: persisted.persistence,+ };+ if (persisted.status !== "complete") {+ return {+ status: persisted.status === "partial" ? "partial" : "blocked",+ code: "content-source-partial-persistence",+ message:+ persisted.status === "partial"+ ? "Some content changes were saved. Retry the unfinished steps."+ : "The content changes could not be saved.",+ result: plan,+ };+ }+ if (action === "disconnect") {+ activeKeys.delete(+ getContentBlockRenderScopeKey(blockInstanceId, renderScope)+ );+ } else if (persisted.state !== undefined) {+ publishSession(persisted.state);+ }+ return { status: "complete", result: plan };+ };++ const semanticEdit = async <Result extends Record<string, unknown>>({+ operationId,+ input,+ blockInstanceId,+ renderScope,+ variables,+ dryRun = false,+ }: {+ operationId: string;+ input: unknown;+ blockInstanceId: string;+ renderScope: string;+ variables?: Readonly<Record<string, unknown>>;+ dryRun?: boolean;+ }): Promise<+ | Readonly<{+ status: "complete";+ result: ContentBlockSemanticMutation<Result>;+ }>+ | Readonly<{+ status: "blocked" | "partial";+ code: string;+ message: string;+ result?: ContentBlockSemanticMutation<Result>;+ }>+ > => {+ const projectVersionBeforeMutation =+ getProjectVersion?.() ?? context.projectVersion;+ let active = getActiveState(blockInstanceId, renderScope);+ if (active === undefined) {+ await inspectSource({ blockInstanceId, renderScope, variables });+ active = getActiveState(blockInstanceId, renderScope);+ }+ if (active === undefined || !("root" in active) || !("key" in active)) {+ return {+ status: "blocked",+ code: "content-source-not-loaded",+ message: "Inspect and load the exact Content Block render scope first",+ };+ }+ const runtimeOperationId = operationId as BuilderRuntimeOperationId;+ if (operationId.startsWith("instances.") === false) {+ return {+ status: "blocked",+ code: "content-source-session-failed",+ message: "Content Block semantic edit requires an instance mutation",+ };+ }+ let operation;+ try {+ operation = getBuilderRuntimeOperation(runtimeOperationId);+ } catch {+ return {+ status: "blocked",+ code: "content-source-session-failed",+ message: "Content Block semantic edit operation is not supported",+ };+ }+ if (operation.kind !== "mutation") {+ return {+ status: "blocked",+ code: "content-source-session-failed",+ message: "Content Block semantic edit requires an instance mutation",+ };+ }+ const mutation = await executeBuilderRuntimeOperation<+ BuilderRuntimeMutation<Result>+ >({+ id: runtimeOperationId,+ state: getState(),+ input,+ context: {+ ...context,+ materializedContent: [active.root],+ returnStorageChanges: true,+ },+ });+ const storageChanges = mutation.storageChanges ?? [];+ if (storageChanges.length === 0) {+ if (mutation.payload.length > 0 && dryRun === false) {+ if (commitProjectPayload === undefined) {+ return {+ status: "blocked",+ code: "content-source-session-failed",+ message: "Project persistence is not available for this edit",+ result: mutation,+ };+ }+ await commitProjectPayload(mutation.payload);+ }+ return { status: "complete", result: mutation };+ }+ if (dryRun) {+ return { status: "complete", result: mutation };+ }+ const projectFirst =+ mutation.payload.length > 0 &&+ getRuntimeMutationPersistenceOrder(mutation) === "project-first";+ const projectStep: ContentBlockPersistencePlanStep | undefined =+ mutation.payload.length === 0+ ? undefined+ : {+ type: "project",+ preflight: async () =>+ commitProjectPayload !== undefined &&+ (getProjectVersion?.() ?? context.projectVersion) ===+ projectVersionBeforeMutation+ ? { status: "ready" }+ : {+ status: "failed",+ code: "content-source-session-failed",+ message:+ commitProjectPayload === undefined+ ? "Project persistence is not available for this edit"+ : "The project changed before the content edit was saved",+ },+ persist: async () => {+ if (+ (getProjectVersion?.() ?? context.projectVersion) !==+ projectVersionBeforeMutation+ ) {+ return {+ status: "failed",+ code: "content-source-session-failed",+ message: projectFirst+ ? "The project changed before the content edit was saved"+ : "MDX Assets were saved, but the project changed before its step.",+ };+ }+ if (commitProjectPayload === undefined) {+ return {+ status: "failed",+ code: "content-source-session-failed",+ message: "Project persistence is not available for this edit",+ };+ }+ try {+ await commitProjectPayload(mutation.payload);+ return { status: "saved" };+ } catch (error) {+ return {+ status: "failed",+ code: "content-source-session-failed",+ message:+ error instanceof Error+ ? error.message+ : "Project persistence failed",+ };+ }+ },+ };+ const persistence = await persistContentBlockStorageChangesSerially({+ session,+ changes: storageChanges,+ publishState: publishSession,+ projectStep,+ persistenceOrder: projectFirst ? "project-first" : "storage-first",+ });+ if (persistence.status === "complete") {+ return {+ status: "complete",+ result: { ...mutation, persistence },+ };+ }+ const failure = persistence.steps.find(({ status }) => status === "failed");+ return {+ status: persistence.status === "partial" ? "partial" : "blocked",+ code: "content-source-partial-persistence",+ message:+ failure?.message ??+ (persistence.status === "partial"+ ? "Some content changes were saved. Retry the unfinished steps."+ : "The content changes could not be saved."),+ result: { ...mutation, persistence },+ };+ };++ const recover = async ({+ blockInstanceId,+ renderScope,+ action,+ dryRun = false,+ }: {+ blockInstanceId: string;+ renderScope: string;+ action: "retry" | "reload-remote" | "copy-unsaved-mdx";+ dryRun?: boolean;+ }) => {+ const active = getActiveState(blockInstanceId, renderScope);+ if (active === undefined || !("key" in active)) {+ return {+ status: "blocked" as const,+ code: "content-source-not-loaded" as const,+ message: "The MDX Asset is not loaded",+ };+ }+ const recovered = await recoverContentBlockSession({+ session,+ state: active,+ action,+ dryRun,+ reopen:+ action === "retry" && active.status === "recoverable"+ ? async () => {+ const configured = getConfiguredSource(+ getState(),+ blockInstanceId+ );+ return configured === undefined+ ? active+ : session.open({+ blockInstanceId,+ source: configured,+ renderScope,+ state: getState(),+ projectId,+ });+ }+ : undefined,+ });+ publishSession(recovered.state);+ const inspection = await inspectSource({+ blockInstanceId,+ renderScope,+ load: false,+ });+ return recovered.status === "complete"+ ? ({+ status: "complete",+ result: {+ source: recovered.source,+ inspection,+ changedAsset: recovered.changedAsset,+ },+ } as const)+ : ({+ status: "blocked",+ code: recovered.code,+ message: recovered.message,+ result: { inspection, changedAsset: false },+ } as const);+ };++ const getMaterializedContent = () =>+ session.list().flatMap((state) => ("root" in state ? [state.root] : []));++ const migrateTemplateReferences = async ({+ templateInstanceId,+ migration,+ renderScope,+ variables,+ selectedAssetIds = [],+ dryRun = false,+ confirmationToken,+ }: {+ templateInstanceId: string;+ migration: Readonly<{ type: "rename"; to: string } | { type: "remove" }>;+ renderScope: string;+ variables?: Readonly<Record<string, unknown>>;+ selectedAssetIds?: readonly string[];+ dryRun?: boolean;+ confirmationToken?: string;+ }) => {+ const state = getState();+ const template = getSourceBackedBlockTemplateContext({+ templateInstanceId,+ instances: state.instances ?? new Map(),+ props: state.props?.values() ?? [],+ });+ if (template === undefined) {+ return {+ status: "blocked" as const,+ code: "content-source-not-configured" as const,+ message:+ "The instance is not a direct Template of a source-backed Content Block",+ files: [],+ updateCount: 0,+ omissionCount: 0,+ discoveryComplete: false,+ };+ }+ const candidateIds = new Set(selectedAssetIds);+ let discoveryComplete =+ template.source.type === "asset" || selectedAssetIds.length > 0;+ if (template.source.type === "asset" && selectedAssetIds.length === 0) {+ candidateIds.add(template.source.assetId);+ } else if (+ template.source.type === "expression" &&+ selectedAssetIds.length === 0+ ) {+ const staticAssetId = parseJsonExpression(template.source.value);+ if (typeof staticAssetId === "string" && staticAssetId !== "") {+ candidateIds.add(staticAssetId);+ discoveryComplete = true;+ } else {+ const candidates = resolvePublishedMdxAssetCandidates({+ build: {+ instances: [...(state.instances?.values() ?? [])],+ props: [...(state.props?.values() ?? [])],+ dataSources: [...(state.dataSources?.values() ?? [])],+ resources: [...(state.resources?.values() ?? [])],+ pages: state.pages,+ },+ artifact: migrationContentArtifact,+ allowUnresolved: true,+ blockInstanceIds: new Set([template.blockInstanceId]),+ }).get(template.blockInstanceId);+ if (candidates !== undefined && candidates.length > 0) {+ for (const assetId of candidates) {+ candidateIds.add(assetId);+ }+ discoveryComplete = true;+ }+ }+ if (discoveryComplete === false) {+ const resolved = await session.open({+ blockInstanceId: template.blockInstanceId,+ source: template.source,+ renderScope,+ state,+ projectId,+ variables,+ });+ if ("identity" in resolved) {+ candidateIds.add(resolved.identity.assetId);+ }+ }+ }+ if (candidateIds.size === 0) {+ return {+ status: "blocked" as const,+ code: "content-source-not-loaded" as const,+ message: "No reachable MDX Assets were resolved for migration",+ files: [],+ updateCount: 0,+ omissionCount: 0,+ discoveryComplete,+ };+ }+ if (candidateIds.size > 100) {+ return {+ status: "blocked" as const,+ code: "content-source-session-failed" as const,+ message: "MDX template migration is limited to 100 Assets",+ files: [],+ updateCount: 0,+ omissionCount: 0,+ discoveryComplete: false,+ };+ }+ const loaded: Array<{+ key: string;+ assetId: string;+ revision: string;+ contentRef: string;+ source: string;+ }> = [];+ const diagnostics: MdxTemplateMigrationDiagnostic[] = [];+ for (const assetId of [...candidateIds].sort()) {+ const sourceState = await session.open({+ blockInstanceId: template.blockInstanceId,+ source: { type: "asset", assetId },+ renderScope: `${renderScope}:template-migration:${assetId}`,+ state,+ projectId,+ });+ if (!("identity" in sourceState) || !("source" in sourceState)) {+ const authorizationFailed = sourceState.diagnostics.some(+ (diagnostic) => diagnostic.code === "authorization-failed"+ );+ diagnostics.push({+ code: authorizationFailed+ ? "asset-authorization-failed"+ : "asset-write-failed",+ assetId,+ contentRef: assetId,+ message:+ "error" in sourceState+ ? sourceState.error.message+ : authorizationFailed+ ? "The referenced MDX Asset is not authorized"+ : "The referenced MDX Asset could not be loaded",+ });+ continue;+ }+ loaded.push({+ key: sourceState.key,+ assetId,+ revision: sourceState.identity.revision,+ contentRef: sourceState.identity.contentRef,+ source: sourceState.source,+ });+ }+ const normalizedMigration: MdxTemplateMigration =+ migration.type === "rename"+ ? { type: "rename", from: template.templateName, to: migration.to }+ : { type: "remove", name: template.templateName };+ const plan = await planMdxTemplateMigration({+ projectId,+ migration: normalizedMigration,+ files: loaded,+ selectionAssetIds: [...candidateIds].sort(),+ confirmationScope: {+ templateInstanceId,+ blockInstanceId: template.blockInstanceId,+ projectVersion: getProjectVersion?.() ?? context.projectVersion,+ renderScope,+ discoveryComplete,+ },+ });+ const confirmed = await validateMdxTemplateMigrationConfirmation({+ projectId,+ plan,+ confirmationToken,+ });+ const publicFiles: Array<{+ assetId: string;+ revision?: string;+ contentRef: string;+ changed?: boolean;+ status?: "updated" | "unchanged" | "failed";+ updateCount: number;+ omissionCount: number;+ diagnostics: readonly MdxTemplateMigrationDiagnostic[];+ }> = plan.files.map(+ ({+ assetId,+ revision,+ contentRef,+ changed,+ updateCount,+ omissionCount,+ diagnostics,+ }) => ({+ assetId,+ revision,+ contentRef,+ changed,+ updateCount,+ omissionCount,+ diagnostics,+ })+ );+ for (const diagnostic of diagnostics) {+ publicFiles.push({+ assetId: diagnostic.assetId,+ contentRef: diagnostic.contentRef,+ changed: false,+ status: "failed" as const,+ updateCount: 0,+ omissionCount: 0,+ diagnostics: [diagnostic],+ });+ }+ if (discoveryComplete === false) {+ return {+ status: "blocked" as const,+ code: "content-source-session-failed" as const,+ message:+ "The complete MDX candidate set cannot be proven; select the reviewed Assets explicitly",+ files: publicFiles,+ updateCount: plan.updateCount,+ omissionCount: plan.omissionCount,+ discoveryComplete,+ diagnostics,+ };+ }+ if (dryRun || confirmed === false) {+ return {+ status: "confirmation-required" as const,+ code: "content-source-confirmation-required" as const,+ confirmationToken: plan.confirmationToken,+ confirmationExpiresAt: plan.confirmationExpiresAt,+ files: publicFiles,+ updateCount: plan.updateCount,+ omissionCount: plan.omissionCount,+ discoveryComplete,+ diagnostics,+ };+ }+ const results = publicFiles.filter(({ status }) => status === "failed");+ for (const file of plan.files) {+ const loadedFile = loaded.find(({ assetId }) => assetId === file.assetId);+ if (+ loadedFile === undefined ||+ file.changed === false ||+ file.diagnostics.length > 0+ ) {+ results.push({+ ...publicFiles.find(({ assetId }) => assetId === file.assetId)!,+ status:+ file.diagnostics.length > 0+ ? ("failed" as const)+ : ("unchanged" as const),+ });+ continue;+ }+ const restored = await session.persistSourceReplacement({+ key: loadedFile.key,+ expectedSource: loadedFile.source,+ source: file.source,+ });+ const restoreDiagnostics: readonly MdxTemplateMigrationDiagnostic[] =+ restored.status === "applied"+ ? file.diagnostics+ : [+ {+ code:+ restored.reason === "unauthorized"+ ? "asset-authorization-failed"+ : restored.reason === "identity-mismatch" ||+ restored.reason === "source-mismatch"+ ? "asset-revision-conflict"+ : "asset-write-failed",+ assetId: file.assetId,+ contentRef: file.contentRef,+ message: `MDX Asset migration is blocked: ${restored.reason}`,+ },+ ];+ results.push({+ ...publicFiles.find(({ assetId }) => assetId === file.assetId)!,+ diagnostics: restoreDiagnostics,+ status:+ restored.status === "applied"+ ? ("updated" as const)+ : ("failed" as const),+ });+ }+ const updated = results.filter(({ status }) => status === "updated");+ const failed = results.filter(({ status }) => status === "failed");+ return {+ status:+ failed.length === 0+ ? ("complete" as const)+ : updated.length > 0+ ? ("partial" as const)+ : ("blocked" as const),+ code:+ failed.length > 0+ ? ("content-source-session-failed" as const)+ : undefined,+ files: results,+ updateCount: updated.reduce((sum, file) => sum + file.updateCount, 0),+ omissionCount: updated.reduce((sum, file) => sum + file.omissionCount, 0),+ discoveryComplete,+ diagnostics,+ changedAsset: updated.length > 0,+ };+ };++ const saveStorageChanges = async (+ changes: readonly ContentStorageChange[]+ ): Promise<+ | Readonly<{+ status: "complete";+ persistence: ContentBlockPersistenceResult;+ }>+ | Readonly<{+ status: "partial" | "failed";+ code: ContentBlockApplicationErrorCode;+ message: string;+ persistence: ContentBlockPersistenceResult;+ }>+ > => {+ const persisted = await persistContentBlockStorageChangesSerially({+ session,+ changes,+ publishState: publishSession,+ });+ return persisted.status === "complete"+ ? { status: "complete", persistence: persisted }+ : {+ status: persisted.status,+ code: "content-source-partial-persistence",+ message:+ persisted.status === "partial"+ ? "Some MDX Assets were saved. Retry the unfinished roots."+ : "The MDX Asset changes could not be saved.",+ persistence: persisted,+ };+ };++ const preflightStorageChanges = async (+ changes: readonly ContentStorageChange[]+ ) => preflightContentBlockStorageChanges({ session, changes });++ return {+ inspectSource,+ applyLifecycle,+ semanticEdit,+ recover,+ migrateTemplateReferences,+ getMaterializedContent,+ preflightStorageChanges,+ saveStorageChanges,+ };+};++export type ContentBlockApplicationOperations = ReturnType<+ typeof createContentBlockApplicationOperations+>;diff --git a/packages/project-build/src/runtime/content-block-source-lifecycle.test.ts b/packages/project-build/src/runtime/content-block-source-lifecycle.test.tsnew file mode 100644index 0000000000..90d61e6f25--- /dev/null+++ b/packages/project-build/src/runtime/content-block-source-lifecycle.test.ts@@ -0,0 +1,882 @@+import { describe, expect, test } from "vitest";+import type { AssetRepository } from "@webstudio-is/asset-uploader/server";+import {+ blockComponent,+ blockTemplateComponent,+ elementComponent,+} from "@webstudio-is/sdk";+import type { BuilderState } from "../state/builder-state";+import { applyBuilderPatchTransactions } from "../state/patch";+import {+ ContentBlockSourceAuthorityRequiredError,+ prepareContentBlockConnect,+ prepareContentBlockDisconnect,+ prepareContentBlockSwitch,+} from "./content-block-source-lifecycle";+import { createMdxAssetEditingSession } from "./mdx-asset-session";++const encoder = new TextEncoder();++const createRepository = (initial: Record<string, string>) => {+ const sources = new Map(Object.entries(initial));+ const names = new Map(+ Object.keys(initial).map((id) => [id, `${id}_initial.mdx`])+ );+ const writes: string[] = [];+ let revision = 0;+ const repository = {+ readContent: async ({ assetId }: { assetId: string }) => {+ const source = sources.get(assetId);+ const name = names.get(assetId);+ if (source === undefined || name === undefined) {+ throw new Error("Asset not found");+ }+ const bytes = encoder.encode(source);+ return {+ asset: {+ id: assetId,+ projectId: "project",+ type: "file" as const,+ format: "file",+ name,+ filename: `${assetId}.mdx`,+ size: bytes.byteLength,+ description: null,+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-01T00:00:00.000Z",+ meta: {},+ },+ data: {+ async *[Symbol.asyncIterator]() {+ yield bytes;+ },+ },+ };+ },+ updateContent: async ({+ assetId,+ expectedName,+ data,+ }: Parameters<AssetRepository["updateContent"]>[0]) => {+ if (names.get(assetId) !== expectedName) {+ throw new Error("Changed remotely");+ }+ const source = await new Response(data).text();+ revision += 1;+ const name = `${assetId}_${revision}.mdx`;+ names.set(assetId, name);+ sources.set(assetId, source);+ writes.push(source);+ return {+ id: assetId,+ projectId: "project",+ type: "file" as const,+ format: "file",+ name,+ filename: `${assetId}.mdx`,+ size: encoder.encode(source).byteLength,+ description: null,+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-01T00:00:00.000Z",+ meta: {},+ };+ },+ } satisfies Pick<AssetRepository, "readContent" | "updateContent">;+ return { repository, sources, writes };+};++const createState = ({+ body = true,+ source,+}: {+ body?: boolean;+ source?: "first" | "expression";+} = {}): BuilderState => {+ const instances: NonNullable<BuilderState["instances"]> = new Map([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [+ { type: "id", value: "templates" },+ ...(body ? ([{ type: "id", value: "body" }] as const) : []),+ ],+ },+ ],+ [+ "templates",+ {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [],+ },+ ],+ ]);+ if (body) {+ instances.set("body", {+ type: "instance",+ id: "body",+ component: elementComponent,+ tag: "p",+ children: [{ type: "text", value: "Block body" }],+ });+ }+ return {+ pages: {+ homePageId: "page",+ rootFolderId: "folder",+ pages: new Map([+ [+ "page",+ {+ id: "page",+ name: "Home",+ title: "Home",+ path: "",+ rootInstanceId: "block",+ meta: {},+ },+ ],+ ]),+ folders: new Map([+ [+ "folder",+ { id: "folder", name: "Root", slug: "", children: ["page"] },+ ],+ ]),+ },+ instances,+ props:+ source === undefined+ ? new Map()+ : new Map([+ [+ "src",+ source === "expression"+ ? {+ id: "src",+ instanceId: "block",+ name: "src",+ type: "expression" as const,+ value: "$ws$dataSource$asset",+ }+ : {+ id: "src",+ instanceId: "block",+ name: "src",+ type: "asset" as const,+ value: "first",+ },+ ],+ ]),+ dataSources: new Map(),+ resources: new Map(),+ styleSources: new Map(),+ styleSourceSelections: new Map(),+ styles: new Map(),+ breakpoints: new Map(),+ assets: new Map(),+ };+};++const createContext = () => {+ let id = 0;+ return { projectId: "project", createId: () => `generated-${id++}` };+};++const applyPayload = (+ state: BuilderState,+ payload: readonly import("../contracts/patch").BuilderPatchChange[]+) =>+ applyBuilderPatchTransactions(state, [+ {+ id: "lifecycle",+ payload: payload.map((change) => structuredClone(change)),+ },+ ]).state;++describe("Content Block source lifecycle", () => {+ test("requires an explicit authority when block and file both have content", async () => {+ const { repository } = createRepository({ first: "File body" });+ const session = createMdxAssetEditingSession({+ repository,+ authorizeAsset: () => true,+ });++ await expect(+ prepareContentBlockConnect({+ state: createState(),+ blockInstanceId: "block",+ source: { type: "asset", assetId: "first" },+ renderScope: "page:/",+ projectId: "project",+ session,+ context: createContext(),+ })+ ).rejects.toThrow(ContentBlockSourceAuthorityRequiredError);+ });++ test("uses validated file content and removes every persisted body child", async () => {+ const { repository } = createRepository({ first: "File body" });+ const session = createMdxAssetEditingSession({+ repository,+ authorizeAsset: () => true,+ });+ const state = createState();+ const prepared = await prepareContentBlockConnect({+ state,+ blockInstanceId: "block",+ source: { type: "asset", assetId: "first" },+ renderScope: "page:/",+ projectId: "project",+ authority: "use-file-content",+ session,+ context: createContext(),+ });++ const next = applyPayload(state, prepared.projectPayload);+ expect(next.instances?.get("block")?.children).toEqual([+ { type: "id", value: "templates" },+ ]);+ expect(next.instances?.has("body")).toBe(false);+ expect(Array.from(next.props?.values() ?? [])).toMatchObject([+ { name: "src", type: "asset", value: "first" },+ ]);+ expect(prepared.storageWrites).toEqual([]);+ });++ test("replaces only the file body while preserving target frontmatter", async () => {+ const { repository } = createRepository({+ first: "---\ntitle: Existing\n---\n\nFile body\n",+ });+ const session = createMdxAssetEditingSession({+ repository,+ authorizeAsset: () => true,+ });+ const state = createState();+ const prepared = await prepareContentBlockConnect({+ state,+ blockInstanceId: "block",+ source: { type: "asset", assetId: "first" },+ renderScope: "page:/",+ projectId: "project",+ authority: "replace-file-body-with-block-content",+ session,+ context: createContext(),+ });++ expect(prepared.persistenceOrder).toBe("storage-before-project");+ expect(prepared.storageWrites).toHaveLength(1);+ expect(prepared.storageWrites[0].source).toContain("title: Existing");+ expect(prepared.storageWrites[0].source).toContain("Block body");+ expect(prepared.storageWrites[0].source).not.toContain("File body");+ });++ test("disconnects by copying resolved content with fresh project ids", async () => {+ const { repository, sources } = createRepository({ first: "# File body" });+ const state = createState({ body: false, source: "first" });+ const session = createMdxAssetEditingSession({+ repository,+ authorizeAsset: () => true,+ });+ const loaded = await session.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "first" },+ renderScope: "page:/",+ state,+ projectId: "project",+ });+ if (loaded.status !== "saved") {+ throw new Error("Expected loaded source");+ }+ const sourceRootId = loaded.root.fragment.instances[0].id;+ const prepared = await prepareContentBlockDisconnect({+ state,+ blockInstanceId: "block",+ currentSessionKey: loaded.key,+ renderScope: "page:/",+ session,+ context: createContext(),+ });+ const next = applyPayload(state, prepared.projectPayload);+ const copiedChild = next.instances?.get("block")?.children[1];++ expect(copiedChild?.type).toBe("id");+ expect(copiedChild?.type === "id" && copiedChild.value).not.toBe(+ sourceRootId+ );+ expect(Array.from(next.props?.values() ?? [])).not.toMatchObject([+ { name: "src" },+ ]);+ expect(sources.get("first")).toBe("# File body");+ });++ test("switch validates the new dynamic source before changing the old source prop", async () => {+ const { repository } = createRepository({ first: "First" });+ const state = createState({ body: false, source: "first" });+ const session = createMdxAssetEditingSession({+ repository,+ authorizeAsset: () => true,+ resolveExpressionAssetId: () => "missing",+ });+ const loaded = await session.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "first" },+ renderScope: "page:/",+ state,+ projectId: "project",+ });+ if (loaded.status !== "saved") {+ throw new Error("Expected loaded source");+ }+ const restore = await session.prepareSourceReplacement({+ key: loaded.key,+ expectedSource: loaded.source,+ source: "Unsaved first",+ });+ if (restore.status !== "ready") {+ throw new Error("Expected prepared source restore");+ }+ const pending = restore.apply({ schedule: false }).state;++ await expect(+ prepareContentBlockSwitch({+ state,+ blockInstanceId: "block",+ currentSessionKey: loaded.key,+ source: { type: "expression", value: "$ws$dataSource$asset" },+ renderScope: "page:/",+ projectId: "project",+ session,+ context: createContext(),+ })+ ).rejects.toThrow();+ expect(state.props?.get("src")).toMatchObject({+ type: "asset",+ value: "first",+ });+ expect(session.get(loaded.key)).toBe(pending);+ });++ test("resolves a dynamic source once and persists the expression contract", async () => {+ const { repository } = createRepository({ first: "File body" });+ let resolutions = 0;+ const session = createMdxAssetEditingSession({+ repository,+ authorizeAsset: () => true,+ resolveExpressionAssetId: () => {+ resolutions += 1;+ return "first";+ },+ });+ const state = createState({ body: false });+ const prepared = await prepareContentBlockConnect({+ state,+ blockInstanceId: "block",+ source: { type: "expression", value: "$ws$dataSource$asset" },+ renderScope: "collection:item-1",+ projectId: "project",+ session,+ context: createContext(),+ });+ const next = applyPayload(state, prepared.projectPayload);++ expect(resolutions).toBe(1);+ expect(next.props?.get("generated-0")).toMatchObject({+ instanceId: "block",+ name: "src",+ type: "expression",+ value: "$ws$dataSource$asset",+ });+ expect(prepared.sourceState).toMatchObject({+ status: "saved",+ identity: { assetId: "first", renderScope: "collection:item-1" },+ });+ });++ test("defaults to the only non-empty content authority", async () => {+ const { repository } = createRepository({ first: "" });+ const session = createMdxAssetEditingSession({+ repository,+ authorizeAsset: () => true,+ });+ const prepared = await prepareContentBlockConnect({+ state: createState(),+ blockInstanceId: "block",+ source: { type: "asset", assetId: "first" },+ renderScope: "page:/",+ projectId: "project",+ session,+ context: createContext(),+ });++ expect(prepared.storageWrites).toHaveLength(1);+ expect(prepared.storageWrites[0].source).toContain("Block body");+ });++ test("does not persist pending writes while preparing a source switch", async () => {+ const { repository, sources, writes } = createRepository({+ first: "First",+ second: "Second",+ });+ const state = createState({ body: false, source: "first" });+ const session = createMdxAssetEditingSession({+ repository,+ authorizeAsset: () => true,+ });+ const loaded = await session.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "first" },+ renderScope: "page:/",+ state,+ projectId: "project",+ });+ if (loaded.status !== "saved") {+ throw new Error("Expected loaded source");+ }+ const restore = await session.prepareSourceReplacement({+ key: loaded.key,+ expectedSource: loaded.source,+ source: "Edited first",+ });+ if (restore.status !== "ready") {+ throw new Error("Expected prepared source restore");+ }+ restore.apply({ schedule: false });++ await expect(+ prepareContentBlockSwitch({+ state,+ blockInstanceId: "block",+ currentSessionKey: loaded.key,+ source: { type: "asset", assetId: "second" },+ renderScope: "page:/",+ projectId: "project",+ authority: "use-file-content",+ session,+ context: createContext(),+ })+ ).rejects.toThrow("MDX Asset session is pending");++ expect(writes).toEqual([]);+ expect(sources.get("first")).toBe("First");+ expect(state.props?.get("src")).toMatchObject({+ type: "asset",+ value: "first",+ });+ });++ test("switches source contracts without an authority choice when they resolve to the same file", async () => {+ const { repository, writes } = createRepository({ first: "First" });+ const state = createState({ body: false, source: "first" });+ const session = createMdxAssetEditingSession({+ repository,+ authorizeAsset: () => true,+ resolveExpressionAssetId: () => "first",+ });+ const loaded = await session.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "first" },+ renderScope: "page:/",+ state,+ projectId: "project",+ });+ if (loaded.status !== "saved") {+ throw new Error("Expected loaded source");+ }+ const restore = await session.prepareSourceReplacement({+ key: loaded.key,+ expectedSource: loaded.source,+ source: "Unsaved first",+ });+ if (restore.status !== "ready") {+ throw new Error("Expected prepared source restore");+ }+ restore.apply({ schedule: false });++ const prepared = await prepareContentBlockSwitch({+ state,+ blockInstanceId: "block",+ currentSessionKey: loaded.key,+ source: { type: "expression", value: "$ws$dataSource$asset" },+ renderScope: "page:/",+ projectId: "project",+ session,+ context: createContext(),+ });+ const next = applyPayload(state, prepared.projectPayload);++ expect(writes).toEqual([]);+ expect(next.props?.get("src")).toMatchObject({+ type: "expression",+ value: "$ws$dataSource$asset",+ });+ expect(prepared.storageWrites).toEqual([]);+ expect(prepared.sourceState).toMatchObject({+ status: "pending",+ localSource: "Unsaved first",+ });+ });++ test("does not settle the current source when the target has unresolved writes", async () => {+ const { repository, writes } = createRepository({+ first: "First",+ second: "Second",+ });+ const state = createState({ body: false, source: "first" });+ const session = createMdxAssetEditingSession({+ repository,+ authorizeAsset: () => true,+ });+ const first = await session.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "first" },+ renderScope: "page:/",+ state,+ projectId: "project",+ });+ const second = await session.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "second" },+ renderScope: "page:/",+ state,+ projectId: "project",+ });+ if (first.status !== "saved" || second.status !== "saved") {+ throw new Error("Expected loaded sources");+ }+ const firstRestore = await session.prepareSourceReplacement({+ key: first.key,+ expectedSource: first.source,+ source: "Unsaved first",+ });+ const secondRestore = await session.prepareSourceReplacement({+ key: second.key,+ expectedSource: second.source,+ source: "Unsaved second",+ });+ if (firstRestore.status !== "ready" || secondRestore.status !== "ready") {+ throw new Error("Expected prepared source restores");+ }+ const pendingFirst = firstRestore.apply({ schedule: false }).state;+ const pendingSecond = secondRestore.apply({ schedule: false }).state;++ await expect(+ prepareContentBlockSwitch({+ state,+ blockInstanceId: "block",+ currentSessionKey: first.key,+ source: { type: "asset", assetId: "second" },+ renderScope: "page:/",+ projectId: "project",+ authority: "use-file-content",+ session,+ context: createContext(),+ })+ ).rejects.toThrow("MDX Asset session is pending");++ expect(session.get(first.key)).toBe(pendingFirst);+ expect(session.get(second.key)).toBe(pendingSecond);+ expect(writes).toEqual([]);+ });++ test("switches by replacing only the target body", async () => {+ const { repository } = createRepository({+ first: "First",+ second: "---\ntitle: Target\n---\n\nSecond\n",+ });+ const state = createState({ body: false, source: "first" });+ const session = createMdxAssetEditingSession({+ repository,+ authorizeAsset: () => true,+ });+ const loaded = await session.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "first" },+ renderScope: "page:/",+ state,+ projectId: "project",+ });+ if (loaded.status !== "saved") {+ throw new Error("Expected loaded source");+ }++ const prepared = await prepareContentBlockSwitch({+ state,+ blockInstanceId: "block",+ currentSessionKey: loaded.key,+ source: { type: "asset", assetId: "second" },+ renderScope: "page:/",+ projectId: "project",+ authority: "replace-file-body-with-block-content",+ session,+ context: createContext(),+ });++ expect(prepared.storageWrites).toHaveLength(1);+ expect(prepared.storageWrites[0].source).toContain("title: Target");+ expect(prepared.storageWrites[0].source).toContain("First");+ expect(prepared.storageWrites[0].source).not.toContain("Second");+ });++ test("rejects invalid switch targets without replacing the usable source", async () => {+ const { repository, writes } = createRepository({+ first: "First",+ second: "export const unsafe = true",+ });+ const state = createState({ body: false, source: "first" });+ const session = createMdxAssetEditingSession({+ repository,+ authorizeAsset: () => true,+ });+ const loaded = await session.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "first" },+ renderScope: "page:/",+ state,+ projectId: "project",+ });+ if (loaded.status !== "saved") {+ throw new Error("Expected loaded source");+ }++ await expect(+ prepareContentBlockSwitch({+ state,+ blockInstanceId: "block",+ currentSessionKey: loaded.key,+ source: { type: "asset", assetId: "second" },+ renderScope: "page:/",+ projectId: "project",+ session,+ context: createContext(),+ })+ ).rejects.toThrow("MDX Asset session is recoverable");++ expect(writes).toEqual([]);+ expect(session.get(loaded.key)).toBe(loaded);+ expect(state.props?.get("src")).toMatchObject({ value: "first" });+ });++ test("keeps unresolved MDX out of the copied project body and reports it", async () => {+ const { repository } = createRepository({+ first: 'Before\n\n<ws.element ws:name="Missing" />\n\nAfter',+ });+ const state = createState({ body: false, source: "first" });+ const session = createMdxAssetEditingSession({+ repository,+ authorizeAsset: () => true,+ });+ const loaded = await session.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "first" },+ renderScope: "page:/",+ state,+ projectId: "project",+ });+ if (loaded.status !== "saved") {+ throw new Error("Expected loaded source");+ }+ const prepared = await prepareContentBlockDisconnect({+ state,+ blockInstanceId: "block",+ currentSessionKey: loaded.key,+ renderScope: "page:/",+ session,+ context: createContext(),+ });+ const next = applyPayload(state, prepared.projectPayload);+ const copiedText = Array.from(next.instances?.values() ?? [])+ .flatMap(({ children }) => children)+ .flatMap((child) => (child.type === "text" ? [child.value] : []))+ .join(" ");++ expect(prepared.diagnostics.map(({ code }) => code)).toContain(+ "unresolved-template"+ );+ expect(copiedText).toContain("Before");+ expect(copiedText).toContain("After");+ expect(copiedText).not.toContain("Missing");+ expect(next.instances?.get("block")?.children[0]).toEqual({+ type: "id",+ value: "templates",+ });+ });++ test("rejects a loaded session from another source or render scope", async () => {+ const { repository, writes } = createRepository({+ first: "First",+ second: "Second",+ });+ const state = createState({ body: false, source: "first" });+ const session = createMdxAssetEditingSession({+ repository,+ authorizeAsset: () => true,+ });+ const otherSource = await session.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "second" },+ renderScope: "page:/",+ state,+ projectId: "project",+ });+ const otherScope = await session.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "first" },+ renderScope: "collection:item-1",+ state,+ projectId: "project",+ });+ if (otherSource.status !== "saved" || otherScope.status !== "saved") {+ throw new Error("Expected loaded sources");+ }+ const restore = await session.prepareSourceReplacement({+ key: otherSource.key,+ expectedSource: otherSource.source,+ source: "Unsaved second",+ });+ if (restore.status !== "ready") {+ throw new Error("Expected prepared source restore");+ }+ const pendingOtherSource = restore.apply({ schedule: false }).state;++ await expect(+ prepareContentBlockDisconnect({+ state,+ blockInstanceId: "block",+ currentSessionKey: otherSource.key,+ renderScope: "page:/",+ session,+ context: createContext(),+ })+ ).rejects.toThrow("does not match the Content Block source");+ await expect(+ prepareContentBlockDisconnect({+ state,+ blockInstanceId: "block",+ currentSessionKey: otherScope.key,+ renderScope: "page:/",+ session,+ context: createContext(),+ })+ ).rejects.toThrow("different render scope");+ expect(session.get(otherSource.key)).toBe(pendingOtherSource);+ expect(writes).toEqual([]);+ });++ test("validates persisted ownership before settling a disconnect write", async () => {+ const { repository, writes } = createRepository({ first: "First" });+ const state = createState({ source: "first" });+ const session = createMdxAssetEditingSession({+ repository,+ authorizeAsset: () => true,+ });+ const loaded = await session.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "first" },+ renderScope: "page:/",+ state,+ projectId: "project",+ });+ if (loaded.status !== "saved") {+ throw new Error("Expected loaded source");+ }+ const restore = await session.prepareSourceReplacement({+ key: loaded.key,+ expectedSource: loaded.source,+ source: "Unsaved first",+ });+ if (restore.status !== "ready") {+ throw new Error("Expected prepared source restore");+ }+ const pending = restore.apply({ schedule: false }).state;++ await expect(+ prepareContentBlockDisconnect({+ state,+ blockInstanceId: "block",+ currentSessionKey: loaded.key,+ renderScope: "page:/",+ session,+ context: createContext(),+ })+ ).rejects.toThrow("persisted body content");++ expect(session.get(loaded.key)).toBe(pending);+ expect(writes).toEqual([]);+ });++ test("repeated connect is a noop while a prepared replacement remains saved", async () => {+ const { repository } = createRepository({ first: "" });+ const session = createMdxAssetEditingSession({+ repository,+ authorizeAsset: () => true,+ });+ const state = createState();+ const first = await prepareContentBlockConnect({+ state,+ blockInstanceId: "block",+ source: { type: "asset", assetId: "first" },+ renderScope: "page:/",+ projectId: "project",+ session,+ context: createContext(),+ });+ const connected = applyPayload(state, first.projectPayload);+ const repeated = await prepareContentBlockConnect({+ state: connected,+ blockInstanceId: "block",+ source: { type: "asset", assetId: "first" },+ renderScope: "page:/",+ projectId: "project",+ session,+ context: createContext(),+ });++ expect(repeated.projectPayload).toEqual([]);+ expect(repeated.storageWrites).toEqual([]);+ expect(repeated.sourceState?.status).toBe("saved");+ });++ test("repeated disconnect is a project-only noop", async () => {+ const { repository } = createRepository({ first: "File body" });+ const state = createState({ body: false, source: "first" });+ const session = createMdxAssetEditingSession({+ repository,+ authorizeAsset: () => true,+ });+ const loaded = await session.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "first" },+ renderScope: "page:/",+ state,+ projectId: "project",+ });+ if (loaded.status !== "saved") {+ throw new Error("Expected loaded source");+ }+ const first = await prepareContentBlockDisconnect({+ state,+ blockInstanceId: "block",+ currentSessionKey: loaded.key,+ renderScope: "page:/",+ session,+ context: createContext(),+ });+ const disconnected = applyPayload(state, first.projectPayload);++ const repeated = await prepareContentBlockDisconnect({+ state: disconnected,+ blockInstanceId: "block",+ renderScope: "page:/",+ session,+ context: createContext(),+ });++ expect(repeated.projectPayload).toEqual([]);+ expect(repeated.storageWrites).toEqual([]);+ });+});diff --git a/packages/project-build/src/runtime/content-block-source-lifecycle.ts b/packages/project-build/src/runtime/content-block-source-lifecycle.tsnew file mode 100644index 0000000000..3f691c4736--- /dev/null+++ b/packages/project-build/src/runtime/content-block-source-lifecycle.ts@@ -0,0 +1,721 @@+import {+ parseMdxDocument,+ serializeMdxDocument,+ type MdxDocument,+} from "@webstudio-is/content-engine/mdx";+import {+ blockComponent,+ blockTemplateComponent,+ contentBlockSourceProp,+ parseContentBlockSourceProp,+ type ContentBlockDiagnostic,+ type ContentBlockSource,+ type Instance,+ type Prop,+ type WebstudioFragment,+} from "@webstudio-is/sdk";+import type { BuilderPatchChange } from "../contracts/patch";+import type { BuilderState } from "../state/builder-state";+import { getRequiredComponentInsertData, insertFragment } from "./components";+import type { BuilderRuntimeContext } from "./context";+import { extractWebstudioFragment, mergeWebstudioFragments } from "./fragment";+import { createInstanceDeletePayload } from "./instances";+import {+ materializeMdxAuthoredContent,+ reconcileMdxAuthoredContent,+} from "./mdx-authored-content";+import type {+ MdxAssetEditingSessionState,+ MdxAssetSourceController,+} from "./mdx-asset-session";+import type { MdxTemplateMaterialization } from "./mdx-materialization";+import type { PendingMdxContentStorageWrite } from "./mdx-storage-adapter";++export type ContentBlockSourceAuthority =+ | "use-file-content"+ | "replace-file-body-with-block-content";++export class ContentBlockSourceAuthorityRequiredError extends Error {}++type LifecycleSession = MdxAssetSourceController &+ Readonly<{+ open: (input: {+ blockInstanceId: string;+ source: ContentBlockSource;+ renderScope: string;+ expectedRevision?: string;+ state: BuilderState;+ projectId: string;+ variables?: Readonly<Record<string, unknown>>;+ }) => Promise<MdxAssetEditingSessionState>;+ get: (key: string) => MdxAssetEditingSessionState | undefined;+ }>;++export type PreparedContentBlockSourceLifecycle = Readonly<{+ status: "prepared";+ action: "connect" | "switch" | "disconnect";+ projectPayload: readonly BuilderPatchChange[];+ storageWrites: readonly PendingMdxContentStorageWrite[];+ diagnostics: readonly ContentBlockDiagnostic[];+ sourceState?: MdxAssetEditingSessionState;+ persistenceOrder: "none" | "storage-before-project";+}>;++const emptyTemplateMaterialization: MdxTemplateMaterialization = {+ templates: [],+ diagnostics: [],+ dependencies: { templateNames: [], templates: [] },+};++const mergePayload = (+ ...payloads: readonly (readonly BuilderPatchChange[])[]+): BuilderPatchChange[] => {+ const byNamespace = new Map<+ BuilderPatchChange["namespace"],+ BuilderPatchChange+ >();+ for (const payload of payloads) {+ for (const change of payload) {+ const accumulated = byNamespace.get(change.namespace) ?? {+ namespace: change.namespace,+ patches: [],+ };+ accumulated.patches.push(...change.patches);+ byNamespace.set(change.namespace, accumulated);+ }+ }+ return Array.from(byNamespace.values()).filter(+ ({ patches }) => patches.length > 0+ );+};++const getBlock = (state: BuilderState, blockInstanceId: string) => {+ const block = state.instances?.get(blockInstanceId);+ if (block?.component !== blockComponent) {+ throw new Error(`Content Block "${blockInstanceId}" does not exist`);+ }+ return block;+};++const getBlockParts = (state: BuilderState, block: Instance) => {+ const templateChildren = block.children.filter(+ (child) =>+ child.type === "id" &&+ state.instances?.get(child.value)?.component === blockTemplateComponent+ );+ if (templateChildren.length !== 1) {+ throw new Error("Content Block must contain exactly one Templates list");+ }+ const [templateChild] = templateChildren;+ return {+ templateChild,+ bodyChildren: block.children.filter((child) => child !== templateChild),+ };+};++const getSourceProp = (state: BuilderState, blockInstanceId: string) => {+ const sourceProps = Array.from(state.props?.values() ?? []).filter(+ (prop) =>+ prop.instanceId === blockInstanceId &&+ prop.name === contentBlockSourceProp+ );+ if (sourceProps.length > 1) {+ throw new Error("Content Block has multiple source props");+ }+ return sourceProps[0];+};++const toSourceProp = ({+ id,+ blockInstanceId,+ source,+}: {+ id: string;+ blockInstanceId: string;+ source: ContentBlockSource;+}): Prop =>+ source.type === "asset"+ ? {+ id,+ instanceId: blockInstanceId,+ name: contentBlockSourceProp,+ type: "asset",+ value: source.assetId,+ }+ : {+ id,+ instanceId: blockInstanceId,+ name: contentBlockSourceProp,+ type: "expression",+ value: source.value,+ };++const isSameSource = (+ left: ContentBlockSource | undefined,+ right: ContentBlockSource+) => {+ if (left?.type !== right.type) {+ return false;+ }+ if (left.type === "asset" && right.type === "asset") {+ return left.assetId === right.assetId;+ }+ return left.type === "expression" && right.type === "expression"+ ? left.value === right.value+ : false;+};++const createSourcePayload = ({+ state,+ blockInstanceId,+ source,+ createId,+}: {+ state: BuilderState;+ blockInstanceId: string;+ source?: ContentBlockSource;+ createId: () => string;+}): BuilderPatchChange[] => {+ const existing = getSourceProp(state, blockInstanceId);+ if (source === undefined) {+ return existing === undefined+ ? []+ : [+ {+ namespace: "props",+ patches: [{ op: "remove", path: [existing.id] }],+ },+ ];+ }+ const next = toSourceProp({+ id: existing?.id ?? createId(),+ blockInstanceId,+ source,+ });+ const parsed = existing && parseContentBlockSourceProp(existing);+ if (+ parsed?.type === source.type &&+ existing?.type === next.type &&+ existing.value === next.value+ ) {+ return [];+ }+ return [+ {+ namespace: "props",+ patches: [+ existing === undefined+ ? { op: "add", path: [next.id], value: next }+ : { op: "replace", path: [existing.id], value: next },+ ],+ },+ ];+};++const extractBlockBodyFragment = ({+ state,+ bodyChildren,+}: {+ state: BuilderState;+ bodyChildren: Instance["children"];+}): WebstudioFragment => {+ const data = getRequiredComponentInsertData(state);+ const rootIds = bodyChildren.flatMap((child) =>+ child.type === "id" ? [child.value] : []+ );+ const fragment = mergeWebstudioFragments(+ rootIds,+ rootIds.map((rootId) => extractWebstudioFragment(data, rootId))+ );+ return { ...fragment, children: structuredClone(bodyChildren) };+};++const serializeBlockBody = ({+ state,+ bodyChildren,+ target,+}: {+ state: BuilderState;+ bodyChildren: Instance["children"];+ target: Extract<MdxAssetEditingSessionState, { status: "saved" }>;+}) => {+ const emptyDocument: MdxDocument = {+ frontmatter: target.root.document.frontmatter,+ children: [],+ };+ const emptyRoot = materializeMdxAuthoredContent({+ identity: target.identity,+ document: emptyDocument,+ templateMaterialization: emptyTemplateMaterialization,+ });+ return serializeMdxDocument(+ reconcileMdxAuthoredContent({+ root: emptyRoot,+ fragment: extractBlockBodyFragment({ state, bodyChildren }),+ })+ );+};++const createRemoveBodyPayload = ({+ state,+ block,+ bodyChildren,+ templateChild,+}: {+ state: BuilderState;+ block: Instance;+ bodyChildren: Instance["children"];+ templateChild: Instance["children"][number];+}) => {+ const rootIds = bodyChildren.flatMap((child) =>+ child.type === "id" ? [child.value] : []+ );+ const cleanup =+ rootIds.length === 0+ ? []+ : (() => {+ const result = createInstanceDeletePayload({+ instances: state.instances ?? new Map(),+ instanceIds: rootIds,+ props: state.props?.values() ?? [],+ dataSources: state.dataSources?.values() ?? [],+ styleSources: state.styleSources?.values() ?? [],+ styleSourceSelections: state.styleSourceSelections?.values() ?? [],+ styles: state.styles?.values() ?? [],+ });+ if (result.errors.length > 0) {+ throw new Error("Content Block body is not a valid instance tree");+ }+ return result.payload;+ })();+ return mergePayload(cleanup, [+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: [block.id, "children"],+ value: [templateChild],+ },+ ],+ },+ ]);+};++const requireSaved = (+ state: MdxAssetEditingSessionState+): Extract<MdxAssetEditingSessionState, { status: "saved" }> => {+ if (state.status !== "saved") {+ throw new Error(`MDX Asset session is ${state.status}`);+ }+ return state;+};++const requireUsable = (state: MdxAssetEditingSessionState) => {+ if ("root" in state && "identity" in state) {+ return state;+ }+ throw new Error(`MDX Asset session is ${state.status}`);+};++const assertLoadedSource = ({+ state,+ source,+ renderScope,+}: {+ state: Extract<MdxAssetEditingSessionState, { identity: unknown }>;+ source: ContentBlockSource | undefined;+ renderScope?: string;+}) => {+ if (source === undefined) {+ throw new Error("Content Block source prop is invalid");+ }+ if (source.type === "asset" && state.identity.assetId !== source.assetId) {+ throw new Error("Loaded MDX Asset does not match the Content Block source");+ }+ if (renderScope !== undefined && state.identity.renderScope !== renderScope) {+ throw new Error("Loaded MDX Asset belongs to a different render scope");+ }+};++const getSavedSession = (session: LifecycleSession, key: string) => {+ const current = session.get(key);+ if (current === undefined) {+ throw new Error("MDX Asset editing session does not exist");+ }+ return requireSaved(current);+};++const getAuthority = ({+ blockHasBody,+ fileHasBody,+ authority,+}: {+ blockHasBody: boolean;+ fileHasBody: boolean;+ authority?: ContentBlockSourceAuthority;+}) => {+ if (+ authority !== undefined &&+ authority !== "use-file-content" &&+ authority !== "replace-file-body-with-block-content"+ ) {+ throw new Error("Content authority is invalid");+ }+ if (blockHasBody && fileHasBody && authority === undefined) {+ throw new ContentBlockSourceAuthorityRequiredError(+ "Connecting non-empty content requires an explicit content authority"+ );+ }+ return (+ authority ??+ (fileHasBody ? "use-file-content" : "replace-file-body-with-block-content")+ );+};++const prepareReplacement = async ({+ session,+ target,+ source,+}: {+ session: LifecycleSession;+ target: Extract<MdxAssetEditingSessionState, { status: "saved" }>;+ source: string;+}) => {+ if (source === target.source) {+ return {+ changesSource: false,+ source,+ };+ }+ const prepared = await session.prepareSourceReplacement({+ key: target.key,+ expectedSource: target.source,+ source,+ });+ if (prepared.status === "blocked") {+ throw new Error(`MDX Asset replacement is blocked: ${prepared.reason}`);+ }+ const preflight = prepared.canApply();+ if (preflight.status === "blocked") {+ throw new Error(`MDX Asset replacement is blocked: ${preflight.reason}`);+ }+ return {+ changesSource: true,+ source,+ };+};++const createNoopResult = ({+ action,+ sourceState,+}: {+ action: PreparedContentBlockSourceLifecycle["action"];+ sourceState?: MdxAssetEditingSessionState;+}): PreparedContentBlockSourceLifecycle => ({+ status: "prepared",+ action,+ projectPayload: [],+ storageWrites: [],+ diagnostics: sourceState?.diagnostics ?? [],+ sourceState,+ persistenceOrder: "none",+});++export const prepareContentBlockConnect = async ({+ state,+ blockInstanceId,+ source,+ renderScope,+ projectId,+ authority,+ variables,+ session,+ context,+}: {+ state: BuilderState;+ blockInstanceId: string;+ source: ContentBlockSource;+ renderScope: string;+ projectId: string;+ authority?: ContentBlockSourceAuthority;+ variables?: Readonly<Record<string, unknown>>;+ session: LifecycleSession;+ context: BuilderRuntimeContext;+}): Promise<PreparedContentBlockSourceLifecycle> => {+ const block = getBlock(state, blockInstanceId);+ const existingSource = getSourceProp(state, blockInstanceId);+ if (existingSource !== undefined) {+ const parsed = parseContentBlockSourceProp(existingSource);+ if (isSameSource(parsed, source) === false) {+ throw new Error("Content Block is already connected; use switch instead");+ }+ const sourceState = requireUsable(+ await session.open({+ blockInstanceId,+ source,+ renderScope,+ state,+ projectId,+ variables,+ })+ );+ return createNoopResult({+ action: "connect",+ sourceState,+ });+ }+ const target = requireSaved(+ await session.open({+ blockInstanceId,+ source,+ renderScope,+ state,+ projectId,+ variables,+ })+ );+ const { templateChild, bodyChildren } = getBlockParts(state, block);+ const selectedAuthority = getAuthority({+ blockHasBody: bodyChildren.length > 0,+ fileHasBody: target.root.document.children.length > 0,+ authority,+ });+ const projectPayload = mergePayload(+ createRemoveBodyPayload({+ state,+ block,+ bodyChildren,+ templateChild,+ }),+ createSourcePayload({+ state,+ blockInstanceId,+ source,+ createId: context.createId,+ })+ );+ const replacement =+ selectedAuthority === "replace-file-body-with-block-content"+ ? await prepareReplacement({+ session,+ target,+ source: serializeBlockBody({ state, bodyChildren, target }),+ })+ : undefined;+ const storageWrites =+ replacement?.changesSource === true+ ? [+ {+ root: { type: "external" as const, identity: target.identity },+ expectedRevision: target.identity.revision,+ source: replacement.source,+ },+ ]+ : [];+ return {+ status: "prepared",+ action: "connect",+ projectPayload,+ storageWrites,+ diagnostics: target.diagnostics,+ sourceState: target,+ persistenceOrder:+ storageWrites.length === 1 ? "storage-before-project" : "none",+ };+};++export const prepareContentBlockDisconnect = async ({+ state,+ blockInstanceId,+ currentSessionKey,+ renderScope,+ session,+ context,+}: {+ state: BuilderState;+ blockInstanceId: string;+ currentSessionKey?: string;+ renderScope: string;+ session: LifecycleSession;+ context: BuilderRuntimeContext;+}): Promise<PreparedContentBlockSourceLifecycle> => {+ const block = getBlock(state, blockInstanceId);+ const sourceProp = getSourceProp(state, blockInstanceId);+ if (sourceProp === undefined) {+ return createNoopResult({ action: "disconnect" });+ }+ if (currentSessionKey === undefined) {+ throw new Error("Disconnect requires the loaded MDX Asset session key");+ }+ const loaded = session.get(currentSessionKey);+ if (loaded === undefined) {+ throw new Error("MDX Asset editing session does not exist");+ }+ const usable = requireUsable(loaded);+ if (usable.identity.blockInstanceId !== blockInstanceId) {+ throw new Error("Loaded MDX Asset does not belong to this Content Block");+ }+ assertLoadedSource({+ state: usable,+ source: parseContentBlockSourceProp(sourceProp),+ renderScope,+ });+ if (getBlockParts(state, block).bodyChildren.length > 0) {+ throw new Error(+ "Source-backed Content Block contains persisted body content"+ );+ }+ const current = getSavedSession(session, currentSessionKey);+ const insertion = insertFragment(+ state,+ {+ parentInstanceId: blockInstanceId,+ fragment: current.root.fragment,+ mode: "append",+ contentMode: false,+ },+ context+ );+ const projectPayload = mergePayload(+ insertion.payload,+ createSourcePayload({+ state,+ blockInstanceId,+ createId: context.createId,+ })+ );+ return {+ status: "prepared",+ action: "disconnect",+ projectPayload,+ storageWrites: [],+ diagnostics: current.diagnostics,+ sourceState: current,+ persistenceOrder: "none",+ };+};++export const prepareContentBlockSwitch = async ({+ state,+ blockInstanceId,+ currentSessionKey,+ source,+ renderScope,+ projectId,+ authority,+ variables,+ session,+ context,+}: {+ state: BuilderState;+ blockInstanceId: string;+ currentSessionKey: string;+ source: ContentBlockSource;+ renderScope: string;+ projectId: string;+ authority?: ContentBlockSourceAuthority;+ variables?: Readonly<Record<string, unknown>>;+ session: LifecycleSession;+ context: BuilderRuntimeContext;+}): Promise<PreparedContentBlockSourceLifecycle> => {+ getBlock(state, blockInstanceId);+ const existingSourceProp = getSourceProp(state, blockInstanceId);+ if (existingSourceProp === undefined) {+ throw new Error("Content Block is not connected; use connect instead");+ }+ const loadedPrevious = session.get(currentSessionKey);+ if (loadedPrevious === undefined) {+ throw new Error("MDX Asset editing session does not exist");+ }+ const usablePrevious = requireUsable(loadedPrevious);+ if (usablePrevious.identity.blockInstanceId !== blockInstanceId) {+ throw new Error("Loaded MDX Asset does not belong to this Content Block");+ }+ const existingSource = parseContentBlockSourceProp(existingSourceProp);+ assertLoadedSource({+ state: usablePrevious,+ source: existingSource,+ renderScope,+ });+ if (isSameSource(existingSource, source)) {+ const previous = getSavedSession(session, currentSessionKey);+ return createNoopResult({+ action: "switch",+ sourceState: previous,+ });+ }+ const loadedTarget = requireUsable(+ await session.open({+ blockInstanceId,+ source,+ renderScope,+ state,+ projectId,+ variables,+ })+ );+ const sharesCurrentStorage = loadedTarget.key === usablePrevious.key;+ if (sharesCurrentStorage) {+ return {+ status: "prepared",+ action: "switch",+ projectPayload: createSourcePayload({+ state,+ blockInstanceId,+ source,+ createId: context.createId,+ }),+ storageWrites: [],+ diagnostics: usablePrevious.diagnostics,+ sourceState: usablePrevious,+ persistenceOrder: "none",+ };+ }+ const selectedAuthority = getAuthority({+ blockHasBody: usablePrevious.root.document.children.length > 0,+ fileHasBody: loadedTarget.root.document.children.length > 0,+ authority,+ });+ const savedTarget = requireSaved(loadedTarget);+ const previous = getSavedSession(session, currentSessionKey);+ const target = savedTarget;+ const replacement =+ selectedAuthority === "replace-file-body-with-block-content"+ ? await prepareReplacement({+ session,+ target,+ source: serializeMdxDocument({+ ...target.root.document,+ children: (await parseMdxDocument({ source: previous.source }))+ .children,+ }),+ })+ : undefined;+ const projectPayload = createSourcePayload({+ state,+ blockInstanceId,+ source,+ createId: context.createId,+ });+ const storageWrites =+ replacement?.changesSource === true+ ? [+ {+ root: { type: "external" as const, identity: target.identity },+ expectedRevision: target.identity.revision,+ source: replacement.source,+ },+ ]+ : [];+ return {+ status: "prepared",+ action: "switch",+ projectPayload,+ storageWrites,+ diagnostics: target.diagnostics,+ sourceState: target,+ persistenceOrder:+ storageWrites.length === 1 ? "storage-before-project" : "none",+ };+};diff --git a/packages/project-build/src/runtime/content-mode-permissions.test.ts b/packages/project-build/src/runtime/content-mode-permissions.test.tsindex 6aa23736f1..20919454f8 100644--- a/packages/project-build/src/runtime/content-mode-permissions.test.ts+++ b/packages/project-build/src/runtime/content-mode-permissions.test.ts@@ -15,6 +15,7 @@ import {applyContentModeTransaction,getContentModeCapabilities,getContentModeEditableInstanceIds,+ getContentModePropEligibility,getContentModePropNamesByTag,isContentModeCopyableProp,isContentModePagePath,@@ -1074,6 +1075,44 @@ describe("content mode permissions", () => {).toBe(false);});+ test("explains why a prop is not editable in content mode", () => {+ const capabilities = getContentModeCapabilities({+ instances,+ metas,+ props,+ styleSources,+ });+ const instance = instances.get("link")!;+ const getEligibility = (prop: Prop) =>+ getContentModePropEligibility({ capabilities, instance, prop });++ expect(getEligibility(props.get("href-prop")!)).toEqual({+ editable: true,+ });+ expect(+ getEligibility({+ id: "boolean-href",+ instanceId: "link",+ name: "href",+ type: "boolean",+ value: true,+ })+ ).toEqual({ editable: false, reason: "incompatible" });+ expect(getEligibility(props.get("target-prop")!)).toEqual({+ editable: false,+ reason: "design-only",+ });+ expect(+ getEligibility({+ id: "unknown-prop",+ instanceId: "link",+ name: "unknown",+ type: "string",+ value: "value",+ })+ ).toEqual({ editable: false, reason: "unknown" });+ });+test("supports content mode props derived from ws:element tag", () => {const capabilities = getContentModeCapabilities({instances: new Map([diff --git a/packages/project-build/src/runtime/content-mode-permissions.ts b/packages/project-build/src/runtime/content-mode-permissions.tsindex 817bd68738..58af93742b 100644--- a/packages/project-build/src/runtime/content-mode-permissions.ts+++ b/packages/project-build/src/runtime/content-mode-permissions.ts@@ -17,6 +17,7 @@ import {type Breakpoints,type Instance,type Prop,+ type PropMeta,type Props,type StyleDecl,type StyleSource,@@ -254,7 +255,7 @@ const getBlockTemplateChildIdsByInstanceId = (return childIdsByInstanceId;};-const getContentModePropMeta = ({+const getInstancePropMetas = ({capabilities,instance,propName,@@ -263,10 +264,12 @@ const getContentModePropMeta = ({instance: Instance;propName: Prop["name"];}) => {- const meta = capabilities.metas.get(instance.component);- const propMeta = meta?.props?.[propName];- if (propMeta?.contentMode === true) {- return propMeta;+ const propMetas: PropMeta[] = [];+ const propMeta = capabilities.metas.get(instance.component)?.props?.[+ propName+ ];+ if (propMeta !== undefined) {+ propMetas.push(propMeta);}const tag = getHtmlTagFromInstance({@@ -276,34 +279,68 @@ const getContentModePropMeta = ({htmlTagsByInstanceId: capabilities.htmlTagsByInstanceId,});if (tag === undefined) {- return;+ return propMetas;}for (const componentMeta of capabilities.metas.values()) {if (Object.keys(componentMeta.presetStyle ?? {}).includes(tag) === false) {continue;}const propMeta = componentMeta.props?.[propName];- if (propMeta?.contentMode === true) {- return propMeta;+ if (propMeta !== undefined) {+ propMetas.push(propMeta);}}+ return propMetas;};-const isContentModePropForInstance = ({+export type ContentModePropEligibility =+ | { editable: true }+ | {+ editable: false;+ reason: "unknown" | "incompatible" | "design-only";+ };++export const getContentModePropEligibility = ({capabilities,instance,prop,}: {capabilities: ContentModeCapabilities;instance: Instance;- prop: Prop;-}) =>- prop.type === "asset" ||- getContentModePropMeta({+ prop: Pick<Prop, "name" | "type">;+}): ContentModePropEligibility => {+ if (prop.type === "asset") {+ return { editable: true };+ }+ const propMetas = getInstancePropMetas({capabilities,instance,propName: prop.name,- })?.type === prop.type;+ });+ const contentModePropMeta = propMetas.find(+ (propMeta) => propMeta.contentMode === true+ );+ if (contentModePropMeta === undefined) {+ return {+ editable: false,+ reason: propMetas.length === 0 ? "unknown" : "design-only",+ };+ }+ if (contentModePropMeta.type !== prop.type) {+ return { editable: false, reason: "incompatible" };+ }+ return { editable: true };+};++const isContentModePropForInstance = ({+ capabilities,+ instance,+ prop,+}: {+ capabilities: ContentModeCapabilities;+ instance: Instance;+ prop: Prop;+}) => getContentModePropEligibility({ capabilities, instance, prop }).editable;const contentModeNonCopyablePropTypes = new Set<Prop["type"]>(["resource",diff --git a/packages/project-build/src/runtime/content-storage.test.ts b/packages/project-build/src/runtime/content-storage.test.tsnew file mode 100644index 0000000000..a07d8911df--- /dev/null+++ b/packages/project-build/src/runtime/content-storage.test.ts@@ -0,0 +1,3938 @@+import { describe, expect, test } from "vitest";+import {+ blockComponent,+ blockTemplateComponent,+ elementComponent,+ encodeDataVariableId,+ portalComponent,+} from "@webstudio-is/sdk";+import type {+ ContentBlockExternalContentIdentity,+ Prop,+ WebstudioFragment,+} from "@webstudio-is/sdk";+import type { BuilderState } from "../state/builder-state";+import {+ createContentStorageProjection,+ createContentStorageSelectorProjection,+ getContentStorageRootKey,+ resolveContentStorageRoot,+} from "./content-storage";+import { executeBuilderRuntimeOperation } from "./registry";+import { createDefaultPages } from "../shared/pages-utils";++const identity = (+ renderScope: string,+ blockInstanceId = "block",+ assetId = "article"+): ContentBlockExternalContentIdentity => ({+ blockInstanceId,+ assetId,+ revision: "sha256:article",+ contentRef: "articles/post.mdx",+ format: "mdx",+ renderScope,+});++const fragment = (rootId: string): WebstudioFragment => ({+ children: [{ type: "id", value: rootId }],+ instances: [+ {+ type: "instance",+ id: rootId,+ component: elementComponent,+ tag: "p",+ children: [{ type: "text", value: "External content" }],+ },+ ],+ props: [],+ assets: [],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+});++const assetSource = (value = "article"): Prop => ({+ id: "src",+ instanceId: "block",+ name: "src",+ type: "asset",+ value,+});++const createState = (source: Prop = assetSource()): BuilderState => ({+ instances: new Map([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: "templates" }],+ },+ ],+ [+ "templates",+ {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [],+ },+ ],+ ]),+ props: new Map([[source.id, source]]),+});++const createStructuralState = () => ({+ ...createState(),+ pages: createDefaultPages({ rootInstanceId: "block" }),+ dataSources: new Map(),+ resources: new Map(),+ styleSources: new Map(),+ styleSourceSelections: new Map(),+ styles: new Map(),+ breakpoints: new Map([["base", { id: "base", label: "Base" }]]),+ assets: new Map(),+});++const createIdFactory = () => {+ let index = 0;+ return () => `generated-${index++}`;+};++const createNestedMaterializedContent = () => {+ const parentIdentity = identity("page:/post");+ const nestedIdentity = identity(+ "page:/post:nested",+ "nested-block",+ "nested-article"+ );+ const parentFragment: WebstudioFragment = {+ ...fragment("outer-rich-text"),+ instances: [+ {+ type: "instance",+ id: "outer-rich-text",+ component: elementComponent,+ children: [{ type: "id", value: "nested-block" }],+ },+ {+ type: "instance",+ id: "nested-block",+ component: blockComponent,+ children: [{ type: "id", value: "nested-templates" }],+ },+ {+ type: "instance",+ id: "nested-templates",+ component: blockTemplateComponent,+ children: [],+ },+ ],+ props: [+ {+ id: "nested-src",+ instanceId: "nested-block",+ name: "src",+ type: "asset",+ value: "nested-article",+ },+ ],+ };+ return {+ parentIdentity,+ nestedIdentity,+ roots: [+ { identity: nestedIdentity, fragment: fragment("nested-content") },+ { identity: parentIdentity, fragment: parentFragment },+ ],+ };+};++describe.each([+ {+ sourceType: "direct",+ source: {+ id: "src",+ instanceId: "block",+ name: "src",+ type: "asset",+ value: "article",+ } satisfies Prop,+ },+ {+ sourceType: "dynamic",+ source: {+ id: "src",+ instanceId: "block",+ name: "src",+ type: "expression",+ value: "$ws$data$source",+ } satisfies Prop,+ },+])("$sourceType Content Block source", ({ source }) => {+ test("projects scope-local content without changing persisted instances", () => {+ const state = createState(source);+ const externalIdentity = identity(`scope-${source.type}`);+ const projection = createContentStorageProjection({+ state,+ materializedRoots: [+ {+ identity: externalIdentity,+ fragment: fragment(`root-${source.type}`),+ },+ ],+ });++ expect(projection.state.instances?.get("block")?.children).toEqual([+ { type: "id", value: "templates" },+ { type: "id", value: `root-${source.type}` },+ ]);+ expect(state.instances?.get("block")?.children).toEqual([+ { type: "id", value: "templates" },+ ]);+ expect(+ resolveContentStorageRoot(projection, {+ type: "instance",+ instanceId: `root-${source.type}`,+ })+ ).toEqual({ type: "external", identity: externalIdentity });+ });+});++test("resolves instance and child-list mutation targets to one storage root", () => {+ const state = createState();+ const externalIdentity = identity("page:/post");+ const projection = createContentStorageProjection({+ state,+ materializedRoots: [+ { identity: externalIdentity, fragment: fragment("external-root") },+ ],+ });++ expect(+ resolveContentStorageRoot(projection, {+ type: "children",+ parentInstanceId: "block",+ })+ ).toEqual({ type: "external", identity: externalIdentity });+ expect(+ resolveContentStorageRoot(projection, {+ type: "instance",+ instanceId: "block",+ })+ ).toEqual({ type: "project" });+ expect(+ resolveContentStorageRoot(projection, {+ type: "instance",+ instanceId: "templates",+ })+ ).toEqual({ type: "project" });+ expect(+ resolveContentStorageRoot(projection, {+ type: "children",+ parentInstanceId: "external-root",+ })+ ).toEqual({ type: "external", identity: externalIdentity });+});++test("preserves ordinary Content Block behavior without materialized content", () => {+ const state = createState();+ const projection = createContentStorageProjection({+ state,+ materializedRoots: [],+ });++ expect(projection.state).toBe(state);+ expect(+ resolveContentStorageRoot(projection, {+ type: "children",+ parentInstanceId: "block",+ })+ ).toEqual({ type: "project" });+});++test("rejects persisted children that compete with external storage", () => {+ const state = createState();+ state.instances?.set("persisted", {+ type: "instance",+ id: "persisted",+ component: elementComponent,+ children: [],+ });+ state.instances?.get("block")?.children.push({+ type: "id",+ value: "persisted",+ });++ expect(() =>+ createContentStorageProjection({+ state,+ materializedRoots: [+ { identity: identity("page:/post"), fragment: fragment("external") },+ ],+ })+ ).toThrow("persisted content");+});++test("rejects two render scopes projected onto the same block", () => {+ const state = createState();++ expect(() =>+ createContentStorageProjection({+ state,+ materializedRoots: [+ { identity: identity("page:/one"), fragment: fragment("one") },+ { identity: identity("page:/two"), fragment: fragment("two") },+ ],+ })+ ).toThrow("one render scope");+});++test("resolves repeated Content Block children by exact render scope", () => {+ const state = createState();+ const projection = createContentStorageSelectorProjection({+ state,+ materializedRoots: [+ { identity: identity("page:/one"), fragment: fragment("one") },+ { identity: identity("page:/two"), fragment: fragment("two") },+ ],+ });+ const block = projection.state.instances?.get("block");+ if (block === undefined) {+ throw new Error("Expected Content Block");+ }++ expect(projection.state.instances?.has("one")).toBe(true);+ expect(projection.state.instances?.has("two")).toBe(true);+ expect(projection.getInstanceChildren(block, "page:/one")).toEqual([+ { type: "id", value: "templates" },+ { type: "id", value: "one" },+ ]);+ expect(projection.getInstanceChildren(block, "page:/two")).toEqual([+ { type: "id", value: "templates" },+ { type: "id", value: "two" },+ ]);+});++test("projects materialized roots into runtime reads", () => {+ const state = createState();+ const materializedContent = [+ {+ identity: identity("page:/post"),+ fragment: fragment("external-root"),+ },+ ];++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.list",+ state,+ input: { rootInstanceId: "block" },+ context: { createId: () => "unused", materializedContent },+ })+ ).toMatchObject({+ instances: [+ { id: "block", depth: 0 },+ { id: "templates", depth: 1 },+ { id: "external-root", depth: 1 },+ ],+ });+ expect(state.instances?.has("external-root")).toBe(false);+});++test("projects reads whose contract does not load source props", () => {+ const state = createState();+ state.props = undefined;+ state.pages = createDefaultPages({ rootInstanceId: "block" });++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.listTexts",+ state,+ input: { instanceId: "external-root" },+ context: {+ createId: () => "unused",+ materializedContent: [+ {+ identity: identity("page:/post"),+ fragment: fragment("external-root"),+ },+ ],+ },+ })+ ).toMatchObject({+ texts: [+ {+ instanceId: "external-root",+ valuePreview: "External content",+ },+ ],+ });+});++test("projects nested storage roots regardless of input order", () => {+ const state = createState();+ const { parentIdentity, nestedIdentity, roots } =+ createNestedMaterializedContent();+ const projection = createContentStorageProjection({+ state,+ materializedRoots: roots,+ });++ expect(projection.state.instances?.get("nested-block")?.children).toEqual([+ { type: "id", value: "nested-templates" },+ { type: "id", value: "nested-content" },+ ]);+ expect(+ resolveContentStorageRoot(projection, {+ type: "instance",+ instanceId: "nested-block",+ })+ ).toEqual({ type: "external", identity: parentIdentity });+ expect(+ resolveContentStorageRoot(projection, {+ type: "children",+ parentInstanceId: "nested-block",+ })+ ).toEqual({ type: "external", identity: nestedIdentity });+ expect(+ resolveContentStorageRoot(projection, {+ type: "instance",+ instanceId: "nested-content",+ })+ ).toEqual({ type: "external", identity: nestedIdentity });+});++test("rejects a stale materialization for a changed direct binding", () => {+ const state = createState(assetSource("new-article"));++ expect(() =>+ createContentStorageProjection({+ state,+ materializedRoots: [+ { identity: identity("page:/post"), fragment: fragment("external") },+ ],+ })+ ).toThrow("changed source");+});++test("rejects conflicting reusable records instead of silently shadowing them", () => {+ const state = createState();+ state.styleSources = new Map([+ ["shared-token", { type: "token", id: "shared-token", name: "Current" }],+ ]);+ const externalFragment = fragment("external");+ externalFragment.styleSources = [+ { type: "token", id: "shared-token", name: "Stale" },+ ];++ expect(() =>+ createContentStorageProjection({+ state,+ materializedRoots: [+ { identity: identity("page:/post"), fragment: externalFragment },+ ],+ })+ ).toThrow("conflicts with project data");+});++test("rejects materialized instance references outside their storage root", () => {+ const state = createState();+ const externalFragment = fragment("external");+ externalFragment.instances[0].children = [{ type: "id", value: "templates" }];++ expect(() =>+ createContentStorageProjection({+ state,+ materializedRoots: [+ { identity: identity("page:/post"), fragment: externalFragment },+ ],+ })+ ).toThrow("outside its storage root");+});++test("requires the protected Templates list on a source-backed block", () => {+ const state = createState();+ state.instances?.get("block")?.children.splice(0);++ expect(() =>+ createContentStorageProjection({+ state,+ materializedRoots: [+ { identity: identity("page:/post"), fragment: fragment("external") },+ ],+ })+ ).toThrow("one Templates list");+});++test("requires materialized local style sources to be scope-local", () => {+ const state = createState();+ state.styleSources = new Map([["local", { type: "local", id: "local" }]]);+ const externalFragment = fragment("external");+ externalFragment.styleSources = [{ type: "local", id: "local" }];++ expect(() =>+ createContentStorageProjection({+ state,+ materializedRoots: [+ { identity: identity("page:/post"), fragment: externalFragment },+ ],+ })+ ).toThrow("not scope-local");+});++test("routes external text updates without patching persisted instances", () => {+ const state = createState();+ const externalIdentity = identity("page:/post");+ const externalFragment = fragment("external");++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.updateText",+ state,+ input: {+ instanceId: "external",+ childIndex: 0,+ text: "Updated content",+ },+ context: {+ createId: () => "unused",+ returnStorageChanges: true,+ materializedContent: [+ { identity: externalIdentity, fragment: externalFragment },+ ],+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [+ {+ root: { type: "external", identity: externalIdentity },+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: ["external", "children", 0],+ value: { type: "text", value: "Updated content" },+ },+ ],+ },+ ],+ },+ ],+ });+ expect(state.instances?.has("external")).toBe(false);+ expect(externalFragment.instances[0].children).toEqual([+ { type: "text", value: "External content" },+ ]);+});++test("keeps ordinary text updates on the project patch path", () => {+ const state = createState();+ state.instances?.set("ordinary", {+ type: "instance",+ id: "ordinary",+ component: elementComponent,+ children: [{ type: "text", value: "Before" }],+ });++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.updateText",+ state,+ input: { instanceId: "ordinary", childIndex: 0, text: "After" },+ context: { createId: () => "unused" },+ })+ ).toMatchObject({+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: ["ordinary", "children", 0],+ value: { type: "text", value: "After" },+ },+ ],+ },+ ],+ });+});++test("validates external text updates with Content-mode permissions", () => {+ const state = createState();+ const protectedFragment = fragment("external-template");+ protectedFragment.instances[0].component = blockTemplateComponent;++ try {+ executeBuilderRuntimeOperation({+ id: "instances.updateText",+ state,+ input: {+ instanceId: "external-template",+ childIndex: 0,+ text: "Blocked",+ },+ context: {+ createId: () => "unused",+ returnStorageChanges: true,+ materializedContent: [+ {+ identity: identity("page:/post"),+ fragment: protectedFragment,+ },+ ],+ },+ });+ throw new Error("Expected Content-mode validation to reject the update");+ } catch (error) {+ expect(error).toMatchObject({ code: "BAD_REQUEST" });+ }+ expect(protectedFragment.instances[0].children).toEqual([+ { type: "text", value: "External content" },+ ]);+});++test("routes direct Content Block text children to external storage", () => {+ const state = createState();+ const externalIdentity = identity("page:/post");+ const externalFragment = fragment("unused");+ externalFragment.children = [+ { type: "text", value: "Direct external content" },+ ];+ externalFragment.instances = [];++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.updateText",+ state,+ input: { instanceId: "block", childIndex: 1, text: "Updated direct" },+ context: {+ createId: () => "unused",+ returnStorageChanges: true,+ materializedContent: [+ { identity: externalIdentity, fragment: externalFragment },+ ],+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [+ {+ root: { type: "external", identity: externalIdentity },+ payload: [+ {+ namespace: "fragment",+ patches: [+ {+ path: ["children", 0],+ value: { type: "text", value: "Updated direct" },+ },+ ],+ },+ ],+ },+ ],+ });+});++test("routes text updates to the innermost nested storage scope", () => {+ const state = createState();+ const { nestedIdentity, roots } = createNestedMaterializedContent();++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.updateText",+ state,+ input: {+ instanceId: "nested-content",+ childIndex: 0,+ text: "Nested update",+ },+ context: {+ createId: () => "unused",+ returnStorageChanges: true,+ materializedContent: roots,+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [+ {+ root: { type: "external", identity: nestedIdentity },+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ path: ["nested-content", "children", 0],+ value: { type: "text", value: "Nested update" },+ },+ ],+ },+ ],+ },+ ],+ });+});++test("routes external whole-text mutations through the same storage contract", () => {+ const state = createState();+ const externalIdentity = identity("page:/post");++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.setTextContent",+ state,+ input: {+ operation: "set",+ instanceId: "external",+ text: "Replacement",+ mode: "text",+ },+ context: {+ createId: () => "unused",+ returnStorageChanges: true,+ materializedContent: [+ { identity: externalIdentity, fragment: fragment("external") },+ ],+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [+ {+ root: { type: "external", identity: externalIdentity },+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ path: ["external", "children"],+ value: [{ type: "text", value: "Replacement" }],+ },+ ],+ },+ ],+ },+ ],+ });+});++test("preserves Templates when replacing direct Content Block text", () => {+ const state = createState();+ const externalIdentity = identity("page:/post");+ const externalFragment = fragment("unused");+ externalFragment.children = [{ type: "text", value: "Before" }];+ externalFragment.instances = [];++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.setTextContent",+ state,+ input: {+ operation: "set",+ instanceId: "block",+ text: "After",+ mode: "text",+ },+ context: {+ createId: () => "unused",+ returnStorageChanges: true,+ materializedContent: [+ { identity: externalIdentity, fragment: externalFragment },+ ],+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [+ {+ root: { type: "external", identity: externalIdentity },+ payload: [+ {+ namespace: "fragment",+ patches: [+ {+ path: ["children"],+ value: [{ type: "text", value: "After" }],+ },+ ],+ },+ ],+ },+ ],+ });+ expect(state.instances?.get("block")?.children).toEqual([+ { type: "id", value: "templates" },+ ]);+});++test("requires callers to opt into handling authored storage changes", () => {+ expect(() =>+ executeBuilderRuntimeOperation({+ id: "instances.updateText",+ state: createState(),+ input: { instanceId: "external", childIndex: 0, text: "Update" },+ context: {+ createId: () => "unused",+ materializedContent: [+ { identity: identity("page:/post"), fragment: fragment("external") },+ ],+ },+ })+ ).toThrow("storage changes");+});++test("returns an external noop after a repeated text update", () => {+ const externalFragment = fragment("external");+ externalFragment.instances[0].children = [+ { type: "text", value: "Already updated" },+ ];++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.updateText",+ state: createState(),+ input: {+ instanceId: "external",+ childIndex: 0,+ text: "Already updated",+ },+ context: {+ createId: () => "unused",+ returnStorageChanges: true,+ materializedContent: [+ {+ identity: identity("page:/post"),+ fragment: externalFragment,+ },+ ],+ },+ })+ ).toMatchObject({ payload: [], noop: true });+});++test("routes inline-expression conversion without mutating materialized input", () => {+ const externalFragment = fragment("external");+ externalFragment.instances[0].children = [+ { type: "expression", value: "$ws$data$title" },+ ];++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.setTextContent",+ state: createState(),+ input: {+ operation: "inlineExpressions",+ instanceId: "external",+ replacements: [+ {+ childIndex: 0,+ expression: "$ws$data$title",+ text: "Resolved title",+ },+ ],+ },+ context: {+ createId: () => "unused",+ returnStorageChanges: true,+ materializedContent: [+ {+ identity: identity("page:/post"),+ fragment: externalFragment,+ },+ ],+ },+ })+ ).toMatchObject({+ storageChanges: [+ {+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ path: ["external", "children"],+ value: [{ type: "text", value: "Resolved title" }],+ },+ ],+ },+ ],+ },+ ],+ });+ expect(externalFragment.instances[0].children).toEqual([+ { type: "expression", value: "$ws$data$title" },+ ]);+});++test("partitions bulk text replacement between project and external storage", () => {+ const state = createState();+ state.instances?.set("body", {+ type: "instance",+ id: "body",+ component: elementComponent,+ children: [+ { type: "id", value: "block" },+ { type: "id", value: "ordinary" },+ ],+ });+ state.instances?.set("ordinary", {+ type: "instance",+ id: "ordinary",+ component: elementComponent,+ children: [{ type: "text", value: "Replace me" }],+ });+ state.pages = createDefaultPages({ rootInstanceId: "body" });+ const externalIdentity = identity("page:/post");+ const externalFragment = fragment("external");+ externalFragment.instances[0].children = [+ { type: "text", value: "Replace me" },+ ];++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.replaceText",+ state,+ input: { find: "Replace me", replace: "Replaced", match: "exact" },+ context: {+ createId: () => "unused",+ returnStorageChanges: true,+ materializedContent: [+ { identity: externalIdentity, fragment: externalFragment },+ ],+ },+ })+ ).toMatchObject({+ payload: [+ {+ namespace: "instances",+ patches: [{ path: ["ordinary", "children", 0] }],+ },+ ],+ storageChanges: [+ {+ root: { type: "external", identity: externalIdentity },+ payload: [+ {+ namespace: "instances",+ patches: [{ path: ["external", "children", 0] }],+ },+ ],+ },+ ],+ result: { changedCount: 2, matchingChildCount: 2 },+ });+});++test("routes rich-text tree updates and preserves authored siblings", () => {+ const state = createState();+ const externalIdentity = identity("page:/post");+ const externalFragment = fragment("rich-text");+ externalFragment.children.push({ type: "id", value: "unresolved-marker" });+ externalFragment.instances.push({+ type: "instance",+ id: "unresolved-marker",+ component: elementComponent,+ children: [{ type: "text", value: "Preserve me" }],+ });++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.updateTextTree",+ state,+ input: {+ rootInstanceId: "rich-text",+ instances: [+ {+ type: "instance",+ id: "rich-text",+ component: elementComponent,+ tag: "p",+ children: [{ type: "text", value: "Updated rich text" }],+ },+ ],+ },+ context: {+ createId: () => "unused",+ returnStorageChanges: true,+ materializedContent: [+ { identity: externalIdentity, fragment: externalFragment },+ ],+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [+ {+ root: { type: "external", identity: externalIdentity },+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ path: ["rich-text"],+ value: expect.objectContaining({+ children: [{ type: "text", value: "Updated rich text" }],+ }),+ },+ ],+ },+ ],+ },+ ],+ });+ expect(externalFragment.instances.at(-1)?.id).toBe("unresolved-marker");+ expect(externalFragment.children.at(-1)).toEqual({+ type: "id",+ value: "unresolved-marker",+ });+});++test("rejects rich-text updates that cross a nested storage boundary", () => {+ const { roots } = createNestedMaterializedContent();++ expect(() =>+ executeBuilderRuntimeOperation({+ id: "instances.updateTextTree",+ state: createState(),+ input: {+ rootInstanceId: "outer-rich-text",+ instances: [+ {+ type: "instance",+ id: "outer-rich-text",+ component: elementComponent,+ children: [{ type: "text", value: "Remove nested content" }],+ },+ ],+ },+ context: {+ createId: () => "unused",+ returnStorageChanges: true,+ materializedContent: roots,+ },+ })+ ).toThrow("storage boundary");+});++const linkFragment = (id: string, href: string): WebstudioFragment => ({+ ...fragment(id),+ instances: [+ {+ type: "instance",+ id,+ component: "Link",+ children: [{ type: "text", value: id }],+ },+ ],+ props: [+ {+ id: `${id}-href`,+ instanceId: id,+ name: "href",+ type: "string",+ value: href,+ },+ ],+});++test("partitions mixed project and external prop updates", () => {+ const state = createState();+ state.instances?.set("ordinary-link", {+ type: "instance",+ id: "ordinary-link",+ component: "Link",+ children: [],+ });+ state.props?.set("ordinary-href", {+ id: "ordinary-href",+ instanceId: "ordinary-link",+ name: "href",+ type: "string",+ value: "/before",+ });+ const externalIdentity = identity("page:/post");++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.updateProps",+ state,+ input: {+ updates: [+ {+ instanceId: "ordinary-link",+ name: "href",+ type: "string",+ value: "/ordinary",+ },+ {+ instanceId: "external-link",+ name: "href",+ type: "string",+ value: "/external",+ },+ ],+ },+ context: {+ createId: () => "unused",+ returnStorageChanges: true,+ materializedContent: [+ {+ identity: externalIdentity,+ fragment: linkFragment("external-link", "/before"),+ },+ ],+ },+ })+ ).toMatchObject({+ payload: [+ {+ namespace: "props",+ patches: [{ path: ["ordinary-href"] }],+ },+ ],+ storageChanges: [+ {+ root: { type: "external", identity: externalIdentity },+ payload: [+ {+ namespace: "props",+ patches: [{ path: ["external-link-href"] }],+ },+ ],+ },+ ],+ result: { propIds: ["ordinary-href", "external-link-href"] },+ });+});++test("routes bulk prop replacement and deletion to external storage", () => {+ const state = createState();+ state.instances?.set("ordinary-link", {+ type: "instance",+ id: "ordinary-link",+ component: "Link",+ children: [],+ });+ state.props?.set("ordinary-href", {+ id: "ordinary-href",+ instanceId: "ordinary-link",+ name: "href",+ type: "string",+ value: "/before",+ });+ const externalIdentity = identity("page:/post");+ const externalFragment = linkFragment("external-link", "/before");+ const context = {+ createId: () => "unused",+ returnStorageChanges: true,+ materializedContent: [+ { identity: externalIdentity, fragment: externalFragment },+ ],+ };++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.replacePropText",+ state,+ input: { find: "/before", replace: "/after", match: "exact" },+ context,+ })+ ).toMatchObject({+ payload: [+ {+ namespace: "props",+ patches: [{ path: ["ordinary-href", "value"], value: "/after" }],+ },+ ],+ storageChanges: [+ {+ root: { type: "external", identity: externalIdentity },+ payload: [+ {+ namespace: "props",+ patches: [+ { path: ["external-link-href", "value"], value: "/after" },+ ],+ },+ ],+ },+ ],+ result: { changedCount: 2, matchingPropCount: 2 },+ });++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.deleteProps",+ state,+ input: {+ deletions: [{ instanceId: "external-link", name: "href" }],+ },+ context,+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [+ {+ root: { type: "external", identity: externalIdentity },+ payload: [+ {+ namespace: "props",+ patches: [{ op: "remove", path: ["external-link-href"] }],+ },+ ],+ },+ ],+ });+});++test("routes asset props while retaining the authored Asset reference", () => {+ const state = createState();+ const externalIdentity = identity("page:/post");+ const externalFragment = fragment("external-image");+ externalFragment.instances[0].component = "Image";++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.updateProps",+ state,+ input: {+ updates: [+ {+ instanceId: "external-image",+ name: "src",+ type: "asset",+ value: "hero-asset",+ },+ ],+ },+ context: {+ createId: () => "external-src",+ returnStorageChanges: true,+ materializedContent: [+ { identity: externalIdentity, fragment: externalFragment },+ ],+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [+ {+ root: { type: "external", identity: externalIdentity },+ payload: [+ {+ namespace: "props",+ patches: [+ {+ path: ["external-src"],+ value: { type: "asset", value: "hero-asset" },+ },+ ],+ },+ ],+ },+ ],+ });+});++test("rejects design-only props and cross-root prop references", () => {+ const state = createState();+ state.instances?.set("ordinary-link", {+ type: "instance",+ id: "ordinary-link",+ component: "Link",+ children: [],+ });+ const firstIdentity = identity("page:/first");+ const secondIdentity = identity("page:/second", "second-block", "second");+ state.instances?.set("second-block", {+ type: "instance",+ id: "second-block",+ component: blockComponent,+ children: [{ type: "id", value: "second-templates" }],+ });+ state.instances?.set("second-templates", {+ type: "instance",+ id: "second-templates",+ component: blockTemplateComponent,+ children: [],+ });+ state.props?.set("second-src", {+ id: "second-src",+ instanceId: "second-block",+ name: "src",+ type: "asset",+ value: "second",+ });+ const secondFragment = linkFragment("second-link", "/second");+ secondFragment.dataSources.push({+ id: "second-parameter",+ scopeInstanceId: "second-link",+ type: "parameter",+ name: "secondParameter",+ });+ const materializedContent = [+ {+ identity: firstIdentity,+ fragment: linkFragment("first-link", "/first"),+ },+ { identity: secondIdentity, fragment: secondFragment },+ ];++ expect(() =>+ executeBuilderRuntimeOperation({+ id: "instances.updateProps",+ state,+ input: {+ updates: [+ {+ instanceId: "first-link",+ name: "target",+ type: "string",+ value: "_blank",+ },+ ],+ },+ context: {+ createId: () => "first-target",+ returnStorageChanges: true,+ materializedContent,+ },+ })+ ).toThrow("not editable in content mode");++ expect(() =>+ executeBuilderRuntimeOperation({+ id: "instances.bindProps",+ state,+ input: {+ bindings: [+ {+ instanceId: "first-link",+ name: "href",+ binding: { type: "parameter", value: "second-parameter" },+ },+ ],+ },+ context: {+ createId: () => "first-binding",+ returnStorageChanges: true,+ materializedContent,+ },+ })+ ).toThrow("crosses an authored storage boundary");++ expect(() =>+ executeBuilderRuntimeOperation({+ id: "instances.bindProps",+ state,+ input: {+ bindings: [+ {+ instanceId: "ordinary-link",+ name: "href",+ binding: { type: "parameter", value: "second-parameter" },+ },+ ],+ },+ context: {+ createId: () => "ordinary-binding",+ returnStorageChanges: true,+ materializedContent,+ },+ })+ ).toThrow("crosses an authored storage boundary");+});++test.each([+ {+ label: "incompatible",+ update: {+ instanceId: "external-link",+ name: "href",+ type: "boolean" as const,+ value: true,+ },+ },+ {+ label: "unknown",+ update: {+ instanceId: "external-link",+ name: "unknown",+ type: "string" as const,+ value: "value",+ },+ },+])("rejects $label external props", ({ update }) => {+ expect(() =>+ executeBuilderRuntimeOperation({+ id: "instances.updateProps",+ state: createState(),+ input: { updates: [update] },+ context: {+ createId: () => `${update.name}-prop`,+ returnStorageChanges: true,+ materializedContent: [+ {+ identity: identity("page:/post"),+ fragment: linkFragment("external-link", "/before"),+ },+ ],+ },+ })+ ).toThrow("not editable in content mode");+});++test("routes prop updates to the innermost nested storage root", () => {+ const { nestedIdentity, roots } = createNestedMaterializedContent();+ roots[0].fragment.instances[0].component = "Image";++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.updateProps",+ state: createState(),+ input: {+ updates: [+ {+ instanceId: "nested-content",+ name: "src",+ type: "asset",+ value: "nested-image",+ },+ ],+ },+ context: {+ createId: () => "nested-content-src",+ returnStorageChanges: true,+ materializedContent: roots,+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [+ {+ root: { type: "external", identity: nestedIdentity },+ payload: [+ {+ namespace: "props",+ patches: [+ {+ path: ["nested-content-src"],+ value: { value: "nested-image" },+ },+ ],+ },+ ],+ },+ ],+ });+});++test("inserts a component into direct authored Content Block children", () => {+ const state = createStructuralState();+ const externalIdentity = identity("page:/post");++ const mutation = executeBuilderRuntimeOperation({+ id: "instances.insertComponent",+ state,+ input: {+ parentInstanceId: "block",+ component: elementComponent,+ tag: "section",+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ { identity: externalIdentity, fragment: fragment("external") },+ ],+ },+ });++ expect(mutation).toMatchObject({+ payload: [],+ storageChanges: [+ {+ root: { type: "external", identity: externalIdentity },+ payload: expect.arrayContaining([+ {+ namespace: "fragment",+ patches: [expect.objectContaining({ path: ["children", 1] })],+ },+ ]),+ },+ ],+ result: { parentInstanceId: "block" },+ });+ expect(state.instances?.get("block")?.children).toEqual([+ { type: "id", value: "templates" },+ ]);++ expect(() =>+ executeBuilderRuntimeOperation({+ id: "instances.insertComponent",+ state,+ input: {+ parentInstanceId: "block",+ component: elementComponent,+ tag: "section",+ },+ context: {+ createId: createIdFactory(),+ materializedContent: [+ { identity: externalIdentity, fragment: fragment("external") },+ ],+ },+ })+ ).toThrow("must handle authored storage changes");+});++test.each([+ { label: "explicit first index", input: { insertIndex: 0 } },+ { label: "prepend", input: { mode: "prepend" as const } },+ { label: "replace", input: { mode: "replace" as const } },+])("inserts at direct authored coordinates with $label", ({ input }) => {+ const externalIdentity = identity("page:/post");+ const mutation = executeBuilderRuntimeOperation({+ id: "instances.insertComponent",+ state: createStructuralState(),+ input: {+ parentInstanceId: "block",+ component: elementComponent,+ tag: "section",+ ...input,+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ { identity: externalIdentity, fragment: fragment("external") },+ ],+ },+ });+ expect(mutation).toMatchObject({+ payload: [],+ storageChanges: [+ {+ root: { type: "external", identity: externalIdentity },+ payload: expect.arrayContaining([+ {+ namespace: "fragment",+ patches: expect.arrayContaining([+ expect.objectContaining({ path: ["children", 0] }),+ ]),+ },+ ]),+ },+ ],+ result: {+ removedInstanceIds: input.mode === "replace" ? ["external"] : [],+ },+ });+});++test("inserts a fragment into an external descendant", () => {+ const state = createStructuralState();+ const externalIdentity = identity("page:/post");+ const externalFragment = fragment("external");+ externalFragment.instances[0].tag = "div";+ const insertedFragment = fragment("incoming");+ insertedFragment.instances[0].tag = "article";++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.insertFragment",+ state,+ input: {+ parentInstanceId: "external",+ fragment: insertedFragment,+ contentMode: true,+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ { identity: externalIdentity, fragment: externalFragment },+ ],+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [+ {+ root: { type: "external", identity: externalIdentity },+ payload: [expect.objectContaining({ namespace: "instances" })],+ },+ ],+ result: { parentInstanceId: "external" },+ });+});++test("inserts into the innermost nested storage scope", () => {+ const { nestedIdentity, roots } = createNestedMaterializedContent();++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.insertComponent",+ state: createStructuralState(),+ input: {+ parentInstanceId: "nested-content",+ component: elementComponent,+ tag: "span",+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: roots,+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [{ root: { type: "external", identity: nestedIdentity } }],+ });+});++test("keeps token-only fragments project-owned when a parent is provided", () => {+ const tokenFragment = fragment("unused");+ tokenFragment.children = [];+ tokenFragment.instances = [];+ tokenFragment.styleSources = [{ type: "token", id: "brand", name: "Brand" }];+ tokenFragment.styles = [+ {+ styleSourceId: "brand",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ];+ tokenFragment.breakpoints = [{ id: "base", label: "" }];++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.insertFragment",+ state: createStructuralState(),+ input: {+ parentInstanceId: "external",+ fragment: tokenFragment,+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ { identity: identity("page:/post"), fragment: fragment("external") },+ ],+ },+ })+ ).toMatchObject({+ storageChanges: undefined,+ payload: expect.arrayContaining([+ expect.objectContaining({ namespace: "styleSources" }),+ ]),+ result: { rootInstanceIds: [] },+ });+});++test("routes collection insertion through Content-mode validation", () => {+ const externalIdentity = identity("page:/post");+ const externalFragment = fragment("external");+ externalFragment.instances[0].tag = "div";++ expect(() =>+ executeBuilderRuntimeOperation({+ id: "instances.insertCollection",+ state: createStructuralState(),+ input: {+ parentInstanceId: "external",+ data: { type: "json", value: [] },+ itemFragment: fragment("item"),+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ { identity: externalIdentity, fragment: externalFragment },+ ],+ },+ })+ ).toThrow("not editable in content mode");+});++test("deletes an authored instance without changing persisted children", () => {+ const state = createStructuralState();+ const externalIdentity = identity("page:/post");++ const mutation = executeBuilderRuntimeOperation({+ id: "instances.deleteBySelector",+ state,+ input: { instanceSelector: ["external", "block"] },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ { identity: externalIdentity, fragment: fragment("external") },+ ],+ },+ });++ expect(mutation).toMatchObject({+ payload: [],+ storageChanges: [+ {+ root: { type: "external", identity: externalIdentity },+ payload: expect.arrayContaining([+ expect.objectContaining({ namespace: "fragment" }),+ expect.objectContaining({ namespace: "instances" }),+ ]),+ },+ ],+ result: { instanceIds: ["external"] },+ });+ expect(state.instances?.get("block")?.children).toEqual([+ { type: "id", value: "templates" },+ ]);++ expect(() =>+ executeBuilderRuntimeOperation({+ id: "instances.deleteBySelector",+ state,+ input: { instanceSelector: ["external", "block"] },+ context: {+ createId: createIdFactory(),+ materializedContent: [+ { identity: externalIdentity, fragment: fragment("external") },+ ],+ },+ })+ ).toThrow("must handle authored storage changes");+});++test("deletes from the innermost nested storage scope", () => {+ const { nestedIdentity, roots } = createNestedMaterializedContent();++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.deleteBySelector",+ state: createStructuralState(),+ input: { instanceSelector: ["nested-content", "nested-block"] },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: roots,+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [{ root: { type: "external", identity: nestedIdentity } }],+ result: { instanceIds: ["nested-content"] },+ });+});++test.each([+ {+ operation: "delete",+ id: "instances.deleteBySelector" as const,+ input: { instanceSelector: ["templates", "block"] },+ },+ {+ operation: "convert",+ id: "instances.convert" as const,+ input: {+ instanceSelector: ["templates", "block"],+ component: elementComponent,+ tag: "div",+ },+ },+])("protects the Templates list from $operation", ({ id, input }) => {+ expect(() =>+ executeBuilderRuntimeOperation({+ id,+ state: createStructuralState(),+ input,+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ { identity: identity("page:/post"), fragment: fragment("external") },+ ],+ },+ })+ ).toThrow("Templates list cannot be changed");+});++test("protects a nested source-backed Templates list", () => {+ const { roots } = createNestedMaterializedContent();++ expect(() =>+ executeBuilderRuntimeOperation({+ id: "instances.deleteBySelector",+ state: createStructuralState(),+ input: {+ instanceSelector: [+ "nested-templates",+ "nested-block",+ "outer-rich-text",+ "block",+ ],+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: roots,+ },+ })+ ).toThrow("Templates list cannot be changed");+});++test("rejects converting authored component and tag metadata", () => {+ expect(() =>+ executeBuilderRuntimeOperation({+ id: "instances.convert",+ state: createStructuralState(),+ input: {+ instanceSelector: ["external", "block"],+ component: elementComponent,+ tag: "section",+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ { identity: identity("page:/post"), fragment: fragment("external") },+ ],+ },+ })+ ).toThrow("Instance patch is not editable in content mode");+});++test("fills an authored grid in cell order", () => {+ const state = createStructuralState();+ const externalIdentity = identity("page:/post");+ const externalFragment = fragment("grid");+ externalFragment.instances[0].tag = "div";++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.fillGrid",+ state,+ input: {+ parentInstanceId: "grid",+ totalCells: 2,+ breakpointId: "base",+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ { identity: externalIdentity, fragment: externalFragment },+ ],+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [+ {+ root: { type: "external", identity: externalIdentity },+ payload: [+ {+ namespace: "instances",+ patches: expect.arrayContaining([+ expect.objectContaining({+ path: ["grid", "children", 1],+ value: { type: "id", value: "generated-0" },+ }),+ expect.objectContaining({+ path: ["grid", "children", 2],+ value: { type: "id", value: "generated-2" },+ }),+ ]),+ },+ expect.objectContaining({ namespace: "styleSources" }),+ expect.objectContaining({ namespace: "styleSourceSelections" }),+ expect.objectContaining({ namespace: "styles" }),+ ],+ },+ ],+ result: {+ instanceIds: ["generated-0", "generated-2"],+ styleSourceIds: ["generated-1", "generated-3"],+ },+ });+ expect(state.instances?.get("block")?.children).toEqual([+ { type: "id", value: "templates" },+ ]);+});++test("fills a grid in the innermost nested storage scope", () => {+ const { nestedIdentity, roots } = createNestedMaterializedContent();+ roots[0].fragment.instances[0].tag = "div";++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.fillGrid",+ state: createStructuralState(),+ input: {+ parentInstanceId: "nested-content",+ totalCells: 1,+ breakpointId: "base",+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: roots,+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [{ root: { type: "external", identity: nestedIdentity } }],+ result: {+ instanceIds: ["generated-0"],+ styleSourceIds: ["generated-1"],+ },+ });+});++test("keeps a complete authored grid as a storage noop", () => {+ const externalFragment = fragment("grid");+ externalFragment.instances[0].tag = "div";+ externalFragment.instances[0].children = [+ { type: "id", value: "existing-cell" },+ ];+ externalFragment.instances.push({+ type: "instance",+ id: "existing-cell",+ component: elementComponent,+ tag: "div",+ children: [],+ });++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.fillGrid",+ state: createStructuralState(),+ input: {+ parentInstanceId: "grid",+ totalCells: 1,+ breakpointId: "base",+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ { identity: identity("page:/post"), fragment: externalFragment },+ ],+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: undefined,+ noop: true,+ result: { instanceIds: [], styleSourceIds: [] },+ });++ expect(() =>+ executeBuilderRuntimeOperation({+ id: "instances.fillGrid",+ state: createStructuralState(),+ input: {+ parentInstanceId: "grid",+ totalCells: 1,+ breakpointId: "base",+ },+ context: {+ createId: createIdFactory(),+ materializedContent: [+ { identity: identity("page:/post"), fragment: externalFragment },+ ],+ },+ })+ ).toThrow("must handle authored storage changes");+});++test("rejects generated grid cell id collisions", () => {+ const externalFragment = fragment("grid");+ externalFragment.instances[0].tag = "div";++ expect(() =>+ executeBuilderRuntimeOperation({+ id: "instances.fillGrid",+ state: createStructuralState(),+ input: {+ parentInstanceId: "grid",+ totalCells: 1,+ breakpointId: "base",+ },+ context: {+ createId: () => "grid",+ returnStorageChanges: true,+ materializedContent: [+ { identity: identity("page:/post"), fragment: externalFragment },+ ],+ },+ })+ ).toThrow("Instance patch is not editable in content mode");+});++test.each([+ {+ operation: "tag",+ id: "instances.setTag" as const,+ input: { instanceId: "external", tag: "section" },+ },+ {+ operation: "label",+ id: "instances.setLabel" as const,+ input: { instanceId: "external", label: "Article body" },+ },+])("rejects authored instance $operation metadata", ({ id, input }) => {+ const state = createStructuralState();+ const externalIdentity = identity("page:/post");+ const materializedContent = [+ { identity: externalIdentity, fragment: fragment("external") },+ ];++ expect(() =>+ executeBuilderRuntimeOperation({+ id,+ state,+ input,+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent,+ },+ })+ ).toThrow("Instance patch is not editable in content mode");+ expect(state.instances?.has("external")).toEqual(false);++ expect(() =>+ executeBuilderRuntimeOperation({+ id,+ state,+ input,+ context: {+ createId: createIdFactory(),+ materializedContent,+ },+ })+ ).toThrow("must handle authored storage changes");+});++test("rejects nested authored metadata in its own storage scope", () => {+ const { roots } = createNestedMaterializedContent();++ expect(() =>+ executeBuilderRuntimeOperation({+ id: "instances.setLabel",+ state: createStructuralState(),+ input: { instanceId: "nested-content", label: "Nested article" },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: roots,+ },+ })+ ).toThrow("Instance patch is not editable in content mode");+});++test.each([+ {+ operation: "tag",+ id: "instances.setTag" as const,+ input: { instanceId: "external", tag: "p" },+ result: { instanceId: "external", tag: "p" },+ },+ {+ operation: "label",+ id: "instances.setLabel" as const,+ input: { instanceId: "external", label: "Article body" },+ result: { instanceIds: ["external"], label: "Article body" },+ },+])("keeps repeated authored $operation metadata as a noop", (testCase) => {+ const externalFragment = fragment("external");+ externalFragment.instances[0].label = "Article body";+ const materializedContent = [+ { identity: identity("page:/post"), fragment: externalFragment },+ ];++ expect(+ executeBuilderRuntimeOperation({+ id: testCase.id,+ state: createStructuralState(),+ input: testCase.input,+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent,+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: undefined,+ noop: true,+ result: testCase.result,+ });++ expect(() =>+ executeBuilderRuntimeOperation({+ id: testCase.id,+ state: createStructuralState(),+ input: testCase.input,+ context: {+ createId: createIdFactory(),+ materializedContent,+ },+ })+ ).toThrow("must handle authored storage changes");+});++test("keeps Content Block and Templates metadata project-owned", () => {+ const state = createStructuralState();+ state.instances?.get("templates")?.children.push({+ type: "id",+ value: "template",+ });+ state.instances?.set("template", {+ type: "instance",+ id: "template",+ component: elementComponent,+ tag: "section",+ children: [],+ });+ const materializedContent = [+ {+ identity: identity("page:/post"),+ fragment: fragment("external"),+ },+ ];++ for (const instanceId of ["block", "templates", "template"]) {+ expect(+ executeBuilderRuntimeOperation({+ id: "instances.setLabel",+ state,+ input: {+ instanceId,+ label: `Renamed ${instanceId}`,+ ...(instanceId === "template"+ ? {+ templateNameConfirmation: {+ action: "rename" as const,+ templates: [+ {+ instanceId: "template",+ oldName: "<section>",+ newName: "Renamed template",+ },+ ],+ },+ }+ : {}),+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent,+ },+ })+ ).toMatchObject({+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ path: [instanceId, "label"],+ value: `Renamed ${instanceId}`,+ },+ ],+ },+ ],+ storageChanges: undefined,+ result: {+ instanceIds: [instanceId],+ label: `Renamed ${instanceId}`,+ },+ });+ }+});++const siblingFragment = (+ parentId: string,+ childIds: readonly string[]+): WebstudioFragment => ({+ ...fragment(parentId),+ instances: [+ {+ type: "instance",+ id: parentId,+ component: elementComponent,+ tag: "div",+ children: childIds.map((value) => ({ type: "id" as const, value })),+ },+ ...childIds.map((id) => ({+ type: "instance" as const,+ id,+ component: elementComponent,+ tag: "p",+ children: [{ type: "text" as const, value: id }],+ })),+ ],+});++const addSecondSourceBlock = (state: BuilderState) => {+ state.instances?.set("second-block", {+ type: "instance",+ id: "second-block",+ component: blockComponent,+ children: [{ type: "id", value: "second-templates" }],+ });+ state.instances?.set("second-templates", {+ type: "instance",+ id: "second-templates",+ component: blockTemplateComponent,+ children: [],+ });+ state.props?.set("second-src", {+ id: "second-src",+ instanceId: "second-block",+ name: "src",+ type: "asset",+ value: "second",+ });+ return state;+};++test("reorders authored siblings within one storage root", () => {+ const externalIdentity = identity("page:/post");+ const externalFragment = siblingFragment("parent", ["first", "second"]);++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.reparent",+ state: createStructuralState(),+ input: {+ sourceInstanceSelector: ["first", "parent", "block"],+ dropTarget: {+ parentSelector: ["parent", "block"],+ position: "end",+ },+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ { identity: externalIdentity, fragment: externalFragment },+ ],+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [+ { root: { type: "external", identity: externalIdentity } },+ ],+ result: { instanceSelector: ["first", "parent", "block"] },+ });++ expect(() =>+ executeBuilderRuntimeOperation({+ id: "instances.reparent",+ state: createStructuralState(),+ input: {+ sourceInstanceSelector: ["first", "parent", "block"],+ dropTarget: {+ parentSelector: ["parent", "block"],+ position: "end",+ },+ },+ context: {+ createId: createIdFactory(),+ materializedContent: [+ { identity: externalIdentity, fragment: externalFragment },+ ],+ },+ })+ ).toThrow("must handle authored storage changes");+});++test("keeps a repeated authored reorder as a noop", () => {+ expect(+ executeBuilderRuntimeOperation({+ id: "instances.reparent",+ state: createStructuralState(),+ input: {+ sourceInstanceSelector: ["first", "parent", "block"],+ dropTarget: {+ parentSelector: ["parent", "block"],+ position: "end",+ },+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ {+ identity: identity("page:/post"),+ fragment: siblingFragment("parent", ["second", "first"]),+ },+ ],+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: undefined,+ noop: true,+ result: { instanceSelector: ["first", "parent", "block"] },+ });+});++test("routes batched moves within their authored roots", () => {+ const externalIdentity = identity("page:/post");++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.move",+ state: createStructuralState(),+ input: {+ moves: [+ { instanceId: "first", parentInstanceId: "parent", position: "end" },+ ],+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ {+ identity: externalIdentity,+ fragment: siblingFragment("parent", ["first", "second"]),+ },+ ],+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [+ { root: { type: "external", identity: externalIdentity } },+ ],+ result: { instanceIds: ["first"] },+ });+});++test("orders independent batched moves by their authored roots", () => {+ const firstIdentity = identity("page:/post");+ const secondIdentity = identity("page:/second", "second-block", "second");++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.move",+ state: addSecondSourceBlock(createStructuralState()),+ input: {+ moves: [+ {+ instanceId: "first",+ parentInstanceId: "first-parent",+ position: "end",+ },+ {+ instanceId: "second",+ parentInstanceId: "second-parent",+ position: "end",+ },+ ],+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ {+ identity: firstIdentity,+ fragment: siblingFragment("first-parent", ["first", "first-tail"]),+ },+ {+ identity: secondIdentity,+ fragment: siblingFragment("second-parent", [+ "second",+ "second-tail",+ ]),+ },+ ],+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [+ { root: { type: "external", identity: firstIdentity } },+ { root: { type: "external", identity: secondIdentity } },+ ],+ result: { instanceIds: ["first", "second"] },+ });+});++test("moves authored content into project ownership", () => {+ const state = createStructuralState();+ state.instances?.set("project-parent", {+ type: "instance",+ id: "project-parent",+ component: elementComponent,+ tag: "div",+ children: [],+ });+ const externalFragment = siblingFragment("parent", ["first"]);+ externalFragment.props = [+ {+ id: "first-asset",+ instanceId: "first",+ name: "src",+ type: "asset",+ value: "article",+ },+ ];+ externalFragment.dataSources = [+ {+ id: "first-data",+ scopeInstanceId: "first",+ name: "Posts",+ type: "resource",+ resourceId: "first-resource",+ },+ ];+ externalFragment.resources = [+ {+ id: "first-resource",+ name: "Posts",+ method: "get",+ url: '"/posts"',+ headers: [],+ },+ ];+ externalFragment.styleSources = [{ type: "local", id: "first-style" }];+ externalFragment.styleSourceSelections = [+ { instanceId: "first", values: ["first-style"] },+ ];+ externalFragment.styles = [+ {+ styleSourceId: "first-style",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ];++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.move",+ state,+ input: {+ moves: [+ {+ instanceId: "first",+ parentInstanceId: "project-parent",+ position: "end",+ },+ ],+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ {+ identity: identity("page:/post"),+ fragment: externalFragment,+ },+ ],+ },+ })+ ).toMatchObject({+ payload: expect.arrayContaining([+ expect.objectContaining({ namespace: "instances" }),+ expect.objectContaining({ namespace: "props" }),+ expect.objectContaining({ namespace: "dataSources" }),+ expect.objectContaining({ namespace: "resources" }),+ expect.objectContaining({ namespace: "styleSourceSelections" }),+ expect.objectContaining({ namespace: "styleSources" }),+ expect.objectContaining({ namespace: "styles" }),+ ]),+ storageChanges: [+ { root: { type: "external", identity: identity("page:/post") } },+ ],+ result: { instanceIds: ["first"] },+ });+});++test("orders the destination before the source when moving between authored roots", () => {+ const sourceIdentity = identity("page:/post");+ const targetIdentity = identity("page:/second", "second-block", "second");++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.move",+ state: addSecondSourceBlock(createStructuralState()),+ input: {+ moves: [+ {+ instanceId: "first",+ parentInstanceId: "second-parent",+ position: "end",+ },+ ],+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ {+ identity: sourceIdentity,+ fragment: siblingFragment("parent", ["first"]),+ },+ {+ identity: targetIdentity,+ fragment: siblingFragment("second-parent", ["second"]),+ },+ ],+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [+ { root: { type: "external", identity: targetIdentity } },+ { root: { type: "external", identity: sourceIdentity } },+ ],+ result: { instanceIds: ["first"] },+ });+});++test("keeps repeated render scopes distinct in persistence plans", () => {+ const sourceIdentity = identity("collection:item-1", "block", "first");+ const targetIdentity = identity("collection:item-2", "block", "second");++ expect(+ getContentStorageRootKey({ type: "external", identity: sourceIdentity })+ ).not.toBe(+ getContentStorageRootKey({ type: "external", identity: targetIdentity })+ );+});++test("rejects cyclic cross-root moves before returning persistence steps", () => {+ const sourceIdentity = identity("page:/post");+ const targetIdentity = identity("page:/second", "second-block", "second");++ expect(() =>+ executeBuilderRuntimeOperation({+ id: "instances.move",+ state: addSecondSourceBlock(createStructuralState()),+ input: {+ moves: [+ {+ instanceId: "first",+ parentInstanceId: "second-parent",+ position: "end",+ },+ {+ instanceId: "second",+ parentInstanceId: "parent",+ position: "end",+ },+ ],+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ {+ identity: sourceIdentity,+ fragment: siblingFragment("parent", ["first"]),+ },+ {+ identity: targetIdentity,+ fragment: siblingFragment("second-parent", ["second"]),+ },+ ],+ },+ })+ ).toThrow(+ "Cyclic cross-root ownership transfers are not supported by serial persistence."+ );+});++test("rejects overlapping cross-root subtree transfers atomically", () => {+ const sourceFragment = siblingFragment("parent", ["wrapper"]);+ const wrapper = sourceFragment.instances.find(+ (instance) => instance.id === "wrapper"+ );+ if (wrapper !== undefined) {+ wrapper.children = [{ type: "id", value: "child" }];+ }+ sourceFragment.instances.push({+ type: "instance",+ id: "child",+ component: elementComponent,+ tag: "span",+ children: [],+ });+ const targetFragment = siblingFragment("second-parent", ["second"]);+ const state = addSecondSourceBlock(createStructuralState());+ const beforeState = structuredClone(state);+ const beforeSource = structuredClone(sourceFragment);+ const beforeTarget = structuredClone(targetFragment);++ expect(() =>+ executeBuilderRuntimeOperation({+ id: "instances.move",+ state,+ input: {+ moves: [+ {+ instanceId: "wrapper",+ parentInstanceId: "second-parent",+ position: "end",+ },+ {+ instanceId: "child",+ parentInstanceId: "second-parent",+ position: "end",+ },+ ],+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ { identity: identity("page:/post"), fragment: sourceFragment },+ {+ identity: identity("page:/second", "second-block", "second"),+ fragment: targetFragment,+ },+ ],+ },+ })+ ).toThrow("Overlapping cross-root ownership transfers");+ expect(state).toEqual(beforeState);+ expect(sourceFragment).toEqual(beforeSource);+ expect(targetFragment).toEqual(beforeTarget);+});++test("keeps a repeated cross-root move as a noop after ownership changes", () => {+ const sourceIdentity = identity("page:/post");+ const targetIdentity = identity("page:/second", "second-block", "second");++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.move",+ state: addSecondSourceBlock(createStructuralState()),+ input: {+ moves: [+ {+ instanceId: "first",+ parentInstanceId: "second-parent",+ position: "end",+ },+ ],+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ {+ identity: sourceIdentity,+ fragment: siblingFragment("parent", []),+ },+ {+ identity: targetIdentity,+ fragment: siblingFragment("second-parent", ["second", "first"]),+ },+ ],+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: undefined,+ noop: true,+ result: { instanceIds: ["first"] },+ });+});++test("orders the destination before the source when reparenting between authored roots", () => {+ const sourceIdentity = identity("page:/post");+ const targetIdentity = identity("page:/second", "second-block", "second");++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.reparent",+ state: addSecondSourceBlock(createStructuralState()),+ input: {+ sourceInstanceSelector: ["first", "parent", "block"],+ dropTarget: {+ parentSelector: ["second-parent", "second-block"],+ position: "end",+ },+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ {+ identity: sourceIdentity,+ fragment: siblingFragment("parent", ["first"]),+ },+ {+ identity: targetIdentity,+ fragment: siblingFragment("second-parent", ["second"]),+ },+ ],+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [+ { root: { type: "external", identity: targetIdentity } },+ { root: { type: "external", identity: sourceIdentity } },+ ],+ result: {+ instanceSelector: ["first", "second-parent", "second-block"],+ },+ });+});++test("moves project content into authored storage", () => {+ const state = createStructuralState();+ state.instances?.set("project-parent", {+ type: "instance",+ id: "project-parent",+ component: elementComponent,+ tag: "div",+ children: [{ type: "id", value: "project-child" }],+ });+ state.instances?.set("project-child", {+ type: "instance",+ id: "project-child",+ component: elementComponent,+ tag: "p",+ children: [{ type: "text", value: "Project" }],+ });+ const targetIdentity = identity("page:/post");++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.move",+ state,+ input: {+ moves: [+ {+ instanceId: "project-child",+ parentInstanceId: "parent",+ position: "end",+ },+ ],+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ {+ identity: targetIdentity,+ fragment: siblingFragment("parent", ["first"]),+ },+ ],+ },+ })+ ).toMatchObject({+ payload: [+ {+ namespace: "instances",+ patches: expect.arrayContaining([+ { op: "remove", path: ["project-child"] },+ { op: "remove", path: ["project-parent", "children", 0] },+ ]),+ },+ ],+ storageChanges: [{ root: { type: "external", identity: targetIdentity } }],+ result: { instanceIds: ["project-child"] },+ });+});++test("moves content across nested authored ownership boundaries", () => {+ const { parentIdentity, nestedIdentity, roots } =+ createNestedMaterializedContent();+ roots[0].fragment.instances[0].tag = "p";+ roots[1].fragment.instances[0].tag = "div";++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.move",+ state: createStructuralState(),+ input: {+ moves: [+ {+ instanceId: "nested-content",+ parentInstanceId: "outer-rich-text",+ position: "end",+ },+ ],+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: roots,+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [+ { root: { type: "external", identity: parentIdentity } },+ { root: { type: "external", identity: nestedIdentity } },+ ],+ result: { instanceIds: ["nested-content"] },+ });+});++test("rejects moving a data source referenced outside its subtree atomically", () => {+ const state = createStructuralState();+ state.instances?.set("project-parent", {+ type: "instance",+ id: "project-parent",+ component: elementComponent,+ tag: "div",+ children: [],+ });+ const externalFragment = siblingFragment("parent", ["first", "outside"]);+ externalFragment.dataSources = [+ {+ id: "first-data",+ scopeInstanceId: "first",+ name: "First",+ type: "variable",+ value: { type: "string", value: "First" },+ },+ ];+ const outside = externalFragment.instances.find(+ (instance) => instance.id === "outside"+ );+ if (outside !== undefined) {+ outside.children = [+ { type: "expression", value: encodeDataVariableId("first-data") },+ ];+ }+ const beforeState = structuredClone(state);+ const beforeFragment = structuredClone(externalFragment);++ expect(() =>+ executeBuilderRuntimeOperation({+ id: "instances.move",+ state,+ input: {+ moves: [+ {+ instanceId: "first",+ parentInstanceId: "project-parent",+ position: "end",+ },+ ],+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ { identity: identity("page:/post"), fragment: externalFragment },+ ],+ },+ })+ ).toThrow("data source referenced outside the moved subtree");+ expect(state).toEqual(beforeState);+ expect(externalFragment).toEqual(beforeFragment);+});++test.each([+ {+ reference: "text expression",+ configure: (externalFragment: WebstudioFragment) => {+ const moved = externalFragment.instances.find(+ (instance) => instance.id === "first"+ );+ if (moved !== undefined) {+ moved.children = [+ { type: "expression", value: encodeDataVariableId("outside-data") },+ ];+ }+ },+ },+ {+ reference: "parameter prop",+ configure: (externalFragment: WebstudioFragment) => {+ externalFragment.props.push({+ id: "first-parameter",+ instanceId: "first",+ name: "value",+ type: "parameter",+ value: "outside-data",+ });+ },+ },+ {+ reference: "action prop",+ configure: (externalFragment: WebstudioFragment) => {+ externalFragment.props.push({+ id: "first-action",+ instanceId: "first",+ name: "onClick",+ type: "action",+ value: [+ {+ type: "execute",+ args: [],+ code: encodeDataVariableId("outside-data"),+ },+ ],+ });+ },+ },+ {+ reference: "resource expression",+ configure: (externalFragment: WebstudioFragment) => {+ externalFragment.props.push({+ id: "first-resource-prop",+ instanceId: "first",+ name: "resource",+ type: "resource",+ value: "first-resource",+ });+ externalFragment.resources.push({+ id: "first-resource",+ name: "First",+ method: "get",+ url: encodeDataVariableId("outside-data"),+ headers: [],+ });+ },+ },+ {+ reference: "page prop instance",+ configure: (externalFragment: WebstudioFragment) => {+ externalFragment.props.push({+ id: "first-page",+ instanceId: "first",+ name: "href",+ type: "page",+ value: { pageId: "page", instanceId: "outside" },+ });+ },+ },+])(+ "rejects a moved $reference that would cross storage roots",+ ({ configure }) => {+ const state = addSecondSourceBlock(createStructuralState());+ const sourceFragment = siblingFragment("parent", ["first", "outside"]);+ sourceFragment.dataSources.push({+ id: "outside-data",+ scopeInstanceId: "outside",+ name: "Outside",+ type: "variable",+ value: { type: "string", value: "Outside" },+ });+ configure(sourceFragment);+ const targetFragment = siblingFragment("second-parent", ["second"]);+ const beforeState = structuredClone(state);+ const beforeSource = structuredClone(sourceFragment);+ const beforeTarget = structuredClone(targetFragment);++ expect(() =>+ executeBuilderRuntimeOperation({+ id: "instances.move",+ state,+ input: {+ moves: [+ {+ instanceId: "first",+ parentInstanceId: "second-parent",+ position: "end",+ },+ ],+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ { identity: identity("page:/post"), fragment: sourceFragment },+ {+ identity: identity("page:/second", "second-block", "second"),+ fragment: targetFragment,+ },+ ],+ },+ })+ ).toThrow("reference crosses an authored storage boundary");+ expect(state).toEqual(beforeState);+ expect(sourceFragment).toEqual(beforeSource);+ expect(targetFragment).toEqual(beforeTarget);+ }+);++test.each([+ {+ reference: "instance child",+ configure: (externalFragment: WebstudioFragment) => {+ const outside = externalFragment.instances.find(+ (instance) => instance.id === "outside"+ );+ if (outside !== undefined) {+ outside.children = [{ type: "id", value: "first" }];+ }+ },+ },+ {+ reference: "page prop",+ configure: (externalFragment: WebstudioFragment) => {+ externalFragment.props.push({+ id: "outside-page",+ instanceId: "outside",+ name: "href",+ type: "page",+ value: { pageId: "page", instanceId: "first" },+ });+ },+ },+])("rejects a $reference left behind by a cross-root move", ({ configure }) => {+ const sourceFragment = siblingFragment("parent", ["first", "outside"]);+ configure(sourceFragment);++ expect(() =>+ executeBuilderRuntimeOperation({+ id: "instances.move",+ state: addSecondSourceBlock(createStructuralState()),+ input: {+ moves: [+ {+ instanceId: "first",+ parentInstanceId: "second-parent",+ position: "end",+ },+ ],+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ { identity: identity("page:/post"), fragment: sourceFragment },+ {+ identity: identity("page:/second", "second-block", "second"),+ fragment: siblingFragment("second-parent", ["second"]),+ },+ ],+ },+ })+ ).toThrow("reference crosses an authored storage boundary");+});++test("partitions deletion across project and authored roots", () => {+ const state = addSecondSourceBlock(createStructuralState());+ state.instances?.get("templates")?.children.push({+ type: "id",+ value: "project-child",+ });+ state.instances?.set("project-child", {+ type: "instance",+ id: "project-child",+ component: elementComponent,+ tag: "p",+ children: [],+ });+ const firstIdentity = identity("page:/post");+ const secondIdentity = identity("page:/second", "second-block", "second");++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.delete",+ state,+ input: {+ instanceIds: ["first", "project-child", "second"],+ templateNameConfirmation: {+ action: "delete",+ templates: [{ instanceId: "project-child", oldName: "<p>" }],+ },+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ {+ identity: firstIdentity,+ fragment: siblingFragment("first-parent", ["first"]),+ },+ {+ identity: secondIdentity,+ fragment: siblingFragment("second-parent", ["second"]),+ },+ ],+ },+ })+ ).toMatchObject({+ payload: [expect.objectContaining({ namespace: "instances" })],+ storageChanges: [+ { root: { type: "external", identity: firstIdentity } },+ { root: { type: "external", identity: secondIdentity } },+ ],+ result: { instanceIds: ["first", "project-child", "second"] },+ });+ expect(state.instances?.has("project-child")).toEqual(true);+});++test("routes deletion to the innermost nested storage root", () => {+ const { nestedIdentity, roots } = createNestedMaterializedContent();++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.delete",+ state: createStructuralState(),+ input: { instanceIds: ["nested-content"] },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: roots,+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [{ root: { type: "external", identity: nestedIdentity } }],+ result: { instanceIds: ["nested-content"] },+ });+});++test("keeps deleted authored local styles in the same storage root", () => {+ const externalIdentity = identity("page:/post");+ const externalFragment = fragment("external");+ externalFragment.styleSources = [{ type: "local", id: "external-style" }];+ externalFragment.styleSourceSelections = [+ { instanceId: "external", values: ["external-style"] },+ ];+ externalFragment.styles = [+ {+ styleSourceId: "external-style",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ];++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.delete",+ state: createStructuralState(),+ input: { instanceIds: ["external"] },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ { identity: externalIdentity, fragment: externalFragment },+ ],+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [+ {+ root: { type: "external", identity: externalIdentity },+ payload: expect.arrayContaining([+ expect.objectContaining({ namespace: "instances" }),+ expect.objectContaining({ namespace: "styleSourceSelections" }),+ expect.objectContaining({ namespace: "styleSources" }),+ expect.objectContaining({ namespace: "styles" }),+ ]),+ },+ ],+ });+});++test("rejects a protected Templates deletion before returning other roots", () => {+ const state = createStructuralState();++ expect(() =>+ executeBuilderRuntimeOperation({+ id: "instances.delete",+ state,+ input: { instanceIds: ["external", "templates"] },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ { identity: identity("page:/post"), fragment: fragment("external") },+ ],+ },+ })+ ).toThrow("Templates list cannot be changed");+ expect(state.instances?.has("templates")).toEqual(true);+});++test("rejects moving the protected Templates list through project storage", () => {+ const state = createStructuralState();+ state.instances?.set("project-container", {+ type: "instance",+ id: "project-container",+ component: elementComponent,+ tag: "div",+ children: [],+ });++ expect(() =>+ executeBuilderRuntimeOperation({+ id: "instances.move",+ state,+ input: {+ moves: [+ {+ instanceId: "templates",+ parentInstanceId: "project-container",+ position: "end",+ },+ ],+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ { identity: identity("page:/post"), fragment: fragment("external") },+ ],+ },+ })+ ).toThrow("Templates list cannot be changed");+ expect(state.instances?.get("block")?.children).toEqual([+ { type: "id", value: "templates" },+ ]);+});++test("wraps authored content within its storage root", () => {+ const externalIdentity = identity("page:/post");+ const externalFragment = siblingFragment("parent", ["selected"]);++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.wrap",+ state: createStructuralState(),+ input: {+ instanceSelector: ["selected", "parent", "block"],+ component: elementComponent,+ tag: "section",+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ { identity: externalIdentity, fragment: externalFragment },+ ],+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [+ { root: { type: "external", identity: externalIdentity } },+ ],+ result: { instanceSelector: ["generated-0", "parent", "block"] },+ });++ expect(() =>+ executeBuilderRuntimeOperation({+ id: "instances.wrap",+ state: createStructuralState(),+ input: {+ instanceSelector: ["selected", "parent", "block"],+ component: elementComponent,+ tag: "section",+ },+ context: {+ createId: createIdFactory(),+ materializedContent: [+ { identity: externalIdentity, fragment: externalFragment },+ ],+ },+ })+ ).toThrow("must handle authored storage changes");+});++test("normalizes an authored legacy Slot before wrapping its child", () => {+ const externalIdentity = identity("page:/post");+ const externalFragment = siblingFragment("body", []);+ externalFragment.instances[0].children = [{ type: "id", value: "slot" }];+ externalFragment.instances.push(+ {+ type: "instance",+ id: "slot",+ component: "Slot",+ children: [{ type: "id", value: "selected" }],+ },+ {+ type: "instance",+ id: "selected",+ component: elementComponent,+ tag: "p",+ children: [{ type: "text", value: "Selected" }],+ }+ );++ const mutation = executeBuilderRuntimeOperation({+ id: "instances.wrap",+ state: createStructuralState(),+ input: {+ instanceSelector: ["selected", "slot", "body", "block"],+ component: elementComponent,+ tag: "section",+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ { identity: externalIdentity, fragment: externalFragment },+ ],+ },+ });++ expect(mutation).toMatchObject({+ payload: [],+ storageChanges: [+ { root: { type: "external", identity: externalIdentity } },+ ],+ result: {+ instanceSelector: ["generated-1", "generated-0", "slot", "body", "block"],+ },+ });+});++test("unwraps authored content within its storage root", () => {+ const externalIdentity = identity("page:/post");+ const externalFragment = siblingFragment("grandparent", []);+ externalFragment.instances[0].children = [{ type: "id", value: "wrapper" }];+ externalFragment.instances.push(+ {+ type: "instance",+ id: "wrapper",+ component: elementComponent,+ tag: "div",+ children: [{ type: "id", value: "selected" }],+ },+ {+ type: "instance",+ id: "selected",+ component: elementComponent,+ tag: "p",+ children: [{ type: "text", value: "Selected" }],+ }+ );++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.unwrap",+ state: createStructuralState(),+ input: {+ instanceSelector: ["selected", "wrapper", "grandparent", "block"],+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ { identity: externalIdentity, fragment: externalFragment },+ ],+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [+ { root: { type: "external", identity: externalIdentity } },+ ],+ result: { instanceSelector: ["selected", "grandparent", "block"] },+ });+});++test("keeps an authored wrapper when unwrapping one of multiple children", () => {+ const externalIdentity = identity("page:/post");+ const externalFragment = siblingFragment("grandparent", []);+ externalFragment.instances[0].children = [{ type: "id", value: "wrapper" }];+ externalFragment.instances.push(+ {+ type: "instance",+ id: "wrapper",+ component: elementComponent,+ tag: "div",+ children: [+ { type: "id", value: "selected" },+ { type: "id", value: "sibling" },+ ],+ },+ {+ type: "instance",+ id: "selected",+ component: elementComponent,+ tag: "p",+ children: [{ type: "text", value: "Selected" }],+ },+ {+ type: "instance",+ id: "sibling",+ component: elementComponent,+ tag: "p",+ children: [{ type: "text", value: "Sibling" }],+ }+ );++ const mutation = executeBuilderRuntimeOperation({+ id: "instances.unwrap",+ state: createStructuralState(),+ input: {+ instanceSelector: ["selected", "wrapper", "grandparent", "block"],+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ { identity: externalIdentity, fragment: externalFragment },+ ],+ },+ });++ expect(mutation).toMatchObject({+ payload: [],+ storageChanges: [+ {+ root: { type: "external", identity: externalIdentity },+ payload: [+ {+ namespace: "instances",+ patches: [+ { op: "remove", path: ["wrapper", "children", 0] },+ {+ op: "add",+ path: ["grandparent", "children", 1],+ value: { type: "id", value: "selected" },+ },+ ],+ },+ ],+ },+ ],+ result: { instanceSelector: ["selected", "grandparent", "block"] },+ });+});++test.each([+ { operation: "clone", id: "instances.clone" as const },+ {+ operation: "duplicate",+ id: "instances.duplicateAfterItself" as const,+ },+])("copies authored content with $operation in the same root", ({ id }) => {+ const externalIdentity = identity("page:/post");++ expect(+ executeBuilderRuntimeOperation({+ id,+ state: createStructuralState(),+ input:+ id === "instances.clone"+ ? { sourceInstanceId: "selected", targetParentInstanceId: "parent" }+ : { sourceInstanceId: "selected", parentInstanceId: "parent" },+ context: {+ createId: createIdFactory(),+ projectId: "project",+ returnStorageChanges: true,+ materializedContent: [+ {+ identity: externalIdentity,+ fragment: siblingFragment("parent", ["selected"]),+ },+ ],+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [+ {+ root: { type: "external", identity: externalIdentity },+ copySource: {+ root: { type: "external", identity: externalIdentity },+ instanceId: "selected",+ },+ },+ ],+ result: { instanceId: "generated-0" },+ });+});++test("copies content in the innermost nested storage root", () => {+ const { nestedIdentity, roots } = createNestedMaterializedContent();++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.clone",+ state: createStructuralState(),+ input: { sourceInstanceId: "nested-content" },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: roots,+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [{ root: { type: "external", identity: nestedIdentity } }],+ result: { instanceId: "generated-0" },+ });+});++test("copies authored content into project ownership", () => {+ const state = createStructuralState();+ state.instances?.set("project-root", {+ type: "instance",+ id: "project-root",+ component: elementComponent,+ tag: "main",+ children: [+ { type: "id", value: "block" },+ { type: "id", value: "project-parent" },+ ],+ });+ state.instances?.set("project-parent", {+ type: "instance",+ id: "project-parent",+ component: elementComponent,+ tag: "div",+ children: [],+ });+ state.pages = createDefaultPages({ rootInstanceId: "project-root" });++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.clone",+ state,+ input: {+ sourceInstanceId: "selected",+ targetParentInstanceId: "project-parent",+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ {+ identity: identity("page:/post"),+ fragment: siblingFragment("parent", ["selected"]),+ },+ ],+ },+ })+ ).toMatchObject({+ payload: [expect.objectContaining({ namespace: "instances" })],+ storageChanges: undefined,+ result: { instanceId: "generated-0" },+ });+});++test("copies content between authored storage roots", () => {+ const state = addSecondSourceBlock(createStructuralState());+ state.instances?.set("project-root", {+ type: "instance",+ id: "project-root",+ component: elementComponent,+ tag: "main",+ children: [+ { type: "id", value: "block" },+ { type: "id", value: "second-block" },+ ],+ });+ state.pages = createDefaultPages({ rootInstanceId: "project-root" });+ const targetIdentity = identity("page:/second", "second-block", "second");+ const sourceFragment = siblingFragment("parent", ["selected"]);+ sourceFragment.dataSources = [+ {+ id: "selected-data",+ scopeInstanceId: "selected",+ name: "Posts",+ type: "resource",+ resourceId: "selected-resource",+ },+ ];+ sourceFragment.resources = [+ {+ id: "selected-resource",+ name: "Posts",+ method: "get",+ url: '"/posts"',+ headers: [],+ },+ ];+ sourceFragment.props = [+ {+ id: "selected-asset",+ instanceId: "selected",+ name: "src",+ type: "asset",+ value: "article",+ },+ ];++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.clone",+ state,+ input: {+ sourceInstanceId: "selected",+ targetParentInstanceId: "second-parent",+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ {+ identity: identity("page:/post"),+ fragment: sourceFragment,+ },+ {+ identity: targetIdentity,+ fragment: siblingFragment("second-parent", ["second"]),+ },+ ],+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [+ {+ root: { type: "external", identity: targetIdentity },+ copySource: {+ root: {+ type: "external",+ identity: identity("page:/post"),+ },+ instanceId: "selected",+ },+ payload: expect.arrayContaining([+ expect.objectContaining({ namespace: "instances" }),+ expect.objectContaining({+ namespace: "props",+ patches: expect.arrayContaining([+ expect.objectContaining({+ value: expect.objectContaining({ value: "article" }),+ }),+ ]),+ }),+ expect.objectContaining({ namespace: "dataSources" }),+ expect.objectContaining({ namespace: "resources" }),+ ]),+ },+ ],+ result: { instanceId: "generated-0" },+ });+});++test("remaps portal content when copying across storage roots", () => {+ const state = addSecondSourceBlock(createStructuralState());+ state.instances?.set("project-root", {+ type: "instance",+ id: "project-root",+ component: elementComponent,+ tag: "main",+ children: [+ { type: "id", value: "block" },+ { type: "id", value: "second-block" },+ ],+ });+ state.pages = createDefaultPages({ rootInstanceId: "project-root" });+ const sourceFragment = siblingFragment("parent", ["first"]);+ const source = sourceFragment.instances.find(+ (instance) => instance.id === "first"+ );+ if (source !== undefined) {+ source.component = portalComponent;+ source.tag = "div";+ source.children = [{ type: "id", value: "portal-content" }];+ }+ sourceFragment.instances.push({+ type: "instance",+ id: "portal-content",+ component: elementComponent,+ tag: "p",+ children: [{ type: "text", value: "Portal" }],+ });+ const targetIdentity = identity("page:/second", "second-block", "second");+ const targetFragment = siblingFragment("second-parent", ["second"]);+ targetFragment.instances[0].tag = "div";++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.clone",+ state,+ input: {+ sourceInstanceId: "first",+ targetParentInstanceId: "second-parent",+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ { identity: identity("page:/post"), fragment: sourceFragment },+ {+ identity: targetIdentity,+ fragment: targetFragment,+ },+ ],+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [+ {+ root: { type: "external", identity: targetIdentity },+ payload: [+ {+ namespace: "instances",+ patches: expect.arrayContaining([+ expect.objectContaining({+ path: ["generated-0"],+ value: expect.objectContaining({+ children: [{ type: "id", value: "generated-1" }],+ }),+ }),+ expect.objectContaining({ path: ["generated-1"] }),+ ]),+ },+ ],+ },+ ],+ result: { instanceId: "generated-0" },+ });+});++test("rejects duplicating authored content into another storage root", () => {+ expect(() =>+ executeBuilderRuntimeOperation({+ id: "instances.duplicateAfterItself",+ state: addSecondSourceBlock(createStructuralState()),+ input: {+ sourceInstanceId: "selected",+ parentInstanceId: "second-parent",+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ {+ identity: identity("page:/post"),+ fragment: siblingFragment("parent", ["selected"]),+ },+ {+ identity: identity("page:/second", "second-block", "second"),+ fragment: siblingFragment("second-parent", ["second"]),+ },+ ],+ },+ })+ ).toThrow("Copying content across authored storage roots is not supported");+});++test("copies project content into authored storage", () => {+ const state = createStructuralState();+ state.instances?.set("project-parent", {+ type: "instance",+ id: "project-parent",+ component: elementComponent,+ tag: "div",+ children: [{ type: "id", value: "project-selected" }],+ });+ state.instances?.set("project-selected", {+ type: "instance",+ id: "project-selected",+ component: elementComponent,+ tag: "p",+ children: [{ type: "text", value: "Project" }],+ });+ state.dataSources?.set("project-data", {+ id: "project-data",+ scopeInstanceId: "project-selected",+ name: "Posts",+ type: "resource",+ resourceId: "project-resource",+ });+ state.resources?.set("project-resource", {+ id: "project-resource",+ name: "Posts",+ method: "get",+ url: '"/posts"',+ headers: [],+ });+ const beforeState = structuredClone(state);++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.clone",+ state,+ input: {+ sourceInstanceId: "project-selected",+ targetParentInstanceId: "parent",+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ {+ identity: identity("page:/post"),+ fragment: siblingFragment("parent", ["selected"]),+ },+ ],+ },+ })+ ).toMatchObject({+ payload: [],+ storageChanges: [+ {+ root: { type: "external", identity: identity("page:/post") },+ copySource: {+ root: { type: "project" },+ instanceId: "project-selected",+ },+ payload: expect.arrayContaining([+ expect.objectContaining({ namespace: "instances" }),+ expect.objectContaining({+ namespace: "dataSources",+ patches: expect.arrayContaining([+ expect.objectContaining({+ path: ["generated-1"],+ value: expect.objectContaining({+ scopeInstanceId: "generated-0",+ resourceId: "generated-2",+ }),+ }),+ ]),+ }),+ expect.objectContaining({+ namespace: "resources",+ patches: expect.arrayContaining([+ expect.objectContaining({ path: ["generated-2"] }),+ ]),+ }),+ ]),+ },+ ],+ result: { instanceId: "generated-0" },+ });+ expect(state).toEqual(beforeState);+});++test("rejects cross-root clone id collisions without changing either root", () => {+ const state = createStructuralState();+ state.instances?.set("project-selected", {+ type: "instance",+ id: "project-selected",+ component: elementComponent,+ tag: "p",+ children: [{ type: "text", value: "Project" }],+ });+ const externalFragment = siblingFragment("parent", ["selected"]);+ const beforeState = structuredClone(state);+ const beforeFragment = structuredClone(externalFragment);++ expect(() =>+ executeBuilderRuntimeOperation({+ id: "instances.clone",+ state,+ input: {+ sourceInstanceId: "project-selected",+ targetParentInstanceId: "parent",+ },+ context: {+ createId: () => "parent",+ returnStorageChanges: true,+ materializedContent: [+ { identity: identity("page:/post"), fragment: externalFragment },+ ],+ },+ })+ ).toThrow('Generated instance id "parent" already exists');+ expect(state).toEqual(beforeState);+ expect(externalFragment).toEqual(beforeFragment);+});++test("uses the resolved implicit parent for a cross-root clone", () => {+ const state = createStructuralState();+ state.instances?.set("project-root", {+ type: "instance",+ id: "project-root",+ component: elementComponent,+ tag: "main",+ children: [+ { type: "id", value: "project-parent" },+ { type: "id", value: "block" },+ ],+ });+ state.instances?.set("project-parent", {+ type: "instance",+ id: "project-parent",+ component: elementComponent,+ tag: "div",+ children: [{ type: "id", value: "selected" }],+ });+ state.pages = createDefaultPages({ rootInstanceId: "project-root" });++ expect(+ executeBuilderRuntimeOperation({+ id: "instances.clone",+ state,+ input: { sourceInstanceId: "selected" },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ {+ identity: identity("page:/post"),+ fragment: siblingFragment("external-parent", ["selected"]),+ },+ ],+ },+ })+ ).toMatchObject({+ payload: [expect.objectContaining({ namespace: "instances" })],+ storageChanges: undefined,+ result: { instanceId: "generated-0" },+ });+});++test("rejects copying the protected Templates list", () => {+ expect(() =>+ executeBuilderRuntimeOperation({+ id: "instances.clone",+ state: createStructuralState(),+ input: {+ sourceInstanceId: "templates",+ targetParentInstanceId: "block",+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ { identity: identity("page:/post"), fragment: fragment("external") },+ ],+ },+ })+ ).toThrow("Templates list cannot be changed");+});++test("rejects wrapping the protected Templates list", () => {+ expect(() =>+ executeBuilderRuntimeOperation({+ id: "instances.wrap",+ state: createStructuralState(),+ input: {+ instanceSelector: ["templates", "block"],+ component: elementComponent,+ tag: "div",+ },+ context: {+ createId: createIdFactory(),+ returnStorageChanges: true,+ materializedContent: [+ { identity: identity("page:/post"), fragment: fragment("external") },+ ],+ },+ })+ ).toThrow("Templates list cannot be changed");+});diff --git a/packages/project-build/src/runtime/content-storage.ts b/packages/project-build/src/runtime/content-storage.tsnew file mode 100644index 0000000000..6a7c1f1ad7--- /dev/null+++ b/packages/project-build/src/runtime/content-storage.ts@@ -0,0 +1,2129 @@+import {+ blockComponent,+ blockTemplateComponent,+ decodeDataVariableId,+ getStyleDeclKey,+ getContentBlockSource,+ prop as propSchema,+ type ContentBlockExternalContentIdentity,+ type Instance,+ type Prop,+ type WebstudioFragment,+} from "@webstudio-is/sdk";+import { getExpressionIdentifiers } from "@webstudio-is/expression";+import type { BuilderState } from "../state/builder-state";+import { applyBuilderPatchTransactions } from "../state/patch";+import equal from "fast-deep-equal";+import type { BuilderPatchChange } from "../contracts/patch";+import {+ hasContentStorageChange,+ getRuntimeMutationPersistenceOrder,+ type BuilderRuntimeMutation,+ type ContentStorageChange,+ type ContentStoragePatchChange,+} from "./mutation";+import {+ getContentModeCapabilities,+ validateContentModeTransaction,+} from "./content-mode-permissions";+import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";+import { listResourceExpressions } from "./data";+import { throwBuilderRuntimeError } from "./errors";+import { listPropExpressions } from "./props";++export type MaterializedContentRoot = Readonly<{+ identity: ContentBlockExternalContentIdentity;+ fragment: WebstudioFragment;+}>;++export type ContentStorageRoot =+ | Readonly<{ type: "project" }>+ | Readonly<{+ type: "external";+ identity: ContentBlockExternalContentIdentity;+ }>;++export const getContentBlockRenderScopeKey = (+ blockInstanceId: Instance["id"],+ renderScope: string+) => JSON.stringify([blockInstanceId, renderScope]);++export const getContentStorageIdentityKey = (+ identity: ContentBlockExternalContentIdentity+) =>+ JSON.stringify([+ identity.blockInstanceId,+ identity.assetId,+ identity.revision,+ identity.contentRef,+ identity.format,+ identity.renderScope,+ ]);++export const getContentStorageRootKey = (root: ContentStorageRoot) =>+ root.type === "project"+ ? "project"+ : `external:${getContentStorageIdentityKey(root.identity)}`;++export type ContentStorageTarget =+ | Readonly<{ type: "instance"; instanceId: Instance["id"] }>+ | Readonly<{+ type: "children";+ parentInstanceId: Instance["id"];+ }>;++export type ContentStorageOwnershipTransfer = Readonly<{+ rootInstanceId: Instance["id"];+ source: ContentStorageTarget;+ target: ContentStorageTarget;+}>;++type ContentStorageTargetResolver =+ | ContentStorageTarget+ | ((state: BuilderState) => ContentStorageTarget);++export type ContentStorageProjection = Readonly<{+ state: BuilderState;+ externalRootByBlockId: ReadonlyMap<+ Instance["id"],+ ContentBlockExternalContentIdentity+ >;+ externalRootByInstanceId: ReadonlyMap<+ Instance["id"],+ ContentBlockExternalContentIdentity+ >;+ externalRootByDataSourceId: ReadonlyMap<+ string,+ ContentBlockExternalContentIdentity+ >;+ externalRootByResourceId: ReadonlyMap<+ string,+ ContentBlockExternalContentIdentity+ >;+ externalRootByStyleSourceId: ReadonlyMap<+ string,+ ContentBlockExternalContentIdentity+ >;+ externalRootByStyleDeclKey: ReadonlyMap<+ string,+ ContentBlockExternalContentIdentity+ >;+}>;++export type ContentStorageSelectorProjection = Readonly<{+ state: BuilderState;+ getInstanceChildren: (+ instance: Instance,+ renderScope: string+ ) => Instance["children"];+}>;++export const getContentStorageProtectedChildCount = ({+ state,+ root,+ parentInstanceId,+}: {+ state: BuilderState;+ root: ContentStorageRoot;+ parentInstanceId: Instance["id"];+}) => {+ if (+ root.type !== "external" ||+ root.identity.blockInstanceId !== parentInstanceId+ ) {+ return 0;+ }+ return (+ state.instances+ ?.get(parentInstanceId)+ ?.children.filter(+ (child) =>+ child.type === "id" &&+ state.instances?.get(child.value)?.component ===+ blockTemplateComponent+ ).length ?? 0+ );+};++export const projectContentStorageChanges = ({+ state,+ changes,+}: {+ state: BuilderState;+ changes: readonly ContentStorageChange[];+}): BuilderPatchChange[] =>+ changes.flatMap(({ root, payload }) =>+ payload.map((change) => {+ if (change.namespace !== "fragment") {+ return change;+ }+ const block = state.instances?.get(root.identity.blockInstanceId);+ if (block === undefined) {+ throw new Error(+ `Materialized content block "${root.identity.blockInstanceId}" is missing`+ );+ }+ const templateChildren = block.children.filter(+ (child) =>+ child.type === "id" &&+ state.instances?.get(child.value)?.component ===+ blockTemplateComponent+ );+ return {+ namespace: "instances" as const,+ patches: change.patches.map<BuilderPatchChange["patches"][number]>(+ (patch) => {+ const [field, childIndex] = patch.path;+ if (+ field === "children" &&+ patch.path.length === 2 &&+ typeof childIndex === "number"+ ) {+ return {+ ...patch,+ path: [+ block.id,+ "children",+ templateChildren.length + childIndex,+ ],+ };+ }+ if (+ field === "children" &&+ patch.path.length === 1 &&+ patch.op !== "remove" &&+ Array.isArray(patch.value)+ ) {+ return {+ ...patch,+ path: [block.id, "children"],+ value: [...templateChildren, ...patch.value],+ };+ }+ throw new Error("Unsupported fragment storage patch");+ }+ ),+ };+ })+ );++const projectItemsById = <Item extends { id: string }>({+ current,+ items,+ namespace,+ rejectCollision = false,+}: {+ current: Map<string, Item> | undefined;+ items: readonly Item[];+ namespace: string;+ rejectCollision?: boolean | ((item: Item) => boolean);+}) => {+ if (items.length === 0) {+ return current;+ }+ const projected = new Map(current);+ for (const item of items) {+ const existing = projected.get(item.id);+ const collisionIsInvalid =+ rejectCollision === true ||+ (typeof rejectCollision === "function" && rejectCollision(item));+ if (collisionIsInvalid && existing !== undefined) {+ throw new Error(+ `Materialized content ${namespace} id "${item.id}" is not scope-local`+ );+ }+ if (existing !== undefined && equal(existing, item) === false) {+ throw new Error(+ `Materialized content ${namespace} id "${item.id}" conflicts with project data`+ );+ }+ if (existing === undefined) {+ projected.set(item.id, item);+ }+ }+ return projected;+};++const assertExternalBlockStorage = ({+ state,+ identity,+ validateSource,+}: {+ state: BuilderState;+ identity: ContentBlockExternalContentIdentity;+ validateSource: boolean;+}) => {+ const block = state.instances?.get(identity.blockInstanceId);+ if (block?.component !== blockComponent) {+ throw new Error(+ `Materialized content block "${identity.blockInstanceId}" is missing`+ );+ }+ if (validateSource && state.props !== undefined) {+ const source = getContentBlockSource({+ blockInstanceId: block.id,+ props: state.props.values(),+ });+ if (source === undefined) {+ throw new Error(+ `Materialized content block "${block.id}" has no valid source`+ );+ }+ if (source.type === "asset" && source.assetId !== identity.assetId) {+ throw new Error(+ `Materialized content block "${block.id}" has changed source`+ );+ }+ }+ const templateChildren = block.children.filter(+ (child) =>+ child.type === "id" &&+ state.instances?.get(child.value)?.component === blockTemplateComponent+ );+ if (templateChildren.length !== 1) {+ throw new Error(+ `Source-backed Content Block "${block.id}" must contain one Templates list`+ );+ }+ const hasPersistedContent = block.children.some(+ (child) =>+ child.type !== "id" ||+ state.instances?.get(child.value)?.component !== blockTemplateComponent+ );+ if (hasPersistedContent) {+ throw new Error(+ `Source-backed Content Block "${block.id}" contains persisted content`+ );+ }+ return block;+};++const assertFragmentInstanceReferences = (fragment: WebstudioFragment) => {+ const instanceIds = new Set(+ fragment.instances.map((instance) => instance.id)+ );+ const children = [+ ...fragment.children,+ ...fragment.instances.flatMap((instance) => instance.children),+ ];+ for (const child of children) {+ if (child.type === "id" && instanceIds.has(child.value) === false) {+ throw new Error(+ `Materialized instance "${child.value}" is outside its storage root`+ );+ }+ }+};++const createContentStorageProjectionInternal = ({+ state,+ materializedRoots,+ includeRootChildren,+ validateSource,+}: {+ state: BuilderState;+ materializedRoots: readonly MaterializedContentRoot[];+ /**+ * Scope-aware readers can merge every root namespace while projecting the+ * children of only the render scope they are currently reading.+ */+ includeRootChildren?: (+ identity: ContentBlockExternalContentIdentity+ ) => boolean;+ validateSource: boolean;+}): ContentStorageProjection => {+ if (materializedRoots.length === 0) {+ return {+ state,+ externalRootByBlockId: new Map(),+ externalRootByInstanceId: new Map(),+ externalRootByDataSourceId: new Map(),+ externalRootByResourceId: new Map(),+ externalRootByStyleSourceId: new Map(),+ externalRootByStyleDeclKey: new Map(),+ };+ }++ const projectedState: BuilderState = {+ ...state,+ instances: new Map(state.instances),+ };+ const externalRootByBlockId = new Map<+ Instance["id"],+ ContentBlockExternalContentIdentity+ >();+ const externalRootByInstanceId = new Map<+ Instance["id"],+ ContentBlockExternalContentIdentity+ >();+ const externalRootByDataSourceId = new Map<+ string,+ ContentBlockExternalContentIdentity+ >();+ const externalRootByResourceId = new Map<+ string,+ ContentBlockExternalContentIdentity+ >();+ const externalRootByStyleSourceId = new Map<+ string,+ ContentBlockExternalContentIdentity+ >();+ const externalRootByStyleDeclKey = new Map<+ string,+ ContentBlockExternalContentIdentity+ >();++ for (const { identity } of materializedRoots) {+ if (includeRootChildren?.(identity) === false) {+ continue;+ }+ if (externalRootByBlockId.has(identity.blockInstanceId)) {+ throw new Error(+ `Content Block "${identity.blockInstanceId}" can project only one render scope`+ );+ }+ externalRootByBlockId.set(identity.blockInstanceId, identity);+ }++ const pendingRoots = [...materializedRoots];+ const validatedBlockIds = new Set<Instance["id"]>();+ while (pendingRoots.length > 0) {+ const rootIndex = pendingRoots.findIndex(({ identity }) =>+ projectedState.instances?.has(identity.blockInstanceId)+ );+ if (rootIndex === -1) {+ throw new Error(+ `Materialized content block "${pendingRoots[0].identity.blockInstanceId}" is missing`+ );+ }+ const [{ identity, fragment }] = pendingRoots.splice(rootIndex, 1);+ const block = validatedBlockIds.has(identity.blockInstanceId)+ ? projectedState.instances?.get(identity.blockInstanceId)+ : assertExternalBlockStorage({+ state: projectedState,+ identity,+ validateSource,+ });+ if (block === undefined) {+ throw new Error(+ `Materialized content block "${identity.blockInstanceId}" is missing`+ );+ }+ validatedBlockIds.add(identity.blockInstanceId);+ assertFragmentInstanceReferences(fragment);+ const projectedInstances = projectItemsById({+ current: projectedState.instances,+ items: fragment.instances,+ namespace: "instance",+ rejectCollision: true,+ });+ if (projectedInstances === undefined) {+ throw new Error("Materialized content has no instances");+ }+ projectedState.instances = projectedInstances;+ if (includeRootChildren?.(identity) !== false) {+ projectedState.instances.set(block.id, {+ ...block,+ children: [...block.children, ...fragment.children],+ });+ }+ projectedState.props = projectItemsById({+ current: projectedState.props,+ items: fragment.props,+ namespace: "prop",+ rejectCollision: true,+ });+ projectedState.assets = projectItemsById({+ current: projectedState.assets,+ items: fragment.assets,+ namespace: "asset",+ });+ projectedState.dataSources = projectItemsById({+ current: projectedState.dataSources,+ items: fragment.dataSources,+ namespace: "data source",+ rejectCollision: true,+ });+ projectedState.resources = projectItemsById({+ current: projectedState.resources,+ items: fragment.resources,+ namespace: "resource",+ rejectCollision: true,+ });+ projectedState.breakpoints = projectItemsById({+ current: projectedState.breakpoints,+ items: fragment.breakpoints,+ namespace: "breakpoint",+ });+ projectedState.styleSources = projectItemsById({+ current: projectedState.styleSources,+ items: fragment.styleSources,+ namespace: "style source",+ rejectCollision: (styleSource) => styleSource.type === "local",+ });+ if (fragment.styleSourceSelections.length > 0) {+ const selections = new Map(projectedState.styleSourceSelections);+ for (const selection of fragment.styleSourceSelections) {+ if (selections.has(selection.instanceId)) {+ throw new Error(+ `Materialized content style selection instance id "${selection.instanceId}" is not scope-local`+ );+ }+ selections.set(selection.instanceId, selection);+ }+ projectedState.styleSourceSelections = selections;+ }+ if (fragment.styles.length > 0) {+ const styles = new Map(projectedState.styles);+ for (const style of fragment.styles) {+ const key = getStyleDeclKey(style);+ const existing = styles.get(key);+ if (existing !== undefined && equal(existing, style) === false) {+ throw new Error(+ `Materialized content style "${key}" conflicts with project data`+ );+ }+ if (existing === undefined) {+ styles.set(key, style);+ }+ }+ projectedState.styles = styles;+ }+ for (const instance of fragment.instances) {+ externalRootByInstanceId.set(instance.id, identity);+ }+ for (const dataSource of fragment.dataSources) {+ externalRootByDataSourceId.set(dataSource.id, identity);+ }+ for (const resource of fragment.resources) {+ externalRootByResourceId.set(resource.id, identity);+ }+ for (const styleSource of fragment.styleSources) {+ if (styleSource.type === "local") {+ externalRootByStyleSourceId.set(styleSource.id, identity);+ }+ }+ for (const style of fragment.styles) {+ externalRootByStyleDeclKey.set(getStyleDeclKey(style), identity);+ }+ }++ return {+ state: projectedState,+ externalRootByBlockId,+ externalRootByInstanceId,+ externalRootByDataSourceId,+ externalRootByResourceId,+ externalRootByStyleSourceId,+ externalRootByStyleDeclKey,+ };+};++export const createContentStorageProjection = (args: {+ state: BuilderState;+ materializedRoots: readonly MaterializedContentRoot[];+}): ContentStorageProjection =>+ createContentStorageProjectionInternal({+ ...args,+ validateSource: true,+ });++export const createContentStorageSelectorProjection = ({+ state,+ materializedRoots,+ allowStaleSource = false,+}: {+ state: BuilderState;+ materializedRoots: readonly MaterializedContentRoot[];+ allowStaleSource?: boolean;+}): ContentStorageSelectorProjection => {+ // Builder reads keep the previous materialization visible while a changed+ // source is loading. Mutations must continue to use the strict projection+ // and exact storage identity checks above.+ const projection = createContentStorageProjectionInternal({+ state,+ materializedRoots,+ includeRootChildren: () => false,+ validateSource: allowStaleSource === false,+ });+ const rootByScope = new Map(+ materializedRoots.map((root) => [+ getContentBlockRenderScopeKey(+ root.identity.blockInstanceId,+ root.identity.renderScope+ ),+ root,+ ])+ );+ return {+ state: projection.state,+ getInstanceChildren: (instance, renderScope) => {+ if (instance.component !== blockComponent) {+ return instance.children;+ }+ const root = rootByScope.get(+ getContentBlockRenderScopeKey(instance.id, renderScope)+ );+ if (root === undefined) {+ return instance.children;+ }+ return [...instance.children, ...root.fragment.children];+ },+ };+};++const projectStorageRoot = { type: "project" } as const;++const isSameContentStorageRoot = (+ left: ContentStorageRoot,+ right: ContentStorageRoot+) =>+ left.type === right.type &&+ (left.type === "project" ||+ (right.type === "external" &&+ getContentStorageIdentityKey(left.identity) ===+ getContentStorageIdentityKey(right.identity)));++export const resolveContentStorageRoot = (+ projection: ContentStorageProjection,+ target: ContentStorageTarget+): ContentStorageRoot => {+ const identity =+ target.type === "children"+ ? (projection.externalRootByBlockId.get(target.parentInstanceId) ??+ projection.externalRootByInstanceId.get(target.parentInstanceId))+ : projection.externalRootByInstanceId.get(target.instanceId);+ return identity === undefined+ ? projectStorageRoot+ : { type: "external", identity };+};++const prepareExternalMutationPayload = ({+ projection,+ root,+ payload,+ transferredRecordIds = new Map(),+ validationSkippedRecordIds = transferredRecordIds,+}: {+ projection: ContentStorageProjection;+ root: Extract<ContentStorageRoot, { type: "external" }>;+ payload: BuilderPatchChange[];+ transferredRecordIds?: ReadonlyMap<+ BuilderPatchChange["namespace"],+ ReadonlySet<string>+ >;+ validationSkippedRecordIds?: ReadonlyMap<+ BuilderPatchChange["namespace"],+ ReadonlySet<string>+ >;+}) => {+ const validationPayload: BuilderPatchChange[] = [];+ const storagePayload: ContentStoragePatchChange[] = [];+ const block = projection.state.instances?.get(root.identity.blockInstanceId);+ if (block === undefined) {+ throw new Error(+ `Materialized content block "${root.identity.blockInstanceId}" is missing`+ );+ }+ const templateChildren = block.children.filter(+ (child) =>+ child.type === "id" &&+ projection.state.instances?.get(child.value)?.component ===+ blockTemplateComponent+ );+ for (const change of payload) {+ const validationPatches = [];+ const namespacePatches = [];+ const fragmentPatches = [];+ for (const patch of change.patches) {+ const [instanceId, field, childIndex] = patch.path;+ const isTransferredRecord =+ typeof instanceId === "string" &&+ patch.path.length === 1 &&+ validationSkippedRecordIds.get(change.namespace)?.has(instanceId) ===+ true;+ if (+ change.namespace === "instances" &&+ typeof instanceId === "string" &&+ projection.state.instances?.has(instanceId) &&+ transferredRecordIds.get("instances")?.has(instanceId) !== true+ ) {+ const patchRoot = resolveContentStorageRoot(+ projection,+ field === "children"+ ? { type: "children", parentInstanceId: instanceId }+ : { type: "instance", instanceId }+ );+ if (+ patchRoot.type !== "external" ||+ patchRoot.identity.blockInstanceId !== root.identity.blockInstanceId+ ) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Mutation crosses an authored storage boundary."+ );+ }+ }+ if (+ change.namespace !== "instances" ||+ instanceId !== block.id ||+ field !== "children"+ ) {+ if (isTransferredRecord === false) {+ validationPatches.push(patch);+ }+ namespacePatches.push(patch);+ continue;+ }+ if (patch.path.length === 3 && typeof childIndex === "number") {+ const externalIndex = childIndex - templateChildren.length;+ if (externalIndex < 0) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Templates content is not editable in content mode."+ );+ }+ validationPatches.push(patch);+ fragmentPatches.push({+ ...patch,+ path: ["children", externalIndex],+ });+ continue;+ }+ if (+ patch.path.length === 2 &&+ patch.op !== "remove" &&+ Array.isArray(patch.value)+ ) {+ const externalChildren = patch.value.filter(+ (child) =>+ typeof child !== "object" ||+ child === null ||+ !("type" in child) ||+ child.type !== "id" ||+ !("value" in child) ||+ projection.state.instances?.get(String(child.value))?.component !==+ blockTemplateComponent+ );+ validationPatches.push({+ ...patch,+ value: [...templateChildren, ...externalChildren],+ });+ fragmentPatches.push({+ ...patch,+ path: ["children"],+ value: externalChildren,+ });+ continue;+ }+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Content Block root mutation is not supported."+ );+ }+ if (validationPatches.length > 0) {+ validationPayload.push({ ...change, patches: validationPatches });+ }+ if (namespacePatches.length > 0) {+ storagePayload.push({ ...change, patches: namespacePatches });+ }+ if (fragmentPatches.length > 0) {+ storagePayload.push({ namespace: "fragment", patches: fragmentPatches });+ }+ }+ return { validationPayload, storagePayload };+};++const createExternalStorageChange = ({+ projection,+ root,+ payload,+ transferredRecordIds,+ validationSkippedRecordIds,+ validationState = projection.state,+}: {+ projection: ContentStorageProjection;+ root: Extract<ContentStorageRoot, { type: "external" }>;+ payload: BuilderPatchChange[];+ transferredRecordIds?: ReadonlyMap<+ BuilderPatchChange["namespace"],+ ReadonlySet<string>+ >;+ validationSkippedRecordIds?: ReadonlyMap<+ BuilderPatchChange["namespace"],+ ReadonlySet<string>+ >;+ validationState?: BuilderState;+}) => {+ const { validationPayload, storagePayload } = prepareExternalMutationPayload({+ projection,+ root,+ payload,+ transferredRecordIds,+ validationSkippedRecordIds,+ });+ const validation = validateContentModeTransaction({+ capabilities: getContentModeCapabilities({+ instances: validationState.instances ?? new Map(),+ metas: componentMetas,+ props: validationState.props ?? new Map(),+ styleSources: validationState.styleSources ?? new Map(),+ styleSourceSelections: validationState.styleSourceSelections ?? new Map(),+ styles: validationState.styles ?? new Map(),+ breakpoints: validationState.breakpoints,+ contentRootIds: new Set([root.identity.blockInstanceId]),+ }),+ transaction: { payload: validationPayload },+ });+ if (validation.success === false) {+ return throwBuilderRuntimeError("BAD_REQUEST", validation.error);+ }+ return storagePayload.length === 0+ ? undefined+ : { root, payload: storagePayload };+};++const isProtectedTemplatesList = ({+ projection,+ materializedRoots,+ instanceId,+}: {+ projection: ContentStorageProjection;+ materializedRoots: readonly MaterializedContentRoot[];+ instanceId: Instance["id"];+}) =>+ materializedRoots.some(({ identity }) =>+ projection.state.instances+ ?.get(identity.blockInstanceId)+ ?.children.some(+ (child) =>+ child.type === "id" &&+ child.value === instanceId &&+ projection.state.instances?.get(child.value)?.component ===+ blockTemplateComponent+ )+ );++export const executeContentStorageMutation = <+ Mutation extends BuilderRuntimeMutation,+>({+ state,+ materializedRoots,+ returnStorageChanges,+ target,+ source,+ protectTemplatesList,+ protectedInstanceIds = [],+ crossRootError = "Mutation crosses an authored storage boundary.",+ allowCrossRoot = false,+ copySourceInstanceId,+ mdxInsert,+ validationSkippedNamespaces = [],+ execute,+}: {+ state: BuilderState;+ materializedRoots?: readonly MaterializedContentRoot[];+ returnStorageChanges?: boolean;+ target: ContentStorageTargetResolver;+ source?: ContentStorageTarget;+ protectTemplatesList?: boolean;+ protectedInstanceIds?: readonly Instance["id"][];+ crossRootError?: string;+ allowCrossRoot?: boolean;+ copySourceInstanceId?: Instance["id"];+ mdxInsert?: Readonly<{+ source: string;+ parentInstanceId: Instance["id"];+ childIndex: number;+ position: "append" | "prepend" | "replace" | "index";+ }>;+ validationSkippedNamespaces?: readonly BuilderPatchChange["namespace"][];+ execute: (+ state: BuilderState,+ root: ContentStorageRoot,+ sourceRoot?: ContentStorageRoot+ ) => Mutation;+}): Mutation => {+ if (materializedRoots === undefined || materializedRoots.length === 0) {+ return execute(state, projectStorageRoot);+ }+ const projection = createContentStorageProjection({+ state,+ materializedRoots,+ });+ const resolvedTarget =+ typeof target === "function" ? target(projection.state) : target;+ if (+ protectTemplatesList === true &&+ [+ resolvedTarget,+ source,+ ...protectedInstanceIds.map(+ (instanceId) =>+ ({ type: "instance", instanceId }) satisfies ContentStorageTarget+ ),+ ].some(+ (candidate) =>+ candidate?.type === "instance" &&+ isProtectedTemplatesList({+ projection,+ materializedRoots,+ instanceId: candidate.instanceId,+ })+ )+ ) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "The source-backed Content Block Templates list cannot be changed."+ );+ }+ const root = resolveContentStorageRoot(projection, resolvedTarget);+ const sourceRoot =+ source === undefined+ ? undefined+ : resolveContentStorageRoot(projection, source);+ if (+ sourceRoot !== undefined &&+ isSameContentStorageRoot(sourceRoot, root) === false &&+ allowCrossRoot === false+ ) {+ return throwBuilderRuntimeError("BAD_REQUEST", crossRootError);+ }+ if (root.type === "project") {+ const executionState =+ allowCrossRoot && sourceRoot?.type === "external"+ ? projection.state+ : state;+ return execute(executionState, root, sourceRoot);+ }+ if (returnStorageChanges !== true) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "The caller must handle authored storage changes."+ );+ }++ const mutation = execute(projection.state, root, sourceRoot);+ const validationSkippedRecordIds = new Map<+ BuilderPatchChange["namespace"],+ Set<string>+ >();+ for (const change of mutation.payload) {+ if (validationSkippedNamespaces.includes(change.namespace) === false) {+ continue;+ }+ const ids = new Set<string>();+ for (const patch of change.patches) {+ const [id] = patch.path;+ if (typeof id === "string" && patch.path.length === 1) {+ ids.add(id);+ }+ }+ if (ids.size > 0) {+ validationSkippedRecordIds.set(change.namespace, ids);+ }+ }+ const storageChange = createExternalStorageChange({+ projection,+ root,+ payload: mutation.payload,+ validationSkippedRecordIds,+ });+ let annotatedStorageChange: ContentStorageChange | undefined = storageChange;+ if (copySourceInstanceId !== undefined && sourceRoot !== undefined) {+ annotatedStorageChange = {+ root,+ payload: storageChange?.payload ?? [],+ copySource: {+ root: sourceRoot,+ instanceId: copySourceInstanceId,+ },+ };+ }+ if (mdxInsert !== undefined) {+ const result = mutation.result as Record<string, unknown>;+ if (+ Array.isArray(result.instanceIds) === false ||+ Array.isArray(result.rootInstanceIds) === false+ ) {+ throw new Error("MDX insertion result is missing inserted instance ids");+ }+ annotatedStorageChange = {+ ...(annotatedStorageChange ?? { root, payload: [] }),+ mdxInsert: {+ ...mdxInsert,+ instanceIds: result.instanceIds as string[],+ rootInstanceIds: result.rootInstanceIds as string[],+ },+ };+ }+ const storageChanges =+ annotatedStorageChange === undefined+ ? mutation.storageChanges+ : [...(mutation.storageChanges ?? []), annotatedStorageChange];+ return {+ ...mutation,+ payload: [],+ storageChanges,+ noop: storageChanges?.some(hasContentStorageChange) !== true,+ } as Mutation;+};++export const executeContentStorageTextReplacement = <+ Mutation extends BuilderRuntimeMutation,+>({+ state,+ materializedRoots,+ returnStorageChanges,+ execute,+}: {+ state: BuilderState;+ materializedRoots?: readonly MaterializedContentRoot[];+ returnStorageChanges?: boolean;+ execute: (state: BuilderState) => Mutation;+}): Mutation => {+ if (materializedRoots === undefined || materializedRoots.length === 0) {+ return execute(state);+ }+ const projection = createContentStorageProjection({+ state,+ materializedRoots,+ });+ const mutation = execute(projection.state);+ const projectPatches: BuilderPatchChange["patches"] = [];+ const externalPatches = new Map<+ Instance["id"],+ {+ root: Extract<ContentStorageRoot, { type: "external" }>;+ patches: BuilderPatchChange["patches"];+ }+ >();+ for (const change of mutation.payload) {+ if (change.namespace !== "instances") {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Text replacement produced an unsupported patch."+ );+ }+ for (const patch of change.patches) {+ const [instanceId, field] = patch.path;+ if (typeof instanceId !== "string" || field !== "children") {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Text replacement produced an unsupported patch."+ );+ }+ const root = resolveContentStorageRoot(projection, {+ type: "children",+ parentInstanceId: instanceId,+ });+ if (root.type === "project") {+ projectPatches.push(patch);+ continue;+ }+ const group = externalPatches.get(root.identity.blockInstanceId) ?? {+ root,+ patches: [],+ };+ group.patches.push(patch);+ externalPatches.set(root.identity.blockInstanceId, group);+ }+ }+ if (externalPatches.size > 0 && returnStorageChanges !== true) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "The caller must handle authored storage changes."+ );+ }+ const storageChanges = Array.from(externalPatches.values()).flatMap(+ ({ root, patches }) => {+ const change = createExternalStorageChange({+ projection,+ root,+ payload: [{ namespace: "instances", patches }],+ });+ return change === undefined ? [] : [change];+ }+ );+ const combinedStorageChanges = [+ ...(mutation.storageChanges ?? []),+ ...storageChanges,+ ];+ return {+ ...mutation,+ payload:+ projectPatches.length === 0+ ? []+ : [{ namespace: "instances", patches: projectPatches }],+ storageChanges:+ combinedStorageChanges.length === 0 ? undefined : combinedStorageChanges,+ noop: projectPatches.length === 0 && combinedStorageChanges.length === 0,+ } as Mutation;+};++const getPatchedProp = (+ projection: ContentStorageProjection,+ patch: BuilderPatchChange["patches"][number]+) => {+ const [propId, field] = patch.path;+ if (typeof propId !== "string" || patch.op === "remove") {+ return;+ }+ if (patch.path.length === 1) {+ const parsed = propSchema.safeParse(patch.value);+ return parsed.success ? parsed.data : undefined;+ }+ if (patch.path.length === 2 && field === "value") {+ const existing = projection.state.props?.get(propId);+ if (existing !== undefined) {+ return { ...existing, value: patch.value } as typeof existing;+ }+ }+};++const getPropStorageRoot = (+ projection: ContentStorageProjection,+ patch: BuilderPatchChange["patches"][number]+) => {+ const [propId] = patch.path;+ const prop =+ getPatchedProp(projection, patch) ??+ (typeof propId === "string"+ ? projection.state.props?.get(propId)+ : undefined);+ if (prop === undefined) {+ return throwBuilderRuntimeError("BAD_REQUEST", "Prop owner is missing.");+ }+ const root = resolveContentStorageRoot(projection, {+ type: "instance",+ instanceId: prop.instanceId,+ });+ if (typeof propId === "string") {+ const existing = projection.state.props?.get(propId);+ if (existing !== undefined) {+ const existingRoot = resolveContentStorageRoot(projection, {+ type: "instance",+ instanceId: existing.instanceId,+ });+ if (isSameContentStorageRoot(root, existingRoot) === false) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Prop mutation crosses an authored storage boundary."+ );+ }+ }+ }+ return root;+};++const validateExternalReferenceOwnership = ({+ root,+ referenceRoot,+ error,+}: {+ root: ContentStorageRoot;+ referenceRoot: ContentStorageRoot;+ error: string;+}) => {+ if (+ referenceRoot.type === "external" &&+ isSameContentStorageRoot(root, referenceRoot) === false+ ) {+ return throwBuilderRuntimeError("BAD_REQUEST", error);+ }+};++const getDataSourceReferenceRoot = ({+ projection,+ root,+ dataSourceId,+ ownedDataSourceIds,+}: {+ projection: ContentStorageProjection;+ root: ContentStorageRoot;+ dataSourceId: string;+ ownedDataSourceIds: ReadonlySet<string>;+}): ContentStorageRoot => {+ if (ownedDataSourceIds.has(dataSourceId)) {+ return root;+ }+ const identity = projection.externalRootByDataSourceId.get(dataSourceId);+ return identity === undefined+ ? projectStorageRoot+ : { type: "external", identity };+};++const validateExpressionReferenceOwnership = ({+ projection,+ root,+ expression,+ ownedDataSourceIds = new Set(),+ error,+}: {+ projection: ContentStorageProjection;+ root: ContentStorageRoot;+ expression: string;+ ownedDataSourceIds?: ReadonlySet<string>;+ error: string;+}) => {+ for (const identifier of getExpressionIdentifiers(expression)) {+ const dataSourceId = decodeDataVariableId(identifier);+ if (dataSourceId === undefined) {+ continue;+ }+ validateExternalReferenceOwnership({+ root,+ referenceRoot: getDataSourceReferenceRoot({+ projection,+ root,+ dataSourceId,+ ownedDataSourceIds,+ }),+ error,+ });+ }+};++const validatePropReferenceOwnership = ({+ projection,+ root,+ prop,+ ownedInstanceIds = new Set(),+ ownedDataSourceIds = new Set(),+ ownedResourceIds = new Set(),+ error = "Prop reference crosses an authored storage boundary.",+}: {+ projection: ContentStorageProjection;+ root: ContentStorageRoot;+ prop: Prop;+ ownedInstanceIds?: ReadonlySet<string>;+ ownedDataSourceIds?: ReadonlySet<string>;+ ownedResourceIds?: ReadonlySet<string>;+ error?: string;+}) => {+ const referenceRoots: ContentStorageRoot[] = [];+ if (prop.type === "parameter") {+ referenceRoots.push(+ getDataSourceReferenceRoot({+ projection,+ root,+ dataSourceId: prop.value,+ ownedDataSourceIds,+ })+ );+ } else if (prop.type === "resource") {+ const identity = projection.externalRootByResourceId.get(prop.value);+ referenceRoots.push(+ ownedResourceIds.has(prop.value)+ ? root+ : identity === undefined+ ? projectStorageRoot+ : { type: "external", identity }+ );+ } else if (+ prop.type === "page" &&+ typeof prop.value === "object" &&+ prop.value !== null+ ) {+ referenceRoots.push(+ ownedInstanceIds.has(prop.value.instanceId)+ ? root+ : resolveContentStorageRoot(projection, {+ type: "instance",+ instanceId: prop.value.instanceId,+ })+ );+ }+ for (const { expression } of listPropExpressions(prop)) {+ validateExpressionReferenceOwnership({+ projection,+ root,+ expression,+ ownedDataSourceIds,+ error,+ });+ }+ for (const referenceRoot of referenceRoots) {+ validateExternalReferenceOwnership({ root, referenceRoot, error });+ }+};++export const executeContentStoragePropMutation = <+ Mutation extends BuilderRuntimeMutation,+>({+ state,+ materializedRoots,+ returnStorageChanges,+ execute,+}: {+ state: BuilderState;+ materializedRoots?: readonly MaterializedContentRoot[];+ returnStorageChanges?: boolean;+ execute: (state: BuilderState) => Mutation;+}): Mutation => {+ if (materializedRoots === undefined || materializedRoots.length === 0) {+ return execute(state);+ }+ const projection = createContentStorageProjection({+ state,+ materializedRoots,+ });+ const mutation = execute(projection.state);+ const projectChanges = new Map<+ BuilderPatchChange["namespace"],+ BuilderPatchChange+ >();+ const externalChanges = new Map<+ Instance["id"],+ {+ root: Extract<ContentStorageRoot, { type: "external" }>;+ changes: Map<BuilderPatchChange["namespace"], BuilderPatchChange>;+ }+ >();+ for (const change of mutation.payload) {+ for (const patch of change.patches) {+ let root: ContentStorageRoot;+ if (change.namespace === "props") {+ root = getPropStorageRoot(projection, patch);+ const prop = getPatchedProp(projection, patch);+ if (prop !== undefined) {+ validatePropReferenceOwnership({ projection, root, prop });+ }+ } else if (change.namespace === "resources") {+ const [resourceId] = patch.path;+ if (typeof resourceId !== "string") {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Resource owner is missing."+ );+ }+ const identity = projection.externalRootByResourceId.get(resourceId);+ root =+ identity === undefined+ ? projectStorageRoot+ : { type: "external", identity };+ } else {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Prop mutation produced an unsupported patch."+ );+ }+ const changes =+ root.type === "project"+ ? projectChanges+ : (externalChanges.get(root.identity.blockInstanceId)?.changes ??+ new Map());+ const accumulated = changes.get(change.namespace) ?? {+ namespace: change.namespace,+ patches: [],+ };+ accumulated.patches.push(patch);+ changes.set(change.namespace, accumulated);+ if (root.type === "external") {+ externalChanges.set(root.identity.blockInstanceId, { root, changes });+ }+ }+ }+ if (externalChanges.size > 0 && returnStorageChanges !== true) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "The caller must handle authored storage changes."+ );+ }+ const storageChanges = Array.from(externalChanges.values()).flatMap(+ ({ root, changes }) => {+ const storageChange = createExternalStorageChange({+ projection,+ root,+ payload: Array.from(changes.values()),+ });+ return storageChange === undefined ? [] : [storageChange];+ }+ );+ const combinedStorageChanges = [+ ...(mutation.storageChanges ?? []),+ ...storageChanges,+ ];+ return {+ ...mutation,+ payload: Array.from(projectChanges.values()),+ storageChanges:+ combinedStorageChanges.length === 0 ? undefined : combinedStorageChanges,+ noop: projectChanges.size === 0 && combinedStorageChanges.length === 0,+ } as Mutation;+};++const getExistingRecordStorageRoot = ({+ identity,+ exists,+}: {+ identity: ContentBlockExternalContentIdentity | undefined;+ exists: boolean;+}): ContentStorageRoot => {+ if (identity !== undefined) {+ return { type: "external", identity };+ }+ if (exists) {+ return projectStorageRoot;+ }+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Structural mutation owner is missing."+ );+};++const getStructuralPatchRoot = ({+ projection,+ change,+ patch,+}: {+ projection: ContentStorageProjection;+ change: BuilderPatchChange;+ patch: BuilderPatchChange["patches"][number];+}): ContentStorageRoot => {+ const [id, field] = patch.path;+ if (typeof id !== "string") {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Structural mutation owner is missing."+ );+ }+ if (change.namespace === "instances") {+ if (projection.state.instances?.has(id) === false) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Structural mutation cannot create instances while partitioning roots."+ );+ }+ return resolveContentStorageRoot(+ projection,+ field === "children"+ ? { type: "children", parentInstanceId: id }+ : { type: "instance", instanceId: id }+ );+ }+ if (change.namespace === "props") {+ const root = getPropStorageRoot(projection, patch);+ const prop = getPatchedProp(projection, patch);+ if (prop !== undefined) {+ validatePropReferenceOwnership({ projection, root, prop });+ }+ return root;+ }+ if (change.namespace === "styleSourceSelections") {+ return resolveContentStorageRoot(projection, {+ type: "instance",+ instanceId: id,+ });+ }+ if (change.namespace === "dataSources") {+ return getExistingRecordStorageRoot({+ identity: projection.externalRootByDataSourceId.get(id),+ exists: projection.state.dataSources?.has(id) === true,+ });+ }+ if (change.namespace === "resources") {+ return getExistingRecordStorageRoot({+ identity: projection.externalRootByResourceId.get(id),+ exists: projection.state.resources?.has(id) === true,+ });+ }+ if (change.namespace === "styleSources") {+ return getExistingRecordStorageRoot({+ identity: projection.externalRootByStyleSourceId.get(id),+ exists: projection.state.styleSources?.has(id) === true,+ });+ }+ if (change.namespace === "styles") {+ return getExistingRecordStorageRoot({+ identity: projection.externalRootByStyleDeclKey.get(id),+ exists: projection.state.styles?.has(id) === true,+ });+ }+ if (change.namespace === "pages") {+ return projectStorageRoot;+ }+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ `Structural mutation produced unsupported namespace "${change.namespace}".`+ );+};++export const executeContentStorageStructuralMutation = <+ Mutation extends BuilderRuntimeMutation,+>({+ state,+ materializedRoots,+ returnStorageChanges,+ protectedInstanceIds = [],+ rootPairs = [],+ ownershipTransfers = [],+ execute,+}: {+ state: BuilderState;+ materializedRoots?: readonly MaterializedContentRoot[];+ returnStorageChanges?: boolean;+ protectedInstanceIds?: readonly Instance["id"][];+ rootPairs?: readonly Readonly<{+ source: ContentStorageTarget;+ target: ContentStorageTarget;+ }>[];+ ownershipTransfers?: readonly ContentStorageOwnershipTransfer[];+ execute: (state: BuilderState) => Mutation;+}): Mutation => {+ if (materializedRoots === undefined || materializedRoots.length === 0) {+ return execute(state);+ }+ const projection = createContentStorageProjection({+ state,+ materializedRoots,+ });+ for (const instanceId of protectedInstanceIds) {+ if (+ isProtectedTemplatesList({+ projection,+ materializedRoots,+ instanceId,+ })+ ) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "The source-backed Content Block Templates list cannot be changed."+ );+ }+ }+ let hasExternalPair = false;+ for (const pair of rootPairs) {+ const sourceRoot = resolveContentStorageRoot(projection, pair.source);+ const targetRoot = resolveContentStorageRoot(projection, pair.target);+ if (+ isSameContentStorageRoot(sourceRoot, targetRoot) === false &&+ ownershipTransfers.some(+ (transfer) =>+ isSameContentStorageRoot(+ resolveContentStorageRoot(projection, transfer.source),+ sourceRoot+ ) &&+ isSameContentStorageRoot(+ resolveContentStorageRoot(projection, transfer.target),+ targetRoot+ )+ ) === false+ ) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Moving content across authored storage roots is not supported."+ );+ }+ hasExternalPair ||=+ sourceRoot.type === "external" || targetRoot.type === "external";+ }+ if (rootPairs.length > 0 && hasExternalPair === false) {+ return execute(state);+ }+ const ownershipTransferPlans = ownershipTransfers.flatMap((transfer) => {+ const sourceRoot = resolveContentStorageRoot(projection, transfer.source);+ const targetRoot = resolveContentStorageRoot(projection, transfer.target);+ if (isSameContentStorageRoot(sourceRoot, targetRoot)) {+ return [];+ }+ const instanceIds = new Set<Instance["id"]>();+ const visit = (instanceId: Instance["id"]) => {+ if (instanceIds.has(instanceId)) {+ return;+ }+ const instance = projection.state.instances?.get(instanceId);+ if (+ instance === undefined ||+ isSameContentStorageRoot(+ resolveContentStorageRoot(projection, {+ type: "instance",+ instanceId,+ }),+ sourceRoot+ ) === false+ ) {+ return;+ }+ instanceIds.add(instanceId);+ for (const child of instance.children) {+ if (child.type === "id") {+ visit(child.value);+ }+ }+ };+ visit(transfer.rootInstanceId);+ if (instanceIds.size === 0) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Transferred subtree is missing from its authored storage root."+ );+ }+ if (+ Array.from(instanceIds).some(+ (instanceId) =>+ projection.state.instances?.get(instanceId)?.component ===+ blockTemplateComponent+ )+ ) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "A subtree containing Content Block Templates cannot change storage ownership."+ );+ }+ return [{ transfer, sourceRoot, targetRoot, instanceIds }];+ });+ const transferTargets = new Map<string, Set<string>>();+ for (const { sourceRoot, targetRoot } of ownershipTransferPlans) {+ const sourceKey = getContentStorageRootKey(sourceRoot);+ const targets = transferTargets.get(sourceKey) ?? new Set<string>();+ targets.add(getContentStorageRootKey(targetRoot));+ transferTargets.set(sourceKey, targets);+ }+ const visitedRoots = new Set<string>();+ const visitingRoots = new Set<string>();+ const hasTransferCycle = (rootKey: string): boolean => {+ if (visitingRoots.has(rootKey)) {+ return true;+ }+ if (visitedRoots.has(rootKey)) {+ return false;+ }+ visitingRoots.add(rootKey);+ for (const targetKey of transferTargets.get(rootKey) ?? []) {+ if (hasTransferCycle(targetKey)) {+ return true;+ }+ }+ visitingRoots.delete(rootKey);+ visitedRoots.add(rootKey);+ return false;+ };+ if (Array.from(transferTargets.keys()).some(hasTransferCycle)) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Cyclic cross-root ownership transfers are not supported by serial persistence."+ );+ }+ const transferredInstanceIds = new Set<Instance["id"]>();+ for (const { instanceIds } of ownershipTransferPlans) {+ for (const instanceId of instanceIds) {+ if (transferredInstanceIds.has(instanceId)) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Overlapping cross-root ownership transfers are not supported."+ );+ }+ transferredInstanceIds.add(instanceId);+ }+ }+ for (const { transfer } of ownershipTransferPlans) {+ const targetInstanceId =+ transfer.target.type === "children"+ ? transfer.target.parentInstanceId+ : transfer.target.instanceId;+ if (transferredInstanceIds.has(targetInstanceId)) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "A cross-root transfer target cannot change ownership in the same mutation."+ );+ }+ }+ const mutation = execute(projection.state);+ const afterState = applyBuilderPatchTransactions(projection.state, [+ { id: "content-storage-ownership-transfer", payload: mutation.payload },+ ]).state;+ const projectChanges = new Map<+ BuilderPatchChange["namespace"],+ BuilderPatchChange+ >();+ const externalChanges = new Map<+ Instance["id"],+ {+ root: Extract<ContentStorageRoot, { type: "external" }>;+ changes: Map<BuilderPatchChange["namespace"], BuilderPatchChange>;+ }+ >();+ const addPatch = (+ root: ContentStorageRoot,+ namespace: BuilderPatchChange["namespace"],+ patch: BuilderPatchChange["patches"][number]+ ) => {+ const changes =+ root.type === "project"+ ? projectChanges+ : (externalChanges.get(root.identity.blockInstanceId)?.changes ??+ new Map());+ const accumulated = changes.get(namespace) ?? { namespace, patches: [] };+ accumulated.patches.push(patch);+ changes.set(namespace, accumulated);+ if (root.type === "external") {+ externalChanges.set(root.identity.blockInstanceId, { root, changes });+ }+ };+ const transferredRecordIds = new Map<+ BuilderPatchChange["namespace"],+ Set<string>+ >();+ const validationRemovedRecordIdsByBlockId = new Map<+ Instance["id"],+ Map<BuilderPatchChange["namespace"], Set<string>>+ >();+ const validationSkippedRecordIdsByBlockId = new Map<+ Instance["id"],+ Map<BuilderPatchChange["namespace"], Set<string>>+ >();+ const incomingInstanceIdsByBlockId = new Map<+ Instance["id"],+ Set<Instance["id"]>+ >();+ const markTransferred = (+ namespace: BuilderPatchChange["namespace"],+ id: string+ ) => {+ const ids = transferredRecordIds.get(namespace) ?? new Set();+ ids.add(id);+ transferredRecordIds.set(namespace, ids);+ };+ for (const {+ sourceRoot,+ targetRoot,+ instanceIds,+ } of ownershipTransferPlans) {+ const recordIds = new Map<BuilderPatchChange["namespace"], Set<string>>([+ ["instances", instanceIds],+ ]);+ const collect = (+ namespace: BuilderPatchChange["namespace"],+ entries: Iterable<readonly [string, unknown]>,+ include: (value: never) => boolean+ ) => {+ const ids = new Set<string>();+ for (const [id, value] of entries) {+ if (include(value as never)) {+ ids.add(id);+ }+ }+ if (ids.size > 0) {+ recordIds.set(namespace, ids);+ }+ };+ collect("props", projection.state.props ?? [], (prop: Prop) =>+ instanceIds.has(prop.instanceId)+ );+ collect(+ "dataSources",+ projection.state.dataSources ?? [],+ (+ dataSource: NonNullable<BuilderState["dataSources"]> extends Map<+ string,+ infer Value+ >+ ? Value+ : never+ ) => instanceIds.has(dataSource.scopeInstanceId ?? "")+ );+ const transferredDataSourceIds = recordIds.get("dataSources") ?? new Set();+ const referencesTransferredDataSource = (expression: string) =>+ Array.from(getExpressionIdentifiers(expression)).some((identifier) => {+ const dataSourceId = decodeDataVariableId(identifier);+ return (+ dataSourceId !== undefined &&+ transferredDataSourceIds.has(dataSourceId)+ );+ });+ if (transferredDataSourceIds.size > 0) {+ for (const instance of projection.state.instances?.values() ?? []) {+ if (instanceIds.has(instance.id)) {+ continue;+ }+ if (+ instance.children.some(+ (child) =>+ child.type === "expression" &&+ referencesTransferredDataSource(child.value)+ )+ ) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "A data source referenced outside the moved subtree cannot change storage ownership."+ );+ }+ }+ for (const prop of projection.state.props?.values() ?? []) {+ if (instanceIds.has(prop.instanceId)) {+ continue;+ }+ if (+ (prop.type === "parameter" &&+ transferredDataSourceIds.has(prop.value)) ||+ listPropExpressions(prop).some(({ expression }) =>+ referencesTransferredDataSource(expression)+ )+ ) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "A data source referenced outside the moved subtree cannot change storage ownership."+ );+ }+ }+ }+ collect(+ "styleSourceSelections",+ projection.state.styleSourceSelections ?? [],+ (+ selection: NonNullable<+ BuilderState["styleSourceSelections"]+ > extends Map<string, infer Value>+ ? Value+ : never+ ) => instanceIds.has(selection.instanceId)+ );+ const localStyleSourceIds = new Set<string>();+ for (const instanceId of instanceIds) {+ for (const styleSourceId of projection.state.styleSourceSelections?.get(+ instanceId+ )?.values ?? []) {+ if (+ projection.state.styleSources?.get(styleSourceId)?.type === "local"+ ) {+ localStyleSourceIds.add(styleSourceId);+ }+ }+ }+ if (localStyleSourceIds.size > 0) {+ for (const selection of projection.state.styleSourceSelections?.values() ??+ []) {+ if (+ instanceIds.has(selection.instanceId) === false &&+ selection.values.some((id) => localStyleSourceIds.has(id))+ ) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "A local style shared outside the moved subtree cannot change storage ownership."+ );+ }+ }+ recordIds.set("styleSources", localStyleSourceIds);+ recordIds.set(+ "styles",+ new Set(+ Array.from(projection.state.styles ?? [])+ .filter(([, style]) => localStyleSourceIds.has(style.styleSourceId))+ .map(([id]) => id)+ )+ );+ }+ const resourceIds = new Set<string>();+ for (const propId of recordIds.get("props") ?? []) {+ const prop = projection.state.props?.get(propId);+ if (prop?.type === "resource") {+ resourceIds.add(prop.value);+ }+ }+ for (const dataSourceId of recordIds.get("dataSources") ?? []) {+ const dataSource = projection.state.dataSources?.get(dataSourceId);+ if (dataSource?.type === "resource") {+ resourceIds.add(dataSource.resourceId);+ }+ }+ for (const resourceId of resourceIds) {+ const resourceRoot = getExistingRecordStorageRoot({+ identity: projection.externalRootByResourceId.get(resourceId),+ exists: projection.state.resources?.has(resourceId) === true,+ });+ if (isSameContentStorageRoot(resourceRoot, sourceRoot) === false) {+ resourceIds.delete(resourceId);+ }+ }+ if (transferredDataSourceIds.size > 0) {+ for (const resource of projection.state.resources?.values() ?? []) {+ if (resourceIds.has(resource.id)) {+ continue;+ }+ if (+ listResourceExpressions(resource).some(({ expression }) =>+ referencesTransferredDataSource(expression)+ )+ ) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "A data source referenced outside the moved subtree cannot change storage ownership."+ );+ }+ }+ }+ if (resourceIds.size > 0) {+ for (const prop of projection.state.props?.values() ?? []) {+ if (+ instanceIds.has(prop.instanceId) === false &&+ prop.type === "resource" &&+ resourceIds.has(prop.value)+ ) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "A resource shared outside the moved subtree cannot change storage ownership."+ );+ }+ }+ for (const dataSource of projection.state.dataSources?.values() ?? []) {+ if (+ instanceIds.has(dataSource.scopeInstanceId ?? "") === false &&+ dataSource.type === "resource" &&+ resourceIds.has(dataSource.resourceId)+ ) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "A resource shared outside the moved subtree cannot change storage ownership."+ );+ }+ }+ recordIds.set("resources", resourceIds);+ }+ const movedReferenceError =+ "Moved content reference crosses an authored storage boundary.";+ for (const instance of afterState.instances?.values() ?? []) {+ if (instanceIds.has(instance.id)) {+ continue;+ }+ const referencesMovedInstance = instance.children.some(+ (child) => child.type === "id" && instanceIds.has(child.value)+ );+ if (referencesMovedInstance === false) {+ continue;+ }+ const instanceRoot = resolveContentStorageRoot(projection, {+ type: "instance",+ instanceId: instance.id,+ });+ if (isSameContentStorageRoot(instanceRoot, targetRoot) === false) {+ return throwBuilderRuntimeError("BAD_REQUEST", movedReferenceError);+ }+ }+ for (const prop of afterState.props?.values() ?? []) {+ if (+ instanceIds.has(prop.instanceId) ||+ prop.type !== "page" ||+ typeof prop.value !== "object" ||+ prop.value === null ||+ instanceIds.has(prop.value.instanceId) === false+ ) {+ continue;+ }+ validateExternalReferenceOwnership({+ root: resolveContentStorageRoot(projection, {+ type: "instance",+ instanceId: prop.instanceId,+ }),+ referenceRoot: targetRoot,+ error: movedReferenceError,+ });+ }+ for (const instanceId of instanceIds) {+ const instance = projection.state.instances?.get(instanceId);+ for (const child of instance?.children ?? []) {+ if (child.type === "expression") {+ validateExpressionReferenceOwnership({+ projection,+ root: targetRoot,+ expression: child.value,+ ownedDataSourceIds: transferredDataSourceIds,+ error: movedReferenceError,+ });+ }+ }+ }+ for (const propId of recordIds.get("props") ?? []) {+ const prop = projection.state.props?.get(propId);+ if (prop !== undefined) {+ validatePropReferenceOwnership({+ projection,+ root: targetRoot,+ prop,+ ownedInstanceIds: instanceIds,+ ownedDataSourceIds: transferredDataSourceIds,+ ownedResourceIds: resourceIds,+ error: movedReferenceError,+ });+ }+ }+ for (const resourceId of resourceIds) {+ const resource = projection.state.resources?.get(resourceId);+ if (resource === undefined) {+ continue;+ }+ for (const { expression } of listResourceExpressions(resource)) {+ validateExpressionReferenceOwnership({+ projection,+ root: targetRoot,+ expression,+ ownedDataSourceIds: transferredDataSourceIds,+ error: movedReferenceError,+ });+ }+ }+ for (const [namespace, ids] of recordIds) {+ const afterNamespace = afterState[namespace];+ if (!(afterNamespace instanceof Map)) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ `Transferred namespace "${namespace}" is missing.`+ );+ }+ for (const id of ids) {+ const value = afterNamespace.get(id);+ if (value === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ `Transferred ${namespace} record "${id}" is missing.`+ );+ }+ markTransferred(namespace, id);+ addPatch(targetRoot, namespace, { op: "add", path: [id], value });+ addPatch(sourceRoot, namespace, { op: "remove", path: [id] });+ for (const externalRoot of [sourceRoot, targetRoot]) {+ if (externalRoot.type !== "external") {+ continue;+ }+ const removedByNamespace =+ validationRemovedRecordIdsByBlockId.get(+ externalRoot.identity.blockInstanceId+ ) ?? new Map();+ const removedIds = removedByNamespace.get(namespace) ?? new Set();+ removedIds.add(id);+ removedByNamespace.set(namespace, removedIds);+ validationRemovedRecordIdsByBlockId.set(+ externalRoot.identity.blockInstanceId,+ removedByNamespace+ );+ }+ if (sourceRoot.type === "external") {+ const skippedByNamespace =+ validationSkippedRecordIdsByBlockId.get(+ sourceRoot.identity.blockInstanceId+ ) ?? new Map();+ const skippedIds = skippedByNamespace.get(namespace) ?? new Set();+ skippedIds.add(id);+ skippedByNamespace.set(namespace, skippedIds);+ validationSkippedRecordIdsByBlockId.set(+ sourceRoot.identity.blockInstanceId,+ skippedByNamespace+ );+ }+ if (targetRoot.type === "external" && namespace !== "instances") {+ const skippedByNamespace =+ validationSkippedRecordIdsByBlockId.get(+ targetRoot.identity.blockInstanceId+ ) ?? new Map();+ const skippedIds = skippedByNamespace.get(namespace) ?? new Set();+ skippedIds.add(id);+ skippedByNamespace.set(namespace, skippedIds);+ validationSkippedRecordIdsByBlockId.set(+ targetRoot.identity.blockInstanceId,+ skippedByNamespace+ );+ }+ if (targetRoot.type === "external" && namespace === "instances") {+ const incomingIds =+ incomingInstanceIdsByBlockId.get(+ targetRoot.identity.blockInstanceId+ ) ?? new Set();+ incomingIds.add(id);+ incomingInstanceIdsByBlockId.set(+ targetRoot.identity.blockInstanceId,+ incomingIds+ );+ }+ }+ }+ }+ for (const change of mutation.payload) {+ for (const patch of change.patches) {+ const [recordId] = patch.path;+ if (+ typeof recordId === "string" &&+ transferredRecordIds.get(change.namespace)?.has(recordId)+ ) {+ continue;+ }+ const root = getStructuralPatchRoot({ projection, change, patch });+ addPatch(root, change.namespace, patch);+ }+ }+ if (externalChanges.size > 0 && returnStorageChanges !== true) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "The caller must handle authored storage changes."+ );+ }+ const storageChanges = Array.from(externalChanges.values()).flatMap(+ ({ root, changes }) => {+ const removedByNamespace = validationRemovedRecordIdsByBlockId.get(+ root.identity.blockInstanceId+ );+ const validationState = { ...projection.state };+ if (removedByNamespace !== undefined) {+ for (const [namespace, ids] of removedByNamespace) {+ const namespaceState = projection.state[namespace];+ if (!(namespaceState instanceof Map)) {+ continue;+ }+ const values = new Map(+ namespaceState as ReadonlyMap<string, unknown>+ );+ for (const id of ids) {+ values.delete(id);+ }+ (validationState as Record<string, unknown>)[namespace] = values;+ }+ }+ const incomingInstanceIds = incomingInstanceIdsByBlockId.get(+ root.identity.blockInstanceId+ );+ if (incomingInstanceIds !== undefined && validationState.instances) {+ validationState.instances = new Map(+ Array.from(validationState.instances, ([id, instance]) => [+ id,+ incomingInstanceIds.has(id)+ ? instance+ : {+ ...instance,+ children: instance.children.filter(+ (child) =>+ child.type !== "id" ||+ incomingInstanceIds.has(child.value) === false+ ),+ },+ ])+ );+ }+ const storageChange = createExternalStorageChange({+ projection,+ root,+ payload: Array.from(changes.values()),+ transferredRecordIds,+ validationSkippedRecordIds:+ validationSkippedRecordIdsByBlockId.get(+ root.identity.blockInstanceId+ ) ?? new Map(),+ validationState,+ });+ return storageChange === undefined ? [] : [storageChange];+ }+ );+ const combinedStorageChanges = [+ ...(mutation.storageChanges ?? []),+ ...storageChanges,+ ];+ const result = {+ ...mutation,+ payload: Array.from(projectChanges.values()),+ storageChanges:+ combinedStorageChanges.length === 0 ? undefined : combinedStorageChanges,+ noop: projectChanges.size === 0 && combinedStorageChanges.length === 0,+ } as Mutation;+ return {+ ...result,+ persistenceOrder: getRuntimeMutationPersistenceOrder(result),+ };+};diff --git a/packages/project-build/src/runtime/context.ts b/packages/project-build/src/runtime/context.tsindex bf10251f6f..39f414b810 100644--- a/packages/project-build/src/runtime/context.ts+++ b/packages/project-build/src/runtime/context.ts@@ -1,10 +1,233 @@import { nanoid } from "nanoid";+import type { MaterializedContentRoot } from "./content-storage";+import type { ContentStorageChange } from "./mutation";+import type { BuilderPatchChange } from "../contracts/patch";+import type { BuilderNamespace } from "../contracts/namespaces";+import type {+ ContentBlockDiagnostic,+ ContentBlockExternalContentIdentity,+ ContentBlockSource,+} from "@webstudio-is/sdk";++export type ContentBlockSourceInspection = Readonly<{+ blockInstanceId: string;+ renderScope: string;+ configuredSource?: ContentBlockSource;+ resolvedIdentity?: ContentBlockExternalContentIdentity;+ sessionStatus:+ | "disconnected"+ | "saved"+ | "pending"+ | "conflicting"+ | "cancelled"+ | "recoverable"+ | "failed";+ pending: boolean;+ diagnostics: readonly ContentBlockDiagnostic[];+ capabilities: Readonly<{+ canConnect: boolean;+ canSwitch: boolean;+ canDisconnectWithCopy: boolean;+ canEdit: boolean;+ canRetry: boolean;+ canReloadRemote: boolean;+ canCopyUnsavedSource: boolean;+ }>;+ repairRoutes: readonly (+ | "open-file"+ | "retry"+ | "reload-remote"+ | "copy-unsaved-mdx"+ | "disconnect-with-copy"+ )[];+}>;++export type ContentBlockPersistenceStep = Readonly<{+ type: "asset" | "project";+ status: "saved" | "failed" | "not-attempted";+ root?: ContentBlockExternalContentIdentity;+ code?: string;+ message?: string;+}>;++export type ContentBlockPersistenceResult = Readonly<{+ status: "complete" | "partial" | "failed";+ steps: readonly ContentBlockPersistenceStep[];+ retry: Readonly<{+ replan: true;+ roots: readonly ContentBlockExternalContentIdentity[];+ project: boolean;+ }>;+}>;++export type ContentStorageApplication = Readonly<{+ getMaterializedContent: () => readonly MaterializedContentRoot[];+ preflightStorageChanges: (+ changes: readonly ContentStorageChange[]+ ) => Promise<+ | Readonly<{ status: "ready" }>+ | Readonly<{+ status: "failed";+ code: string;+ message: string;+ persistence: ContentBlockPersistenceResult;+ }>+ >;+ saveStorageChanges: (changes: readonly ContentStorageChange[]) => Promise<+ | Readonly<{+ status: "complete";+ persistence: ContentBlockPersistenceResult;+ }>+ | Readonly<{+ status: "failed" | "partial";+ code: string;+ message: string;+ persistence: ContentBlockPersistenceResult;+ }>+ >;+ inspectSource?: (input: {+ blockInstanceId: string;+ renderScope: string;+ load?: boolean;+ variables?: Readonly<Record<string, unknown>>;+ }) => Promise<ContentBlockSourceInspection>;+ applyLifecycle?: (+ input: {+ action: "connect" | "switch" | "disconnect";+ blockInstanceId: string;+ renderScope: string;+ source?: ContentBlockSource;+ authority?: "use-file-content" | "replace-file-body-with-block-content";+ dryRun?: boolean;+ confirmationToken?: string;+ variables?: Readonly<Record<string, unknown>>;+ },+ execution?: {+ commitProjectPayload?: (+ payload: readonly BuilderPatchChange[]+ ) => void | Promise<void>;+ }+ ) => Promise<+ | Readonly<{+ status: "complete";+ result: ContentBlockLifecyclePlan;+ }>+ | Readonly<{+ status: "confirmation-required";+ code: "content-source-confirmation-required";+ confirmationToken: string;+ confirmationExpiresAt: string;+ result: ContentBlockLifecyclePlan;+ }>+ | Readonly<{+ status: "blocked" | "partial";+ code: string;+ message: string;+ result?: ContentBlockLifecyclePlan;+ }>+ >;+ recover?: (input: {+ blockInstanceId: string;+ renderScope: string;+ action: "retry" | "reload-remote" | "copy-unsaved-mdx";+ dryRun?: boolean;+ }) => Promise<+ | Readonly<{+ status: "complete";+ result: Readonly<{+ inspection: ContentBlockSourceInspection;+ source?: string;+ changedAsset: boolean;+ }>;+ }>+ | Readonly<{+ status: "blocked";+ code: string;+ message: string;+ result?: Readonly<{+ inspection: ContentBlockSourceInspection;+ changedAsset: boolean;+ }>;+ }>+ >;+ semanticEdit?: (input: {+ operationId: string;+ input: unknown;+ blockInstanceId: string;+ renderScope: string;+ variables?: Readonly<Record<string, unknown>>;+ dryRun?: boolean;+ }) => Promise<+ | Readonly<{ status: "complete"; result: unknown }>+ | Readonly<{+ status: "blocked" | "partial";+ code: string;+ message: string;+ result?: unknown;+ }>+ >;+ migrateTemplateReferences?: (input: {+ templateInstanceId: string;+ migration:+ | Readonly<{ type: "rename"; to: string }>+ | Readonly<{ type: "remove" }>;+ renderScope: string;+ variables?: Readonly<Record<string, unknown>>;+ selectedAssetIds?: readonly string[];+ dryRun?: boolean;+ confirmationToken?: string;+ }) => Promise<+ Readonly<{+ status: "complete" | "partial" | "blocked" | "confirmation-required";+ code?: string;+ message?: string;+ discoveryComplete: boolean;+ updateCount: number;+ omissionCount: number;+ changedAsset?: boolean;+ files: readonly Readonly<{+ assetId: string;+ revision?: string;+ contentRef: string;+ changed?: boolean;+ status?: "updated" | "unchanged" | "failed";+ updateCount: number;+ omissionCount: number;+ diagnostics: readonly Readonly<{ code: string; message: string }>[];+ }>[];+ diagnostics?: readonly Readonly<{ code: string; message: string }>[];+ confirmationToken?: string;+ confirmationExpiresAt?: string;+ }>+ >;+}>;++type ContentBlockLifecyclePlan = Readonly<{+ action: "connect" | "switch" | "disconnect";+ changesProject: boolean;+ storageWrites: readonly Readonly<{+ identity: ContentBlockExternalContentIdentity;+ expectedRevision: string;+ }>[];+ diagnostics: readonly ContentBlockDiagnostic[];+ persistenceOrder: "none" | "storage-before-project";+}>;export type BuilderRuntimeContext = {createId: () => string;projectId?: string;projectVersion?: number;allowLegacyContentModelWarnings?: boolean;+ materializedContent?: readonly MaterializedContentRoot[];+ returnStorageChanges?: boolean;+ contentStorageApplication?: ContentStorageApplication;+ applicationDryRun?: boolean;+ commitApplicationProjectPayload?: (input: {+ payload: readonly BuilderPatchChange[];+ expectedVersion: number;+ operationId: string;+ invalidatesNamespaces: readonly BuilderNamespace[];+ }) => Promise<{ version: number }>;};export const builderRuntimeContext: BuilderRuntimeContext = {diff --git a/packages/project-build/src/runtime/cutover.ts b/packages/project-build/src/runtime/cutover.tsindex 0271e18df1..968d6f1c34 100644--- a/packages/project-build/src/runtime/cutover.ts+++ b/packages/project-build/src/runtime/cutover.ts@@ -105,6 +105,22 @@ export const builderRuntimeCutoverManifests = [] as const,callers: ["appRouter.api.instances"] as const,},+ {+ family: "content-block-source-operations",+ operationIds: [+ "contentBlocks.inspectSource",+ "contentBlocks.connectSource",+ "contentBlocks.switchSource",+ "contentBlocks.disconnectSource",+ "contentBlocks.recoverSource",+ "contentBlocks.migrateTemplateReferences",+ "contentBlocks.semanticEdit",+ ] as const,+ callers: [+ "Builder stateful Content Block adapter using shared application policy",+ "MCP/CLI content editing",+ ] as const,+ },{family: "project-inspection-read",operationIds: [@@ -135,6 +151,7 @@ export const builderRuntimeCutoverManifests = ["instances.insertComponent","instances.insertCollection","instances.insertFragment",+ "instances.insertMdxText","slots.attach","slots.extract",] as const,@@ -142,6 +159,7 @@ export const builderRuntimeCutoverManifests = ["appRouter.api.instances","MCP insert-collection","MCP insert-fragment",+ "MCP/CLI MDX text insertion","MCP shared Slot authoring","Builder components panel",] as const,diff --git a/packages/project-build/src/runtime/data-formats/instance-transfer.test.ts b/packages/project-build/src/runtime/data-formats/instance-transfer.test.tsindex ab77f92537..bc5a5e40ab 100644--- a/packages/project-build/src/runtime/data-formats/instance-transfer.test.ts+++ b/packages/project-build/src/runtime/data-formats/instance-transfer.test.ts@@ -1,6 +1,41 @@import { expect, test } from "vitest";+import { blockComponent, type WebstudioFragment } from "@webstudio-is/sdk";import { parseInstanceTransferData } from "./instance-transfer";+const createContentBlockFragment = ({+ sourceType = "asset",+ assets = [],+}: {+ sourceType?: "asset" | "expression" | "string";+ assets?: WebstudioFragment["assets"];+} = {}): WebstudioFragment => ({+ children: [{ type: "id", value: "block" }],+ instances: [+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [],+ },+ ],+ assets,+ dataSources: [],+ resources: [],+ props: [+ {+ id: "source",+ instanceId: "block",+ name: "src",+ type: sourceType,+ value: "post",+ },+ ],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+});+test("validates instance transfer data", () => {const valid = parseInstanceTransferData(JSON.stringify({@@ -39,3 +74,43 @@ test("validates instance transfer data", () => {valid: false,});});++test("validates Content Block sources in copied instance data", () => {+ const mdxAsset: WebstudioFragment["assets"][number] = {+ id: "post",+ projectId: "project",+ type: "file",+ name: "post_hash.mdx",+ filename: "post",+ format: "mdx",+ size: 1,+ meta: {},+ description: null,+ createdAt: "2026-08-14T00:00:00.000Z",+ };+ const parse = (fragment: WebstudioFragment) =>+ parseInstanceTransferData(+ JSON.stringify({+ "@webstudio/instance/v0.1": {+ ...fragment,+ instanceSelector: ["block", "body"],+ },+ })+ );++ expect(+ parse(createContentBlockFragment({ assets: [mdxAsset] }))+ ).toMatchObject({ owned: true, valid: true });+ expect(+ parse(createContentBlockFragment({ sourceType: "expression" }))+ ).toMatchObject({ owned: true, valid: true });+ expect(parse(createContentBlockFragment())).toEqual({+ owned: true,+ valid: false,+ });+ expect(+ parse(+ createContentBlockFragment({ sourceType: "string", assets: [mdxAsset] })+ )+ ).toEqual({ owned: true, valid: false });+});diff --git a/packages/project-build/src/runtime/data-formats/instance-transfer.ts b/packages/project-build/src/runtime/data-formats/instance-transfer.tsindex fc9613c415..68d9f10c38 100644--- a/packages/project-build/src/runtime/data-formats/instance-transfer.ts+++ b/packages/project-build/src/runtime/data-formats/instance-transfer.ts@@ -1,17 +1,17 @@-import { webstudioFragment } from "@webstudio-is/sdk";import { z } from "zod";+import { webstudioFragmentMutationInput } from "../fragment";import { parseDataEnvelope } from "./data-envelope";export const instanceTransferDataVersion = "@webstudio/instance/v0.1";export const instancesTransferDataVersion = "@webstudio/instances/v0.1";-export const instanceTransferData = webstudioFragment.extend({- instanceSelector: z.array(z.string()),-});+export const instanceTransferData = webstudioFragmentMutationInput.and(+ z.object({ instanceSelector: z.array(z.string()) })+);export const instancesTransferData = z.object({rootInstanceIds: z.array(z.string()),- fragment: webstudioFragment,+ fragment: webstudioFragmentMutationInput,});export type InstanceTransferData = z.infer<typeof instanceTransferData>;diff --git a/packages/project-build/src/runtime/data-formats/page-transfer.test.ts b/packages/project-build/src/runtime/data-formats/page-transfer.test.tsindex dca037a2fc..2282b92511 100644--- a/packages/project-build/src/runtime/data-formats/page-transfer.test.ts+++ b/packages/project-build/src/runtime/data-formats/page-transfer.test.ts@@ -1,19 +1,21 @@import { expect, test } from "vitest";+import { blockComponent, type WebstudioFragment } from "@webstudio-is/sdk";import { parsePageTransferData } from "./page-transfer";+const emptyFragment: WebstudioFragment = {+ children: [],+ instances: [],+ assets: [],+ dataSources: [],+ resources: [],+ props: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+};+test("validates page transfer data", () => {- const fragment = {- children: [],- instances: [],- assets: [],- dataSources: [],- resources: [],- props: [],- breakpoints: [],- styleSourceSelections: [],- styleSources: [],- styles: [],- };const valid = parsePageTransferData(JSON.stringify({"@webstudio/page/v0.1": {@@ -26,8 +28,8 @@ test("validates page transfer data", () => {meta: {},rootInstanceId: "body",},- rootFragment: fragment,- bodyFragment: fragment,+ rootFragment: emptyFragment,+ bodyFragment: emptyFragment,},}));@@ -47,3 +49,40 @@ test("validates page transfer data", () => {valid: false,});});++test("validates Content Block sources in copied page data", () => {+ const bodyFragment: WebstudioFragment = {+ ...emptyFragment,+ children: [{ type: "id", value: "block" }],+ instances: [+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [],+ },+ ],+ props: [+ {+ id: "source",+ instanceId: "block",+ name: "src",+ type: "asset",+ value: "missing-post",+ },+ ],+ };++ expect(+ parsePageTransferData(+ JSON.stringify({+ "@webstudio/page/v0.1": {+ type: "page",+ page: {},+ rootFragment: emptyFragment,+ bodyFragment,+ },+ })+ )+ ).toEqual({ owned: true, valid: false });+});diff --git a/packages/project-build/src/runtime/data-formats/page-transfer.ts b/packages/project-build/src/runtime/data-formats/page-transfer.tsindex 4c80160fb0..54e460dc22 100644--- a/packages/project-build/src/runtime/data-formats/page-transfer.ts+++ b/packages/project-build/src/runtime/data-formats/page-transfer.ts@@ -3,9 +3,9 @@ import {type Page,type PageTemplate,type WebstudioFragment,- webstudioFragment,} from "@webstudio-is/sdk";import { z } from "zod";+import { webstudioFragmentMutationInput } from "../fragment";import { parseDataEnvelope } from "./data-envelope";export type PageCopyData = {@@ -51,16 +51,16 @@ export const collectPageTransferItems = (export const pageTransferPageInput: z.ZodType<PageTransferData> = z.object({type: z.literal("page"),page: z.custom<Page>(),- rootFragment: webstudioFragment,- bodyFragment: webstudioFragment,+ rootFragment: webstudioFragmentMutationInput,+ bodyFragment: webstudioFragmentMutationInput,});export const pageTransferTemplateInput: z.ZodType<TemplateTransferData> =z.object({type: z.literal("template"),template: z.custom<PageTemplate>(),- rootFragment: webstudioFragment,- bodyFragment: webstudioFragment,+ rootFragment: webstudioFragmentMutationInput,+ bodyFragment: webstudioFragmentMutationInput,});export const pageTransferFolderInput: z.ZodType<FolderTransferData> = z.lazy(diff --git a/packages/project-build/src/runtime/fragment.test.tsx b/packages/project-build/src/runtime/fragment.test.tsxindex 891b065ae1..040171ffe1 100644--- a/packages/project-build/src/runtime/fragment.test.tsx+++ b/packages/project-build/src/runtime/fragment.test.tsx@@ -17,6 +17,7 @@ import {import { createDefaultPages } from "@webstudio-is/project-build";import {encodeDataVariableId,+ blockComponent,getStyleDeclKey,portalComponent,ROOT_INSTANCE_ID,@@ -131,6 +132,72 @@ test("copies a fragment for a target instance and maps root children", () => {);});+test("copies a Content Block with its direct MDX source Asset", () => {+ const data = renderData(<$.Body ws:id="bodyId"></$.Body>);+ const fragment = {+ children: [{ type: "id" as const, value: "block" }],+ instances: [+ {+ type: "instance" as const,+ id: "block",+ component: blockComponent,+ children: [],+ },+ ],+ props: [+ {+ id: "source",+ instanceId: "block",+ name: "src",+ type: "asset" as const,+ value: "post",+ },+ ],+ assets: [+ {+ id: "post",+ projectId: "source-project",+ type: "file" as const,+ name: "post_hash.mdx",+ filename: "post",+ format: "mdx",+ size: 1,+ meta: {},+ description: null,+ createdAt: "2026-08-14T00:00:00.000Z",+ },+ ],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ };+ const ids = ["block-copy", "source-copy"];++ copyWebstudioFragmentMutable({+ data,+ fragment,+ targetInstanceId: "bodyId",+ projectId: "target-project",+ createId: () => ids.shift() ?? "missing",+ });++ expect(data.assets.get("post")).toMatchObject({+ id: "post",+ projectId: "target-project",+ name: "post_hash.mdx",+ });+ expect(data.props.get("source-copy")).toEqual({+ id: "source-copy",+ instanceId: "block-copy",+ name: "src",+ type: "asset",+ value: "post",+ });+});+test("merges multiple copied fragments and preserves requested roots", () => {const first = renderTemplate(<$.Box ws:id="box">diff --git a/packages/project-build/src/runtime/fragment.ts b/packages/project-build/src/runtime/fragment.tsindex 01dd9e523d..a0690d256a 100644--- a/packages/project-build/src/runtime/fragment.ts+++ b/packages/project-build/src/runtime/fragment.ts@@ -19,6 +19,8 @@ import {findPageByIdOrPath,findTreeInstanceIds,findTreeInstanceIdsExcludingSlotDescendants,+ formatContentBlockSourceIntegrityIssue,+ getContentBlockSourceIntegrityIssues,getHomePage,portalComponent,webstudioFragment,@@ -51,6 +53,7 @@ import {collectFontFamiliesFromStyleValue,traverseStyleValue,} from "./style-utils";+import { addZodValidationIssue } from "./errors";export type ContentModeCopyableProp = (input: {prop: Prop;@@ -104,6 +107,28 @@ export const webstudioFragmentMutationInput = webstudioFragment.superRefine(});addExpressionValidationIssues(context, errors, entry.path);}+ const propIndexById = new Map(+ fragment.props.map((prop, index) => [prop.id, index])+ );+ for (const issue of getContentBlockSourceIntegrityIssues({+ instances: fragment.instances,+ props: fragment.props,+ assets: fragment.assets,+ })) {+ const propId =+ issue.type === "duplicateContentBlockSource"+ ? issue.propIds[0]+ : issue.propId;+ addZodValidationIssue(context, {+ code: issue.type,+ path:+ propId === undefined+ ? []+ : ["props", String(propIndexById.get(propId) ?? 0)],+ message: formatContentBlockSourceIntegrityIssue(issue),+ constraint: "valid_content_block_source",+ });+ }});@@ -586,9 +611,11 @@ export const insertWebstudioFragmentCopy = ({metas,contentModeCopyableProp,createId = nanoid,- // In content mode, insertion keeps content-editable instance data, creates- // local styles for inserted instances, and avoids data/resource records.+ // Content mode keeps content-editable instance data and creates local styles.+ // Callers may opt into copying owned data/resources or remapping portal content.contentMode = false,+ includeDataResources = contentMode === false,+ reusePortalContent = true,}: {data: Omit<WebstudioData, "pages">;fragment: WebstudioFragment;@@ -600,6 +627,8 @@ export const insertWebstudioFragmentCopy = ({contentModeCopyableProp?: ContentModeCopyableProp;createId?: () => string;contentMode?: boolean;+ includeDataResources?: boolean;+ reusePortalContent?: boolean;}) => {const newInstanceIds = new Map<Instance["id"], Instance["id"]>();const newDataSourceIds = new Map<DataSource["id"], DataSource["id"]>();@@ -680,7 +709,7 @@ export const insertWebstudioFragmentCopy = ({// - data sources// - props// - local styles- for (const rootInstanceId of portalContentRootIds) {+ for (const rootInstanceId of reusePortalContent ? portalContentRootIds : []) {const instanceIds = findTreeInstanceIdsExcludingSlotDescendants(fragmentInstances,rootInstanceId@@ -692,7 +721,7 @@ export const insertWebstudioFragmentCopy = ({continue;}- if (contentMode === false) {+ if (includeDataResources) {const usedResourceIds = new Set<Resource["id"]>();for (const dataSource of fragment.dataSources) {// insert only data sources within portal content@@ -768,7 +797,7 @@ export const insertWebstudioFragmentCopy = ({maskedIdByName.set(dataSource.name, dataSource.id);}const newResourceIds = new Map<Resource["id"], Resource["id"]>();- if (contentMode === false) {+ if (includeDataResources) {for (let dataSource of fragment.dataSources) {const scopeInstanceId = dataSource.scopeInstanceId ?? "";if (scopeInstanceId === ROOT_INSTANCE_ID) {@@ -851,7 +880,7 @@ export const insertWebstudioFragmentCopy = ({props.set(prop.id, prop);}- if (contentMode === false) {+ if (includeDataResources) {for (let resource of fragment.resources) {if (newResourceIds.has(resource.id) === false) {continue;diff --git a/packages/project-build/src/runtime/instance-duplicate.test.ts b/packages/project-build/src/runtime/instance-duplicate.test.tsindex 36278a4571..2db0cee976 100644--- a/packages/project-build/src/runtime/instance-duplicate.test.ts+++ b/packages/project-build/src/runtime/instance-duplicate.test.ts@@ -1,5 +1,6 @@import { expect, test } from "vitest";import {+ blockTemplateComponent,getStyleDeclKey,type Instance,type StyleDecl,@@ -104,6 +105,31 @@ test("duplicates an instance after itself", () => {]);});+test("assigns a unique name when duplicating a block template", () => {+ const data = createData();+ const parent = data.instances.get("parent");+ if (parent === undefined) {+ throw new Error("Expected parent");+ }+ parent.component = blockTemplateComponent;+ const source = data.instances.get("source");+ if (source === undefined) {+ throw new Error("Expected source");+ }+ source.label = "Hero Card";+ const ids = ["source-copy", "child-copy"];++ duplicateInstanceAfterItselfMutable({+ data,+ sourceInstanceId: "source",+ parentInstanceId: "parent",+ projectId: "project-id",+ createId: () => ids.shift() ?? "missing",+ });++ expect(data.instances.get("source-copy")?.label).toBe("Hero Card 2");+});+test("preserves legacy HtmlEmbed code when duplicating an instance", () => {const data = createData();data.instances.set("source", {diff --git a/packages/project-build/src/runtime/instance-duplicate.ts b/packages/project-build/src/runtime/instance-duplicate.tsindex 3656209572..5d6dd25532 100644--- a/packages/project-build/src/runtime/instance-duplicate.ts+++ b/packages/project-build/src/runtime/instance-duplicate.ts@@ -1,4 +1,8 @@-import type { Instance, WebstudioData } from "@webstudio-is/sdk";+import {+ findChildReferenceIndex,+ type Instance,+ type WebstudioData,+} from "@webstudio-is/sdk";import type { BuilderState } from "../state/builder-state";import type { BuilderRuntimeContext } from "./context";import { findAvailableVariables, produceWebstudioDataMutation } from "./data";@@ -7,11 +11,11 @@ import {extractWebstudioFragment,insertWebstudioFragmentCopy,} from "./fragment";-import { findChildReferenceIndex } from "./instances";import { isAutoGridPlacement, resetGridChildPlacement } from "./style-utils";import { createRuntimeMutation } from "./mutation";import { getSlotFragmentDropTargetMutable } from "./slot";import { z } from "zod";+import { assignUniqueBlockTemplateNamesMutable } from "./block";export const duplicateInstanceAfterItselfInput = z.object({sourceInstanceId: z.string(),@@ -104,6 +108,11 @@ export const duplicateInstanceAfterItselfMutable = ({if (indexWithinChildren === -1) {return;}+ assignUniqueBlockTemplateNamesMutable({+ instanceIds: [newRootInstanceId],+ parent: parentInstance,+ instances: data.instances,+ });parentInstance.children.splice(indexWithinChildren + 1, 0, {type: "id",value: newRootInstanceId,diff --git a/packages/project-build/src/runtime/instances.test.ts b/packages/project-build/src/runtime/instances.test.tsindex 97ac87a28c..52bcceabae 100644--- a/packages/project-build/src/runtime/instances.test.ts+++ b/packages/project-build/src/runtime/instances.test.ts@@ -1,5 +1,8 @@import { describe, expect, test } from "vitest";import {+ blockTemplateComponent,+ blockComponent,+ contentBlockSourceProp,encodeDataVariableId,type DataSource,elementComponent,@@ -30,9 +33,7 @@ import {createTextContentResetPayload,createTextContentSetPayload,createTextContentUpdatePayload,- findChildReferenceIndex,findLocalStyleSourcesWithinInstances,- findParentInstanceReference,fillGrid,findTextContentChild,getInstanceDepths,@@ -47,6 +48,7 @@ import {deleteInstances,moveInstancesInput,moveInstances,+ reparentInstanceMutable,replaceTextInput,serializeTextNodes,setInstanceLabel,@@ -61,6 +63,7 @@ import {import { applyBuilderPatchPayloadMutable } from "../state/patch";import { createDefaultPages } from "@webstudio-is/project-build";import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";+import { BuilderRuntimeError } from "./errors";const runtimeContext = { createId: () => "generated" };@@ -1093,6 +1096,41 @@ describe("wrapInstance", () => {]);});+ test("assigns a unique name to a wrapper in Templates", () => {+ const result = wrapInstance(+ {+ instances: new Map([+ [+ "templates",+ createInstance("templates", blockTemplateComponent, [+ { type: "id", value: "existing" },+ { type: "id", value: "selected" },+ ]),+ ],+ ["existing", createInstance("existing", "Box")],+ ["selected", createInstance("selected", "Section")],+ ]),+ props: new Map(),+ },+ {+ instanceSelector: ["selected", "templates"],+ component: "Box",+ },+ { createId: () => "wrapper" }+ );++ expect(result.payload[0]?.patches).toContainEqual({+ op: "add",+ path: ["wrapper"],+ value: {+ ...createInstance("wrapper", "Box", [+ { type: "id", value: "selected" },+ ]),+ label: "Box 2",+ },+ });+ });+test("wraps selected instance inside shared Slot content", () => {const result = wrapInstance({@@ -1263,6 +1301,90 @@ describe("convertInstance", () => {]);});+ test("rejects conversion that duplicates a template name", () => {+ const card = createInstance("card", "Box");++ expect(() =>+ convertInstance(+ {+ instances: new Map([+ [+ "templates",+ createInstance("templates", blockTemplateComponent, [+ { type: "id", value: "card" },+ { type: "id", value: "section" },+ ]),+ ],+ [card.id, card],+ ["section", createInstance("section", "Section")],+ ]),+ props: new Map(),+ },+ {+ instanceSelector: ["section", "templates"],+ component: "Box",+ },+ runtimeContext+ )+ ).toThrow("Template name must be unique");+ });++ test("requires confirmation when conversion changes a source-backed template name", () => {+ const block = createInstance("block", blockComponent, [+ { type: "id", value: "templates" },+ ]);+ const templates = createInstance("templates", blockTemplateComponent, [+ { type: "id", value: "card" },+ ]);+ const card = createInstance("card", "Box");+ const state = {+ instances: new Map([+ [block.id, block],+ [templates.id, templates],+ [card.id, card],+ ]),+ props: new Map([+ [+ "src",+ {+ id: "src",+ instanceId: block.id,+ name: contentBlockSourceProp,+ type: "asset" as const,+ value: "article.mdx",+ },+ ],+ ]),+ };+ expect(() =>+ convertInstance(+ state,+ {+ instanceSelector: [card.id, templates.id, block.id],+ component: "Section",+ },+ runtimeContext+ )+ ).toThrow("Template name change requires confirmation");++ expect(+ convertInstance(+ state,+ {+ instanceSelector: [card.id, templates.id, block.id],+ component: "Section",+ templateNameConfirmation: {+ action: "rename",+ templates: [+ { instanceId: "card", oldName: "Box", newName: "Section" },+ ],+ },+ },+ runtimeContext+ ).result+ ).toEqual({ instanceId: "card" });+ });+test("removes legacy tag prop and renames React props when converting to element", () => {const result = convertInstance({@@ -1402,6 +1524,40 @@ describe("convertInstance", () => {]);});+ test("rejects converting a direct Slot template to a duplicate name", () => {+ expect(() =>+ convertInstance(+ {+ pages: createDefaultPages({ rootInstanceId: "templates" }),+ instances: new Map([+ [+ "templates",+ createInstance("templates", blockTemplateComponent, [+ { type: "id", value: "box" },+ { type: "id", value: "slot" },+ ]),+ ],+ ["box", createInstance("box", "Box")],+ ["slot", createInstance("slot", "Slot")],+ ]),+ props: new Map(),+ dataSources: new Map(),+ resources: new Map(),+ styleSources: new Map(),+ styleSourceSelections: new Map(),+ styles: new Map(),+ breakpoints: new Map(),+ assets: new Map(),+ },+ {+ instanceSelector: ["slot", "templates"],+ component: "Box",+ },+ runtimeContext+ )+ ).toThrow("Template name must be unique");+ });+test("rejects conversion that violates content model", () => {expect(() =>convertInstance(@@ -1482,6 +1638,72 @@ describe("unwrapInstance", () => {]);});+ test("assigns a unique name when unwrapping into Templates", () => {+ const result = unwrapInstance(+ {+ instances: new Map([+ [+ "templates",+ createInstance("templates", blockTemplateComponent, [+ { type: "id", value: "existing" },+ { type: "id", value: "parent" },+ ]),+ ],+ ["existing", createInstance("existing", "Box")],+ [+ "parent",+ createInstance("parent", "Section", [+ { type: "id", value: "selected" },+ ]),+ ],+ ["selected", createInstance("selected", "Box")],+ ]),+ props: new Map(),+ },+ { instanceSelector: ["selected", "parent", "templates"] },+ runtimeContext+ );++ expect(result.payload[0]?.patches).toContainEqual({+ op: "add",+ path: ["selected", "label"],+ value: "Box 2",+ });+ });++ test("includes a retained wrapper when naming an unwrapped template", () => {+ const result = unwrapInstance(+ {+ instances: new Map([+ [+ "templates",+ createInstance("templates", blockTemplateComponent, [+ { type: "id", value: "parent" },+ ]),+ ],+ [+ "parent",+ createInstance("parent", "Box", [+ { type: "id", value: "selected" },+ { type: "id", value: "sibling" },+ ]),+ ],+ ["selected", createInstance("selected", "Box")],+ ["sibling", createInstance("sibling", "Image")],+ ]),+ props: new Map(),+ },+ { instanceSelector: ["selected", "parent", "templates"] },+ runtimeContext+ );++ expect(result.payload[0]?.patches).toContainEqual({+ op: "add",+ path: ["selected", "label"],+ value: "Box 2",+ });+ });+test("moves selected instance after parent when parent keeps siblings", () => {const result = unwrapInstance({@@ -1846,6 +2068,86 @@ describe("setInstanceTag", () => {expect(result.noop).toEqual(true);expect(result.payload).toEqual([]);});++ test("rejects a tag that duplicates a template name", () => {+ const templates = createInstance("templates", blockTemplateComponent, [+ { type: "id", value: "heading" },+ { type: "id", value: "paragraph" },+ ]);+ const heading = createInstance("heading", elementComponent);+ heading.tag = "h2";+ const paragraph = createInstance("paragraph", elementComponent);+ paragraph.tag = "p";++ expect(() =>+ setInstanceTag(+ {+ instances: new Map([+ ["templates", templates],+ ["heading", heading],+ ["paragraph", paragraph],+ ]),+ props: new Map(),+ },+ { instanceId: "paragraph", tag: "h2" }+ )+ ).toThrow("Template name must be unique");+ });++ test("requires confirmation when an unlabeled source-backed template tag changes", () => {+ const block = createInstance("block", blockComponent, [+ { type: "id", value: "templates" },+ ]);+ const templates = createInstance("templates", blockTemplateComponent, [+ { type: "id", value: "element" },+ ]);+ const element = createInstance("element", elementComponent);+ element.tag = "div";+ const state = {+ instances: new Map([+ [block.id, block],+ [templates.id, templates],+ [element.id, element],+ ]),+ props: new Map([+ [+ "src",+ {+ id: "src",+ instanceId: block.id,+ name: contentBlockSourceProp,+ type: "asset" as const,+ value: "article.mdx",+ },+ ],+ ]),+ };++ expect(() =>+ setInstanceTag(state, { instanceId: element.id, tag: "section" })+ ).toThrow("Template name change requires confirmation");+ expect(+ setInstanceTag(state, {+ instanceId: element.id,+ tag: "section",+ templateNameConfirmation: {+ action: "rename",+ templates: [+ {+ instanceId: "element",+ oldName: "<div>",+ newName: "<section>",+ },+ ],+ },+ }).result+ ).toEqual({ instanceId: "element", tag: "section" });++ element.label = "Hero element";+ expect(+ setInstanceTag(state, { instanceId: element.id, tag: "article" }).result+ ).toEqual({ instanceId: "element", tag: "article" });+ });});describe("setInstanceLabel", () => {@@ -1927,6 +2229,32 @@ describe("setInstanceLabel", () => {]);});+ test("rejects mirrored Slot labels that collide in one Templates list", () => {+ const templates = createInstance("templates", blockTemplateComponent, [+ { type: "id", value: "slot" },+ { type: "id", value: "matching-slot" },+ ]);+ const slot = createInstance("slot", "Slot", [+ { type: "id", value: "child" },+ ]);+ const matchingSlot = createInstance("matching-slot", "Slot", [+ { type: "id", value: "child" },+ ]);++ expect(() =>+ setInstanceLabel(+ {+ instances: new Map([+ ["templates", templates],+ ["slot", slot],+ ["matching-slot", matchingSlot],+ ]),+ },+ { instanceId: "slot", label: "Shared slot" }+ )+ ).toThrow("Template name must be unique");+ });+test("does not mutate unchanged label", () => {const instance = createInstance("box", "Box");instance.label = "Hero card";@@ -1943,6 +2271,166 @@ describe("setInstanceLabel", () => {expect(result.noop).toEqual(true);expect(result.payload).toEqual([]);});++ test("rejects a duplicate name in the same Content Block Templates list", () => {+ const block = createInstance("block", blockComponent, [+ { type: "id", value: "templates" },+ ]);+ const templates = createInstance("templates", blockTemplateComponent, [+ { type: "id", value: "hero" },+ { type: "id", value: "card" },+ ]);+ const hero = createInstance("hero", "Box");+ hero.label = "Hero Card";++ expect(() =>+ setInstanceLabel(+ {+ instances: new Map([+ ["block", block],+ ["templates", templates],+ ["hero", hero],+ ["card", createInstance("card", "Box")],+ ]),+ props: new Map([+ [+ "src",+ {+ id: "src",+ instanceId: block.id,+ name: contentBlockSourceProp,+ type: "asset" as const,+ value: "article.mdx",+ },+ ],+ ]),+ },+ { instanceId: "card", label: "Hero Card" }+ )+ ).toThrow("Template name must be unique");+ });++ test("requires a current confirmation before renaming a source-backed template", () => {+ const block = createInstance("block", blockComponent, [+ { type: "id", value: "templates" },+ ]);+ const templates = createInstance("templates", blockTemplateComponent, [+ { type: "id", value: "card" },+ ]);+ const card = createInstance("card", "Box");+ const state = {+ instances: new Map([+ [block.id, block],+ [templates.id, templates],+ [card.id, card],+ ]),+ props: new Map([+ [+ "src",+ {+ id: "src",+ instanceId: block.id,+ name: contentBlockSourceProp,+ type: "expression" as const,+ value: "articleAssetId",+ },+ ],+ ]),+ };+ let confirmation: unknown;+ try {+ setInstanceLabel(state, { instanceId: card.id, label: "Hero Card" });+ } catch (error) {+ expect(error).toBeInstanceOf(BuilderRuntimeError);+ const issue = (error as BuilderRuntimeError).issues?.[0];+ expect(issue).toMatchObject({+ code: "template_name_change_requires_confirmation",+ constraint: "requires_confirmation:template_name_references",+ });+ confirmation = issue?.example;+ }+ expect(confirmation).toEqual({+ action: "rename",+ templates: [{ instanceId: "card", oldName: "Box", newName: "Hero Card" }],+ });++ expect(+ setInstanceLabel(state, {+ instanceId: card.id,+ label: "Hero Card",+ templateNameConfirmation: confirmation as {+ action: "rename";+ templates: Array<{+ instanceId: string;+ oldName: string;+ newName?: string;+ }>;+ },+ }).result+ ).toEqual({ instanceIds: ["card"], label: "Hero Card" });++ card.label = "Current card";+ expect(() =>+ setInstanceLabel(state, {+ instanceId: card.id,+ label: "Hero Card",+ templateNameConfirmation: confirmation as {+ action: "rename";+ templates: Array<{+ instanceId: string;+ oldName: string;+ newName?: string;+ }>;+ },+ })+ ).toThrow("Template name change requires confirmation");+ });++ test("uses the default effective name when clearing a template label", () => {+ const block = createInstance("block", blockComponent, [+ { type: "id", value: "templates" },+ ]);+ const templates = createInstance("templates", blockTemplateComponent, [+ { type: "id", value: "card" },+ ]);+ const card = createInstance("card", "Box");+ card.label = "Hero Card";+ const state = {+ instances: new Map([+ [block.id, block],+ [templates.id, templates],+ [card.id, card],+ ]),+ props: new Map([+ [+ "src",+ {+ id: "src",+ instanceId: block.id,+ name: contentBlockSourceProp,+ type: "asset" as const,+ value: "article.mdx",+ },+ ],+ ]),+ };++ expect(() =>+ setInstanceLabel(state, { instanceId: card.id, label: " " })+ ).toThrow("Template name change requires confirmation");+ expect(+ setInstanceLabel(state, {+ instanceId: card.id,+ label: " ",+ templateNameConfirmation: {+ action: "rename",+ templates: [+ { instanceId: "card", oldName: "Hero Card", newName: "Box" },+ ],+ },+ }).result.label+ ).toBe("");+ });});test("clone instance with mapped id children", () => {@@ -2058,22 +2546,6 @@ test("gets instance depths from root ids", () => {);});-test("finds child reference index", () => {- expect(- findChildReferenceIndex(- [- { type: "text", value: "before" },- { type: "id", value: "child" },- { type: "text", value: "after" },- ],- "child"- )- ).toBe(1);- expect(- findChildReferenceIndex([{ type: "text", value: "only" }], "child")- ).toBe(-1);-});-test("creates instance child references", () => {expect(createInstanceChild("child")).toEqual({ type: "id", value: "child" });});@@ -2093,25 +2565,6 @@ test("adjusts same-parent insert index after removal", () => {).toBe(1);});-test("finds parent instance reference", () => {- const instances = new Map([- [- "parent",- createInstance("parent", elementComponent, [- { type: "text", value: "before" },- { type: "id", value: "child" },- ]),- ],- ["child", createInstance("child", elementComponent)],- ]);-- expect(findParentInstanceReference(instances, "child")).toEqual({- instance: instances.get("parent"),- childIndex: 1,- });- expect(findParentInstanceReference(instances, "missing")).toBeUndefined();-});-test("creates instance move patches", () => {const instances = new Map([[@@ -2144,6 +2597,71 @@ test("creates instance move patches", () => {});});+const createTemplateMoveInstances = () => {+ const moving = createInstance("moving", "Box");+ moving.label = "Hero Card";+ const existing = createInstance("existing", "Box");+ existing.label = "Hero Card";+ return {+ moving,+ instances: new Map([+ [+ "source",+ createInstance("source", elementComponent, [+ { type: "id", value: moving.id },+ ]),+ ],+ [+ "templates",+ createInstance("templates", blockTemplateComponent, [+ { type: "id", value: existing.id },+ ]),+ ],+ [moving.id, moving],+ [existing.id, existing],+ ]),+ };+};++test("assigns a unique template name when moving between parents", () => {+ const { instances, moving } = createTemplateMoveInstances();++ expect(+ createInstanceMovePatches({+ instances,+ moves: [{ instanceId: moving.id, parentInstanceId: "templates" }],+ }).patches+ ).toContainEqual({+ op: "replace",+ path: [moving.id, "label"],+ value: "Hero Card 2",+ });+});++test("assigns a unique template name when reparenting in the Builder", () => {+ const { instances, moving } = createTemplateMoveInstances();+ const data = {+ instances,+ props: new Map(),+ dataSources: new Map(),+ resources: new Map(),+ styleSources: new Map(),+ styleSourceSelections: new Map(),+ styles: new Map(),+ breakpoints: new Map(),+ assets: new Map(),+ };++ reparentInstanceMutable({+ data,+ sourceInstanceSelector: [moving.id, "source"],+ dropTarget: { parentSelector: ["templates"], position: "end" },+ createId: () => "generated",+ });++ expect(data.instances.get(moving.id)?.label).toBe("Hero Card 2");+});+test("creates instance move payload", () => {const instances = new Map([[diff --git a/packages/project-build/src/runtime/instances.ts b/packages/project-build/src/runtime/instances.tsindex a013bf9211..4b01707059 100644--- a/packages/project-build/src/runtime/instances.ts+++ b/packages/project-build/src/runtime/instances.ts@@ -1,5 +1,8 @@import {+ blockTemplateComponent,elementComponent,+ findChildReferenceIndex,+ findParentInstanceReference,findTreeInstanceIds,getHtmlTagsFromProps,getStyleDeclKey,@@ -16,6 +19,8 @@ import {type WebstudioData,type WsComponentMeta,} from "@webstudio-is/sdk";+// Preserve the project-build runtime API while instance-tree utilities move to SDK.+export { findChildReferenceIndex } from "@webstudio-is/sdk";import {compactBuilderPatchPayload,type BuilderPatchChange,@@ -72,6 +77,76 @@ import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";import { reactPropsToStandardAttributes } from "@webstudio-is/react-sdk/standard-attributes";import equal from "fast-deep-equal";import { z } from "zod";+import {+ assignUniqueBlockTemplateNamesMutable,+ type BlockTemplateNameConfirmation,+ findBlockTemplateNameCollision,+ getBlockTemplateNameConfirmation,+} from "./block";++const throwDuplicateBlockTemplateName = ({+ name,+ path,+}: {+ name: string;+ path: "component" | "label" | "tag";+}): never =>+ throwBuilderValidationError("Template name must be unique", [+ {+ code: "duplicate_template_name",+ path: [path],+ message: `Template name "${name}" is already in use.`,+ constraint: "unique_within:block_templates",+ example: `${name} 2`,+ },+ ]);++export const blockTemplateNameConfirmationInput = z+ .object({+ action: z.enum(["rename", "delete"]),+ templates: z.array(+ z.object({+ instanceId: z.string(),+ oldName: z.string(),+ newName: z.string().optional(),+ })+ ),+ })+ .describe(+ "Retry with the exact confirmation example returned by template_name_change_requires_confirmation after user approval."+ );++export const requireBlockTemplateNameConfirmation = ({+ required,+ confirm,+ path,+}: {+ required: BlockTemplateNameConfirmation | undefined;+ confirm: BlockTemplateNameConfirmation | undefined;+ path:+ | "component"+ | "instanceIds"+ | "instanceSelector"+ | "label"+ | "mode"+ | "tag";+}) => {+ if (required === undefined || equal(required, confirm)) {+ return;+ }+ throwBuilderValidationError("Template name change requires confirmation", [+ {+ code: "template_name_change_requires_confirmation",+ path: [path],+ message:+ required.action === "delete"+ ? "Deleting this template may disconnect references in MDX files."+ : "Renaming this template may disconnect references in MDX files.",+ constraint: "requires_confirmation:template_name_references",+ example: required,+ },+ ]);+};export const insertIndexInput = z.number().int().nonnegative();const instanceEndPositionInput = z.literal("end");@@ -127,10 +202,12 @@ export const cloneInstanceInput = z.object({export const deleteInstancesInput = z.object({instanceIds: z.array(z.string()).min(1),+ templateNameConfirmation: blockTemplateNameConfirmationInput.optional(),});export const deleteInstanceBySelectorInput = z.object({instanceSelector: z.array(z.string()).min(2),+ templateNameConfirmation: blockTemplateNameConfirmationInput.optional(),});export const fillGridInput = z.object({@@ -160,6 +237,7 @@ export const convertInstanceInput = z.object({component: instanceInput.shape.component,tag: z.string().min(1).optional(),currentTag: z.string().min(1).optional(),+ templateNameConfirmation: blockTemplateNameConfirmationInput.optional(),});export const unwrapInstanceInput = z.object({@@ -175,11 +253,13 @@ export const setInstanceTagInput = z.object({instanceId: z.string(),tag: z.string(),legacyPropName: z.string().optional(),+ templateNameConfirmation: blockTemplateNameConfirmationInput.optional(),});export const setInstanceLabelInput = z.object({instanceId: z.string(),label: z.string(),+ templateNameConfirmation: blockTemplateNameConfirmationInput.optional(),});export const updateTextInstanceInput = z.object({@@ -486,14 +566,6 @@ const getRequiredInstances = (return state.instances;};-export const findChildReferenceIndex = (- children: Instance["children"],- instanceId: Instance["id"]-) =>- children.findIndex(- (child) => child.type === "id" && child.value === instanceId- );-export const createInstanceChild = (instanceId: Instance["id"]) =>({ type: "id", value: instanceId }) as const;@@ -665,18 +737,6 @@ export const getSameParentAdjustedInsertIndex = ({requestedIndex: number;}) => (requestedIndex > currentIndex ? requestedIndex - 1 : requestedIndex);-export const findParentInstanceReference = (- instances: Instances,- instanceId: Instance["id"]-) => {- for (const instance of instances.values()) {- const childIndex = findChildReferenceIndex(instance.children, instanceId);- if (childIndex !== -1) {- return { instance, childIndex };- }- }-};-export const getInstanceDepths = (instances: Pick<Instances, "get" | "values">,rootInstanceIds?: Instance["id"][]@@ -1066,6 +1126,27 @@ export const createInstanceMovePatches = ({requestedIndex: requestedInsertIndex,}): requestedInsertIndex;+ if (+ parent.instance.id === nextParent.id &&+ insertIndex === parent.childIndex+ ) {+ continue;+ }+ if (parent.instance.id !== nextParent.id) {+ const previousLabel = instance.label;+ assignUniqueBlockTemplateNamesMutable({+ instanceIds: [instance.id],+ parent: nextParent,+ instances: mutableInstances,+ });+ if (instance.label !== previousLabel && instance.label !== undefined) {+ patches.push({+ op: previousLabel === undefined ? "add" : "replace",+ path: [instance.id, "label"],+ value: instance.label,+ });+ }+ }patches.push({op: "remove" as const,path: [parent.instance.id, "children", parent.childIndex] as [@@ -1114,6 +1195,7 @@ export const createInstanceAppendPayload = ({styleSources,styleSourceSelections,styles,+ protectedChildCount = 0,}: {parent: Instance;instances: Instances;@@ -1125,12 +1207,14 @@ export const createInstanceAppendPayload = ({styleSources: Iterable<StyleSource>;styleSourceSelections: Iterable<StyleSourceSelection>;styles: Iterable<StyleDecl>;+ protectedChildCount?: number;}) => {const parentChildren = parent.children ?? [];+ const replaceableChildren = parentChildren.slice(protectedChildCount);const replacedInstanceIds =mode === "replace"? new Set(- parentChildren.flatMap((child) =>+ replaceableChildren.flatMap((child) =>child.type === "id"? collectInstanceIds(instances, child.value): []@@ -1161,9 +1245,9 @@ export const createInstanceAppendPayload = ({patches: [...(mode === "replace"? sortChildRemovalPatches(- parentChildren.map((_child, index) => ({+ replaceableChildren.map((_child, index) => ({op: "remove" as const,- path: [parent.id, "children", index] as [+ path: [parent.id, "children", protectedChildCount + index] as [string,"children",number,@@ -1773,6 +1857,13 @@ const moveInstanceToParentMutable = (const [newParentId] = dropTarget.parentSelector;const newParent = data.instances.get(newParentId);const newChild = createInstanceChild(rootInstanceId);+ if (newParent !== undefined) {+ assignUniqueBlockTemplateNamesMutable({+ instanceIds: [rootInstanceId],+ parent: newParent,+ instances: data.instances,+ });+ }if (dropTarget.position === "end") {newParent?.children.push(newChild);} else {@@ -1954,6 +2045,11 @@ export const wrapInstance = (selectedItem.instance.id,wrapperInstanceId);+ assignUniqueBlockTemplateNamesMutable({+ instanceIds: [wrapperInstanceId],+ parent: parentInstance,+ instances: nextInstances,+ });const wrapperSelector = [wrapperInstanceId, ...parentItem.instanceSelector];const isSatisfying = isTreeSatisfyingContentModel({instances: nextInstances,@@ -2027,6 +2123,12 @@ export const wrapInstance = (createInstanceChild(wrapperInstanceId);nextInstances.set(parentInstanceId, nextParentInstance);nextInstances.set(wrapperInstanceId, wrapperInstance);+ assignUniqueBlockTemplateNamesMutable({+ instanceIds: [wrapperInstanceId],+ parent: parentInstance,+ replacedInstanceIds: [instanceId],+ instances: nextInstances,+ });const wrapperSelector = [wrapperInstanceId,...input.instanceSelector.slice(1),@@ -2193,7 +2295,6 @@ const unwrapInstanceMutable = ({if (grandparentInstance === undefined) {return { success: false, error: "Grandparent instance not found" };}-const selectedParentId = selectedItem.instanceSelector[1];const selectedParentInstance = instances.get(selectedParentId);if (@@ -2251,6 +2352,13 @@ const unwrapInstanceMutable = ({parentInstance.children,selectedItem.instance.id);+ assignUniqueBlockTemplateNamesMutable({+ instanceIds: [selectedInstance.id],+ parent: grandparentInstance,+ replacedInstanceIds:+ parentInstance.children.length === 0 ? [parentInstance.id] : [],+ instances,+ });if (parentInstance.children.length === 0) {instances.delete(parentItem.instance.id);}@@ -2331,6 +2439,7 @@ export const convertInstance = ();const [selectedItem] = nextInstancePath;const selectedInstance = selectedItem.instance;+ const previousInstance = { ...selectedInstance };if (selectedInstance.component === "Slot" && input.component !== "Slot") {detachSharedSlotChildrenMutable({data: draft,@@ -2379,6 +2488,17 @@ export const convertInstance = (nextInstance.tag = defaultTag;}}+ const collision = findBlockTemplateNameCollision({+ instance: previousInstance,+ nextInstance,+ instances: draft.instances,+ });+ if (collision) {+ return throwDuplicateBlockTemplateName({+ name: collision.name,+ path: "component",+ });+ }const isSatisfying = isTreeSatisfyingContentModel({instances: draft.instances,props: draft.props,@@ -2391,6 +2511,15 @@ export const convertInstance = ("Converted tree violates content model");}+ requireBlockTemplateNameConfirmation({+ required: getBlockTemplateNameConfirmation({+ changes: [{ instance: previousInstance, nextInstance }],+ instances: draft.instances,+ props: draft.props.values(),+ }),+ confirm: input.templateNameConfirmation,+ path: "component",+ });});return createRuntimeMutation({payload,@@ -2489,6 +2618,17 @@ export const convertInstance = (}}+ const collision = findBlockTemplateNameCollision({+ instance,+ nextInstance,+ instances,+ });+ if (collision) {+ return throwDuplicateBlockTemplateName({+ name: collision.name,+ path: "component",+ });+ }const isSatisfying = canConvertInstance({instanceId,instanceSelector: input.instanceSelector,@@ -2505,6 +2645,15 @@ export const convertInstance = ("Converted tree violates content model");}+ requireBlockTemplateNameConfirmation({+ required: getBlockTemplateNameConfirmation({+ changes: [{ instance, nextInstance }],+ instances,+ props: state.props.values(),+ }),+ confirm: input.templateNameConfirmation,+ path: "component",+ });payload.push({ namespace: "instances", patches: instancePatches });return createRuntimeMutation({@@ -2714,6 +2863,18 @@ export const unwrapInstance = ();}nextInstances.set(grandparentInstanceId, nextGrandparentInstance);+ let nextSelectedInstance = selectedInstance;+ if (grandparentInstance.component === blockTemplateComponent) {+ nextSelectedInstance = { ...selectedInstance };+ nextInstances.set(instanceId, nextSelectedInstance);+ assignUniqueBlockTemplateNamesMutable({+ instanceIds: [instanceId],+ parent: grandparentInstance,+ replacedInstanceIds:+ nextParentInstance.children.length === 0 ? [parentInstanceId] : [],+ instances: nextInstances,+ });+ }const nextInstanceSelector = [instanceId, ...input.instanceSelector.slice(2)];const isSatisfying = isTreeSatisfyingContentModel({instances: nextInstances,@@ -2726,6 +2887,13 @@ export const unwrapInstance = (}const patches: BuilderPatchChange["patches"] = [];+ if (nextSelectedInstance.label !== selectedInstance.label) {+ patches.push({+ op: selectedInstance.label === undefined ? "add" : "replace",+ path: [instanceId, "label"],+ value: nextSelectedInstance.label,+ });+ }if (nextParentInstance.children.length === 0) {patches.push({ op: "remove", path: [parentInstanceId] });} else {@@ -2883,6 +3051,26 @@ export const setInstanceTag = (if (instance === undefined) {return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");}+ const collision = findBlockTemplateNameCollision({+ instance,+ nextInstance: { ...instance, tag: input.tag },+ instances,+ });+ if (collision) {+ return throwDuplicateBlockTemplateName({+ name: collision.name,+ path: "tag",+ });+ }+ requireBlockTemplateNameConfirmation({+ required: getBlockTemplateNameConfirmation({+ changes: [{ instance, nextInstance: { ...instance, tag: input.tag } }],+ instances,+ props: state.props.values(),+ }),+ confirm: input.templateNameConfirmation,+ path: "tag",+ });const payload: BuilderPatchChange[] = [];if (input.legacyPropName !== undefined) {@@ -2920,7 +3108,7 @@ export const setInstanceTag = (};export const setInstanceLabel = (- state: Pick<BuilderState, "instances">,+ state: Pick<BuilderState, "instances"> & Partial<Pick<BuilderState, "props">>,input: z.infer<typeof setInstanceLabelInput>) => {const instances = getRequiredInstances(state);@@ -2940,6 +3128,36 @@ export const setInstanceLabel = (): [instance];+ const prospectiveInstances = new Map(instances);+ for (const targetInstance of targetInstances) {+ prospectiveInstances.set(targetInstance.id, { ...targetInstance, label });+ }+ for (const targetInstance of targetInstances) {+ const collision = findBlockTemplateNameCollision({+ instance: targetInstance,+ nextInstance: { ...targetInstance, label },+ instances: prospectiveInstances,+ });+ if (collision) {+ return throwDuplicateBlockTemplateName({+ name: collision.name,+ path: "label",+ });+ }+ }+ requireBlockTemplateNameConfirmation({+ required: getBlockTemplateNameConfirmation({+ changes: targetInstances.map((targetInstance) => ({+ instance: targetInstance,+ nextInstance: prospectiveInstances.get(targetInstance.id),+ })),+ instances,+ props: state.props?.values() ?? [],+ }),+ confirm: input.templateNameConfirmation,+ path: "label",+ });+const patches: BuilderPatchChange["patches"] = [];for (const targetInstance of targetInstances) {if (targetInstance.label === label) {@@ -2995,6 +3213,18 @@ export const deleteInstances = (if (error?.type === "parent-not-found") {return throwBuilderRuntimeError("NOT_FOUND", "Parent instance not found");}+ requireBlockTemplateNameConfirmation({+ required: getBlockTemplateNameConfirmation({+ changes: input.instanceIds.flatMap((instanceId) => {+ const instance = mutationState.instances.get(instanceId);+ return instance === undefined ? [] : [{ instance }];+ }),+ instances: mutationState.instances,+ props: mutationState.props.values(),+ }),+ confirm: input.templateNameConfirmation,+ path: "instanceIds",+ });return createRuntimeMutation({payload,result: { instanceIds },@@ -3054,6 +3284,15 @@ export const deleteInstanceBySelector = (if (error?.type === "parent-not-found") {return throwBuilderRuntimeError("NOT_FOUND", "Parent instance not found");}+ requireBlockTemplateNameConfirmation({+ required: getBlockTemplateNameConfirmation({+ changes: [{ instance: targetInstance }],+ instances: draft.instances,+ props: draft.props.values(),+ }),+ confirm: input.templateNameConfirmation,+ path: "instanceSelector",+ });instanceIds = deletePayload.instanceIds;applyBuilderPatchPayloadMutable((namespace) => getWebstudioDataNamespace(draft, namespace),@@ -3166,6 +3405,24 @@ export const updateTextTree = (});};+export const findInstanceCloneTargetParent = ({+ instances,+ sourceInstanceId,+ targetParentInstanceId,+}: {+ instances: Instances;+ sourceInstanceId: Instance["id"];+ targetParentInstanceId?: Instance["id"];+}) => {+ if (targetParentInstanceId !== undefined) {+ return instances.get(targetParentInstanceId);+ }+ const source = instances.get(sourceInstanceId);+ return source === undefined+ ? undefined+ : findParentInstanceReference(instances, source.id)?.instance;+};+export const cloneInstance = (state: TreeMutationState,input: z.infer<typeof cloneInstanceInput>,@@ -3176,11 +3433,11 @@ export const cloneInstance = (if (source === undefined) {return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");}- const targetParent =- input.targetParentInstanceId === undefined- ? findParentInstanceReference(mutationState.instances, source.id)- ?.instance- : mutationState.instances.get(input.targetParentInstanceId);+ const targetParent = findInstanceCloneTargetParent({+ instances: mutationState.instances,+ sourceInstanceId: source.id,+ targetParentInstanceId: input.targetParentInstanceId,+ });if (targetParent === undefined) {return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");}diff --git a/packages/project-build/src/runtime/mdx-asset-session.test.ts b/packages/project-build/src/runtime/mdx-asset-session.test.tsnew file mode 100644index 0000000000..f9b1f4db00--- /dev/null+++ b/packages/project-build/src/runtime/mdx-asset-session.test.ts@@ -0,0 +1,1554 @@+import { describe, expect, test } from "vitest";+import {+ getAssetContentHash,+ blockComponent,+ blockTemplateComponent,+} from "@webstudio-is/sdk";+import type { AssetRepository } from "@webstudio-is/asset-uploader/server";+import { AssetRevisionConflictError } from "@webstudio-is/asset-uploader/server";+import type { BuilderState } from "../state/builder-state";+import {+ createMdxAssetEditingSession,+ type MdxAssetEditingSessionState,+} from "./mdx-asset-session";++const encoder = new TextEncoder();++const asset = (id: string, name = `${id}_hash.mdx`) => ({+ id,+ projectId: "project",+ size: 0,+ name,+ filename: `${id}.mdx`,+ description: null,+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-02T00:00:00.000Z",+ type: "file" as const,+ format: "file",+ meta: {},+});++const createRepository = (sources: Map<string, string>) =>+ ({+ readContent: async ({ assetId }: { assetId: string }) => {+ const source = sources.get(assetId);+ if (source === undefined) {+ throw new Error("Asset not found");+ }+ const bytes = encoder.encode(source);+ return {+ asset: { ...asset(assetId), size: bytes.byteLength },+ data: {+ async *[Symbol.asyncIterator]() {+ yield bytes;+ },+ },+ contentLength: bytes.byteLength,+ };+ },+ }) satisfies Pick<AssetRepository, "readContent">;++const readStream = async (stream: ReadableStream<Uint8Array>) => {+ const reader = stream.getReader();+ const chunks: Uint8Array[] = [];+ for (;;) {+ const { value, done } = await reader.read();+ if (done) {+ break;+ }+ chunks.push(value);+ }+ const length = chunks.reduce((total, chunk) => total + chunk.byteLength, 0);+ const bytes = new Uint8Array(length);+ let offset = 0;+ for (const chunk of chunks) {+ bytes.set(chunk, offset);+ offset += chunk.byteLength;+ }+ return new TextDecoder().decode(bytes);+};++const createWritableRepository = (initial: Map<string, string>) => {+ const sources = new Map(initial);+ const names = new Map(+ Array.from(initial.keys(), (id) => [id, `${id}_hash.mdx`])+ );+ const updates: Array<{+ assetId: string;+ expectedName: string;+ source: string;+ }> = [];+ let revision = 0;+ const repository = {+ readContent: async ({ assetId }: { assetId: string }) => {+ const source = sources.get(assetId);+ const name = names.get(assetId);+ if (source === undefined || name === undefined) {+ throw new Error("Asset not found");+ }+ const bytes = encoder.encode(source);+ return {+ asset: { ...asset(assetId, name), size: bytes.byteLength },+ data: {+ async *[Symbol.asyncIterator]() {+ yield bytes;+ },+ },+ contentLength: bytes.byteLength,+ };+ },+ updateContent: async ({+ assetId,+ expectedName,+ data,+ }: Parameters<AssetRepository["updateContent"]>[0]) => {+ if (names.get(assetId) !== expectedName) {+ throw new AssetRevisionConflictError("Changed remotely");+ }+ const source = await readStream(data);+ revision += 1;+ const name = `${assetId}_revision_${revision}.mdx`;+ names.set(assetId, name);+ sources.set(assetId, source);+ updates.push({ assetId, expectedName, source });+ return {+ ...asset(assetId, name),+ size: encoder.encode(source).byteLength,+ };+ },+ } satisfies Pick<AssetRepository, "readContent" | "updateContent">;+ return { repository, sources, names, updates };+};++const textChange = (+ state: Extract<MdxAssetEditingSessionState, { status: "saved" | "pending" }>,+ value: string+) => ({+ root: { type: "external" as const, identity: state.identity },+ payload: [+ {+ namespace: "instances" as const,+ patches: [+ {+ op: "replace" as const,+ path: [state.root.fragment.instances[0].id, "children", 0, "value"],+ value,+ },+ ],+ },+ ],+});++const createState = (): BuilderState => ({+ instances: new Map([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: "templates" }],+ },+ ],+ [+ "templates",+ {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [],+ },+ ],+ ]),+ props: new Map(),+ dataSources: new Map(),+ resources: new Map(),+ styleSources: new Map(),+ styleSourceSelections: new Map(),+ styles: new Map(),+ breakpoints: new Map(),+ assets: new Map(),+});++const expectStatus = <Status extends MdxAssetEditingSessionState["status"]>(+ state: MdxAssetEditingSessionState,+ status: Status+) => {+ expect(state.status).toBe(status);+ return state as Extract<MdxAssetEditingSessionState, { status: Status }>;+};++describe("MDX Asset editing session", () => {+ test("loads direct Assets into a revision-pinned materialized root", async () => {+ const source = "# Direct";+ const session = createMdxAssetEditingSession({+ repository: createRepository(new Map([["direct", source]])),+ authorizeAsset: () => true,+ });++ const loaded = expectStatus(+ await session.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "direct" },+ renderScope: "page:/one",+ state: createState(),+ projectId: "project",+ }),+ "saved"+ );++ expect(loaded.identity).toEqual({+ blockInstanceId: "block",+ assetId: "direct",+ revision: `sha256:${await getAssetContentHash(encoder.encode(source))}`,+ contentRef: "direct_hash.mdx",+ format: "mdx",+ renderScope: "page:/one",+ });+ expect(loaded.root.fragment.instances[0]).toMatchObject({ tag: "h1" });+ });++ test("resolves a dynamic binding once and isolates render scopes", async () => {+ const sources = new Map([+ ["first", "First"],+ ["second", "Second"],+ ]);+ let resolved = "first";+ let resolutionCount = 0;+ const session = createMdxAssetEditingSession({+ repository: createRepository(sources),+ authorizeAsset: () => true,+ resolveExpressionAssetId: () => {+ resolutionCount += 1;+ return resolved;+ },+ });+ const input = {+ blockInstanceId: "block",+ source: { type: "expression" as const, value: "post.body" },+ state: createState(),+ projectId: "project",+ };++ const first = expectStatus(+ await session.open({ ...input, renderScope: "collection:first" }),+ "saved"+ );+ resolved = "second";+ const second = expectStatus(+ await session.open({ ...input, renderScope: "collection:second" }),+ "saved"+ );++ expect(first.key).not.toBe(second.key);+ expect(first.identity.assetId).toBe("first");+ expect(second.identity.assetId).toBe("second");+ expect(session.get(first.key)).toBe(first);+ expect(session.get(second.key)).toBe(second);+ expect(resolutionCount).toBe(2);+ });++ test("returns a typed failure when dynamic source resolution fails", async () => {+ const session = createMdxAssetEditingSession({+ repository: createRepository(new Map()),+ authorizeAsset: () => true,+ resolveExpressionAssetId: () => {+ throw new Error("Unavailable scope");+ },+ });++ const failed = expectStatus(+ await session.open({+ blockInstanceId: "block",+ source: { type: "expression", value: "post.body" },+ renderScope: "page:/one",+ state: createState(),+ projectId: "project",+ }),+ "failed"+ );+ expect(failed.error.message).toBe("Unavailable scope");+ });++ test("does not re-evaluate a changed dynamic binding while saving", async () => {+ let resolved = "first";+ let resolutionCount = 0;+ const authorized: string[] = [];+ const writable = createWritableRepository(new Map([["first", "Before"]]));+ const session = createMdxAssetEditingSession({+ repository: writable.repository,+ authorizeAsset: ({ assetId, operation }) => {+ authorized.push(`${operation}:${assetId}`);+ return true;+ },+ resolveExpressionAssetId: () => {+ resolutionCount += 1;+ return resolved;+ },+ });+ const loaded = expectStatus(+ await session.open({+ blockInstanceId: "block",+ source: { type: "expression", value: "post.body" },+ renderScope: "page:/one",+ state: createState(),+ projectId: "project",+ }),+ "saved"+ );+ const instance = loaded.root.fragment.instances[0];+ resolved = "other";++ const pending = expectStatus(+ await session.prepareSave({+ key: loaded.key,+ changes: [+ {+ root: { type: "external", identity: loaded.identity },+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: [instance.id, "children", 0],+ value: { type: "text", value: "After" },+ },+ ],+ },+ ],+ },+ ],+ }),+ "pending"+ );++ expect(resolutionCount).toBe(1);+ expect(pending.writes[0].root.identity.assetId).toBe("first");+ expectStatus(await session.flush(loaded.key), "saved");+ expect(authorized).toEqual(["read:first", "write:first", "write:first"]);+ });++ test("does not discard a pending save when the same scope is reopened", async () => {+ const session = createMdxAssetEditingSession({+ repository: createRepository(new Map([["post", "Before"]])),+ authorizeAsset: () => true,+ });+ const input = {+ blockInstanceId: "block",+ source: { type: "asset" as const, assetId: "post" },+ renderScope: "page:/one",+ state: createState(),+ projectId: "project",+ };+ const loaded = expectStatus(await session.open(input), "saved");+ const instance = loaded.root.fragment.instances[0];+ const pending = expectStatus(+ await session.prepareSave({+ key: loaded.key,+ changes: [+ {+ root: { type: "external", identity: loaded.identity },+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: [instance.id, "children", 0],+ value: { type: "text", value: "After" },+ },+ ],+ },+ ],+ },+ ],+ }),+ "pending"+ );++ expect(await session.open(input)).toBe(pending);+ expect(session.get(loaded.key)).toBe(pending);+ });++ test("keeps the latest result when the same scope is opened out of order", async () => {+ let releaseFirstRead: (() => void) | undefined;+ const firstRead = new Promise<void>((resolve) => {+ releaseFirstRead = resolve;+ });+ let readCount = 0;+ const session = createMdxAssetEditingSession({+ repository: {+ readContent: async ({ assetId }) => {+ readCount += 1;+ const currentRead = readCount;+ if (currentRead === 1) {+ await firstRead;+ }+ const source = currentRead === 1 ? "Old" : "New";+ const bytes = encoder.encode(source);+ return {+ asset: {+ ...asset(assetId, `${assetId}_${source.toLowerCase()}.mdx`),+ size: bytes.byteLength,+ },+ data: {+ async *[Symbol.asyncIterator]() {+ yield bytes;+ },+ },+ };+ },+ },+ authorizeAsset: () => true,+ });+ const input = {+ blockInstanceId: "block",+ source: { type: "asset" as const, assetId: "post" },+ renderScope: "page:/one",+ state: createState(),+ projectId: "project",+ };++ const olderOpen = session.open(input);+ while (readCount === 0) {+ await Promise.resolve();+ }+ const latest = expectStatus(await session.open(input), "saved");+ releaseFirstRead?.();+ await olderOpen;++ expect(latest.source).toBe("New");+ expect(session.get(latest.key)).toBe(latest);+ expect(session.list()).toEqual([latest]);+ });++ test("keeps a session saved when there are no writes to prepare", async () => {+ let scheduled = false;+ const session = createMdxAssetEditingSession({+ repository: createRepository(new Map([["post", "Body"]])),+ authorizeAsset: () => true,+ schedule: () => {+ scheduled = true;+ },+ });+ const input = {+ blockInstanceId: "block",+ source: { type: "asset" as const, assetId: "post" },+ renderScope: "page:/one",+ state: createState(),+ projectId: "project",+ };+ const loaded = expectStatus(await session.open(input), "saved");++ expect(await session.prepareSave({ key: loaded.key, changes: [] })).toBe(+ loaded+ );+ expect(await session.queueSave({ key: loaded.key, changes: [] })).toBe(+ loaded+ );+ expect(scheduled).toBe(false);+ expect(session.get(loaded.key)).toBe(loaded);+ });++ test("debounces and coalesces text, prop, and reorder edits", async () => {+ const writable = createWritableRepository(+ new Map([+ [+ "post",+ `<ws.element ws:tag="p" class="before">Before</ws.element>\n\nSecond`,+ ],+ ])+ );+ const tasks = new Set<() => void>();+ const session = createMdxAssetEditingSession({+ repository: writable.repository,+ authorizeAsset: () => true,+ debounceMilliseconds: 10,+ schedule: (callback) => {+ tasks.add(callback);+ return callback;+ },+ cancelScheduled: (callback) => {+ tasks.delete(callback as () => void);+ },+ });+ const loaded = expectStatus(+ await session.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "post" },+ renderScope: "page:/one",+ state: createState(),+ projectId: "project",+ }),+ "saved"+ );+ const textPending = expectStatus(+ await session.queueSave({+ key: loaded.key,+ changes: [textChange(loaded, "After")],+ }),+ "pending"+ );+ const classProp = textPending.root.fragment.props.find(+ ({ name }) => name === "class"+ )!;+ const propPending = expectStatus(+ await session.queueSave({+ key: loaded.key,+ changes: [+ {+ root: { type: "external", identity: textPending.identity },+ payload: [+ {+ namespace: "props",+ patches: [+ {+ op: "replace",+ path: [classProp.id, "value"],+ value: "after",+ },+ ],+ },+ ],+ },+ ],+ }),+ "pending"+ );+ await session.queueSave({+ key: loaded.key,+ changes: [+ {+ root: { type: "external", identity: propPending.identity },+ payload: [+ {+ namespace: "fragment",+ patches: [+ {+ op: "replace",+ path: ["children"],+ value: [...propPending.root.fragment.children].reverse(),+ },+ ],+ },+ ],+ },+ ],+ });++ expect(tasks.size).toBe(1);+ tasks.values().next().value?.();+ const saved = expectStatus(await session.flush(loaded.key), "saved");+ expect(writable.updates).toHaveLength(1);+ expect(writable.updates[0].source).toContain('class="after"');+ expect(writable.updates[0].source).toContain("After");+ expect(writable.updates[0].source.indexOf("Second")).toBeLessThan(+ writable.updates[0].source.indexOf("After")+ );+ expect(saved.identity.contentRef).toBe("post_revision_1.mdx");+ expect(await session.flush(loaded.key)).toBe(saved);+ expect(writable.updates).toHaveLength(1);+ });++ test("replaces pending source locally and persists the next replacement", async () => {+ const writable = createWritableRepository(new Map([["post", "Before"]]));+ const tasks = new Set<() => void>();+ const session = createMdxAssetEditingSession({+ repository: writable.repository,+ authorizeAsset: () => true,+ schedule: (callback) => {+ tasks.add(callback);+ return callback;+ },+ cancelScheduled: (callback) => tasks.delete(callback as () => void),+ });+ const loaded = expectStatus(+ await session.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "post" },+ renderScope: "page:/one",+ state: createState(),+ projectId: "project",+ }),+ "saved"+ );+ const pending = expectStatus(+ await session.queueSave({+ key: loaded.key,+ changes: [textChange(loaded, "After")],+ }),+ "pending"+ );++ const restored = await session.replaceSource({+ key: loaded.key,+ expectedSource: pending.localSource,+ source: loaded.source,+ });+ expect(restored).toMatchObject({+ status: "applied",+ state: { status: "saved" },+ });+ expect(tasks.size).toBe(0);+ expect(writable.updates).toHaveLength(0);++ const replaced = await session.replaceSource({+ key: loaded.key,+ expectedSource: loaded.source,+ source: pending.localSource,+ });+ expect(replaced).toMatchObject({+ status: "applied",+ state: { status: "pending" },+ });+ expectStatus(await session.flush(loaded.key), "saved");+ expect(writable.sources.get("post")).toContain("After");+ });++ test("reports a committed restore when rematerialization fails after writing", async () => {+ const writable = createWritableRepository(new Map([["post", "Before"]]));+ const state = createState();+ const updateContent = writable.repository.updateContent;+ const session = createMdxAssetEditingSession({+ repository: {+ ...writable.repository,+ updateContent: async (input) => {+ const result = await updateContent(input);+ state.assets = undefined;+ return result;+ },+ },+ authorizeAsset: () => true,+ schedule: () => 0,+ cancelScheduled: () => {},+ });+ const loaded = expectStatus(+ await session.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "post" },+ renderScope: "page:/one",+ state,+ projectId: "project",+ }),+ "saved"+ );++ const restored = await session.persistSourceReplacement({+ key: loaded.key,+ expectedSource: loaded.source,+ source: "After",+ });++ expect(restored).toMatchObject({+ status: "applied",+ state: { status: "recoverable", committedSource: "After" },+ });+ expect(writable.sources.get("post")).toBe("After");+ });++ test("treats restoring the current source as an idempotent no-op", async () => {+ const writable = createWritableRepository(new Map([["post", "Before"]]));+ const tasks = new Set<() => void>();+ let scheduledCalls = 0;+ let cancelledCalls = 0;+ const session = createMdxAssetEditingSession({+ repository: writable.repository,+ authorizeAsset: () => true,+ schedule: (callback) => {+ scheduledCalls += 1;+ tasks.add(callback);+ return callback;+ },+ cancelScheduled: (callback) => {+ cancelledCalls += 1;+ tasks.delete(callback as () => void);+ },+ });+ const loaded = expectStatus(+ await session.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "post" },+ renderScope: "page:/one",+ state: createState(),+ projectId: "project",+ }),+ "saved"+ );+ const pending = expectStatus(+ await session.queueSave({+ key: loaded.key,+ changes: [textChange(loaded, "After")],+ }),+ "pending"+ );++ expect(+ await session.replaceSource({+ key: loaded.key,+ expectedSource: pending.localSource,+ source: pending.localSource,+ })+ ).toMatchObject({ status: "applied", state: { status: "pending" } });+ expect(scheduledCalls).toBe(1);+ expect(cancelledCalls).toBe(0);+ expect(tasks.size).toBe(1);+ expect(writable.updates).toHaveLength(0);+ });++ test("prepares a multi-root restore without scheduling independent persistence", async () => {+ const writable = createWritableRepository(new Map([["post", "Before"]]));+ const tasks = new Set<() => void>();+ const session = createMdxAssetEditingSession({+ repository: writable.repository,+ authorizeAsset: () => true,+ schedule: (callback) => {+ tasks.add(callback);+ return callback;+ },+ cancelScheduled: (callback) => tasks.delete(callback as () => void),+ });+ const loaded = expectStatus(+ await session.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "post" },+ renderScope: "page:/one",+ state: createState(),+ projectId: "project",+ }),+ "saved"+ );+ const prepared = await session.prepareSourceReplacement({+ key: loaded.key,+ expectedSource: loaded.source,+ source: "After",+ });+ if (prepared.status !== "ready") {+ throw new Error("Expected source restore to be ready");+ }++ expect(prepared.canApply().status).toBe("ready");+ expect(prepared.apply({ schedule: false })).toMatchObject({+ status: "applied",+ state: { status: "pending", localSource: "After" },+ });+ expect(tasks.size).toBe(0);+ expect(writable.updates).toHaveLength(0);+ });++ test("authorizes the exact pinned Asset before preparing a source replacement", async () => {+ const writable = createWritableRepository(new Map([["post", "Before"]]));+ const session = createMdxAssetEditingSession({+ repository: writable.repository,+ authorizeAsset: ({ operation, assetId, identity }) => {+ if (+ operation === "write" &&+ assetId === "post" &&+ identity?.contentRef === "post_hash.mdx"+ ) {+ throw new Error("Authorization service unavailable");+ }+ return operation === "read";+ },+ });+ const loaded = expectStatus(+ await session.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "post" },+ renderScope: "page:/one",+ state: createState(),+ projectId: "project",+ }),+ "saved"+ );++ expect(+ await session.prepareSourceReplacement({+ key: loaded.key,+ expectedSource: loaded.source,+ source: "After",+ })+ ).toMatchObject({+ status: "blocked",+ reason: "unauthorized",+ currentSource: "Before",+ });+ expect(session.get(loaded.key)).toBe(loaded);+ expect(writable.updates).toHaveLength(0);+ });++ test("rejects a prepared restore after the session changes", async () => {+ const writable = createWritableRepository(new Map([["post", "Before"]]));+ const session = createMdxAssetEditingSession({+ repository: writable.repository,+ authorizeAsset: () => true,+ schedule: () => 0,+ cancelScheduled: () => {},+ });+ const loaded = expectStatus(+ await session.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "post" },+ renderScope: "page:/one",+ state: createState(),+ projectId: "project",+ }),+ "saved"+ );+ const prepared = await session.prepareSourceReplacement({+ key: loaded.key,+ expectedSource: loaded.source,+ source: "After",+ });+ if (prepared.status !== "ready") {+ throw new Error("Expected source restore to be ready");+ }++ session.cancel(loaded.key);++ expect(prepared.canApply()).toMatchObject({+ status: "blocked",+ reason: "source-mismatch",+ });+ expect(() => prepared.apply()).toThrowError();+ expect(writable.updates).toHaveLength(0);+ });++ test("rejects a prepared restore after the pinned Asset revision changes", async () => {+ const writable = createWritableRepository(new Map([["post", "Before"]]));+ const session = createMdxAssetEditingSession({+ repository: writable.repository,+ authorizeAsset: () => true,+ schedule: () => 0,+ cancelScheduled: () => {},+ });+ const input = {+ blockInstanceId: "block",+ source: { type: "asset" as const, assetId: "post" },+ renderScope: "page:/one",+ state: createState(),+ projectId: "project",+ };+ const loaded = expectStatus(await session.open(input), "saved");+ const prepared = await session.prepareSourceReplacement({+ key: loaded.key,+ expectedSource: loaded.source,+ source: "After",+ });+ if (prepared.status !== "ready") {+ throw new Error("Expected source restore to be ready");+ }+ await writable.repository.updateContent({+ assetId: "post",+ expectedName: loaded.identity.contentRef,+ data: new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(encoder.encode(loaded.source));+ controller.close();+ },+ }),+ });++ const reopened = expectStatus(await session.open(input), "saved");+ expect(reopened.identity.contentRef).not.toBe(loaded.identity.contentRef);+ expect(prepared.canApply()).toMatchObject({+ status: "blocked",+ reason: "identity-mismatch",+ });+ expect(() => prepared.apply()).toThrowError();+ });++ test("replaces saved content against each latest revision", async () => {+ const writable = createWritableRepository(new Map([["post", "Before"]]));+ const session = createMdxAssetEditingSession({+ repository: writable.repository,+ authorizeAsset: () => true,+ schedule: () => 0,+ cancelScheduled: () => {},+ });+ const loaded = expectStatus(+ await session.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "post" },+ renderScope: "page:/one",+ state: createState(),+ projectId: "project",+ }),+ "saved"+ );+ await session.queueSave({+ key: loaded.key,+ changes: [textChange(loaded, "After")],+ });+ const savedAfter = expectStatus(await session.flush(loaded.key), "saved");++ expect(+ await session.replaceSource({+ key: loaded.key,+ expectedSource: savedAfter.source,+ source: loaded.source,+ })+ ).toMatchObject({ status: "applied", state: { status: "pending" } });+ const savedBefore = expectStatus(await session.flush(loaded.key), "saved");+ expect(savedBefore.identity.contentRef).toBe("post_revision_2.mdx");+ expect(writable.sources.get("post")).toBe("Before");++ expect(+ await session.replaceSource({+ key: loaded.key,+ expectedSource: savedBefore.source,+ source: savedAfter.source,+ })+ ).toMatchObject({ status: "applied", state: { status: "pending" } });+ const replaced = expectStatus(await session.flush(loaded.key), "saved");+ expect(replaced.identity.contentRef).toBe("post_revision_3.mdx");+ expect(writable.sources.get("post")).toContain("After");+ });++ test("serializes an edit queued while a write is in flight", async () => {+ const writable = createWritableRepository(new Map([["post", "Before"]]));+ const updateContent = writable.repository.updateContent;+ let releaseFirst!: () => void;+ const firstGate = new Promise<void>((resolve) => {+ releaseFirst = resolve;+ });+ let updateCount = 0;+ const session = createMdxAssetEditingSession({+ repository: {+ ...writable.repository,+ updateContent: async (input) => {+ updateCount += 1;+ if (updateCount === 1) {+ await firstGate;+ }+ return updateContent(input);+ },+ },+ authorizeAsset: () => true,+ schedule: () => 0,+ cancelScheduled: () => {},+ });+ const input = {+ blockInstanceId: "block",+ source: { type: "asset" as const, assetId: "post" },+ renderScope: "page:/one",+ state: createState(),+ projectId: "project",+ };+ const loaded = expectStatus(await session.open(input), "saved");+ await session.queueSave({+ key: loaded.key,+ changes: [textChange(loaded, "First")],+ });+ const flushing = session.flush(loaded.key);+ await Promise.resolve();+ const firstPending = expectStatus(session.get(loaded.key)!, "pending");+ await session.queueSave({+ key: loaded.key,+ changes: [textChange(firstPending, "Second")],+ });+ const joinedFlush = session.flush(loaded.key);+ releaseFirst();++ const saved = expectStatus(await flushing, "saved");+ expectStatus(await joinedFlush, "saved");+ expect(writable.updates.map(({ source }) => source.trim())).toEqual([+ "First",+ "Second",+ ]);+ expect(saved.identity.contentRef).toBe("post_revision_2.mdx");+ });++ test("does not reload remote state while a write is in flight", async () => {+ const writable = createWritableRepository(new Map([["post", "Before"]]));+ const updateContent = writable.repository.updateContent;+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ const session = createMdxAssetEditingSession({+ repository: {+ ...writable.repository,+ updateContent: async (input) => {+ await gate;+ return updateContent(input);+ },+ },+ authorizeAsset: () => true,+ schedule: () => 0,+ cancelScheduled: () => {},+ });+ const input = {+ blockInstanceId: "block",+ source: { type: "asset" as const, assetId: "post" },+ renderScope: "page:/one",+ state: createState(),+ projectId: "project",+ };+ const loaded = expectStatus(await session.open(input), "saved");+ await session.queueSave({+ key: loaded.key,+ changes: [textChange(loaded, "After")],+ });+ const flushing = session.flush(loaded.key);+ await Promise.resolve();++ await expect(session.reloadRemote(loaded.key)).rejects.toThrow(+ "Cannot reload an MDX Asset while its write is in flight"+ );+ release();+ expectStatus(await flushing, "saved");+ });++ test("preserves a conflicting local source for retry and remote reload", async () => {+ const writable = createWritableRepository(new Map([["post", "Remote"]]));+ const session = createMdxAssetEditingSession({+ repository: writable.repository,+ authorizeAsset: () => true,+ schedule: () => 0,+ cancelScheduled: () => {},+ });+ const loaded = expectStatus(+ await session.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "post" },+ renderScope: "page:/one",+ state: createState(),+ projectId: "project",+ }),+ "saved"+ );+ await session.queueSave({+ key: loaded.key,+ changes: [textChange(loaded, "Local")],+ });+ writable.names.set("post", "post_remote.mdx");++ expectStatus(await session.flush(loaded.key), "conflicting");+ expect(session.copyUnsavedSource(loaded.key)).toContain("Local");+ expectStatus(await session.retry(loaded.key), "conflicting");++ const remote = expectStatus(+ await session.reloadRemote(loaded.key),+ "saved"+ );+ expect(remote.identity.contentRef).toBe("post_remote.mdx");+ expect(remote.root.fragment.instances[0].children).toEqual([+ { type: "text", value: "Remote" },+ ]);+ expect(session.copyUnsavedSource(loaded.key)).toContain("Local");+ });++ test("keeps failed local writes retryable", async () => {+ const writable = createWritableRepository(new Map([["post", "Before"]]));+ const updateContent = writable.repository.updateContent;+ let shouldFail = true;+ const session = createMdxAssetEditingSession({+ repository: {+ ...writable.repository,+ updateContent: async (input) => {+ if (shouldFail) {+ shouldFail = false;+ throw new Error("Offline");+ }+ return updateContent(input);+ },+ },+ authorizeAsset: () => true,+ schedule: () => 0,+ cancelScheduled: () => {},+ });+ const input = {+ blockInstanceId: "block",+ source: { type: "asset" as const, assetId: "post" },+ renderScope: "page:/one",+ state: createState(),+ projectId: "project",+ };+ const loaded = expectStatus(await session.open(input), "saved");+ await session.queueSave({+ key: loaded.key,+ changes: [textChange(loaded, "After")],+ });++ const failed = expectStatus(await session.flush(loaded.key), "failed");+ expect(failed.error.message).toBe("Offline");+ expect(session.copyUnsavedSource(loaded.key)).toContain("After");+ if (!("localSource" in failed)) {+ throw new Error("Expected failed write state");+ }+ expect(+ session.canReplaceSource({+ key: loaded.key,+ expectedSource: failed.localSource,+ })+ ).toMatchObject({ status: "blocked", reason: "unresolved-write" });+ expect(+ await session.replaceSource({+ key: loaded.key,+ expectedSource: failed.localSource,+ source: loaded.source,+ })+ ).toMatchObject({ status: "blocked", reason: "unresolved-write" });+ expect(await session.open(input)).toBe(failed);+ expectStatus(await session.retry(loaded.key), "saved");+ expect(writable.sources.get("post")).toContain("After");+ });++ test("rechecks exact Asset authorization when a queued write flushes", async () => {+ const writable = createWritableRepository(new Map([["post", "Before"]]));+ let canWrite = true;+ const session = createMdxAssetEditingSession({+ repository: writable.repository,+ authorizeAsset: ({ operation, assetId, identity }) =>+ operation === "read" ||+ (canWrite &&+ assetId === "post" &&+ identity?.contentRef === "post_hash.mdx"),+ schedule: () => 0,+ cancelScheduled: () => {},+ });+ const loaded = expectStatus(+ await session.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "post" },+ renderScope: "page:/one",+ state: createState(),+ projectId: "project",+ }),+ "saved"+ );+ await session.queueSave({+ key: loaded.key,+ changes: [textChange(loaded, "After")],+ });+ canWrite = false;++ const failed = expectStatus(await session.flush(loaded.key), "failed");+ expect(failed.error.message).toBe(+ "MDX Asset is not authorized for writing"+ );+ expect(writable.updates).toHaveLength(0);+ expect(session.copyUnsavedSource(loaded.key)).toContain("After");+ });++ test("flushes independent Assets concurrently without scope leakage", async () => {+ const writable = createWritableRepository(+ new Map([+ ["first", "First"],+ ["second", "Second"],+ ])+ );+ const updateContent = writable.repository.updateContent;+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ let active = 0;+ let maximumActive = 0;+ const session = createMdxAssetEditingSession({+ repository: {+ ...writable.repository,+ updateContent: async (input) => {+ active += 1;+ maximumActive = Math.max(maximumActive, active);+ await gate;+ const result = await updateContent(input);+ active -= 1;+ return result;+ },+ },+ authorizeAsset: () => true,+ schedule: () => 0,+ cancelScheduled: () => {},+ });+ const input = {+ blockInstanceId: "block",+ state: createState(),+ projectId: "project",+ };+ const first = expectStatus(+ await session.open({+ ...input,+ source: { type: "asset", assetId: "first" },+ renderScope: "collection:first",+ }),+ "saved"+ );+ const second = expectStatus(+ await session.open({+ ...input,+ source: { type: "asset", assetId: "second" },+ renderScope: "collection:second",+ }),+ "saved"+ );+ await session.queueSave({+ key: first.key,+ changes: [textChange(first, "First updated")],+ });+ await session.queueSave({+ key: second.key,+ changes: [textChange(second, "Second updated")],+ });+ const flushing = Promise.all([+ session.flush(first.key),+ session.flush(second.key),+ ]);+ await Promise.resolve();+ await Promise.resolve();+ expect(maximumActive).toBe(2);+ release();+ const results = await flushing;++ expect(results.map(({ status }) => status)).toEqual(["saved", "saved"]);+ expect(writable.sources.get("first")).toContain("First updated");+ expect(writable.sources.get("second")).toContain("Second updated");+ });++ test("cancels a queued write without persisting and rejects stale returned identity", async () => {+ const writable = createWritableRepository(new Map([["post", "Before"]]));+ const tasks = new Set<() => void>();+ const session = createMdxAssetEditingSession({+ repository: writable.repository,+ authorizeAsset: () => true,+ schedule: (callback) => {+ tasks.add(callback);+ return callback;+ },+ cancelScheduled: (callback) => tasks.delete(callback as () => void),+ });+ const input = {+ blockInstanceId: "block",+ source: { type: "asset" as const, assetId: "post" },+ renderScope: "page:/one",+ state: createState(),+ projectId: "project",+ };+ const loaded = expectStatus(await session.open(input), "saved");+ const pending = expectStatus(+ await session.queueSave({+ key: loaded.key,+ changes: [textChange(loaded, "Cancelled")],+ }),+ "pending"+ );+ expect(session.cancel(loaded.key).status).toBe("cancelled");+ expect(tasks.size).toBe(0);+ expectStatus(await session.flush(loaded.key), "cancelled");+ expect(writable.updates).toHaveLength(0);+ expect(+ await session.replaceSource({+ key: loaded.key,+ expectedSource: pending.localSource,+ source: loaded.source,+ })+ ).toMatchObject({ status: "applied", state: { status: "saved" } });++ const stale = createMdxAssetEditingSession({+ repository: {+ ...writable.repository,+ updateContent: async ({ assetId, data }) => {+ const source = await readStream(data);+ return {+ ...asset(assetId, `${assetId}_next.mdx`),+ projectId: "other-project",+ size: encoder.encode(source).byteLength,+ };+ },+ },+ authorizeAsset: () => true,+ schedule: () => 0,+ cancelScheduled: () => {},+ });+ const staleLoaded = expectStatus(await stale.open(input), "saved");+ await stale.queueSave({+ key: staleLoaded.key,+ changes: [textChange(staleLoaded, "Stale")],+ });+ const conflict = expectStatus(+ await stale.flush(staleLoaded.key),+ "conflicting"+ );+ expect("error" in conflict && conflict.error.message).toBe(+ "Asset repository returned a stale MDX revision"+ );+ expect(stale.copyUnsavedSource(staleLoaded.key)).toContain("Stale");+ stale.cancel(staleLoaded.key);+ expect(+ stale.canReplaceSource({+ key: staleLoaded.key,+ expectedSource: stale.copyUnsavedSource(staleLoaded.key)!,+ })+ ).toMatchObject({ status: "blocked", reason: "unresolved-write" });+ });++ test("cancels an in-flight flush before storage starts", async () => {+ const writable = createWritableRepository(new Map([["post", "Before"]]));+ let releaseAuthorization!: () => void;+ const authorizationGate = new Promise<void>((resolve) => {+ releaseAuthorization = resolve;+ });+ let writeAuthorizations = 0;+ const session = createMdxAssetEditingSession({+ repository: writable.repository,+ authorizeAsset: async ({ operation }) => {+ if (operation === "write") {+ writeAuthorizations += 1;+ if (writeAuthorizations === 2) {+ await authorizationGate;+ }+ }+ return true;+ },+ schedule: () => 0,+ cancelScheduled: () => {},+ });+ const loaded = expectStatus(+ await session.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "post" },+ renderScope: "page:/one",+ state: createState(),+ projectId: "project",+ }),+ "saved"+ );+ await session.queueSave({+ key: loaded.key,+ changes: [textChange(loaded, "Cancelled")],+ });+ const flushing = session.flush(loaded.key);+ await Promise.resolve();+ session.cancel(loaded.key);+ releaseAuthorization();++ expectStatus(await flushing, "cancelled");+ expect(writable.updates).toHaveLength(0);+ });++ test("reopens against remote content after cancelling an active storage write", async () => {+ const writable = createWritableRepository(new Map([["post", "Before"]]));+ const updateContent = writable.repository.updateContent;+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ let started!: () => void;+ const storageStarted = new Promise<void>((resolve) => {+ started = resolve;+ });+ const session = createMdxAssetEditingSession({+ repository: {+ ...writable.repository,+ updateContent: async (input) => {+ started();+ await gate;+ return updateContent(input);+ },+ },+ authorizeAsset: () => true,+ schedule: () => 0,+ cancelScheduled: () => {},+ });+ const input = {+ blockInstanceId: "block",+ source: { type: "asset" as const, assetId: "post" },+ renderScope: "page:/one",+ state: createState(),+ projectId: "project",+ };+ const loaded = expectStatus(await session.open(input), "saved");+ await session.queueSave({+ key: loaded.key,+ changes: [textChange(loaded, "After")],+ });+ const flushing = session.flush(loaded.key);+ await storageStarted;+ session.cancel(loaded.key);+ release();++ expectStatus(await flushing, "cancelled");+ expect(+ session.canReplaceSource({+ key: loaded.key,+ expectedSource: loaded.source,+ })+ ).toMatchObject({ status: "blocked", reason: "unresolved-write" });+ const reopened = expectStatus(await session.open(input), "saved");+ expect(reopened.identity.contentRef).toBe("post_revision_1.mdx");+ expect(reopened.root.fragment.instances[0].children).toEqual([+ { type: "text", value: "After" },+ ]);+ });++ test("reports changed direct bindings and stale revisions as conflicts", async () => {+ const mismatchedRepository = {+ readContent: async () => {+ const bytes = encoder.encode("Body");+ return {+ asset: { ...asset("other"), size: bytes.byteLength },+ data: {+ async *[Symbol.asyncIterator]() {+ yield bytes;+ },+ },+ };+ },+ } satisfies Pick<AssetRepository, "readContent">;+ const mismatch = createMdxAssetEditingSession({+ repository: mismatchedRepository,+ authorizeAsset: () => true,+ });+ const changed = expectStatus(+ await mismatch.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "selected" },+ renderScope: "page:/one",+ state: createState(),+ projectId: "project",+ }),+ "conflicting"+ );+ expect(changed.diagnostics).toMatchObject([+ {+ code: "changed-binding",+ loadedAssetId: "other",+ resolvedAssetId: "selected",+ },+ ]);++ const stale = createMdxAssetEditingSession({+ repository: createRepository(new Map([["selected", "Body"]])),+ authorizeAsset: () => true,+ });+ const conflict = expectStatus(+ await stale.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "selected" },+ renderScope: "page:/one",+ expectedRevision: "sha256:stale",+ state: createState(),+ projectId: "project",+ }),+ "conflicting"+ );+ expect(conflict.diagnostics).toMatchObject([+ {+ code: "stale-revision",+ expectedRevision: "sha256:stale",+ },+ ]);++ const legacy = expectStatus(+ await stale.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "selected" },+ renderScope: "page:/legacy",+ expectedRevision: "file:selected_hash.mdx:2026-01-02T00:00:00.000Z:4",+ state: createState(),+ projectId: "project",+ }),+ "saved"+ );+ expect(legacy.identity.revision).toBe(+ "file:selected_hash.mdx:2026-01-02T00:00:00.000Z:4"+ );+ });++ test.each([+ [{ projectId: "other" }, "Body"],+ [{ size: 3 }, "Body"],+ ])(+ "rejects content whose identity does not match its bytes %#",+ async (assetOverride, source) => {+ const bytes = encoder.encode(source);+ const session = createMdxAssetEditingSession({+ repository: {+ readContent: async () => ({+ asset: {+ ...asset("post"),+ size: bytes.byteLength,+ ...assetOverride,+ },+ data: {+ async *[Symbol.asyncIterator]() {+ yield bytes;+ },+ },+ }),+ },+ authorizeAsset: () => true,+ });++ const failed = expectStatus(+ await session.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "post" },+ renderScope: "page:/one",+ state: createState(),+ projectId: "project",+ }),+ "failed"+ );+ expect(failed.error.message).toBe(+ "Asset content identity does not match its bytes"+ );+ }+ );++ test("keeps invalid and unsafe MDX recoverable and supports reload/cancel", async () => {+ const sources = new Map([["post", `<ws.element ws:tag="p">`]]);+ const session = createMdxAssetEditingSession({+ repository: createRepository(sources),+ authorizeAsset: () => true,+ });+ const input = {+ blockInstanceId: "block",+ source: { type: "asset" as const, assetId: "post" },+ renderScope: "page:/one",+ state: createState(),+ projectId: "project",+ };+ const invalid = expectStatus(await session.open(input), "recoverable");+ expect(invalid.diagnostics[0]).toMatchObject({ code: "invalid-mdx" });++ sources.set("post", `{alert("unsafe")}`);+ const recoverable = expectStatus(await session.open(input), "recoverable");+ expect(recoverable.diagnostics[0]).toMatchObject({ code: "unsafe-mdx" });++ sources.set("post", "Recovered");+ const recovered = expectStatus(await session.open(input), "saved");+ expect(recovered.key).not.toBe(recoverable.key);+ expect(session.cancel(recovered.key).status).toBe("cancelled");+ });++ test("keeps invalid UTF-8 recoverable", async () => {+ const bytes = new Uint8Array([0xff]);+ const session = createMdxAssetEditingSession({+ repository: {+ readContent: async () => ({+ asset: { ...asset("post"), size: bytes.byteLength },+ data: {+ async *[Symbol.asyncIterator]() {+ yield bytes;+ },+ },+ }),+ },+ authorizeAsset: () => true,+ });++ const recoverable = expectStatus(+ await session.open({+ blockInstanceId: "block",+ source: { type: "asset", assetId: "post" },+ renderScope: "page:/one",+ state: createState(),+ projectId: "project",+ }),+ "recoverable"+ );+ expect(recoverable.diagnostics).toMatchObject([{ code: "invalid-mdx" }]);+ });+});diff --git a/packages/project-build/src/runtime/mdx-asset-session.ts b/packages/project-build/src/runtime/mdx-asset-session.tsnew file mode 100644index 0000000000..bee3b48bd3--- /dev/null+++ b/packages/project-build/src/runtime/mdx-asset-session.ts@@ -0,0 +1,1368 @@+import { createAssetContentRevision } from "@webstudio-is/asset-uploader/content-revision";+import {+ AssetRevisionConflictError,+ type AssetContentRepository,+} from "@webstudio-is/asset-uploader/content-repository";+import {+ decodeUtf8,+ readBoundedBytes,+} from "@webstudio-is/content-engine/compiler";+import { contentEngineLimits } from "@webstudio-is/content-engine/limits";+import {+ MdxDocumentError,+ parseMdxDocument,+} from "@webstudio-is/content-engine/mdx";+import {+ getAssetContentHash,+ getAssetDisplayNameParts,+ type ContentBlockDiagnostic,+ type ContentBlockExternalContentIdentity,+ type ContentBlockSource,+} from "@webstudio-is/sdk";+import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";+import type { BuilderState } from "../state/builder-state";+import { getRequiredComponentInsertData } from "./components";+import {+ getContentBlockRenderScopeKey,+ getContentStorageIdentityKey,+} from "./content-storage";+import { materializeMdxAuthoredContent } from "./mdx-authored-content";+import { materializeMdxTemplates } from "./mdx-materialization";+import {+ prepareMdxContentStorageWrites,+ type PendingMdxContentStorageWrite,+} from "./mdx-storage-adapter";+import { resolveMdxTemplates } from "./mdx-template-resolution";+import type { ContentStorageChange } from "./mutation";++type SessionBase = Readonly<{+ key: string;+ identity: ContentBlockExternalContentIdentity;+ diagnostics: readonly ContentBlockDiagnostic[];+}>;++type LoadedSessionBase = SessionBase &+ Readonly<{+ root: ReturnType<typeof materializeMdxAuthoredContent>;+ source: string;+ }>;++type UnsavedSessionBase = LoadedSessionBase &+ Readonly<{+ writes: readonly PendingMdxContentStorageWrite[];+ localSource: string;+ }>;++export type MdxAssetEditingSessionState =+ | (LoadedSessionBase & Readonly<{ status: "saved" }>)+ | (UnsavedSessionBase & Readonly<{ status: "pending" }>)+ | (SessionBase & Readonly<{ status: "conflicting" }>)+ | (UnsavedSessionBase & Readonly<{ status: "conflicting"; error: Error }>)+ | (SessionBase & Readonly<{ status: "cancelled" }>)+ | (SessionBase &+ Readonly<{+ status: "recoverable";+ error: Error;+ committedSource?: string;+ }>)+ | Readonly<{+ status: "failed";+ blockInstanceId: string;+ renderScope: string;+ diagnostics: readonly ContentBlockDiagnostic[];+ error: Error;+ }>+ | (UnsavedSessionBase & Readonly<{ status: "failed"; error: Error }>);++export const getContentBlockSessionSource = (+ state: MdxAssetEditingSessionState | undefined+) =>+ state !== undefined && "localSource" in state+ ? state.localSource+ : state !== undefined && "source" in state+ ? state.source+ : undefined;++export const isContentBlockSessionSourceCommitted = ({+ state,+ source,+}: {+ state: MdxAssetEditingSessionState;+ source: string;+}) =>+ (state.status === "saved" && state.source === source) ||+ (state.status === "recoverable" && state.committedSource === source);++export type MdxAssetSessionAuthorization = (input: {+ assetId: string;+ operation: "read" | "write";+ identity?: ContentBlockExternalContentIdentity;+}) => boolean | Promise<boolean>;++export type MdxAssetSessionOpenInput = Readonly<{+ blockInstanceId: string;+ source: ContentBlockSource;+ renderScope: string;+ expectedRevision?: string;+ state: BuilderState;+ projectId: string;+ variables?: Readonly<Record<string, unknown>>;+}>;++type MdxAssetSessionSchedule = (+ callback: () => void,+ delayMilliseconds: number+) => unknown;++type MdxAssetSessionQueueEntry = {+ key: string;+ input: MdxAssetSessionOpenInput;+ assetId: string;+ version: number;+ timer?: unknown;+ inFlight?: Promise<MdxAssetEditingSessionState>;+ unsavedSource?: string;+ persisted?: LoadedSessionBase;+ cancelled: boolean;+ remoteStateUnknown: boolean;+};++export type MdxAssetSourceReplacementResult =+ | Readonly<{+ status: "applied";+ state: MdxAssetEditingSessionState;+ }>+ | Readonly<{+ status: "blocked";+ state: MdxAssetEditingSessionState;+ reason:+ | "in-flight"+ | "unresolved-write"+ | "source-mismatch"+ | "identity-mismatch"+ | "unauthorized";+ currentSource?: string;+ }>;++export type MdxAssetSourceReplacementPreflight =+ | Readonly<{ status: "ready"; currentSource: string }>+ | Extract<MdxAssetSourceReplacementResult, { status: "blocked" }>;++export type MdxAssetPreparedSourceReplacement =+ | Extract<MdxAssetSourceReplacementResult, { status: "blocked" }>+ | Readonly<{+ status: "ready";+ canApply: () => MdxAssetSourceReplacementPreflight;+ apply: (options?: {+ schedule?: boolean;+ }) => Extract<MdxAssetSourceReplacementResult, { status: "applied" }>;+ }>;++export type MdxAssetSourceController = Readonly<{+ canReplaceSource: (input: {+ key: string;+ expectedSource: string;+ }) => MdxAssetSourceReplacementPreflight;+ replaceSource: (input: {+ key: string;+ expectedSource: string;+ source: string;+ }) => Promise<MdxAssetSourceReplacementResult>;+ prepareSourceReplacement: (input: {+ key: string;+ expectedSource: string;+ source: string;+ }) => Promise<MdxAssetPreparedSourceReplacement>;+ persistSourceReplacement: (input: {+ key: string;+ expectedSource: string;+ source: string;+ isCurrent?: () => boolean;+ }) => Promise<MdxAssetSourceReplacementResult>;+}>;++const toParserDiagnostic = ({+ error,+ identity,+}: {+ error: unknown;+ identity: ContentBlockExternalContentIdentity;+}): ContentBlockDiagnostic => {+ if (error instanceof MdxDocumentError && error.code === "unsafe-mdx") {+ return {+ code: "unsafe-mdx",+ severity: "error",+ blockInstanceId: identity.blockInstanceId,+ assetId: identity.assetId,+ contentRef: identity.contentRef,+ renderScope: identity.renderScope,+ nodeType: error.nodeType ?? "unknown",+ reason: error.reason ?? error.message,+ sourceRange: error.sourceRange,+ };+ }+ return {+ code: "invalid-mdx",+ severity: "error",+ blockInstanceId: identity.blockInstanceId,+ assetId: identity.assetId,+ contentRef: identity.contentRef,+ renderScope: identity.renderScope,+ message: error instanceof Error ? error.message : "Unable to parse MDX",+ sourceRange:+ error instanceof MdxDocumentError ? error.sourceRange : undefined,+ };+};++const createRecoverableState = ({+ error,+ identity,+}: {+ error: unknown;+ identity: ContentBlockExternalContentIdentity;+}) => ({+ status: "recoverable" as const,+ key: getContentStorageIdentityKey(identity),+ identity,+ diagnostics: [toParserDiagnostic({ error, identity })],+ error: error instanceof Error ? error : new Error("Unable to parse MDX"),+});++const getUnsavedState = (+ state: MdxAssetEditingSessionState | undefined+): UnsavedSessionBase | undefined => {+ if (+ state !== undefined &&+ "localSource" in state &&+ "writes" in state &&+ "root" in state+ ) {+ return state;+ }+};++export const createMdxAssetEditingSession = ({+ repository,+ authorizeAsset,+ resolveExpressionAssetId,+ schedule = (callback, delayMilliseconds) =>+ setTimeout(callback, delayMilliseconds),+ cancelScheduled = (handle) =>+ clearTimeout(handle as ReturnType<typeof setTimeout>),+ debounceMilliseconds = 300,+}: {+ repository: Pick<AssetContentRepository, "readContent"> &+ Partial<Pick<AssetContentRepository, "updateContent">>;+ authorizeAsset: MdxAssetSessionAuthorization;+ resolveExpressionAssetId?: (input: {+ expression: string;+ blockInstanceId: string;+ renderScope: string;+ variables?: Readonly<Record<string, unknown>>;+ }) => string | undefined | Promise<string | undefined>;+ schedule?: MdxAssetSessionSchedule;+ cancelScheduled?: (handle: unknown) => void;+ debounceMilliseconds?: number;+}) => {+ const states = new Map<string, MdxAssetEditingSessionState>();+ const queueEntries = new Map<string, MdxAssetSessionQueueEntry>();+ const keyAliases = new Map<string, string>();+ const openVersions = new Map<string, number>();++ const resolveKey = (key: string) => {+ let resolved = key;+ const visited = new Set<string>();+ while (keyAliases.has(resolved) && visited.has(resolved) === false) {+ visited.add(resolved);+ resolved = keyAliases.get(resolved)!;+ }+ return resolved;+ };++ const materializeSource = async ({+ identity,+ source,+ input,+ }: {+ identity: ContentBlockExternalContentIdentity;+ source: string;+ input: MdxAssetSessionOpenInput;+ }): Promise<LoadedSessionBase> => {+ const document = await parseMdxDocument({ source });+ const data = getRequiredComponentInsertData(input.state);+ const resolution = resolveMdxTemplates({+ document,+ identity,+ instances: data.instances,+ metas: componentMetas,+ });+ const templateMaterialization = await materializeMdxTemplates({+ identity,+ resolution,+ data,+ metas: componentMetas,+ projectId: input.projectId,+ });+ return {+ key: getContentStorageIdentityKey(identity),+ identity,+ source,+ root: materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization,+ }),+ diagnostics: templateMaterialization.diagnostics,+ };+ };++ const setQueueEntryKey = (+ entry: MdxAssetSessionQueueEntry,+ nextKey: string+ ) => {+ if (entry.key === nextKey) {+ return;+ }+ const previousKey = entry.key;+ queueEntries.delete(previousKey);+ states.delete(previousKey);+ entry.key = nextKey;+ queueEntries.set(nextKey, entry);+ keyAliases.set(previousKey, nextKey);+ };++ const findQueueEntry = ({+ blockInstanceId,+ assetId,+ renderScope,+ }: {+ blockInstanceId: string;+ assetId: string;+ renderScope: string;+ }) =>+ Array.from(queueEntries.values()).find(+ (entry) =>+ entry.input.blockInstanceId === blockInstanceId &&+ entry.assetId === assetId &&+ entry.input.renderScope === renderScope+ );++ const getOrCreateQueueEntry = ({+ key,+ input,+ assetId,+ }: {+ key: string;+ input: MdxAssetSessionOpenInput;+ assetId: string;+ }) => {+ const existing =+ queueEntries.get(resolveKey(key)) ??+ findQueueEntry({+ blockInstanceId: input.blockInstanceId,+ assetId,+ renderScope: input.renderScope,+ });+ if (existing !== undefined) {+ existing.input = input;+ existing.version += 1;+ setQueueEntryKey(existing, key);+ return existing;+ }+ const entry: MdxAssetSessionQueueEntry = {+ key,+ input,+ assetId,+ version: 0,+ cancelled: false,+ remoteStateUnknown: false,+ };+ queueEntries.set(key, entry);+ return entry;+ };++ const open = async (+ input: MdxAssetSessionOpenInput+ ): Promise<MdxAssetEditingSessionState> => {+ const openScopeKey = getContentBlockRenderScopeKey(+ input.blockInstanceId,+ input.renderScope+ );+ const openVersion = (openVersions.get(openScopeKey) ?? 0) + 1;+ openVersions.set(openScopeKey, openVersion);+ const isCurrentOpen = () => openVersions.get(openScopeKey) === openVersion;+ let assetId: string | undefined;+ try {+ assetId =+ input.source.type === "asset"+ ? input.source.assetId+ : await resolveExpressionAssetId?.({+ expression: input.source.value,+ blockInstanceId: input.blockInstanceId,+ renderScope: input.renderScope,+ variables: input.variables,+ });+ } catch (error) {+ return {+ status: "failed",+ blockInstanceId: input.blockInstanceId,+ renderScope: input.renderScope,+ diagnostics: [],+ error:+ error instanceof Error+ ? error+ : new Error("Content Block source resolution failed"),+ };+ }+ if (assetId === undefined || assetId.length === 0) {+ return {+ status: "failed",+ blockInstanceId: input.blockInstanceId,+ renderScope: input.renderScope,+ diagnostics: [],+ error: new Error("Content Block source did not resolve to an Asset"),+ };+ }+ const activeEntry = findQueueEntry({+ blockInstanceId: input.blockInstanceId,+ assetId,+ renderScope: input.renderScope,+ });+ if (activeEntry?.cancelled && activeEntry.inFlight !== undefined) {+ await activeEntry.inFlight;+ }+ const unsaved = Array.from(states.values()).find((state) => {+ const candidate = getUnsavedState(state);+ return (+ candidate !== undefined &&+ candidate.identity.blockInstanceId === input.blockInstanceId &&+ candidate.identity.assetId === assetId &&+ candidate.identity.renderScope === input.renderScope+ );+ });+ if (unsaved !== undefined) {+ return unsaved;+ }+ let readAuthorized = false;+ try {+ readAuthorized =+ (await authorizeAsset({ assetId, operation: "read" })) === true;+ } catch (error) {+ return {+ status: "failed",+ blockInstanceId: input.blockInstanceId,+ renderScope: input.renderScope,+ diagnostics: [],+ error:+ error instanceof Error+ ? error+ : new Error("MDX Asset read authorization failed"),+ };+ }+ if (readAuthorized === false) {+ return {+ status: "failed",+ blockInstanceId: input.blockInstanceId,+ renderScope: input.renderScope,+ diagnostics: [+ {+ code: "authorization-failed",+ severity: "error",+ blockInstanceId: input.blockInstanceId,+ assetId,+ renderScope: input.renderScope,+ operation: "read",+ },+ ],+ error: new Error("MDX Asset is not authorized for reading"),+ };+ }++ let read: Awaited<ReturnType<AssetContentRepository["readContent"]>>;+ let bytes: Uint8Array;+ try {+ read = await repository.readContent({ assetId });+ bytes = await readBoundedBytes(+ read.data,+ contentEngineLimits.hydratedFileBytes+ );+ } catch (error) {+ return {+ status: "failed",+ blockInstanceId: input.blockInstanceId,+ renderScope: input.renderScope,+ diagnostics: [],+ error: error instanceof Error ? error : new Error("Asset read failed"),+ };+ }+ if (+ read.asset.projectId !== input.projectId ||+ bytes.byteLength !== read.asset.size+ ) {+ return {+ status: "failed",+ blockInstanceId: input.blockInstanceId,+ renderScope: input.renderScope,+ diagnostics: [],+ error: new Error("Asset content identity does not match its bytes"),+ };+ }+ const contentHash = await getAssetContentHash(new Uint8Array(bytes).buffer);+ const revisionInput = {+ storageName: read.asset.name,+ updatedAt: read.asset.updatedAt ?? read.asset.createdAt,+ size: read.asset.size,+ };+ const contentRevision = createAssetContentRevision({+ ...revisionInput,+ contentHash,+ });+ const legacyRevision = createAssetContentRevision(revisionInput);+ const revision =+ input.expectedRevision === legacyRevision+ ? legacyRevision+ : contentRevision;+ const identity: ContentBlockExternalContentIdentity = {+ blockInstanceId: input.blockInstanceId,+ assetId: read.asset.id,+ revision,+ contentRef: read.asset.name,+ format: "mdx",+ renderScope: input.renderScope,+ };+ const key = getContentStorageIdentityKey(identity);+ if (read.asset.id !== assetId) {+ const conflicting = {+ status: "conflicting" as const,+ key,+ identity,+ diagnostics: [+ {+ code: "changed-binding" as const,+ severity: "error" as const,+ blockInstanceId: input.blockInstanceId,+ assetId,+ contentRef: identity.contentRef,+ renderScope: input.renderScope,+ loadedAssetId: read.asset.id,+ resolvedAssetId: assetId,+ },+ ],+ };+ if (isCurrentOpen()) {+ states.set(key, conflicting);+ }+ return conflicting;+ }+ if (+ read.asset.type !== "file" ||+ getAssetDisplayNameParts(read.asset).ext.toLowerCase() !== "mdx"+ ) {+ return {+ status: "failed",+ blockInstanceId: input.blockInstanceId,+ renderScope: input.renderScope,+ diagnostics: [],+ error: new Error("Content Block source Asset must be an MDX file"),+ };+ }+ if (+ input.expectedRevision !== undefined &&+ input.expectedRevision !== contentRevision &&+ input.expectedRevision !== legacyRevision+ ) {+ const conflicting = {+ status: "conflicting" as const,+ key,+ identity,+ diagnostics: [+ {+ code: "stale-revision" as const,+ severity: "error" as const,+ blockInstanceId: input.blockInstanceId,+ assetId,+ contentRef: identity.contentRef,+ renderScope: input.renderScope,+ expectedRevision: input.expectedRevision,+ actualRevision: revision,+ },+ ],+ };+ if (isCurrentOpen()) {+ states.set(key, conflicting);+ }+ return conflicting;+ }+ const existing = states.get(key);+ if (existing?.status === "pending") {+ return existing;+ }++ let source: string;+ try {+ source = decodeUtf8(bytes);+ } catch (error) {+ const recoverable = createRecoverableState({ error, identity });+ if (isCurrentOpen()) {+ states.set(key, recoverable);+ getOrCreateQueueEntry({ key, input, assetId });+ }+ return recoverable;+ }+ try {+ const loaded = await materializeSource({ identity, source, input });+ const saved = {+ ...loaded,+ status: "saved" as const,+ };+ if (isCurrentOpen() === false) {+ return saved;+ }+ states.set(key, saved);+ const entry = getOrCreateQueueEntry({ key, input, assetId });+ entry.persisted = loaded;+ entry.unsavedSource = undefined;+ entry.cancelled = false;+ entry.remoteStateUnknown = false;+ return saved;+ } catch (error) {+ if (error instanceof MdxDocumentError) {+ const recoverable = createRecoverableState({ error, identity });+ if (isCurrentOpen()) {+ states.set(key, recoverable);+ getOrCreateQueueEntry({ key, input, assetId });+ }+ return recoverable;+ }+ const failed = {+ status: "failed" as const,+ blockInstanceId: input.blockInstanceId,+ renderScope: input.renderScope,+ diagnostics: [] as const,+ error:+ error instanceof Error+ ? error+ : new Error("MDX materialization failed"),+ };+ return failed;+ }+ };++ const prepareSave = async ({+ key,+ changes,+ }: {+ key: string;+ changes: readonly ContentStorageChange[];+ }): Promise<MdxAssetEditingSessionState> => {+ const resolvedKey = resolveKey(key);+ const current = states.get(resolvedKey);+ const entry = queueEntries.get(resolvedKey);+ if (+ current === undefined ||+ entry === undefined ||+ (current.status !== "saved" &&+ current.status !== "pending" &&+ !(current.status === "failed" && "root" in current))+ ) {+ throw new Error("MDX Asset editing session is not ready to save");+ }+ try {+ const writes = await prepareMdxContentStorageWrites({+ loadedRoots: [current.root],+ changes,+ authorizeAssetWrite: async (identity) =>+ identity.assetId === current.identity.assetId &&+ getContentStorageIdentityKey(identity) === current.key &&+ (await authorizeAsset({+ assetId: current.identity.assetId,+ operation: "write",+ identity: current.identity,+ })),+ });+ if (writes.length === 0) {+ return current;+ }+ if (writes.length !== 1) {+ throw new Error("An MDX Asset session must prepare exactly one write");+ }+ const localSource = writes[0].source;+ const loaded = await materializeSource({+ identity: current.identity,+ source: localSource,+ input: entry.input,+ });+ const pending = {+ ...loaded,+ status: "pending" as const,+ writes,+ localSource,+ };+ entry.version += 1;+ entry.unsavedSource = localSource;+ entry.cancelled = false;+ states.set(resolvedKey, pending);+ return pending;+ } catch (error) {+ const failed = {+ status: "failed" as const,+ blockInstanceId: current.identity.blockInstanceId,+ renderScope: current.identity.renderScope,+ diagnostics: [] as const,+ error:+ error instanceof Error+ ? error+ : new Error("Unable to prepare MDX Asset save"),+ };+ return failed;+ }+ };++ const preflightSave = async ({+ key,+ changes,+ }: {+ key: string;+ changes: readonly ContentStorageChange[];+ }): Promise<+ | Readonly<{ status: "ready" }>+ | Readonly<{ status: "blocked"; reason: string }>+ > => {+ const current = states.get(resolveKey(key));+ if (+ current === undefined ||+ (current.status !== "saved" &&+ current.status !== "pending" &&+ !(current.status === "failed" && "root" in current))+ ) {+ return {+ status: "blocked",+ reason: "MDX Asset editing session is not ready to save",+ };+ }+ try {+ await prepareMdxContentStorageWrites({+ loadedRoots: [current.root],+ changes,+ authorizeAssetWrite: async (identity) =>+ identity.assetId === current.identity.assetId &&+ getContentStorageIdentityKey(identity) === current.key &&+ (await authorizeAsset({+ assetId: current.identity.assetId,+ operation: "write",+ identity: current.identity,+ })),+ });+ return { status: "ready" };+ } catch (error) {+ return {+ status: "blocked",+ reason:+ error instanceof Error+ ? error.message+ : "Unable to prepare MDX Asset save",+ };+ }+ };++ const flushOne = async (+ key: string+ ): Promise<MdxAssetEditingSessionState> => {+ const resolvedKey = resolveKey(key);+ const entry = queueEntries.get(resolvedKey);+ const initial = states.get(resolvedKey);+ if (entry === undefined || initial === undefined) {+ throw new Error("MDX Asset editing session does not exist");+ }+ if (entry.timer !== undefined) {+ cancelScheduled(entry.timer);+ entry.timer = undefined;+ }+ if (entry.inFlight !== undefined) {+ await entry.inFlight;+ return flushOne(entry.key);+ }+ const unsaved = getUnsavedState(initial);+ if (unsaved === undefined) {+ return initial;+ }+ const updateContent = repository.updateContent;+ if (updateContent === undefined) {+ const failed = {+ ...unsaved,+ status: "failed" as const,+ error: new Error("MDX Asset repository does not support writes"),+ };+ states.set(resolvedKey, failed);+ return failed;+ }+ if (unsaved.writes.length !== 1) {+ throw new Error("An MDX Asset session must flush exactly one write");+ }+ const write = unsaved.writes[0];+ if (+ write.expectedRevision !== unsaved.identity.revision ||+ getContentStorageIdentityKey(write.root.identity) !== unsaved.key+ ) {+ throw new Error(+ "Pending MDX Asset write identity does not match session"+ );+ }++ const flushVersion = entry.version;+ const flushKey = entry.key;+ const operation = (async (): Promise<MdxAssetEditingSessionState> => {+ let storageCommitted = false;+ let committed:+ | Readonly<{+ identity: ContentBlockExternalContentIdentity;+ source: string;+ }>+ | undefined;+ try {+ const writeAuthorized = await authorizeAsset({+ assetId: unsaved.identity.assetId,+ operation: "write",+ identity: unsaved.identity,+ });+ if (writeAuthorized !== true) {+ throw new Error("MDX Asset is not authorized for writing");+ }+ if (entry.cancelled) {+ return states.get(entry.key) ?? initial;+ }+ const bytes = new TextEncoder().encode(unsaved.localSource);+ const asset = await updateContent({+ assetId: unsaved.identity.assetId,+ expectedName: unsaved.identity.contentRef,+ data: new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(bytes);+ controller.close();+ },+ }),+ });+ storageCommitted = true;+ if (entry.cancelled) {+ return states.get(entry.key) ?? initial;+ }+ if (+ asset.id !== unsaved.identity.assetId ||+ asset.projectId !== entry.input.projectId ||+ asset.type !== "file" ||+ asset.name.length === 0 ||+ asset.name === unsaved.identity.contentRef ||+ getAssetDisplayNameParts(asset).ext.toLowerCase() !== "mdx" ||+ asset.size !== bytes.byteLength+ ) {+ throw new AssetRevisionConflictError(+ "Asset repository returned a stale MDX revision"+ );+ }++ const contentHash = await getAssetContentHash(+ new Uint8Array(bytes).buffer+ );+ const identity: ContentBlockExternalContentIdentity = {+ ...unsaved.identity,+ revision: createAssetContentRevision({+ storageName: asset.name,+ updatedAt: asset.updatedAt ?? asset.createdAt,+ size: asset.size,+ contentHash,+ }),+ contentRef: asset.name,+ };+ committed = { identity, source: unsaved.localSource };+ const persisted = await materializeSource({+ identity,+ source: unsaved.localSource,+ input: entry.input,+ });+ entry.persisted = persisted;+ const latest = getUnsavedState(states.get(entry.key));+ const hasNewerChanges =+ entry.version !== flushVersion && latest !== undefined;+ const localSource = hasNewerChanges+ ? latest.localSource+ : unsaved.localSource;+ const loaded = hasNewerChanges+ ? await materializeSource({+ identity,+ source: localSource,+ input: entry.input,+ })+ : persisted;+ setQueueEntryKey(entry, loaded.key);+ if (hasNewerChanges) {+ const pending = {+ ...loaded,+ status: "pending" as const,+ localSource,+ writes: [+ {+ root: { type: "external" as const, identity },+ expectedRevision: identity.revision,+ source: localSource,+ },+ ],+ };+ states.set(entry.key, pending);+ return pending;+ }+ entry.unsavedSource = undefined;+ const saved = { ...loaded, status: "saved" as const };+ states.set(entry.key, saved);+ return saved;+ } catch (error) {+ if (entry.cancelled) {+ return states.get(entry.key) ?? initial;+ }+ if (committed !== undefined) {+ entry.persisted = undefined;+ entry.unsavedSource = undefined;+ entry.remoteStateUnknown = false;+ const recoverable = {+ ...createRecoverableState({+ error,+ identity: committed.identity,+ }),+ committedSource: committed.source,+ };+ setQueueEntryKey(entry, recoverable.key);+ states.set(entry.key, recoverable);+ return recoverable;+ }+ const latest = getUnsavedState(states.get(entry.key)) ?? unsaved;+ const writeError =+ error instanceof Error ? error : new Error("MDX Asset write failed");+ const failed: MdxAssetEditingSessionState =+ storageCommitted || writeError instanceof AssetRevisionConflictError+ ? { ...latest, status: "conflicting", error: writeError }+ : { ...latest, status: "failed", error: writeError };+ states.set(entry.key, failed);+ return failed;+ }+ })();+ entry.inFlight = operation;+ const result = await operation;+ entry.inFlight = undefined;+ if (+ result.status === "pending" &&+ entry.cancelled === false &&+ entry.version !== flushVersion+ ) {+ return flushOne(entry.key);+ }+ if (flushKey !== entry.key) {+ keyAliases.set(flushKey, entry.key);+ }+ return result;+ };++ const scheduleEntry = (entry: MdxAssetSessionQueueEntry) => {+ if (entry.timer !== undefined) {+ cancelScheduled(entry.timer);+ }+ entry.timer = schedule(() => {+ entry.timer = undefined;+ void flushOne(entry.key);+ }, debounceMilliseconds);+ };++ const queueSave = async ({+ key,+ changes,+ }: {+ key: string;+ changes: readonly ContentStorageChange[];+ }) => {+ const state = await prepareSave({ key, changes });+ if (state.status !== "pending") {+ return state;+ }+ const entry = queueEntries.get(resolveKey(key));+ if (entry === undefined) {+ throw new Error("MDX Asset editing session does not exist");+ }+ scheduleEntry(entry);+ return state;+ };++ const flush = (key: string) => flushOne(key);++ const retry = (key: string) => flushOne(key);++ const reloadRemote = async (key: string) => {+ const resolvedKey = resolveKey(key);+ const entry = queueEntries.get(resolvedKey);+ if (entry === undefined) {+ throw new Error("MDX Asset editing session does not exist");+ }+ if (entry.inFlight !== undefined) {+ throw new Error(+ "Cannot reload an MDX Asset while its write is in flight"+ );+ }+ if (entry.timer !== undefined) {+ cancelScheduled(entry.timer);+ entry.timer = undefined;+ }+ const unsavedSource = entry.unsavedSource;+ states.delete(resolvedKey);+ const state = await open({+ ...entry.input,+ source: { type: "asset", assetId: entry.assetId },+ expectedRevision: undefined,+ });+ const migrated = queueEntries.get(resolveKey(entry.key)) ?? entry;+ migrated.unsavedSource = unsavedSource;+ return state;+ };++ const copyUnsavedSource = (key: string) =>+ queueEntries.get(resolveKey(key))?.unsavedSource;++ const canReplaceSource = ({+ key,+ expectedSource,+ }: {+ key: string;+ expectedSource: string;+ }): MdxAssetSourceReplacementPreflight => {+ const resolvedKey = resolveKey(key);+ const entry = queueEntries.get(resolvedKey);+ const state = states.get(resolvedKey);+ if (entry === undefined || state === undefined) {+ throw new Error("MDX Asset editing session does not exist");+ }+ const currentSource =+ getUnsavedState(state)?.localSource ??+ (state.status === "saved"+ ? state.source+ : state.status === "recoverable" && state.committedSource !== undefined+ ? state.committedSource+ : (entry.unsavedSource ?? entry.persisted?.source));+ if (entry.inFlight !== undefined) {+ return { status: "blocked", state, reason: "in-flight", currentSource };+ }+ if (entry.remoteStateUnknown) {+ return {+ status: "blocked",+ state,+ reason: "unresolved-write",+ currentSource,+ };+ }+ if (+ state.status === "failed" ||+ state.status === "conflicting" ||+ (state.status === "recoverable" && state.committedSource === undefined)+ ) {+ return {+ status: "blocked",+ state,+ reason: "unresolved-write",+ currentSource,+ };+ }+ if (currentSource !== expectedSource) {+ return {+ status: "blocked",+ state,+ reason: "source-mismatch",+ currentSource,+ };+ }+ return { status: "ready", currentSource };+ };++ const prepareSourceReplacement = async ({+ key,+ expectedSource,+ source,+ }: {+ key: string;+ expectedSource: string;+ source: string;+ }): Promise<MdxAssetPreparedSourceReplacement> => {+ const preflight = canReplaceSource({ key, expectedSource });+ if (preflight.status === "blocked") {+ return preflight;+ }+ const resolvedKey = resolveKey(key);+ const entry = queueEntries.get(resolvedKey)!;+ const current = states.get(resolvedKey)!;+ const preparedVersion = entry.version;+ const preparedIdentityKey =+ "identity" in current+ ? getContentStorageIdentityKey(current.identity)+ : undefined;+ const canApply = () => {+ const latest = canReplaceSource({ key, expectedSource });+ if (latest.status === "blocked") {+ return latest;+ }+ const latestState = states.get(resolveKey(key))!;+ const latestIdentityKey =+ "identity" in latestState+ ? getContentStorageIdentityKey(latestState.identity)+ : undefined;+ if (latestIdentityKey !== preparedIdentityKey) {+ return {+ status: "blocked" as const,+ state: latestState,+ reason: "identity-mismatch" as const,+ currentSource: latest.currentSource,+ };+ }+ if (entry.version !== preparedVersion) {+ return {+ status: "blocked" as const,+ state: states.get(resolveKey(key))!,+ reason: "source-mismatch" as const,+ currentSource: latest.currentSource,+ };+ }+ return latest;+ };+ const assertCanApply = () => {+ if (canApply().status === "blocked") {+ throw new Error("Prepared MDX Asset source replacement is stale");+ }+ };+ if (source === preflight.currentSource) {+ return {+ status: "ready",+ canApply,+ apply: () => {+ assertCanApply();+ return { status: "applied", state: current };+ },+ };+ }+ if (source === entry.persisted?.source) {+ const persisted = entry.persisted;+ return {+ status: "ready",+ canApply,+ apply: () => {+ assertCanApply();+ if (entry.timer !== undefined) {+ cancelScheduled(entry.timer);+ entry.timer = undefined;+ }+ entry.unsavedSource = undefined;+ entry.cancelled = false;+ entry.version += 1;+ const saved = { ...persisted, status: "saved" as const };+ states.set(resolveKey(key), saved);+ return { status: "applied", state: saved };+ },+ };+ }+ const identity =+ "identity" in current ? current.identity : entry.persisted?.identity;+ if (identity === undefined) {+ return {+ status: "blocked",+ state: current,+ reason: "unresolved-write",+ currentSource: preflight.currentSource,+ };+ }+ let writeAuthorized = false;+ try {+ writeAuthorized =+ (await authorizeAsset({+ assetId: identity.assetId,+ operation: "write",+ identity,+ })) === true;+ } catch {+ // Authorization failures are stable preflight blockers. They must not+ // advance the session or expose transport-specific errors to lifecycle callers.+ }+ if (writeAuthorized === false) {+ return {+ status: "blocked",+ state: current,+ reason: "unauthorized",+ currentSource: preflight.currentSource,+ };+ }+ const loaded = await materializeSource({+ identity,+ source,+ input: entry.input,+ });+ return {+ status: "ready",+ canApply,+ apply: ({ schedule: shouldSchedule = true } = {}) => {+ assertCanApply();+ if (entry.timer !== undefined) {+ cancelScheduled(entry.timer);+ entry.timer = undefined;+ }+ const pending = {+ ...loaded,+ status: "pending" as const,+ localSource: source,+ writes: [+ {+ root: { type: "external" as const, identity },+ expectedRevision: identity.revision,+ source,+ },+ ],+ };+ entry.version += 1;+ entry.unsavedSource = source;+ entry.cancelled = false;+ states.set(resolveKey(key), pending);+ if (shouldSchedule) {+ scheduleEntry(entry);+ }+ return { status: "applied", state: pending };+ },+ };+ };++ const replaceSource = async (input: {+ key: string;+ expectedSource: string;+ source: string;+ }): Promise<MdxAssetSourceReplacementResult> => {+ const prepared = await prepareSourceReplacement(input);+ if (prepared.status === "blocked") {+ return prepared;+ }+ const preflight = prepared.canApply();+ return preflight.status === "ready" ? prepared.apply() : preflight;+ };++ const persistSourceReplacement = async (input: {+ key: string;+ expectedSource: string;+ source: string;+ isCurrent?: () => boolean;+ }): Promise<MdxAssetSourceReplacementResult> => {+ const current = states.get(resolveKey(input.key));+ if (+ current?.status === "recoverable" &&+ current.committedSource === input.source+ ) {+ return input.isCurrent?.() === false+ ? {+ status: "blocked",+ state: current,+ reason: "source-mismatch",+ currentSource: current.committedSource,+ }+ : { status: "applied", state: current };+ }+ if (+ current !== undefined &&+ (current.status === "failed" || current.status === "pending") &&+ "localSource" in current &&+ current.localSource === input.source+ ) {+ if (input.isCurrent?.() === false) {+ return {+ status: "blocked",+ state: current,+ reason: "source-mismatch",+ currentSource: current.localSource,+ };+ }+ const persisted = await flushOne(input.key);+ return isContentBlockSessionSourceCommitted({+ state: persisted,+ source: input.source,+ })+ ? { status: "applied", state: persisted }+ : {+ status: "blocked",+ state: persisted,+ reason: "unresolved-write",+ currentSource: getContentBlockSessionSource(persisted),+ };+ }+ const prepared = await prepareSourceReplacement(input);+ if (prepared.status === "blocked") {+ return prepared;+ }+ const preflight = prepared.canApply();+ if (preflight.status === "blocked") {+ return preflight;+ }+ if (input.isCurrent?.() === false) {+ return {+ status: "blocked",+ state: states.get(resolveKey(input.key))!,+ reason: "source-mismatch",+ currentSource: preflight.currentSource,+ };+ }+ const applied = prepared.apply({ schedule: false });+ if (applied.state.status !== "pending") {+ return applied;+ }+ const persisted = await flushOne(applied.state.key);+ return isContentBlockSessionSourceCommitted({+ state: persisted,+ source: input.source,+ })+ ? { status: "applied", state: persisted }+ : {+ status: "blocked",+ state: persisted,+ reason: "unresolved-write",+ currentSource: getContentBlockSessionSource(persisted),+ };+ };++ const cancel = (key: string): MdxAssetEditingSessionState => {+ const resolvedKey = resolveKey(key);+ const current = states.get(resolvedKey);+ const entry = queueEntries.get(resolvedKey);+ if (current === undefined || entry === undefined || !("key" in current)) {+ throw new Error("MDX Asset editing session does not exist");+ }+ if (entry.timer !== undefined) {+ cancelScheduled(entry.timer);+ entry.timer = undefined;+ }+ entry.cancelled = true;+ entry.remoteStateUnknown =+ entry.inFlight !== undefined || current.status === "conflicting";+ entry.version += 1;+ const cancelled = {+ status: "cancelled" as const,+ key: current.key,+ identity: current.identity,+ diagnostics: current.diagnostics,+ };+ states.set(resolvedKey, cancelled);+ return cancelled;+ };++ return {+ open,+ prepareSave,+ preflightSave,+ queueSave,+ flush,+ retry,+ reloadRemote,+ copyUnsavedSource,+ canReplaceSource,+ prepareSourceReplacement,+ persistSourceReplacement,+ replaceSource,+ cancel,+ get: (key: string) => states.get(resolveKey(key)),+ list: () => Array.from(states.values()),+ };+};diff --git a/packages/project-build/src/runtime/mdx-authored-content.test.ts b/packages/project-build/src/runtime/mdx-authored-content.test.tsnew file mode 100644index 0000000000..6ec1c91926--- /dev/null+++ b/packages/project-build/src/runtime/mdx-authored-content.test.ts@@ -0,0 +1,539 @@+import { describe, expect, test } from "vitest";+import {+ discoverMdxBodyAssetReferences,+ parseMdxDocument,+ serializeMdxDocument,+} from "@webstudio-is/content-engine/mdx";+import {+ elementComponent,+ type ContentBlockExternalContentIdentity,+ type WebstudioFragment,+} from "@webstudio-is/sdk";+import {+ materializeMdxAuthoredContent,+ reconcileMdxAuthoredContent,+} from "./mdx-authored-content";++const identity: ContentBlockExternalContentIdentity = {+ blockInstanceId: "block",+ assetId: "article",+ revision: "sha256:article",+ contentRef: "posts/article.mdx",+ format: "mdx",+ renderScope: "page:/article",+};++const emptyTemplates = {+ templates: [],+ diagnostics: [],+ dependencies: { templateNames: [], templates: [] },+} as const;++describe("MDX authored content", () => {+ test("materializes deterministic nested Markdown and MDX elements", async () => {+ const document = await parseMdxDocument({+ source: `# Heading\n\n<ws.element ws:tag="section" data-kind="intro"><ws.element ws:tag="strong">Body</ws.element></ws.element>`,+ });+ const first = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const second = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const otherScope = materializeMdxAuthoredContent({+ identity: { ...identity, renderScope: "page:/other" },+ document,+ templateMaterialization: emptyTemplates,+ });+ const otherRevision = materializeMdxAuthoredContent({+ identity: { ...identity, revision: "sha256:next" },+ document,+ templateMaterialization: emptyTemplates,+ });++ expect(second.fragment).toEqual(first.fragment);+ expect(otherScope.fragment.instances[0].id).not.toBe(+ first.fragment.instances[0].id+ );+ expect(otherRevision.fragment.instances[0].id).not.toBe(+ first.fragment.instances[0].id+ );+ expect(+ first.fragment.instances.map(({ component, tag }) => [component, tag])+ ).toEqual([+ [elementComponent, "h1"],+ [elementComponent, "strong"],+ [elementComponent, "section"],+ ]);+ });++ test("reconciles text, props, insertion, deletion, and reorder semantically", async () => {+ const document = await parseMdxDocument({+ source: `---\ntitle: Example\n---\n\n{/* before */}\n\n# First\n\n<ws.element ws:tag="p" class="lead">Second</ws.element>`,+ });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const [headingId, paragraphId] = root.fragment.children.flatMap((child) =>+ child.type === "id" ? [child.value] : []+ );+ const next = structuredClone(root.fragment);+ next.children = [+ { type: "id", value: paragraphId },+ { type: "id", value: "inserted" },+ ];+ next.instances = [+ ...next.instances.filter(({ id }) => id !== headingId),+ {+ type: "instance",+ id: "inserted",+ component: elementComponent,+ tag: "aside",+ children: [{ type: "text", value: "New" }],+ },+ ];+ const paragraph = next.instances.find(({ id }) => id === paragraphId)!;+ paragraph.children = [{ type: "text", value: "Changed" }];+ const paragraphProp = next.props.find(+ ({ instanceId, name }) => instanceId === paragraphId && name === "class"+ )!;+ paragraphProp.value = "summary";+ const nextBeforeReconcile = structuredClone(next);+ const documentBeforeReconcile = structuredClone(document);++ const reconciled = reconcileMdxAuthoredContent({ root, fragment: next });+ expect(next).toEqual(nextBeforeReconcile);+ expect(document).toEqual(documentBeforeReconcile);+ expect(reconcileMdxAuthoredContent({ root, fragment: next })).toEqual(+ reconciled+ );+ const reparsed = await parseMdxDocument({+ source: serializeMdxDocument(reconciled),+ });++ expect(reparsed.frontmatter.properties).toEqual({ title: "Example" });+ expect(reparsed.children.map((node) => node.type)).toEqual([+ "comment",+ "element",+ "element",+ ]);+ expect(reparsed.children[1]).toMatchObject({+ type: "element",+ tag: "p",+ props: [{ name: "class", value: "summary" }],+ children: [{ type: "text", value: "Changed" }],+ });+ expect(reparsed.children[2]).toMatchObject({+ type: "element",+ syntax: "mdx",+ tag: "aside",+ children: [{ type: "text", value: "New" }],+ });+ });++ test("round-trips Markdown lists, tables, code whitespace, links, and marks", async () => {+ const document = await parseMdxDocument({+ source: `- First\n- Second with **bold** and [guide](./guide.pdf)\n\n| Name | Value |\n| --- | ---: |\n| Alpha | 1 |\n\n\`\`\`js\n const value = 1;\n\`\`\``,+ });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const next = structuredClone(root.fragment);+ const code = next.instances.find(({ tag }) => tag === "code");+ if (code === undefined) {+ throw new Error("Expected code instance");+ }+ code.children = [{ type: "text", value: " const value = 2;\n" }];++ const reconciled = reconcileMdxAuthoredContent({ root, fragment: next });+ const serialized = serializeMdxDocument(reconciled);+ const reparsed = await parseMdxDocument({ source: serialized });+ const rematerialized = materializeMdxAuthoredContent({+ identity,+ document: reparsed,+ templateMaterialization: emptyTemplates,+ });++ expect(rematerialized.fragment.instances.map(({ tag }) => tag)).toEqual(+ root.fragment.instances.map(({ tag }) => tag)+ );+ expect(+ rematerialized.fragment.instances.find(({ tag }) => tag === "code")+ ?.children+ ).toEqual([{ type: "text", value: " const value = 2;\n" }]);+ expect(serialized).toContain("**bold**");+ });++ test("synthesizes nested block and inline JSX with stable modes", async () => {+ const document = await parseMdxDocument({+ source: `<ws.element ws:tag="section"><ws.element ws:tag="p">Before</ws.element></ws.element>`,+ });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const next = structuredClone(root.fragment);+ const section = next.instances.find(({ tag }) => tag === "section")!;+ section.children.push({ type: "id", value: "aside" });+ next.instances.push(+ {+ type: "instance",+ id: "aside",+ component: elementComponent,+ tag: "aside",+ children: [{ type: "id", value: "inserted-paragraph" }],+ },+ {+ type: "instance",+ id: "inserted-paragraph",+ component: elementComponent,+ tag: "p",+ children: [{ type: "id", value: "strong" }],+ },+ {+ type: "instance",+ id: "strong",+ component: elementComponent,+ tag: "strong",+ children: [{ type: "text", value: "Nested" }],+ }+ );++ const serialized = serializeMdxDocument(+ reconcileMdxAuthoredContent({ root, fragment: next })+ );+ const reparsed = await parseMdxDocument({ source: serialized });+ const rematerialized = materializeMdxAuthoredContent({+ identity,+ document: reparsed,+ templateMaterialization: emptyTemplates,+ });++ expect(rematerialized.fragment.instances.map(({ tag }) => tag)).toEqual([+ "p",+ "strong",+ "p",+ "aside",+ "section",+ ]);+ const reparsedSection = reparsed.children[0];+ expect(+ reparsedSection.type === "element"+ ? reparsedSection.children.find(+ (node) => node.type === "element" && node.tag === "aside"+ )+ : undefined+ ).toMatchObject({ type: "element", syntax: "mdx", mdxMode: "flow" });+ expect(serializeMdxDocument(reparsed)).toBe(serialized);+ });++ test("preserves unresolved templates, comments, and ignored authored props", async () => {+ const document = await parseMdxDocument({+ source: `{/* note */}\n\n<ws.element ws:name="Missing" obsolete="yes">Keep me</ws.element>\n\nParagraph`,+ });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: {+ ...emptyTemplates,+ templates: [+ {+ type: "unresolved-template",+ reference: {+ type: "unresolved-template",+ path: [1],+ templateName: "Missing",+ },+ markerId: "missing",+ },+ ],+ },+ });+ const next = structuredClone(root.fragment);+ next.instances[0].children = [{ type: "text", value: "Changed" }];++ expect(root.provenance.unresolvedTemplates).toEqual([+ {+ path: [1],+ markerId: "missing",+ templateName: "Missing",+ },+ ]);++ const reconciled = reconcileMdxAuthoredContent({ root, fragment: next });++ expect(reconciled.children).toMatchObject([+ { type: "comment", value: "/* note */" },+ {+ type: "template",+ name: "Missing",+ props: [{ name: "obsolete", value: "yes" }],+ children: [{ type: "text", value: "Keep me" }],+ },+ {+ type: "element",+ children: [{ type: "text", value: "Changed" }],+ },+ ]);+ });++ test("keeps an inline comment anchored when adjacent text is deleted", async () => {+ const document = await parseMdxDocument({+ source: `<ws.element ws:tag="p">Before{/* note */}After</ws.element>`,+ });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const next = structuredClone(root.fragment);+ next.instances[0].children = [{ type: "text", value: "After" }];++ const reconciled = reconcileMdxAuthoredContent({ root, fragment: next });+ const paragraph = reconciled.children[0];+ expect(+ paragraph.type === "element" ? paragraph.children : []+ ).toMatchObject([+ { type: "comment", value: "/* note */" },+ { type: "text", value: "After" },+ ]);+ });++ test("rejects changes to unsupported authored namespaces", async () => {+ const document = await parseMdxDocument({ source: "Paragraph" });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const next = structuredClone(root.fragment);+ next.styles.push({+ breakpointId: "base",+ styleSourceId: "local",+ property: "color",+ value: { type: "keyword", value: "red" },+ });++ expect(() => reconcileMdxAuthoredContent({ root, fragment: next })).toThrow(+ "cannot be represented losslessly in MDX"+ );+ });++ test("rejects duplicate props and reused instances instead of losing them", async () => {+ const document = await parseMdxDocument({+ source: `<ws.element ws:tag="p" class="first">Text</ws.element>`,+ });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ });+ const duplicateProp = structuredClone(root.fragment);+ const originalProp = duplicateProp.props[0];+ if (originalProp?.type !== "string") {+ throw new Error("Expected string prop");+ }+ duplicateProp.props.push({+ ...originalProp,+ id: "duplicate-prop",+ value: "second",+ });+ expect(() =>+ reconcileMdxAuthoredContent({ root, fragment: duplicateProp })+ ).toThrow('Duplicate authored prop "class"');++ const reusedInstance = structuredClone(root.fragment);+ reusedInstance.children.push(reusedInstance.children[0]);+ expect(() =>+ reconcileMdxAuthoredContent({ root, fragment: reusedInstance })+ ).toThrow("is reused");+ });++ test("preserves authored Asset references while changing content", async () => {+ const document = await parseMdxDocument({+ source: `<ws.element ws:tag="figure"><ws.element ws:tag="img" src="./hero.png" /><ws.element ws:tag="a" href="../files/guide.pdf">Read</ws.element></ws.element>`,+ });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: emptyTemplates,+ assetReferences: discoverMdxBodyAssetReferences({+ document,+ sourcePath: "posts/article.mdx",+ assetIdsByPath: new Map([+ ["posts/hero.png", "hero-asset"],+ ["files/guide.pdf", "guide-asset"],+ ]),+ }),+ });+ expect(root.fragment.props.map(({ type, value }) => [type, value])).toEqual(+ [+ ["asset", "hero-asset"],+ ["asset", "guide-asset"],+ ]+ );+ const next = structuredClone(root.fragment);+ next.instances.find(({ tag }) => tag === "a")!.children = [+ { type: "text", value: "Download" },+ ];++ const source = serializeMdxDocument(+ reconcileMdxAuthoredContent({ root, fragment: next })+ );+ expect(source).toContain('src="./hero.png"');+ expect(source).toContain('href="../files/guide.pdf"');+ expect(source).toContain("Download");++ const changedAsset = next.props.find(({ name }) => name === "src");+ if (changedAsset?.type !== "asset") {+ throw new Error("Expected Asset prop");+ }+ changedAsset.value = "other-asset";+ expect(() => reconcileMdxAuthoredContent({ root, fragment: next })).toThrow(+ 'Asset prop "src" cannot be represented losslessly in MDX'+ );+ });++ test("updates template shell props without serializing expanded internals", async () => {+ const document = await parseMdxDocument({+ source: `<ws.element ws:name="Card" tone="quiet" legacy="authored" />`,+ });+ const templateFragment: WebstudioFragment = {+ children: [{ type: "id", value: "template-root" }],+ instances: [+ {+ type: "instance",+ id: "template-root",+ component: elementComponent,+ tag: "article",+ children: [{ type: "id", value: "template-heading" }],+ },+ {+ type: "instance",+ id: "template-heading",+ component: elementComponent,+ tag: "h2",+ children: [{ type: "text", value: "Template heading" }],+ },+ ],+ props: [+ {+ id: "tone",+ instanceId: "template-root",+ name: "tone",+ type: "string",+ value: "quiet",+ },+ {+ id: "legacy",+ instanceId: "template-root",+ name: "legacy",+ type: "string",+ value: "template default",+ },+ ],+ assets: [],+ dataSources: [],+ resources: [],+ breakpoints: [{ id: "base", label: "Base" }],+ styleSourceSelections: [+ { instanceId: "template-root", values: ["template-local"] },+ ],+ styleSources: [{ type: "local", id: "template-local" }],+ styles: [+ {+ breakpointId: "base",+ styleSourceId: "template-local",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ };+ const authoredTemplate = document.children[0];+ if (authoredTemplate?.type !== "template") {+ throw new Error("Expected authored template");+ }+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: {+ templates: [+ {+ type: "resolved-template",+ reference: {+ type: "resolved-template",+ path: [0],+ templateName: "Card",+ templateInstanceId: "card-template",+ props: authoredTemplate.props,+ },+ fragment: templateFragment,+ },+ ],+ diagnostics: [+ {+ code: "ignored-template-prop",+ severity: "warning",+ blockInstanceId: "block",+ assetId: "article",+ contentRef: "posts/article.mdx",+ renderScope: "page:/article",+ templateName: "Card",+ propName: "legacy",+ reason: "stale",+ },+ ],+ dependencies: { templateNames: ["Card"], templates: [] },+ },+ });+ const next = structuredClone(root.fragment);+ const tone = next.props.find(({ id }) => id === "tone");+ if (tone?.type !== "string") {+ throw new Error("Expected tone prop");+ }+ tone.value = "loud";++ expect(+ reconcileMdxAuthoredContent({ root, fragment: next }).children[0]+ ).toMatchObject({+ type: "template",+ name: "Card",+ props: [+ { name: "tone", value: "loud" },+ { name: "legacy", value: "authored" },+ ],+ });++ next.instances.find(({ id }) => id === "template-heading")!.children = [+ { type: "text", value: "Changed internal" },+ ];+ expect(() => reconcileMdxAuthoredContent({ root, fragment: next })).toThrow(+ "Expanded template internals"+ );++ expect(+ reconcileMdxAuthoredContent({+ root,+ fragment: {+ ...root.fragment,+ children: [],+ instances: [],+ props: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ },+ }).children+ ).toEqual([]);+ });+});diff --git a/packages/project-build/src/runtime/mdx-authored-content.ts b/packages/project-build/src/runtime/mdx-authored-content.tsnew file mode 100644index 0000000000..f0c184e271--- /dev/null+++ b/packages/project-build/src/runtime/mdx-authored-content.ts@@ -0,0 +1,873 @@+import equal from "fast-deep-equal";+import { elementsByTag } from "@webstudio-is/html-data";+import type { AssetValueReference } from "@webstudio-is/content-engine";+import type {+ MdxAuthoredNode,+ MdxAuthoredProp,+ MdxDocument,+ MdxMode,+} from "@webstudio-is/content-engine/mdx";+import {+ elementComponent,+ getStyleDeclKey,+ type ContentBlockExternalContentIdentity,+ type Instance,+ type Prop,+ type WebstudioFragment,+} from "@webstudio-is/sdk";+import {+ createMdxScopeIdGenerator,+ type MaterializedMdxTemplate,+ type MdxTemplateMaterialization,+} from "./mdx-materialization";+import type { MaterializedContentRoot } from "./content-storage";+import { createEmptyWebstudioFragment } from "./component-template";++type AuthoredElementProvenance = Readonly<{+ type: "element";+ path: readonly number[];+ instanceId: Instance["id"];+ assetProps: readonly Readonly<{+ propId: Prop["id"];+ assetId: string;+ authoredValue: string;+ }>[];+}>;++type TemplateProvenance = Readonly<{+ type: "template";+ path: readonly number[];+ instanceId: Instance["id"];+ editablePropNames: readonly string[];+ expandedInstanceIds: readonly Instance["id"][];+ namespaceKeys: readonly Readonly<{+ namespace: UnsupportedNamespace;+ key: string;+ }>[];+}>;++type UnsupportedNamespace = (typeof unsupportedNamespaces)[number];++const unsupportedNamespaces = [+ "assets",+ "dataSources",+ "resources",+ "breakpoints",+ "styleSourceSelections",+ "styleSources",+ "styles",+] as const;++const getNamespaceRecordKey = (+ namespace: UnsupportedNamespace,+ record: WebstudioFragment[UnsupportedNamespace][number]+) => {+ if (namespace === "styleSourceSelections") {+ return (record as WebstudioFragment["styleSourceSelections"][number])+ .instanceId;+ }+ if (namespace === "styles") {+ return getStyleDeclKey(record as WebstudioFragment["styles"][number]);+ }+ return (record as { id: string }).id;+};++export type MdxAuthoredContentProvenance = Readonly<{+ nodes: readonly (AuthoredElementProvenance | TemplateProvenance)[];+ unresolvedTemplates: readonly Readonly<{+ path: readonly number[];+ markerId: string;+ templateName: string;+ }>[];+}>;++export type MaterializedMdxAuthoredContentRoot = MaterializedContentRoot &+ Readonly<{+ document: MdxDocument;+ provenance: MdxAuthoredContentProvenance;+ }>;++const pathKey = (path: readonly number[]) => path.join(".");++const mergeRecords = <Record extends { id: string }>(+ target: Record[],+ source: readonly Record[],+ namespace: string,+ allowEqual = false+) => {+ const records = new Map(target.map((record) => [record.id, record]));+ for (const record of source) {+ const existing = records.get(record.id);+ if (existing !== undefined && (!allowEqual || !equal(existing, record))) {+ throw new Error(+ `Materialized MDX ${namespace} id "${record.id}" collides`+ );+ }+ if (existing === undefined) {+ records.set(record.id, record);+ target.push(record);+ }+ }+};++const mergeTemplateFragment = (+ target: WebstudioFragment,+ source: WebstudioFragment+) => {+ mergeRecords(target.instances, source.instances, "instance");+ mergeRecords(target.props, source.props, "prop");+ mergeRecords(target.assets, source.assets, "asset", true);+ mergeRecords(target.dataSources, source.dataSources, "data source");+ mergeRecords(target.resources, source.resources, "resource");+ mergeRecords(target.breakpoints, source.breakpoints, "breakpoint", true);+ mergeRecords(target.styleSources, source.styleSources, "style source", true);+ const selectedInstanceIds = new Set(+ target.styleSourceSelections.map(({ instanceId }) => instanceId)+ );+ for (const selection of source.styleSourceSelections) {+ if (selectedInstanceIds.has(selection.instanceId)) {+ throw new Error(+ `Materialized MDX style selection id "${selection.instanceId}" collides`+ );+ }+ selectedInstanceIds.add(selection.instanceId);+ target.styleSourceSelections.push(selection);+ }+ const styles = new Map(+ target.styles.map((style) => [getStyleDeclKey(style), style])+ );+ for (const style of source.styles) {+ const key = getStyleDeclKey(style);+ const existing = styles.get(key);+ if (existing !== undefined && !equal(existing, style)) {+ throw new Error(`Materialized MDX style "${key}" collides`);+ }+ if (existing === undefined) {+ styles.set(key, style);+ target.styles.push(style);+ }+ }+};++const createLiteralProp = ({+ id,+ instanceId,+ prop,+ assetId,+}: {+ id: string;+ instanceId: string;+ prop: MdxAuthoredProp;+ assetId?: string;+}): Prop =>+ assetId !== undefined+ ? {+ id,+ instanceId,+ name: prop.name,+ type: "asset",+ value: assetId,+ }+ : prop.value === true+ ? {+ id,+ instanceId,+ name: prop.name,+ type: "boolean",+ value: true,+ }+ : {+ id,+ instanceId,+ name: prop.name,+ type: "string",+ value: prop.value,+ };++const getSingleTemplateRootId = (template: MaterializedMdxTemplate) => {+ if (+ template.type !== "resolved-template" ||+ template.fragment.children.length !== 1 ||+ template.fragment.children[0]?.type !== "id"+ ) {+ throw new Error("Resolved MDX template must materialize one root instance");+ }+ return template.fragment.children[0].value;+};++export const materializeMdxAuthoredContent = ({+ identity,+ document,+ templateMaterialization,+ assetReferences = [],+}: {+ identity: ContentBlockExternalContentIdentity;+ document: MdxDocument;+ templateMaterialization: MdxTemplateMaterialization;+ assetReferences?: readonly AssetValueReference[];+}): MaterializedMdxAuthoredContentRoot => {+ const fragment = createEmptyWebstudioFragment();+ const nodes: (AuthoredElementProvenance | TemplateProvenance)[] = [];+ const templatesByPath = new Map(+ templateMaterialization.templates.map((template) => [+ pathKey(template.reference.path),+ template,+ ])+ );+ const ignoredPropsByTemplateName = new Map<string, Set<string>>();+ const assetReferenceByPath = new Map(+ assetReferences.map((reference) => [+ reference.path.map(String).join("/"),+ reference,+ ])+ );+ for (const diagnostic of templateMaterialization.diagnostics) {+ if (diagnostic.code === "ignored-template-prop") {+ const props =+ ignoredPropsByTemplateName.get(diagnostic.templateName) ?? new Set();+ props.add(diagnostic.propName);+ ignoredPropsByTemplateName.set(diagnostic.templateName, props);+ }+ }++ const visit = (+ authoredNodes: readonly MdxAuthoredNode[],+ parentPath: readonly number[]+ ): Instance["children"] => {+ const children: Instance["children"] = [];+ for (const [index, node] of authoredNodes.entries()) {+ const path = [...parentPath, index];+ if (node.type === "text") {+ children.push({ type: "text", value: node.value });+ continue;+ }+ if (node.type === "comment") {+ continue;+ }+ if (node.type === "template") {+ const template = templatesByPath.get(pathKey(path));+ if (template === undefined || template.type === "unresolved-template") {+ continue;+ }+ const rootId = getSingleTemplateRootId(template);+ mergeTemplateFragment(fragment, template.fragment);+ const rootPropNames = new Set(+ template.fragment.props+ .filter(({ instanceId }) => instanceId === rootId)+ .map(({ name }) => name)+ );+ const ignored =+ ignoredPropsByTemplateName.get(node.name) ?? new Set<string>();+ nodes.push({+ type: "template",+ path,+ instanceId: rootId,+ editablePropNames: node.props+ .map(({ name }) => name)+ .filter((name) => rootPropNames.has(name) && !ignored.has(name)),+ expandedInstanceIds: template.fragment.instances.map(({ id }) => id),+ namespaceKeys: unsupportedNamespaces.flatMap((namespace) =>+ template.fragment[namespace].map((record) => ({+ namespace,+ key: getNamespaceRecordKey(namespace, record),+ }))+ ),+ });+ children.push({ type: "id", value: rootId });+ continue;+ }++ const createId = createMdxScopeIdGenerator({ identity, path });+ const instanceId = createId();+ const instance: Instance = {+ type: "instance",+ id: instanceId,+ component: elementComponent,+ tag: node.tag,+ children: visit(node.children, path),+ };+ fragment.instances.push(instance);+ const assetProps: AuthoredElementProvenance["assetProps"][number][] = [];+ node.props.forEach((prop, propIndex) => {+ const propId = createId();+ const assetReference = assetReferenceByPath.get(+ ["children", ...path.flatMap((segment) => [segment, "children"])]+ .slice(0, -1)+ .concat("props", propIndex, "value")+ .map(String)+ .join("/")+ );+ fragment.props.push(+ createLiteralProp({+ id: propId,+ instanceId,+ prop,+ assetId: assetReference?.assetId,+ })+ );+ if (assetReference !== undefined && typeof prop.value === "string") {+ assetProps.push({+ propId,+ assetId: assetReference.assetId,+ authoredValue: prop.value,+ });+ }+ });+ nodes.push({ type: "element", path, instanceId, assetProps });+ children.push({ type: "id", value: instanceId });+ }+ return children;+ };++ fragment.children = visit(document.children, []);+ const unresolvedTemplates = templateMaterialization.templates.flatMap(+ (template) =>+ template.type === "unresolved-template"+ ? [+ {+ path: template.reference.path,+ markerId: template.markerId,+ templateName: template.reference.templateName,+ },+ ]+ : []+ );+ return {+ identity,+ fragment,+ document,+ provenance: { nodes, unresolvedTemplates },+ };+};++const assertSupportedNamespaces = ({+ root,+ fragment,+ deletedTemplateRootIds,+}: {+ root: MaterializedMdxAuthoredContentRoot;+ fragment: WebstudioFragment;+ deletedTemplateRootIds: ReadonlySet<string>;+}) => {+ for (const namespace of unsupportedNamespaces) {+ const removableKeys = new Set<string>();+ const requiredKeys = new Set<string>();+ for (const node of root.provenance.nodes) {+ if (node.type !== "template") {+ continue;+ }+ const keys = node.namespaceKeys.flatMap((entry) =>+ entry.namespace === namespace ? [entry.key] : []+ );+ const target = deletedTemplateRootIds.has(node.instanceId)+ ? removableKeys+ : requiredKeys;+ for (const key of keys) {+ target.add(key);+ }+ }+ for (const key of requiredKeys) {+ removableKeys.delete(key);+ }+ const originalByKey = new Map(+ root.fragment[namespace].map((record) => [+ getNamespaceRecordKey(namespace, record),+ record,+ ])+ );+ const nextKeys = fragment[namespace].map((record) => {+ const key = getNamespaceRecordKey(namespace, record);+ if (!equal(originalByKey.get(key), record)) {+ throw new Error(+ `Changes to ${namespace} cannot be represented losslessly in MDX`+ );+ }+ return key;+ });+ const nextKeySet = new Set(nextKeys);+ if (+ nextKeys.length !== nextKeySet.size ||+ Array.from(originalByKey.keys()).some(+ (key) => !nextKeySet.has(key) && !removableKeys.has(key)+ ) ||+ !equal(+ nextKeys,+ Array.from(originalByKey.keys()).filter((key) => nextKeySet.has(key))+ )+ ) {+ throw new Error(+ `Changes to ${namespace} cannot be represented losslessly in MDX`+ );+ }+ }+};++const toAuthoredProps = ({+ original,+ props,+ assetProps = [],+}: {+ original: readonly MdxAuthoredProp[];+ props: readonly Prop[];+ assetProps?: AuthoredElementProvenance["assetProps"];+}) => {+ const values = new Map<string, string | true>();+ const assetPropsById = new Map(assetProps.map((prop) => [prop.propId, prop]));+ for (const prop of props) {+ if (values.has(prop.name)) {+ throw new Error(+ `Duplicate authored prop "${prop.name}" is not supported`+ );+ }+ if (prop.type === "string") {+ values.set(prop.name, prop.value);+ } else if (prop.type === "boolean" && prop.value === true) {+ values.set(prop.name, true);+ } else if (prop.type === "asset") {+ const assetProp = assetPropsById.get(prop.id);+ if (assetProp?.assetId === prop.value) {+ values.set(prop.name, assetProp.authoredValue);+ continue;+ }+ throw new Error(+ `Asset prop "${prop.name}" cannot be represented losslessly in MDX`+ );+ } else {+ throw new Error(+ `Prop "${prop.name}" cannot be represented losslessly in MDX`+ );+ }+ }+ const result: MdxAuthoredProp[] = [];+ for (const prop of original) {+ const value = values.get(prop.name);+ if (value !== undefined) {+ result.push({ name: prop.name, value });+ values.delete(prop.name);+ }+ }+ for (const [name, value] of values) {+ result.push({ name, value });+ }+ return result;+};++export const reconcileMdxAuthoredContent = ({+ root,+ fragment,+}: {+ root: MaterializedMdxAuthoredContentRoot;+ fragment: WebstudioFragment;+}): MdxDocument => {+ const deletedTemplateRootIds = new Set(+ root.provenance.nodes.flatMap((node) =>+ node.type === "template" &&+ fragment.instances.some(({ id }) => id === node.instanceId) === false+ ? [node.instanceId]+ : []+ )+ );+ assertSupportedNamespaces({ root, fragment, deletedTemplateRootIds });+ for (const [namespace, records] of [+ ["instance", fragment.instances],+ ["prop", fragment.props],+ ] as const) {+ const ids = new Set<string>();+ for (const { id } of records) {+ if (ids.has(id)) {+ throw new Error(`Duplicate authored ${namespace} id "${id}"`);+ }+ ids.add(id);+ }+ }+ const instanceById = new Map(+ fragment.instances.map((instance) => [instance.id, instance])+ );+ const originalInstanceById = new Map(+ root.fragment.instances.map((instance) => [instance.id, instance])+ );+ const propsByInstanceId = new Map<string, Prop[]>();+ for (const prop of fragment.props) {+ const props = propsByInstanceId.get(prop.instanceId) ?? [];+ props.push(prop);+ propsByInstanceId.set(prop.instanceId, props);+ }+ const provenanceById = new Map(+ root.provenance.nodes.map((node) => [node.instanceId, node])+ );+ const provenanceByPath = new Map(+ root.provenance.nodes.map((node) => [pathKey(node.path), node])+ );+ const originalNodeByPath = new Map<string, MdxAuthoredNode>();+ const originalPathByNode = new Map<MdxAuthoredNode, string>();+ const indexOriginal = (+ nodes: readonly MdxAuthoredNode[],+ parentPath: readonly number[]+ ) => {+ nodes.forEach((node, index) => {+ const path = [...parentPath, index];+ originalNodeByPath.set(pathKey(path), node);+ originalPathByNode.set(node, pathKey(path));+ if (node.type !== "text" && node.type !== "comment") {+ indexOriginal(node.children, path);+ }+ });+ };+ indexOriginal(root.document.children, []);++ const templateByExpandedInstanceId = new Map(+ root.provenance.nodes.flatMap((node) =>+ node.type === "template"+ ? node.expandedInstanceIds.map((id) => [id, node] as const)+ : []+ )+ );+ const templateInternalIds = new Set(templateByExpandedInstanceId.keys());+ const editableTemplatePropIds = new Set<string>();+ for (const node of root.provenance.nodes) {+ if (node.type !== "template") {+ continue;+ }+ if (instanceById.has(node.instanceId) === false) {+ const expandedIds = new Set(node.expandedInstanceIds);+ if (+ fragment.instances.some(({ id }) => expandedIds.has(id)) ||+ fragment.props.some(({ instanceId }) => expandedIds.has(instanceId))+ ) {+ throw new Error(+ "A partially deleted template cannot be represented losslessly in MDX"+ );+ }+ continue;+ }+ for (const prop of root.fragment.props) {+ if (+ prop.instanceId === node.instanceId &&+ node.editablePropNames.includes(prop.name)+ ) {+ editableTemplatePropIds.add(prop.id);+ }+ }+ }+ for (const original of root.fragment.instances) {+ const template = templateByExpandedInstanceId.get(original.id);+ if (+ templateInternalIds.has(original.id) &&+ (template?.type !== "template" ||+ deletedTemplateRootIds.has(template.instanceId) === false)+ ) {+ const next = instanceById.get(original.id);+ if (next === undefined || !equal(next, original)) {+ throw new Error(+ "Expanded template internals cannot be represented losslessly in MDX"+ );+ }+ }+ }+ const originalPropsById = new Map(+ root.fragment.props.map((prop) => [prop.id, prop])+ );+ const templateByRootId = new Map(+ root.provenance.nodes.flatMap((node) =>+ node.type === "template" ? [[node.instanceId, node] as const] : []+ )+ );+ for (const prop of fragment.props) {+ const original = originalPropsById.get(prop.id);+ if (+ original !== undefined &&+ templateInternalIds.has(original.instanceId) &&+ !editableTemplatePropIds.has(prop.id) &&+ !equal(prop, original)+ ) {+ throw new Error(+ "Expanded template props cannot be represented losslessly in MDX"+ );+ }+ const template = templateByRootId.get(prop.instanceId);+ if (+ template !== undefined &&+ template.editablePropNames.includes(prop.name) === false &&+ (original === undefined || !equal(original, prop))+ ) {+ throw new Error(+ "Expanded template props cannot be represented losslessly in MDX"+ );+ }+ }+ for (const original of root.fragment.props) {+ if (+ templateInternalIds.has(original.instanceId) &&+ deletedTemplateRootIds.has(+ templateByExpandedInstanceId.get(original.instanceId)?.instanceId ?? ""+ ) === false &&+ !editableTemplatePropIds.has(original.id) &&+ fragment.props.some(({ id }) => id === original.id) === false+ ) {+ throw new Error(+ "Expanded template props cannot be represented losslessly in MDX"+ );+ }+ }+ const serializedInstanceIds = new Set<string>();+ const usesPhrasingContent = (tag: string) =>+ elementsByTag[tag]?.categories.includes("phrasing") === true;+ const getInsertedNodeMode = (children: Instance["children"]): MdxMode =>+ children.every(+ (child) =>+ child.type === "text" ||+ (child.type === "id" &&+ instanceById.get(child.value)?.tag !== undefined &&+ usesPhrasingContent(instanceById.get(child.value)?.tag ?? ""))+ )+ ? "text"+ : "flow";+ const getChildrenMode = ({+ original,+ tag,+ }: {+ original: MdxAuthoredNode | undefined;+ tag: string;+ }): MdxMode => {+ if (original?.type === "element" && original.syntax === "mdx") {+ return original.mdxMode;+ }+ return elementsByTag[tag]?.children.includes("phrasing") === true+ ? "text"+ : "flow";+ };++ const toNode = (+ instanceId: string,+ mode: MdxMode,+ active: Set<string>+ ): MdxAuthoredNode => {+ if (active.has(instanceId)) {+ throw new Error("Cyclic authored MDX instance tree");+ }+ const instance = instanceById.get(instanceId);+ if (instance === undefined) {+ throw new Error(`Authored MDX instance "${instanceId}" is missing`);+ }+ const provenance = provenanceById.get(instanceId);+ if (provenance?.type === "template") {+ if (serializedInstanceIds.has(instanceId)) {+ throw new Error(`Authored MDX instance "${instanceId}" is reused`);+ }+ for (const expandedId of provenance.expandedInstanceIds) {+ serializedInstanceIds.add(expandedId);+ }+ const original = originalNodeByPath.get(pathKey(provenance.path));+ if (original?.type !== "template") {+ throw new Error("Authored MDX template provenance is invalid");+ }+ const editableProps = (propsByInstanceId.get(instanceId) ?? []).filter(+ ({ name }) => provenance.editablePropNames.includes(name)+ );+ if (+ new Set(editableProps.map(({ name }) => name)).size !==+ editableProps.length+ ) {+ throw new Error("Duplicate authored template props are not supported");+ }+ const editableNames = new Set(provenance.editablePropNames);+ const nextEditable = toAuthoredProps({+ original: original.props.filter(({ name }) => editableNames.has(name)),+ props: editableProps,+ });+ const nextByName = new Map(nextEditable.map((prop) => [prop.name, prop]));+ const props = original.props.flatMap((prop) => {+ if (editableNames.has(prop.name) === false) {+ return [prop];+ }+ const next = nextByName.get(prop.name);+ nextByName.delete(prop.name);+ return next === undefined ? [] : [next];+ });+ props.push(...nextByName.values());+ return mode === "text"+ ? { ...original, props, mdxMode: "text" }+ : { ...original, props };+ }+ if (instance.component !== elementComponent || instance.tag === undefined) {+ throw new Error(+ `Instance "${instanceId}" cannot be represented losslessly in MDX`+ );+ }+ if (serializedInstanceIds.has(instanceId)) {+ throw new Error(`Authored MDX instance "${instanceId}" is reused`);+ }+ serializedInstanceIds.add(instanceId);+ const original =+ provenance?.type === "element"+ ? originalNodeByPath.get(pathKey(provenance.path))+ : undefined;+ if (+ original !== undefined &&+ (original.type === "text" ||+ original.type === "comment" ||+ original.type === "template")+ ) {+ throw new Error("Authored MDX element provenance is invalid");+ }+ if (original !== undefined) {+ const originalInstance = originalInstanceById.get(instanceId);+ if (+ originalInstance?.component !== instance.component ||+ originalInstance.tag !== instance.tag ||+ originalInstance.label !== instance.label+ ) {+ throw new Error(+ "Element metadata cannot be represented losslessly in MDX"+ );+ }+ }+ active.add(instanceId);+ const children = reconcileChildren({+ original: original?.children ?? [],+ children: instance.children,+ mode: getChildrenMode({ original, tag: instance.tag }),+ active,+ });+ active.delete(instanceId);+ const props = toAuthoredProps({+ original: original?.props ?? [],+ props: propsByInstanceId.get(instanceId) ?? [],+ assetProps:+ provenance?.type === "element" ? provenance.assetProps : undefined,+ });+ if (original !== undefined) {+ if (original.syntax === "mdx") {+ const contentMode = getInsertedNodeMode(instance.children);+ if (contentMode === "flow" && mode === "text") {+ throw new Error(+ "Block content cannot be represented inside inline MDX"+ );+ }+ return {+ ...original,+ props,+ children,+ mdxMode:+ original.mdxMode === "flow" && mode === "flow"+ ? "flow"+ : contentMode,+ };+ }+ return { ...original, props, children };+ }+ const element = {+ type: "element",+ syntax: "mdx",+ tag: instance.tag,+ props,+ children,+ mdxMode: getInsertedNodeMode(instance.children),+ } as const;+ return element;+ };++ const reconcileChildren = ({+ original,+ children,+ mode,+ active,+ }: {+ original: readonly MdxAuthoredNode[];+ children: Instance["children"];+ mode: MdxMode;+ active: Set<string>;+ }): MdxAuthoredNode[] => {+ const textPaths = original+ .map((node, index) => ({ node, key: `text:${index}` }))+ .filter(({ node }) => node.type === "text");+ const unusedTextPaths = [...textPaths];+ const rendered = children.map((child) => {+ if (child.type === "expression") {+ throw new Error(+ "Expression text cannot be represented losslessly in MDX"+ );+ }+ if (child.type === "text") {+ const exactIndex = unusedTextPaths.findIndex(+ ({ node }) => node.type === "text" && node.value === child.value+ );+ const [entry] = unusedTextPaths.splice(+ exactIndex === -1 ? 0 : exactIndex,+ 1+ );+ const node: MdxAuthoredNode =+ entry?.node.type === "text"+ ? { ...entry.node, value: child.value }+ : { type: "text", value: child.value };+ return { key: entry?.key, node };+ }+ const provenance = provenanceById.get(child.value);+ return {+ key:+ provenance === undefined+ ? undefined+ : `node:${pathKey(provenance.path)}`,+ node: toNode(child.value, mode, active),+ };+ });+ const surviving = new Set(+ rendered.flatMap(({ key }) => (key ? [key] : []))+ );+ const anchorsByKey = new Map<string, MdxAuthoredNode[]>();+ const tail: MdxAuthoredNode[] = [];+ let pending: MdxAuthoredNode[] = [];+ for (const [index, node] of original.entries()) {+ const originalPath = originalPathByNode.get(node);+ const provenance =+ originalPath === undefined+ ? undefined+ : provenanceByPath.get(originalPath);+ const key =+ node.type === "text"+ ? `text:${index}`+ : provenance === undefined+ ? undefined+ : `node:${pathKey(provenance.path)}`;+ if (key !== undefined && surviving.has(key)) {+ anchorsByKey.set(key, pending);+ pending = [];+ } else if (key === undefined) {+ pending.push(node);+ }+ }+ tail.push(...pending);+ return [+ ...rendered.flatMap(({ key, node }) => [+ ...(key === undefined ? [] : (anchorsByKey.get(key) ?? [])),+ node,+ ]),+ ...tail,+ ];+ };++ const children = reconcileChildren({+ original: root.document.children,+ children: fragment.children,+ mode: "flow",+ active: new Set(),+ });+ if (+ fragment.instances.some(({ id }) => serializedInstanceIds.has(id) === false)+ ) {+ throw new Error(+ "Unreachable instances cannot be represented losslessly in MDX"+ );+ }+ if (+ fragment.props.some(+ ({ instanceId }) => serializedInstanceIds.has(instanceId) === false+ )+ ) {+ throw new Error("Orphan props cannot be represented losslessly in MDX");+ }+ return {+ ...root.document,+ children,+ };+};diff --git a/packages/project-build/src/runtime/mdx-materialization.test.ts b/packages/project-build/src/runtime/mdx-materialization.test.tsnew file mode 100644index 0000000000..858d05e6da--- /dev/null+++ b/packages/project-build/src/runtime/mdx-materialization.test.ts@@ -0,0 +1,565 @@+import { describe, expect, test } from "vitest";+import {+ parseMdxDocument,+ serializeMdxDocument,+} from "@webstudio-is/content-engine/mdx";+import {+ blockComponent,+ blockTemplateComponent,+ encodeDataVariableId,+ type Asset,+ type ContentBlockExternalContentIdentity,+ type Instance,+ type Prop,+ type WebstudioData,+ type WsComponentMeta,+} from "@webstudio-is/sdk";+import {+ materializeMdxTemplates,+ type MaterializedMdxTemplate,+} from "./mdx-materialization";+import {+ resolveMdxTemplates,+ type MdxTemplateResolution,+} from "./mdx-template-resolution";++const identity: ContentBlockExternalContentIdentity = {+ blockInstanceId: "block",+ assetId: "article",+ revision: "revision-1",+ contentRef: "articles/hello.mdx",+ format: "mdx",+ renderScope: "route:/hello",+};++const resolution: MdxTemplateResolution = {+ templateNames: ["Hero Card"],+ references: [+ {+ type: "resolved-template",+ path: [0],+ templateName: "Hero Card",+ props: [],+ templateInstanceId: "hero",+ },+ {+ type: "unresolved-template",+ path: [1],+ templateName: "Missing",+ },+ ],+ diagnostics: [+ {+ code: "unresolved-template",+ severity: "warning",+ blockInstanceId: "block",+ assetId: "article",+ contentRef: "articles/hello.mdx",+ renderScope: "route:/hello",+ templateName: "Missing",+ },+ ],+};++const metas = new Map<string, WsComponentMeta>([+ [+ "Card",+ {+ props: {+ tone: {+ type: "string",+ control: "text",+ required: false,+ contentMode: true,+ },+ featured: {+ type: "boolean",+ control: "boolean",+ required: false,+ contentMode: true,+ },+ title: {+ type: "string",+ control: "text",+ required: false,+ contentMode: true,+ },+ count: {+ type: "number",+ control: "number",+ required: false,+ contentMode: true,+ },+ layout: {+ type: "string",+ control: "text",+ required: false,+ },+ },+ },+ ],+]);++const createData = (): Omit<WebstudioData, "pages"> => {+ const hero: Instance = {+ type: "instance",+ id: "hero",+ component: "Card",+ children: [{ type: "id", value: "heading" }],+ };+ const heading: Instance = {+ type: "instance",+ id: "heading",+ component: "ws:element",+ tag: "h2",+ children: [{ type: "text", value: "Template title" }],+ };+ const prop: Prop = {+ id: "hero:tone",+ instanceId: "hero",+ name: "tone",+ type: "string",+ value: "strong",+ };+ const duplicateToneProp: Prop = {+ ...prop,+ id: "hero:tone-duplicate",+ value: "duplicate",+ };+ const imageProp: Prop = {+ id: "hero:image",+ instanceId: "hero",+ name: "image",+ type: "asset",+ value: "image",+ };+ const expressionProp: Prop = {+ id: "hero:title",+ instanceId: "hero",+ name: "title",+ type: "expression",+ value: encodeDataVariableId("site-title"),+ };+ const countProp: Prop = {+ id: "hero:count",+ instanceId: "hero",+ name: "count",+ type: "number",+ value: 1,+ };+ const layoutProp: Prop = {+ id: "hero:layout",+ instanceId: "hero",+ name: "layout",+ type: "string",+ value: "contained",+ };+ const legacyProp: Prop = {+ id: "hero:legacy",+ instanceId: "hero",+ name: "legacy",+ type: "string",+ value: "Template legacy",+ };+ const asset: Asset = {+ id: "image",+ projectId: "source-project",+ name: "hero.png",+ type: "image",+ format: "png",+ size: 100,+ meta: { width: 10, height: 10 },+ createdAt: "2026-01-01T00:00:00.000Z",+ };+ return {+ instances: new Map([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: "templates" }],+ },+ ],+ [+ "templates",+ {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [{ type: "id", value: hero.id }],+ },+ ],+ [hero.id, hero],+ [heading.id, heading],+ ]),+ props: new Map<Prop["id"], Prop>([+ [prop.id, prop],+ [duplicateToneProp.id, duplicateToneProp],+ [imageProp.id, imageProp],+ [expressionProp.id, expressionProp],+ [countProp.id, countProp],+ [layoutProp.id, layoutProp],+ [legacyProp.id, legacyProp],+ ]),+ dataSources: new Map([+ [+ "site-title",+ {+ type: "variable",+ id: "site-title",+ name: "Site Title",+ value: { type: "string", value: "Webstudio" },+ },+ ],+ ]),+ resources: new Map(),+ styleSources: new Map([+ ["token", { type: "token", id: "token", name: "Card" }],+ ["hero-local", { type: "local", id: "hero-local" }],+ ]),+ styleSourceSelections: new Map([+ ["hero", { instanceId: "hero", values: ["token", "hero-local"] }],+ ]),+ styles: new Map([+ [+ "hero-local:base:color:",+ {+ styleSourceId: "hero-local",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ [+ "token:base:display:",+ {+ styleSourceId: "token",+ breakpointId: "base",+ property: "display",+ value: { type: "keyword", value: "block" },+ },+ ],+ ]),+ breakpoints: new Map([["base", { id: "base", label: "" }]]),+ assets: new Map([[asset.id, asset]]),+ };+};++const getResolvedTemplate = (+ templates: readonly MaterializedMdxTemplate[]+): Extract<MaterializedMdxTemplate, { type: "resolved-template" }> => {+ for (const template of templates) {+ if (template.type === "resolved-template") {+ return template;+ }+ }+ throw new Error("Expected a resolved template");+};++const getUnresolvedTemplate = (+ templates: readonly MaterializedMdxTemplate[]+): Extract<MaterializedMdxTemplate, { type: "unresolved-template" }> => {+ for (const template of templates) {+ if (template.type === "unresolved-template") {+ return template;+ }+ }+ throw new Error("Expected an unresolved template");+};++describe("materializeMdxTemplates", () => {+ test("copies resolved fragments and represents unresolved usages", async () => {+ const data = createData();+ const originalData = structuredClone(data);+ const materialization = await materializeMdxTemplates({+ identity,+ resolution,+ data,+ metas,+ projectId: "target-project",+ });+ const materializedTemplates = materialization.templates;+ const materialized = getResolvedTemplate(materializedTemplates);++ expect(materializedTemplates).toHaveLength(2);+ expect(materialized.reference.templateName).toBe("Hero Card");+ expect(materialized.fragment.children).toEqual([+ { type: "id", value: expect.stringMatching(/^mdx-/) },+ ]);+ expect(materialized.fragment.instances).toEqual([+ expect.objectContaining({+ component: "Card",+ children: [{ type: "id", value: expect.stringMatching(/^mdx-/) }],+ }),+ expect.objectContaining({+ component: "ws:element",+ tag: "h2",+ children: [{ type: "text", value: "Template title" }],+ }),+ ]);+ expect(materialized.fragment.props).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ name: "tone", value: "strong" }),+ expect.objectContaining({+ name: "image",+ type: "asset",+ value: "image",+ }),+ expect.objectContaining({+ name: "title",+ type: "expression",+ value: encodeDataVariableId("site-title"),+ }),+ ])+ );+ expect(materialized.fragment.styleSources).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ type: "token", name: "Card" }),+ expect.objectContaining({ type: "local" }),+ ])+ );+ expect(materialized.fragment.styles).toHaveLength(2);+ expect(materialized.fragment.assets).toEqual([+ expect.objectContaining({ id: "image", projectId: "target-project" }),+ ]);+ expect(data).toEqual(originalData);+ expect(materializedTemplates[1]).toEqual(+ expect.objectContaining({+ type: "unresolved-template",+ markerId: expect.stringMatching(/^mdx-/),+ reference: expect.objectContaining({+ type: "unresolved-template",+ templateName: "Missing",+ }),+ })+ );+ expect(materialization.diagnostics).toEqual([+ expect.objectContaining({+ code: "unresolved-template",+ templateName: "Missing",+ }),+ ]);+ });++ test("rejects a resolved reference when its template was removed", async () => {+ const data = createData();+ data.instances.delete("hero");++ await expect(+ materializeMdxTemplates({+ identity,+ resolution,+ data,+ metas,+ projectId: "target-project",+ })+ ).rejects.toThrow('Resolved MDX template instance "hero" is missing');+ });++ test("generates stable IDs scoped by revision, render scope, and usage path", async () => {+ const materialize = (+ nextIdentity: ContentBlockExternalContentIdentity,+ nextResolution: MdxTemplateResolution = resolution+ ) =>+ materializeMdxTemplates({+ identity: nextIdentity,+ resolution: nextResolution,+ data: createData(),+ metas,+ projectId: "target-project",+ });+ const materializeRootId = async (+ nextIdentity: ContentBlockExternalContentIdentity,+ nextResolution: MdxTemplateResolution = resolution+ ) =>+ getResolvedTemplate(+ (await materialize(nextIdentity, nextResolution)).templates+ ).fragment.children[0];+ const materializeMarkerId = async (+ nextIdentity: ContentBlockExternalContentIdentity+ ) =>+ getUnresolvedTemplate((await materialize(nextIdentity)).templates)+ .markerId;++ const first = await materializeRootId(identity);+ expect(await materializeRootId(identity)).toEqual(first);+ expect(+ await materializeRootId({ ...identity, revision: "revision-2" })+ ).not.toEqual(first);+ expect(+ await materializeRootId({ ...identity, renderScope: "route:/other" })+ ).not.toEqual(first);+ const markerId = await materializeMarkerId(identity);+ expect(await materializeMarkerId(identity)).toBe(markerId);+ expect(+ await materializeMarkerId({ ...identity, revision: "revision-2" })+ ).not.toBe(markerId);+ expect(+ await materializeMarkerId({ ...identity, renderScope: "route:/other" })+ ).not.toBe(markerId);+ expect(+ await materializeRootId(identity, {+ references: [+ {+ type: "resolved-template",+ path: [2],+ templateName: "Hero Card",+ props: [],+ templateInstanceId: "hero",+ },+ ],+ diagnostics: [],+ templateNames: ["Hero Card"],+ })+ ).not.toEqual(first);+ });++ test("applies valid props and preserves ignored authored props", async () => {+ const source = `<ws.element ws:name="Card" tone="quiet" featured title="Authored title" count="2" layout="wide" legacy="Authored legacy" missing="preserved" />`;+ const document = await parseMdxDocument({ source });+ const authoredDocument = structuredClone(document);+ const data = createData();+ const originalData = structuredClone(data);+ const materialization = await materializeMdxTemplates({+ identity,+ resolution: resolveMdxTemplates({+ document,+ identity,+ instances: data.instances,+ metas,+ }),+ data,+ metas,+ projectId: "target-project",+ });+ const materialized = getResolvedTemplate(materialization.templates);++ expect(materialized.fragment.props).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ name: "tone", value: "quiet" }),+ expect.objectContaining({ name: "featured", value: true }),+ expect.objectContaining({+ name: "title",+ type: "string",+ value: "Authored title",+ }),+ expect.objectContaining({ name: "count", type: "number", value: 1 }),+ expect.objectContaining({ name: "layout", value: "contained" }),+ expect.objectContaining({ name: "legacy", value: "Template legacy" }),+ ])+ );+ expect(materialized.fragment.dataSources).toEqual([]);+ expect(+ materialized.fragment.props.filter((prop) => prop.name === "tone")+ ).toEqual([expect.objectContaining({ type: "string", value: "quiet" })]);+ expect(+ materialized.fragment.props.find((prop) => prop.name === "missing")+ ).toBeUndefined();+ expect(document).toEqual(authoredDocument);+ expect(data).toEqual(originalData);+ expect(+ (await parseMdxDocument({ source: serializeMdxDocument(document) }))+ .children[0]+ ).toMatchObject({+ type: "template",+ props: [+ { name: "tone", value: "quiet" },+ { name: "featured", value: true },+ { name: "title", value: "Authored title" },+ { name: "count", value: "2" },+ { name: "layout", value: "wide" },+ { name: "legacy", value: "Authored legacy" },+ { name: "missing", value: "preserved" },+ ],+ });+ expect(materialization.diagnostics).toEqual([+ expect.objectContaining({+ code: "ignored-template-prop",+ propName: "count",+ reason: "incompatible",+ }),+ expect.objectContaining({+ code: "ignored-template-prop",+ propName: "layout",+ reason: "design-only",+ }),+ expect.objectContaining({+ code: "ignored-template-prop",+ propName: "legacy",+ reason: "stale",+ }),+ expect.objectContaining({+ code: "ignored-template-prop",+ propName: "missing",+ reason: "unknown",+ }),+ ]);+ });++ test("tracks effective names and deduplicated template revisions", async () => {+ const data = createData();+ const originalData = structuredClone(data);+ const materialize = (sourceData = data) =>+ materializeMdxTemplates({+ identity,+ resolution: {+ ...resolution,+ references: [+ resolution.references[0],+ {+ type: "resolved-template",+ path: [2],+ templateName: "Hero Card",+ templateInstanceId: "hero",+ props: [],+ },+ ],+ diagnostics: [],+ },+ data: sourceData,+ metas,+ projectId: "target-project",+ });++ const firstMaterialization = await materialize();+ expect(data).toEqual(originalData);+ const first = firstMaterialization.dependencies;+ expect(first.templateNames).toEqual(["Hero Card"]);+ expect(first.templates).toEqual([+ {+ templateInstanceId: "hero",+ templateName: "Hero Card",+ revision: expect.stringMatching(/^sha256:[0-9a-f]{64}$/),+ },+ ]);+ const rootIds = firstMaterialization.templates.flatMap((template) =>+ template.type === "resolved-template"+ ? template.fragment.children.map((child) => child.value)+ : []+ );+ expect(new Set(rootIds).size).toBe(2);++ const reorderedData = createData();+ const reorderedAsset = reorderedData.assets.get("image");+ if (reorderedAsset?.type !== "image") {+ throw new Error("Expected image Asset");+ }+ reorderedData.assets.set("image", {+ ...reorderedAsset,+ meta: { height: 10, width: 10 },+ });+ expect(+ (await materialize(reorderedData)).dependencies.templates[0].revision+ ).toBe(first.templates[0].revision);++ data.instances.get("heading")?.children.push({+ type: "text",+ value: "Changed",+ });+ expect((await materialize()).dependencies.templates[0].revision).not.toBe(+ first.templates[0].revision+ );+ });+});diff --git a/packages/project-build/src/runtime/mdx-materialization.ts b/packages/project-build/src/runtime/mdx-materialization.tsnew file mode 100644index 0000000000..edaaef6e2e--- /dev/null+++ b/packages/project-build/src/runtime/mdx-materialization.ts@@ -0,0 +1,258 @@+import hash from "@emotion/hash";+import { serializeJsonDeterministically } from "@webstudio-is/content-engine/compiler";+import {+ getAssetContentHash,+ type ContentBlockDiagnostic,+ type ContentBlockExternalContentIdentity,+ type Instance,+ type WebstudioData,+ type WebstudioFragment,+ type WsComponentMeta,+} from "@webstudio-is/sdk";+import {+ getContentModeCapabilities,+ getContentModePropEligibility,+} from "./content-mode-permissions";+import { findAvailableVariables } from "./data";+import {+ extractWebstudioFragment,+ insertWebstudioFragmentCopy,+} from "./fragment";+import type {+ MdxTemplateReference,+ MdxTemplateResolution,+} from "./mdx-template-resolution";+import { createPropValue, findProp } from "./props";++export type MaterializedMdxTemplate =+ | Readonly<{+ type: "resolved-template";+ reference: Extract<MdxTemplateReference, { type: "resolved-template" }>;+ fragment: WebstudioFragment;+ }>+ | Readonly<{+ type: "unresolved-template";+ reference: Extract<MdxTemplateReference, { type: "unresolved-template" }>;+ markerId: string;+ }>;++export type MdxTemplateDependency = Readonly<{+ templateInstanceId: Instance["id"];+ templateName: string;+ revision: `sha256:${string}`;+}>;++export type MdxTemplateMaterialization = Readonly<{+ templates: readonly MaterializedMdxTemplate[];+ diagnostics: readonly ContentBlockDiagnostic[];+ dependencies: Readonly<{+ templateNames: readonly string[];+ templates: readonly MdxTemplateDependency[];+ }>;+}>;++const createEmptyFragmentData = (): Omit<WebstudioData, "pages"> => ({+ instances: new Map(),+ props: new Map(),+ dataSources: new Map(),+ resources: new Map(),+ styleSources: new Map(),+ styleSourceSelections: new Map(),+ styles: new Map(),+ breakpoints: new Map(),+ assets: new Map(),+});++export const createMdxScopeIdGenerator = ({+ identity,+ path,+}: {+ identity: ContentBlockExternalContentIdentity;+ path: readonly number[];+}) => {+ const scope = hash(+ JSON.stringify([+ identity.blockInstanceId,+ identity.assetId,+ identity.revision,+ identity.contentRef,+ identity.renderScope,+ path,+ ])+ );+ let index = 0;+ return () => `mdx-${scope}-${index++}`;+};++export const materializeMdxTemplates = async ({+ identity,+ resolution,+ data,+ metas,+ projectId,+}: {+ identity: ContentBlockExternalContentIdentity;+ resolution: MdxTemplateResolution;+ data: Omit<WebstudioData, "pages">;+ metas: Map<string, WsComponentMeta>;+ projectId: string;+}): Promise<MdxTemplateMaterialization> => {+ const materializedTemplates: MaterializedMdxTemplate[] = [];+ const diagnostics: ContentBlockDiagnostic[] = [...resolution.diagnostics];+ const sourceTemplates = new Map<+ Instance["id"],+ {+ fragment: WebstudioFragment;+ dependency: MdxTemplateDependency;+ }+ >();+ for (const reference of resolution.references) {+ if (reference.type === "unresolved-template") {+ materializedTemplates.push({+ type: "unresolved-template",+ reference,+ markerId: createMdxScopeIdGenerator({+ identity,+ path: reference.path,+ })(),+ });+ continue;+ }+ if (data.instances.has(reference.templateInstanceId) === false) {+ throw new Error(+ `Resolved MDX template instance "${reference.templateInstanceId}" is missing`+ );+ }++ let sourceTemplate = sourceTemplates.get(reference.templateInstanceId);+ if (sourceTemplate === undefined) {+ const fragment = extractWebstudioFragment(+ data,+ reference.templateInstanceId+ );+ sourceTemplate = {+ fragment,+ dependency: {+ templateInstanceId: reference.templateInstanceId,+ templateName: reference.templateName,+ revision: `sha256:${await getAssetContentHash(+ new TextEncoder().encode(serializeJsonDeterministically(fragment))+ )}`,+ },+ };+ sourceTemplates.set(reference.templateInstanceId, sourceTemplate);+ }+ const sourceFragment = sourceTemplate.fragment;+ const materializedData = createEmptyFragmentData();+ const createId = createMdxScopeIdGenerator({+ identity,+ path: reference.path,+ });+ const { newInstanceIds } = insertWebstudioFragmentCopy({+ data: materializedData,+ fragment: sourceFragment,+ availableVariables: findAvailableVariables({+ startingInstanceId: reference.templateInstanceId,+ instances: data.instances,+ dataSources: data.dataSources,+ }),+ projectId,+ createId,+ });+ const materializedRootId = newInstanceIds.get(reference.templateInstanceId);+ if (materializedRootId === undefined) {+ throw new Error(+ `Materialized MDX template instance "${reference.templateInstanceId}" is missing`+ );+ }+ const rootInstance = materializedData.instances.get(materializedRootId);+ if (rootInstance === undefined) {+ throw new Error(+ `Materialized MDX template root "${materializedRootId}" is missing`+ );+ }+ const capabilities = getContentModeCapabilities({+ instances: materializedData.instances,+ metas,+ props: materializedData.props,+ styleSources: materializedData.styleSources,+ styleSourceSelections: materializedData.styleSourceSelections,+ styles: materializedData.styles,+ breakpoints: materializedData.breakpoints,+ contentRootIds: new Set([materializedRootId]),+ });+ for (const authoredProp of reference.props) {+ const existingProp = findProp(+ materializedData.props.values(),+ materializedRootId,+ authoredProp.name+ );+ const propType = authoredProp.value === true ? "boolean" : "string";+ const eligibility = getContentModePropEligibility({+ capabilities,+ instance: rootInstance,+ prop: {+ name: authoredProp.name,+ type: propType,+ },+ });+ if (eligibility.editable) {+ const prop = createPropValue({+ id: existingProp?.id ?? createId(),+ instanceId: materializedRootId,+ name: authoredProp.name,+ type: propType,+ value: authoredProp.value,+ required: existingProp?.required,+ });+ materializedData.props.set(prop.id, prop);+ for (const candidate of materializedData.props.values()) {+ if (+ candidate.id !== prop.id &&+ candidate.instanceId === materializedRootId &&+ candidate.name === authoredProp.name+ ) {+ materializedData.props.delete(candidate.id);+ }+ }+ continue;+ }+ // A persisted prop that is no longer recognized by the root's current+ // component/tag contract is stale in this template revision. An+ // authored name with no persisted history remains unknown.+ const reason =+ eligibility.reason === "unknown" && existingProp !== undefined+ ? "stale"+ : eligibility.reason;+ diagnostics.push({+ code: "ignored-template-prop",+ severity: "warning",+ blockInstanceId: identity.blockInstanceId,+ assetId: identity.assetId,+ contentRef: identity.contentRef,+ renderScope: identity.renderScope,+ templateName: reference.templateName,+ propName: authoredProp.name,+ reason,+ sourceRange: reference.sourceRange,+ });+ }++ materializedTemplates.push({+ type: "resolved-template",+ reference,+ fragment: extractWebstudioFragment(materializedData, materializedRootId),+ });+ }+ return {+ templates: materializedTemplates,+ diagnostics,+ dependencies: {+ templateNames: resolution.templateNames,+ templates: Array.from(+ sourceTemplates.values(),+ ({ dependency }) => dependency+ ),+ },+ };+};diff --git a/packages/project-build/src/runtime/mdx-paste.test.ts b/packages/project-build/src/runtime/mdx-paste.test.tsnew file mode 100644index 0000000000..f97275320f--- /dev/null+++ b/packages/project-build/src/runtime/mdx-paste.test.ts@@ -0,0 +1,396 @@+import { describe, expect, test } from "vitest";+import { parseMdxDocument } from "@webstudio-is/content-engine/mdx";+import {+ blockComponent,+ blockTemplateComponent,+ elementComponent,+ type ContentBlockExternalContentIdentity,+} from "@webstudio-is/sdk";+import type { BuilderState } from "../state/builder-state";+import { createDefaultPages } from "../shared/pages-utils";+import { materializeMdxAuthoredContent } from "./mdx-authored-content";+import type { MdxPasteResult } from "./mdx-paste";+import { prepareMdxContentStorageWrites } from "./mdx-storage-adapter";+import type { BuilderRuntimeMutation } from "./mutation";+import { executeBuilderRuntimeOperation } from "./registry";++const identity: ContentBlockExternalContentIdentity = {+ blockInstanceId: "block",+ assetId: "article",+ revision: "sha256:article",+ contentRef: "posts/article.mdx",+ format: "mdx",+ renderScope: "page:/article",+};++const createId = () => {+ let index = 0;+ return () => `generated-${index++}`;+};++const createState = (): BuilderState => ({+ pages: createDefaultPages({ rootInstanceId: "block" }),+ instances: new Map([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: "templates" }],+ },+ ],+ [+ "templates",+ {+ type: "instance",+ id: "templates",+ component: blockTemplateComponent,+ children: [{ type: "id", value: "hero" }],+ },+ ],+ [+ "hero",+ {+ type: "instance",+ id: "hero",+ component: elementComponent,+ tag: "article",+ label: "Hero Card",+ children: [{ type: "id", value: "hero-heading" }],+ },+ ],+ [+ "hero-heading",+ {+ type: "instance",+ id: "hero-heading",+ component: elementComponent,+ tag: "h2",+ children: [{ type: "text", value: "Destination template" }],+ },+ ],+ ]),+ props: new Map([+ [+ "src",+ {+ id: "src",+ instanceId: "block",+ name: "src",+ type: "asset",+ value: "article",+ },+ ],+ ]),+ dataSources: new Map(),+ resources: new Map(),+ styleSources: new Map(),+ styleSourceSelections: new Map(),+ styles: new Map(),+ breakpoints: new Map(),+ assets: new Map(),+});++const loadRoot = async (source = "Existing") =>+ materializeMdxAuthoredContent({+ identity,+ document: await parseMdxDocument({ source }),+ templateMaterialization: {+ templates: [],+ diagnostics: [],+ dependencies: { templateNames: [], templates: [] },+ },+ });++const paste = async ({+ source,+ loaded = true,+ mode,+ destinationSource = `---\ntitle: Destination\n---\n\nExisting`,+}: {+ source: string;+ loaded?: boolean;+ mode?: "append" | "prepend" | "replace";+ destinationSource?: string;+}) => {+ const root = await loadRoot(destinationSource);+ const state = createState();+ if (loaded === false) {+ state.props?.delete("src");+ }+ const mutation = await executeBuilderRuntimeOperation<+ BuilderRuntimeMutation<MdxPasteResult>+ >({+ id: "instances.insertMdxText",+ state,+ input: { parentInstanceId: "block", source, mode },+ context: {+ createId: createId(),+ projectId: "project",+ returnStorageChanges: true,+ materializedContent: loaded ? [root] : undefined,+ },+ });+ return { root, mutation };+};++describe("pasted MDX", () => {+ test("requires confirmation when replacement changes a template name", async () => {+ const execute = (templateNameConfirmation?: {+ action: "rename";+ templates: Array<{+ instanceId: string;+ oldName: string;+ newName: string;+ }>;+ }) =>+ executeBuilderRuntimeOperation({+ id: "instances.insertMdxText",+ state: createState(),+ input: {+ parentInstanceId: "templates",+ source: "# Replacement",+ mode: "replace",+ templateNameConfirmation,+ },+ context: { createId: createId(), projectId: "project" },+ });++ await expect(execute()).rejects.toMatchObject({+ code: "INVALID_INPUT",+ issues: [+ expect.objectContaining({+ code: "template_name_change_requires_confirmation",+ example: {+ action: "rename",+ templates: [+ {+ instanceId: "hero",+ oldName: "Hero Card",+ newName: "<h1>",+ },+ ],+ },+ }),+ ],+ });+ await expect(+ execute({+ action: "rename",+ templates: [+ {+ instanceId: "hero",+ oldName: "Hero Card",+ newName: "<h1>",+ },+ ],+ })+ ).resolves.toMatchObject({+ result: { removedInstanceIds: ["hero", "hero-heading"] },+ });+ });++ test("resolves names only from the destination Templates list", async () => {+ const source = `---\ntitle: Pasted\n---\n\n# Intro\n\n<ws.element ws:name="Hero Card" />`;+ const { root, mutation } = await paste({+ source,+ });++ expect(mutation.result.diagnostics).toEqual([]);+ expect(mutation.storageChanges?.[0]).toMatchObject({+ root: { type: "external", identity },+ mdxInsert: {+ source,+ parentInstanceId: "block",+ },+ });+ const request = {+ loadedRoots: [root],+ changes: mutation.storageChanges ?? [],+ authorizeAssetWrite: () => true,+ };+ const [write] = await prepareMdxContentStorageWrites(request);+ const [repeatedWrite] = await prepareMdxContentStorageWrites(request);+ const document = await parseMdxDocument({ source: write.source });++ expect(repeatedWrite.source).toBe(write.source);+ expect(document.frontmatter.properties).toEqual({ title: "Destination" });+ expect(document.children.slice(1)).toMatchObject([+ { type: "element", tag: "h1" },+ { type: "template", name: "Hero Card" },+ ]);+ expect(write.source).not.toContain("Destination template");+ });++ test("preserves comments and unresolved nested names without copying templates", async () => {+ const source = `{/* pasted */}\n\n<ws.element ws:tag="section"><ws.element ws:name="Hero Card" /><ws.element ws:name="Other Project Card" /></ws.element>`;+ const { root, mutation } = await paste({+ source,+ mode: "replace",+ destinationSource: `---\ntitle: Destination\n---\n\n{/* old */}\n\n<ws.element ws:name="Old Missing" />`,+ });++ expect(mutation.result.diagnostics).toMatchObject([+ {+ code: "unresolved-template",+ templateName: "Other Project Card",+ },+ ]);+ const [write] = await prepareMdxContentStorageWrites({+ loadedRoots: [root],+ changes: mutation.storageChanges ?? [],+ authorizeAssetWrite: () => true,+ });+ const document = await parseMdxDocument({ source: write.source });++ expect(document.children).toMatchObject([+ { type: "comment", value: "/* pasted */" },+ {+ type: "element",+ tag: "section",+ children: [+ { type: "template", name: "Hero Card" },+ { type: "template", name: "Other Project Card" },+ ],+ },+ ]);+ expect(write.source).not.toContain("Destination template");+ });++ test("rejects invalid and executable MDX", async () => {+ await expect(+ paste({ source: `<ws.element ws:tag="p">` })+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });+ await expect(paste({ source: `{alert("unsafe")}` })).rejects.toMatchObject({+ code: "BAD_REQUEST",+ });+ });++ test("persists non-rendered comments and unresolved names as authored text", async () => {+ const source = `{/* note */}\n\n<ws.element ws:name="Missing" />`;+ const { root, mutation } = await paste({ source });++ expect(mutation.noop).toBe(false);+ expect(mutation.result.instanceIds).toEqual([]);+ expect(mutation.result.diagnostics).toMatchObject([+ { code: "unresolved-template", templateName: "Missing" },+ ]);+ const [write] = await prepareMdxContentStorageWrites({+ loadedRoots: [root],+ changes: mutation.storageChanges ?? [],+ authorizeAssetWrite: () => true,+ });+ const document = await parseMdxDocument({ source: write.source });++ expect(document.children.slice(1)).toMatchObject([+ { type: "comment", value: "/* note */" },+ { type: "template", name: "Missing" },+ ]);+ });++ test("positions pasted MDX by rendered children around unresolved names", async () => {+ const destinationSource = `<ws.element ws:name="Missing" />\n\nExisting`;+ const document = await parseMdxDocument({ source: destinationSource });+ const root = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: {+ templates: [+ {+ type: "unresolved-template",+ reference: {+ type: "unresolved-template",+ path: [0],+ templateName: "Missing",+ },+ markerId: "missing",+ },+ ],+ diagnostics: [],+ dependencies: { templateNames: ["Missing"], templates: [] },+ },+ });+ const state = createState();+ const mutation = await executeBuilderRuntimeOperation<+ BuilderRuntimeMutation<MdxPasteResult>+ >({+ id: "instances.insertMdxText",+ state,+ input: {+ parentInstanceId: "block",+ source: "# Inserted",+ insertIndex: 1,+ },+ context: {+ createId: createId(),+ projectId: "project",+ returnStorageChanges: true,+ materializedContent: [root],+ },+ });++ const [write] = await prepareMdxContentStorageWrites({+ loadedRoots: [root],+ changes: mutation.storageChanges ?? [],+ authorizeAssetWrite: () => true,+ });+ const persisted = await parseMdxDocument({ source: write.source });++ expect(persisted.children).toMatchObject([+ { type: "template", name: "Missing" },+ { type: "element", tag: "p" },+ { type: "element", tag: "h1" },+ ]);+ });++ test("rejects raw MDX metadata that does not match the semantic insertion", async () => {+ const { root, mutation } = await paste({ source: "# Inserted" });+ const change = mutation.storageChanges?.[0];+ if (change?.mdxInsert === undefined) {+ throw new Error("Expected an MDX storage insertion");+ }++ await expect(+ prepareMdxContentStorageWrites({+ loadedRoots: [root],+ changes: [+ {+ ...change,+ mdxInsert: {+ ...change.mdxInsert,+ instanceIds: [],+ rootInstanceIds: [],+ },+ },+ ],+ authorizeAssetWrite: () => true,+ })+ ).rejects.toThrow("does not match its semantic insertion");+ });++ test("uses the same destination templates without file-backed storage", async () => {+ const { mutation } = await paste({+ source: `<ws.element ws:name="Hero Card" />`,+ loaded: false,+ });++ expect(mutation.storageChanges).toBeUndefined();+ expect(mutation.result.diagnostics).toEqual([]);+ expect(mutation.payload).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ namespace: "instances" }),+ ])+ );+ expect(mutation.result.rootInstanceIds).toHaveLength(1);++ const unresolved = await paste({+ source: `<ws.element ws:name="Other Project Card" />`,+ loaded: false,+ });+ expect(unresolved.mutation.result.diagnostics).toMatchObject([+ { code: "unresolved-template", templateName: "Other Project Card" },+ ]);+ expect(unresolved.mutation.noop).toBe(true);+ });+});diff --git a/packages/project-build/src/runtime/mdx-paste.ts b/packages/project-build/src/runtime/mdx-paste.tsnew file mode 100644index 0000000000..0f048e68e9--- /dev/null+++ b/packages/project-build/src/runtime/mdx-paste.ts@@ -0,0 +1,159 @@+import { parseMdxDocument } from "@webstudio-is/content-engine/mdx";+import {+ blockComponent,+ contentBlockDiagnostic,+ findParentInstanceReference,+ getAssetContentHash,+ type ContentBlockExternalContentIdentity,+ type Instance,+ type WebstudioData,+} from "@webstudio-is/sdk";+import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";+import { z } from "zod";+import type { BuilderState } from "../state/builder-state";+import { componentInsertResult } from "./component-insert-contract";+import { getRequiredComponentInsertData, insertFragment } from "./components";+import type { BuilderRuntimeContext } from "./context";+import { throwBuilderRuntimeError } from "./errors";+import {+ blockTemplateNameConfirmationInput,+ instanceInsertModeInput,+ insertIndexInput,+} from "./instances";+import { materializeMdxAuthoredContent } from "./mdx-authored-content";+import { materializeMdxTemplates } from "./mdx-materialization";+import { resolveMdxTemplates } from "./mdx-template-resolution";+import type { BuilderRuntimeMutation } from "./mutation";++export const insertMdxTextInput = z.object({+ parentInstanceId: z.string().min(1),+ source: z.string().min(1),+ mode: instanceInsertModeInput.optional(),+ insertIndex: insertIndexInput.optional(),+ templateNameConfirmation: blockTemplateNameConfirmationInput.optional(),+});++export const mdxPasteResult = componentInsertResult.extend({+ diagnostics: z.array(contentBlockDiagnostic),+});++export type MdxPasteResult = z.infer<typeof mdxPasteResult>;++const findDestinationBlock = ({+ parentInstanceId,+ instances,+}: {+ parentInstanceId: Instance["id"];+ instances: WebstudioData["instances"];+}) => {+ let instance = instances.get(parentInstanceId);+ const visited = new Set<Instance["id"]>();+ while (instance !== undefined) {+ if (visited.has(instance.id)) {+ return;+ }+ visited.add(instance.id);+ if (instance.component === blockComponent) {+ return instance;+ }+ instance = findParentInstanceReference(instances, instance.id)?.instance;+ }+};++const createPasteIdentity = async ({+ blockInstanceId,+ parentInstanceId,+ source,+}: {+ blockInstanceId: Instance["id"];+ parentInstanceId: Instance["id"];+ source: string;+}): Promise<ContentBlockExternalContentIdentity> => ({+ blockInstanceId,+ assetId: "clipboard",+ revision: `sha256:${await getAssetContentHash(+ new TextEncoder().encode(source)+ )}`,+ contentRef: "clipboard.mdx",+ format: "mdx",+ renderScope: `paste:${parentInstanceId}`,+});++const parsePastedMdx = async (source: string) => {+ try {+ return await parseMdxDocument({ source });+ } catch {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Pasted text is not valid safe MDX."+ );+ }+};++export const insertMdxText = async ({+ state,+ input,+ context,+ destinationIdentity,+ protectedChildCount,+}: {+ state: BuilderState;+ input: z.infer<typeof insertMdxTextInput>;+ context: BuilderRuntimeContext;+ destinationIdentity?: ContentBlockExternalContentIdentity;+ protectedChildCount?: number;+}): Promise<BuilderRuntimeMutation<MdxPasteResult>> => {+ const data = getRequiredComponentInsertData(state);+ const destinationBlock = findDestinationBlock({+ parentInstanceId: input.parentInstanceId,+ instances: data.instances,+ });+ const identity =+ destinationIdentity ??+ (await createPasteIdentity({+ blockInstanceId: destinationBlock?.id ?? input.parentInstanceId,+ parentInstanceId: input.parentInstanceId,+ source: input.source,+ }));+ const document = await parsePastedMdx(input.source);+ const resolution = resolveMdxTemplates({+ document,+ identity,+ instances: data.instances,+ metas: componentMetas,+ });+ const templateMaterialization = await materializeMdxTemplates({+ identity,+ resolution,+ data,+ metas: componentMetas,+ projectId: context.projectId ?? "",+ });+ const authored = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization,+ });+ const mutation = insertFragment(+ state,+ {+ parentInstanceId: input.parentInstanceId,+ fragment: authored.fragment,+ contentMode: destinationBlock !== undefined,+ mode: input.mode,+ insertIndex: input.insertIndex,+ templateNameConfirmation: input.templateNameConfirmation,+ },+ context,+ { protectedChildCount }+ );+ return {+ ...mutation,+ result: {+ ...mutation.result,+ parentInstanceId:+ mutation.result.parentInstanceId ?? input.parentInstanceId,+ diagnostics: [...templateMaterialization.diagnostics],+ },+ };+};diff --git a/packages/project-build/src/runtime/mdx-storage-adapter.test.ts b/packages/project-build/src/runtime/mdx-storage-adapter.test.tsnew file mode 100644index 0000000000..2a20077460--- /dev/null+++ b/packages/project-build/src/runtime/mdx-storage-adapter.test.ts@@ -0,0 +1,660 @@+import { describe, expect, test } from "vitest";+import {+ discoverMdxBodyAssetReferences,+ parseMdxDocument,+} from "@webstudio-is/content-engine/mdx";+import {+ elementComponent,+ type ContentBlockExternalContentIdentity,+ type Instance,+ type WebstudioFragment,+} from "@webstudio-is/sdk";+import {+ materializeMdxAuthoredContent,+ type MaterializedMdxAuthoredContentRoot,+} from "./mdx-authored-content";+import { prepareMdxContentStorageWrites } from "./mdx-storage-adapter";+import type { ContentStorageChange } from "./mutation";++const identity = (+ blockInstanceId: string,+ revision = `sha256:${blockInstanceId}`+): ContentBlockExternalContentIdentity => ({+ blockInstanceId,+ assetId: `${blockInstanceId}-asset`,+ revision,+ contentRef: `posts/${blockInstanceId}.mdx`,+ format: "mdx",+ renderScope: `page:/${blockInstanceId}`,+});++const load = async (+ blockInstanceId: string,+ source: string+): Promise<MaterializedMdxAuthoredContentRoot> =>+ materializeMdxAuthoredContent({+ identity: identity(blockInstanceId),+ document: await parseMdxDocument({ source }),+ templateMaterialization: {+ templates: [],+ diagnostics: [],+ dependencies: { templateNames: [], templates: [] },+ },+ });++const storageChange = (+ root: MaterializedMdxAuthoredContentRoot,+ payload: ContentStorageChange["payload"]+): ContentStorageChange => ({+ root: { type: "external", identity: root.identity },+ payload,+});++const authorizeAssetWrite = () => true;++const loadResolvedTemplate = async () => {+ const source = `<ws.element ws:name="Card" />`;+ const document = await parseMdxDocument({ source });+ const authoredTemplate = document.children[0];+ if (authoredTemplate?.type !== "template") {+ throw new Error("Expected authored template");+ }+ const fragment: WebstudioFragment = {+ children: [{ type: "id", value: "template-root" }],+ instances: [+ {+ type: "instance",+ id: "template-root",+ component: elementComponent,+ tag: "article",+ children: [{ type: "id", value: "template-heading" }],+ },+ {+ type: "instance",+ id: "template-heading",+ component: elementComponent,+ tag: "h2",+ children: [{ type: "text", value: "Template heading" }],+ },+ ],+ props: [],+ assets: [],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ };+ return materializeMdxAuthoredContent({+ identity: identity("article"),+ document,+ templateMaterialization: {+ templates: [+ {+ type: "resolved-template",+ reference: {+ type: "resolved-template",+ path: [0],+ templateName: "Card",+ templateInstanceId: "card-template",+ props: authoredTemplate.props,+ },+ fragment,+ },+ ],+ diagnostics: [],+ dependencies: { templateNames: ["Card"], templates: [] },+ },+ });+};++const cloneTemplateExpansion = (root: MaterializedMdxAuthoredContentRoot) => {+ const clonedRoot: Instance = {+ ...root.fragment.instances[0],+ id: "cloned-template-root",+ children: [{ type: "id", value: "cloned-template-heading" }],+ };+ const clonedHeading: Instance = {+ ...root.fragment.instances[1],+ id: "cloned-template-heading",+ };+ return { clonedRoot, clonedHeading };+};++const insertClonedTemplateExpansion = (+ root: MaterializedMdxAuthoredContentRoot+): ContentStorageChange => {+ const { clonedRoot, clonedHeading } = cloneTemplateExpansion(root);+ return storageChange(root, [+ {+ namespace: "instances",+ patches: [+ { op: "add", path: [clonedRoot.id], value: clonedRoot },+ { op: "add", path: [clonedHeading.id], value: clonedHeading },+ ],+ },+ {+ namespace: "fragment",+ patches: [+ {+ op: "add",+ path: ["children", 1],+ value: { type: "id", value: clonedRoot.id },+ },+ ],+ },+ ]);+};++describe("MDX storage adapter", () => {+ test("applies text and prop changes while preserving authored metadata", async () => {+ const root = await load(+ "article",+ `---\ntitle: Article\n---\n\n{/* keep */}\n\n<ws.element ws:tag="p" class="before">Before</ws.element>\n\n<ws.element ws:name="Missing" stale="keep" />`+ );+ const paragraph = root.fragment.instances.find(({ tag }) => tag === "p")!;+ const classProp = root.fragment.props.find(({ name }) => name === "class")!;+ const before = structuredClone(root);++ const changes: ContentStorageChange[] = [+ storageChange(root, [+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: [paragraph.id, "children", 0, "value"],+ value: "After",+ },+ ],+ },+ {+ namespace: "props",+ patches: [+ {+ op: "replace",+ path: [classProp.id, "value"],+ value: "after",+ },+ ],+ },+ ]),+ ];+ const request = {+ loadedRoots: [root],+ changes,+ authorizeAssetWrite,+ };+ const [write] = await prepareMdxContentStorageWrites(request);+ const [repeatedWrite] = await prepareMdxContentStorageWrites(request);+ const document = await parseMdxDocument({ source: write.source });++ expect(root).toEqual(before);+ expect(repeatedWrite).toEqual(write);+ expect(write.root.identity).toEqual(root.identity);+ expect(write.expectedRevision).toBe(root.identity.revision);+ expect(document.frontmatter.properties).toEqual({ title: "Article" });+ expect(document.children).toMatchObject([+ { type: "comment", value: "/* keep */" },+ {+ type: "element",+ props: [{ name: "class", value: "after" }],+ children: [{ type: "text", value: "After" }],+ },+ {+ type: "template",+ name: "Missing",+ props: [{ name: "stale", value: "keep" }],+ },+ ]);+ });++ test("applies structural fragment changes", async () => {+ const root = await load("article", "Paragraph");+ const inserted: Instance = {+ type: "instance",+ id: "inserted",+ component: elementComponent,+ tag: "aside",+ children: [{ type: "text", value: "Inserted" }],+ };+ const [write] = await prepareMdxContentStorageWrites({+ loadedRoots: [root],+ changes: [+ storageChange(root, [+ {+ namespace: "instances",+ patches: [{ op: "add", path: [inserted.id], value: inserted }],+ },+ {+ namespace: "fragment",+ patches: [+ {+ op: "add",+ path: ["children", 1],+ value: { type: "id", value: inserted.id },+ },+ ],+ },+ ]),+ ],+ authorizeAssetWrite,+ });++ expect(+ (await parseMdxDocument({ source: write.source })).children[1]+ ).toMatchObject({ type: "element", tag: "aside" });+ });++ test("combines repeated changes and preserves first-root ordering", async () => {+ const first = await load("first", "First");+ const second = await load("second", "Second");+ const firstId = first.fragment.instances[0].id;+ const secondId = second.fragment.instances[0].id;+ const authorized: ContentBlockExternalContentIdentity[] = [];+ const writes = await prepareMdxContentStorageWrites({+ loadedRoots: [first, second],+ changes: [+ storageChange(second, [+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: [secondId, "children", 0, "value"],+ value: "Second updated",+ },+ ],+ },+ ]),+ storageChange(first, [+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: [firstId, "children", 0, "value"],+ value: "Intermediate",+ },+ ],+ },+ ]),+ storageChange(first, [+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: [firstId, "children", 0, "value"],+ value: "First updated",+ },+ ],+ },+ ]),+ ],+ authorizeAssetWrite: (requestedIdentity) => {+ authorized.push(requestedIdentity);+ return true;+ },+ });++ expect(writes.map(({ root }) => root.identity.blockInstanceId)).toEqual([+ "second",+ "first",+ ]);+ expect(authorized).toEqual([second.identity, first.identity]);+ expect(writes[1].source).toContain("First updated");+ });++ test("reconciles an atomic structural transfer across roots", async () => {+ const source = await load(+ "source",+ `<ws.element ws:tag="aside">Moved</ws.element>`+ );+ const target = await load("target", "Target");+ const moved = source.fragment.instances[0];+ const writes = await prepareMdxContentStorageWrites({+ loadedRoots: [source, target],+ changes: [+ storageChange(source, [+ {+ namespace: "fragment",+ patches: [{ op: "remove", path: ["children", 0] }],+ },+ {+ namespace: "instances",+ patches: [{ op: "remove", path: [moved.id] }],+ },+ ]),+ storageChange(target, [+ {+ namespace: "instances",+ patches: [{ op: "add", path: [moved.id], value: moved }],+ },+ {+ namespace: "fragment",+ patches: [+ {+ op: "add",+ path: ["children", 1],+ value: { type: "id", value: moved.id },+ },+ ],+ },+ ]),+ ],+ authorizeAssetWrite,+ });++ expect(+ (await parseMdxDocument({ source: writes[0].source })).children+ ).toEqual([]);+ expect(+ (await parseMdxDocument({ source: writes[1].source })).children[1]+ ).toMatchObject({ type: "element", tag: "aside" });+ });++ test("requires exact authorization and current loaded identity", async () => {+ const root = await load("article", "Article");+ const change = storageChange(root, [+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: [root.fragment.instances[0].id, "children", 0, "value"],+ value: "Changed",+ },+ ],+ },+ ]);+ const authorizationRequests: ContentBlockExternalContentIdentity[] = [];+ await expect(+ prepareMdxContentStorageWrites({+ loadedRoots: [root],+ changes: [change],+ authorizeAssetWrite: (requestedIdentity) => {+ authorizationRequests.push(requestedIdentity);+ return false;+ },+ })+ ).rejects.toThrow("not authorized");+ expect(authorizationRequests).toEqual([root.identity]);++ await expect(+ prepareMdxContentStorageWrites({+ loadedRoots: [root],+ changes: [change],+ authorizeAssetWrite: () => undefined as unknown as boolean,+ })+ ).rejects.toThrow("not authorized");++ for (const mismatchedIdentity of [+ { ...root.identity, assetId: "other-asset" },+ { ...root.identity, contentRef: "posts/other.mdx" },+ { ...root.identity, revision: "sha256:stale" },+ { ...root.identity, renderScope: "page:/other" },+ ]) {+ await expect(+ prepareMdxContentStorageWrites({+ loadedRoots: [root],+ changes: [+ {+ ...change,+ root: { type: "external", identity: mismatchedIdentity },+ },+ ],+ authorizeAssetWrite,+ })+ ).rejects.toThrow("does not match its loaded Asset");+ }+ });++ test("rejects missing, duplicate, and non-MDX loaded roots", async () => {+ const root = await load("article", "Article");+ const change = storageChange(root, [+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: [root.fragment.instances[0].id, "children", 0, "value"],+ value: "Changed",+ },+ ],+ },+ ]);++ await expect(+ prepareMdxContentStorageWrites({+ loadedRoots: [],+ changes: [change],+ authorizeAssetWrite,+ })+ ).rejects.toThrow("is not loaded");+ await expect(+ prepareMdxContentStorageWrites({+ loadedRoots: [root, root],+ changes: [change],+ authorizeAssetWrite,+ })+ ).rejects.toThrow("Duplicate loaded MDX storage root");+ await expect(+ prepareMdxContentStorageWrites({+ loadedRoots: [+ {+ ...root,+ identity: { ...root.identity, format: "md" },+ } as unknown as MaterializedMdxAuthoredContentRoot,+ ],+ changes: [],+ authorizeAssetWrite,+ })+ ).rejects.toThrow("is not MDX");++ await expect(+ prepareMdxContentStorageWrites({+ loadedRoots: [root],+ changes: [+ storageChange(root, []),+ storageChange(root, [{ namespace: "instances", patches: [] }]),+ ],+ authorizeAssetWrite: () => {+ throw new Error("Empty changes must not request authorization");+ },+ })+ ).resolves.toEqual([]);+ });++ test("preserves authored Asset references", async () => {+ const source = `<ws.element ws:tag="figure"><ws.element ws:tag="img" src="./hero.png" /><ws.element ws:tag="a" href="../files/guide.pdf">Read</ws.element></ws.element>`;+ const document = await parseMdxDocument({ source });+ const root = materializeMdxAuthoredContent({+ identity: identity("article"),+ document,+ templateMaterialization: {+ templates: [],+ diagnostics: [],+ dependencies: { templateNames: [], templates: [] },+ },+ assetReferences: discoverMdxBodyAssetReferences({+ document,+ sourcePath: "posts/article.mdx",+ assetIdsByPath: new Map([+ ["posts/hero.png", "hero-asset"],+ ["files/guide.pdf", "guide-asset"],+ ]),+ }),+ });+ const link = root.fragment.instances.find(({ tag }) => tag === "a")!;+ const [write] = await prepareMdxContentStorageWrites({+ loadedRoots: [root],+ changes: [+ storageChange(root, [+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: [link.id, "children", 0, "value"],+ value: "Download",+ },+ ],+ },+ ]),+ ],+ authorizeAssetWrite,+ });++ expect(write.source).toContain('src="./hero.png"');+ expect(write.source).toContain('href="../files/guide.pdf"');+ expect(write.source).toContain("Download");+ });++ test("fails all roots atomically when any change is invalid", async () => {+ const first = await load("first", "First");+ const second = await load("second", "Second");+ const originalFirst = structuredClone(first.fragment);++ await expect(+ prepareMdxContentStorageWrites({+ loadedRoots: [first, second],+ changes: [+ storageChange(first, [+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: [+ first.fragment.instances[0].id,+ "children",+ 0,+ "value",+ ],+ value: "Changed",+ },+ ],+ },+ ]),+ storageChange(second, [+ {+ namespace: "pages",+ patches: [{ op: "remove", path: ["home"] }],+ },+ ]),+ ],+ authorizeAssetWrite,+ })+ ).rejects.toThrow("Unsupported MDX storage namespace");+ expect(first.fragment).toEqual(originalFirst);+ });++ test("rejects stale authored provenance", async () => {+ const root = await load("article", "Article");+ const stale = structuredClone(root);+ stale.fragment.instances[0].children = [+ { type: "text", value: "Out-of-band change" },+ ];++ await expect(+ prepareMdxContentStorageWrites({+ loadedRoots: [stale],+ changes: [+ storageChange(stale, [+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: [+ stale.fragment.instances[0].id,+ "children",+ 0,+ "value",+ ],+ value: "Requested change",+ },+ ],+ },+ ]),+ ],+ authorizeAssetWrite,+ })+ ).rejects.toThrow("authored provenance is stale");+ });++ test("rejects copied template expansions without shell provenance", async () => {+ const root = await loadResolvedTemplate();+ const change = insertClonedTemplateExpansion(root);++ await expect(+ prepareMdxContentStorageWrites({+ loadedRoots: [root],+ changes: [+ {+ ...change,+ copySource: {+ root: { type: "external", identity: root.identity },+ instanceId: root.fragment.instances[0].id,+ },+ },+ ],+ authorizeAssetWrite,+ })+ ).rejects.toThrow("require transferred shell provenance");++ await expect(+ prepareMdxContentStorageWrites({+ loadedRoots: [root],+ changes: [+ {+ ...change,+ copySource: {+ root: {+ type: "external",+ identity: {+ ...root.identity,+ revision: "sha256:stale-source",+ },+ },+ instanceId: root.fragment.instances[0].id,+ },+ },+ ],+ authorizeAssetWrite,+ })+ ).rejects.toThrow("does not match its loaded Asset");++ await expect(+ prepareMdxContentStorageWrites({+ loadedRoots: [root],+ changes: [+ {+ ...change,+ copySource: {+ root: { type: "external", identity: root.identity },+ instanceId: "missing-source",+ },+ },+ ],+ authorizeAssetWrite,+ })+ ).rejects.toThrow('source instance "missing-source" is not loaded');+ });++ test("does not mistake an inserted element tree for a template copy", async () => {+ const root = await loadResolvedTemplate();++ const [write] = await prepareMdxContentStorageWrites({+ loadedRoots: [root],+ changes: [insertClonedTemplateExpansion(root)],+ authorizeAssetWrite,+ });++ expect(+ (await parseMdxDocument({ source: write.source })).children[1]+ ).toMatchObject({ type: "element", tag: "article" });+ });+});diff --git a/packages/project-build/src/runtime/mdx-storage-adapter.ts b/packages/project-build/src/runtime/mdx-storage-adapter.tsnew file mode 100644index 0000000000..074bb75ffe--- /dev/null+++ b/packages/project-build/src/runtime/mdx-storage-adapter.ts@@ -0,0 +1,516 @@+import equal from "fast-deep-equal";+import {+ parseMdxDocument,+ serializeMdxDocument,+ type MdxAuthoredNode,+ type MdxDocument,+} from "@webstudio-is/content-engine/mdx";+import {+ getStyleDeclKey,+ type ContentBlockExternalContentIdentity,+ type WebstudioFragment,+} from "@webstudio-is/sdk";+import type { BuilderNamespace } from "../contracts/namespaces";+import type { BuilderState } from "../state/builder-state";+import {+ createBuilderBuildDataSnapshotFromState,+ createBuilderStateFromBuildData,+} from "../state/adapters";+import {+ applyBuilderNamespacePatches,+ applyBuilderPatchTransactions,+} from "../state/patch";+import {+ getContentStorageIdentityKey,+ type ContentStorageRoot,+} from "./content-storage";+import {+ reconcileMdxAuthoredContent,+ type MaterializedMdxAuthoredContentRoot,+} from "./mdx-authored-content";+import { hasContentStorageChange, type ContentStorageChange } from "./mutation";++export type PendingMdxContentStorageWrite = Readonly<{+ root: Extract<ContentStorageRoot, { type: "external" }>;+ expectedRevision: string;+ source: string;+}>;++const fragmentNamespaces = [+ "instances",+ "props",+ "assets",+ "dataSources",+ "resources",+ "breakpoints",+ "styleSources",+ "styleSourceSelections",+ "styles",+] as const satisfies readonly BuilderNamespace[];++type FragmentNamespace = (typeof fragmentNamespaces)[number];++const fromFragmentState = ({+ state,+ children,+}: {+ state: BuilderState;+ children: WebstudioFragment["children"];+}): WebstudioFragment => {+ const snapshot = createBuilderBuildDataSnapshotFromState(state);+ return {+ children,+ instances: snapshot.instances ?? [],+ props: snapshot.props ?? [],+ assets: snapshot.assets ?? [],+ dataSources: snapshot.dataSources ?? [],+ resources: snapshot.resources ?? [],+ breakpoints: snapshot.breakpoints ?? [],+ styleSources: snapshot.styleSources ?? [],+ styleSourceSelections: snapshot.styleSourceSelections ?? [],+ styles: snapshot.styles ?? [],+ };+};++export const applyMdxContentStorageChanges = ({+ root,+ changes,+}: {+ root: MaterializedMdxAuthoredContentRoot;+ changes: readonly ContentStorageChange[];+}) => {+ let state = createBuilderStateFromBuildData(root.fragment);+ let fragmentRoot = { children: root.fragment.children };+ for (const change of changes) {+ for (const storageChange of change.payload) {+ if (storageChange.namespace === "fragment") {+ fragmentRoot = applyBuilderNamespacePatches(+ fragmentRoot,+ storageChange.patches+ );+ continue;+ }+ if (+ fragmentNamespaces.includes(+ storageChange.namespace as FragmentNamespace+ ) === false+ ) {+ throw new Error(+ `Unsupported MDX storage namespace "${storageChange.namespace}"`+ );+ }+ state = applyBuilderPatchTransactions(state, [+ {+ id: "mdx-storage-adapter",+ payload: [storageChange],+ },+ ]).state;+ }+ }+ return fromFragmentState({ state, children: fragmentRoot.children });+};++const keepOriginalRecords = <Record>(+ records: readonly Record[],+ original: readonly Record[],+ getKey: (record: Record) => string+) => {+ const originalKeys = new Set(original.map(getKey));+ return records.filter((record) => originalKeys.has(getKey(record)));+};++const removeInsertedMdxRecords = ({+ root,+ fragment,+ change,+}: {+ root: MaterializedMdxAuthoredContentRoot;+ fragment: WebstudioFragment;+ change: NonNullable<ContentStorageChange["mdxInsert"]>;+}): WebstudioFragment => {+ const insertedIds = new Set(change.instanceIds);+ const insertedRootIds = new Set(change.rootInstanceIds);+ const instances = fragment.instances+ .filter(({ id }) => insertedIds.has(id) === false)+ .map((instance) =>+ instance.id === change.parentInstanceId+ ? {+ ...instance,+ children: instance.children.filter(+ (child) =>+ child.type !== "id" ||+ insertedRootIds.has(child.value) === false+ ),+ }+ : instance+ );+ return {+ children:+ change.parentInstanceId === root.identity.blockInstanceId+ ? fragment.children.filter(+ (child) =>+ child.type !== "id" || insertedRootIds.has(child.value) === false+ )+ : fragment.children,+ instances,+ props: fragment.props.filter(+ ({ instanceId }) => insertedIds.has(instanceId) === false+ ),+ assets: keepOriginalRecords(+ fragment.assets,+ root.fragment.assets,+ ({ id }) => id+ ),+ dataSources: keepOriginalRecords(+ fragment.dataSources,+ root.fragment.dataSources,+ ({ id }) => id+ ),+ resources: keepOriginalRecords(+ fragment.resources,+ root.fragment.resources,+ ({ id }) => id+ ),+ breakpoints: keepOriginalRecords(+ fragment.breakpoints,+ root.fragment.breakpoints,+ ({ id }) => id+ ),+ styleSources: keepOriginalRecords(+ fragment.styleSources,+ root.fragment.styleSources,+ ({ id }) => id+ ),+ styleSourceSelections: fragment.styleSourceSelections.filter(+ ({ instanceId }) => insertedIds.has(instanceId) === false+ ),+ styles: keepOriginalRecords(+ fragment.styles,+ root.fragment.styles,+ getStyleDeclKey+ ),+ };+};++const hasSameValues = (left: ReadonlySet<string>, right: ReadonlySet<string>) =>+ left.size === right.size &&+ Array.from(left).every((value) => right.has(value));++const assertMdxInsertMatchesFragment = ({+ root,+ fragment,+ change,+}: {+ root: MaterializedMdxAuthoredContentRoot;+ fragment: WebstudioFragment;+ change: NonNullable<ContentStorageChange["mdxInsert"]>;+}) => {+ const originalIds = new Set(root.fragment.instances.map(({ id }) => id));+ const addedIds = new Set(+ fragment.instances+ .filter(({ id }) => originalIds.has(id) === false)+ .map(({ id }) => id)+ );+ const insertedIds = new Set(change.instanceIds);+ const parentChildren =+ change.parentInstanceId === root.identity.blockInstanceId+ ? fragment.children+ : fragment.instances.find(({ id }) => id === change.parentInstanceId)+ ?.children;+ const addedChildIds = new Set(+ parentChildren?.flatMap((child) =>+ child.type === "id" && addedIds.has(child.value) ? [child.value] : []+ ) ?? []+ );+ const insertedRootIds = new Set(change.rootInstanceIds);+ if (+ insertedIds.size !== change.instanceIds.length ||+ insertedRootIds.size !== change.rootInstanceIds.length ||+ hasSameValues(addedIds, insertedIds) === false ||+ hasSameValues(addedChildIds, insertedRootIds) === false+ ) {+ throw new Error(+ "Pasted MDX metadata does not match its semantic insertion"+ );+ }+};++const getNodeAtPath = (+ document: MdxDocument,+ path: readonly number[]+): Exclude<MdxAuthoredNode, { type: "text" | "comment" }> | undefined => {+ let nodes = document.children;+ let node: MdxAuthoredNode | undefined;+ for (const index of path) {+ node = nodes[index];+ if (node === undefined || node.type === "text" || node.type === "comment") {+ return;+ }+ nodes = node.children;+ }+ return node?.type === "text" || node?.type === "comment" ? undefined : node;+};++const insertAuthoredNodes = ({+ root,+ document,+ change,+ nodes,+}: {+ root: MaterializedMdxAuthoredContentRoot;+ document: MdxDocument;+ change: NonNullable<ContentStorageChange["mdxInsert"]>;+ nodes: readonly MdxAuthoredNode[];+}): MdxDocument => {+ const next = structuredClone(document);+ let children = next.children as MdxAuthoredNode[];+ let parentPath: readonly number[] = [];+ if (change.parentInstanceId !== root.identity.blockInstanceId) {+ const provenance = root.provenance.nodes.find(+ ({ instanceId }) => instanceId === change.parentInstanceId+ );+ if (provenance?.type !== "element") {+ throw new Error(+ "Pasted MDX can only target an authored element or Content Block root"+ );+ }+ const parent = getNodeAtPath(next, provenance.path);+ if (parent?.type !== "element") {+ throw new Error("Pasted MDX parent provenance is stale");+ }+ parentPath = provenance.path;+ children = parent.children as MdxAuthoredNode[];+ }+ if (change.position === "replace") {+ children.splice(0, children.length, ...structuredClone(nodes));+ return next;+ }+ let authoredIndex = change.position === "append" ? children.length : 0;+ if (change.position === "index") {+ const unresolvedPaths = new Set(+ root.provenance.unresolvedTemplates.map(({ path }) => path.join("."))+ );+ let renderedIndex = 0;+ authoredIndex = children.length;+ for (const [index, node] of children.entries()) {+ if (+ node.type === "comment" ||+ unresolvedPaths.has([...parentPath, index].join("."))+ ) {+ continue;+ }+ if (renderedIndex === change.childIndex) {+ authoredIndex = index;+ break;+ }+ renderedIndex += 1;+ }+ }+ children.splice(authoredIndex, 0, ...structuredClone(nodes));+ return next;+};++const reconcileMdxInsert = async ({+ root,+ changes,+}: {+ root: MaterializedMdxAuthoredContentRoot;+ changes: readonly ContentStorageChange[];+}) => {+ const inserts = changes.flatMap(({ mdxInsert }) =>+ mdxInsert === undefined ? [] : [mdxInsert]+ );+ if (inserts.length !== 1 || changes.length !== 1) {+ throw new Error(+ "An MDX paste must be persisted before applying more changes to the same storage root"+ );+ }+ const [insert] = inserts;+ const finalFragment = applyMdxContentStorageChanges({ root, changes });+ assertMdxInsertMatchesFragment({+ root,+ fragment: finalFragment,+ change: insert,+ });+ const baseFragment = removeInsertedMdxRecords({+ root,+ fragment: finalFragment,+ change: insert,+ });+ const document = reconcileMdxAuthoredContent({+ root,+ fragment: baseFragment,+ });+ const pasted = await parseMdxDocument({ source: insert.source });+ return insertAuthoredNodes({+ root,+ document,+ change: insert,+ nodes: pasted.children,+ });+};++const getLoadedRoot = ({+ loadedRoots,+ loadedByIdentity,+ identity,+}: {+ loadedRoots: readonly MaterializedMdxAuthoredContentRoot[];+ loadedByIdentity: ReadonlyMap<string, MaterializedMdxAuthoredContentRoot>;+ identity: ContentBlockExternalContentIdentity;+}) => {+ const loaded = loadedByIdentity.get(getContentStorageIdentityKey(identity));+ if (loaded !== undefined) {+ return loaded;+ }+ if (+ loadedRoots.some(+ (root) => root.identity.blockInstanceId === identity.blockInstanceId+ )+ ) {+ throw new Error(+ `MDX storage root "${identity.blockInstanceId}" does not match its loaded Asset, content reference, revision, or render scope`+ );+ }+ throw new Error(+ `MDX storage root "${identity.blockInstanceId}" is not loaded`+ );+};++const assertCopySourceIsSerializable = ({+ change,+ loadedRoots,+ loadedByIdentity,+}: {+ change: ContentStorageChange;+ loadedRoots: readonly MaterializedMdxAuthoredContentRoot[];+ loadedByIdentity: ReadonlyMap<string, MaterializedMdxAuthoredContentRoot>;+}) => {+ const source = change.copySource;+ if (source === undefined || source.root.type === "project") {+ return;+ }+ const loaded = getLoadedRoot({+ loadedRoots,+ loadedByIdentity,+ identity: source.root.identity,+ });+ if (+ loaded.fragment.instances.some(({ id }) => id === source.instanceId) ===+ false+ ) {+ throw new Error(+ `Copied MDX source instance "${source.instanceId}" is not loaded`+ );+ }+ if (+ loaded.provenance.nodes.some(+ (node) =>+ node.type === "template" &&+ node.expandedInstanceIds.includes(source.instanceId)+ )+ ) {+ throw new Error(+ "Copied expanded MDX templates require transferred shell provenance"+ );+ }+};++export const prepareMdxContentStorageWrites = async ({+ loadedRoots,+ changes,+ authorizeAssetWrite,+}: {+ loadedRoots: readonly MaterializedMdxAuthoredContentRoot[];+ changes: readonly ContentStorageChange[];+ authorizeAssetWrite: (+ identity: ContentBlockExternalContentIdentity+ ) => boolean | Promise<boolean>;+}): Promise<PendingMdxContentStorageWrite[]> => {+ const loadedByIdentity = new Map<+ string,+ MaterializedMdxAuthoredContentRoot+ >();+ for (const root of loadedRoots) {+ if (root.identity.format !== "mdx") {+ throw new Error(+ `Content storage root "${root.identity.contentRef}" is not MDX`+ );+ }+ const key = getContentStorageIdentityKey(root.identity);+ if (loadedByIdentity.has(key)) {+ throw new Error(+ `Duplicate loaded MDX storage root "${root.identity.contentRef}"`+ );+ }+ loadedByIdentity.set(key, root);+ }++ const changesByIdentity = new Map<+ string,+ {+ root: MaterializedMdxAuthoredContentRoot;+ changes: ContentStorageChange[];+ }+ >();+ for (const change of changes) {+ if (hasContentStorageChange(change) === false) {+ continue;+ }+ const identity = change.root.identity;+ if (identity.format !== "mdx") {+ throw new Error(+ `Content storage root "${identity.contentRef}" is not MDX`+ );+ }+ const key = getContentStorageIdentityKey(identity);+ const loaded = getLoadedRoot({ loadedRoots, loadedByIdentity, identity });+ assertCopySourceIsSerializable({+ change,+ loadedRoots,+ loadedByIdentity,+ });+ const entry = changesByIdentity.get(key) ?? { root: loaded, changes: [] };+ entry.changes.push(change);+ changesByIdentity.set(key, entry);+ }++ for (const { root } of changesByIdentity.values()) {+ if ((await authorizeAssetWrite(root.identity)) !== true) {+ throw new Error(+ `MDX Asset "${root.identity.assetId}" is not authorized for writing`+ );+ }+ }++ const writes: PendingMdxContentStorageWrite[] = [];+ for (const { root, changes: rootChanges } of changesByIdentity.values()) {+ if (+ equal(+ reconcileMdxAuthoredContent({ root, fragment: root.fragment }),+ root.document+ ) === false+ ) {+ throw new Error(+ `MDX storage root "${root.identity.blockInstanceId}" authored provenance is stale`+ );+ }+ const document = rootChanges.some(+ ({ mdxInsert }) => mdxInsert !== undefined+ )+ ? await reconcileMdxInsert({ root, changes: rootChanges })+ : reconcileMdxAuthoredContent({+ root,+ fragment: applyMdxContentStorageChanges({+ root,+ changes: rootChanges,+ }),+ });+ writes.push({+ root: { type: "external", identity: root.identity },+ expectedRevision: root.identity.revision,+ source: serializeMdxDocument(document),+ });+ }+ return writes;+};diff --git a/packages/project-build/src/runtime/mdx-template-migration.test.ts b/packages/project-build/src/runtime/mdx-template-migration.test.tsnew file mode 100644index 0000000000..05ee1ef7b5--- /dev/null+++ b/packages/project-build/src/runtime/mdx-template-migration.test.ts@@ -0,0 +1,105 @@+import { parseMdxDocument } from "@webstudio-is/content-engine/mdx";+import { describe, expect, test } from "vitest";+import { planMdxTemplateMigration } from "./mdx-template-migration";++const files = [+ {+ assetId: "article",+ revision: "revision-1",+ contentRef: "article.mdx-revision-1",+ source: `---\ntitle: Article\n---\n\n{/* keep */}\n\n<ws.element ws:name="Card">\n <ws.element ws:name="Card" />\n</ws.element>\n\n<ws.element ws:name="Other" />`,+ },+];++describe("MDX template migration", () => {+ test("rejects duplicate, excessive, and oversized file selections", async () => {+ const input = {+ projectId: "project",+ migration: { type: "remove", name: "Card" } as const,+ };+ await expect(+ planMdxTemplateMigration({ ...input, files: [files[0], files[0]] })+ ).rejects.toThrow('Duplicate MDX Asset "article"');+ await expect(+ planMdxTemplateMigration({+ ...input,+ files: Array.from({ length: 101 }, (_, index) => ({+ ...files[0],+ assetId: `article-${index}`,+ })),+ })+ ).rejects.toThrow("limited to 100 files");+ await expect(+ planMdxTemplateMigration({+ ...input,+ files: [+ {+ ...files[0],+ source: "x".repeat(10 * 1024 * 1024 + 1),+ },+ ],+ })+ ).rejects.toThrow("exceeds the 10 MiB limit");+ });++ test("previews nested AST renames while preserving frontmatter and comments", async () => {+ const plan = await planMdxTemplateMigration({+ projectId: "project",+ migration: { type: "rename", from: "Card", to: "Feature Card" },+ files,+ });++ expect(plan).toMatchObject({+ status: "confirmation-required",+ updateCount: 2,+ omissionCount: 0,+ changedFileCount: 1,+ files: [{ assetId: "article", changed: true, updateCount: 2 }],+ });+ const document = await parseMdxDocument({ source: plan.files[0].source });+ expect(document.frontmatter.properties).toEqual({ title: "Article" });+ expect(document.children[0]).toMatchObject({+ type: "comment",+ value: "/* keep */",+ });+ expect(document.children[1]).toMatchObject({+ type: "template",+ name: "Feature Card",+ children: [{ type: "template", name: "Feature Card" }],+ });+ expect(document.children[2]).toMatchObject({+ type: "template",+ name: "Other",+ });+ });++ test("omits the complete matching subtree and reports invalid files", async () => {+ const plan = await planMdxTemplateMigration({+ projectId: "project",+ migration: { type: "remove", name: "Card" },+ files: [+ ...files,+ { ...files[0], assetId: "invalid", source: "<ws.element>" },+ ],+ });++ expect(plan).toMatchObject({+ updateCount: 0,+ omissionCount: 1,+ changedFileCount: 1,+ files: [+ { assetId: "article", omissionCount: 1, diagnostics: [] },+ {+ assetId: "invalid",+ changed: false,+ diagnostics: [{ code: "invalid-mdx" }],+ },+ ],+ });+ const document = await parseMdxDocument({ source: plan.files[0].source });+ expect(document.children).toEqual([+ expect.objectContaining({ type: "comment" }),+ expect.objectContaining({ type: "template", name: "Other" }),+ ]);+ });+});diff --git a/packages/project-build/src/runtime/mdx-template-migration.ts b/packages/project-build/src/runtime/mdx-template-migration.tsnew file mode 100644index 0000000000..953d533b6d--- /dev/null+++ b/packages/project-build/src/runtime/mdx-template-migration.ts@@ -0,0 +1,283 @@+import {+ parseMdxDocument,+ serializeMdxDocument,+ type MdxAuthoredNode,+ type MdxDocumentError,+ type MdxSourceRange,+} from "@webstudio-is/content-engine/mdx";+import {+ createConfirmationToken,+ validateConfirmationToken,+} from "../confirmation-token";++export type MdxTemplateMigration = Readonly<+ | { type: "rename"; from: string; to: string }+ | { type: "remove"; name: string }+>;++export type MdxTemplateMigrationFile = Readonly<{+ assetId: string;+ revision: string;+ contentRef: string;+ source: string;+}>;++export type MdxTemplateMigrationDiagnostic = Readonly<{+ code:+ | "invalid-mdx"+ | "unsafe-mdx"+ | "asset-revision-conflict"+ | "asset-authorization-failed"+ | "asset-write-failed";+ assetId: string;+ contentRef: string;+ message: string;+ sourceRange?: MdxSourceRange;+}>;++export type MdxTemplateMigrationFilePlan = Readonly<{+ assetId: string;+ revision: string;+ contentRef: string;+ source: string;+ changed: boolean;+ updateCount: number;+ omissionCount: number;+ diagnostics: readonly MdxTemplateMigrationDiagnostic[];+}>;++export type MdxTemplateMigrationPlan = Readonly<{+ status: "confirmation-required";+ migration: MdxTemplateMigration;+ files: readonly MdxTemplateMigrationFilePlan[];+ updateCount: number;+ omissionCount: number;+ changedFileCount: number;+ selectionAssetIds: readonly string[];+ confirmationScope?: Readonly<Record<string, unknown>>;+ confirmationToken: string;+ confirmationExpiresAt: string;+}>;++const updateNodes = (+ nodes: readonly MdxAuthoredNode[],+ migration: MdxTemplateMigration+): {+ nodes: readonly MdxAuthoredNode[];+ updateCount: number;+ omissionCount: number;+} => {+ let updateCount = 0;+ let omissionCount = 0;+ let changed = false;+ const nextNodes: MdxAuthoredNode[] = [];+ for (const node of nodes) {+ if (node.type === "template") {+ const matches =+ migration.type === "rename"+ ? node.name === migration.from+ : node.name === migration.name;+ if (matches && migration.type === "remove") {+ omissionCount += 1;+ changed = true;+ continue;+ }+ const children = updateNodes(node.children, migration);+ updateCount += children.updateCount;+ omissionCount += children.omissionCount;+ if (matches && migration.type === "rename") {+ updateCount += 1;+ changed = true;+ nextNodes.push({+ ...node,+ name: migration.to,+ children: children.nodes,+ });+ continue;+ }+ if (children.nodes !== node.children) {+ changed = true;+ nextNodes.push({ ...node, children: children.nodes });+ } else {+ nextNodes.push(node);+ }+ continue;+ }+ if (node.type === "element") {+ const children = updateNodes(node.children, migration);+ updateCount += children.updateCount;+ omissionCount += children.omissionCount;+ if (children.nodes !== node.children) {+ changed = true;+ nextNodes.push({ ...node, children: children.nodes });+ } else {+ nextNodes.push(node);+ }+ continue;+ }+ nextNodes.push(node);+ }+ return {+ nodes: changed ? nextNodes : nodes,+ updateCount,+ omissionCount,+ };+};++const toParseDiagnostic = (+ file: MdxTemplateMigrationFile,+ error: unknown+): MdxTemplateMigrationDiagnostic => ({+ code:+ typeof error === "object" &&+ error !== null &&+ "code" in error &&+ error.code === "unsafe-mdx"+ ? "unsafe-mdx"+ : "invalid-mdx",+ assetId: file.assetId,+ contentRef: file.contentRef,+ message: error instanceof Error ? error.message : "Unable to parse MDX",+ sourceRange: (error as MdxDocumentError | undefined)?.sourceRange,+});++const getConfirmationPayload = ({+ projectId,+ migration,+ files,+ selectionAssetIds,+ confirmationScope,+}: {+ projectId: string;+ migration: MdxTemplateMigration;+ files: readonly MdxTemplateMigrationFilePlan[];+ selectionAssetIds?: readonly string[];+ confirmationScope?: Readonly<Record<string, unknown>>;+}) => ({+ operation: "mdx-template-migration",+ projectId,+ migration,+ confirmationScope,+ selectionAssetIds:+ selectionAssetIds === undefined+ ? files.map(({ assetId }) => assetId).sort()+ : [...selectionAssetIds].sort(),+ files: files.map(({ assetId, revision, contentRef, source, changed }) => ({+ assetId,+ revision,+ contentRef,+ source,+ changed,+ })),+});++export const validateMdxTemplateMigrationConfirmation = ({+ projectId,+ plan,+ confirmationToken,+}: {+ projectId: string;+ plan: MdxTemplateMigrationPlan;+ confirmationToken?: string;+}) =>+ validateConfirmationToken(+ confirmationToken,+ getConfirmationPayload({+ projectId,+ migration: plan.migration,+ files: plan.files,+ selectionAssetIds: plan.selectionAssetIds,+ confirmationScope: plan.confirmationScope,+ })+ );++export const planMdxTemplateMigration = async ({+ projectId,+ migration,+ files,+ selectionAssetIds,+ confirmationScope,+ confirmationTtlMs = 5 * 60_000,+}: {+ projectId: string;+ migration: MdxTemplateMigration;+ files: readonly MdxTemplateMigrationFile[];+ selectionAssetIds?: readonly string[];+ confirmationScope?: Readonly<Record<string, unknown>>;+ confirmationTtlMs?: number;+}): Promise<MdxTemplateMigrationPlan> => {+ if (files.length > 100) {+ throw new Error("MDX template migration is limited to 100 files");+ }+ const selected = selectionAssetIds ?? files.map(({ assetId }) => assetId);+ if (+ selected.length > 100 ||+ (selectionAssetIds !== undefined &&+ new Set(selected).size !== selected.length)+ ) {+ throw new Error("MDX template migration selection is invalid");+ }+ const seenAssetIds = new Set<string>();+ let totalBytes = 0;+ const plannedFiles: MdxTemplateMigrationFilePlan[] = [];+ for (const file of files) {+ if (seenAssetIds.has(file.assetId)) {+ throw new Error(`Duplicate MDX Asset "${file.assetId}"`);+ }+ seenAssetIds.add(file.assetId);+ totalBytes += new TextEncoder().encode(file.source).byteLength;+ if (totalBytes > 10 * 1024 * 1024) {+ throw new Error("MDX template migration exceeds the 10 MiB limit");+ }+ try {+ const document = await parseMdxDocument({ source: file.source });+ const result = updateNodes(document.children, migration);+ plannedFiles.push({+ assetId: file.assetId,+ revision: file.revision,+ contentRef: file.contentRef,+ source:+ result.nodes === document.children+ ? file.source+ : serializeMdxDocument({ ...document, children: result.nodes }),+ changed: result.nodes !== document.children,+ updateCount: result.updateCount,+ omissionCount: result.omissionCount,+ diagnostics: [],+ });+ } catch (error) {+ plannedFiles.push({+ ...file,+ changed: false,+ updateCount: 0,+ omissionCount: 0,+ diagnostics: [toParseDiagnostic(file, error)],+ });+ }+ }+ const confirmation = await createConfirmationToken(+ getConfirmationPayload({+ projectId,+ migration,+ files: plannedFiles,+ selectionAssetIds: selected,+ confirmationScope,+ }),+ confirmationTtlMs+ );+ return {+ status: "confirmation-required",+ migration,+ files: plannedFiles,+ updateCount: plannedFiles.reduce((sum, file) => sum + file.updateCount, 0),+ omissionCount: plannedFiles.reduce(+ (sum, file) => sum + file.omissionCount,+ 0+ ),+ changedFileCount: plannedFiles.filter((file) => file.changed).length,+ selectionAssetIds: [...selected].sort(),+ confirmationScope,+ confirmationToken: confirmation.token,+ confirmationExpiresAt: new Date(confirmation.expiresAt).toISOString(),+ };+};diff --git a/packages/project-build/src/runtime/mdx-template-resolution.test.ts b/packages/project-build/src/runtime/mdx-template-resolution.test.tsnew file mode 100644index 0000000000..8a456ad5c5--- /dev/null+++ b/packages/project-build/src/runtime/mdx-template-resolution.test.ts@@ -0,0 +1,218 @@+import { describe, expect, test } from "vitest";+import { parseMdxDocument } from "@webstudio-is/content-engine/mdx";+import {+ blockComponent,+ blockTemplateComponent,+ elementComponent,+ type ContentBlockExternalContentIdentity,+ type Instance,+ type Instances,+ type WsComponentMeta,+} from "@webstudio-is/sdk";+import { resolveMdxTemplates } from "./mdx-template-resolution";++const createInstance = (+ id: string,+ component: string,+ values: Partial<Pick<Instance, "children" | "label" | "tag">> = {}+): Instance => ({ type: "instance", id, component, children: [], ...values });++const identity: ContentBlockExternalContentIdentity = {+ blockInstanceId: "block",+ assetId: "article",+ revision: "revision-1",+ contentRef: "articles/hello.mdx",+ format: "mdx",+ renderScope: "route:/hello",+};++const metas = new Map<string, WsComponentMeta>([+ ["Card", { label: "Card" }],+ ["Badge", { label: "Badge" }],+]);++const createInstances = (): Instances =>+ new Map([+ [+ "block",+ createInstance("block", blockComponent, {+ children: [{ type: "id", value: "templates" }],+ }),+ ],+ [+ "templates",+ createInstance("templates", blockTemplateComponent, {+ children: [+ { type: "id", value: "hero" },+ { type: "id", value: "card" },+ ],+ }),+ ],+ [+ "hero",+ createInstance("hero", elementComponent, {+ label: "Hero Card",+ tag: "section",+ }),+ ],+ [+ "card",+ createInstance("card", "Card", {+ children: [{ type: "id", value: "badge" }],+ }),+ ],+ ["badge", createInstance("badge", "Badge", { label: "Nested" })],+ ]);++describe("resolveMdxTemplates", () => {+ test("resolves exact displayed names from the direct flat Templates list", async () => {+ const document = await parseMdxDocument({+ source: `<ws.element ws:name="Hero Card" tone="quiet" />++<ws.element ws:tag="section">+ <ws.element ws:name="Card" />+</ws.element>`,+ });++ const result = resolveMdxTemplates({+ document,+ identity,+ instances: createInstances(),+ metas,+ });++ expect(result.references).toEqual([+ expect.objectContaining({+ type: "resolved-template",+ path: [0],+ templateName: "Hero Card",+ props: [{ name: "tone", value: "quiet" }],+ templateInstanceId: "hero",+ }),+ expect.objectContaining({+ type: "resolved-template",+ path: [1, 0],+ templateName: "Card",+ props: [],+ templateInstanceId: "card",+ }),+ ]);+ expect(result.diagnostics).toEqual([]);+ expect(result.templateNames).toEqual(["Hero Card", "Card"]);+ });++ test("does not resolve descendants of a template entry or inexact names", async () => {+ const document = await parseMdxDocument({+ source: `<ws.element ws:name="Nested" />++<ws.element ws:name=" Hero Card " />`,+ });++ const result = resolveMdxTemplates({+ document,+ identity,+ instances: createInstances(),+ metas,+ });++ expect(result.references).toEqual([+ expect.objectContaining({+ type: "unresolved-template",+ path: [0],+ templateName: "Nested",+ }),+ expect.objectContaining({+ type: "unresolved-template",+ path: [1],+ templateName: " Hero Card ",+ }),+ ]);+ expect(result.diagnostics).toEqual([+ expect.objectContaining({+ code: "unresolved-template",+ blockInstanceId: "block",+ assetId: "article",+ contentRef: "articles/hello.mdx",+ renderScope: "route:/hello",+ templateName: "Nested",+ }),+ expect.objectContaining({+ code: "unresolved-template",+ templateName: " Hero Card ",+ }),+ ]);+ expect(result.templateNames).toEqual(["Hero Card", "Card"]);+ });++ test("keeps ambiguous duplicate displayed names unresolved", async () => {+ const instances = createInstances();+ instances.set(+ "duplicate",+ createInstance("duplicate", "Card", { label: "Hero Card" })+ );+ instances.get("templates")?.children.push({+ type: "id",+ value: "duplicate",+ });+ const document = await parseMdxDocument({+ source: `<ws.element ws:name="Hero Card">Preserved</ws.element>`,+ });++ const result = resolveMdxTemplates({+ document,+ identity,+ instances,+ metas,+ });++ expect(result.references).toEqual([+ expect.objectContaining({+ type: "unresolved-template",+ path: [0],+ templateName: "Hero Card",+ }),+ ]);+ expect(result.diagnostics).toEqual([+ expect.objectContaining({+ code: "unresolved-template",+ templateName: "Hero Card",+ }),+ ]);+ expect(result.templateNames).toEqual(["Hero Card", "Card", "Hero Card"]);+ expect(document.children[0]).toMatchObject({+ type: "template",+ name: "Hero Card",+ children: [{ type: "text", value: "Preserved" }],+ });+ });++ test("does not resolve or diagnose descendants of an unresolved subtree", async () => {+ const document = await parseMdxDocument({+ source: `<ws.element ws:name="Missing">+ <ws.element ws:name="Card" />+ <ws.element ws:name="Also Missing" />+</ws.element>`,+ });++ const result = resolveMdxTemplates({+ document,+ identity,+ instances: createInstances(),+ metas,+ });++ expect(result.references).toEqual([+ expect.objectContaining({+ type: "unresolved-template",+ path: [0],+ templateName: "Missing",+ }),+ ]);+ expect(result.diagnostics).toEqual([+ expect.objectContaining({+ code: "unresolved-template",+ templateName: "Missing",+ }),+ ]);+ });+});diff --git a/packages/project-build/src/runtime/mdx-template-resolution.ts b/packages/project-build/src/runtime/mdx-template-resolution.tsnew file mode 100644index 0000000000..d978a8a297--- /dev/null+++ b/packages/project-build/src/runtime/mdx-template-resolution.ts@@ -0,0 +1,114 @@+import type {+ MdxAuthoredProp,+ MdxAuthoredNode,+ MdxDocument,+} from "@webstudio-is/content-engine/mdx";+import {+ getInstanceName,+ type ContentBlockDiagnostic,+ type ContentBlockExternalContentIdentity,+ type ContentBlockSourceRange,+ type Instance,+ type Instances,+ type WsComponentMeta,+} from "@webstudio-is/sdk";+import { findBlockTemplates } from "./block";++export type MdxTemplateReference = Readonly<{+ path: readonly number[];+ templateName: string;+ sourceRange?: ContentBlockSourceRange;+}> &+ (+ | Readonly<{+ type: "resolved-template";+ templateInstanceId: Instance["id"];+ props: readonly MdxAuthoredProp[];+ }>+ | Readonly<{+ type: "unresolved-template";+ }>+ );++export type MdxTemplateResolution = Readonly<{+ templateNames: readonly string[];+ references: readonly MdxTemplateReference[];+ diagnostics: readonly ContentBlockDiagnostic[];+}>;++export const resolveMdxTemplates = ({+ document,+ identity,+ instances,+ metas,+}: {+ document: MdxDocument;+ identity: ContentBlockExternalContentIdentity;+ instances: Instances;+ metas: ReadonlyMap<Instance["component"], WsComponentMeta>;+}): MdxTemplateResolution => {+ const templateIdsByName = new Map<string, Instance["id"][]>();+ const templateNames: string[] = [];+ for (const [template] of findBlockTemplates({+ anchor: [identity.blockInstanceId],+ instances,+ }) ?? []) {+ const name = getInstanceName({ instance: template, metas });+ templateNames.push(name);+ const templateIds = templateIdsByName.get(name) ?? [];+ templateIds.push(template.id);+ templateIdsByName.set(name, templateIds);+ }++ const references: MdxTemplateReference[] = [];+ const diagnostics: ContentBlockDiagnostic[] = [];++ const visit = (+ nodes: readonly MdxAuthoredNode[],+ parentPath: readonly number[]+ ) => {+ for (const [index, node] of nodes.entries()) {+ const path = [...parentPath, index];+ if (node.type === "template") {+ const templateIds = templateIdsByName.get(node.name);+ if (templateIds?.length === 1) {+ references.push({+ type: "resolved-template",+ path,+ templateName: node.name,+ props: node.props,+ templateInstanceId: templateIds[0],+ sourceRange: node.sourceRange,+ });+ } else {+ references.push({+ type: "unresolved-template",+ path,+ templateName: node.name,+ sourceRange: node.sourceRange,+ });+ diagnostics.push({+ code: "unresolved-template",+ severity: "warning",+ blockInstanceId: identity.blockInstanceId,+ assetId: identity.assetId,+ contentRef: identity.contentRef,+ renderScope: identity.renderScope,+ templateName: node.name,+ sourceRange: node.sourceRange,+ });+ // The unresolved marker replaces the complete subtree in the Builder,+ // and publication omits it, so descendant references are not actionable.+ continue;+ }+ }++ if (node.type !== "text" && node.type !== "comment") {+ visit(node.children, path);+ }+ }+ };++ visit(document.children, []);+ return { templateNames, references, diagnostics };+};diff --git a/packages/project-build/src/runtime/mutation.test.ts b/packages/project-build/src/runtime/mutation.test.tsindex 73d12bf622..836f9d25b2 100644--- a/packages/project-build/src/runtime/mutation.test.ts+++ b/packages/project-build/src/runtime/mutation.test.ts@@ -1,10 +1,96 @@import { expect, test } from "vitest";import { createDefaultPages } from "../shared/pages-utils";+import {+ blockComponent,+ blockTemplateComponent,+ type Instance,+} from "@webstudio-is/sdk";import {createRuntimeMutation,createRuntimeMutationAccumulator,+ getRuntimeMutationPersistenceOrder,} from "./mutation";+const externalRoot = {+ type: "external" as const,+ identity: {+ blockInstanceId: "block",+ assetId: "article",+ revision: "sha256:article",+ contentRef: "article.mdx",+ format: "mdx" as const,+ renderScope: "page:/",+ },+};++test("orders the durable destination before a cross-storage source removal", () => {+ const storageRemoval = {+ root: externalRoot,+ payload: [+ {+ namespace: "instances" as const,+ patches: [{ op: "remove" as const, path: ["moved"] }],+ },+ ],+ };+ expect(+ getRuntimeMutationPersistenceOrder({+ payload: [+ {+ namespace: "instances",+ patches: [{ op: "add", path: ["moved"], value: {} }],+ },+ ],+ storageChanges: [storageRemoval],+ })+ ).toBe("project-first");+ expect(+ getRuntimeMutationPersistenceOrder({+ payload: [+ {+ namespace: "instances",+ patches: [{ op: "remove", path: ["moved"] }],+ },+ ],+ storageChanges: [+ {+ root: externalRoot,+ payload: [+ {+ namespace: "instances",+ patches: [{ op: "add", path: ["moved"], value: {} }],+ },+ ],+ },+ ],+ })+ ).toBe("storage-first");+});++test("does not correlate unrelated records that only share an id", () => {+ expect(+ getRuntimeMutationPersistenceOrder({+ payload: [+ {+ namespace: "props",+ patches: [{ op: "add", path: ["shared"], value: {} }],+ },+ ],+ storageChanges: [+ {+ root: externalRoot,+ payload: [+ {+ namespace: "instances",+ patches: [{ op: "remove", path: ["shared"] }],+ },+ ],+ },+ ],+ })+ ).toBe("storage-first");+});+test("creates mutation result and marks noop from payload", () => {expect(createRuntimeMutation({@@ -77,3 +163,86 @@ test("stages mutations against the latest state and combines their contract", ()],});});++test("preserves multiple authored storage changes and their noop semantics", () => {+ const instances = new Map<Instance["id"], Instance>();+ for (const id of ["first", "second"]) {+ instances.set(id, {+ type: "instance",+ id,+ component: blockComponent,+ children: [+ { type: "id", value: `${id}-templates` },+ { type: "text", value: "Before" },+ ],+ });+ instances.set(`${id}-templates`, {+ type: "instance",+ id: `${id}-templates`,+ component: blockTemplateComponent,+ children: [],+ });+ }+ const accumulator = createRuntimeMutationAccumulator({ instances });+ const firstRoot = {+ type: "external" as const,+ identity: {+ blockInstanceId: "first",+ assetId: "first-asset",+ revision: "first-revision",+ contentRef: "first.mdx",+ format: "mdx" as const,+ renderScope: "page:/first",+ },+ };+ const secondRoot = {+ type: "external" as const,+ identity: {+ ...firstRoot.identity,+ blockInstanceId: "second",+ assetId: "second-asset",+ contentRef: "second.mdx",+ renderScope: "page:/second",+ },+ };+ for (const root of [firstRoot, secondRoot]) {+ accumulator.stage(+ createRuntimeMutation({+ payload: [],+ storageChanges: [+ {+ root,+ payload: [+ {+ namespace: "fragment",+ patches: [+ {+ op: "replace",+ path: ["children", 0],+ value: { type: "text", value: root.identity.assetId },+ },+ ],+ },+ ],+ },+ ],+ result: {},+ invalidatesNamespaces: ["instances"],+ })+ );+ }++ expect(accumulator.state.instances?.get("first")?.children[1]).toEqual({+ type: "text",+ value: "first-asset",+ });+ expect(accumulator.state.instances?.get("second")?.children[1]).toEqual({+ type: "text",+ value: "second-asset",+ });++ expect(accumulator.complete({})).toMatchObject({+ noop: false,+ storageChanges: [{ root: firstRoot }, { root: secondRoot }],+ });+});diff --git a/packages/project-build/src/runtime/mutation.ts b/packages/project-build/src/runtime/mutation.tsindex 71d68a6051..68661adc60 100644--- a/packages/project-build/src/runtime/mutation.ts+++ b/packages/project-build/src/runtime/mutation.ts@@ -1,7 +1,37 @@+import type { Instance } from "@webstudio-is/sdk";import type { BuilderNamespace } from "../contracts/namespaces";import type { BuilderPatchChange } from "../contracts/patch";import type { BuilderState } from "../state/builder-state";import { applyBuilderPatchTransactions } from "../state/patch";+import {+ projectContentStorageChanges,+ type ContentStorageRoot,+} from "./content-storage";++export type ContentStoragePatchChange =+ | BuilderPatchChange+ | { namespace: "fragment"; patches: BuilderPatchChange["patches"] };++export type ContentStorageChange = {+ root: Extract<ContentStorageRoot, { type: "external" }>;+ payload: ContentStoragePatchChange[];+ copySource?: Readonly<{+ root: ContentStorageRoot;+ instanceId: Instance["id"];+ }>;+ mdxInsert?: Readonly<{+ source: string;+ parentInstanceId: Instance["id"];+ childIndex: number;+ position: "append" | "prepend" | "replace" | "index";+ instanceIds: readonly Instance["id"][];+ rootInstanceIds: readonly Instance["id"][];+ }>;+};++export const hasContentStorageChange = (change: ContentStorageChange) =>+ change.mdxInsert !== undefined ||+ change.payload.some(({ patches }) => patches.length > 0);export type BuilderRuntimeMutation<Result extends Record<string, unknown> = Record<string, unknown>,@@ -10,25 +40,80 @@ export type BuilderRuntimeMutation<payload: BuilderPatchChange[];result: Result;invalidatesNamespaces: readonly BuilderNamespace[];+ storageChanges?: ContentStorageChange[];+ persistenceOrder?: "storage-first" | "project-first";noop: boolean;};+// Moving authored records into project ownership is the one serial persistence+// case where saving the project first avoids deleting the only durable copy.+// The inverse move remains storage-first so the external destination exists+// before the project source is removed.+export const getRuntimeMutationPersistenceOrder = (+ mutation: Pick<+ BuilderRuntimeMutation,+ "payload" | "storageChanges" | "persistenceOrder"+ >+): "storage-first" | "project-first" => {+ if (+ "persistenceOrder" in mutation &&+ mutation.persistenceOrder !== undefined+ ) {+ return mutation.persistenceOrder;+ }+ const projectAdds = new Set(+ mutation.payload.flatMap(({ namespace, patches }) =>+ patches.flatMap((patch) =>+ patch.op === "add" &&+ patch.path.length === 1 &&+ typeof patch.path[0] === "string"+ ? [JSON.stringify([namespace, patch.path[0]])]+ : []+ )+ )+ );+ const storageRemovals = new Set(+ (mutation.storageChanges ?? []).flatMap(({ payload }) =>+ payload.flatMap(({ namespace, patches }) =>+ patches.flatMap((patch) =>+ patch.op === "remove" &&+ patch.path.length === 1 &&+ typeof patch.path[0] === "string"+ ? [JSON.stringify([namespace, patch.path[0]])]+ : []+ )+ )+ )+ );+ return Array.from(projectAdds).some((id) => storageRemovals.has(id))+ ? "project-first"+ : "storage-first";+};+export const createRuntimeMutation = <Result extends Record<string, unknown> = Record<string, unknown>,>({payload,result,invalidatesNamespaces,+ storageChanges,+ persistenceOrder,}: {payload: BuilderPatchChange[];result: Result;invalidatesNamespaces: readonly BuilderNamespace[];+ storageChanges?: ContentStorageChange[];+ persistenceOrder?: BuilderRuntimeMutation["persistenceOrder"];}): BuilderRuntimeMutation<Result> => ({kind: "mutation",payload,result,invalidatesNamespaces,- noop: payload.length === 0,+ storageChanges,+ ...(persistenceOrder === undefined ? {} : { persistenceOrder }),+ noop:+ payload.length === 0 &&+ storageChanges?.some(hasContentStorageChange) !== true,});export const createRuntimeMutationAccumulator = (@@ -37,6 +122,7 @@ export const createRuntimeMutationAccumulator = (let state = initialState;const changes = new Map<BuilderNamespace, BuilderPatchChange>();const invalidatesNamespaces = new Set<BuilderNamespace>();+ const storageChanges: ContentStorageChange[] = [];const stage = <Result extends Record<string, unknown>>(mutation: BuilderRuntimeMutation<Result>@@ -55,9 +141,17 @@ export const createRuntimeMutationAccumulator = (for (const namespace of mutation.invalidatesNamespaces) {invalidatesNamespaces.add(namespace);}- if (mutation.payload.length > 0) {+ storageChanges.push(...(mutation.storageChanges ?? []));+ const stagedPayload = [+ ...mutation.payload,+ ...projectContentStorageChanges({+ state,+ changes: mutation.storageChanges ?? [],+ }),+ ];+ if (stagedPayload.length > 0) {state = applyBuilderPatchTransactions(state, [- { id: "runtime-mutation-stage", payload: mutation.payload },+ { id: "runtime-mutation-stage", payload: stagedPayload },]).state;}return mutation.result;@@ -68,6 +162,7 @@ export const createRuntimeMutationAccumulator = (payload: Array.from(changes.values()),result,invalidatesNamespaces: Array.from(invalidatesNamespaces),+ storageChanges: storageChanges.length === 0 ? undefined : storageChanges,});return {diff --git a/packages/project-build/src/runtime/output-schemas.ts b/packages/project-build/src/runtime/output-schemas.tsindex 49d7750f40..b65ca543ae 100644--- a/packages/project-build/src/runtime/output-schemas.ts+++ b/packages/project-build/src/runtime/output-schemas.ts@@ -11,6 +11,9 @@ import {projectMeta,prop,instance,+ contentBlockExternalContentIdentity,+ contentBlockDiagnostic,+ contentBlockSource,} from "@webstudio-is/sdk";import {assetQueryResultMode,@@ -32,6 +35,7 @@ import {} from "./component-insert-contract";import { expressionWarningSchema } from "./expression-validation";import { designTokenImportPlanEntrySchema } from "./design-token-import";+import { mdxPasteResult } from "./mdx-paste";const looseObject = <Shape extends z.ZodRawShape>(shape: Shape) =>z.looseObject(shape);@@ -46,6 +50,136 @@ const patchChange = z.object({namespace: z.enum(builderNamespaces),patches: z.array(builderPatchSchema),});+const contentStoragePatchChange = z.union([+ patchChange,+ z.object({+ namespace: z.literal("fragment"),+ patches: z.array(builderPatchSchema),+ }),+]);++const externalContentStorageRoot = z.object({+ type: z.literal("external"),+ identity: contentBlockExternalContentIdentity,+});+const contentStorageRoot = z.discriminatedUnion("type", [+ z.object({ type: z.literal("project") }),+ externalContentStorageRoot,+]);++const contentBlockSourceInspection = z.object({+ blockInstanceId: z.string(),+ renderScope: z.string(),+ configuredSource: contentBlockSource.optional(),+ resolvedIdentity: contentBlockExternalContentIdentity.optional(),+ sessionStatus: z.enum([+ "disconnected",+ "saved",+ "pending",+ "conflicting",+ "cancelled",+ "recoverable",+ "failed",+ ]),+ pending: z.boolean(),+ diagnostics: z.array(contentBlockDiagnostic),+ capabilities: z.object({+ canConnect: z.boolean(),+ canSwitch: z.boolean(),+ canDisconnectWithCopy: z.boolean(),+ canEdit: z.boolean(),+ canRetry: z.boolean(),+ canReloadRemote: z.boolean(),+ canCopyUnsavedSource: z.boolean(),+ }),+ repairRoutes: z.array(+ z.enum([+ "open-file",+ "retry",+ "reload-remote",+ "copy-unsaved-mdx",+ "disconnect-with-copy",+ ])+ ),+});+const contentBlockLifecyclePlan = z.object({+ action: z.enum(["connect", "switch", "disconnect"]),+ changesProject: z.boolean(),+ storageWrites: z.array(+ z.object({+ identity: contentBlockExternalContentIdentity,+ expectedRevision: z.string(),+ })+ ),+ diagnostics: z.array(contentBlockDiagnostic),+ persistenceOrder: z.enum(["none", "storage-before-project"]),+ persistence: z+ .object({+ status: z.enum(["complete", "partial", "failed"]),+ steps: z.array(+ z.object({+ type: z.enum(["asset", "project"]),+ status: z.enum(["saved", "failed", "not-attempted"]),+ root: contentBlockExternalContentIdentity.optional(),+ code: z.string().optional(),+ message: z.string().optional(),+ })+ ),+ retry: z.object({+ replan: z.literal(true),+ roots: z.array(contentBlockExternalContentIdentity),+ project: z.boolean(),+ }),+ })+ .optional(),+});+const contentBlockApplicationResult = z.object({+ status: z.enum(["complete", "partial", "confirmation-required", "blocked"]),+ code: z.string().optional(),+ message: z.string().optional(),+ source: contentBlockSourceInspection,+ plan: contentBlockLifecyclePlan.optional(),+ confirmation: z+ .object({ token: z.string(), expiresAt: z.string() })+ .optional(),+});+const contentBlockRecoveryResult = z.object({+ status: z.enum(["complete", "partial", "blocked"]),+ code: z.string().optional(),+ message: z.string().optional(),+ source: contentBlockSourceInspection,+ localMdx: z.string().optional(),+ changedAsset: z.boolean(),+});+const contentBlockTemplateMigrationResult = z.object({+ status: z.enum(["complete", "partial", "blocked", "confirmation-required"]),+ code: z.string().optional(),+ message: z.string().optional(),+ discoveryComplete: z.boolean(),+ updateCount: z.number().int().nonnegative(),+ omissionCount: z.number().int().nonnegative(),+ changedAsset: z.boolean(),+ files: z.array(+ z.object({+ assetId: z.string(),+ revision: z.string().optional(),+ contentRef: z.string(),+ changed: z.boolean().optional(),+ status: z.enum(["updated", "unchanged", "failed"]).optional(),+ updateCount: z.number().int().nonnegative(),+ omissionCount: z.number().int().nonnegative(),+ diagnostics: z.array(+ z.looseObject({ code: z.string(), message: z.string() })+ ),+ })+ ),+ diagnostics: z+ .array(z.looseObject({ code: z.string(), message: z.string() }))+ .optional(),+ confirmation: z+ .object({ token: z.string(), expiresAt: z.string() })+ .optional(),+});export const pageDraftOutputHint ="True when the page is a draft. Missing or false means the page is publishable.";@@ -60,9 +194,58 @@ export const createRuntimeMutationExecutionSchema = <payload: z.array(patchChange),result,invalidatesNamespaces: z.array(z.enum(builderNamespaces)),+ storageChanges: z+ .array(+ z.object({+ root: externalContentStorageRoot,+ payload: z.array(contentStoragePatchChange),+ copySource: z+ .object({+ root: contentStorageRoot,+ instanceId: z.string().min(1),+ })+ .optional(),+ mdxInsert: z+ .object({+ source: z.string(),+ parentInstanceId: z.string(),+ childIndex: z.number().int().nonnegative(),+ position: z.enum(["append", "prepend", "replace", "index"]),+ instanceIds: z.array(z.string()),+ rootInstanceIds: z.array(z.string()),+ })+ .optional(),+ })+ )+ .optional(),+ persistenceOrder: z.enum(["storage-first", "project-first"]).optional(),noop: z.boolean(),});+const contentBlockSemanticEditResult = z.object({+ status: z.enum(["complete", "partial", "blocked"]),+ code: z.string().optional(),+ message: z.string().optional(),+ result: z+ .object({+ result: z.looseObject({}),+ noop: z.boolean(),+ })+ .optional(),+ changedAsset: z.boolean(),+ persistence: z+ .object({+ status: z.enum(["complete", "partial", "failed"]),+ steps: z.array(z.looseObject({})),+ retry: z.object({+ replan: z.literal(true),+ roots: z.array(contentBlockExternalContentIdentity),+ project: z.boolean(),+ }),+ })+ .optional(),+});+const pageSummary = looseObject({id,name: z.string(),@@ -411,6 +594,14 @@ export const runtimeOutputSchemas = {}),"pageTree.move": looseObject({ childId: id }),"pageTree.reparentOrphans": looseObject({}),+ "contentBlocks.inspectSource": contentBlockSourceInspection,+ "contentBlocks.connectSource": contentBlockApplicationResult,+ "contentBlocks.switchSource": contentBlockApplicationResult,+ "contentBlocks.disconnectSource": contentBlockApplicationResult,+ "contentBlocks.recoverSource": contentBlockRecoveryResult,+ "contentBlocks.semanticEdit": contentBlockSemanticEditResult,+ "contentBlocks.migrateTemplateReferences":+ contentBlockTemplateMigrationResult,"instances.list": looseObject({instances: z.array(instanceSummary.extend({ record: instance.optional() })),...outputPage,@@ -500,6 +691,7 @@ export const runtimeOutputSchemas = {warnings: expressionWarnings.optional(),}),"instances.insertFragment": fragmentInsertResult,+ "instances.insertMdxText": mdxPasteResult,"slots.attach": looseObject({ slotId: id, fragmentId: id }),"slots.extract": looseObject({ slotId: id, fragmentId: id, instanceId: id }),"instances.move": instanceIdsResult,diff --git a/packages/project-build/src/runtime/pre-publish-audit.test.tsx b/packages/project-build/src/runtime/pre-publish-audit.test.tsxindex 6bdbec4c8e..0556e543d6 100644--- a/packages/project-build/src/runtime/pre-publish-audit.test.tsx+++ b/packages/project-build/src/runtime/pre-publish-audit.test.tsx@@ -1,6 +1,7 @@import { expect, test } from "vitest";import {ROOT_FOLDER_ID,+ blockComponent,type Folder,type Page,type Pages,@@ -49,6 +50,7 @@ const runAudit = ({...data,dataSources: new Map(),resources: new Map(),+ assets: new Map(),metas: componentMetas,});@@ -218,6 +220,7 @@ test("blocks publishing when required audit input is unavailable", () => {props,dataSources: new Map(),resources: new Map(),+ assets: new Map(),metas: componentMetas,});@@ -250,6 +253,7 @@ test("includes existing resource integrity checks in the audit pipeline", () =>],]),resources: new Map(),+ assets: new Map(),metas: componentMetas,});@@ -266,3 +270,32 @@ test("includes existing resource integrity checks in the audit pipeline", () =>},]);});++test("includes Content Block source integrity checks in the audit pipeline", () => {+ const { instances, props } = renderData(<$.Body ws:id="body"></$.Body>);+ instances.set("block", {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [],+ });+ props.set("source", {+ id: "source",+ instanceId: "block",+ name: "src",+ type: "asset",+ value: "missing-post",+ });++ expect(runAudit({ instances, props })).toContainEqual({+ ruleId: "content-block-source-integrity",+ severity: "error",+ message:+ 'Content Block source prop "source" references missing Asset "missing-post".',+ location: {+ instanceId: "block",+ propId: "source",+ assetId: "missing-post",+ },+ });+});diff --git a/packages/project-build/src/runtime/pre-publish-audit.ts b/packages/project-build/src/runtime/pre-publish-audit.tsindex 01fbbaea1f..f6a9e51041 100644--- a/packages/project-build/src/runtime/pre-publish-audit.ts+++ b/packages/project-build/src/runtime/pre-publish-audit.ts@@ -1,6 +1,7 @@import {getPagePath,getPublishablePages,+ type Assets,type DataSources,type Instances,type Pages,@@ -26,6 +27,7 @@ export type PrePublishAuditFinding = {dataSourceId?: string;propId?: string;resourceId?: string;+ assetId?: string;};};@@ -35,6 +37,7 @@ type PrePublishAuditContext = {props: Props;dataSources: DataSources;resources: Resources;+ assets: Assets;metas: Map<string, WsComponentMeta>;};@@ -82,30 +85,50 @@ const checkHtmlContentModel: PrePublishAuditCheck = ({return findings;};-const checkResourceIntegrity: PrePublishAuditCheck = ({+const checkBuildIntegrity: PrePublishAuditCheck = ({dataSources,props,resources,+ instances,+ assets,}) =>getBuildIntegrityIssues({dataSources: dataSources.values(),props: props.values(),resources: resources.values(),+ instances: instances.values(),+ assets: assets.values(),}).map((issue) => ({- ruleId: "resource-integrity",+ ruleId:+ issue.type === "missingResource"+ ? "resource-integrity"+ : "content-block-source-integrity",severity: "error",message: formatBuildIntegrityIssue(issue),location: {- ...(issue.source === "dataSource"- ? { dataSourceId: issue.dataSourceId }- : { propId: issue.propId }),- resourceId: issue.resourceId,+ ...(issue.type === "missingResource"+ ? {+ ...(issue.source === "dataSource"+ ? { dataSourceId: issue.dataSourceId }+ : { propId: issue.propId }),+ resourceId: issue.resourceId,+ }+ : {+ instanceId: issue.blockInstanceId,+ ...(issue.type === "duplicateContentBlockSource"+ ? { propId: issue.propIds[0] }+ : { propId: issue.propId }),+ ...(issue.type === "missingContentBlockSourceAsset" ||+ issue.type === "incompatibleContentBlockSourceAsset"+ ? { assetId: issue.assetId }+ : {}),+ }),},}));const prePublishAuditChecks: PrePublishAuditCheck[] = [checkHtmlContentModel,- checkResourceIntegrity,+ checkBuildIntegrity,];export const runPrePublishAudit = ({diff --git a/packages/project-build/src/runtime/published-mdx.test.ts b/packages/project-build/src/runtime/published-mdx.test.tsnew file mode 100644index 0000000000..a52bf07e3b--- /dev/null+++ b/packages/project-build/src/runtime/published-mdx.test.ts@@ -0,0 +1,467 @@+import { describe, expect, test } from "vitest";+import type { ContentArtifactV1 } from "@webstudio-is/content-engine";+import {+ discoverMdxBodyAssetReferences,+ parseMdxDocument,+} from "@webstudio-is/content-engine/mdx";+import type { Instance, WebstudioData } from "@webstudio-is/sdk";+import { materializePublishedMdx } from "./published-mdx";++const revision = (value: string) => `sha256:${value.repeat(64)}` as const;++const createData = ({+ sourceType = "asset",+ expression = '"article"',+ withTemplate = false,+}: {+ sourceType?: "asset" | "expression";+ expression?: string;+ withTemplate?: boolean;+}) => {+ const block: Instance = {+ type: "instance",+ id: "block",+ component: "ws:block",+ children: withTemplate ? [{ type: "id", value: "templates" }] : [],+ };+ const instances: Instance[] = [block];+ if (withTemplate) {+ instances.push(+ {+ type: "instance",+ id: "templates",+ component: "ws:block-template",+ children: [{ type: "id", value: "hero" }],+ },+ {+ type: "instance",+ id: "hero",+ component: "ws:element",+ tag: "section",+ label: "Hero",+ children: [{ type: "text", value: "Template body" }],+ }+ );+ }+ return {+ instances: new Map(instances.map((instance) => [instance.id, instance])),+ props: new Map([+ [+ "source",+ {+ id: "source",+ instanceId: "block",+ name: "src",+ type: sourceType,+ value: sourceType === "asset" ? "article" : expression,+ },+ ],+ ]),+ dataSources: new Map(),+ resources: new Map(),+ styleSources: new Map(),+ styleSourceSelections: new Map(),+ styles: new Map(),+ breakpoints: new Map(),+ assets: new Map(),+ } as Omit<WebstudioData, "pages">;+};++const createArtifact = (+ files: readonly { id: string; source: string; revision?: string }[],+ assetValueReferences?: ContentArtifactV1["assetValueReferences"]+) =>+ ({+ format: "webstudio-content-database",+ version: 1,+ assetRevision: revision("a"),+ documents: files.map(({ id, source, revision: fileRevision }) => ({+ _id: id,+ _type: "asset.file",+ name: `${id}.mdx`,+ path: `${id}.mdx`,+ key: id,+ extension: "mdx",+ mimeType: "text/mdx",+ size: source.length,+ revision: fileRevision ?? revision(id === "article" ? "b" : "c"),+ contentRef: `${id}.mdx`,+ })),+ contents: Object.fromEntries(+ files.map(({ id, source }) => [`${id}.mdx`, source])+ ),+ assetValueReferences,+ fieldCatalog: { canonicalRevision: revision("a"), fields: {} },+ integrity: { algorithm: "sha256", checksum: revision("d") },+ }) as ContentArtifactV1;++const getFragmentText = (+ fragment: Awaited<+ ReturnType<typeof materializePublishedMdx>+ >["roots"][number]["fragment"]+) =>+ JSON.stringify(fragment.instances.flatMap((instance) => instance.children));++describe("published MDX materialization", () => {+ test("materializes a direct source before rendering", async () => {+ const result = await materializePublishedMdx({+ route: "/blog/article",+ data: createData({}),+ artifact: createArtifact([{ id: "article", source: "# Published" }]),+ metas: new Map(),+ projectId: "project",+ });++ expect(result.roots).toHaveLength(1);+ expect(result.roots[0].identity).toMatchObject({+ blockInstanceId: "block",+ assetId: "article",+ contentRef: "article.mdx",+ renderScope: "route:/blog/article:block:block",+ });+ expect(getFragmentText(result.roots[0].fragment)).toContain("Published");+ });++ test("materializes only rendered blocks and ignores template definitions", async () => {+ const data = createData({});+ data.instances.set("template-block", {+ type: "instance",+ id: "template-block",+ component: "ws:block",+ children: [],+ });+ data.props.set("template-source", {+ id: "template-source",+ instanceId: "template-block",+ name: "src",+ type: "asset",+ value: "template-article",+ });++ const result = await materializePublishedMdx({+ route: "/",+ data,+ artifact: createArtifact([+ { id: "article", source: "# Rendered" },+ { id: "template-article", source: "# Definition only" },+ ]),+ metas: new Map(),+ projectId: "project",+ blockInstanceIds: new Set(["block"]),+ });++ expect(+ result.roots.map(({ identity }) => identity.blockInstanceId)+ ).toEqual(["block"]);+ });++ test("ignores src props on instances that are not Content Blocks", async () => {+ const data = createData({});+ const block = data.instances.get("block");+ if (block === undefined) {+ throw new Error("Expected Content Block");+ }+ data.instances.set("block", { ...block, component: "ws:element" });++ const result = await materializePublishedMdx({+ route: "/",+ data,+ artifact: createArtifact([{ id: "article", source: "# Private" }]),+ metas: new Map(),+ projectId: "project",+ });++ expect(result.roots).toEqual([]);+ });++ test("materializes the exact candidate for a static expression source", async () => {+ const result = await materializePublishedMdx({+ route: "/blog/:slug",+ data: createData({ sourceType: "expression" }),+ artifact: createArtifact([+ { id: "article", source: "# Article" },+ { id: "other", source: "# Other" },+ ]),+ metas: new Map(),+ projectId: "project",+ });++ expect(result.roots.map(({ identity }) => identity.assetId)).toEqual([+ "article",+ ]);+ });++ test("rejects an unbounded dynamic source instead of exposing unrelated MDX", async () => {+ await expect(+ materializePublishedMdx({+ route: "/blog/:slug",+ data: createData({ sourceType: "expression", expression: "post.body" }),+ artifact: createArtifact([+ { id: "article", source: "# Article" },+ { id: "private", source: "# Private" },+ ]),+ metas: new Map(),+ projectId: "project",+ })+ ).rejects.toThrow("no bounded dynamic MDX dependency set");+ });++ test("materializes only the bounded dynamic candidates with isolated variants", async () => {+ const materialize = (articleRevision?: string) =>+ materializePublishedMdx({+ route: "/blog/:slug",+ data: createData({ sourceType: "expression", expression: "post.mdx" }),+ artifact: createArtifact([+ { id: "article", source: "# Article", revision: articleRevision },+ { id: "other", source: "# Other" },+ { id: "private", source: "# Private" },+ ]),+ metas: new Map(),+ projectId: "project",+ dynamicAssetIdsByBlock: new Map([["block", ["article", "other"]]]),+ });+ const result = await materialize();+ const changed = await materialize(revision("g"));++ expect(result.roots.map(({ identity }) => identity.assetId)).toEqual([+ "article",+ "other",+ ]);+ expect(result.roots.map(({ identity }) => identity.renderScope)).toEqual([+ "route:/blog/:slug:block:block:asset:article",+ "route:/blog/:slug:block:block:asset:other",+ ]);+ expect(result.roots[0].dependencyRevision).not.toBe(+ changed.roots[0].dependencyRevision+ );+ });++ test("materializes more sources than the bounded parse cache retains", async () => {+ const files = Array.from({ length: 21 }, (_, index) => ({+ id: `article-${index}`,+ source: `# Article ${index}`,+ }));+ const result = await materializePublishedMdx({+ route: "/articles",+ data: createData({ sourceType: "expression", expression: "post.mdx" }),+ artifact: createArtifact(files),+ metas: new Map(),+ projectId: "project",+ dynamicAssetIdsByBlock: new Map([["block", files.map(({ id }) => id)]]),+ });++ expect(result.roots).toHaveLength(21);+ });++ test("omits an unresolved template subtree and keeps valid siblings", async () => {+ const result = await materializePublishedMdx({+ route: "/",+ data: createData({}),+ artifact: createArtifact([+ {+ id: "article",+ source:+ '<ws.element ws:name="Missing">\n\n## Hidden\n\n</ws.element>\n\n# Visible',+ },+ ]),+ metas: new Map(),+ projectId: "project",+ });++ expect(getFragmentText(result.roots[0].fragment)).not.toContain("Hidden");+ expect(getFragmentText(result.roots[0].fragment)).toContain("Visible");+ expect(result.warnings).toEqual([+ expect.objectContaining({+ route: "/",+ diagnostic: expect.objectContaining({+ code: "unresolved-template",+ templateName: "Missing",+ blockInstanceId: "block",+ renderScope: "route:/:block:block",+ sourceRange: expect.objectContaining({}),+ }),+ }),+ ]);+ });++ test("includes template revisions in dependency identity", async () => {+ const materialize = (templateText: string) => {+ const data = createData({ withTemplate: true });+ data.instances.get("hero")!.children = [+ { type: "text", value: templateText },+ ];+ return materializePublishedMdx({+ route: "/",+ data,+ artifact: createArtifact([+ {+ id: "article",+ source: '<ws.element ws:name="Hero" />',+ },+ ]),+ metas: new Map(),+ projectId: "project",+ });+ };++ const first = await materialize("First");+ const second = await materialize("Second");++ expect(first.roots[0].dependencyRevision).not.toBe(+ second.roots[0].dependencyRevision+ );+ });++ test("includes unresolved template names and referenced Asset revisions in dependency identity", async () => {+ const references = {+ article: [{ path: ["unmatched"], assetId: "image", suffix: "#hero" }],+ };+ const materialize = (imageRevision: string, withTemplate: boolean) =>+ materializePublishedMdx({+ route: "/",+ data: createData({ withTemplate }),+ artifact: createArtifact(+ [+ {+ id: "article",+ source: '<ws.element ws:name="Hero" />',+ },+ { id: "image", source: "image", revision: imageRevision },+ ],+ references+ ),+ metas: new Map(),+ projectId: "project",+ });++ const unresolved = await materialize(revision("e"), false);+ const resolved = await materialize(revision("e"), true);+ const replacedAsset = await materialize(revision("f"), false);++ expect(unresolved.roots[0].templateNames).toEqual(["Hero"]);+ expect(unresolved.roots[0].dependencyRevision).not.toBe(+ resolved.roots[0].dependencyRevision+ );+ expect(unresolved.roots[0].dependencyRevision).not.toBe(+ replacedAsset.roots[0].dependencyRevision+ );+ });++ test("emits ignored authored prop warnings with publication context", async () => {+ const result = await materializePublishedMdx({+ route: "/articles/:slug",+ data: createData({ withTemplate: true }),+ artifact: createArtifact([+ {+ id: "article",+ source: '<ws.element ws:name="Hero" mystery="preserved" />',+ },+ ]),+ metas: new Map(),+ projectId: "project",+ });++ expect(result.warnings).toEqual([+ expect.objectContaining({+ route: "/articles/:slug",+ diagnostic: expect.objectContaining({+ code: "ignored-template-prop",+ reason: "unknown",+ propName: "mystery",+ assetId: "article",+ contentRef: "article.mdx",+ renderScope: "route:/articles/:slug:block:block",+ }),+ }),+ ]);+ });++ test("materializes referenced Assets for the published URL rewrite pipeline", async () => {+ const source =+ '<ws.element ws:tag="img" src="./images/hero.png" alt="Hero" />';+ const document = await parseMdxDocument({ source });+ const result = await materializePublishedMdx({+ route: "/",+ data: createData({}),+ artifact: createArtifact([{ id: "article", source }], {+ article: discoverMdxBodyAssetReferences({+ document,+ sourcePath: "article.mdx",+ assetIdsByPath: new Map([["images/hero.png", "hero-image"]]),+ }),+ }),+ metas: new Map(),+ projectId: "project",+ });++ expect(result.roots[0].fragment.props).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ name: "src",+ type: "asset",+ value: "hero-image",+ }),+ ])+ );+ });++ test("fails when a required source is missing or invalid", async () => {+ await expect(+ materializePublishedMdx({+ route: "/",+ data: createData({}),+ artifact: createArtifact([]),+ metas: new Map(),+ projectId: "project",+ })+ ).rejects.toThrow('requires unavailable MDX Asset "article"');++ await expect(+ materializePublishedMdx({+ route: "/",+ data: createData({}),+ artifact: createArtifact([{ id: "article", source: "{unsafe}" }]),+ metas: new Map(),+ projectId: "project",+ })+ ).rejects.toThrow();+ });++ test("rejects an invalid document dependency graph", async () => {+ const artifact = createArtifact([{ id: "article", source: "# Article" }]);+ artifact.documentGraph = {+ format: "webstudio-document-graph",+ version: 1,+ nodes: [+ {+ id: "article",+ revision: revision("b"),+ contentRef: "article.mdx",+ format: "mdx",+ },+ ],+ edges: [+ {+ sourceId: "missing",+ referenceId: "#frontmatter/author",+ reference: {+ documentId: "article",+ revision: revision("b"),+ representation: { type: "markdown-frontmatter" },+ },+ },+ ],+ integrity: { algorithm: "sha256", checksum: revision("d") },+ };++ await expect(+ materializePublishedMdx({+ route: "/",+ data: createData({}),+ artifact,+ metas: new Map(),+ projectId: "project",+ })+ ).rejects.toThrow("Document graph source missing does not exist");+ });+});diff --git a/packages/project-build/src/runtime/published-mdx.ts b/packages/project-build/src/runtime/published-mdx.tsnew file mode 100644index 0000000000..e853edd063--- /dev/null+++ b/packages/project-build/src/runtime/published-mdx.ts@@ -0,0 +1,322 @@+import {+ parseMdxDocument,+ type MdxDocument,+} from "@webstudio-is/content-engine/mdx";+import type {+ AssetValueReference,+ ContentArtifactV1,+} from "@webstudio-is/content-engine";+import {+ contentEngineLimits,+ createDocumentGraph,+ getDocumentGraphClosure,+} from "@webstudio-is/content-engine";+import {+ blockComponent,+ getAssetContentHash,+ getContentBlockSource,+ type ContentBlockDiagnostic,+ type ContentBlockExternalContentIdentity,+ type ContentBlockSource,+ type WebstudioData,+ type WsComponentMeta,+} from "@webstudio-is/sdk";+import { parseJsonExpression } from "@webstudio-is/expression";+import { materializeMdxAuthoredContent } from "./mdx-authored-content";+import {+ materializeMdxTemplates,+ type MdxTemplateDependency,+} from "./mdx-materialization";+import { resolveMdxTemplates } from "./mdx-template-resolution";++export type PublishedMdxWarning = Readonly<{+ route: string;+ diagnostic: Extract<ContentBlockDiagnostic, { severity: "warning" }>;+}>;++export type PublishedMdxRoot = Readonly<{+ source: ContentBlockSource;+ dynamic: boolean;+ identity: ContentBlockExternalContentIdentity;+ document: MdxDocument;+ fragment: ReturnType<typeof materializeMdxAuthoredContent>["fragment"];+ templateDependencies: readonly MdxTemplateDependency[];+ templateNames: readonly string[];+ dependencyRevision: `sha256:${string}`;+}>;++const publishedMdxMaterializerRevision = 1;++export const createPublishedMdxMaterializationCache = () => ({+ documents: new Map<string, Promise<MdxDocument>>(),+});++type PublishedMdxMaterializationCache = ReturnType<+ typeof createPublishedMdxMaterializationCache+>;++const getMdxDocuments = (artifact: ContentArtifactV1) =>+ artifact.documents+ .filter(+ (document) =>+ document.extension?.toLowerCase() === "mdx" ||+ document.mimeType === "text/mdx"+ )+ .sort((left, right) => left._id.localeCompare(right._id));++const getNestedDocumentDependencies = ({+ artifact,+ assetId,+}: {+ artifact: ContentArtifactV1;+ assetId: string;+}) => {+ if (artifact.documentGraph === undefined) {+ return [];+ }+ const graph = createDocumentGraph(artifact.documentGraph);+ if (graph.nodes.some(({ id }) => id === assetId) === false) {+ return [];+ }+ return getDocumentGraphClosure({ graph, rootIds: [assetId] })+ .map(({ id, revision, contentRef }) => ({ id, revision, contentRef }))+ .sort((left, right) => left.id.localeCompare(right.id));+};++const createDependencyRevision = async ({+ identity,+ nestedDocuments,+ assetReferences,+ assetDependencies,+ templateNames,+ templateDependencies,+}: {+ identity: ContentBlockExternalContentIdentity;+ nestedDocuments: ReturnType<typeof getNestedDocumentDependencies>;+ assetReferences: readonly AssetValueReference[];+ assetDependencies: readonly Readonly<{+ id: string;+ contentRef: string;+ revision?: string;+ }>[];+ templateNames: readonly string[];+ templateDependencies: readonly MdxTemplateDependency[];+}) =>+ `sha256:${await getAssetContentHash(+ new TextEncoder().encode(+ JSON.stringify({+ materializerRevision: publishedMdxMaterializerRevision,+ identity,+ nestedDocuments,+ assetReferences: [...assetReferences]+ .map(({ assetId, suffix }) => ({ assetId, suffix }))+ .sort((left, right) =>+ `${left.assetId}${left.suffix ?? ""}`.localeCompare(+ `${right.assetId}${right.suffix ?? ""}`+ )+ ),+ assetDependencies: [...assetDependencies].sort((left, right) =>+ left.id.localeCompare(right.id)+ ),+ templateNames: [...templateNames].sort(),+ templateDependencies: [...templateDependencies].sort((left, right) =>+ left.templateInstanceId.localeCompare(right.templateInstanceId)+ ),+ })+ )+ )}` as const;++export const materializePublishedMdx = async ({+ route,+ data,+ artifact,+ metas,+ projectId,+ cache = createPublishedMdxMaterializationCache(),+ dynamicAssetIdsByBlock = new Map(),+ blockInstanceIds,+}: {+ route: string;+ data: Omit<WebstudioData, "pages">;+ artifact: ContentArtifactV1;+ metas: Map<string, WsComponentMeta>;+ projectId: string;+ cache?: PublishedMdxMaterializationCache;+ dynamicAssetIdsByBlock?: ReadonlyMap<string, readonly string[]>;+ blockInstanceIds?: ReadonlySet<string>;+}): Promise<{+ roots: readonly PublishedMdxRoot[];+ warnings: readonly PublishedMdxWarning[];+}> => {+ const documents = getMdxDocuments(artifact);+ const roots: PublishedMdxRoot[] = [];+ const warnings: PublishedMdxWarning[] = [];+ for (const block of data.instances.values()) {+ if (+ block.component !== blockComponent ||+ (blockInstanceIds !== undefined &&+ blockInstanceIds.has(block.id) === false)+ ) {+ continue;+ }+ const source = getContentBlockSource({+ blockInstanceId: block.id,+ props: data.props.values(),+ });+ if (source === undefined) {+ continue;+ }+ const staticAssetId =+ source.type === "asset"+ ? source.assetId+ : parseJsonExpression(source.value);+ const isDynamicSource = typeof staticAssetId !== "string";+ const resolvedAssetIds =+ typeof staticAssetId === "string" && staticAssetId.length > 0+ ? [staticAssetId]+ : (dynamicAssetIdsByBlock.get(block.id) ?? []);+ if (resolvedAssetIds.length > contentEngineLimits.candidateDocuments) {+ throw new Error(+ `Published Content Block "${block.id}" exceeds the safe MDX candidate limit`+ );+ }+ if (resolvedAssetIds.length === 0) {+ throw new Error(+ `Published Content Block "${block.id}" has no bounded dynamic MDX dependency set`+ );+ }+ const resolvedAssetIdSet = new Set(resolvedAssetIds);+ const candidates = documents.filter(({ _id }) =>+ resolvedAssetIdSet.has(_id)+ );+ if (candidates.length !== resolvedAssetIdSet.size) {+ const unavailableAssetId = resolvedAssetIds.find(+ (assetId) => candidates.some(({ _id }) => _id === assetId) === false+ );+ throw new Error(+ `Published Content Block "${block.id}" requires unavailable MDX Asset "${unavailableAssetId}"`+ );+ }+ for (const candidate of candidates) {+ if (+ candidate.revision === undefined ||+ candidate.contentRef === undefined+ ) {+ throw new Error(+ `Published MDX Asset "${candidate._id}" has no revision identity`+ );+ }+ const sourceText = artifact.contents?.[candidate.contentRef];+ if (sourceText === undefined) {+ throw new Error(+ `Published MDX Asset "${candidate._id}" content is unavailable`+ );+ }+ const identity: ContentBlockExternalContentIdentity = {+ blockInstanceId: block.id,+ assetId: candidate._id,+ revision: candidate.revision,+ contentRef: candidate.contentRef,+ format: "mdx",+ renderScope: `route:${route}:block:${block.id}${+ isDynamicSource ? `:asset:${candidate._id}` : ""+ }`,+ };+ const documentKey = `${candidate._id}:${candidate.revision}:${candidate.contentRef}`;+ let parsedDocument = cache.documents.get(documentKey);+ if (parsedDocument === undefined) {+ if (cache.documents.size >= contentEngineLimits.hydratedFileCount) {+ const oldestKey = cache.documents.keys().next().value;+ if (oldestKey !== undefined) {+ cache.documents.delete(oldestKey);+ }+ }+ parsedDocument = parseMdxDocument({ source: sourceText });+ cache.documents.set(documentKey, parsedDocument);+ }+ const document = await parsedDocument;+ const resolution = resolveMdxTemplates({+ document,+ identity,+ instances: data.instances,+ metas,+ });+ const templates = await materializeMdxTemplates({+ identity,+ resolution,+ data,+ metas,+ projectId,+ });+ const referencedTemplateNames = Array.from(+ new Set(+ resolution.references.map((reference) => reference.templateName)+ )+ );+ const assetReferences =+ artifact.assetValueReferences?.[candidate._id] ?? [];+ const materialized = materializeMdxAuthoredContent({+ identity,+ document,+ templateMaterialization: templates,+ assetReferences,+ });+ if (+ materialized.fragment.instances.length > contentEngineLimits.mdxNodes ||+ materialized.fragment.props.length > contentEngineLimits.mdxProps+ ) {+ throw new Error("Published MDX materialization exceeds safe limits");+ }+ for (const diagnostic of templates.diagnostics) {+ if (diagnostic.severity === "warning") {+ warnings.push({ route, diagnostic });+ }+ }+ roots.push({+ source,+ dynamic: isDynamicSource,+ identity,+ document,+ fragment: materialized.fragment,+ templateDependencies: templates.dependencies.templates,+ templateNames: referencedTemplateNames,+ dependencyRevision: await createDependencyRevision({+ identity,+ nestedDocuments: getNestedDocumentDependencies({+ artifact,+ assetId: candidate._id,+ }),+ assetReferences,+ assetDependencies: assetReferences.map(({ assetId }) => {+ const asset = data.assets.get(assetId);+ const documentDependency = artifact.documents.find(+ ({ _id }) => _id === assetId+ );+ return {+ id: assetId,+ contentRef:+ asset?.name ?? documentDependency?.contentRef ?? "unavailable",+ ...(documentDependency?.revision === undefined+ ? {}+ : { revision: documentDependency.revision }),+ };+ }),+ templateNames: referencedTemplateNames,+ templateDependencies: templates.dependencies.templates,+ }),+ });+ }+ }+ const warningKeys = new Set<string>();+ return {+ roots,+ warnings: warnings.filter(({ route: warningRoute, diagnostic }) => {+ const key = JSON.stringify([warningRoute, diagnostic]);+ if (warningKeys.has(key)) {+ return false;+ }+ warningKeys.add(key);+ return true;+ }),+ };+};diff --git a/packages/project-build/src/runtime/registry.test.ts b/packages/project-build/src/runtime/registry.test.tsindex 420eb28db1..2c8b144846 100644--- a/packages/project-build/src/runtime/registry.test.ts+++ b/packages/project-build/src/runtime/registry.test.ts@@ -1,4 +1,4 @@-import { describe, expect, test } from "vitest";+import { describe, expect, test, vi } from "vitest";import {getInputJsonSchemaMetadata,toInputJsonSchemaObject,@@ -404,6 +404,172 @@ describe("builder runtime pages", () => {});describe("builder runtime read families", () => {+ test("exposes exact Content Block source inspection through the shared application", async () => {+ const inspectSource = vi.fn(async () => ({+ blockInstanceId: "block",+ renderScope: "page:/posts:item:one",+ configuredSource: { type: "asset" as const, assetId: "article" },+ resolvedIdentity: {+ blockInstanceId: "block",+ assetId: "article",+ revision: "sha256:article",+ contentRef: "article-revision.mdx",+ format: "mdx" as const,+ renderScope: "page:/posts:item:one",+ },+ sessionStatus: "saved" as const,+ pending: false,+ diagnostics: [],+ capabilities: {+ canConnect: false,+ canSwitch: true,+ canDisconnectWithCopy: true,+ canEdit: true,+ canRetry: false,+ canReloadRemote: false,+ canCopyUnsavedSource: false,+ },+ repairRoutes: ["open-file", "disconnect-with-copy"] as const,+ }));++ await expect(+ executeBuilderRuntimeOperation({+ id: "contentBlocks.inspectSource",+ state,+ input: {+ blockInstanceId: "block",+ renderScope: "page:/posts:item:one",+ },+ context: {+ createId: () => "unused",+ contentStorageApplication: {+ getMaterializedContent: () => [],+ preflightStorageChanges: async () => ({ status: "ready" as const }),+ saveStorageChanges: async () => ({+ status: "complete" as const,+ persistence: {+ status: "complete" as const,+ steps: [],+ retry: { replan: true as const, roots: [], project: false },+ },+ }),+ inspectSource,+ },+ },+ })+ ).resolves.toMatchObject({+ resolvedIdentity: {+ assetId: "article",+ renderScope: "page:/posts:item:one",+ },+ capabilities: { canEdit: true },+ repairRoutes: ["open-file", "disconnect-with-copy"],+ });+ expect(inspectSource).toHaveBeenCalledWith({+ blockInstanceId: "block",+ renderScope: "page:/posts:item:one",+ });+ });++ test("keeps recovery dry-runs non-mutating and exposes one-shot semantic editing", async () => {+ const inspection = {+ blockInstanceId: "block",+ renderScope: "page:/",+ sessionStatus: "failed" as const,+ pending: false,+ diagnostics: [],+ capabilities: {+ canConnect: false,+ canSwitch: true,+ canDisconnectWithCopy: false,+ canEdit: false,+ canRetry: true,+ canReloadRemote: false,+ canCopyUnsavedSource: true,+ },+ repairRoutes: ["retry" as const],+ };+ const recover = vi.fn(async () => ({+ status: "complete" as const,+ result: { inspection, changedAsset: false },+ }));+ const semanticEdit = vi.fn(async () => ({+ status: "complete" as const,+ result: {+ kind: "mutation" as const,+ payload: [],+ result: { updated: true },+ invalidatesNamespaces: [],+ storageChanges: [],+ noop: false,+ },+ }));+ const contentStorageApplication = {+ getMaterializedContent: () => [],+ preflightStorageChanges: async () => ({ status: "ready" as const }),+ saveStorageChanges: async () => ({+ status: "complete" as const,+ persistence: {+ status: "complete" as const,+ steps: [],+ retry: { replan: true as const, roots: [], project: false },+ },+ }),+ inspectSource: async () => inspection,+ recover,+ semanticEdit,+ };++ await executeBuilderRuntimeOperation({+ id: "contentBlocks.recoverSource",+ state,+ input: {+ blockInstanceId: "block",+ renderScope: "page:/",+ action: "retry",+ },+ context: {+ createId: () => "unused",+ applicationDryRun: true,+ contentStorageApplication,+ },+ });+ expect(recover).toHaveBeenCalledWith({+ blockInstanceId: "block",+ renderScope: "page:/",+ action: "retry",+ dryRun: true,+ });++ const edit = await executeBuilderRuntimeOperation<{+ status: string;+ result: Record<string, unknown>;+ }>({+ id: "contentBlocks.semanticEdit",+ state,+ input: {+ blockInstanceId: "block",+ renderScope: "page:/",+ operationId: "instances.updateText",+ input: { instanceId: "text", childIndex: 0, text: "Updated" },+ },+ context: { createId: () => "unused", contentStorageApplication },+ });+ expect(edit).toMatchObject({+ status: "complete",+ result: { result: { updated: true }, noop: false },+ });+ expect(edit.result).not.toHaveProperty("payload");+ expect(edit.result).not.toHaveProperty("storageChanges");+ expect(semanticEdit).toHaveBeenCalledWith({+ blockInstanceId: "block",+ renderScope: "page:/",+ operationId: "instances.updateText",+ input: { instanceId: "text", childIndex: 0, text: "Updated" },+ dryRun: false,+ });+ });+test("keeps representative high-volume compact lists within budget", () => {const sourceInstance = state.instances.get("heading")!;const sourceAsset = state.assets.get("asset")!;@@ -2220,6 +2386,16 @@ describe("builder runtime registry", () => {expect(getBuilderRuntimeOperation("pages.create").requiresConfirm).toBe(false);+ for (const operationId of [+ "instances.updateProps",+ "instances.replacePropText",+ "instances.deleteProps",+ "instances.bindProps",+ ] as const) {+ expect(getBuilderRuntimeOperation(operationId).requiresAssets).toBe(+ false+ );+ }});test("rejects client-supplied generated ids and hides generated id fields", () => {@@ -2355,6 +2531,7 @@ describe("builder runtime registry", () => {["runtimeUi.integrate", {}],["instances.insertComponent", { parentInstanceId: "body" }],["instances.insertCollection", { parentInstanceId: "body" }],+ ["instances.insertMdxText", { parentInstanceId: "body" }],["instances.insertFragment", { parentInstanceId: "body" }],["slots.attach", {}],["slots.extract", {}],diff --git a/packages/project-build/src/runtime/registry.ts b/packages/project-build/src/runtime/registry.tsindex eedfb71cd6..91c4e1d4c5 100644--- a/packages/project-build/src/runtime/registry.ts+++ b/packages/project-build/src/runtime/registry.ts@@ -11,11 +11,16 @@ import {} from "../contracts/input-schema";import {assetType,+ contentBlockSource,instanceFilterInput,type InputJsonSchema,} from "@webstudio-is/sdk";import { pageCopyNamespaces } from "../contracts/namespaces";-import { builderRuntimeContext, type BuilderRuntimeContext } from "./context";+import {+ builderRuntimeContext,+ type BuilderRuntimeContext,+ type ContentBlockSourceInspection,+} from "./context";import { z } from "zod";import * as assets from "./assets";import * as assetResources from "./asset-resources";@@ -28,6 +33,7 @@ import * as fonts from "./fonts";import * as instanceDuplicate from "./instance-duplicate";import * as instances from "./instances";import * as migrations from "./migrations";+import * as mdxPaste from "./mdx-paste";import * as pageCopy from "./page-copy";import * as pages from "./pages";import * as projectSettings from "./project-settings";@@ -37,8 +43,13 @@ import * as projectSearch from "./project-search";import * as slot from "./slot";import * as designTokenImport from "./design-token-import";import * as audit from "./audit";+import type { ContentBlockPersistenceResult } from "./content-block-application";import * as styles from "./styles";-import { getZodValidationIssues, throwBuilderValidationError } from "./errors";+import {+ getZodValidationIssues,+ throwBuilderRuntimeError,+ throwBuilderValidationError,+} from "./errors";import {createRuntimeMutationExecutionSchema,getRuntimeOutputSchema,@@ -51,6 +62,15 @@ import {bindExpressionInput,getScopedExpressionWarnings,} from "./expression-scope";+import {+ createContentStorageProjection,+ executeContentStorageMutation,+ executeContentStoragePropMutation,+ executeContentStorageStructuralMutation,+ executeContentStorageTextReplacement,+ getContentStorageProtectedChildCount,+ resolveContentStorageRoot,+} from "./content-storage";export type BuilderRuntimeOperation<Id extends string = string,@@ -61,7 +81,7 @@ export type BuilderRuntimeOperation<command: string;client: string;permit?: BuilderApiCapability;- kind: "read" | "mutation";+ kind: "read" | "mutation" | "application";inputSchema: z.ZodTypeAny;inputJsonSchema: InputJsonSchema;outputSchema: z.ZodTypeAny;@@ -101,6 +121,14 @@ type RuntimeOperationContractInput =retryOnConflict?: boolean;requiresAssets?: boolean;requiresConfirm?: boolean;+ }+ | {+ kind: "application";+ readNamespaces: readonly BuilderNamespace[];+ writeNamespaces: readonly BuilderNamespace[];+ invalidatesNamespaces?: readonly BuilderNamespace[];+ requiresAssets?: boolean;+ requiresConfirm?: boolean;};type ReadContract = Extract<RuntimeOperationContractInput, { kind: "read" }>;@@ -108,6 +136,10 @@ type MutationContract = Extract<RuntimeOperationContractInput,{ kind: "mutation" }>;+type ApplicationContract = Extract<+ RuntimeOperationContractInput,+ { kind: "application" }+>;type RuntimeExecutionOutput<Id extends RuntimeOutputSchemaId,Contract extends RuntimeOperationContractInput,@@ -219,7 +251,7 @@ const runtimeOperation = <RuntimeExecutionOutput<Id, Contract>> => {const writeNamespaces =- contract.kind === "mutation" ? contract.writeNamespaces : [];+ contract.kind === "read" ? [] : contract.writeNamespaces;const inputJsonSchema = getInputSchemaMetadata(inputSchema, {isHiddenField: isHiddenPublicApiInputField,}).inputJsonSchema;@@ -239,9 +271,9 @@ const runtimeOperation = <readNamespaces: contract.readNamespaces,writeNamespaces,invalidatesNamespaces:- contract.kind === "mutation"- ? (contract.invalidatesNamespaces ?? contract.writeNamespaces)- : [],+ contract.kind === "read"+ ? []+ : (contract.invalidatesNamespaces ?? contract.writeNamespaces),retryOnConflict:contract.kind === "mutation"? (contract.retryOnConflict ?? false)@@ -251,13 +283,22 @@ const runtimeOperation = <(contract.readNamespaces.includes("assets") ||writeNamespaces.includes("assets")),requiresConfirm:- contract.kind === "mutation"+ contract.kind === "mutation" || contract.kind === "application"? (contract.requiresConfirm ??isDestructiveRuntimeCommand(publicApi.command)): false,execute: ({ state, input, context }) => {+ const executionState =+ contract.kind === "read" &&+ state.instances !== undefined &&+ context.materializedContent !== undefined+ ? createContentStorageProjection({+ state,+ materializedRoots: context.materializedContent,+ }).state+ : state;const result = execute({- state,+ state: executionState,input: parseOperationInput(inputSchema, input, inputJsonSchema),context,});@@ -307,6 +348,14 @@ const mutationContract = (input: {requiresConfirm?: boolean;}): MutationContract => ({ kind: "mutation", ...input });+const applicationContract = (input: {+ readNamespaces: readonly BuilderNamespace[];+ writeNamespaces: readonly BuilderNamespace[];+ invalidatesNamespaces?: readonly BuilderNamespace[];+ requiresAssets?: boolean;+ requiresConfirm?: boolean;+}): ApplicationContract => ({ kind: "application", ...input });+const pageNamespaces = ["pages", "instances"] as const;const pageExpressionNamespaces = ["pages", "instances", "dataSources"] as const;const instanceReadNamespaces = ["pages", "instances", "props"] as const;@@ -316,6 +365,11 @@ const styleNamespaces = ["styleSourceSelections",] as const;const dataNamespaces = ["dataSources", "resources"] as const;+const contentStoragePropReadNamespaces = [+ "instances",+ "props",+ ...dataNamespaces,+] as const;const treeMutationNamespaces = ["pages","instances",@@ -414,8 +468,365 @@ const assetUsageInput = z.object({assetId: z.string(),...paginatedOutputInputSchema.shape,});+const contentBlockSourceInspectionInput = z.object({+ blockInstanceId: z.string().min(1),+ renderScope: z.string().min(1),+ load: z.boolean().optional(),+ variables: z+ .record(z.string().min(1), z.json())+ .refine(+ (variables) =>+ Object.keys(variables).length <= 100 &&+ new TextEncoder().encode(JSON.stringify(variables)).byteLength <=+ 64 * 1024,+ "Render-scope variables are limited to 100 entries and 64 KiB"+ )+ .optional(),+});+const contentBlockLifecycleBaseInput = contentBlockSourceInspectionInput+ .omit({ load: true })+ .extend({+ dryRun: z.boolean().optional(),+ confirmationToken: z.string().min(1).optional(),+ });+const contentBlockSourceChangeInput = contentBlockLifecycleBaseInput.extend({+ source: contentBlockSource,+ authority: z+ .enum(["use-file-content", "replace-file-body-with-block-content"])+ .optional(),+});+const contentBlockRecoveryInput = contentBlockSourceInspectionInput+ .omit({ load: true, variables: true })+ .extend({+ action: z.enum(["retry", "reload-remote", "copy-unsaved-mdx"]),+ });+const contentBlockTemplateMigrationInput = z.object({+ templateInstanceId: z.string().min(1),+ migration: z.discriminatedUnion("type", [+ z.object({ type: z.literal("rename"), to: z.string().min(1) }),+ z.object({ type: z.literal("remove") }),+ ]),+ renderScope: z.string().min(1),+ variables: contentBlockSourceInspectionInput.shape.variables,+ selectedAssetIds: z.array(z.string().min(1)).max(100).optional(),+ dryRun: z.boolean().optional(),+ confirmationToken: z.string().min(1).optional(),+});+const contentBlockSemanticEditInput = contentBlockSourceInspectionInput+ .omit({ load: true })+ .extend({+ operationId: z.string().min(1),+ input: z.json(),+ dryRun: z.boolean().optional(),+ });+const contentBlockApplicationContract = applicationContract({+ readNamespaces: components.componentInsertReadNamespaces,+ writeNamespaces: components.componentInsertReadNamespaces,+ requiresAssets: true,+ requiresConfirm: false,+});+const serializeContentBlockInspection = (+ result: ContentBlockSourceInspection+) => ({+ ...result,+ diagnostics: [...result.diagnostics],+ repairRoutes: [...result.repairRoutes],+});++const executeContentBlockLifecycleApplication = async ({+ operationId,+ action,+ input,+ context,+}: {+ operationId:+ | "contentBlocks.connectSource"+ | "contentBlocks.switchSource"+ | "contentBlocks.disconnectSource";+ action: "connect" | "switch" | "disconnect";+ input: z.infer<typeof contentBlockLifecycleBaseInput> & {+ source?: z.infer<typeof contentBlockSource>;+ authority?: "use-file-content" | "replace-file-body-with-block-content";+ };+ context: BuilderRuntimeContext;+}) => {+ const application = context.contentStorageApplication;+ if (application === undefined) {+ return throwBuilderRuntimeError(+ "CONFLICT",+ "Content Block source updates require an Asset editing session"+ );+ }+ const applyLifecycle = application.applyLifecycle;+ const inspectSource = application.inspectSource;+ if (applyLifecycle === undefined || inspectSource === undefined) {+ return throwBuilderRuntimeError(+ "CONFLICT",+ "Content Block source updates require lifecycle and inspection capabilities"+ );+ }+ const expectedVersion = context.projectVersion;+ const result = await applyLifecycle(+ {+ ...input,+ action,+ dryRun: input.dryRun === true || context.applicationDryRun === true,+ },+ {+ commitProjectPayload:+ expectedVersion === undefined ||+ context.commitApplicationProjectPayload === undefined+ ? undefined+ : async (payload) => {+ await context.commitApplicationProjectPayload?.({+ payload,+ expectedVersion,+ operationId,+ invalidatesNamespaces: components.componentInsertReadNamespaces,+ });+ },+ }+ );+ const source = serializeContentBlockInspection(+ await inspectSource({+ blockInstanceId: input.blockInstanceId,+ renderScope: input.renderScope,+ variables: input.variables,+ load: false,+ })+ );+ return {+ status: result.status,+ code: "code" in result ? result.code : undefined,+ message: "message" in result ? result.message : undefined,+ source,+ plan:+ result.result === undefined+ ? undefined+ : {+ ...result.result,+ storageWrites: [...result.result.storageWrites],+ diagnostics: [...result.result.diagnostics],+ },+ confirmation:+ result.status === "confirmation-required"+ ? {+ token: result.confirmationToken,+ expiresAt: result.confirmationExpiresAt,+ }+ : undefined,+ };+};export const builderRuntimeOperations = [+ runtimeOperation(+ "contentBlocks.inspectSource",+ api("inspect-content-block-source", "inspectContentBlockSource", "view"),+ readContract([...components.componentInsertReadNamespaces], {+ requiresAssets: true,+ }),+ contentBlockSourceInspectionInput,+ async ({ input, context }) => {+ const inspect = context.contentStorageApplication?.inspectSource;+ if (inspect === undefined) {+ return throwBuilderRuntimeError(+ "CONFLICT",+ "Content Block source inspection requires an Asset editing session"+ );+ }+ return serializeContentBlockInspection(await inspect(input));+ }+ ),+ runtimeOperation(+ "contentBlocks.connectSource",+ api("connect-content-block-source", "connectContentBlockSource", "edit"),+ contentBlockApplicationContract,+ contentBlockSourceChangeInput,+ ({ input, context }) =>+ executeContentBlockLifecycleApplication({+ operationId: "contentBlocks.connectSource",+ action: "connect",+ input,+ context,+ })+ ),+ runtimeOperation(+ "contentBlocks.switchSource",+ api("switch-content-block-source", "switchContentBlockSource", "edit"),+ contentBlockApplicationContract,+ contentBlockSourceChangeInput,+ ({ input, context }) =>+ executeContentBlockLifecycleApplication({+ operationId: "contentBlocks.switchSource",+ action: "switch",+ input,+ context,+ })+ ),+ runtimeOperation(+ "contentBlocks.disconnectSource",+ api(+ "disconnect-content-block-source",+ "disconnectContentBlockSource",+ "edit"+ ),+ contentBlockApplicationContract,+ contentBlockLifecycleBaseInput,+ ({ input, context }) =>+ executeContentBlockLifecycleApplication({+ operationId: "contentBlocks.disconnectSource",+ action: "disconnect",+ input,+ context,+ })+ ),+ runtimeOperation(+ "contentBlocks.recoverSource",+ api("recover-content-block-source", "recoverContentBlockSource", "edit"),+ contentBlockApplicationContract,+ contentBlockRecoveryInput,+ async ({ input, context }) => {+ const application = context.contentStorageApplication;+ if (application === undefined) {+ return throwBuilderRuntimeError(+ "CONFLICT",+ "Content Block source recovery requires an Asset editing session"+ );+ }+ const recover = application.recover;+ const inspectSource = application.inspectSource;+ if (recover === undefined || inspectSource === undefined) {+ return throwBuilderRuntimeError(+ "CONFLICT",+ "Content Block source recovery requires recovery and inspection capabilities"+ );+ }+ const result = await recover({+ ...input,+ dryRun: context.applicationDryRun === true,+ });+ const inspection =+ result.result?.inspection ??+ (await inspectSource({+ blockInstanceId: input.blockInstanceId,+ renderScope: input.renderScope,+ load: false,+ }));+ return {+ status: result.status,+ code: "code" in result ? result.code : undefined,+ message: "message" in result ? result.message : undefined,+ source: serializeContentBlockInspection(inspection),+ localMdx:+ result.result !== undefined && "source" in result.result+ ? result.result.source+ : undefined,+ changedAsset: result.result?.changedAsset ?? false,+ };+ }+ ),+ runtimeOperation(+ "contentBlocks.migrateTemplateReferences",+ api(+ "migrate-content-block-template-references",+ "migrateContentBlockTemplateReferences",+ "edit"+ ),+ contentBlockApplicationContract,+ contentBlockTemplateMigrationInput,+ async ({ input, context }) => {+ const migrate =+ context.contentStorageApplication?.migrateTemplateReferences;+ if (migrate === undefined) {+ return throwBuilderRuntimeError(+ "CONFLICT",+ "Content Block template migration requires an Asset editing session"+ );+ }+ const result = await migrate({+ ...input,+ dryRun: input.dryRun === true || context.applicationDryRun === true,+ });+ return {+ ...result,+ changedAsset: result.changedAsset ?? false,+ files: result.files.map((file) => ({+ ...file,+ diagnostics: [...file.diagnostics],+ })),+ diagnostics:+ result.diagnostics === undefined+ ? undefined+ : [...result.diagnostics],+ confirmation:+ result.status === "confirmation-required" &&+ typeof result.confirmationToken === "string" &&+ typeof result.confirmationExpiresAt === "string"+ ? {+ token: result.confirmationToken,+ expiresAt: result.confirmationExpiresAt,+ }+ : undefined,+ };+ }+ ),+ runtimeOperation(+ "contentBlocks.semanticEdit",+ api("edit-content-block-source", "editContentBlockSource", "edit"),+ contentBlockApplicationContract,+ contentBlockSemanticEditInput,+ async ({ input, context }) => {+ const semanticEdit = context.contentStorageApplication?.semanticEdit;+ if (semanticEdit === undefined) {+ return throwBuilderRuntimeError(+ "CONFLICT",+ "Content Block semantic editing requires an Asset editing session"+ );+ }+ const dryRun =+ input.dryRun === true || context.applicationDryRun === true;+ const result = await semanticEdit({ ...input, dryRun });+ const mutation = result.result as+ | BuilderRuntimeMutation<Record<string, unknown>>+ | undefined;+ const serializedMutation =+ mutation === undefined+ ? undefined+ : {+ result: { ...mutation.result },+ noop: mutation.noop,+ };+ return {+ ...result,+ result: serializedMutation,+ persistence:+ mutation === undefined || !("persistence" in mutation)+ ? undefined+ : (() => {+ const persistence =+ mutation.persistence as ContentBlockPersistenceResult;+ return {+ ...persistence,+ steps: persistence.steps.map((step) => ({ ...step })),+ retry: {+ ...persistence.retry,+ roots: persistence.retry.roots.map((root) => ({ ...root })),+ },+ };+ })(),+ changedAsset:+ dryRun === false &&+ (result.status === "complete" || result.status === "partial") &&+ (mutation !== undefined && "persistence" in mutation+ ? (+ mutation.persistence as ContentBlockPersistenceResult+ ).steps.some(+ (step) => step.type === "asset" && step.status === "saved"+ )+ : (mutation?.storageChanges?.length ?? 0) > 0),+ };+ }+ ),runtimeOperation("pages.list",api("list-pages", "listPages"),@@ -901,7 +1312,23 @@ export const builderRuntimeOperations = [}),components.insertComponentInput,({ state, input, context }) =>- components.insertComponent(state, input, context)+ executeContentStorageMutation({+ state,+ materializedRoots: context.materializedContent,+ returnStorageChanges: context.returnStorageChanges,+ target: {+ type: "children",+ parentInstanceId: input.parentInstanceId,+ },+ execute: (mutationState, root) =>+ components.insertComponent(mutationState, input, context, {+ protectedChildCount: getContentStorageProtectedChildCount({+ state: mutationState,+ root,+ parentInstanceId: input.parentInstanceId,+ }),+ }),+ })),runtimeOperation("instances.insertCollection",@@ -911,31 +1338,107 @@ export const builderRuntimeOperations = [writeNamespaces: components.componentInsertNamespaces,}),collection.insertCollectionInput,- ({ state, input, context }) => {- const warnings = [- ...(input.data.type === "expression"- ? getScopedExpressionWarnings(- state,- input.parentInstanceId,- ["data", "value"],- input.data.value- )- : []),- ...listFragmentExpressions(input.itemFragment).flatMap((entry) =>- getScopedExpressionWarnings(- state,- input.parentInstanceId,- ["itemFragment", ...entry.path],- entry.expression,- entry.allowAssignment,- ["collectionItem", "collectionItemKey", ...entry.variables]- )- ),- ];- return withExpressionWarnings(- components.insertCollection(state, input, context),- warnings- );+ ({ state, input, context }) =>+ executeContentStorageMutation({+ state,+ materializedRoots: context.materializedContent,+ returnStorageChanges: context.returnStorageChanges,+ target: {+ type: "children",+ parentInstanceId: input.parentInstanceId,+ },+ execute: (mutationState, root) => {+ const warnings = [+ ...(input.data.type === "expression"+ ? getScopedExpressionWarnings(+ mutationState,+ input.parentInstanceId,+ ["data", "value"],+ input.data.value+ )+ : []),+ ...listFragmentExpressions(input.itemFragment).flatMap((entry) =>+ getScopedExpressionWarnings(+ mutationState,+ input.parentInstanceId,+ ["itemFragment", ...entry.path],+ entry.expression,+ entry.allowAssignment,+ ["collectionItem", "collectionItemKey", ...entry.variables]+ )+ ),+ ];+ return withExpressionWarnings(+ components.insertCollection(mutationState, input, context, {+ protectedChildCount: getContentStorageProtectedChildCount({+ state: mutationState,+ root,+ parentInstanceId: input.parentInstanceId,+ }),+ }),+ warnings+ );+ },+ })+ ),+ runtimeOperation(+ "instances.insertMdxText",+ api("insert-mdx-text", "insertMdxText"),+ mutationContract({+ readNamespaces: components.componentInsertReadNamespaces,+ writeNamespaces: components.componentInsertNamespaces,+ }),+ mdxPaste.insertMdxTextInput,+ async ({ state, input, context }) => {+ const target = {+ type: "children" as const,+ parentInstanceId: input.parentInstanceId,+ };+ const projection = createContentStorageProjection({+ state,+ materializedRoots: context.materializedContent ?? [],+ });+ const root = resolveContentStorageRoot(projection, target);+ const parent = projection.state.instances?.get(input.parentInstanceId);+ if (parent === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");+ }+ const protectedChildCount = getContentStorageProtectedChildCount({+ state: projection.state,+ root,+ parentInstanceId: input.parentInstanceId,+ });+ const childIndex =+ input.mode === "replace" || input.mode === "prepend"+ ? 0+ : (input.insertIndex ??+ Math.max(0, parent.children.length - protectedChildCount));+ const mutation = await mdxPaste.insertMdxText({+ state: projection.state,+ input,+ context,+ destinationIdentity:+ root.type === "external" ? root.identity : undefined,+ protectedChildCount,+ });+ return executeContentStorageMutation({+ state,+ materializedRoots: context.materializedContent,+ returnStorageChanges: context.returnStorageChanges,+ target,+ mdxInsert: {+ source: input.source,+ parentInstanceId: input.parentInstanceId,+ childIndex,+ position:+ input.mode === "replace" || input.mode === "prepend"+ ? input.mode+ : input.insertIndex === undefined+ ? "append"+ : "index",+ },+ execute: () => mutation,+ });}),runtimeOperation(@@ -946,8 +1449,29 @@ export const builderRuntimeOperations = [writeNamespaces: components.componentInsertNamespaces,}),components.insertFragmentInput,- ({ state, input, context }) =>- components.insertFragment(state, input, context)+ ({ state, input, context }) => {+ const parentInstanceId = input.parentInstanceId;+ if (+ parentInstanceId === undefined ||+ input.fragment.children.length === 0+ ) {+ return components.insertFragment(state, input, context);+ }+ return executeContentStorageMutation({+ state,+ materializedRoots: context.materializedContent,+ returnStorageChanges: context.returnStorageChanges,+ target: { type: "children", parentInstanceId },+ execute: (mutationState, root) =>+ components.insertFragment(mutationState, input, context, {+ protectedChildCount: getContentStorageProtectedChildCount({+ state: mutationState,+ root,+ parentInstanceId,+ }),+ }),+ });+ }),runtimeOperation("slots.attach",@@ -977,7 +1501,28 @@ export const builderRuntimeOperations = [writeNamespaces: ["pages", "instances", "props", ...dataNamespaces],}),instances.moveInstancesInput,- ({ state, input }) => instances.moveInstances(state, input)+ ({ state, input, context }) =>+ executeContentStorageStructuralMutation({+ state,+ materializedRoots: context.materializedContent,+ returnStorageChanges: context.returnStorageChanges,+ protectedInstanceIds: input.moves.flatMap(+ ({ instanceId, parentInstanceId }) => [instanceId, parentInstanceId]+ ),+ rootPairs: input.moves.map(({ instanceId, parentInstanceId }) => ({+ source: { type: "instance", instanceId },+ target: { type: "children", parentInstanceId },+ })),+ ownershipTransfers: input.moves.map(+ ({ instanceId, parentInstanceId }) => ({+ rootInstanceId: instanceId,+ source: { type: "instance", instanceId },+ target: { type: "children", parentInstanceId },+ })+ ),+ execute: (mutationState) =>+ instances.moveInstances(mutationState, input),+ })),runtimeOperation("instances.reparent",@@ -1004,7 +1549,42 @@ export const builderRuntimeOperations = [}),instances.reparentInstanceInput,({ state, input, context }) =>- instances.reparentInstance(state, input, context)+ executeContentStorageStructuralMutation({+ state,+ materializedRoots: context.materializedContent,+ returnStorageChanges: context.returnStorageChanges,+ protectedInstanceIds: [+ input.sourceInstanceSelector[0],+ input.dropTarget.parentSelector[0],+ ],+ rootPairs: [+ {+ source: {+ type: "instance",+ instanceId: input.sourceInstanceSelector[0],+ },+ target: {+ type: "children",+ parentInstanceId: input.dropTarget.parentSelector[0],+ },+ },+ ],+ ownershipTransfers: [+ {+ rootInstanceId: input.sourceInstanceSelector[0],+ source: {+ type: "instance",+ instanceId: input.sourceInstanceSelector[0],+ },+ target: {+ type: "children",+ parentInstanceId: input.dropTarget.parentSelector[0],+ },+ },+ ],+ execute: (mutationState) =>+ instances.reparentInstance(mutationState, input, context),+ })),runtimeOperation("instances.fillGrid",@@ -1019,7 +1599,18 @@ export const builderRuntimeOperations = [],}),instances.fillGridInput,- ({ state, input, context }) => instances.fillGrid(state, input, context)+ ({ state, input, context }) =>+ executeContentStorageMutation({+ state,+ materializedRoots: context.materializedContent,+ returnStorageChanges: context.returnStorageChanges,+ target: {+ type: "children",+ parentInstanceId: input.parentInstanceId,+ },+ execute: (mutationState) =>+ instances.fillGrid(mutationState, input, context),+ })),runtimeOperation("instances.wrap",@@ -1029,7 +1620,19 @@ export const builderRuntimeOperations = [writeNamespaces: ["instances"],}),instances.wrapInstanceInput,- ({ state, input, context }) => instances.wrapInstance(state, input, context)+ ({ state, input, context }) =>+ executeContentStorageMutation({+ state,+ materializedRoots: context.materializedContent,+ returnStorageChanges: context.returnStorageChanges,+ protectTemplatesList: true,+ target: {+ type: "instance",+ instanceId: input.instanceSelector[0],+ },+ execute: (mutationState) =>+ instances.wrapInstance(mutationState, input, context),+ })),runtimeOperation("instances.convert",@@ -1061,7 +1664,18 @@ export const builderRuntimeOperations = [}),instances.convertInstanceInput,({ state, input, context }) =>- instances.convertInstance(state, input, context)+ executeContentStorageMutation({+ state,+ materializedRoots: context.materializedContent,+ returnStorageChanges: context.returnStorageChanges,+ protectTemplatesList: true,+ target: {+ type: "instance",+ instanceId: input.instanceSelector[0],+ },+ execute: (mutationState) =>+ instances.convertInstance(mutationState, input, context),+ })),runtimeOperation("instances.unwrap",@@ -1072,18 +1686,114 @@ export const builderRuntimeOperations = [}),instances.unwrapInstanceInput,({ state, input, context }) =>- instances.unwrapInstance(state, input, context)+ executeContentStorageMutation({+ state,+ materializedRoots: context.materializedContent,+ returnStorageChanges: context.returnStorageChanges,+ protectedInstanceIds: [input.instanceSelector[1]],+ protectTemplatesList: true,+ source: {+ type: "children",+ parentInstanceId: input.instanceSelector[2],+ },+ target: {+ type: "instance",+ instanceId: input.instanceSelector[0],+ },+ crossRootError:+ "Moving content across authored storage roots is not supported.",+ execute: (mutationState) =>+ instances.unwrapInstance(mutationState, input, context),+ })),runtimeOperation("instances.clone",api("clone-instance", "cloneInstance"),mutationContract({- readNamespaces: treeMutationNamespaces,- writeNamespaces: treeMutationNamespaces,+ readNamespaces: components.componentInsertReadNamespaces,+ writeNamespaces: components.componentInsertReadNamespaces,}),instances.cloneInstanceInput,({ state, input, context }) =>- instances.cloneInstance(state, input, context)+ executeContentStorageMutation({+ state,+ materializedRoots: context.materializedContent,+ returnStorageChanges: context.returnStorageChanges,+ protectTemplatesList: true,+ allowCrossRoot: true,+ copySourceInstanceId: input.sourceInstanceId,+ validationSkippedNamespaces: ["dataSources", "resources"],+ crossRootError:+ "Copying content across authored storage roots is not supported.",+ source: { type: "instance", instanceId: input.sourceInstanceId },+ target:+ input.targetParentInstanceId === undefined+ ? (mutationState) => {+ const parent = instances.findInstanceCloneTargetParent({+ instances: mutationState.instances ?? new Map(),+ sourceInstanceId: input.sourceInstanceId,+ });+ return parent === undefined+ ? { type: "instance", instanceId: input.sourceInstanceId }+ : { type: "children", parentInstanceId: parent.id };+ }+ : {+ type: "children",+ parentInstanceId: input.targetParentInstanceId,+ },+ execute: (mutationState, targetRoot, sourceRoot) => {+ const isSameRoot =+ sourceRoot === undefined ||+ (sourceRoot.type === targetRoot.type &&+ (sourceRoot.type === "project" ||+ (targetRoot.type === "external" &&+ sourceRoot.identity.blockInstanceId ===+ targetRoot.identity.blockInstanceId)));+ if (isSameRoot) {+ return instances.cloneInstance(mutationState, input, context);+ }+ const targetParentInstanceId =+ input.targetParentInstanceId ??+ instances.findInstanceCloneTargetParent({+ instances: mutationState.instances ?? new Map(),+ sourceInstanceId: input.sourceInstanceId,+ })?.id;+ if (targetParentInstanceId === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Clone target parent is missing."+ );+ }+ const mutation = components.insertInstanceCopy(+ mutationState,+ {+ sourceInstanceId: input.sourceInstanceId,+ parentInstanceId: targetParentInstanceId,+ insertIndex: input.insertIndex,+ contentMode: targetRoot.type === "external",+ },+ context,+ {+ protectedChildCount: getContentStorageProtectedChildCount({+ state: mutationState,+ root: targetRoot,+ parentInstanceId: targetParentInstanceId,+ }),+ }+ );+ const instanceId = mutation.result.rootInstanceIds[0];+ if (instanceId === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Cloned fragment has no root instance."+ );+ }+ return {+ ...mutation,+ result: { instanceId, instanceIds: mutation.result.instanceIds },+ };+ },+ })),runtimeOperation("instances.duplicateAfterItself",@@ -1094,7 +1804,26 @@ export const builderRuntimeOperations = [}),instanceDuplicate.duplicateInstanceAfterItselfInput,({ state, input, context }) =>- instanceDuplicate.duplicateInstanceAfterItself(state, input, context)+ executeContentStorageMutation({+ state,+ materializedRoots: context.materializedContent,+ returnStorageChanges: context.returnStorageChanges,+ protectTemplatesList: true,+ copySourceInstanceId: input.sourceInstanceId,+ crossRootError:+ "Copying content across authored storage roots is not supported.",+ source: { type: "instance", instanceId: input.sourceInstanceId },+ target: {+ type: "children",+ parentInstanceId: input.parentInstanceId,+ },+ execute: (mutationState) =>+ instanceDuplicate.duplicateInstanceAfterItself(+ mutationState,+ input,+ context+ ),+ })),runtimeOperation("instances.delete",@@ -1104,7 +1833,15 @@ export const builderRuntimeOperations = [writeNamespaces: treeMutationNamespaces,}),instances.deleteInstancesInput,- ({ state, input }) => instances.deleteInstances(state, input)+ ({ state, input, context }) =>+ executeContentStorageStructuralMutation({+ state,+ materializedRoots: context.materializedContent,+ returnStorageChanges: context.returnStorageChanges,+ protectedInstanceIds: input.instanceIds,+ execute: (mutationState) =>+ instances.deleteInstances(mutationState, input),+ })),runtimeOperation("instances.deleteBySelector",@@ -1131,111 +1868,146 @@ export const builderRuntimeOperations = [}),instances.deleteInstanceBySelectorInput,({ state, input, context }) =>- instances.deleteInstanceBySelector(state, input, context)+ executeContentStorageMutation({+ state,+ materializedRoots: context.materializedContent,+ returnStorageChanges: context.returnStorageChanges,+ protectTemplatesList: true,+ target: {+ type: "instance",+ instanceId: input.instanceSelector[0],+ },+ execute: (mutationState) =>+ instances.deleteInstanceBySelector(mutationState, input, context),+ })),runtimeOperation("instances.updateProps",api("update-props", "updateProps", "edit"),mutationContract({- readNamespaces: ["instances", "props", "dataSources"],+ readNamespaces: contentStoragePropReadNamespaces,writeNamespaces: ["props"],}),props.propUpdatesInput,- ({ state, input, context }) => {- const warnings = input.updates.flatMap((update, index) =>- getScopedPropWarnings({- state,- instanceId: update.instanceId,- path: ["updates", String(index), "value"],- prop: update,- })- );- return withExpressionWarnings(- props.updateProps(- state,- {- updates: input.updates.map((update) =>- update.type === "expression"- ? {- ...update,- value: bindExpressionInput(- state,- update.instanceId,- update.value- ),- }- : update+ ({ state, input, context }) =>+ executeContentStoragePropMutation({+ state,+ materializedRoots: context.materializedContent,+ returnStorageChanges: context.returnStorageChanges,+ execute: (mutationState) => {+ const warnings = input.updates.flatMap((update, index) =>+ getScopedPropWarnings({+ state: mutationState,+ instanceId: update.instanceId,+ path: ["updates", String(index), "value"],+ prop: update,+ })+ );+ return withExpressionWarnings(+ props.updateProps(+ mutationState,+ {+ updates: input.updates.map((update) =>+ update.type === "expression"+ ? {+ ...update,+ value: bindExpressionInput(+ mutationState,+ update.instanceId,+ update.value+ ),+ }+ : update+ ),+ },+ context),- },- context- ),- warnings- );- }+ warnings+ );+ },+ })),runtimeOperation("instances.replacePropText",api("replace-prop-text", "replacePropText", "edit"),mutationContract({- readNamespaces: ["instances", "props"],+ readNamespaces: contentStoragePropReadNamespaces,writeNamespaces: ["props"],retryOnConflict: true,}),props.replacePropTextInput,- ({ state, input }) => props.replacePropText(state, input)+ ({ state, input, context }) =>+ executeContentStoragePropMutation({+ state,+ materializedRoots: context.materializedContent,+ returnStorageChanges: context.returnStorageChanges,+ execute: (mutationState) => props.replacePropText(mutationState, input),+ })),runtimeOperation("instances.deleteProps",api("delete-props", "deleteProps", "edit"),mutationContract({- readNamespaces: ["instances", "props"],+ readNamespaces: contentStoragePropReadNamespaces,writeNamespaces: ["props", "resources"],}),props.propDeletionsInput,- ({ state, input }) => props.deleteProps(state, input)+ ({ state, input, context }) =>+ executeContentStoragePropMutation({+ state,+ materializedRoots: context.materializedContent,+ returnStorageChanges: context.returnStorageChanges,+ execute: (mutationState) => props.deleteProps(mutationState, input),+ })),runtimeOperation("instances.bindProps",api("bind-props", "bindProps"),mutationContract({- readNamespaces: ["instances", "props", ...dataNamespaces],+ readNamespaces: contentStoragePropReadNamespaces,writeNamespaces: ["props"],}),props.propBindingsInput,- ({ state, input, context }) => {- const warnings = input.bindings.flatMap((binding, index) =>- getScopedPropWarnings({- state,- instanceId: binding.instanceId,- path: ["bindings", String(index), "binding", "value"],- prop: binding.binding,- })- );- return withExpressionWarnings(- props.bindProps(- state,- {- bindings: input.bindings.map((binding) =>- binding.binding.type === "expression"- ? {- ...binding,- binding: {- ...binding.binding,- value: bindExpressionInput(- state,- binding.instanceId,- binding.binding.value- ),- },- }- : binding+ ({ state, input, context }) =>+ executeContentStoragePropMutation({+ state,+ materializedRoots: context.materializedContent,+ returnStorageChanges: context.returnStorageChanges,+ execute: (mutationState) => {+ const warnings = input.bindings.flatMap((binding, index) =>+ getScopedPropWarnings({+ state: mutationState,+ instanceId: binding.instanceId,+ path: ["bindings", String(index), "binding", "value"],+ prop: binding.binding,+ })+ );+ return withExpressionWarnings(+ props.bindProps(+ mutationState,+ {+ bindings: input.bindings.map((binding) =>+ binding.binding.type === "expression"+ ? {+ ...binding,+ binding: {+ ...binding.binding,+ value: bindExpressionInput(+ mutationState,+ binding.instanceId,+ binding.binding.value+ ),+ },+ }+ : binding+ ),+ },+ context),- },- context- ),- warnings- );- }+ warnings+ );+ },+ })),runtimeOperation("instances.listTexts",@@ -1248,78 +2020,131 @@ export const builderRuntimeOperations = ["instances.updateText",api("update-text", "updateText", "edit"),mutationContract({- readNamespaces: ["instances", "dataSources"],+ readNamespaces: [+ "instances",+ "props",+ "dataSources",+ ...styleNamespaces,+ "breakpoints",+ ],writeNamespaces: ["instances"],retryOnConflict: true,}),instances.updateTextInstanceInput,- ({ state, input }) => {- const warnings =- input.mode === "expression"- ? getScopedExpressionWarnings(- state,- input.instanceId,- ["text"],- input.text- )- : [];- return withExpressionWarnings(- instances.updateTextInstance(- state,- input.mode === "expression"- ? {- ...input,- text: bindExpressionInput(state, input.instanceId, input.text),- }- : input- ),- warnings- );- }+ ({ state, input, context }) =>+ executeContentStorageMutation({+ state,+ materializedRoots: context.materializedContent,+ returnStorageChanges: context.returnStorageChanges,+ target: {+ type: "children",+ parentInstanceId: input.instanceId,+ },+ execute: (mutationState) => {+ const warnings =+ input.mode === "expression"+ ? getScopedExpressionWarnings(+ mutationState,+ input.instanceId,+ ["text"],+ input.text+ )+ : [];+ return withExpressionWarnings(+ instances.updateTextInstance(+ mutationState,+ input.mode === "expression"+ ? {+ ...input,+ text: bindExpressionInput(+ mutationState,+ input.instanceId,+ input.text+ ),+ }+ : input+ ),+ warnings+ );+ },+ })),runtimeOperation("instances.replaceText",api("replace-text", "replaceText", "edit"),mutationContract({- readNamespaces: ["pages", "instances"],+ readNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ ...styleNamespaces,+ "breakpoints",+ ],writeNamespaces: ["instances"],retryOnConflict: true,}),instances.replaceTextInput,- ({ state, input }) => instances.replaceText(state, input)+ ({ state, input, context }) =>+ executeContentStorageTextReplacement({+ state,+ materializedRoots: context.materializedContent,+ returnStorageChanges: context.returnStorageChanges,+ execute: (mutationState) => instances.replaceText(mutationState, input),+ })),runtimeOperation("instances.setTextContent",api("set-text-content", "setTextContent", "edit"),mutationContract({- readNamespaces: ["instances", "dataSources"],+ readNamespaces: [+ "instances",+ "props",+ "dataSources",+ ...styleNamespaces,+ "breakpoints",+ ],writeNamespaces: ["instances"],retryOnConflict: true,}),instances.setTextContentInput,- ({ state, input }) => {- const warnings =- input.operation === "set" && input.mode === "expression"- ? getScopedExpressionWarnings(- state,- input.instanceId,- ["text"],- input.text- )- : [];- return withExpressionWarnings(- instances.setTextContent(- state,- input.operation === "set" && input.mode === "expression"- ? {- ...input,- text: bindExpressionInput(state, input.instanceId, input.text),- }- : input- ),- warnings- );- }+ ({ state, input, context }) =>+ executeContentStorageMutation({+ state,+ materializedRoots: context.materializedContent,+ returnStorageChanges: context.returnStorageChanges,+ target: {+ type: "children",+ parentInstanceId: input.instanceId,+ },+ execute: (mutationState) => {+ const warnings =+ input.operation === "set" && input.mode === "expression"+ ? getScopedExpressionWarnings(+ mutationState,+ input.instanceId,+ ["text"],+ input.text+ )+ : [];+ return withExpressionWarnings(+ instances.setTextContent(+ mutationState,+ input.operation === "set" && input.mode === "expression"+ ? {+ ...input,+ text: bindExpressionInput(+ mutationState,+ input.instanceId,+ input.text+ ),+ }+ : input+ ),+ warnings+ );+ },+ })),runtimeOperation("instances.updateTextTree",@@ -1332,6 +2157,7 @@ export const builderRuntimeOperations = ["styleSources","styleSourceSelections","styles",+ "breakpoints",],writeNamespaces: ["instances",@@ -1346,7 +2172,17 @@ export const builderRuntimeOperations = [}),instances.updateTextTreeInput,({ state, input, context }) =>- instances.updateTextTree(state, input, context)+ executeContentStorageMutation({+ state,+ materializedRoots: context.materializedContent,+ returnStorageChanges: context.returnStorageChanges,+ target: {+ type: "children",+ parentInstanceId: input.rootInstanceId,+ },+ execute: (mutationState) =>+ instances.updateTextTree(mutationState, input, context),+ })),runtimeOperation("instances.setTag",@@ -1357,18 +2193,34 @@ export const builderRuntimeOperations = [retryOnConflict: true,}),instances.setInstanceTagInput,- ({ state, input }) => instances.setInstanceTag(state, input)+ ({ state, input, context }) =>+ executeContentStorageMutation({+ state,+ materializedRoots: context.materializedContent,+ returnStorageChanges: context.returnStorageChanges,+ target: { type: "instance", instanceId: input.instanceId },+ execute: (mutationState) =>+ instances.setInstanceTag(mutationState, input),+ })),runtimeOperation("instances.setLabel",api("set-instance-label", "setInstanceLabel", "edit"),mutationContract({- readNamespaces: ["instances"],+ readNamespaces: ["instances", "props"],writeNamespaces: ["instances"],retryOnConflict: true,}),instances.setInstanceLabelInput,- ({ state, input }) => instances.setInstanceLabel(state, input)+ ({ state, input, context }) =>+ executeContentStorageMutation({+ state,+ materializedRoots: context.materializedContent,+ returnStorageChanges: context.returnStorageChanges,+ target: { type: "instance", instanceId: input.instanceId },+ execute: (mutationState) =>+ instances.setInstanceLabel(mutationState, input),+ })),runtimeOperation("styles.getDeclarations",diff --git a/packages/project-build/src/state/patch.ts b/packages/project-build/src/state/patch.tsindex 142b714bc3..a2986267ca 100644--- a/packages/project-build/src/state/patch.ts+++ b/packages/project-build/src/state/patch.ts@@ -1,4 +1,4 @@-import { applyPatches, type Patch } from "immer";+import { applyPatches, produceWithPatches, type Patch } from "immer";import { enableImmerPatchPlugins } from "./immer";import type {BuilderPatch,@@ -215,6 +215,25 @@ export const applyBuilderPatchPayloadMutable = (}};+export const createBuilderPatchInversePayload = ({+ state,+ payload,+}: {+ state: BuilderState;+ payload: readonly BuilderPatchChange[];+}) => {+ const [, , inversePatches] = produceWithPatches(state, (draft) => {+ applyBuilderPatchPayloadMutable((namespace) => {+ const namespaceData = draft[namespace];+ if (namespaceData === undefined) {+ throw new MissingBuilderStateNamespaceError(namespace);+ }+ return namespaceData;+ }, payload);+ });+ return createBuilderPatchPayloadFromImmerPatches(inversePatches);+};+export const applyBuilderPatchTransactions = (state: BuilderState,transactions: readonly BuilderPatchTransaction[]diff --git a/packages/protocol/src/asset-resource-api.test.ts b/packages/protocol/src/asset-resource-api.test.tsindex 65888c674e..1010dbbe35 100644--- a/packages/protocol/src/asset-resource-api.test.ts+++ b/packages/protocol/src/asset-resource-api.test.ts@@ -10,6 +10,7 @@ import { assetResourceLimits } from "@webstudio-is/sdk/asset-resource-limits";import {assetFolderCreateRequest,assetFolderUpdateRequest,+ assetContentDescriptorHeader,assetMetadataUpdate,assetResourceApiOperations,assetUploadReservationRequest,@@ -343,6 +344,14 @@ describe("Assets OpenAPI description", () => {document.paths[assetResourceApiOperations.downloadAssetContent.path].get.responses[200].content).toHaveProperty("*/*");+ expect(+ document.paths[assetResourceApiOperations.downloadAssetContent.path].get+ .responses[200].headers+ ).toHaveProperty(assetContentDescriptorHeader);+ expect(+ document.paths[assetResourceApiOperations.replaceAssetContent.path].put+ .requestBody.content+ ).toHaveProperty("text/mdx", { schema: { type: "string" } });expect(document.paths[assetResourceApiOperations.createAssetFolder.path].post.responses[201]diff --git a/packages/protocol/src/asset-resource-api.ts b/packages/protocol/src/asset-resource-api.tsindex 556145d228..4b34466eef 100644--- a/packages/protocol/src/asset-resource-api.ts+++ b/packages/protocol/src/asset-resource-api.ts@@ -35,6 +35,38 @@ const assetItemApiPath = `${assetsApiUrl}/{assetId}`;const assetContentApiPath = `${assetItemApiPath}/content`;const assetFolderItemApiPath = `${assetsFoldersApiUrl}/{folderId}`;+export const assetContentDescriptorHeader =+ "x-webstudio-asset-content-descriptor";++export const assetContentDescriptor = z.object({+ id: z.string(),+ projectId: z.string(),+ name: z.string(),+ type: assetType,+ format: z.string(),+ size: z.number().nonnegative(),+ createdAt: z.string(),+ updatedAt: z.string().optional(),+});+export type AssetContentDescriptor = z.infer<typeof assetContentDescriptor>;++export const serializeAssetContentDescriptor = (+ value: AssetContentDescriptor+) => encodeURIComponent(JSON.stringify(assetContentDescriptor.parse(value)));++export const parseAssetContentDescriptor = (value: string | null) => {+ if (value === null) {+ throw new Error("Asset content response is missing its revision identity");+ }+ try {+ return assetContentDescriptor.parse(JSON.parse(decodeURIComponent(value)));+ } catch (cause) {+ throw new Error("Asset content response has an invalid revision identity", {+ cause,+ });+ }+};+const operation = <OperationId extends string,Method extends string,@@ -862,6 +894,13 @@ const assetFolderParameters = [projectIdParameter,];const binarySchema = { type: "string", format: "binary" } as const;+const assetContentResponseHeaders = {+ [assetContentDescriptorHeader]: {+ description:+ "URI-encoded JSON identity of the exact Asset revision in this response",+ schema: { type: "string" },+ },+};/*** OpenAPI is both the transport description and the sole query-authoring@@ -1082,6 +1121,7 @@ export const createAssetResourceOpenApi = ({responses: {200: {description: "Complete asset content",+ headers: assetContentResponseHeaders,content: {"*/*": {schema: binarySchema,@@ -1091,6 +1131,7 @@ export const createAssetResourceOpenApi = ({206: {description: "Partial asset content",headers: {+ ...assetContentResponseHeaders,"Content-Range": { schema: { type: "string" } },},content: {@@ -1125,6 +1166,7 @@ export const createAssetResourceOpenApi = ({schema: binarySchema,},"text/markdown": { schema: { type: "string" } },+ "text/mdx": { schema: { type: "string" } },"application/json": { schema: {} },},},diff --git a/packages/protocol/src/builder-api/runtime-contracts.ts b/packages/protocol/src/builder-api/runtime-contracts.tsindex 96f165ca76..32d6a5ccba 100644--- a/packages/protocol/src/builder-api/runtime-contracts.ts+++ b/packages/protocol/src/builder-api/runtime-contracts.ts@@ -12,7 +12,7 @@ export type PublicApiOperationNamespace =export const publicApiOperationPermits = builderApiCapabilities;export type PublicApiOperationPermit =(typeof publicApiOperationPermits)[number];-export type PublicApiOperationKind = "read" | "mutation";+export type PublicApiOperationKind = "read" | "mutation" | "application";export type PublicRuntimeOperationId =(typeof runtimeOperationContracts)[number]["id"];diff --git a/packages/react-sdk/placeholder.d.ts b/packages/react-sdk/placeholder.d.tsindex 572686dc06..090e33884f 100644--- a/packages/react-sdk/placeholder.d.ts+++ b/packages/react-sdk/placeholder.d.ts@@ -37,9 +37,13 @@ declare module "__CLIENT__" {declare module "__SERVER__" {import type { PageMeta, System, ResourceRequest } from "@webstudio-is/sdk";- export const getResources: (props: { system: System }) => {+ export const getResources: (props: {+ system: System;+ resources?: Record<string, any>;+ }) => {data: Map<string, ResourceRequest>;action: Map<string, ResourceRequest>;+ contentData: Map<string, ResourceRequest>;};export const getPageMeta: (props: {diff --git a/packages/react-sdk/src/component-generator.test.tsx b/packages/react-sdk/src/component-generator.test.tsxindex 736bd2270f..0d24704269 100644--- a/packages/react-sdk/src/component-generator.test.tsx+++ b/packages/react-sdk/src/component-generator.test.tsx@@ -1388,6 +1388,88 @@ test("ignore ws:block-template when generate index attribute", () => {);});+test("renders pre-materialized dynamic Content Block candidates without loading", () => {+ const instances = new Map([+ [+ "body",+ {+ type: "instance" as const,+ id: "body",+ component: elementComponent,+ tag: "main",+ children: [{ type: "id" as const, value: "block" }],+ },+ ],+ [+ "block",+ {+ type: "instance" as const,+ id: "block",+ component: "ws:block",+ children: [],+ },+ ],+ [+ "article-heading",+ {+ type: "instance" as const,+ id: "article-heading",+ component: elementComponent,+ tag: "h1",+ children: [{ type: "text" as const, value: "Article" }],+ },+ ],+ [+ "other-heading",+ {+ type: "instance" as const,+ id: "other-heading",+ component: elementComponent,+ tag: "h1",+ children: [{ type: "text" as const, value: "Other" }],+ },+ ],+ ]);+ const generated = generateWebstudioComponent({+ classesMap: new Map(),+ scope: createScope(),+ name: "Page",+ rootInstanceId: "body",+ parameters: [],+ metas: new Map(),+ instances,+ props: new Map(),+ dataSources: new Map(),+ publishedContentBlocks: new Map([+ [+ "block",+ {+ sourceExpression: '"article"',+ candidates: [+ {+ assetId: "article",+ dependencyRevision: "article-revision",+ children: [{ type: "id", value: "article-heading" }],+ },+ {+ assetId: "other",+ dependencyRevision: "other-revision",+ children: [{ type: "id", value: "other-heading" }],+ },+ ],+ },+ ],+ ]),+ });++ expect(generated).toContain('contentSource === "article"');+ expect(generated).toContain('contentSource === "other"');+ expect(generated.split('("article")')).toHaveLength(2);+ expect(generated).toContain("<h1>");+ expect(generated).not.toContain("fetch(");+ expect(isValidJSX(generated)).toBe(true);+});+test("render empty component when no instances found", () => {expect(generateWebstudioComponent({diff --git a/packages/react-sdk/src/component-generator.ts b/packages/react-sdk/src/component-generator.tsindex 19c1cf53d5..b42f0e8a0c 100644--- a/packages/react-sdk/src/component-generator.ts+++ b/packages/react-sdk/src/component-generator.ts@@ -26,6 +26,16 @@ import { isAttributeNameSafe, showAttribute } from "./props";import { standardAttributesToReactProps } from "./__generated__/standard-attributes";import { generateCollectionIterationCode } from "./collection-utils";+export type PublishedContentBlock = Readonly<{+ sourceExpression?: string;+ candidates: readonly Readonly<{+ assetId: string;+ dependencyRevision: string;+ children: Instance["children"];+ resourceIds?: readonly string[];+ }>[];+}>;+/*** (arg1) => {* myVar = myVar + arg1@@ -370,6 +380,7 @@ export const generateJsxChildren = ({indexesWithinAncestors,classesMap,excludePlaceholders,+ publishedContentBlocks,}: {scope: Scope;metas: Map<Instance["component"], WsComponentMeta>;@@ -383,6 +394,7 @@ export const generateJsxChildren = ({indexesWithinAncestors: IndexesWithinAncestors;classesMap?: Map<string, Array<string>>;excludePlaceholders?: boolean;+ publishedContentBlocks?: ReadonlyMap<Instance["id"], PublishedContentBlock>;}) => {let generatedChildren = "";for (const child of children) {@@ -414,18 +426,10 @@ export const generateJsxChildren = ({if (instance === undefined) {continue;}- generatedChildren += generateJsxElement({- context: "jsx",- scope,- metas,- tagsOverrides,- instance,- props,- dataSources,- usedDataSources,- indexesWithinAncestors,- classesMap,- children: generateJsxChildren({+ const publishedContent = publishedContentBlocks?.get(instance.id);+ let generatedInstanceChildren: string;+ if (publishedContent === undefined) {+ generatedInstanceChildren = generateJsxChildren({classesMap,scope,metas,@@ -437,7 +441,72 @@ export const generateJsxChildren = ({usedDataSources,indexesWithinAncestors,excludePlaceholders,- }),+ publishedContentBlocks,+ });+ } else {+ const sourceExpression =+ publishedContent.sourceExpression === undefined+ ? undefined+ : generateExpression({+ expression: publishedContent.sourceExpression,+ dataSources,+ usedDataSources,+ scope,+ });+ const generatedCandidates = publishedContent.candidates.map(+ ({ assetId, dependencyRevision, children: candidateChildren }) => {+ const generated = generateJsxChildren({+ classesMap,+ scope,+ metas,+ tagsOverrides,+ children: candidateChildren,+ instances,+ props,+ dataSources,+ usedDataSources,+ indexesWithinAncestors,+ excludePlaceholders,+ publishedContentBlocks,+ });+ return { assetId, dependencyRevision, generated };+ }+ );+ if (sourceExpression === undefined) {+ generatedInstanceChildren = generatedCandidates+ .map(+ ({ dependencyRevision, generated }) =>+ `<Fragment key=${JSON.stringify(dependencyRevision)}>\n${generated}</Fragment>\n`+ )+ .join("");+ } else {+ const sourceName = scope.getName(+ `${instance.id}-published-source`,+ "contentSource"+ );+ const branches = generatedCandidates+ .map(+ ({ assetId, dependencyRevision, generated }) =>+ `${sourceName} === ${JSON.stringify(assetId)} ? <Fragment key=${JSON.stringify(dependencyRevision)}>\n${generated}</Fragment>`+ )+ .join(" : ");+ generatedInstanceChildren = `{((${sourceName}) => ${+ branches.length === 0 ? "null" : `${branches} : null`+ })(${sourceExpression})}\n`;+ }+ }+ generatedChildren += generateJsxElement({+ context: "jsx",+ scope,+ metas,+ tagsOverrides,+ instance,+ props,+ dataSources,+ usedDataSources,+ indexesWithinAncestors,+ classesMap,+ children: generatedInstanceChildren,});continue;}@@ -457,6 +526,7 @@ export const generateWebstudioComponent = ({metas,tagsOverrides,classesMap,+ publishedContentBlocks,}: {scope: Scope;name: string;@@ -466,6 +536,7 @@ export const generateWebstudioComponent = ({props: Props;dataSources: DataSources;classesMap: Map<string, Array<string>>;+ publishedContentBlocks?: ReadonlyMap<Instance["id"], PublishedContentBlock>;metas: Map<Instance["component"], WsComponentMeta>;/*** Record<tag, componentDescriptor>@@ -503,6 +574,7 @@ export const generateWebstudioComponent = ({usedDataSources,indexesWithinAncestors,classesMap,+ publishedContentBlocks,}),});}diff --git a/packages/react-sdk/src/index.ts b/packages/react-sdk/src/index.tsindex 37033d1feb..da4e655bf7 100644--- a/packages/react-sdk/src/index.ts+++ b/packages/react-sdk/src/index.ts@@ -8,5 +8,6 @@ export {generateWebstudioComponent,generateJsxElement,generateJsxChildren,+ type PublishedContentBlock,} from "./component-generator";export * from "./__generated__/standard-attributes";diff --git a/packages/sdk/src/assets.test.ts b/packages/sdk/src/assets.test.tsindex 8b6852f641..232da24a24 100644--- a/packages/sdk/src/assets.test.ts+++ b/packages/sdk/src/assets.test.ts@@ -137,6 +137,7 @@ describe("allowed-file-types", () => {["txt", "plain"],["csv", "plain"],["md", "markdown"],+ ["mdx", "markdown"],["js", "javascript"],["css", "css"],["json", "json"],@@ -161,12 +162,14 @@ describe("allowed-file-types", () => {expect(getMimeTypeByExtension("png")).toBe("image/png");expect(getMimeTypeByExtension("pdf")).toBe("application/pdf");expect(getMimeTypeByExtension("mp4")).toBe("video/mp4");+ expect(getMimeTypeByExtension("mdx")).toBe("text/mdx");});test("is case-insensitive", () => {expect(getMimeTypeByExtension("JPG")).toBe("image/jpeg");expect(getMimeTypeByExtension("PNG")).toBe("image/png");expect(getMimeTypeByExtension("PDF")).toBe("application/pdf");+ expect(getMimeTypeByExtension("MDX")).toBe("text/mdx");});test("returns undefined for invalid extension", () => {diff --git a/packages/sdk/src/assets.ts b/packages/sdk/src/assets.tsindex ea24cda642..cf6e533a1c 100644--- a/packages/sdk/src/assets.ts+++ b/packages/sdk/src/assets.ts@@ -138,6 +138,7 @@ const assetFileTypes = {// Codetxt: textFile("text/plain", "plain"),md: textFile("text/markdown", "markdown"),+ mdx: textFile("text/mdx", "markdown"),js: textFile("text/javascript", "javascript"),css: textFile("text/css", "css"),json: textFile("application/json", "json"),diff --git a/packages/sdk/src/content-block.test.ts b/packages/sdk/src/content-block.test.tsnew file mode 100644index 0000000000..4d56ec3758--- /dev/null+++ b/packages/sdk/src/content-block.test.ts@@ -0,0 +1,256 @@+import { describe, expect, test } from "vitest";+import { blockComponent } from "./core-metas";+import type { FileAsset } from "./schema/assets";+import type { Instance } from "./schema/instances";+import type { Prop } from "./schema/props";+import {+ allocateUniqueContentBlockTemplateName,+ getContentBlockSourceIntegrityIssues,+ parseContentBlockSourceProp,+} from "./content-block";++const block: Instance = {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [],+};++const sourceProp = (values: Partial<Prop> = {}): Prop =>+ ({+ id: "source-prop",+ instanceId: block.id,+ name: "src",+ type: "asset",+ value: "post",+ ...values,+ }) as Prop;++const mdxAsset: FileAsset = {+ id: "post",+ projectId: "project",+ type: "file",+ name: "post_hash.mdx",+ filename: "post",+ format: "mdx",+ size: 1,+ meta: {},+ description: null,+ createdAt: "2026-08-14T00:00:00.000Z",+};++describe("Content Block source", () => {+ test("keeps the source optional for existing Content Blocks", () => {+ expect(+ getContentBlockSourceIntegrityIssues({+ instances: [block],+ props: [],+ assets: [],+ })+ ).toEqual([]);+ });++ test("maps persisted Asset and expression props to the source contract", () => {+ expect(parseContentBlockSourceProp(sourceProp())).toEqual({+ type: "asset",+ assetId: "post",+ });+ expect(+ parseContentBlockSourceProp(+ sourceProp({ type: "expression", value: "post.body" })+ )+ ).toEqual({ type: "expression", value: "post.body" });+ expect(+ parseContentBlockSourceProp(sourceProp({ type: "string", value: "post" }))+ ).toBeUndefined();+ });++ test("diagnoses duplicate, invalid, missing, and incompatible sources", () => {+ expect(+ getContentBlockSourceIntegrityIssues({+ instances: [block],+ props: [sourceProp(), sourceProp({ id: "other-source" })],+ assets: [mdxAsset],+ })+ ).toEqual([+ {+ type: "duplicateContentBlockSource",+ blockInstanceId: "block",+ propIds: ["source-prop", "other-source"],+ },+ ]);+ expect(+ getContentBlockSourceIntegrityIssues({+ instances: [block],+ props: [sourceProp({ type: "string" })],+ assets: [mdxAsset],+ })+ ).toEqual([+ {+ type: "invalidContentBlockSource",+ blockInstanceId: "block",+ propId: "source-prop",+ propType: "string",+ },+ ]);+ expect(+ getContentBlockSourceIntegrityIssues({+ instances: [block],+ props: [sourceProp()],+ assets: [],+ })+ ).toEqual([+ {+ type: "missingContentBlockSourceAsset",+ blockInstanceId: "block",+ propId: "source-prop",+ assetId: "post",+ },+ ]);+ expect(+ getContentBlockSourceIntegrityIssues({+ instances: [block],+ props: [sourceProp()],+ assets: [{ ...mdxAsset, name: "post_hash.md", format: "md" }],+ })+ ).toEqual([+ {+ type: "incompatibleContentBlockSourceAsset",+ blockInstanceId: "block",+ propId: "source-prop",+ assetId: "post",+ assetName: "post_hash.md",+ },+ ]);+ expect(+ getContentBlockSourceIntegrityIssues({+ instances: [block],+ props: [sourceProp()],+ assets: [mdxAsset],+ })+ ).toEqual([]);+ });+});++describe("allocateUniqueContentBlockTemplateName", () => {+ test.each([+ {+ name: "Card",+ existingNames: [],+ expected: "Card",+ reason: "keeps an unused name",+ },+ {+ name: " Card ",+ existingNames: [],+ expected: "Card",+ reason: "trims an unused name",+ },+ {+ name: "Card",+ existingNames: ["Card"],+ expected: "Card 2",+ reason: "adds the first suffix",+ },+ {+ name: "Card",+ existingNames: ["Card", "Card 2"],+ expected: "Card 3",+ reason: "skips a consecutive collision",+ },+ {+ name: "Card",+ existingNames: ["Card", "Card 3"],+ expected: "Card 2",+ reason: "fills the first available suffix",+ },+ {+ name: "Card 2",+ existingNames: ["Card 2"],+ expected: "Card 3",+ reason: "increments an existing suffix",+ },+ {+ name: "Card 2",+ existingNames: ["Card 2", "Card 3", "Card 5"],+ expected: "Card 4",+ reason: "fills a gap after an existing suffix",+ },+ {+ name: "Card 20",+ existingNames: ["Card 20"],+ expected: "Card 21",+ reason: "increments a multi-digit suffix",+ },+ {+ name: "Card 1",+ existingNames: ["Card 1"],+ expected: "Card 1 2",+ reason: "treats one as part of the base name",+ },+ {+ name: "Card 0",+ existingNames: ["Card 0"],+ expected: "Card 0 2",+ reason: "treats zero as part of the base name",+ },+ {+ name: "Card -2",+ existingNames: ["Card -2"],+ expected: "Card -2 2",+ reason: "does not interpret a negative suffix",+ },+ {+ name: "Card 2.5",+ existingNames: ["Card 2.5"],+ expected: "Card 2.5 2",+ reason: "does not interpret a decimal suffix",+ },+ {+ name: "Card 9007199254740992",+ existingNames: ["Card 9007199254740992"],+ expected: "Card 9007199254740992 2",+ reason: "does not increment an unsafe integer suffix",+ },+ {+ name: "Card 9007199254740991",+ existingNames: ["Card 9007199254740991"],+ expected: "Card 9007199254740991 2",+ reason: "does not increment past the safe integer range",+ },+ {+ name: "Card 9007199254740990",+ existingNames: ["Card 9007199254740990", "Card 9007199254740991"],+ expected: "Card 9007199254740991 2",+ reason: "falls back after colliding at the safe integer boundary",+ },+ {+ name: "Card 02",+ existingNames: ["Card 02"],+ expected: "Card 3",+ reason: "normalizes an incremented numeric suffix",+ },+ {+ name: "card",+ existingNames: ["Card"],+ expected: "card",+ reason: "matches names case-sensitively",+ },+ {+ name: "Héro 🦸",+ existingNames: ["Héro 🦸"],+ expected: "Héro 🦸 2",+ reason: "preserves Unicode names",+ },+ ])("$reason", ({ name, existingNames, expected }) => {+ const names = new Set(existingNames);++ expect(+ allocateUniqueContentBlockTemplateName({+ name,+ existingNames: names,+ })+ ).toBe(expected);+ expect(names).toEqual(new Set(existingNames));+ });+});diff --git a/packages/sdk/src/content-block.ts b/packages/sdk/src/content-block.tsnew file mode 100644index 0000000000..12babb0503--- /dev/null+++ b/packages/sdk/src/content-block.ts@@ -0,0 +1,205 @@+import { getAssetDisplayNameParts } from "./assets";+import { blockComponent } from "./core-metas";+import {+ contentBlockSourceProp,+ contentBlockSourcePropSchema,+ type ContentBlockSource,+} from "./schema/content-block";+import type { Asset } from "./schema/assets";+import type { Instance } from "./schema/instances";+import type { Prop } from "./schema/props";++export const parseContentBlockSourceProp = (+ prop: Prop+): ContentBlockSource | undefined => {+ const result = contentBlockSourcePropSchema.safeParse(prop);+ if (result.success === false) {+ return;+ }+ if (result.data.type === "asset") {+ return { type: "asset", assetId: result.data.value };+ }+ if (result.data.type === "expression") {+ return { type: "expression", value: result.data.value };+ }+};++export const getContentBlockSource = ({+ blockInstanceId,+ props,+}: {+ blockInstanceId: Instance["id"];+ props: Iterable<Prop>;+}) => {+ let sourceProp: Prop | undefined;+ for (const prop of props) {+ if (+ prop.instanceId !== blockInstanceId ||+ prop.name !== contentBlockSourceProp+ ) {+ continue;+ }+ if (sourceProp !== undefined) {+ return;+ }+ sourceProp = prop;+ }+ return sourceProp === undefined+ ? undefined+ : parseContentBlockSourceProp(sourceProp);+};++export type ContentBlockSourceIntegrityIssue =+ | {+ type: "duplicateContentBlockSource";+ blockInstanceId: Instance["id"];+ propIds: Prop["id"][];+ }+ | {+ type: "invalidContentBlockSource";+ blockInstanceId: Instance["id"];+ propId: Prop["id"];+ propType: Prop["type"];+ }+ | {+ type: "missingContentBlockSourceAsset";+ blockInstanceId: Instance["id"];+ propId: Prop["id"];+ assetId: Asset["id"];+ }+ | {+ type: "incompatibleContentBlockSourceAsset";+ blockInstanceId: Instance["id"];+ propId: Prop["id"];+ assetId: Asset["id"];+ assetName: Asset["name"];+ };++export const formatContentBlockSourceIntegrityIssue = (+ issue: ContentBlockSourceIntegrityIssue+) => {+ if (issue.type === "duplicateContentBlockSource") {+ return `Content Block "${issue.blockInstanceId}" has multiple source props: ${issue.propIds.map((id) => `"${id}"`).join(", ")}.`;+ }+ if (issue.type === "invalidContentBlockSource") {+ return `Content Block source prop "${issue.propId}" must use an Asset or expression binding.`;+ }+ if (issue.type === "missingContentBlockSourceAsset") {+ return `Content Block source prop "${issue.propId}" references missing Asset "${issue.assetId}".`;+ }+ return `Content Block source prop "${issue.propId}" references Asset "${issue.assetId}" (${issue.assetName}), which is not an MDX file.`;+};++export const getContentBlockSourceIntegrityIssues = ({+ instances,+ props,+ assets,+}: {+ instances: Iterable<Instance>;+ props: Iterable<Prop>;+ assets?: Iterable<Asset>;+}): ContentBlockSourceIntegrityIssue[] => {+ const sourcePropsByInstanceId = new Map<Instance["id"], Prop[]>();+ for (const prop of props) {+ if (prop.name !== contentBlockSourceProp) {+ continue;+ }+ const sourceProps = sourcePropsByInstanceId.get(prop.instanceId) ?? [];+ sourceProps.push(prop);+ sourcePropsByInstanceId.set(prop.instanceId, sourceProps);+ }+ const assetsById =+ assets === undefined+ ? undefined+ : new Map(Array.from(assets, (asset) => [asset.id, asset]));+ const issues: ContentBlockSourceIntegrityIssue[] = [];+ for (const instance of instances) {+ if (instance.component !== blockComponent) {+ continue;+ }+ const sourceProps = sourcePropsByInstanceId.get(instance.id) ?? [];+ if (sourceProps.length > 1) {+ issues.push({+ type: "duplicateContentBlockSource",+ blockInstanceId: instance.id,+ propIds: sourceProps.map((prop) => prop.id),+ });+ continue;+ }+ const [prop] = sourceProps;+ if (prop === undefined) {+ continue;+ }+ const source = parseContentBlockSourceProp(prop);+ if (source === undefined) {+ issues.push({+ type: "invalidContentBlockSource",+ blockInstanceId: instance.id,+ propId: prop.id,+ propType: prop.type,+ });+ continue;+ }+ if (source.type !== "asset" || assetsById === undefined) {+ continue;+ }+ const asset = assetsById.get(source.assetId);+ if (asset === undefined) {+ issues.push({+ type: "missingContentBlockSourceAsset",+ blockInstanceId: instance.id,+ propId: prop.id,+ assetId: source.assetId,+ });+ continue;+ }+ if (+ asset.type !== "file" ||+ getAssetDisplayNameParts(asset).ext.toLowerCase() !== "mdx"+ ) {+ issues.push({+ type: "incompatibleContentBlockSourceAsset",+ blockInstanceId: instance.id,+ propId: prop.id,+ assetId: asset.id,+ assetName: asset.name,+ });+ }+ }+ return issues;+};++export const allocateUniqueContentBlockTemplateName = ({+ name,+ existingNames,+}: {+ name: string;+ existingNames: ReadonlySet<string>;+}) => {+ const normalizedName = name.trim();+ if (existingNames.has(normalizedName) === false) {+ return normalizedName;+ }++ const suffixMatch = /^(.*) (\d+)$/.exec(normalizedName);+ let baseName = normalizedName;+ let index = 2;+ if (suffixMatch !== null) {+ const suffix = Number(suffixMatch[2]);+ if (suffix >= 2 && Number.isSafeInteger(suffix + 1)) {+ baseName = suffixMatch[1];+ index = suffix + 1;+ }+ }+ let candidate = `${baseName} ${index}`;+ while (existingNames.has(candidate)) {+ if (Number.isSafeInteger(index + 1) === false) {+ baseName = candidate;+ index = 2;+ } else {+ index += 1;+ }+ candidate = `${baseName} ${index}`;+ }+ return candidate;+};diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.tsindex 5c40e2e7d7..1d8acbc9d4 100644--- a/packages/sdk/src/index.ts+++ b/packages/sdk/src/index.ts@@ -14,12 +14,14 @@ export * from "./schema/deployment";export * from "./schema/webstudio";export * from "./schema/prop-meta";export * from "./schema/component-meta";+export * from "./schema/content-block";export * from "./assets";export * from "./asset-folder-hierarchy";export * from "./asset-folder-normalization";export * from "./asset-resource-config";export * from "./core-metas";+export * from "./content-block";export * from "./instances-utils";export * from "./page-utils";export * from "./scope";diff --git a/packages/sdk/src/instances-utils.test.tsx b/packages/sdk/src/instances-utils.test.tsxindex 2bdb308a61..ace41f9b95 100644--- a/packages/sdk/src/instances-utils.test.tsx+++ b/packages/sdk/src/instances-utils.test.tsx@@ -1,11 +1,14 @@import { expect, test } from "vitest";import { $, renderData, ws } from "@webstudio-is/template";import {+ findChildReferenceIndex,findTreeInstanceIds,findTreeInstanceIdsExcludingSlotDescendants,+ findParentInstanceReference,getHtmlTagsFromProps,getHtmlTagFromInstance,getIndexesWithinAncestors,+ getInstanceName,parseComponentName,} from "./instances-utils";import type { WsComponentMeta } from "./schema/component-meta";@@ -51,11 +54,79 @@ test("include not existing/virtual instance", () => {).toEqual(new Set([":root"]));});+test("finds the direct parent instance reference", () => {+ const instances = new Map<Instance["id"], Instance>([+ [+ "parent",+ {+ type: "instance",+ id: "parent",+ component: "Box",+ children: [+ { type: "text", value: "before" },+ { type: "id", value: "child" },+ ],+ },+ ],+ [+ "child",+ {+ type: "instance",+ id: "child",+ component: "Box",+ children: [],+ },+ ],+ ]);++ expect(findParentInstanceReference(instances, "child")).toEqual({+ instance: instances.get("parent"),+ childIndex: 1,+ });+ expect(findParentInstanceReference(instances, "missing")).toBeUndefined();+});++test("finds child reference index", () => {+ expect(+ findChildReferenceIndex(+ [+ { type: "text", value: "before" },+ { type: "id", value: "child" },+ { type: "text", value: "after" },+ ],+ "child"+ )+ ).toBe(1);+ expect(+ findChildReferenceIndex([{ type: "text", value: "only" }], "child")+ ).toBe(-1);+});+test("extract short name and namespace from component name", () => {expect(parseComponentName("Box")).toEqual([undefined, "Box"]);expect(parseComponentName("radix:Box")).toEqual(["radix", "Box"]);});+test("gets the instance name from user label, element tag, or component", () => {+ expect(+ getInstanceName({+ instance: { component: "Box", label: "Hero Card" },+ metas: new Map([["Box", { label: "Box" }]]),+ })+ ).toBe("Hero Card");+ expect(+ getInstanceName({+ instance: { component: "ws:element", tag: "article" },+ metas: new Map([["ws:element", { label: "Element" }]]),+ })+ ).toBe("<article>");+ expect(+ getInstanceName({+ instance: { component: "custom:HeroCard" },+ })+ ).toBe("HeroCard");+});+test("get html tag from instance", () => {const metas = new Map<Instance["component"], WsComponentMeta>([["Box", { presetStyle: { section: [] } }],diff --git a/packages/sdk/src/instances-utils.ts b/packages/sdk/src/instances-utils.tsindex 3ba6de26fe..12b69ed9b1 100644--- a/packages/sdk/src/instances-utils.ts+++ b/packages/sdk/src/instances-utils.ts@@ -1,7 +1,7 @@import type { WsComponentMeta } from "./schema/component-meta";import type { Instance, Instances } from "./schema/instances";import type { Props } from "./schema/props";-import { blockTemplateComponent } from "./core-metas";+import { blockTemplateComponent, elementComponent } from "./core-metas";export const ROOT_INSTANCE_ID = ":root";@@ -50,6 +50,26 @@ export const findTreeInstanceIdsExcludingSlotDescendants = (return ids;};+export const findChildReferenceIndex = (+ children: Instance["children"],+ instanceId: Instance["id"]+) =>+ children.findIndex(+ (child) => child.type === "id" && child.value === instanceId+ );++export const findParentInstanceReference = (+ instances: Instances,+ instanceId: Instance["id"]+) => {+ for (const instance of instances.values()) {+ const childIndex = findChildReferenceIndex(instance.children, instanceId);+ if (childIndex !== -1) {+ return { instance, childIndex };+ }+ }+};+export const parseComponentName = (componentName: string) => {const parts = componentName.split(":");let namespace: undefined | string;@@ -62,6 +82,33 @@ export const parseComponentName = (componentName: string) => {return [namespace, name] as const;};+/**+ * Returns the instance name shown to users. The component or tag supplies the+ * default name; `instance.label` is the user-defined override created by+ * renaming the instance.+ */+export const getInstanceName = ({+ instance,+ metas,+ fallbackName,+}: {+ instance: Pick<Instance, "component" | "label" | "tag">;+ metas?: ReadonlyMap<Instance["component"], Pick<WsComponentMeta, "label">>;+ fallbackName?: string;+}) => {+ if (instance.label) {+ return instance.label;+ }+ if (instance.component === elementComponent && instance.tag) {+ return `<${instance.tag}>`;+ }+ return (+ metas?.get(instance.component)?.label ||+ fallbackName ||+ parseComponentName(instance.component)[1]+ );+};+export const getHtmlTagsFromProps = (props: Props) => {const tags = new Map<Instance["id"], string>();for (const prop of props.values()) {diff --git a/packages/sdk/src/resources-generator.test.tsx b/packages/sdk/src/resources-generator.test.tsxindex ee1e0950a4..116d31dbc3 100644--- a/packages/sdk/src/resources-generator.test.tsx+++ b/packages/sdk/src/resources-generator.test.tsx@@ -12,6 +12,7 @@ import {replaceFormActionsWithResources,} from "./resources-generator";import type { DataSource } from "./schema/data-sources";+import { encodeDataSourceVariable } from "./expression";const toMap = <T extends { id: string }>(list: T[]) =>new Map(list.map((item) => [item.id, item] as const));@@ -44,7 +45,7 @@ test("generate resources loader", () => {})).toMatchInlineSnapshot(`"import type { System, ResourceRequest } from "@webstudio-is/sdk";- export const getResources = (_props: { system: System }) => {+ export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const resourceName: ResourceRequest = {name: "resourceName",url: "https://my-json.com",@@ -59,14 +60,136 @@ test("generate resources loader", () => {const _data = new Map<string, ResourceRequest>([["resourceName", resourceName],])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}"`);});+test("selects only the active dynamic Content Block resources after base resources load", () => {+ const postsVariable = encodeDataSourceVariable("postsVariable");+ const generated = generateResources({+ scope: createScope(),+ page: { rootInstanceId: "body" } as Page,+ dataSources: toMap([+ {+ id: "postsVariable",+ scopeInstanceId: "body",+ type: "resource",+ name: "Posts",+ resourceId: "postsResource",+ },+ {+ id: "articleVariable",+ scopeInstanceId: "article",+ type: "resource",+ name: "Article API",+ resourceId: "articleResource",+ },+ {+ id: "otherVariable",+ scopeInstanceId: "other",+ type: "resource",+ name: "Other API",+ resourceId: "otherResource",+ },+ ]),+ resources: toMap([+ {+ id: "postsResource",+ name: "Posts",+ url: '"https://example.com/posts"',+ method: "get",+ headers: [],+ },+ {+ id: "articleResource",+ name: "Article API",+ url: '"https://example.com/article"',+ method: "get",+ headers: [],+ },+ {+ id: "otherResource",+ name: "Other API",+ url: '"https://example.com/other"',+ method: "get",+ headers: [],+ },+ ]),+ props: new Map(),+ contentBlockResourceSelections: [+ {+ sourceExpression: `${postsVariable}.data.properties.mdx`,+ candidates: [+ { assetId: "article", resourceIds: ["articleResource"] },+ { assetId: "other", resourceIds: ["otherResource"] },+ ],+ },+ ],+ });++ expect(generated).toContain('const Posts_1 = _props.resources?.["Posts"]');+ expect(generated).toContain(+ 'if (Posts_1?.data?.properties?.mdx === "article")'+ );+ expect(generated).toContain('_contentData.set("ArticleAPI", ArticleAPI)');+ expect(generated).toContain(+ 'if (Posts_1?.data?.properties?.mdx === "other")'+ );+ expect(generated).toContain('_contentData.set("OtherAPI", OtherAPI)');+ expect(generated).toContain('["Posts", Posts]');+ expect(generated).not.toContain('["ArticleAPI", ArticleAPI],');+ expect(generated).not.toContain('["OtherAPI", OtherAPI],');+});++test("rejects dynamic Content Block resources selected by a scoped parameter", () => {+ expect(() =>+ generateResources({+ scope: createScope(),+ page: { rootInstanceId: "body" } as Page,+ dataSources: toMap([+ {+ id: "collectionItem",+ scopeInstanceId: "collection",+ type: "parameter",+ name: "collectionItem",+ },+ {+ id: "articleVariable",+ scopeInstanceId: "article",+ type: "resource",+ name: "Article API",+ resourceId: "articleResource",+ },+ ]),+ resources: toMap([+ {+ id: "articleResource",+ name: "Article API",+ url: '"https://example.com/article"',+ method: "get",+ headers: [],+ },+ ]),+ props: new Map(),+ contentBlockResourceSelections: [+ {+ sourceExpression: `${encodeDataSourceVariable("collectionItem")}.mdx`,+ candidates: [+ { assetId: "article", resourceIds: ["articleResource"] },+ ],+ },+ ],+ })+ ).toThrow(+ "Dynamic Content Block Resources require a source available after base Resources load"+ );+});+test("generates a configured Assets request on the standard endpoint", () => {const generated = generateResources({scope: createScope(),@@ -140,7 +263,7 @@ test("generate variable and use in resources loader", () => {})).toMatchInlineSnapshot(`"import type { System, ResourceRequest } from "@webstudio-is/sdk";- export const getResources = (_props: { system: System }) => {+ export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {let AccessToken = "my-token"const resourceName: ResourceRequest = {name: "resourceName",@@ -156,9 +279,10 @@ test("generate variable and use in resources loader", () => {const _data = new Map<string, ResourceRequest>([["resourceName", resourceName],])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}"`);@@ -202,7 +326,7 @@ test("generate page system variable and use in resources loader", () => {})).toMatchInlineSnapshot(`"import type { System, ResourceRequest } from "@webstudio-is/sdk";- export const getResources = (_props: { system: System }) => {+ export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const system = _props.systemconst resourceName: ResourceRequest = {name: "resourceName",@@ -218,9 +342,10 @@ test("generate page system variable and use in resources loader", () => {const _data = new Map<string, ResourceRequest>([["resourceName", resourceName],])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}"`);@@ -246,7 +371,7 @@ test("generate global system variable and use in resources loader", () => {})).toMatchInlineSnapshot(`"import type { System, ResourceRequest } from "@webstudio-is/sdk";- export const getResources = (_props: { system: System }) => {+ export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const system = _props.systemconst MyResource: ResourceRequest = {name: "My Resource",@@ -263,9 +388,10 @@ test("generate global system variable and use in resources loader", () => {const _data = new Map<string, ResourceRequest>([["MyResource", MyResource],])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}"`);@@ -282,12 +408,13 @@ test("generate empty resources loader", () => {})).toMatchInlineSnapshot(`"import type { System, ResourceRequest } from "@webstudio-is/sdk";- export const getResources = (_props: { system: System }) => {+ export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}"`);@@ -333,7 +460,7 @@ test("generate resource loader with search params", () => {})).toMatchInlineSnapshot(`"import type { System, ResourceRequest } from "@webstudio-is/sdk";- export const getResources = (_props: { system: System }) => {+ export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {let term = "my-term"const resourceName: ResourceRequest = {name: "resourceName",@@ -348,9 +475,10 @@ test("generate resource loader with search params", () => {const _data = new Map<string, ResourceRequest>([["resourceName", resourceName],])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}"`);@@ -375,12 +503,13 @@ test("prevent generating unused variables", () => {})).toMatchInlineSnapshot(`"import type { System, ResourceRequest } from "@webstudio-is/sdk";- export const getResources = (_props: { system: System }) => {+ export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}"`);@@ -407,12 +536,13 @@ test("prevent generating unused system variable", () => {})).toMatchInlineSnapshot(`"import type { System, ResourceRequest } from "@webstudio-is/sdk";- export const getResources = (_props: { system: System }) => {+ export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}"`);@@ -456,7 +586,7 @@ test("generate action resource without loading a stale data source", () => {})).toMatchInlineSnapshot(`"import type { System, ResourceRequest } from "@webstudio-is/sdk";- export const getResources = (_props: { system: System }) => {+ export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const resourceName: ResourceRequest = {name: "resourceName",url: "https://my-url.com",@@ -468,10 +598,11 @@ test("generate action resource without loading a stale data source", () => {}const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([["resourceName", resourceName],])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}"`);@@ -496,12 +627,13 @@ test("skip missing resource referenced by data source", () => {})).toMatchInlineSnapshot(`"import type { System, ResourceRequest } from "@webstudio-is/sdk";- export const getResources = (_props: { system: System }) => {+ export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}"`);@@ -526,12 +658,13 @@ test("skip missing resource referenced by action prop", () => {})).toMatchInlineSnapshot(`"import type { System, ResourceRequest } from "@webstudio-is/sdk";- export const getResources = (_props: { system: System }) => {+ export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {const _data = new Map<string, ResourceRequest>([])+ const _contentData = new Map<string, ResourceRequest>()const _action = new Map<string, ResourceRequest>([])- return { data: _data, action: _action }+ return { data: _data, action: _action, contentData: _contentData }}"`);diff --git a/packages/sdk/src/resources-generator.ts b/packages/sdk/src/resources-generator.tsindex 4ff40c149f..d2cefdae5b 100644--- a/packages/sdk/src/resources-generator.ts+++ b/packages/sdk/src/resources-generator.ts@@ -12,15 +12,28 @@ export const generateResources = ({dataSources,props,resources,+ contentBlockResourceSelections = [],}: {scope: Scope;page: Page;dataSources: DataSources;props: Props;resources: Resources;+ contentBlockResourceSelections?: readonly {+ sourceExpression: string;+ candidates: readonly {+ assetId: string;+ resourceIds: readonly string[];+ }[];+ }[];}) => {const usedDataSources: DataSources = new Map();const generatedResourceIds = new Set<string>();+ const selectedResourceIds = new Set(+ contentBlockResourceSelections.flatMap(({ candidates }) =>+ candidates.flatMap(({ resourceIds }) => resourceIds)+ )+ );let generatedRequests = "";for (const resource of resources.values()) {@@ -77,6 +90,40 @@ export const generateResources = ({generatedRequests += generatedRequest;}+ const generatedContentSelections = contentBlockResourceSelections.map(+ ({ sourceExpression, candidates }) => {+ const selectionDataSources: DataSources = new Map();+ const source = generateExpression({+ expression: sourceExpression,+ dataSources,+ usedDataSources: selectionDataSources,+ scope,+ });+ const hasResources = candidates.some(+ ({ resourceIds }) => resourceIds.length > 0+ );+ if (hasResources) {+ for (const dataSource of selectionDataSources.values()) {+ if (+ (dataSource.type === "parameter" &&+ dataSource.id !== page.systemDataSourceId &&+ dataSource.id !== SYSTEM_VARIABLE_ID) ||+ (dataSource.type === "resource" &&+ selectedResourceIds.has(dataSource.resourceId))+ ) {+ throw new Error(+ "Dynamic Content Block Resources require a source available after base Resources load"+ );+ }+ }+ }+ for (const dataSource of selectionDataSources.values()) {+ usedDataSources.set(dataSource.id, dataSource);+ }+ return { source, candidates };+ }+ );+let generatedVariables = "";for (const dataSource of usedDataSources.values()) {if (dataSource.type === "variable") {@@ -95,11 +142,20 @@ export const generateResources = ({generatedVariables += ` const ${name} = _props.system\n`;}}++ if (dataSource.type === "resource") {+ const name = scope.getName(dataSource.id, dataSource.name);+ const resourceName = scope.getName(+ dataSource.resourceId,+ dataSource.name+ );+ generatedVariables += ` const ${name} = _props.resources?.[${JSON.stringify(resourceName)}]\n`;+ }}let generated = "";generated += `import type { System, ResourceRequest } from "@webstudio-is/sdk";\n`;- generated += `export const getResources = (_props: { system: System }) => {\n`;+ generated += `export const getResources = (_props: { system: System; resources?: Record<string, any> }) => {\n`;generated += generatedVariables;generated += generatedRequests;@@ -115,6 +171,7 @@ export const generateResources = ({if (dataSource.type === "resource" &&generatedResourceIds.has(dataSource.resourceId) &&+ selectedResourceIds.has(dataSource.resourceId) === false &&actionResourceIds.has(dataSource.resourceId) === false) {const name = scope.getName(dataSource.resourceId, dataSource.name);@@ -123,6 +180,26 @@ export const generateResources = ({}generated += ` ])\n`;+ generated += ` const _contentData = new Map<string, ResourceRequest>()\n`;+ for (const { source, candidates } of generatedContentSelections) {+ for (const { assetId, resourceIds } of candidates) {+ generated += ` if (${source} === ${JSON.stringify(assetId)}) {\n`;+ for (const dataSource of dataSources.values()) {+ if (+ dataSource.type !== "resource" ||+ resourceIds.includes(dataSource.resourceId) === false ||+ generatedResourceIds.has(dataSource.resourceId) === false ||+ actionResourceIds.has(dataSource.resourceId)+ ) {+ continue;+ }+ const name = scope.getName(dataSource.resourceId, dataSource.name);+ generated += ` _contentData.set(${JSON.stringify(name)}, ${name})\n`;+ }+ generated += ` }\n`;+ }+ }+generated += ` const _action = new Map<string, ResourceRequest>([\n`;for (const prop of props.values()) {if (prop.type === "resource" && generatedResourceIds.has(prop.value)) {@@ -132,7 +209,7 @@ export const generateResources = ({}generated += ` ])\n`;- generated += ` return { data: _data, action: _action }\n`;+ generated += ` return { data: _data, action: _action, contentData: _contentData }\n`;generated += `}\n`;return generated;diff --git a/packages/sdk/src/schema.ts b/packages/sdk/src/schema.tsindex 2a921b57c7..5e2edfab8a 100644--- a/packages/sdk/src/schema.ts+++ b/packages/sdk/src/schema.ts@@ -5,6 +5,7 @@ export * from "./schema/assets";export * from "./schema/asset-resource";export * from "./schema/asset-folders";export * from "./schema/breakpoints";+export * from "./schema/content-block";export * from "./schema/data-sources";export * from "./schema/deployment";export * from "./schema/instances";diff --git a/packages/sdk/src/schema/content-block.test.ts b/packages/sdk/src/schema/content-block.test.tsnew file mode 100644index 0000000000..4a6aee2604--- /dev/null+++ b/packages/sdk/src/schema/content-block.test.ts@@ -0,0 +1,133 @@+import { describe, expect, test } from "vitest";+import {+ contentBlockDiagnostic,+ contentBlockExternalContentIdentity,+ contentBlockSource,+ contentBlockSourcePropSchema,+} from "./content-block";++describe("content block source", () => {+ test("accepts direct assets and dynamic expressions", () => {+ expect(+ contentBlockSource.parse({ type: "asset", assetId: "asset-id" })+ ).toEqual({ type: "asset", assetId: "asset-id" });+ expect(+ contentBlockSource.parse({ type: "expression", value: "post.body" })+ ).toEqual({ type: "expression", value: "post.body" });+ });++ test("rejects empty and mixed source identities", () => {+ expect(+ contentBlockSource.safeParse({ type: "asset", assetId: "" }).success+ ).toBe(false);+ expect(+ contentBlockSource.safeParse({+ type: "asset",+ assetId: "asset-id",+ value: "post.body",+ }).success+ ).toBe(false);+ });++ test("parses persisted source props without accepting other prop types", () => {+ expect(+ contentBlockSourcePropSchema.parse({+ id: "source-prop",+ instanceId: "block",+ name: "src",+ type: "asset",+ value: "asset-id",+ })+ ).toMatchObject({ type: "asset", value: "asset-id" });+ expect(+ contentBlockSourcePropSchema.parse({+ id: "source-prop",+ instanceId: "block",+ name: "src",+ type: "expression",+ value: "post.body",+ })+ ).toMatchObject({ type: "expression", value: "post.body" });+ expect(+ contentBlockSourcePropSchema.safeParse({+ id: "source-prop",+ instanceId: "block",+ name: "src",+ type: "string",+ value: "asset-id",+ }).success+ ).toBe(false);+ });+});++test("validates resolved external content identity", () => {+ expect(+ contentBlockExternalContentIdentity.parse({+ blockInstanceId: "block",+ assetId: "asset",+ revision: "revision-1",+ contentRef: "assets/post.mdx",+ format: "mdx",+ renderScope: "route:/posts/hello",+ })+ ).toEqual({+ blockInstanceId: "block",+ assetId: "asset",+ revision: "revision-1",+ contentRef: "assets/post.mdx",+ format: "mdx",+ renderScope: "route:/posts/hello",+ });+ expect(+ contentBlockExternalContentIdentity.safeParse({+ blockInstanceId: "block",+ assetId: "asset",+ revision: "revision-1",+ contentRef: "assets/post.mdx",+ format: "md",+ renderScope: "route:/posts/hello",+ }).success+ ).toBe(false);+});++describe("content block diagnostics", () => {+ test("accepts typed template diagnostics with source locations", () => {+ expect(+ contentBlockDiagnostic.parse({+ code: "unresolved-template",+ severity: "warning",+ blockInstanceId: "block",+ assetId: "asset",+ templateName: "Hero Card",+ sourceRange: {+ start: { line: 3, column: 1, offset: 20 },+ end: { line: 5, column: 14, offset: 80 },+ },+ })+ ).toMatchObject({+ code: "unresolved-template",+ templateName: "Hero Card",+ });+ });++ test("rejects mismatched severities and payloads", () => {+ expect(+ contentBlockDiagnostic.safeParse({+ code: "unresolved-template",+ severity: "error",+ blockInstanceId: "block",+ templateName: "Hero Card",+ }).success+ ).toBe(false);+ expect(+ contentBlockDiagnostic.safeParse({+ code: "ignored-template-prop",+ severity: "warning",+ blockInstanceId: "block",+ templateName: "Hero Card",+ propName: "tone",+ reason: "unsupported",+ }).success+ ).toBe(false);+ });+});diff --git a/packages/sdk/src/schema/content-block.ts b/packages/sdk/src/schema/content-block.tsnew file mode 100644index 0000000000..7c0c2284f5--- /dev/null+++ b/packages/sdk/src/schema/content-block.ts@@ -0,0 +1,123 @@+import { z } from "zod";+import { prop } from "./props";++export const contentBlockSourceProp = "src";++export const contentBlockSource = z.discriminatedUnion("type", [+ z.strictObject({+ type: z.literal("asset"),+ assetId: z.string().min(1),+ }),+ z.strictObject({+ type: z.literal("expression"),+ value: z.string().min(1),+ }),+]);++export type ContentBlockSource = z.infer<typeof contentBlockSource>;++export const contentBlockSourcePropSchema = prop.refine(+ (value) =>+ value.name === contentBlockSourceProp &&+ (value.type === "asset" || value.type === "expression") &&+ value.value.length > 0+);++export const contentBlockExternalContentIdentity = z.strictObject({+ blockInstanceId: z.string().min(1),+ assetId: z.string().min(1),+ revision: z.string().min(1),+ contentRef: z.string().min(1),+ format: z.literal("mdx"),+ renderScope: z.string().min(1),+});++export type ContentBlockExternalContentIdentity = z.infer<+ typeof contentBlockExternalContentIdentity+>;++const sourcePoint = z.strictObject({+ line: z.number().int().positive(),+ column: z.number().int().positive(),+ offset: z.number().int().nonnegative().optional(),+});++export const contentBlockSourceRange = z.strictObject({+ start: sourcePoint,+ end: sourcePoint,+});++export type ContentBlockSourceRange = z.infer<typeof contentBlockSourceRange>;++const diagnosticContext = {+ blockInstanceId: z.string().min(1),+ assetId: z.string().min(1).optional(),+ contentRef: z.string().min(1).optional(),+ renderScope: z.string().min(1).optional(),+ sourceRange: contentBlockSourceRange.optional(),+};++export const contentBlockDiagnostic = z.discriminatedUnion("code", [+ z.strictObject({+ ...diagnosticContext,+ code: z.literal("invalid-mdx"),+ severity: z.literal("error"),+ message: z.string().min(1),+ }),+ z.strictObject({+ ...diagnosticContext,+ code: z.literal("unsafe-mdx"),+ severity: z.literal("error"),+ nodeType: z.string().min(1),+ reason: z.string().min(1),+ }),+ z.strictObject({+ ...diagnosticContext,+ code: z.literal("unresolved-template"),+ severity: z.literal("warning"),+ templateName: z.string().min(1),+ }),+ z.strictObject({+ ...diagnosticContext,+ code: z.literal("ignored-template-prop"),+ severity: z.literal("warning"),+ templateName: z.string().min(1),+ propName: z.string().min(1),+ reason: z.enum(["unknown", "incompatible", "design-only", "stale"]),+ }),+ z.strictObject({+ ...diagnosticContext,+ code: z.literal("stale-revision"),+ severity: z.literal("error"),+ expectedRevision: z.string().min(1),+ actualRevision: z.string().min(1).optional(),+ }),+ z.strictObject({+ ...diagnosticContext,+ code: z.literal("changed-binding"),+ severity: z.literal("error"),+ loadedAssetId: z.string().min(1),+ resolvedAssetId: z.string().min(1),+ }),+ z.strictObject({+ ...diagnosticContext,+ code: z.literal("pending-writes"),+ severity: z.literal("error"),+ pendingMutationCount: z.number().int().positive(),+ }),+ z.strictObject({+ ...diagnosticContext,+ code: z.literal("authorization-failed"),+ severity: z.literal("error"),+ operation: z.enum(["read", "write"]),+ }),+ z.strictObject({+ ...diagnosticContext,+ code: z.literal("partial-recovery"),+ severity: z.literal("error"),+ completedStorageRoots: z.array(z.string().min(1)),+ failedStorageRoots: z.array(z.string().min(1)).min(1),+ }),+]);++export type ContentBlockDiagnostic = z.infer<typeof contentBlockDiagnostic>;diff --git a/packages/sdk/src/schema/instances.ts b/packages/sdk/src/schema/instances.tsindex a9418db586..17ae06ebb6 100644--- a/packages/sdk/src/schema/instances.ts+++ b/packages/sdk/src/schema/instances.ts@@ -21,6 +21,9 @@ export const instanceTag = zexport const instanceAttributes = z.object({component: instanceComponent,tag: instanceTag.optional(),+ // An instance gets its default name from its component (or tag). Renaming the+ // instance stores this user-defined label, which becomes its displayed name+ // without changing the underlying component identity.label: z.string().optional(),});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b85a8e0194..6a783ffb44 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1415,6 +1415,9 @@ importers:'@vitejs/plugin-react':specifier: ^4.4.1version: 4.4.1([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ '@webstudio-is/asset-uploader':+ specifier: workspace:*+ version: link:../asset-uploader'@webstudio-is/content-engine':specifier: workspace:*version: link:../content-engine@@ -1538,21 +1541,57 @@ importers:canonicalize:specifier: 3.0.0version: 3.0.0+ hast-util-raw:+ specifier: 7.2.3+ version: 7.2.3+ hast-util-to-mdast:+ specifier: 9.0.0+ version: 9.0.0lru-cache:specifier: 10.4.3version: 10.4.3+ mdast-util-gfm:+ specifier: 2.0.2+ version: 2.0.2+ mdast-util-mdx-expression:+ specifier: 1.3.2+ version: 1.3.2+ mdast-util-mdx-jsx:+ specifier: 2.1.4+ version: 2.1.4+ mdast-util-to-hast:+ specifier: 12.3.0+ version: 12.3.0+ mdast-util-to-markdown:+ specifier: 1.5.0+ version: 1.5.0micromark:specifier: 4.0.2version: 4.0.2micromark-util-decode-string:specifier: 2.0.1version: 2.0.1+ property-information:+ specifier: 6.2.0+ version: 6.2.0+ remark-frontmatter:+ specifier: 4.0.1+ version: 4.0.1+ remark-gfm:+ specifier: 3.0.1+ version: 3.0.1+ remark-mdx:+ specifier: 2.3.0+ version: 2.3.0remark-parse:specifier: 10.0.2version: 10.0.2unified:specifier: 10.1.2version: 10.1.2+ vfile:+ specifier: 5.3.6+ version: 5.3.6yaml:specifier: 2.9.0version: 2.9.0@@ -2195,6 +2234,9 @@ importers:'@modelcontextprotocol/sdk':specifier: ^1.10.0version: 1.10.0+ '@webstudio-is/asset-uploader':+ specifier: workspace:*+ version: link:../asset-uploader'@webstudio-is/authorization-token':specifier: workspace:*version: link:../authorization-token@@ -2225,6 +2267,9 @@ importers:'@webstudio-is/project-migrations':specifier: workspace:*version: link:../project-migrations+ '@webstudio-is/protocol':+ specifier: workspace:*+ version: link:../protocol'@webstudio-is/query-builder':specifier: workspace:*version: link:../query-builder@@ -6738,6 +6783,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-ejlPM315qwLpaQlQDTjPdsUFSc6ZsP4AN6AlWnogPjQ7CVi7PYF3YVz+CY3jE2pwYf7E/7HlDAN0rV2GxTG0HQ==}+ '@types/[email protected]':+ resolution: {integrity: sha512-ArMouDUTJEz1SQRpFsT2rIw7DeqICFv5aaVzLSIYMYQSLcwcGOfT3VyglQs/p7K3F7fT4zxr0NWxYZIdifD6dA==}+'@types/[email protected]':resolution: {integrity: sha512-wN+8bYxIpJf+5oZdrdtaX04qUuWHcKxcDEgRS9Qm9ZClSHjzEn13SxUC+5eRM+4yXIeTYk8mTzLAWGF64847ew==}@@ -6774,6 +6822,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-gFnFp/JMzLHCwRf7tQHrNnfhN4eYBVYYI897CGX4MY1tzY9l2aLkVyx2IlKZ/SAqDbB3I1AOZW5gTMGGsqWliA==}+ '@types/[email protected]':+ resolution: {integrity: sha512-SuT16Q1K51EAVPz1K29DJ/sXjhSQ0zjvsypYJ6tlwVsRV9jwW5Adq2ch8Dq8kDBCkYnELS7N7VNCSB5nC56t/g==}+'@types/[email protected]':resolution: {integrity: sha512-JCB8C6SnDoQf0cNycqd/35A7MjcnK+ZTqE7judS6o7utxUCg6imJg3QK2qzHKszlTjcj2cn+NwMB2i96ubpj7w==}@@ -8575,21 +8626,60 @@ packages:resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-QUdSOP1/o+/TxXtpPFXR2mUg2P+ySrmlX7QjwHZCXqMFyYk7YmcGSvqRW+4XgXAoHifdE1t2PwFaQK33TqVjSw==}++ resolution: {integrity: sha512-Nz7FfPBuljzsN3tCQ4kCBKqdNhQE2l0Tn+X1ubgKBPRoiDIu1mL08Cfw4k7q71+Duyaw7DXDN+VTAp4Vh3oCOw==}++ resolution: {integrity: sha512-X2+RwZIMTMKpXUzlotatPzWj8bspCymtXH3cfG3iQKV+wPF53Vgaqxi/eLqGck0wKq1kS9nvoB1wchbCPEL8sg==}++ resolution: {integrity: sha512-S58hCexyKdD31vMsErvgLfflW6vYWo/ixRLPJTtkOvLld24vyI8vmYmkgLA5LG3la2ME7nm7dLGdm48gfLRBfw==}++ resolution: {integrity: sha512-O1bKah6mhgEq2WtVMk+Ta5K7pPMqsBBlmzysLdcwKVrqzZQ0CHqUPiIVspNhAG1rvxpvJjtGee17XfauZYKqVA==}++ resolution: {integrity: sha512-jdlwBjEexy1oGz0aJ2f4GKMaVKkA9jwjr4MjAAI22E5fM/TXVZHuS5OpONtdeIkRKqAaryQ2E9xNQxijoThSZA==}++ resolution: {integrity: sha512-yGkCfPkkfCyiLfK6KEl/orMDr/zgCnq/NaO9HfULx6/Zga5fso5eqQA5Ov/JZVqACygvw9shRYWgXNcG2ilo7w==}++ resolution: {integrity: sha512-RujVQfVsOrxzPOPSzZFiwofMArbQke6DJjnFfceiEbFh7S05CbPt0cYN+A5YeD3pso0JQk6O1aHBnx9+Pm2uqg==}+resolution: {integrity: sha512-kiGD9WIW3gRKK8Gao3n1f+ahUeTMeJUJILnIT2QNrPigDNdH7rJxzhEbh81UajGeAdAHFecT1a+fLVOCTq9B4Q==}+ resolution: {integrity: sha512-4tpQTUOr9BMjtYyNlt0P50mH7xj0Ks2xpo8M943Vykljf99HW6EzulIoJP1N3eKOSScEHzyzi9dm7/cn0RfGwA==}+resolution: {integrity: sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==}resolution: {integrity: sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==}+ resolution: {integrity: sha512-7Pl4mWA3JCSHx0s3A1CgJaFirkISDUJsu+DeJd/cHUAlVDgs1sITzg9HZAidSf9LUE7kl8Hf2ZJr1HZTfhV/Yw==}++ resolution: {integrity: sha512-YNRgAJkH2Jky5ySkIqFXTQiaqcAtJyVE+D5lkN6CdtOqrnkLfGYYrEcKuHOJZlp+MwjSwuD3fZuawI+sic/RBw==}++ resolution: {integrity: sha512-tcllLfp23dJJ+ju5wCCZHVpzsQQ43+moJbqVX3jNWPB7z/KFC4FyZD6R7y94cHL6MQ33YtMZL8Z0aIXXI4XFTw==}+resolution: {integrity: sha512-nAxA0v8+vXSBDt3AnRUNjyRIQ0rD+ntpbAp4LnPkumc5M9yUbSMa4XDU9Q6etY4f1Wp4bNgvc1yjiZtsTTrSng==}resolution: {integrity: sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==}+ resolution: {integrity: sha512-TtYPq24IldU8iKoJQqvZOuhi5CyCQRAbvDOX0x1eW6rsHSxa/1i2CCiptNTotGHJ3VoHRGmqiv6/D3q113ikkw==}+resolution: {integrity: sha512-Wv7UgbOswBXYMWQCrzuf5j6Yxs3Dz4Gm3hdrrMV88mD1bbL4khX5aojJvMRLOe30bj6eRo5TYRdcDwTEWl4Wbg==}@@ -8618,6 +8708,9 @@ packages:resolution: {integrity: sha512-KM1SNmemQtsD+OTInZTYKZNbyPzzVrjMR2Iz1Np+Y+bcxUh0dgKF4NtylJVkGZRLe3NklHizJ5k1Vd3ug1uTPA==}engines: {node: '>=18.20'}+ resolution: {integrity: sha512-0quDb7s97CfemeJAnW9wC0hw78MtW7NU3hqtCD75g2vFlDLt36llsYD7uB7SUzojLMP24N5IatXf7ylGXiGG9A==}+resolution: {integrity: sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==}@@ -9245,6 +9338,9 @@ packages:resolution: {integrity: sha512-WWC0ZuMzCyDHYCasEGs4IPvLyTGftYwh6wIEOULOF0HXcqZlhwRzrK0w2VUlxWA98xnvb/jszw4ZSkJ6ADpM6Q==}engines: {node: '>=0.10.0'}+ resolution: {integrity: sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==}+resolution: {integrity: sha512-ocnPZQLNpvbedwTy9kNrQEsknEfgvcLMvOtz3sFeWApDq1MXH1TqkCIx58xlpESsfwQOnuBO9beyQuNGzVvuhQ==}@@ -9261,6 +9357,9 @@ packages:resolution: {integrity: sha512-I3fNFt+DHmpWCYAT7quoM6lHf9wuqtI+oCOfvILnoicNIqjh5E3dEJWiXuYME2gNe8vl1iMQwyUHa7bgFmak6Q==}+ resolution: {integrity: sha512-MTtdFRz/eMDHXzeK6W3dO7mXUlF82Gom4y0oOgvHhh/HXZAGvIQDUvQ0SuUx+j2tv44b8xTHOm8K/9OoRFnXKw==}+resolution: {integrity: sha512-4xTO/M8c82qBcnQc1tgpNtubGUW/Y1tBQ1B0i5CtSoelOLKFYlElIr3bvgREYYO5iRqbMY1YuqZng0GVOI8Qww==}@@ -9273,6 +9372,24 @@ packages:resolution: {integrity: sha512-LRqI9+wdgC25P0URIJY9vwocIzCcksduHQ9OF2joxQoyTNVduwLAFUzjoopuRJbJAReaKrNQKAZKL3uCMugWJA==}+ resolution: {integrity: sha512-My8KJ57FYEy2W2LyNom4n3E7hKTuQk/0SES0u16tjA9Z3oFkF4RrC/hPAPgjlSpezsOvI8ObcXcElo92wn5IGA==}++ resolution: {integrity: sha512-56D19KOGbE00uKVj3sgIykpwKL179QsVFwx/DCW0u/0+URsryacI4MAdNJl0dh+u2PSsD9FtxPFbHCzJ78qJFQ==}++ resolution: {integrity: sha512-DAPhYzTYrRcXdMjUtUjKvW9z/FNAMTdU0ORyMcbmkwYNbKocDpdk+PX1L1dQgOID/+vVs1uBQ7ElrBQfZ0cuiQ==}++ resolution: {integrity: sha512-jjcpmNnQvrmN5Vx7y7lEc2iIOEytYv7rTvu+MeyAsSHTASGCCRA79Igg2uKssgOs1i1po8s3plW0sTu1wkkLGg==}++ resolution: {integrity: sha512-PFTA1gzfp1B1UaiJVyhJZA1rm0+Tzn690frc/L8vNX1Jop4STZgOE6bxUhnzdVSB+vm2GU1tIsuQcA9bxTQpMQ==}++ resolution: {integrity: sha512-qvZ608nBppZ4icQlhQQIAdc6S3Ffj9RGmzwUKUWuEICFnd1LVkN3EktF7ZHAgfcEdvZB5owU9tQgt99e2TlLjg==}+resolution: {integrity: sha512-xIPmR5ReJDu/DHH1OoIT1HkuybIfRGYRywC+gJtI7qHjCJp/M9jrmBEJW22O8lskDWm562BX2W8TiAwRTb0rKA==}@@ -9381,24 +9498,45 @@ packages:resolution: {integrity: sha512-C4AkuM3dA58cgZha7zVnuVxBhDsbttIMiytjgsM2XbHAB2faRVaHRle40558FBN+DJcrLNCoqG5mlrpdU4cRtg==}+ resolution: {integrity: sha512-z3wJSLrDf8kRDOh2qBtoTRD53vJ+CWIyo7uyZuxf/JAbNJjiHsOpG1y5wxk8drtv3ETAHutCu6N3thkOOgueWg==}+resolution: {integrity: sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==}+ resolution: {integrity: sha512-Yxn7z7SxgyGWRNa4wzf8AhYYWNrwl5q1Z8ii+CSTTIqVkmGZF1CElX2JI8g5yGoM3GAman9/PVCUFUSJ0kB/8Q==}+resolution: {integrity: sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw==}+ resolution: {integrity: sha512-sX0FawVE1o3abGk3vRjOH50L5TTLr3b5XMqnP9YDRb34M0v5OoZhG+OHFz1OffZ9dlwgpTBKaT4XW/AsUVnSDw==}+resolution: {integrity: sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw==}+ resolution: {integrity: sha512-3ZORTHtcSnMQEKtAOsBQ9/oHp9096pI/UvdPtN7ehKvrmZZ2+bbWhi0ln+I9drmwXMt5boocn6OlwQzNXeVeqw==}+resolution: {integrity: sha512-t2OU/dXXioARrC6yWfJ4hqB7rct14e8f7m0cbI5hUmDyyIlwv5vEtooptH8INkbLzOatzKuVbQmAYcbWoyz6Dg==}+ resolution: {integrity: sha512-5XWB9GbAUSHTn8VPU8/1DBXMuKYT5uOgEjJb8gN3mW0PNW5OPHpSdojoqf+iq1xo7vWzw/P8bAHY0n6ijpXF7g==}+resolution: {integrity: sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg==}+ resolution: {integrity: sha512-RMFXl2uQ0pNQy6Lun2YBYT9g9INXtWJULgbt01D/x8/6yJ2qpKyzdZD3pi6UIkzF++Da49xAelVKUeUMqd5eIQ==}+resolution: {integrity: sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw==}+ resolution: {integrity: sha512-vb9OoHqrhCmbRidQv/2+Bc6pkP0FrtlhurxZofvOEy5o8RtuuvTq+RQ1Vw5ZDNrVraQZu3HixESqbG+0iKk/MQ==}+resolution: {integrity: sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==}@@ -10001,6 +10139,9 @@ packages:resolution: {integrity: sha512-/2qh0lav6CmI15FzA3i/2Bzk2zCgQhGMkvhOhKNcBVQ1ldgpbfiNTVslmooUmWJcADi1f1kIeynbDRVzNlfR6Q==}+ resolution: {integrity: sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw==}+resolution: {integrity: sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==}@@ -10512,9 +10653,15 @@ packages:resolution: {integrity: sha512-RSYAtP31mvYLkAHrOlh25pCNQ5hWnT106VukGaaFfuJrZFkGRX5GhUAdPqpSDXxOhA2c4akmRuplv1mRqnBn6Q==}engines: {node: '>=8'}+ resolution: {integrity: sha512-PPp4lWJiBPlePI/dv1BeYktbwkfgXkrK59MUa+tYbMPgleod+4DvFK2PLU0O0O60/xuhHfiR9GUIUlXTU8sRIQ==}+resolution: {integrity: sha512-38fJrB0KnmD3E33a5jZC/5+gGAC2WKNiPw1/fdXJvijBlhA7RCsvJklrYJakS0HedninvaCYW8lQGf9C918GfA==}+ resolution: {integrity: sha512-lEFDoi2PICJyNrACFOfDD3JlLkuSbOa5Wd8EPt06HUdptv8Gn0bxYTdbU/XXQ3swAPkEaGxxPN9cbnMHvVu1Ig==}+resolution: {integrity: sha512-7teX9DW4tI2WZkXS4DBxneYSY7NHiXl4AKdWDO9LXVweULlCT8OPWsOjLEnMIXViN1j+QcY8mfbq3k0EK6x3uA==}engines: {node: '>=12.2.0'}@@ -11113,6 +11260,9 @@ packages:resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==}+ resolution: {integrity: sha512-5UR5Biq4VlVOtzqkm2AZlgvSlDJtME46uV0br0gENbwN4l5+mMKT4b9gJKqWtuL2zAIqajGJGuvbCbcAJUZqBg==}+resolution: {integrity: sha512-AqTiAOLcj85xS7vQ8QkAV41hPDIJ71XJB4RCUrzo/1GM2CQwhkJGaf9Hgr7BOugMRpgGUrqRg/DrBDl4H40+8g==}@@ -11251,6 +11401,9 @@ packages:resolution: {integrity: sha512-WrcA6AyEfqDX5bWige/4NQfPZMtASNVxdmWR76WESYQVAACSgWcR6e9i0mofqqBxYFtL4oAxPIptY73/0YE1DQ==}engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}+ resolution: {integrity: sha512-QO/PuPMm2ERxC6vFXEPtmAutOopy5PknD+Oq64gGwxKtk4xwo9Z97t9Av1obPmGU0IyTa6EKYUfTrK2QJS3Ozw==}+resolution: {integrity: sha512-qF72kLmPxAw0oN2fwpWIqbXAVyEqUzDHMsbtPvOudIlUzXYFIeQIuxXQCRCFh22B7cixvU0MG7m3MW8FTq/S+A==}@@ -11486,6 +11639,9 @@ packages:resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==}engines: {node: '>= 0.8'}+ resolution: {integrity: sha512-YF23YMyASIIJXpktBa4vIGLJ5Gs88UB/XePgqPmTa7cDA+JeO3yclbpheQYCHjVHBn/yePzrXuygIL+xbvRYHw==}+resolution: {integrity: sha512-0yaU+rj2gKAyEk12ffdSbBfjnnj+b1zqTBv3OQCTn8yEB02bsPizwdBPrLJjHnK+cU9EMMcUnNv938XcZIkmdA==}@@ -11610,6 +11766,9 @@ packages:resolution: {integrity: sha512-HYLeVCdJ0+lBYV2FvNZmv3HJ2Nt0QYXqZojk3d9FJOLkwnuhzM9tmamh8d7HPM8QqjKH8DeHkFTx+CFlWpZZDA==}+ resolution: {integrity: sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ==}+resolution: {integrity: sha512-e0MO3wdXWKrLbL0DgGnUV7WHVuw9OUvL4hjgnPkIeEvESk74gAITi5G606JtZPp39cd8HA9VQzCIvA49LpPN5Q==}engines: {node: '>= 8'}@@ -15999,6 +16158,8 @@ snapshots:'@types/qs': 6.15.1'@types/serve-static': 1.15.10+ '@types/[email protected]': {}+'@types/[email protected]':dependencies:'@types/node': 22.13.10@@ -16037,6 +16198,8 @@ snapshots:dependencies:'@types/node': 22.13.10+ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]': {}@@ -18034,6 +18197,59 @@ snapshots:function-bind: 1.1.2optional: true+ dependencies:+ hast-util-is-element: 2.1.3++ dependencies:+ '@types/hast': 2.3.4+ '@types/unist': 2.0.6+ hastscript: 7.2.0+ property-information: 6.2.0+ vfile: 5.3.6+ vfile-location: 4.1.0+ web-namespaces: 2.0.1++ [email protected]: {}++ dependencies:+ '@types/hast': 2.3.4+ hast-util-has-property: 2.0.1+ hast-util-is-element: 2.1.3++ dependencies:+ '@types/hast': 2.3.4+ '@types/unist': 2.0.6++ dependencies:+ '@types/hast': 2.3.4++ dependencies:+ '@types/hast': 2.3.4+ hast-util-embedded: 2.0.1+ hast-util-has-property: 2.0.1+ hast-util-is-body-ok-link: 2.0.0+ hast-util-is-element: 2.1.3++ dependencies:+ '@types/hast': 2.3.4+ '@types/parse5': 6.0.3+ hast-util-from-parse5: 7.1.2+ hast-util-to-parse5: 7.1.0+ html-void-elements: 2.0.1+ parse5: 6.0.1+ unist-util-position: 4.0.4+ unist-util-visit: 4.1.2+ vfile: 5.3.6+ web-namespaces: 2.0.1+ zwitch: 2.0.4+dependencies:'@types/estree': 1.0.7@@ -18054,6 +18270,20 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ '@types/hast': 2.3.4+ '@types/unist': 2.0.6+ ccount: 2.0.1+ comma-separated-tokens: 2.0.3+ hast-util-raw: 7.2.3+ hast-util-whitespace: 2.0.1+ html-void-elements: 2.0.1+ property-information: 6.2.0+ space-separated-tokens: 2.0.2+ stringify-entities: 4.0.3+ zwitch: 2.0.4+dependencies:'@types/hast': 3.0.5@@ -18088,12 +18318,54 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ '@types/extend': 3.0.4+ '@types/hast': 2.3.4+ '@types/mdast': 3.0.15+ '@types/unist': 2.0.6+ extend: 3.0.2+ hast-util-phrasing: 2.0.2+ hast-util-to-html: 8.0.4+ hast-util-to-text: 3.1.2+ hast-util-whitespace: 2.0.1+ mdast-util-phrasing: 3.0.1+ mdast-util-to-string: 3.2.0+ rehype-minify-whitespace: 5.0.1+ trim-trailing-lines: 2.1.0+ unist-util-position: 4.0.4+ unist-util-visit: 4.1.2++ dependencies:+ '@types/hast': 2.3.4+ comma-separated-tokens: 2.0.3+ property-information: 6.2.0+ space-separated-tokens: 2.0.2+ web-namespaces: 2.0.1+ zwitch: 2.0.4++ dependencies:+ '@types/hast': 2.3.4+ '@types/unist': 2.0.6+ hast-util-is-element: 2.1.3+ unist-util-find-after: 4.0.1+dependencies:'@types/hast': 3.0.5+ dependencies:+ '@types/hast': 2.3.4+ comma-separated-tokens: 2.0.3+ hast-util-parse-selector: 3.1.1+ property-information: 6.2.0+ space-separated-tokens: 2.0.2+dependencies:'@preact/signals-core': 1.14.0@@ -18118,6 +18390,8 @@ snapshots:+ [email protected]: {}+@@ -18728,6 +19002,8 @@ snapshots:+ [email protected]: {}+@@ -18757,6 +19033,13 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ '@types/mdast': 3.0.15+ escape-string-regexp: 5.0.0+ unist-util-is: 5.2.0+ unist-util-visit-parents: 5.1.3+dependencies:'@types/mdast': 3.0.15@@ -18808,6 +19091,50 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ '@types/mdast': 3.0.15+ ccount: 2.0.1+ mdast-util-find-and-replace: 2.2.2+ micromark-util-character: 1.2.0++ dependencies:+ '@types/mdast': 3.0.15+ mdast-util-to-markdown: 1.5.0+ micromark-util-normalize-identifier: 1.1.0++ dependencies:+ '@types/mdast': 3.0.15+ mdast-util-to-markdown: 1.5.0++ dependencies:+ '@types/mdast': 3.0.15+ markdown-table: 3.0.4+ mdast-util-from-markdown: 1.3.1+ mdast-util-to-markdown: 1.5.0+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@types/mdast': 3.0.15+ mdast-util-to-markdown: 1.5.0++ dependencies:+ mdast-util-from-markdown: 1.3.1+ mdast-util-gfm-autolink-literal: 1.0.3+ mdast-util-gfm-footnote: 1.0.2+ mdast-util-gfm-strikethrough: 1.0.3+ mdast-util-gfm-table: 1.0.7+ mdast-util-gfm-task-list-item: 1.0.2+ mdast-util-to-markdown: 1.5.0+ transitivePeerDependencies:+ - supports-color+dependencies:'@types/estree-jsx': 1.0.0@@ -19054,6 +19381,13 @@ snapshots:micromark-util-symbol: 2.0.1micromark-util-types: 2.0.2+ dependencies:+ micromark-util-character: 1.2.0+ micromark-util-sanitize-uri: 1.2.0+ micromark-util-symbol: 1.1.0+ micromark-util-types: 1.1.0+dependencies:micromark-util-character: 2.1.1@@ -19061,6 +19395,17 @@ snapshots:micromark-util-symbol: 2.0.1micromark-util-types: 2.0.2+ dependencies:+ micromark-core-commonmark: 1.1.0+ micromark-factory-space: 1.1.0+ micromark-util-character: 1.2.0+ micromark-util-normalize-identifier: 1.1.0+ micromark-util-sanitize-uri: 1.2.0+ micromark-util-symbol: 1.1.0+ micromark-util-types: 1.1.0+ uvu: 0.5.6+dependencies:devlop: 1.1.0@@ -19072,6 +19417,15 @@ snapshots:micromark-util-symbol: 2.0.1micromark-util-types: 2.0.2+ dependencies:+ micromark-util-chunked: 1.1.0+ micromark-util-classify-character: 1.1.0+ micromark-util-resolve-all: 1.1.0+ micromark-util-symbol: 1.1.0+ micromark-util-types: 1.1.0+ uvu: 0.5.6+dependencies:devlop: 1.1.0@@ -19081,6 +19435,14 @@ snapshots:micromark-util-symbol: 2.0.1micromark-util-types: 2.0.2+ dependencies:+ micromark-factory-space: 1.1.0+ micromark-util-character: 1.2.0+ micromark-util-symbol: 1.1.0+ micromark-util-types: 1.1.0+ uvu: 0.5.6+dependencies:devlop: 1.1.0@@ -19089,10 +19451,22 @@ snapshots:micromark-util-symbol: 2.0.1micromark-util-types: 2.0.2+ dependencies:+ micromark-util-types: 1.1.0+dependencies:micromark-util-types: 2.0.2+ dependencies:+ micromark-factory-space: 1.1.0+ micromark-util-character: 1.2.0+ micromark-util-symbol: 1.1.0+ micromark-util-types: 1.1.0+ uvu: 0.5.6+dependencies:devlop: 1.1.0@@ -19101,6 +19475,17 @@ snapshots:micromark-util-symbol: 2.0.1micromark-util-types: 2.0.2+ dependencies:+ micromark-extension-gfm-autolink-literal: 1.0.5+ micromark-extension-gfm-footnote: 1.1.2+ micromark-extension-gfm-strikethrough: 1.0.7+ micromark-extension-gfm-table: 1.0.7+ micromark-extension-gfm-tagfilter: 1.0.2+ micromark-extension-gfm-task-list-item: 1.0.5+ micromark-util-combine-extensions: 1.1.0+ micromark-util-types: 1.1.0+dependencies:micromark-extension-gfm-autolink-literal: 2.1.0@@ -19905,6 +20290,8 @@ snapshots:+ [email protected]: {}+dependencies:entities: 6.0.0@@ -20394,6 +20781,15 @@ snapshots:+ dependencies:+ '@types/hast': 2.3.4+ hast-util-embedded: 2.0.1+ hast-util-is-element: 2.1.3+ hast-util-whitespace: 2.0.1+ unified: 10.1.2+ unist-util-is: 5.2.0+dependencies:'@types/mdast': 3.0.15@@ -20401,6 +20797,15 @@ snapshots:micromark-extension-frontmatter: 1.1.1unified: 10.1.2+ dependencies:+ '@types/mdast': 3.0.15+ mdast-util-gfm: 2.0.2+ micromark-extension-gfm: 2.0.3+ unified: 10.1.2+ transitivePeerDependencies:+ - supports-color+dependencies:estree-util-is-identifier-name: 1.1.0@@ -21117,6 +21522,8 @@ snapshots:+ [email protected]: {}+@@ -21288,6 +21695,11 @@ snapshots:dependencies:imurmurhash: 0.1.4+ dependencies:+ '@types/unist': 2.0.6+ unist-util-is: 5.2.0+@@ -21474,6 +21886,11 @@ snapshots:+ dependencies:+ '@types/unist': 2.0.6+ vfile: 5.3.6+dependencies:'@types/unist': 2.0.6@@ -21657,6 +22074,8 @@ snapshots:optionalDependencies:'@zxing/text-encoding': 0.9.0+ [email protected]: {}+diff --git a/scripts/docs/content-engine-reference-page.md b/scripts/docs/content-engine-reference-page.mdindex 88fa36ce8b..6913bbf3c4 100644--- a/scripts/docs/content-engine-reference-page.md+++ b/scripts/docs/content-engine-reference-page.md@@ -1,5 +1,5 @@----description: Query Markdown and JSON Assets with the Content Engine.+description: Query Markdown, MDX, and JSON Assets with the Content Engine.---<!-- Generated from the Content Engine schemas and shared CLI documentation. Do not edit directly. -->