@vcp-dev/site-edit-bridge 0.11.24 → 0.11.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.d.ts CHANGED
@@ -271,7 +271,7 @@ export declare class SiteEditWebSocketClient implements SiteEditBridgeClient {
271
271
  bindings: {
272
272
  sourceKind: "vcp-cms-collection" | "vcp-cms-form" | "vcp-cms-settings" | "vcp-cms-navigation" | "site-api-route" | "external-api" | "unknown-api";
273
273
  sourceType: "api-field" | "cms-field";
274
- targetKind: "repeat-region" | "conditional-region" | "text" | "richtext" | "attribute" | "component-prop";
274
+ targetKind: "text" | "repeat-region" | "conditional-region" | "richtext" | "attribute" | "component-prop";
275
275
  targetName: string;
276
276
  confidence: "unknown" | "exact" | "partial" | "safe-derived";
277
277
  readonly: true;
@@ -305,7 +305,7 @@ export declare class SiteEditWebSocketClient implements SiteEditBridgeClient {
305
305
  };
306
306
  editMode: "unsupported" | "direct" | "readonly" | "proxy" | "upstream";
307
307
  sourceScope: "node" | "repeat-template" | "repeat-item";
308
- allowedWriteScopes: ("selection" | "template")[];
308
+ allowedWriteScopes: ("template" | "selection")[];
309
309
  diagnostics: {
310
310
  code: string;
311
311
  message: string;
@@ -491,8 +491,8 @@ export declare class SiteEditWebSocketClient implements SiteEditBridgeClient {
491
491
  media: {
492
492
  file_path: string;
493
493
  occurrence: number;
494
- kind: "object" | "srcset" | "poster" | "src" | "manifest" | "thumbnail" | "import" | "array-item";
495
- source: "import" | "array-item" | "jsx-attribute" | "object-property" | "media-manifest";
494
+ kind: "object" | "srcset" | "poster" | "src" | "manifest" | "thumbnail" | "import" | "array-item" | "host-fallback";
495
+ source: "import" | "array-item" | "host-fallback" | "jsx-attribute" | "object-property" | "media-manifest";
496
496
  value: string | null;
497
497
  expression: string;
498
498
  asset_key: string | null;
@@ -506,6 +506,16 @@ export declare class SiteEditWebSocketClient implements SiteEditBridgeClient {
506
506
  };
507
507
  content_digest: string;
508
508
  complete: true;
509
+ host_fallback?: {
510
+ file_path: string;
511
+ digest_sha256: "196f0a9da4796aa5effa1da57fa2d68aa4477e047868e7d31aca9051e4a69eea";
512
+ } | undefined;
513
+ cms_field?: {
514
+ sources: {
515
+ slug: string;
516
+ field_path: string;
517
+ }[];
518
+ } | undefined;
509
519
  }[];
510
520
  invocation_bindings: {
511
521
  propName: string;
@@ -536,17 +546,79 @@ export declare class SiteEditWebSocketClient implements SiteEditBridgeClient {
536
546
  } | null;
537
547
  } | {
538
548
  kind: "route-search-params";
549
+ } | {
550
+ kind: "route-params";
539
551
  } | {
540
552
  kind: "target-block-id";
541
553
  };
542
554
  }[];
543
555
  host_contract_digest: string;
556
+ collection_analysis?: {
557
+ kind: "related-source-only";
558
+ collections: {
559
+ requirement_key: string;
560
+ collection_recipe: {
561
+ source_slug: string;
562
+ list_mode: "page" | "embedded";
563
+ paginate: boolean;
564
+ detail_prefix: string;
565
+ schema: {
566
+ name: string;
567
+ cms_type: string;
568
+ label?: string | undefined;
569
+ required?: boolean | undefined;
570
+ value_shape?: string | undefined;
571
+ front_display?: "visible" | "internal" | "forbidden" | undefined;
572
+ choices?: {
573
+ value: string | number;
574
+ label: string;
575
+ }[] | undefined;
576
+ }[];
577
+ list_view: {
578
+ source_path: string;
579
+ target_path: string;
580
+ export_name: string;
581
+ interface_name: string;
582
+ import_specifier?: string | undefined;
583
+ };
584
+ detail_view: {
585
+ source_path: string;
586
+ target_path: string;
587
+ export_name: string;
588
+ interface_name: string;
589
+ import_specifier?: string | undefined;
590
+ };
591
+ top_n?: number | undefined;
592
+ page_size?: number | undefined;
593
+ title?: string | undefined;
594
+ breadcrumb?: {
595
+ homeLabel: string;
596
+ collectionLabel: string;
597
+ } | undefined;
598
+ required_fields?: string[] | undefined;
599
+ force_multi_media?: string[] | undefined;
600
+ list_route_required?: boolean | undefined;
601
+ };
602
+ related_entries: {
603
+ key: string;
604
+ pathTemplate: string;
605
+ export: {
606
+ kind: "default";
607
+ } | {
608
+ kind: "named";
609
+ name: string;
610
+ };
611
+ purpose: "collection-detail-view" | "i18n-companion" | "client-importer";
612
+ requirementKey: string;
613
+ }[];
614
+ }[];
615
+ } | undefined;
544
616
  route_dependencies?: {
545
617
  kind: "host-route";
546
618
  href: string;
547
619
  }[] | undefined;
548
620
  cms_sample_proof?: {
549
- kind: "first-page-no-host-routes";
621
+ kind: "first-page-no-host-routes" | "application-first-page-example";
550
622
  } | undefined;
551
623
  } | {
552
624
  complete: false;
@@ -559,6 +631,10 @@ export declare class SiteEditWebSocketClient implements SiteEditBridgeClient {
559
631
  column: number;
560
632
  } | undefined;
561
633
  }[];
634
+ cms_candidates?: {
635
+ kind: "partial-unproven";
636
+ slugs: string[];
637
+ } | undefined;
562
638
  }>;
563
639
  exportPortableBlockAsset(request: SiteEditPortableAssetRequest): Promise<{
564
640
  complete: true;
@@ -566,7 +642,7 @@ export declare class SiteEditWebSocketClient implements SiteEditBridgeClient {
566
642
  file_path: string;
567
643
  occurrence: number;
568
644
  path: string;
569
- mime_type: "image/png" | "image/jpeg" | "image/webp" | "image/gif";
645
+ mime_type: "image/png" | "image/jpeg" | "image/webp" | "image/gif" | "image/svg+xml";
570
646
  byte_size: number;
571
647
  digest_sha256: string;
572
648
  offset: number;
package/dist/client.js CHANGED
@@ -1 +1 @@
1
- function K(t){if(!G(t)){if(t.encoding==="segment-trie-v1")throw new Error("Invalid compact render document");return t}let e=new Map,n=t.pageComposition.status==="supported"?t.pageComposition.placementUnitKeys:[],s=new Map(t.dynamicDataSummaries??[]),o=new Map(t.pageCompositionActionScopes??[]),r=c=>{let i=e.get(c);if(i)return i;let a=t.nodes[c];if(!a)throw new Error(`Missing compact document node ${c}`);let[u,d]=a,m=t.tokens[d];if(typeof m!="string")throw new Error(`Missing compact document token ${d}`);let x=`${u===null?"":r(u)}${m}`;return e.set(c,x),x};return{siteId:t.siteId,snapshotId:t.snapshotId,composition:{...t.composition},routeId:t.composition.routeId,version:t.version,pageComposition:t.pageComposition,...t.pageBlocks!==void 0?{pageBlocks:t.pageBlocks}:{},entries:t.entries.map((c,i)=>{let[a,u,d]=c,m=d===void 0?void 0:n[d];if(d!==void 0&&!m)throw new Error(`Missing page composition unit ${d}`);let x=t.entryParentNodeIds?.[i],T=o.get(i),D=T?.kind==="source-siblings"?{kind:"source-siblings",siblingKeys:T.siblingEntryIndexes.map(B=>{let M=t.entries[B];if(!M)throw new Error(`Missing source sibling entry ${B}`);return r(M[0])})}:T;return{key:r(a),...t.entryParentNodeIds?{parentKey:x===null?null:r(x)}:{},...m?{pageCompositionUnitKey:m}:{},...D?{pageCompositionActionScope:D}:{},operationSummary:H(u),...s.get(i)?{dynamicDataSummary:s.get(i)}:{}}})}}function H(t){return{canUpdateText:(t&1)!==0,canInsertChild:(t&2)!==0,canMove:(t&4)!==0,canRemove:(t&8)!==0}}function G(t){if(typeof t!="object"||t===null)return!1;let e=t;if(e.encoding!=="segment-trie-v1"||typeof e.siteId!="string"||typeof e.snapshotId!="string"||!J(e.composition)||typeof e.routeId!="string"||e.routeId!==e.composition.routeId||!Number.isInteger(e.version)||e.version<0||!h(e.pageComposition)||e.pageBlocks!==void 0&&!Q(e.pageBlocks)||!Array.isArray(e.tokens)||!e.tokens.every(i=>typeof i=="string")||!Array.isArray(e.nodes)||!Array.isArray(e.entries))return!1;let n=e.nodes;if(!n.every((i,a)=>Array.isArray(i)&&i.length===2&&(i[0]===null||p(i[0])&&i[0]<a)&&p(i[1])&&i[1]<e.tokens.length)||!e.entries.every(i=>Array.isArray(i)&&(i.length===2||i.length===3)&&p(i[0])&&i[0]<n.length&&p(i[1])&&i[1]<=15&&(i.length===2||p(i[2]))))return!1;let s=e.entryParentNodeIds;if(s!==void 0&&(!Array.isArray(s)||s.length!==e.entries.length||!s.every(i=>i===null||p(i)&&i<n.length)))return!1;let o=e.dynamicDataSummaries,r=e.pageCompositionActionScopes;return(r===void 0||Array.isArray(r)&&r.every(i=>{if(!Array.isArray(i)||i.length!==2||!p(i[0])||i[0]>=e.entries.length||!h(i[1])||!["route-unit","source-siblings","unavailable"].includes(String(i[1].kind)))return!1;let a=i[1];return a.kind!=="source-siblings"||Array.isArray(a.siblingEntryIndexes)&&a.siblingEntryIndexes.length>=2&&a.siblingEntryIndexes.every(u=>p(u)&&u<e.entries.length)&&a.siblingEntryIndexes.includes(i[0])}))&&(o===void 0||Array.isArray(o)&&o.every(i=>Array.isArray(i)&&i.length===2&&p(i[0])&&i[0]<e.entries.length&&h(i[1])))}function h(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function J(t){return!h(t)||typeof t.routeId!="string"?!1:t.effectiveTemplateId===void 0||typeof t.effectiveTemplateId=="string"}function p(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0}function Q(t){if(!Array.isArray(t))return!1;let e=new Map;for(let n of t){if(!h(n)||!I(n,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!_(n.blockKey,256)||!_(n.definitionKey,512)||!Y(n.rootRef)||!Z(n.source)||!X(n.owner)||!Array.isArray(n.siblingBlockKeys)||!n.siblingBlockKeys.every(s=>_(s,256))||new Set(n.siblingBlockKeys).size!==n.siblingBlockKeys.length||n.siblingBlockKeys.includes(n.blockKey)||n.placementUnitKey!==void 0&&!b(n.placementUnitKey)||!ee(n.capabilities)||n.unavailableReasons!==void 0&&!te(n.unavailableReasons)||e.has(n.blockKey))return!1;e.set(n.blockKey,n)}for(let n of t){let s=n.owner;for(let o of n.siblingBlockKeys){let r=e.get(o);if(!r)return!1;let c=r.owner;if(s.kind!==c.kind||s.key!==c.key)return!1}}return!0}function Y(t){return!h(t)||!I(t,["key","instanceIndex","instanceCount"])||!b(t.key)||t.instanceIndex!==void 0&&!p(t.instanceIndex)||t.instanceCount!==void 0&&(!p(t.instanceCount)||t.instanceCount<1)?!1:!(t.instanceIndex!==void 0&&t.instanceCount!==void 0&&t.instanceIndex>=t.instanceCount)}function Z(t){return h(t)&&I(t,["file","structuralPath","contentHash"])&&typeof t.file=="string"&&ne(t.file)&&b(t.structuralPath)&&typeof t.contentHash=="string"&&/^sha256:[a-f0-9]{64}$/u.test(t.contentHash)}function X(t){return h(t)&&I(t,["kind","key"])&&(t.kind==="route-member"||t.kind==="component-definition")&&_(t.key,512)}function ee(t){return h(t)&&I(t,["insert","replace","move","remove","save"])&&typeof t.insert=="boolean"&&typeof t.replace=="boolean"&&typeof t.move=="boolean"&&typeof t.remove=="boolean"&&typeof t.save=="boolean"}function te(t){return h(t)&&Object.entries(t).every(([e,n])=>b(e)&&h(n)&&I(n,["code","reason"])&&b(n.code)&&b(n.reason))}function ne(t){let e=se(t),n=e?t.replace("/.vcp/","/_vcp/"):t;if(!t||t.startsWith("/")||t.includes("\\")||n.split("/").some(r=>!r||r==="."||r===".."||r.startsWith(".")||r==="node_modules"||r.toLowerCase()==="package.json"||r==="recipes"||r.startsWith(".env")))return!1;let s=t.toLowerCase();return/^(?:src\/)?app\/api(?:\/|$)/u.test(s)||/^(?:src\/)?app\/(?:.*\/)?route\.[cm]?[jt]sx?$/u.test(s)||/(^|\/)[^/]+\.server\.[cm]?[jt]sx?$/u.test(s)||/^(?:src\/)?app\/(?:.*\/)?(?:action|actions)\.[cm]?[jt]sx?$/u.test(s)||/^(?:lib|src\/lib)\/(?:server|db|cms)(?:\/|$)/u.test(s)||s.split("/").some(r=>["server","db","database","auth","secret","secrets","token","tokens","credential","credentials"].includes(r.replace(/\.[^.]+$/u,"")))?!1:["design.md","app/globals.css","src/app/globals.css"].includes(t.toLowerCase())||/^(?:src\/)?app\/(?:.*\/)?page\.[cm]?[jt]sx?$/iu.test(t)||["components/system/not-found-content.tsx","src/components/system/not-found-content.tsx"].includes(t)||["components/site","src/components/site","lib/generated","src/lib/generated","public"].some(r=>t===r||t.startsWith(`${r}/`))||e}function se(t){let e=/^(?:src\/)?app\/\.vcp\/page-templates\/(.+)\/page\.tsx$/u.exec(t);if(!e)return!1;let n=e[1].split("/"),s=n.some(c=>v(c)),o=s?n[0]:n.pop(),r=s?n.slice(1):n;if(s&&r.length===0||!/^[A-Za-z0-9_-]{1,255}$/u.test(o)||!oe(`/${r.join("/")}`)||r.some(c=>c.includes("[")||c.includes("]")?!v(c):/[\[\]()%]/u.test(c)||c.startsWith("_")||c.startsWith("@")))return!1;try{let c=o.replace(/-/gu,"+").replace(/_/gu,"/"),i=atob(c),a=Uint8Array.from(i,d=>d.charCodeAt(0)),u=new TextDecoder("utf-8",{fatal:!0}).decode(a);return u.length>0&&u.length<=191&&!/[^\x20-\x7e\xa0-\xff]/u.test(u)&&!u.startsWith(" ")&&!u.endsWith(" ")&&new TextEncoder().encode(u).byteLength<=191&&btoa(String.fromCharCode(...new TextEncoder().encode(u))).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")===o}catch{return!1}}function v(t){return/^\[\[\.\.\.[^\[\]]+\]\]$/u.test(t)||/^\[[^\[\]]+\]$/u.test(t)}function oe(t){return!t.startsWith("/")||t.startsWith("//")||/[?#\\\x00-\x20\x7f]/u.test(t)||t.startsWith("/.vcp")?!1:!t.split("/").some(e=>{try{let n=decodeURIComponent(e);return n==="."||n===".."||/[/\\\x00-\x1f\x7f]/u.test(n)||n.startsWith(".vcp")}catch{return!0}})}function _(t,e){return typeof t=="string"&&t.length>0&&t.length<=e}function b(t){return typeof t=="string"&&t.length>0}function I(t,e){let n=new Set(e);return Object.keys(t).every(s=>n.has(s))}var g=class t{constructor(){}static parseMessage(e,n={}){let s=JSON.parse(e);if(!t.isMessage(s,n))throw new Error("Invalid site edit bridge message");return s}static stringifyMessage(e){return JSON.stringify(e)}static extractRequestInfo(e){if(l(e)&&l(e.payload)){let n=typeof e.payload.id=="string"?e.payload.id:"unknown",s=this.isRequestKind(e.payload.kind)?e.payload.kind:"get-document";return{id:n,kind:s}}return{id:"unknown",kind:"get-document"}}static isRequestKind(e){return e==="initialize-session"||e==="get-document"||e==="get-history-status"||e==="get-style-context"||e==="get-object-edit-context"||e==="get-class-name-source"||e==="get-source-tree"||e==="get-source-file"||e==="export-portable-block"||e==="export-portable-block-asset"||e==="resolve-source-location"||e==="execute"||e==="get-operation-result"||e==="get-history-operation-result"||e==="undo"||e==="redo"}static isMessage(e,n={}){return!l(e)||typeof e.type!="string"?!1:e.type==="request"?ie(e.payload,n):e.type==="response"||e.type==="error"?l(e.payload)&&typeof e.payload.id=="string":e.type==="event"?l(e.payload)&&l(e.payload.event):e.type==="auth"?l(e.payload)&&typeof e.payload.key=="string":e.type==="ping"||e.type==="pong"?l(e.payload)&&typeof e.payload.id=="string":e.type==="auth-ok"&&l(e.payload)&&e.payload.ok===!0}};function ie(t,e){if(!l(t)||typeof t.id!="string"||!g.isRequestKind(t.kind))return!1;let n=C(t.composition);switch(t.kind){case"initialize-session":return n&&(t.mutationContext===void 0||q(t.mutationContext));case"get-document":case"get-style-context":return n;case"get-object-edit-context":return typeof t.key=="string"&&n&&j(t.selectionRef);case"get-class-name-source":case"resolve-source-location":return typeof t.key=="string"&&n;case"get-history-status":return n;case"get-source-tree":return n;case"get-source-file":return typeof t.path=="string"&&n;case"export-portable-block":return P(t);case"export-portable-block-asset":return re(t);case"execute":case"get-operation-result":return n&&ce(t.request)&&(t.request.mutationContext===void 0||q(t.request.mutationContext))&&(e.validateOperationRequest?.(t.request)??!0);case"get-history-operation-result":return n&&N(t.request);case"undo":case"redo":return n&&(t.request===void 0||N(t.request)&&t.request.kind===t.kind)&&(t.mutationContext===void 0||q(t.mutationContext))}}function P(t){if(!C(t.composition)||!Object.keys(t).every(n=>["id","kind","composition","request"].includes(n))||!l(t.request))return!1;let e=t.request;return!(!Object.keys(e).every(n=>["site_id","base_snapshot_id","document_version","target","selection_ref"].includes(n))||typeof e.site_id!="string"||typeof e.base_snapshot_id!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(e.site_id)||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(e.base_snapshot_id)||typeof e.document_version!="number"||!Number.isSafeInteger(e.document_version)||e.document_version<0||!l(e.target)||e.target.kind!=="page-block"||typeof e.target.blockKey!="string"||!e.target.blockKey.length||e.target.blockKey.length>256||!Object.keys(e.target).every(n=>["kind","composition","blockKey"].includes(n))||!C(e.target.composition)||e.target.composition.routeId!==t.composition.routeId||e.target.composition.templateId!==t.composition.templateId||e.selection_ref===void 0||!j(e.selection_ref))}function re(t){if(!Object.keys(t).every(n=>["id","kind","composition","request"].includes(n))||!l(t.request))return!1;let e=t.request;return!(!Object.keys(e).every(n=>["request","snapshot_digest","file_path","occurrence","offset"].includes(n))||!P({id:t.id,kind:"export-portable-block",composition:t.composition,request:e.request})||typeof e.snapshot_digest!="string"||!/^sha256:[a-f0-9]{64}$/u.test(e.snapshot_digest)||typeof e.file_path!="string"||!e.file_path.length||e.file_path.length>1024||e.file_path.startsWith("/")||/[\\\0%]/u.test(e.file_path)||e.file_path.split("/").some(n=>!n||n.startsWith(".")||n==="node_modules")||typeof e.occurrence!="number"||!Number.isSafeInteger(e.occurrence)||e.occurrence<0||e.occurrence>4095||typeof e.offset!="number"||!Number.isSafeInteger(e.offset)||e.offset<0||e.offset>50*1024*1024||e.offset%(1024*1024)!==0)}function N(t){return l(t)&&typeof t.request_id=="string"&&t.request_id.length>0&&t.request_id.length<=128&&typeof t.site_id=="string"&&t.site_id.length>0&&typeof t.base_snapshot_id=="string"&&t.base_snapshot_id.length>0&&(t.kind==="undo"||t.kind==="redo")&&C(t.composition)&&Object.keys(t).every(e=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(e))}function j(t){if(t===void 0)return!0;if(!l(t)||typeof t.key!="string"||t.key.length===0)return!1;let e=t.instanceIndex,n=t.instanceCount;return e!==void 0&&(typeof e!="number"||!Number.isInteger(e)||e<0)||n!==void 0&&(typeof n!="number"||!Number.isInteger(n)||n<=0)||typeof e=="number"&&typeof n=="number"&&e>=n?!1:Object.keys(t).every(s=>s==="key"||s==="instanceIndex"||s==="instanceCount")}function ce(t){return l(t)&&typeof t.id=="string"&&typeof t.siteId=="string"&&typeof t.baseSnapshotId=="string"&&C(t.composition)&&typeof t.kind=="string"&&l(t.target)&&(t.target.kind!=="route"||C(t.target.composition))&&typeof t.documentVersion=="number"&&Number.isInteger(t.documentVersion)&&t.documentVersion>=0&&l(t.params)}function C(t){return l(t)&&typeof t.routeId=="string"&&t.routeId.length>0&&(t.templateId===void 0||typeof t.templateId=="string"&&t.templateId.length>0)&&Object.keys(t).every(e=>e==="routeId"||e==="templateId")}function l(t){return typeof t=="object"&&t!==null}function q(t){return l(t)&&typeof t.editingSessionId=="string"&&t.editingSessionId.length>0&&typeof t.lockId=="string"&&t.lockId.length>0&&typeof t.ownerId=="string"&&t.ownerId.length>0&&typeof t.leaseAssertion=="string"&&t.leaseAssertion.length>0}var ae="vcp:designer:trace",ue="designer_trace",L="__VCP_DESIGNER_TRACE__";var de=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function le(t=globalThis){let e=t;try{if(e.localStorage?.getItem(ae)==="1")return!0}catch{}try{let n=e.location?.search??"";return new URLSearchParams(n).get(ue)==="1"}catch{return!1}}function f(t,e={},n=globalThis){if(!le(n))return;let s={type:t,timestamp:Date.now(),payload:pe(e)},o=n,r=o[L]??[];r.push(s),r.length>1e3&&r.splice(0,r.length-1e3),o[L]=r;let c=n.console?.debug;s.payload.diagnosticOnly!==!0&&typeof c=="function"&&c.call(n.console,"[designer-trace]",s)}function pe(t){return A(t,0)}function A(t,e){if(e>4)return"[truncated]";if(Array.isArray(t))return t.map(s=>A(s,e+1));if(!t||typeof t!="object")return t;let n={};for(let[s,o]of Object.entries(t)){if(de.test(s)){n[s]="[redacted]";continue}n[s]=A(o,e+1)}return n}var U=class{constructor(e){this.options=e,this.socket=null,this.connectPromise=null,this.connectAttempt=null,this.connectionState="idle",this.intentionalClose=!1,this.sequence=0,this.pending=new Map,this.listeners=new Set,this.heartbeatState=null,this.connectionStatusListeners=new Set}connect(){return this.socket?.readyState===R&&this.connectionState==="open"?(this.setConnectionState("open"),Promise.resolve()):this.connectPromise?this.connectPromise:(this.intentionalClose=!1,this.setConnectionState("connecting"),this.connectPromise=new Promise((e,n)=>{let s;try{s=this.createSocket(this.options.url)}catch(a){let u=S(a,"WebSocket failed");this.socket=null,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("failed",u.message),n(u);return}let o={socket:s,settled:!1,reject:n};this.connectAttempt=o,this.socket=s;let r=Math.max(0,this.options.connectTimeoutMs??fe);r>0&&(o.deadline=setTimeout(()=>{this.connectAttempt!==o||o.settled||(f("bridge.connect-timeout",{connectTimeoutMs:r}),this.cleanupSocket(s,$(ge,`Bridge connection did not complete within ${r}ms`),"failed"))},r));let c=()=>{this.socket!==s||this.connectAttempt!==o||(o.settled=!0,clearTimeout(o.deadline),this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("open"),this.startHeartbeat(s),e())},i=(a,u)=>{this.cleanupSocket(s,a,u)};s.onopen=()=>{if(!(this.socket!==s||this.connectAttempt!==o)){if(this.options.authKey){try{s.send(g.stringifyMessage({type:"auth",payload:{key:this.options.authKey}}))}catch(a){i(S(a,"WebSocket auth failed"),"failed")}return}c()}},s.onerror=a=>{if(this.socket!==s)return;let u=S(a,"WebSocket failed");i(u,"failed")},s.onmessage=a=>{if(this.socket===s){if(this.noteInboundMessage(s),this.options.authKey&&this.connectAttempt===o&&!o.settled){this.handleAuthHandshakeMessage(a.data,s,o,()=>{c()});return}this.handleMessage(a.data)}},s.onclose=a=>{if(this.socket!==s)return;let u=this.intentionalClose,d=new Error(Se(a,{intentional:u}));i(d,u?"closed":"failed")}}),this.connectPromise)}disconnect(){this.intentionalClose=!0,this.setConnectionState("closing");let e=this.socket;if(!e){this.rejectAll(new Error("WebSocket disconnected")),this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("closed");return}this.cleanupSocket(e,new Error("WebSocket disconnected"),"closed")}getConnectionState(){return this.connectionState}subscribeConnectionStatus(e){return this.connectionStatusListeners.add(e),e({state:this.connectionState}),()=>{this.connectionStatusListeners.delete(e)}}getDocument(e){let n=this.selector(e);return this.request("get-document",{composition:n})}async initializeSession(e){let n=this.selector(e.composition);return await this.request("initialize-session",{composition:n,...e.mutationContext?{mutationContext:e.mutationContext}:{}})}getHistoryStatus(e){return this.request("get-history-status",{composition:this.selector(e)})}getStyleContext(e){let n=this.selector(e);return this.request("get-style-context",{composition:n})}getObjectEditContext(e,n,s){let o=this.selector(n);return this.request("get-object-edit-context",{key:e,composition:o,...s?{selectionRef:s}:{}})}getClassNameSource(e,n){let s=this.selector(n);return this.request("get-class-name-source",{key:e,composition:s})}getSourceTree(e){return this.request("get-source-tree",{composition:this.selector(e)})}getSourceFile(e){return this.request("get-source-file",{path:e.path,composition:this.selector(e.composition)})}exportPortableBlock(e){return this.request("export-portable-block",{composition:this.selector(e.target.composition),request:e})}exportPortableBlockAsset(e){return this.request("export-portable-block-asset",{composition:this.selector(e.request.target.composition),request:e})}resolveSourceLocation(e){return this.request("resolve-source-location",{key:e.key,composition:this.selector(e.composition)})}execute(e,n){let s=w(e),o={...e,composition:y(s)};return this.request("execute",{request:o})}getOperationResult(e){return this.request("get-operation-result",{request:e,composition:y(w(e))})}getHistoryOperationResult(e){return this.request("get-history-operation-result",{request:e,composition:e.composition})}undo(e,n,s){return this.request("undo",{composition:this.selector(e),...s?{request:s}:{}})}redo(e,n,s){return this.request("redo",{composition:this.selector(e),...s?{request:s}:{}})}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}selector(e){return y(e)}request(e,n){let s=this.socket;if(!s||s.readyState!==R||this.connectionState!=="open")return Promise.reject(new Error(`WebSocket is not open (state: ${this.connectionState}, readyState: ${s?.readyState??"none"})`));let o=`${e}-${this.sequence+=1}`,r=we(o,e,n);return f("bridge.request",{id:o,kind:e,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:W(n.request,"kind"),documentVersion:W(n.request,"documentVersion")}),new Promise((c,i)=>{let a=this.resolveRequestTimeoutMs(e),u=a>0?setTimeout(()=>{let d=this.pending.get(o);d&&(this.pending.delete(o),f("bridge.response",{id:o,kind:e,ok:!1,timedOut:!0}),d.reject(new Error(`Bridge request timed out after ${a}ms: ${e}`)))},a):null;u?.unref?.(),this.pending.set(o,{kind:e,timeout:u,resolve:d=>c(d),reject:i});try{s.send(g.stringifyMessage(r))}catch(d){let m=S(d,"WebSocket send failed");this.clearPendingRequest(o),i(m),this.cleanupSocket(s,m,"failed")}})}handleAuthHandshakeMessage(e,n,s,o){try{if(g.parseMessage(e).type==="auth-ok"){o();return}throw new Error("Bridge authentication failed")}catch(r){let c=S(r,"Bridge authentication failed");this.connectAttempt===s&&this.cleanupSocket(n,c,"failed")}}handleMessage(e){let n=g.parseMessage(e);if(n.type==="event"){for(let o of this.listeners)o(n.payload.event);return}if(n.type!=="response"&&n.type!=="error")return;let s=this.pending.get(n.payload.id);if(s){if(this.clearPendingRequest(n.payload.id),(s.kind==="export-portable-block"||s.kind==="export-portable-block-asset")&&n.payload.kind!==s.kind){s.reject(new Error("Portable export response kind does not match the request."));return}if(n.type==="error"){f("bridge.response",{id:n.payload.id,kind:s.kind,ok:!1});let o=new Error(n.payload.message);n.payload.code&&(o.code=n.payload.code),s.reject(o);return}f("bridge.response",{id:n.payload.id,kind:s.kind,ok:!0,resultVersion:ke(n.payload.result)}),s.resolve(s.kind==="get-document"?{...n.payload.result,data:z(n.payload.result.data,n.payload.result.composition)}:s.kind==="initialize-session"?xe(n.payload.result):n.payload.result)}}rejectAll(e){for(let[n,s]of[...this.pending])this.clearPendingRequest(n),s.reject(e)}clearPendingRequest(e){let n=this.pending.get(e);n&&(n.timeout&&clearTimeout(n.timeout),this.pending.delete(e))}resolveRequestTimeoutMs(e){let n=this.options.requestTimeoutMsByKind?.[e];return typeof n=="number"?Math.max(0,n):typeof this.options.requestTimeoutMs=="number"?Math.max(0,this.options.requestTimeoutMs):Ce[e]??Ie}cleanupSocket(e,n,s){if(this.socket===e&&(this.socket=null),this.stopHeartbeat(e),this.connectAttempt?.socket===e){let o=this.connectAttempt;this.connectAttempt=null,clearTimeout(o.deadline),o.settled||(o.settled=!0,o.reject(n))}this.connectPromise=null,this.rejectAll(n),this.setConnectionState(s,n.message),e.onopen=null,e.onmessage=null,e.onerror=null,e.onclose=null;try{(e.readyState===he||e.readyState===R)&&e.close()}catch{}}startHeartbeat(e){let n=this.options.heartbeat===void 0?me:this.options.heartbeat;if(!n||n.intervalMs<=0||n.timeoutMs<=0)return;this.stopHeartbeat(this.heartbeatState?.socket??e);let s=this.options.visibility===void 0?be():this.options.visibility,o=()=>s?.visibilityState!=="hidden",r=()=>{this.heartbeatState?.socket===e&&this.heartbeatState.deadline&&(clearTimeout(this.heartbeatState.deadline),this.heartbeatState.deadline=null)},c=()=>{let a=this.heartbeatState;if(!(a?.socket!==e||this.socket!==e||this.connectionState!=="open"||a.deadline||!o())){try{e.send(g.stringifyMessage({type:"ping",payload:{id:`ping-${this.sequence+=1}`}}))}catch(u){this.cleanupSocket(e,S(u,"WebSocket heartbeat send failed"),"failed");return}a.deadline=setTimeout(()=>{this.heartbeatState?.socket===e&&(this.heartbeatState.deadline=null,o()&&(f("bridge.heartbeat-timeout",{timeoutMs:n.timeoutMs}),this.cleanupSocket(e,$(ye,`Bridge heartbeat was not answered within ${n.timeoutMs}ms`),"failed")))},n.timeoutMs)}},i=()=>{o()?c():r()};s?.addEventListener("visibilitychange",i),this.heartbeatState={socket:e,interval:setInterval(c,n.intervalMs),deadline:null,unbindVisibility:()=>s?.removeEventListener("visibilitychange",i)}}stopHeartbeat(e){let n=this.heartbeatState;!n||n.socket!==e||(clearInterval(n.interval),n.deadline&&clearTimeout(n.deadline),n.unbindVisibility(),this.heartbeatState=null)}noteInboundMessage(e){let n=this.heartbeatState;n?.socket===e&&n.deadline&&(clearTimeout(n.deadline),n.deadline=null)}setConnectionState(e,n){if(this.connectionState===e&&!n)return;this.connectionState=e;let s={state:e,...n?{message:n}:{}};this.options.onConnectionStatus?.(s);for(let o of this.connectionStatusListeners)o(s)}createSocket(e){if(this.options.createSocket)return this.options.createSocket(e);if(typeof WebSocket>"u")throw new Error("Site edit preview bridge requires WebSocket");return new WebSocket(e)}},he=0,R=1,fe=1e4,me={intervalMs:2e4,timeoutMs:1e4},ge="SITE_EDIT_BRIDGE_CONNECT_TIMEOUT",ye="SITE_EDIT_BRIDGE_HEARTBEAT_TIMEOUT";function be(){let t=globalThis.document;return t&&typeof t.visibilityState=="string"&&typeof t.addEventListener=="function"&&typeof t.removeEventListener=="function"?t:null}function $(t,e){let n=new Error(`${t}: ${e}`);return n.code=t,n}var Ie=15e3,Ce={"get-source-tree":1e4,"get-source-file":1e4,"resolve-source-location":1e4,execute:6e4,"get-operation-result":6e4,"get-history-operation-result":6e4,undo:2e4,redo:2e4};function S(t,e){return t instanceof Error?t:new Error(e)}function Se(t,e){return e.intentional?"WebSocket disconnected":t?.code===1008?t.reason?`Bridge session authentication failed: ${t.reason}`:"Bridge session authentication failed":t?.reason?`WebSocket closed: ${t.reason}`:typeof t?.code=="number"&&t.code!==1005?`WebSocket closed with code ${t.code}`:"WebSocket closed"}function W(t,e){if(!t||typeof t!="object")return null;let s=t[e];return typeof s=="string"||typeof s=="number"?s:null}function ke(t){if(!t||typeof t!="object")return null;let e=t,n=e.data?.resultVersion??e.data?.version??null;return typeof n=="number"?n:null}function Me(t){let e="composition"in t?y(t.composition):y({routeId:t.routeId});return new O({composition:e,initialDocument:t.initialDocument,client:t.client})}var O=class{constructor(e){this.params=e,this.serverConfirmedComposition=null,this.refreshInFlight=null,this.objectGeneration=0,this.styleGeneration=0,this.editContextCache=new Map,this.editContextInFlight=new Map,this.classNameSourceCache=new Map,this.classNameSourceInFlight=new Map,this.styleContextCache=new Map,this.styleContextInFlight=new Map,this.snapshotIdentityStale=!1,this.composition=y(e.composition);let n=e.initialDocument.composition.effectiveTemplateId;if(n!==void 0&&(this.composition.templateId===void 0||this.composition.templateId!==n))throw new Error(`Site edit bridge requires a matching templateId for initial document composition ${JSON.stringify(e.initialDocument.composition)}`);this.currentDocument=e.initialDocument,this.observedDocumentVersion=e.initialDocument.version,this.sessionInitialized=!F(e.initialDocument),this.activeCompositionContext=this.sessionInitialized?{...e.initialDocument.composition}:null}async getDocument(e){this.requireBoundComposition(e);let n=F(this.currentDocument)||this.snapshotIdentityStale;return(n||this.currentDocument.version<this.observedDocumentVersion)&&(this.currentDocument=await this.refreshSnapshot(n?void 0:this.observedDocumentVersion,"get-document"),this.snapshotIdentityStale=!1,this.sessionInitialized=!0),{ok:!0,data:this.currentDocument}}async initializeSession(e){let n=this.requireBoundComposition(e.composition);if(!this.params.client.initializeSession)throw new Error("Site edit bridge client does not support initialize-session");let s=await this.params.client.initializeSession({...e,composition:n});return this.currentDocument=s.data.document,this.observedDocumentVersion=s.data.document.version,this.activeCompositionContext={...s.composition},this.rememberServerConfirmedComposition(s.composition),this.sessionInitialized=!0,this.clearObjectCaches(),s}async getHistoryStatus(e){return this.params.client.getHistoryStatus(this.requireBoundComposition(e))}async getStyleContext(e){let n=this.requireBoundComposition(e),s=E(n),o=this.styleContextCache.get(s);if(o?.generation===this.styleGeneration)return{ok:!0,data:o.value};let r=this.styleContextInFlight.get(s);if(r?.generation===this.styleGeneration)return r.request;let c=this.styleGeneration,i=this.params.client.getStyleContext(n).then(a=>(this.styleGeneration===c&&this.styleContextCache.set(s,{generation:c,value:a.data}),a)).finally(()=>{this.styleContextInFlight.get(s)?.request===i&&this.styleContextInFlight.delete(s)});return this.styleContextInFlight.set(s,{generation:c,request:i}),i}async ensureDocumentVersion(e,n){this.requireBoundComposition(e);let s=await this.refreshSnapshot(n,"ensure-version");if(s.version<n)throw new Error(`Document refresh returned version ${s.version}, expected at least ${n}`);return{ok:!0,data:s}}async acknowledgeDocumentVersion(e,n){if(this.requireBoundComposition(e),n>this.currentDocument.version){if(this.currentDocument.pageComposition.status==="supported"){let s=await this.refreshSnapshot(n,"ensure-version");if(s.version<n)throw new Error(`Document refresh returned version ${s.version}, expected at least ${n}`);return{ok:!0,data:s}}this.currentDocument={...this.currentDocument,version:n},this.clearObjectCaches({preserveStyleContext:!0})}return this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n),{ok:!0,data:this.currentDocument}}async getObjectEditContext(e,n,s){let o=this.requireBoundComposition(n),r=this.objectCacheKey(e,o,s),c=this.editContextCache.get(r);if(c)return{ok:!0,composition:c.composition,data:c};let i=this.editContextInFlight.get(r);if(i)return i;let a=this.objectGeneration,u=this.params.client.getObjectEditContext(e,o,...s?[s]:[]).then(d=>(this.objectGeneration===a&&this.editContextCache.set(r,d.data),d)).finally(()=>{this.editContextInFlight.get(r)===u&&this.editContextInFlight.delete(r)});return this.editContextInFlight.set(r,u),u}async getClassNameSource(e,n){let s=this.requireBoundComposition(n),o=this.objectCacheKey(e,s),r=this.classNameSourceCache.get(o);if(r)return r;let c=this.classNameSourceInFlight.get(o);if(c)return c;let i=this.objectGeneration,a=this.params.client.getClassNameSource(e,s).then(u=>(this.objectGeneration===i&&this.classNameSourceCache.set(o,u),u)).finally(()=>{this.classNameSourceInFlight.get(o)===a&&this.classNameSourceInFlight.delete(o)});return this.classNameSourceInFlight.set(o,a),a}async getSourceTree(e){return this.params.client.getSourceTree(this.requireBoundComposition(e))}async getSourceFile(e){return this.params.client.getSourceFile({path:e.path,composition:this.requireBoundComposition(e.composition)})}async exportPortableBlock(e){return this.requireBoundComposition(e.target.composition),this.params.client.exportPortableBlock?this.params.client.exportPortableBlock(e):{complete:!1,unresolved:[{code:"PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE",path:"<snapshot>",message:"No trusted Snapshot proof is available."}]}}async exportPortableBlockAsset(e){return this.requireBoundComposition(e.request.target.composition),this.params.client.exportPortableBlockAsset?this.params.client.exportPortableBlockAsset(e):{complete:!1,unresolved:[{code:"PORTABLE_LOCAL_ASSET_UNAVAILABLE",path:"<asset>",message:"The selected local image is unavailable."}]}}async resolveSourceLocation(e){return this.params.client.resolveSourceLocation({key:e.key,composition:this.requireBoundComposition(e.composition)})}async execute(e,n){let s=w(e);s&&this.composition.templateId!==void 0&&this.requireBoundComposition(s);let o={...e,composition:s??this.composition};return this.params.client.execute(o)}async getOperationResult(e){return this.requireBoundComposition(e.composition),this.params.client.getOperationResult?this.params.client.getOperationResult(e):null}async getHistoryOperationResult(e){return this.requireBoundComposition(e.composition),await this.params.client.getHistoryOperationResult?.(e)??null}async undo(e,n,s){let o=this.requireBoundComposition(e);return s?this.params.client.undo(o,void 0,s):this.params.client.undo(o)}async redo(e,n,s){let o=this.requireBoundComposition(e);return s?this.params.client.redo(o,void 0,s):this.params.client.redo(o)}subscribe(e){return this.params.client.subscribe(n=>{if(n.type==="site-edit.snapshot.changed"&&this.sessionInitialized&&this.isActiveComposition(n.composition)){this.snapshotIdentityStale=!0,this.clearObjectCaches(),e(n);return}if(n.type==="site-edit.document.changed"&&this.sessionInitialized&&this.isActiveComposition(n.composition)){let s=n.version>this.observedDocumentVersion;this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n.version),s&&n.version>this.currentDocument.version&&this.clearObjectCaches(),e(n);return}e(n)})}async refreshSnapshot(e,n="ensure-version"){if(typeof e=="number"&&this.currentDocument.version>=e)return f("bridge.document-refresh",{composition:this.composition,routeId:this.composition.routeId,minVersion:e,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:n}),this.currentDocument;let s=E(this.composition),o=this.refreshInFlight;if(o?.compositionKey===s){f("bridge.document-refresh",{composition:this.composition,routeId:this.composition.routeId,minVersion:e,currentVersion:this.currentDocument.version,deduped:!0,source:n});let c=await o.request;if(typeof e!="number"||c.version>=e||this.currentDocument.version>=e)return this.currentDocument}f("bridge.document-refresh",{composition:this.composition,routeId:this.composition.routeId,minVersion:e,currentVersion:this.currentDocument.version,deduped:!1,source:n});let r=this.params.client.getDocument(this.composition).then(c=>{let i=!this.snapshotIdentityStale&&c.data.snapshotId===this.currentDocument.snapshotId&&k(c.data.composition)===k(this.currentDocument.composition)&&c.data.version>this.currentDocument.version&&c.data.version===this.observedDocumentVersion;return this.currentDocument=c.data,this.activeCompositionContext={...c.data.composition},this.rememberServerConfirmedComposition(c.data.composition),this.observedDocumentVersion=Math.max(this.observedDocumentVersion,c.data.version),i||this.clearObjectCaches(),this.currentDocument});this.refreshInFlight={compositionKey:s,request:r};try{return await r}finally{this.refreshInFlight?.request===r&&(this.refreshInFlight=null)}}clearObjectCaches(e){this.objectGeneration+=1,this.editContextCache.clear(),this.editContextInFlight.clear(),this.classNameSourceCache.clear(),this.classNameSourceInFlight.clear(),!e?.preserveStyleContext&&(this.styleGeneration+=1,this.styleContextCache.clear(),this.styleContextInFlight.clear())}objectCacheKey(e,n,s){return`${E(n)}\0${e}\0${Ee(s)}`}rememberServerConfirmedComposition(e){!e||typeof e.routeId!="string"||(this.serverConfirmedComposition={...e})}isAcceptedComposition(e){if(E(e)===E(this.composition))return!0;let n=this.serverConfirmedComposition;return n!==null&&k(n)===k(V(e))}requireBoundComposition(e){let n=e===void 0?this.composition:y(e);if(!this.isAcceptedComposition(n))throw new Error(`Site edit bridge is bound to composition ${JSON.stringify(this.composition)}, received ${JSON.stringify(n)}`);return y(n)}isActiveComposition(e){let n=this.activeCompositionContext??V(this.composition);return k(e)===k(n)}};function F(t){return t.version===0&&t.entries.length===0}function xe(t){let e=t;return{...e,data:{...e.data,document:z(e.data.document,e.composition)}}}function z(t,e){let n=t,s=K(n.routeId?n:{...n,routeId:e?.routeId??n.composition?.routeId});return e?{...s,composition:e}:s}function y(t){if(t&&typeof t=="object"&&typeof t.routeId=="string"){let e="effectiveTemplateId"in t?t.effectiveTemplateId:"templateId"in t?t.templateId:void 0;return{routeId:t.routeId,...typeof e=="string"?{templateId:e}:{}}}throw new Error("SITE_EDIT_COMPOSITION_SESSION_REQUIRED: a composition selector is required")}function E(t){return JSON.stringify([t.routeId,t.templateId??null])}function Ee(t){return t?JSON.stringify([t.key,t.instanceIndex??null,t.instanceCount??null]):""}function k(t){return JSON.stringify([t.routeId,t.effectiveTemplateId??null])}function V(t){return{routeId:t.routeId,...t.templateId?{effectiveTemplateId:t.templateId}:{}}}function w(t){if(t&&typeof t=="object"){let e=t;if(e.composition&&typeof e.composition=="object"){let n=e.composition;if(typeof n.routeId=="string")return{routeId:n.routeId,...typeof n.templateId=="string"?{templateId:n.templateId}:{}}}}}function we(t,e,n){let s=y(e==="execute"?w(n.request):n.composition),o={id:t,kind:e,composition:s};switch(e){case"initialize-session":case"get-document":case"get-history-status":case"get-style-context":case"get-source-tree":case"undo":case"redo":return{type:"request",payload:{...o,...n.mutationContext?{mutationContext:n.mutationContext}:{},...(e==="undo"||e==="redo")&&n.request?{request:n.request}:{}}};case"get-object-edit-context":return{type:"request",payload:{...o,key:String(n.key),...n.selectionRef?{selectionRef:n.selectionRef}:{}}};case"get-class-name-source":case"resolve-source-location":return{type:"request",payload:{...o,key:String(n.key)}};case"get-source-file":return{type:"request",payload:{...o,path:String(n.path)}};case"export-portable-block":case"export-portable-block-asset":return{type:"request",payload:{...o,request:n.request}};case"execute":case"get-operation-result":case"get-history-operation-result":return{type:"request",payload:{...o,request:{...n.request,composition:w(n.request)??s}}}}}export{ge as SITE_EDIT_BRIDGE_CONNECT_TIMEOUT,ye as SITE_EDIT_BRIDGE_HEARTBEAT_TIMEOUT,U as SiteEditWebSocketClient,Me as createSiteEditBridge};
1
+ function K(t){if(!G(t)){if(t.encoding==="segment-trie-v1")throw new Error("Invalid compact render document");return t}let e=new Map,n=t.pageComposition.status==="supported"?t.pageComposition.placementUnitKeys:[],s=new Map(t.dynamicDataSummaries??[]),o=new Map(t.pageCompositionActionScopes??[]),i=c=>{let r=e.get(c);if(r)return r;let a=t.nodes[c];if(!a)throw new Error(`Missing compact document node ${c}`);let[u,d]=a,m=t.tokens[d];if(typeof m!="string")throw new Error(`Missing compact document token ${d}`);let x=`${u===null?"":i(u)}${m}`;return e.set(c,x),x};return{siteId:t.siteId,snapshotId:t.snapshotId,composition:{...t.composition},routeId:t.composition.routeId,version:t.version,pageComposition:t.pageComposition,...t.pageBlocks!==void 0?{pageBlocks:t.pageBlocks}:{},entries:t.entries.map((c,r)=>{let[a,u,d]=c,m=d===void 0?void 0:n[d];if(d!==void 0&&!m)throw new Error(`Missing page composition unit ${d}`);let x=t.entryParentNodeIds?.[r],T=o.get(r),D=T?.kind==="source-siblings"?{kind:"source-siblings",siblingKeys:T.siblingEntryIndexes.map(B=>{let M=t.entries[B];if(!M)throw new Error(`Missing source sibling entry ${B}`);return i(M[0])})}:T;return{key:i(a),...t.entryParentNodeIds?{parentKey:x===null?null:i(x)}:{},...m?{pageCompositionUnitKey:m}:{},...D?{pageCompositionActionScope:D}:{},operationSummary:H(u),...s.get(r)?{dynamicDataSummary:s.get(r)}:{}}})}}function H(t){return{canUpdateText:(t&1)!==0,canInsertChild:(t&2)!==0,canMove:(t&4)!==0,canRemove:(t&8)!==0}}function G(t){if(typeof t!="object"||t===null)return!1;let e=t;if(e.encoding!=="segment-trie-v1"||typeof e.siteId!="string"||typeof e.snapshotId!="string"||!J(e.composition)||typeof e.routeId!="string"||e.routeId!==e.composition.routeId||!Number.isInteger(e.version)||e.version<0||!h(e.pageComposition)||e.pageBlocks!==void 0&&!Q(e.pageBlocks)||!Array.isArray(e.tokens)||!e.tokens.every(r=>typeof r=="string")||!Array.isArray(e.nodes)||!Array.isArray(e.entries))return!1;let n=e.nodes;if(!n.every((r,a)=>Array.isArray(r)&&r.length===2&&(r[0]===null||p(r[0])&&r[0]<a)&&p(r[1])&&r[1]<e.tokens.length)||!e.entries.every(r=>Array.isArray(r)&&(r.length===2||r.length===3)&&p(r[0])&&r[0]<n.length&&p(r[1])&&r[1]<=15&&(r.length===2||p(r[2]))))return!1;let s=e.entryParentNodeIds;if(s!==void 0&&(!Array.isArray(s)||s.length!==e.entries.length||!s.every(r=>r===null||p(r)&&r<n.length)))return!1;let o=e.dynamicDataSummaries,i=e.pageCompositionActionScopes;return(i===void 0||Array.isArray(i)&&i.every(r=>{if(!Array.isArray(r)||r.length!==2||!p(r[0])||r[0]>=e.entries.length||!h(r[1])||!["route-unit","source-siblings","unavailable"].includes(String(r[1].kind)))return!1;let a=r[1];return a.kind!=="source-siblings"||Array.isArray(a.siblingEntryIndexes)&&a.siblingEntryIndexes.length>=2&&a.siblingEntryIndexes.every(u=>p(u)&&u<e.entries.length)&&a.siblingEntryIndexes.includes(r[0])}))&&(o===void 0||Array.isArray(o)&&o.every(r=>Array.isArray(r)&&r.length===2&&p(r[0])&&r[0]<e.entries.length&&h(r[1])))}function h(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function J(t){return!h(t)||typeof t.routeId!="string"?!1:t.effectiveTemplateId===void 0||typeof t.effectiveTemplateId=="string"}function p(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0}function Q(t){if(!Array.isArray(t))return!1;let e=new Map;for(let n of t){if(!h(n)||!I(n,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!w(n.blockKey,256)||!w(n.definitionKey,512)||!Y(n.rootRef)||!Z(n.source)||!X(n.owner)||!Array.isArray(n.siblingBlockKeys)||!n.siblingBlockKeys.every(s=>w(s,256))||new Set(n.siblingBlockKeys).size!==n.siblingBlockKeys.length||n.siblingBlockKeys.includes(n.blockKey)||n.placementUnitKey!==void 0&&!b(n.placementUnitKey)||!ee(n.capabilities)||n.unavailableReasons!==void 0&&!te(n.unavailableReasons)||e.has(n.blockKey))return!1;e.set(n.blockKey,n)}for(let n of t){let s=n.owner;for(let o of n.siblingBlockKeys){let i=e.get(o);if(!i)return!1;let c=i.owner;if(s.kind!==c.kind||s.key!==c.key)return!1}}return!0}function Y(t){return!h(t)||!I(t,["key","instanceIndex","instanceCount"])||!b(t.key)||t.instanceIndex!==void 0&&!p(t.instanceIndex)||t.instanceCount!==void 0&&(!p(t.instanceCount)||t.instanceCount<1)?!1:!(t.instanceIndex!==void 0&&t.instanceCount!==void 0&&t.instanceIndex>=t.instanceCount)}function Z(t){return h(t)&&I(t,["file","structuralPath","contentHash"])&&typeof t.file=="string"&&ne(t.file)&&b(t.structuralPath)&&typeof t.contentHash=="string"&&/^sha256:[a-f0-9]{64}$/u.test(t.contentHash)}function X(t){return h(t)&&I(t,["kind","key"])&&(t.kind==="route-member"||t.kind==="component-definition")&&w(t.key,512)}function ee(t){return h(t)&&I(t,["insert","replace","move","remove","save"])&&typeof t.insert=="boolean"&&typeof t.replace=="boolean"&&typeof t.move=="boolean"&&typeof t.remove=="boolean"&&typeof t.save=="boolean"}function te(t){return h(t)&&Object.entries(t).every(([e,n])=>b(e)&&h(n)&&I(n,["code","reason"])&&b(n.code)&&b(n.reason))}function ne(t){let e=se(t),n=e?t.replace("/.vcp/","/_vcp/"):t;if(!t||t.startsWith("/")||t.includes("\\")||n.split("/").some(i=>!i||i==="."||i===".."||i.startsWith(".")||i==="node_modules"||i.toLowerCase()==="package.json"||i==="recipes"||i.startsWith(".env")))return!1;let s=t.toLowerCase();return/^(?:src\/)?app\/api(?:\/|$)/u.test(s)||/^(?:src\/)?app\/(?:.*\/)?route\.[cm]?[jt]sx?$/u.test(s)||/(^|\/)[^/]+\.server\.[cm]?[jt]sx?$/u.test(s)||/^(?:src\/)?app\/(?:.*\/)?(?:action|actions)\.[cm]?[jt]sx?$/u.test(s)||/^(?:lib|src\/lib)\/(?:server|db|cms)(?:\/|$)/u.test(s)||s.split("/").some(i=>["server","db","database","auth","secret","secrets","token","tokens","credential","credentials"].includes(i.replace(/\.[^.]+$/u,"")))?!1:["design.md","app/globals.css","src/app/globals.css"].includes(t.toLowerCase())||/^(?:src\/)?app\/(?:.*\/)?page\.[cm]?[jt]sx?$/iu.test(t)||["components/system/not-found-content.tsx","src/components/system/not-found-content.tsx"].includes(t)||["components/site","src/components/site","lib/generated","src/lib/generated","public"].some(i=>t===i||t.startsWith(`${i}/`))||e}function se(t){let e=/^(?:src\/)?app\/\.vcp\/page-templates\/(.+)\/page\.tsx$/u.exec(t);if(!e)return!1;let n=e[1].split("/"),s=n.some(c=>v(c)),o=s?n[0]:n.pop(),i=s?n.slice(1):n;if(s&&i.length===0||!/^[A-Za-z0-9_-]{1,255}$/u.test(o)||!oe(`/${i.join("/")}`)||i.some(c=>c.includes("[")||c.includes("]")?!v(c):/[\[\]()%]/u.test(c)||c.startsWith("_")||c.startsWith("@")))return!1;try{let c=o.replace(/-/gu,"+").replace(/_/gu,"/"),r=atob(c),a=Uint8Array.from(r,d=>d.charCodeAt(0)),u=new TextDecoder("utf-8",{fatal:!0}).decode(a);return u.length>0&&u.length<=191&&!/[^\x20-\x7e\xa0-\xff]/u.test(u)&&!u.startsWith(" ")&&!u.endsWith(" ")&&new TextEncoder().encode(u).byteLength<=191&&btoa(String.fromCharCode(...new TextEncoder().encode(u))).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")===o}catch{return!1}}function v(t){return/^\[\[\.\.\.[^\[\]]+\]\]$/u.test(t)||/^\[[^\[\]]+\]$/u.test(t)}function oe(t){return!t.startsWith("/")||t.startsWith("//")||/[?#\\\x00-\x20\x7f]/u.test(t)||t.startsWith("/.vcp")?!1:!t.split("/").some(e=>{try{let n=decodeURIComponent(e);return n==="."||n===".."||/[/\\\x00-\x1f\x7f]/u.test(n)||n.startsWith(".vcp")}catch{return!0}})}function w(t,e){return typeof t=="string"&&t.length>0&&t.length<=e}function b(t){return typeof t=="string"&&t.length>0}function I(t,e){let n=new Set(e);return Object.keys(t).every(s=>n.has(s))}var g=class t{constructor(){}static parseMessage(e,n={}){let s=JSON.parse(e);if(!t.isMessage(s,n))throw new Error("Invalid site edit bridge message");return s}static stringifyMessage(e){return JSON.stringify(e)}static extractRequestInfo(e){if(l(e)&&l(e.payload)){let n=typeof e.payload.id=="string"?e.payload.id:"unknown",s=this.isRequestKind(e.payload.kind)?e.payload.kind:"get-document";return{id:n,kind:s}}return{id:"unknown",kind:"get-document"}}static isRequestKind(e){return e==="initialize-session"||e==="get-document"||e==="get-history-status"||e==="get-style-context"||e==="get-object-edit-context"||e==="get-class-name-source"||e==="get-source-tree"||e==="get-source-file"||e==="export-portable-block"||e==="export-portable-block-asset"||e==="resolve-source-location"||e==="execute"||e==="get-operation-result"||e==="get-history-operation-result"||e==="undo"||e==="redo"}static isMessage(e,n={}){return!l(e)||typeof e.type!="string"?!1:e.type==="request"?ie(e.payload,n):e.type==="response"||e.type==="error"?l(e.payload)&&typeof e.payload.id=="string":e.type==="event"?l(e.payload)&&l(e.payload.event):e.type==="auth"?l(e.payload)&&typeof e.payload.key=="string":e.type==="ping"||e.type==="pong"?l(e.payload)&&typeof e.payload.id=="string":e.type==="auth-ok"&&l(e.payload)&&e.payload.ok===!0}};function ie(t,e){if(!l(t)||typeof t.id!="string"||!g.isRequestKind(t.kind))return!1;let n=C(t.composition);switch(t.kind){case"initialize-session":return n&&(t.mutationContext===void 0||q(t.mutationContext));case"get-document":case"get-style-context":return n;case"get-object-edit-context":return typeof t.key=="string"&&n&&j(t.selectionRef);case"get-class-name-source":case"resolve-source-location":return typeof t.key=="string"&&n;case"get-history-status":return n;case"get-source-tree":return n;case"get-source-file":return typeof t.path=="string"&&n;case"export-portable-block":return N(t);case"export-portable-block-asset":return ce(t);case"execute":case"get-operation-result":return n&&ae(t.request)&&(t.request.mutationContext===void 0||q(t.request.mutationContext))&&(e.validateOperationRequest?.(t.request)??!0);case"get-history-operation-result":return n&&P(t.request);case"undo":case"redo":return n&&(t.request===void 0||P(t.request)&&t.request.kind===t.kind)&&(t.mutationContext===void 0||q(t.mutationContext))}}function N(t){if(!C(t.composition)||!Object.keys(t).every(n=>["id","kind","composition","request"].includes(n))||!l(t.request))return!1;let e=t.request;return!(!Object.keys(e).every(n=>["site_id","base_snapshot_id","document_version","target","selection_ref","cms_schema_proofs"].includes(n))||typeof e.site_id!="string"||typeof e.base_snapshot_id!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(e.site_id)||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(e.base_snapshot_id)||typeof e.document_version!="number"||!Number.isSafeInteger(e.document_version)||e.document_version<0||!l(e.target)||e.target.kind!=="page-block"||typeof e.target.blockKey!="string"||!e.target.blockKey.length||e.target.blockKey.length>256||!Object.keys(e.target).every(n=>["kind","composition","blockKey"].includes(n))||!C(e.target.composition)||e.target.composition.routeId!==t.composition.routeId||e.target.composition.templateId!==t.composition.templateId||e.selection_ref===void 0||!j(e.selection_ref)||e.cms_schema_proofs!==void 0&&!re(e.cms_schema_proofs))}function re(t){if(!Array.isArray(t)||t.length>16||!Reflect.ownKeys(t).every(e=>e==="length"||typeof e=="string"&&/^(0|[1-9][0-9]*)$/u.test(e)&&Number(e)<t.length))return!1;for(let e=0;e<t.length;e++){let n=Object.getOwnPropertyDescriptor(t,String(e));if(!n||!("value"in n))return!1;let s=n.value;if(!l(s)||!Reflect.ownKeys(s).every(c=>typeof c=="string"&&["payload","signature"].includes(c)))return!1;let o=Object.getOwnPropertyDescriptor(s,"payload"),i=Object.getOwnPropertyDescriptor(s,"signature");if(!o||!("value"in o)||!i||!("value"in i)||typeof o.value!="string"||o.value.length<1||o.value.length>262144||!/^[A-Za-z0-9_-]+$/u.test(o.value)||typeof i.value!="string"||!/^[A-Za-z0-9_-]{86}$/u.test(i.value))return!1}return!0}function ce(t){if(!Object.keys(t).every(n=>["id","kind","composition","request"].includes(n))||!l(t.request))return!1;let e=t.request;return!(!Object.keys(e).every(n=>["request","snapshot_digest","file_path","occurrence","offset"].includes(n))||!N({id:t.id,kind:"export-portable-block",composition:t.composition,request:e.request})||typeof e.snapshot_digest!="string"||!/^sha256:[a-f0-9]{64}$/u.test(e.snapshot_digest)||typeof e.file_path!="string"||!e.file_path.length||e.file_path.length>1024||e.file_path.startsWith("/")||/[\\\0%]/u.test(e.file_path)||e.file_path.split("/").some(n=>!n||n.startsWith(".")||n==="node_modules")||typeof e.occurrence!="number"||!Number.isSafeInteger(e.occurrence)||e.occurrence<0||e.occurrence>4095||typeof e.offset!="number"||!Number.isSafeInteger(e.offset)||e.offset<0||e.offset>50*1024*1024||e.offset%(1024*1024)!==0)}function P(t){return l(t)&&typeof t.request_id=="string"&&t.request_id.length>0&&t.request_id.length<=128&&typeof t.site_id=="string"&&t.site_id.length>0&&typeof t.base_snapshot_id=="string"&&t.base_snapshot_id.length>0&&(t.kind==="undo"||t.kind==="redo")&&C(t.composition)&&Object.keys(t).every(e=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(e))}function j(t){if(t===void 0)return!0;if(!l(t)||typeof t.key!="string"||t.key.length===0)return!1;let e=t.instanceIndex,n=t.instanceCount;return e!==void 0&&(typeof e!="number"||!Number.isInteger(e)||e<0)||n!==void 0&&(typeof n!="number"||!Number.isInteger(n)||n<=0)||typeof e=="number"&&typeof n=="number"&&e>=n?!1:Object.keys(t).every(s=>s==="key"||s==="instanceIndex"||s==="instanceCount")}function ae(t){return l(t)&&typeof t.id=="string"&&typeof t.siteId=="string"&&typeof t.baseSnapshotId=="string"&&C(t.composition)&&typeof t.kind=="string"&&l(t.target)&&(t.target.kind!=="route"||C(t.target.composition))&&typeof t.documentVersion=="number"&&Number.isInteger(t.documentVersion)&&t.documentVersion>=0&&l(t.params)}function C(t){return l(t)&&typeof t.routeId=="string"&&t.routeId.length>0&&(t.templateId===void 0||typeof t.templateId=="string"&&t.templateId.length>0)&&Object.keys(t).every(e=>e==="routeId"||e==="templateId")}function l(t){return typeof t=="object"&&t!==null}function q(t){return l(t)&&typeof t.editingSessionId=="string"&&t.editingSessionId.length>0&&typeof t.lockId=="string"&&t.lockId.length>0&&typeof t.ownerId=="string"&&t.ownerId.length>0&&typeof t.leaseAssertion=="string"&&t.leaseAssertion.length>0}var ue="vcp:designer:trace",de="designer_trace",L="__VCP_DESIGNER_TRACE__";var le=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function pe(t=globalThis){let e=t;try{if(e.localStorage?.getItem(ue)==="1")return!0}catch{}try{let n=e.location?.search??"";return new URLSearchParams(n).get(de)==="1"}catch{return!1}}function f(t,e={},n=globalThis){if(!pe(n))return;let s={type:t,timestamp:Date.now(),payload:he(e)},o=n,i=o[L]??[];i.push(s),i.length>1e3&&i.splice(0,i.length-1e3),o[L]=i;let c=n.console?.debug;s.payload.diagnosticOnly!==!0&&typeof c=="function"&&c.call(n.console,"[designer-trace]",s)}function he(t){return A(t,0)}function A(t,e){if(e>4)return"[truncated]";if(Array.isArray(t))return t.map(s=>A(s,e+1));if(!t||typeof t!="object")return t;let n={};for(let[s,o]of Object.entries(t)){if(le.test(s)){n[s]="[redacted]";continue}n[s]=A(o,e+1)}return n}var U=class{constructor(e){this.options=e,this.socket=null,this.connectPromise=null,this.connectAttempt=null,this.connectionState="idle",this.intentionalClose=!1,this.sequence=0,this.pending=new Map,this.listeners=new Set,this.heartbeatState=null,this.connectionStatusListeners=new Set}connect(){return this.socket?.readyState===R&&this.connectionState==="open"?(this.setConnectionState("open"),Promise.resolve()):this.connectPromise?this.connectPromise:(this.intentionalClose=!1,this.setConnectionState("connecting"),this.connectPromise=new Promise((e,n)=>{let s;try{s=this.createSocket(this.options.url)}catch(a){let u=S(a,"WebSocket failed");this.socket=null,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("failed",u.message),n(u);return}let o={socket:s,settled:!1,reject:n};this.connectAttempt=o,this.socket=s;let i=Math.max(0,this.options.connectTimeoutMs??me);i>0&&(o.deadline=setTimeout(()=>{this.connectAttempt!==o||o.settled||(f("bridge.connect-timeout",{connectTimeoutMs:i}),this.cleanupSocket(s,$(ye,`Bridge connection did not complete within ${i}ms`),"failed"))},i));let c=()=>{this.socket!==s||this.connectAttempt!==o||(o.settled=!0,clearTimeout(o.deadline),this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("open"),this.startHeartbeat(s),e())},r=(a,u)=>{this.cleanupSocket(s,a,u)};s.onopen=()=>{if(!(this.socket!==s||this.connectAttempt!==o)){if(this.options.authKey){try{s.send(g.stringifyMessage({type:"auth",payload:{key:this.options.authKey}}))}catch(a){r(S(a,"WebSocket auth failed"),"failed")}return}c()}},s.onerror=a=>{if(this.socket!==s)return;let u=S(a,"WebSocket failed");r(u,"failed")},s.onmessage=a=>{if(this.socket===s){if(this.noteInboundMessage(s),this.options.authKey&&this.connectAttempt===o&&!o.settled){this.handleAuthHandshakeMessage(a.data,s,o,()=>{c()});return}this.handleMessage(a.data)}},s.onclose=a=>{if(this.socket!==s)return;let u=this.intentionalClose,d=new Error(ke(a,{intentional:u}));r(d,u?"closed":"failed")}}),this.connectPromise)}disconnect(){this.intentionalClose=!0,this.setConnectionState("closing");let e=this.socket;if(!e){this.rejectAll(new Error("WebSocket disconnected")),this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("closed");return}this.cleanupSocket(e,new Error("WebSocket disconnected"),"closed")}getConnectionState(){return this.connectionState}subscribeConnectionStatus(e){return this.connectionStatusListeners.add(e),e({state:this.connectionState}),()=>{this.connectionStatusListeners.delete(e)}}getDocument(e){let n=this.selector(e);return this.request("get-document",{composition:n})}async initializeSession(e){let n=this.selector(e.composition);return await this.request("initialize-session",{composition:n,...e.mutationContext?{mutationContext:e.mutationContext}:{}})}getHistoryStatus(e){return this.request("get-history-status",{composition:this.selector(e)})}getStyleContext(e){let n=this.selector(e);return this.request("get-style-context",{composition:n})}getObjectEditContext(e,n,s){let o=this.selector(n);return this.request("get-object-edit-context",{key:e,composition:o,...s?{selectionRef:s}:{}})}getClassNameSource(e,n){let s=this.selector(n);return this.request("get-class-name-source",{key:e,composition:s})}getSourceTree(e){return this.request("get-source-tree",{composition:this.selector(e)})}getSourceFile(e){return this.request("get-source-file",{path:e.path,composition:this.selector(e.composition)})}exportPortableBlock(e){return this.request("export-portable-block",{composition:this.selector(e.target.composition),request:e})}exportPortableBlockAsset(e){return this.request("export-portable-block-asset",{composition:this.selector(e.request.target.composition),request:e})}resolveSourceLocation(e){return this.request("resolve-source-location",{key:e.key,composition:this.selector(e.composition)})}execute(e,n){let s=_(e),o={...e,composition:y(s)};return this.request("execute",{request:o})}getOperationResult(e){return this.request("get-operation-result",{request:e,composition:y(_(e))})}getHistoryOperationResult(e){return this.request("get-history-operation-result",{request:e,composition:e.composition})}undo(e,n,s){return this.request("undo",{composition:this.selector(e),...s?{request:s}:{}})}redo(e,n,s){return this.request("redo",{composition:this.selector(e),...s?{request:s}:{}})}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}selector(e){return y(e)}request(e,n){let s=this.socket;if(!s||s.readyState!==R||this.connectionState!=="open")return Promise.reject(new Error(`WebSocket is not open (state: ${this.connectionState}, readyState: ${s?.readyState??"none"})`));let o=`${e}-${this.sequence+=1}`,i=we(o,e,n);return f("bridge.request",{id:o,kind:e,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:W(n.request,"kind"),documentVersion:W(n.request,"documentVersion")}),new Promise((c,r)=>{let a=this.resolveRequestTimeoutMs(e),u=a>0?setTimeout(()=>{let d=this.pending.get(o);d&&(this.pending.delete(o),f("bridge.response",{id:o,kind:e,ok:!1,timedOut:!0}),d.reject(new Error(`Bridge request timed out after ${a}ms: ${e}`)))},a):null;u?.unref?.(),this.pending.set(o,{kind:e,timeout:u,resolve:d=>c(d),reject:r});try{s.send(g.stringifyMessage(i))}catch(d){let m=S(d,"WebSocket send failed");this.clearPendingRequest(o),r(m),this.cleanupSocket(s,m,"failed")}})}handleAuthHandshakeMessage(e,n,s,o){try{if(g.parseMessage(e).type==="auth-ok"){o();return}throw new Error("Bridge authentication failed")}catch(i){let c=S(i,"Bridge authentication failed");this.connectAttempt===s&&this.cleanupSocket(n,c,"failed")}}handleMessage(e){let n=g.parseMessage(e);if(n.type==="event"){for(let o of this.listeners)o(n.payload.event);return}if(n.type!=="response"&&n.type!=="error")return;let s=this.pending.get(n.payload.id);if(s){if(this.clearPendingRequest(n.payload.id),(s.kind==="export-portable-block"||s.kind==="export-portable-block-asset")&&n.payload.kind!==s.kind){s.reject(new Error("Portable export response kind does not match the request."));return}if(n.type==="error"){f("bridge.response",{id:n.payload.id,kind:s.kind,ok:!1});let o=new Error(n.payload.message);n.payload.code&&(o.code=n.payload.code),s.reject(o);return}f("bridge.response",{id:n.payload.id,kind:s.kind,ok:!0,resultVersion:xe(n.payload.result)}),s.resolve(s.kind==="get-document"?{...n.payload.result,data:z(n.payload.result.data,n.payload.result.composition)}:s.kind==="initialize-session"?Ee(n.payload.result):n.payload.result)}}rejectAll(e){for(let[n,s]of[...this.pending])this.clearPendingRequest(n),s.reject(e)}clearPendingRequest(e){let n=this.pending.get(e);n&&(n.timeout&&clearTimeout(n.timeout),this.pending.delete(e))}resolveRequestTimeoutMs(e){let n=this.options.requestTimeoutMsByKind?.[e];return typeof n=="number"?Math.max(0,n):typeof this.options.requestTimeoutMs=="number"?Math.max(0,this.options.requestTimeoutMs):Se[e]??Ce}cleanupSocket(e,n,s){if(this.socket===e&&(this.socket=null),this.stopHeartbeat(e),this.connectAttempt?.socket===e){let o=this.connectAttempt;this.connectAttempt=null,clearTimeout(o.deadline),o.settled||(o.settled=!0,o.reject(n))}this.connectPromise=null,this.rejectAll(n),this.setConnectionState(s,n.message),e.onopen=null,e.onmessage=null,e.onerror=null,e.onclose=null;try{(e.readyState===fe||e.readyState===R)&&e.close()}catch{}}startHeartbeat(e){let n=this.options.heartbeat===void 0?ge:this.options.heartbeat;if(!n||n.intervalMs<=0||n.timeoutMs<=0)return;this.stopHeartbeat(this.heartbeatState?.socket??e);let s=this.options.visibility===void 0?Ie():this.options.visibility,o=()=>s?.visibilityState!=="hidden",i=()=>{this.heartbeatState?.socket===e&&this.heartbeatState.deadline&&(clearTimeout(this.heartbeatState.deadline),this.heartbeatState.deadline=null)},c=()=>{let a=this.heartbeatState;if(!(a?.socket!==e||this.socket!==e||this.connectionState!=="open"||a.deadline||!o())){try{e.send(g.stringifyMessage({type:"ping",payload:{id:`ping-${this.sequence+=1}`}}))}catch(u){this.cleanupSocket(e,S(u,"WebSocket heartbeat send failed"),"failed");return}a.deadline=setTimeout(()=>{this.heartbeatState?.socket===e&&(this.heartbeatState.deadline=null,o()&&(f("bridge.heartbeat-timeout",{timeoutMs:n.timeoutMs}),this.cleanupSocket(e,$(be,`Bridge heartbeat was not answered within ${n.timeoutMs}ms`),"failed")))},n.timeoutMs)}},r=()=>{o()?c():i()};s?.addEventListener("visibilitychange",r),this.heartbeatState={socket:e,interval:setInterval(c,n.intervalMs),deadline:null,unbindVisibility:()=>s?.removeEventListener("visibilitychange",r)}}stopHeartbeat(e){let n=this.heartbeatState;!n||n.socket!==e||(clearInterval(n.interval),n.deadline&&clearTimeout(n.deadline),n.unbindVisibility(),this.heartbeatState=null)}noteInboundMessage(e){let n=this.heartbeatState;n?.socket===e&&n.deadline&&(clearTimeout(n.deadline),n.deadline=null)}setConnectionState(e,n){if(this.connectionState===e&&!n)return;this.connectionState=e;let s={state:e,...n?{message:n}:{}};this.options.onConnectionStatus?.(s);for(let o of this.connectionStatusListeners)o(s)}createSocket(e){if(this.options.createSocket)return this.options.createSocket(e);if(typeof WebSocket>"u")throw new Error("Site edit preview bridge requires WebSocket");return new WebSocket(e)}},fe=0,R=1,me=1e4,ge={intervalMs:2e4,timeoutMs:1e4},ye="SITE_EDIT_BRIDGE_CONNECT_TIMEOUT",be="SITE_EDIT_BRIDGE_HEARTBEAT_TIMEOUT";function Ie(){let t=globalThis.document;return t&&typeof t.visibilityState=="string"&&typeof t.addEventListener=="function"&&typeof t.removeEventListener=="function"?t:null}function $(t,e){let n=new Error(`${t}: ${e}`);return n.code=t,n}var Ce=15e3,Se={"get-source-tree":1e4,"get-source-file":1e4,"resolve-source-location":1e4,execute:6e4,"get-operation-result":6e4,"get-history-operation-result":6e4,undo:2e4,redo:2e4};function S(t,e){return t instanceof Error?t:new Error(e)}function ke(t,e){return e.intentional?"WebSocket disconnected":t?.code===1008?t.reason?`Bridge session authentication failed: ${t.reason}`:"Bridge session authentication failed":t?.reason?`WebSocket closed: ${t.reason}`:typeof t?.code=="number"&&t.code!==1005?`WebSocket closed with code ${t.code}`:"WebSocket closed"}function W(t,e){if(!t||typeof t!="object")return null;let s=t[e];return typeof s=="string"||typeof s=="number"?s:null}function xe(t){if(!t||typeof t!="object")return null;let e=t,n=e.data?.resultVersion??e.data?.version??null;return typeof n=="number"?n:null}function ve(t){let e="composition"in t?y(t.composition):y({routeId:t.routeId});return new O({composition:e,initialDocument:t.initialDocument,client:t.client})}var O=class{constructor(e){this.params=e,this.serverConfirmedComposition=null,this.refreshInFlight=null,this.objectGeneration=0,this.styleGeneration=0,this.editContextCache=new Map,this.editContextInFlight=new Map,this.classNameSourceCache=new Map,this.classNameSourceInFlight=new Map,this.styleContextCache=new Map,this.styleContextInFlight=new Map,this.snapshotIdentityStale=!1,this.composition=y(e.composition);let n=e.initialDocument.composition.effectiveTemplateId;if(n!==void 0&&(this.composition.templateId===void 0||this.composition.templateId!==n))throw new Error(`Site edit bridge requires a matching templateId for initial document composition ${JSON.stringify(e.initialDocument.composition)}`);this.currentDocument=e.initialDocument,this.observedDocumentVersion=e.initialDocument.version,this.sessionInitialized=!F(e.initialDocument),this.activeCompositionContext=this.sessionInitialized?{...e.initialDocument.composition}:null}async getDocument(e){this.requireBoundComposition(e);let n=F(this.currentDocument)||this.snapshotIdentityStale;return(n||this.currentDocument.version<this.observedDocumentVersion)&&(this.currentDocument=await this.refreshSnapshot(n?void 0:this.observedDocumentVersion,"get-document"),this.snapshotIdentityStale=!1,this.sessionInitialized=!0),{ok:!0,data:this.currentDocument}}async initializeSession(e){let n=this.requireBoundComposition(e.composition);if(!this.params.client.initializeSession)throw new Error("Site edit bridge client does not support initialize-session");let s=await this.params.client.initializeSession({...e,composition:n});return this.currentDocument=s.data.document,this.observedDocumentVersion=s.data.document.version,this.activeCompositionContext={...s.composition},this.rememberServerConfirmedComposition(s.composition),this.sessionInitialized=!0,this.clearObjectCaches(),s}async getHistoryStatus(e){return this.params.client.getHistoryStatus(this.requireBoundComposition(e))}async getStyleContext(e){let n=this.requireBoundComposition(e),s=E(n),o=this.styleContextCache.get(s);if(o?.generation===this.styleGeneration)return{ok:!0,data:o.value};let i=this.styleContextInFlight.get(s);if(i?.generation===this.styleGeneration)return i.request;let c=this.styleGeneration,r=this.params.client.getStyleContext(n).then(a=>(this.styleGeneration===c&&this.styleContextCache.set(s,{generation:c,value:a.data}),a)).finally(()=>{this.styleContextInFlight.get(s)?.request===r&&this.styleContextInFlight.delete(s)});return this.styleContextInFlight.set(s,{generation:c,request:r}),r}async ensureDocumentVersion(e,n){this.requireBoundComposition(e);let s=await this.refreshSnapshot(n,"ensure-version");if(s.version<n)throw new Error(`Document refresh returned version ${s.version}, expected at least ${n}`);return{ok:!0,data:s}}async acknowledgeDocumentVersion(e,n){if(this.requireBoundComposition(e),n>this.currentDocument.version){if(this.currentDocument.pageComposition.status==="supported"){let s=await this.refreshSnapshot(n,"ensure-version");if(s.version<n)throw new Error(`Document refresh returned version ${s.version}, expected at least ${n}`);return{ok:!0,data:s}}this.currentDocument={...this.currentDocument,version:n},this.clearObjectCaches({preserveStyleContext:!0})}return this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n),{ok:!0,data:this.currentDocument}}async getObjectEditContext(e,n,s){let o=this.requireBoundComposition(n),i=this.objectCacheKey(e,o,s),c=this.editContextCache.get(i);if(c)return{ok:!0,composition:c.composition,data:c};let r=this.editContextInFlight.get(i);if(r)return r;let a=this.objectGeneration,u=this.params.client.getObjectEditContext(e,o,...s?[s]:[]).then(d=>(this.objectGeneration===a&&this.editContextCache.set(i,d.data),d)).finally(()=>{this.editContextInFlight.get(i)===u&&this.editContextInFlight.delete(i)});return this.editContextInFlight.set(i,u),u}async getClassNameSource(e,n){let s=this.requireBoundComposition(n),o=this.objectCacheKey(e,s),i=this.classNameSourceCache.get(o);if(i)return i;let c=this.classNameSourceInFlight.get(o);if(c)return c;let r=this.objectGeneration,a=this.params.client.getClassNameSource(e,s).then(u=>(this.objectGeneration===r&&this.classNameSourceCache.set(o,u),u)).finally(()=>{this.classNameSourceInFlight.get(o)===a&&this.classNameSourceInFlight.delete(o)});return this.classNameSourceInFlight.set(o,a),a}async getSourceTree(e){return this.params.client.getSourceTree(this.requireBoundComposition(e))}async getSourceFile(e){return this.params.client.getSourceFile({path:e.path,composition:this.requireBoundComposition(e.composition)})}async exportPortableBlock(e){return this.requireBoundComposition(e.target.composition),this.params.client.exportPortableBlock?this.params.client.exportPortableBlock(e):{complete:!1,unresolved:[{code:"PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE",path:"<snapshot>",message:"No trusted Snapshot proof is available."}]}}async exportPortableBlockAsset(e){return this.requireBoundComposition(e.request.target.composition),this.params.client.exportPortableBlockAsset?this.params.client.exportPortableBlockAsset(e):{complete:!1,unresolved:[{code:"PORTABLE_LOCAL_ASSET_UNAVAILABLE",path:"<asset>",message:"The selected local image is unavailable."}]}}async resolveSourceLocation(e){return this.params.client.resolveSourceLocation({key:e.key,composition:this.requireBoundComposition(e.composition)})}async execute(e,n){let s=_(e);s&&this.composition.templateId!==void 0&&this.requireBoundComposition(s);let o={...e,composition:s??this.composition};return this.params.client.execute(o)}async getOperationResult(e){return this.requireBoundComposition(e.composition),this.params.client.getOperationResult?this.params.client.getOperationResult(e):null}async getHistoryOperationResult(e){return this.requireBoundComposition(e.composition),await this.params.client.getHistoryOperationResult?.(e)??null}async undo(e,n,s){let o=this.requireBoundComposition(e);return s?this.params.client.undo(o,void 0,s):this.params.client.undo(o)}async redo(e,n,s){let o=this.requireBoundComposition(e);return s?this.params.client.redo(o,void 0,s):this.params.client.redo(o)}subscribe(e){return this.params.client.subscribe(n=>{if(n.type==="site-edit.snapshot.changed"&&this.sessionInitialized&&this.isActiveComposition(n.composition)){this.snapshotIdentityStale=!0,this.clearObjectCaches(),e(n);return}if(n.type==="site-edit.document.changed"&&this.sessionInitialized&&this.isActiveComposition(n.composition)){let s=n.version>this.observedDocumentVersion;this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n.version),s&&n.version>this.currentDocument.version&&this.clearObjectCaches(),e(n);return}e(n)})}async refreshSnapshot(e,n="ensure-version"){if(typeof e=="number"&&this.currentDocument.version>=e)return f("bridge.document-refresh",{composition:this.composition,routeId:this.composition.routeId,minVersion:e,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:n}),this.currentDocument;let s=E(this.composition),o=this.refreshInFlight;if(o?.compositionKey===s){f("bridge.document-refresh",{composition:this.composition,routeId:this.composition.routeId,minVersion:e,currentVersion:this.currentDocument.version,deduped:!0,source:n});let c=await o.request;if(typeof e!="number"||c.version>=e||this.currentDocument.version>=e)return this.currentDocument}f("bridge.document-refresh",{composition:this.composition,routeId:this.composition.routeId,minVersion:e,currentVersion:this.currentDocument.version,deduped:!1,source:n});let i=this.params.client.getDocument(this.composition).then(c=>{let r=!this.snapshotIdentityStale&&c.data.snapshotId===this.currentDocument.snapshotId&&k(c.data.composition)===k(this.currentDocument.composition)&&c.data.version>this.currentDocument.version&&c.data.version===this.observedDocumentVersion;return this.currentDocument=c.data,this.activeCompositionContext={...c.data.composition},this.rememberServerConfirmedComposition(c.data.composition),this.observedDocumentVersion=Math.max(this.observedDocumentVersion,c.data.version),r||this.clearObjectCaches(),this.currentDocument});this.refreshInFlight={compositionKey:s,request:i};try{return await i}finally{this.refreshInFlight?.request===i&&(this.refreshInFlight=null)}}clearObjectCaches(e){this.objectGeneration+=1,this.editContextCache.clear(),this.editContextInFlight.clear(),this.classNameSourceCache.clear(),this.classNameSourceInFlight.clear(),!e?.preserveStyleContext&&(this.styleGeneration+=1,this.styleContextCache.clear(),this.styleContextInFlight.clear())}objectCacheKey(e,n,s){return`${E(n)}\0${e}\0${_e(s)}`}rememberServerConfirmedComposition(e){!e||typeof e.routeId!="string"||(this.serverConfirmedComposition={...e})}isAcceptedComposition(e){if(E(e)===E(this.composition))return!0;let n=this.serverConfirmedComposition;return n!==null&&k(n)===k(V(e))}requireBoundComposition(e){let n=e===void 0?this.composition:y(e);if(!this.isAcceptedComposition(n))throw new Error(`Site edit bridge is bound to composition ${JSON.stringify(this.composition)}, received ${JSON.stringify(n)}`);return y(n)}isActiveComposition(e){let n=this.activeCompositionContext??V(this.composition);return k(e)===k(n)}};function F(t){return t.version===0&&t.entries.length===0}function Ee(t){let e=t;return{...e,data:{...e.data,document:z(e.data.document,e.composition)}}}function z(t,e){let n=t,s=K(n.routeId?n:{...n,routeId:e?.routeId??n.composition?.routeId});return e?{...s,composition:e}:s}function y(t){if(t&&typeof t=="object"&&typeof t.routeId=="string"){let e="effectiveTemplateId"in t?t.effectiveTemplateId:"templateId"in t?t.templateId:void 0;return{routeId:t.routeId,...typeof e=="string"?{templateId:e}:{}}}throw new Error("SITE_EDIT_COMPOSITION_SESSION_REQUIRED: a composition selector is required")}function E(t){return JSON.stringify([t.routeId,t.templateId??null])}function _e(t){return t?JSON.stringify([t.key,t.instanceIndex??null,t.instanceCount??null]):""}function k(t){return JSON.stringify([t.routeId,t.effectiveTemplateId??null])}function V(t){return{routeId:t.routeId,...t.templateId?{effectiveTemplateId:t.templateId}:{}}}function _(t){if(t&&typeof t=="object"){let e=t;if(e.composition&&typeof e.composition=="object"){let n=e.composition;if(typeof n.routeId=="string")return{routeId:n.routeId,...typeof n.templateId=="string"?{templateId:n.templateId}:{}}}}}function we(t,e,n){let s=y(e==="execute"?_(n.request):n.composition),o={id:t,kind:e,composition:s};switch(e){case"initialize-session":case"get-document":case"get-history-status":case"get-style-context":case"get-source-tree":case"undo":case"redo":return{type:"request",payload:{...o,...n.mutationContext?{mutationContext:n.mutationContext}:{},...(e==="undo"||e==="redo")&&n.request?{request:n.request}:{}}};case"get-object-edit-context":return{type:"request",payload:{...o,key:String(n.key),...n.selectionRef?{selectionRef:n.selectionRef}:{}}};case"get-class-name-source":case"resolve-source-location":return{type:"request",payload:{...o,key:String(n.key)}};case"get-source-file":return{type:"request",payload:{...o,path:String(n.path)}};case"export-portable-block":case"export-portable-block-asset":return{type:"request",payload:{...o,request:n.request}};case"execute":case"get-operation-result":case"get-history-operation-result":return{type:"request",payload:{...o,request:{...n.request,composition:_(n.request)??s}}}}}export{ye as SITE_EDIT_BRIDGE_CONNECT_TIMEOUT,be as SITE_EDIT_BRIDGE_HEARTBEAT_TIMEOUT,U as SiteEditWebSocketClient,ve as createSiteEditBridge};