payload-live-preview 1.8.0 → 2.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/README.md +301 -93
  2. package/dist/adapters/astro/PreviewBoundary.astro +66 -0
  3. package/dist/adapters/astro/RichText.astro +6 -0
  4. package/dist/adapters/astro/index.d.ts +165 -134
  5. package/dist/adapters/astro/index.js +1 -1
  6. package/dist/adapters/astro/index.js.map +1 -1
  7. package/dist/adapters/astro/middleware-entry.d.ts +4 -9
  8. package/dist/adapters/astro/middleware-entry.js +1 -1
  9. package/dist/adapters/astro/middleware-entry.js.map +1 -1
  10. package/dist/adapters/nextjs/index.d.ts +13 -80
  11. package/dist/adapters/nextjs/index.js +1 -1
  12. package/dist/adapters/nextjs/index.js.map +1 -1
  13. package/dist/adapters/nuxt/index.d.ts +46 -106
  14. package/dist/adapters/nuxt/index.js +1 -1
  15. package/dist/adapters/nuxt/index.js.map +1 -1
  16. package/dist/adapters/sveltekit/index.d.ts +10 -75
  17. package/dist/adapters/sveltekit/index.js +1 -1
  18. package/dist/adapters/sveltekit/index.js.map +1 -1
  19. package/dist/client.cjs +2 -0
  20. package/dist/client.cjs.map +1 -0
  21. package/dist/client.d.cts +747 -0
  22. package/dist/client.d.ts +747 -0
  23. package/dist/client.js +2 -0
  24. package/dist/client.js.map +1 -0
  25. package/dist/codegen-astro.d.ts +5 -27
  26. package/dist/codegen-astro.js +1 -1
  27. package/dist/codegen-astro.js.map +1 -1
  28. package/dist/codegen-cli.d.ts +3 -16
  29. package/dist/codegen-cli.js +1 -1
  30. package/dist/codegen-cli.js.map +1 -1
  31. package/dist/codegen.cjs +1 -1
  32. package/dist/codegen.cjs.map +1 -1
  33. package/dist/codegen.d.cts +37 -124
  34. package/dist/codegen.d.ts +37 -124
  35. package/dist/codegen.js +1 -1
  36. package/dist/codegen.js.map +1 -1
  37. package/dist/core.cjs +1 -1
  38. package/dist/core.cjs.map +1 -1
  39. package/dist/core.d.cts +647 -1100
  40. package/dist/core.d.ts +647 -1100
  41. package/dist/core.js +1 -1
  42. package/dist/core.js.map +1 -1
  43. package/dist/doctor-cli.d.ts +3 -28
  44. package/dist/doctor-cli.js +1 -1
  45. package/dist/doctor-cli.js.map +1 -1
  46. package/dist/doctor.d.ts +16 -32
  47. package/dist/doctor.js +1 -1
  48. package/dist/doctor.js.map +1 -1
  49. package/dist/fragment.cjs +2 -0
  50. package/dist/fragment.cjs.map +1 -0
  51. package/dist/fragment.d.cts +333 -0
  52. package/dist/fragment.d.ts +333 -0
  53. package/dist/fragment.js +2 -0
  54. package/dist/fragment.js.map +1 -0
  55. package/dist/index.cjs +1 -1
  56. package/dist/index.cjs.map +1 -1
  57. package/dist/index.d.cts +885 -1531
  58. package/dist/index.d.ts +885 -1531
  59. package/dist/index.js +1 -1
  60. package/dist/index.js.map +1 -1
  61. package/dist/lexical.cjs +2 -0
  62. package/dist/lexical.cjs.map +1 -0
  63. package/dist/lexical.d.cts +90 -0
  64. package/dist/lexical.d.ts +90 -0
  65. package/dist/lexical.js +2 -0
  66. package/dist/lexical.js.map +1 -0
  67. package/dist/middleware-CEPsY1P7.d.ts +40 -0
  68. package/dist/migrate.d.ts +73 -0
  69. package/dist/migrate.js +2 -0
  70. package/dist/migrate.js.map +1 -0
  71. package/dist/options-CEzzfHJu.d.ts +197 -0
  72. package/dist/payload.cjs +1 -1
  73. package/dist/payload.cjs.map +1 -1
  74. package/dist/payload.d.cts +11 -80
  75. package/dist/payload.d.ts +11 -80
  76. package/dist/payload.js +1 -1
  77. package/dist/payload.js.map +1 -1
  78. package/dist/plugins.cjs +2 -0
  79. package/dist/plugins.cjs.map +1 -0
  80. package/dist/plugins.d.cts +509 -0
  81. package/dist/plugins.d.ts +509 -0
  82. package/dist/plugins.js +2 -0
  83. package/dist/plugins.js.map +1 -0
  84. package/dist/{probe-tMHdim5y.d.ts → probe-CYtvj_Lm.d.ts} +43 -77
  85. package/dist/server.cjs +2 -0
  86. package/dist/server.cjs.map +1 -0
  87. package/dist/server.d.cts +435 -0
  88. package/dist/server.d.ts +435 -0
  89. package/dist/server.js +2 -0
  90. package/dist/server.js.map +1 -0
  91. package/dist/structural.cjs +3 -0
  92. package/dist/structural.cjs.map +1 -0
  93. package/dist/structural.d.cts +243 -0
  94. package/dist/structural.d.ts +243 -0
  95. package/dist/structural.js +3 -0
  96. package/dist/structural.js.map +1 -0
  97. package/package.json +86 -7
  98. package/dist/middleware-DD4Hwomt.d.ts +0 -189
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["VERSION","FIELD_ATTRIBUTE","TYPE_ATTRIBUTE","TARGET_ATTRIBUTE_ATTRIBUTE","HREF_ATTRIBUTE","SRC_ATTRIBUTE","ALT_ATTRIBUTE","ARRAY_TEMPLATE_ATTRIBUTE","ARRAY_SEPARATOR_ATTRIBUTE","LOCALE_ATTRIBUTE","RICH_TEXT_ATTRIBUTE","HTML_ATTRIBUTE","ARRAY_ATTRIBUTE","STRUCTURAL_ATTRIBUTE","OWNER_ATTRIBUTE","BINDING_ATTRIBUTES","FIELD_SELECTOR","OWNER_SELECTOR","resolveBindingOwner","element","owner","closest","getAttribute","length","__name","VALID_FIELD_TYPES","Set","ElementCache","this","#entries","Map","#elementToEntry","WeakMap","#filter","constructor","options","filter","alwaysTrue","buildFromRoot","root","t0","performance","now","clear","elements","querySelectorAll","elementCount","add","fieldCount","size","durationMs","entry","#resolveBinding","previous","get","#replaceEntry","set","#removeEntry","#append","remove","next","fieldName","bucket","index","indexOf","delete","splice","getByElement","count","values","entries","has","push","explicit","fieldType","resolveFieldType","targetAttribute","hrefField","srcField","altField","arrayTemplate","arraySeparator","locale","explicitFieldType","hasAttribute","tagName","inputType","type","globalOwnerKey","slug","collectionOwnerKey","documentId","nonEmpty","value","messageOwnerKeys","identity","globalSlug","collectionSlug","collectionKey","isBindingInScope","keys","includes","readDocumentId","fields","id","Number","isFinite","String","ObserverManager","s","callbacks","mutationDebounceMs","intersectionRootMargin","start","previousGeneration","stop","generation","mutation","intersection","MutationObserver","mutations","#handleMutations","IntersectionObserver","#handleIntersection","rootMargin","threshold","observe","childList","subtree","attributes","attributeFilter","error","disconnect","observeElement","unobserveElement","unobserve","markVisible","visible","isVisible","timer","clearTimeout","#isCurrentGeneration","hasStructuralImpact","setTimeout","onStructuralChange","target","isIntersecting","onVisibilityChange","m","attributeName","nodeType","node","addedNodes","containsTrackedElement","removedNodes","querySelector","parseFieldSchema","raw","Array","isArray","out","parsed","parseFieldEntry","record","name","blocks","parseBlockSchema","result","LIBRARY_PROTOCOL_VERSION","CAPABILITY_REQUIREMENTS","basic","negotiateProtocol","theirs","sanitisedTheirs","Math","floor","negotiated","min","capabilities","flag","minVersion","Object","ours","hasCapability","negotiation","capability","observeThenableResult","then","Promise","resolve","catch","MessageBus","matcher","handlers","attach","window","committed","listener","event","#receive","origin","#reportInvalid","#resetValidationQueue","addEventListener","removeEventListener","detach","_target","advanceGeneration","sendReady","targets","origins","hasTargets","payload","ready","protocolVersion","postMessage","#matchesOrigin","data","isMessage","isObjectMessage","isLivePreview","isLivePreviewMessage","message","normalizeLivePreviewMessage","#dispatchUpdate","onDocumentEvent","isDocumentEvent","isDocumentEventMessage","#invokeHandler","hasUpdateData","isPlainObject","validator","messageRevision","revision","validateToken","#commitUpdate","verdict","pending","settled","approved","previewToken","#settleValidation","#drainValidationQueue","#dequeueValidation","onUpdate","reason","onInvalid","handler","args","expected","state","slice","v","optionalTypeOk","fieldSchemaJSON","x","optionalDocumentFieldOk","action","check","prototype","getPrototypeOf","NULL_AS_ABSENT_FIELDS","normalized","field","Reflect","deleteProperty","HeartbeatTimer","timeoutMs","onTimeout","kick","Date","handle","lastKickAt","ConnectionState","onChange","status","markConnected","transition","markConnecting","markDisconnected","isolateDiagnostic","diagnostic","noopDiagnostic","safeConsoleError","console","safeConsoleWarn","warn","safeConsoleDebug","debug","hasControlCharacter","character","codePoint","codePointAt","isSafeSlug","encodeURIComponent","isSafeId","DataMerger","serverURL","replace","route","apiRoute","startsWith","depth","fetchFn","log","canMerge","request","merge","attempt","controller","abort","isLatestAttempt","fetch","AbortController","endpoint","url","body","JSON","stringify","flattenLocales","response","method","credentials","headers","signal","isAborted","ok","merged","json","doc","destroy","inflight","aborted","SAFE_PROTOCOLS","DANGEROUS_PROTOCOL_PATTERN","RELATIVE_PATH","isSafeUrl","trimmed","trim","test","URL","protocol","isExternalHttpUrl","BLOCKED_ATTRIBUTES","URL_ATTRIBUTES","applyAttributeBinding","attribute","toLowerCase","removeAttribute","stringValue","setAttribute","noWriteCallbacks","WeakSet","markNoWriteCallback","callback","usesNoWriteOutcome","rendererUsesNoWriteOutcome","renderer","render","UpdateScheduler","apply","scheduleFrame","requestAnimationFrame","bind","globalThis","cb","cancelFrame","cancelAnimationFrame","debounceMs","visibilityGateThreshold","disableVisibilityGate","getCacheSize","onFlush","schedule","update","sameIdentity","existing","allFields","#armDebounce","acceptRevision","activeIdentity","compareIdentity","#cancelScheduledWork","#clearWork","cancelRevision","flushNow","#flush","notifyVisible","replay","#isCurrent","applied","#didApply","#statsFor","retarget","#retargetBuffer","flush","forget","pendingCount","replayCount","gateThreshold","gateActive","token","nextTimer","#requestFrame","completed","nextHandle","batchEntry","appliedFields","deferred","stats","buffer","debounceTimer","frameHandle","a","b","BLOCKED_KEYS","resolveFieldValue","path","preferLocale","localized","readOwn","direct","current","resolved","segment","split","object","key","hasOwnProperty","call","detectInitialLocale","fromHtml","readHtmlLang","fromNavigator","readNavigatorLanguage","document","lang","documentElement","navigator","language","ELEMENT_ID","isGerman","documentLeases","acquireDocumentLease","activeDocument","lease","clearLeaseMessage","A11yAnnouncer","targetDocument","documentLocale","mount","leasedElement","isConnected","ownerDocument","owned","getElementById","createElement","appendChild","announceConnected","say","announceDisconnected","announceUpdate","messageNode","parentNode","createTextNode","hasChildNodes","previousSibling","STRUCTURAL_TYPES","buildSchemaIndex","schemas","basePath","walk","schema","block","lookupSchema","fieldPath","wildcardPath","getId","item","getBlockType","blockType","diffArray","prev","every","diffById","diffByPosition","patches","prevIndexById","i","consumedFromPrev","to","kind","from","prevItem","shallowEqual","oldValue","is","aRec","bRec","aKeys","bKeys","MAP","text","textarea","richText","email","number","checkbox","date","select","radio","array","group","tabs","row","collapsible","relationship","upload","point","code","ui","payloadTypeToRenderer","READY_RETRY_DELAYS_MS","LivePreviewRuntime","d","l","emitter","renderers","resolveRenderer","transformValue","readyTargets","defaultSendReady","heartbeatTimeoutHook","onHeartbeatTimeout","a11y","createA11y","merger","dataMerge","cache","observers","#rebuildCache","scheduler","#applyUpdate","#onFlush","bus","originMatcher","msg","#handleUpdate","emit","timestamp","Error","context","connectionState","heartbeat","heartbeatMs","#onHeartbeatTimeout","scopeBindingsByOwner","lockedOrigin","isDocumentRoot","readyState","onReady","#startNow","#rollbackFailedStart","#reportError","once","observerRoot","readDocumentBody","#buildCacheAndObserve","#isRunning","emitWhile","delay","#sendReadyAfterStart","suspend","#releaseRuntimeResources","deferredStart","#runCleanup","cleanup","refreshCache","updateCount","inspect","active","fieldNames","owners","bindings","binding","version","started","trusted","locked","sort","revisions","accepted","superseded","absentFields","orphanFields","ownerScoped","visibilityGateActive","lastFlush","previousBindings","removed","#applyNegotiation","remoteVersion","transaction","schemaIndex","cancelled","#processUpdate","#resolveIncomingFields","listenerCount","cancel","#scheduleAllFields","isCurrent","ownerKeys","#ownerKeysForUpdate","transformedValue","#transformForBinding","#diagnoseOrphanFields","#ownsAnyBinding","#hasAddressableBinding","some","localisedBindingNames","rawName","SYSTEM_FIELD_NAMES","isLiveBindableScalar","baseName","stripLocaleSuffix","originalValue","transformed","returnedThenable","TypeError","err","#warnOnDeferredWrites","sameRevision","schemaEntry","resolvedType","resolveRuntimeFieldType","looksLikeLexicalRoot","emitElementUpdate","readElementSnapshot","invokeRenderer","previousValue","nextValue","updatedCount","wasConnected","#isDisconnectedWithoutActiveUpdate","cause","schemaType","mapped","enableA11y","a11yLocale","children","parent","opener","Window","suffix","endsWith","src","textContent","importMetaEnvCache","EventEmitter","#regular","#once","on","#register","off","#remove","#emitSequential","shouldContinue","eligible","regular","#invoke","snapshot","removeAllListeners","eventNames","names","label","isInIframe","self","top","isInPopup","isInPreviewContext","isDevMode","nodeEnv","readNodeEnv","importMetaDev","readImportMetaDev","host","location","hostname","getEnvVar","process","env","meta","tryReadImportMetaEnv","NODE_ENV","dev","DEV","__INLINE_RUNTIME_BUILD__","Function","LOCALHOST_PATTERN","VALID_ORIGIN_PATTERN","ENV_VAR_NAMES","OriginDetector","#state","referrerOrigin","additionalOrigins","normalised","normaliseOrigin","envName","enableReferrerDetection","referrer","allowLocalhost","enableLocalhostMatching","forceDevMode","matches","lockOrigin","unlockOrigin","enumerate","port","LOCALHOST_HANDSHAKE_PORTS","referrerWasAvailable","isProductionUnconfigured","isReferrerOnlyTrust","noopDisposer","isPluginDisposer","documentOverride","ResourceScope","#pluginName","#log","#resources","pluginName","assertOpen","own","#track","acquire","finalize","disposed","stage","resource","dispose","#activate","#dispose","commit","close","reverse","ScopedPluginEvents","#events","#scope","#subscriptions","events","scope","super","#subscribe","untypedHandler","subscription","callerEligible","find","subscriptionActive","wrapped","async","PluginManager","#config","#registerRenderer","#onTransformError","#plugins","#initializing","#teardowns","#destroying","#transforms","#mutationQueue","#hookDepth","config","registerFieldRenderer","onTransformError","reportError","register","plugin","#registerNow","#enqueue","unregister","#unregisterNow","destroyAll","#destroyAllNow","applyTransforms","registrations","registration","transform","list","#createContext","initializing","#runHook","init","registerTransform","registerCleanup","getConfig","existingTeardown","teardown","#destroyPlugin","hook","operation","RendererRegistry","#base","#active","#layers","base","layer","stack","wasTop","previousRenderer","at","ALLOWED_TAGS","REMOVE_COMPLETELY","ATTR_GLOBAL","ATTR_BY_TAG","img","picture","source","audio","video","time","abbr","q","blockquote","table","th","td","col","colgroup","ol","li","pre","SanitizerEnvironmentError","resolvePolicy","attrMap","tag","attrs","allowedTags","attrByTag","allowed","additionalAllowedTags","additionalAllowedAttributes","attr","setSanitizerDocument","sanitizeHtml","html","resolveDocument","policy","template","innerHTML","sanitizeFragment","content","hasSanitizerDocument","child","childNodes","sanitizeElement","firstChild","insertBefore","sanitizeAttributes","hardenAnchor","tagAttrs","isSafeSrcset","candidates","candidate","descriptorStart","search","anchor","href","registry","lookup","ALIGNMENT_NUMERIC","ALIGNMENT_STRING","resolveAlignment","fmt","format","resolveIndent","indent","dirAttribute","direction","styleAttribute","align","styles","join","HTML_ESCAPES","freeze","HTML_ESCAPE_PATTERN","escapeHtml","char","escapeCssUrl","ATTR_ESCAPES","ATTR_ESCAPE_PATTERN","escapeHtmlAttribute","escapeAndLinebreak","textRenderer","paragraphRenderer","ctx","renderChildren","VALID_TAGS","headingRenderer","tagRaw","listRenderer","listType","startAttr","checkAttr","listItemRenderer","checked","valueAttr","linkRenderer","targetAttr","buildOptionalAttrs","titleAttr","title","safeTarget","quoteRenderer","codeRenderer","sanitizeLangClass","extractText","codeHighlightRenderer","highlightType","linebreakRenderer","horizontalRuleRenderer","tabRenderer","uploadRenderer","readUploadValue","mime","mimeType","renderVideo","renderAudio","renderImage","renderFallbackLink","alt","width","height","filename","relationshipRenderer","relationTo","readValue","safeLabel","pickLabel","relAttr","registerBlockRenderer","lookupBlockRenderer","blockRenderer","readFields","blockTypeRaw","sanitizeIdent","custom","RENDER_CONTEXT","isLexicalContent","lexicalToHtml","sanitize","lexicalToPlainText","map","extractPlainText","renderNode","createTextRenderer","warnedElements","toPlainString","hasStructuredChildren","warnOnce","firstElementChild","safeStringify","textareaRenderer","richTextRenderer","htmlRenderer","urlRenderer","hrefSource","imageRenderer","media","readMedia","pickUrl","pickAlt","style","backgroundImage","sibling","siblingMedia","collectLabels","rel","selectRenderer","checkboxRenderer","NUMBER_CACHE","DATE_CACHE","getNumberFormat","buildKey","cached","formatter","Intl","NumberFormat","trimToLimit","getDateTimeFormat","DateTimeFormat","localePart","serialised","stableStringify","parts","inner","oldest","dateRenderer","iso","isValid","isNaN","getTime","toISOString","formatDate","toIsoForInput","dateStyle","timeStyle","numberRenderer","num","PLACEHOLDER_PATTERN","hasOwn","interpolateArrayTemplate","placeholder","arrayRenderer","renderTemplate","separator","items","interpolate","KEY_ATTRIBUTE","NESTED_KEY_ATTRIBUTE","NESTED_TEMPLATE_ATTRIBUTE","createStructuralStore","applyStructuralPatches","container","nextItems","store","forceRender","plan","prepareStructuralPlan","commitStructuralPlan","prepareReconciliation","createPatchPlan","claimed","mutated","live","rendered","nestedSlots","nested","synchronizeAttributes","replaceWith","before","memory","getMemory","rememberItem","initialChildren","keyedChildren","indexByAttribute","reserved","readKey","takeIndexedElement","replaces","renders","renderItem","prepareNestedSlots","patch","oldItem","newItem","oldSlotsByKey","findDirectNestedSlots","itemKey","prevValue","plans","newSlot","oldSlot","nextTemplate","liveSlot","previousTemplate","nextNested","readNestedArray","resolvedNext","templateChanged","slot","ancestor","parentElement","indexed","pop","safe","fillTemplate","first","createStructuralArrayRenderer","states","warnedContainers","warnMissingTemplate","previousState","domSnapshot","readDomKeySnapshot","valuesFromDomSnapshot","needsForcedRender","sameDomKeySnapshot","position","__payloadDomPosition","builtinRenderers","buildBuiltinRenderers","defaults","registerBuiltinRenderer","STATELESS_BUILTIN","LivePreviewClient","#emitter","#detector","#rendererRegistry","#runtime","#started","#destroyed","#destroyPromise","allowedOrigins","disableReferrerDetection","disableLocalhostMatching","mergeDepth","mergeFetch","e","autoStart","resume","resolveDestroy","rejectDestroy","inFlight","reject","finally","use","unuse","plugins","destroyed","initLivePreview","client","bindNavigationLifecycle","windowTarget","documentTarget","softEvents","softNavigationEvents","onPageHide","onPageShow","persisted","onSoftNavigation","unbound","DIAGNOSTIC_CODES","NoTrustedOrigin","ReferrerOnlyTrust","OrphanField","UnattributableUpdate","VisibilityGateDeferred","UnsafeAttributeWrite","TextTargetHasChildren","MissingArrayTemplate","MessageRejected","TokenRejected","HandlerThrew","TransformThrew","RendererThrew","StartupFailed","ReadyFailed","AuditRuntimeMissing","AuditNoFrameAncestors","AuditFrameOptionsBlocks","AuditBindingsExposed","AuditGateThresholdExceeded","AuditUnownedBindings","AuditNoBindings","AuditNotAPage","RUNTIME_SOURCE","RUNTIME_BUILD_INFO","generatedAt","generateInlineScript","buildConfigLiteral","compactConfig","wrapWithScriptTag","nonce","escapeNonce","runtimeBuildInfo","RangeError","cryptoOverride","CSP_ASCII_WHITESPACE","CSP_EDGE_ASCII_WHITESPACE","asciiLowercase","setCspCrypto","crypto","generateCspNonce","bytes","isInteger","resolveCrypto","Uint8Array","getRandomValues","base64UrlEncode","fromGlobal","binary","byte","fromCharCode","btoa","Buffer","toString","replaceAll","buildFrameAncestors","allowNone","seen","buildScriptSrcWithNonce","extra","strictDynamic","mergeCspHeader","additions","directives","part","whitespaceIndex","rawAddition","addition","mode","withoutNone","DEFAULT_QUERY_PARAMS","isPreviewRequest","signals","queryParams","checkFetchDest","param","searchParams","adminOrigins","referer","refererOrigin","adminOrigin","fetchPreviewDocument","params","baseParams","requestJson","apiBase","collection","where","appendWhere","docs","fetchPreviewGlobal","global","URLSearchParams","draft","nextPath","seg","Accept","STYLE_ID","styleLeases","highlightLeases","highlightPlugin","prefersReducedMotion","matchMedia","releaseStyle","acquireStyle","duration","activeTimers","timerCleanups","releaseHighlight","acquireHighlight","disposeTimer","HTMLStyleElement","pluginOwned","head","acquiredLease","pluginAdded","classList","contains","debugPlugin","toFixed","createAnalyticsPlugin","totalElements","totalDurationMs","getStats","averageDurationMs","SCROLL_KEY","saveScrollPosition","sessionStorage","setItem","scrollX","y","scrollY","restoreScrollPosition","getItem","removeItem","saved","parse","scrollTo","reloadPreservingScroll","reload","documentSavePlugin","strategy","controllers","runFetch","runRevalidate","isActive","revalidateUrl","revalidateHeaders","onRevalidateFailure","buildAttributes","bindByPath","picker","recordPath","richtext","proxy","Proxy","prop","SUPPRESSED","createPreviewBindings","authorized","bindOptions","Do","F","se","Ae","G","Ce","Le","Pe","Io","ft","ci","fi","vi","Ti","bi","D","wi","h","R","Go","zo","Fo","_i","yi","No","W","V","X","qe","ye","L","Wo","p","Re","z","hi","le","kn","oi","_o","di","nn","Uo"],"sources":["../src/version.ts","../package.json","../src/core/cache.ts","../src/core/binding-owner.ts","../src/core/observers.ts","../src/schema/parser.ts","../src/core/protocol-version.ts","../src/core/thenable.ts","../src/core/message-bus.ts","../src/core/state.ts","../src/core/diagnostics.ts","../src/core/data-merger.ts","../src/security/url-validator.ts","../src/core/attribute-binding.ts","../src/core/internal-outcome.ts","../src/core/update-scheduler.ts","../src/core/field-value.ts","../src/detection/locale.ts","../src/core/a11y.ts","../src/schema/walker.ts","../src/schema/diff.ts","../src/schema/field-type-map.ts","../src/core/lifecycle.ts","../src/events/emitter.ts","../src/detection/environment.ts","../src/detection/origin.ts","../src/plugins/manager.ts","../src/security/sanitizer.ts","../src/plugins/renderer-registry.ts","../src/lexical/registry.ts","../src/lexical/utils.ts","../src/security/escape.ts","../src/lexical/types.ts","../src/lexical/nodes/text.ts","../src/lexical/nodes/paragraph.ts","../src/lexical/nodes/heading.ts","../src/lexical/nodes/list.ts","../src/lexical/nodes/link.ts","../src/lexical/nodes/quote.ts","../src/lexical/nodes/code.ts","../src/lexical/nodes/linebreak.ts","../src/lexical/nodes/upload.ts","../src/lexical/nodes/relationship.ts","../src/lexical/blocks/registry.ts","../src/lexical/nodes/block.ts","../src/lexical/render.ts","../src/field-types/text.ts","../src/field-types/utils.ts","../src/field-types/textarea.ts","../src/field-types/rich-text.ts","../src/field-types/html.ts","../src/field-types/url.ts","../src/field-types/image.ts","../src/field-types/upload.ts","../src/field-types/relationship.ts","../src/field-types/select.ts","../src/field-types/checkbox.ts","../src/core/intl-cache.ts","../src/field-types/date.ts","../src/field-types/number.ts","../src/core/array-template.ts","../src/field-types/array.ts","../src/core/structural-applier.ts","../src/field-types/structural-array.ts","../src/field-types/registry.ts","../src/field-types/index.ts","../src/client/index.ts","../src/core/navigation-lifecycle.ts","../src/core/diagnostic-codes.ts","../src/inline/runtime.generated.ts","../src/inline/generator.ts","../src/security/csp.ts","../src/adapters/shared/preview-request.ts","../src/preview-fetch.ts","../src/plugins/built-in/highlight.ts","../src/plugins/built-in/debug.ts","../src/plugins/built-in/analytics.ts","../src/plugins/built-in/document-save.ts","../src/dsl/bind.ts","../src/dsl/preview-bindings.ts"],"sourcesContent":["/**\n * Single source of truth for the library version.\n *\n * Both the npm package surface (`src/index.ts`, `src/core-entry.ts`)\n * and the inline runtime (`src/core/runtime.ts`, which gets bundled by\n * esbuild and embedded into `runtime.generated.ts`) read the version\n * from here so they never drift.\n *\n * Imports `package.json` directly — tsc, tsup, and esbuild all inline\n * the value at build time when `resolveJsonModule` is enabled.\n *\n * @module @/version\n */\n\nimport pkg from '../package.json' with { type: 'json' };\n\nexport const VERSION: string = pkg.version;\n","{\n \"name\": \"payload-live-preview\",\n \"version\": \"1.8.0\",\n \"description\": \"Live preview for Payload CMS in Astro and any SSR/static frontend (SvelteKit, Nuxt, Next.js, plain HTML). Patches the DOM live, no rebuild.\",\n \"author\": \"relative23\",\n \"license\": \"MIT\",\n \"type\": \"module\",\n \"packageManager\": \"npm@11.16.0\",\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n },\n \"./core\": {\n \"import\": {\n \"types\": \"./dist/core.d.ts\",\n \"default\": \"./dist/core.js\"\n },\n \"require\": {\n \"types\": \"./dist/core.d.cts\",\n \"default\": \"./dist/core.cjs\"\n }\n },\n \"./astro\": {\n \"import\": {\n \"types\": \"./dist/adapters/astro/index.d.ts\",\n \"default\": \"./dist/adapters/astro/index.js\"\n }\n },\n \"./nextjs\": {\n \"import\": {\n \"types\": \"./dist/adapters/nextjs/index.d.ts\",\n \"default\": \"./dist/adapters/nextjs/index.js\"\n }\n },\n \"./sveltekit\": {\n \"import\": {\n \"types\": \"./dist/adapters/sveltekit/index.d.ts\",\n \"default\": \"./dist/adapters/sveltekit/index.js\"\n }\n },\n \"./nuxt\": {\n \"import\": {\n \"types\": \"./dist/adapters/nuxt/index.d.ts\",\n \"default\": \"./dist/adapters/nuxt/index.js\"\n }\n },\n \"./codegen\": {\n \"import\": {\n \"types\": \"./dist/codegen.d.ts\",\n \"default\": \"./dist/codegen.js\"\n },\n \"require\": {\n \"types\": \"./dist/codegen.d.cts\",\n \"default\": \"./dist/codegen.cjs\"\n }\n },\n \"./codegen/astro\": {\n \"import\": {\n \"types\": \"./dist/codegen-astro.d.ts\",\n \"default\": \"./dist/codegen-astro.js\"\n }\n },\n \"./doctor\": {\n \"import\": {\n \"types\": \"./dist/doctor.d.ts\",\n \"default\": \"./dist/doctor.js\"\n }\n },\n \"./payload\": {\n \"import\": {\n \"types\": \"./dist/payload.d.ts\",\n \"default\": \"./dist/payload.js\"\n },\n \"require\": {\n \"types\": \"./dist/payload.d.cts\",\n \"default\": \"./dist/payload.cjs\"\n }\n },\n \"./astro/RichText.astro\": \"./dist/adapters/astro/RichText.astro\",\n \"./astro/middleware-entry\": {\n \"import\": {\n \"types\": \"./dist/adapters/astro/middleware-entry.d.ts\",\n \"default\": \"./dist/adapters/astro/middleware-entry.js\"\n }\n }\n },\n \"bin\": {\n \"pll-codegen\": \"./dist/codegen-cli.js\",\n \"pll\": \"./dist/doctor-cli.js\"\n },\n \"files\": [\n \"dist\",\n \"README.md\",\n \"LICENSE\"\n ],\n \"sideEffects\": false,\n \"scripts\": {\n \"build:runtime\": \"tsx scripts/build-runtime.ts\",\n \"build\": \"npm run build:runtime && tsx scripts/build-dist.ts && npm run build:assets && npm run test:bundle\",\n \"build:assets\": \"node -e \\\"require('node:fs').copyFileSync('src/adapters/astro/RichText.astro','dist/adapters/astro/RichText.astro')\\\"\",\n \"dev\": \"tsup --watch\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"test:unit\": \"vitest run tests/unit\",\n \"test:integration\": \"vitest run tests/integration\",\n \"test:e2e\": \"playwright test\",\n \"test:e2e:real-payload\": \"playwright test --config playwright.real-payload.config.ts\",\n \"test:a11y\": \"playwright test tests/e2e/specs/accessibility.spec.ts\",\n \"test:soak\": \"playwright test --config playwright.soak.config.ts\",\n \"test:bench\": \"vitest bench tests/benchmarks\",\n \"test:bench:codspeed\": \"vitest bench --run --config vitest.bench.config.ts\",\n \"test:bundle\": \"tsx scripts/check-bundle-size.ts\",\n \"test:package\": \"tsx scripts/check-package.ts\",\n \"test:coverage\": \"vitest run --coverage\",\n \"test:coverage:diff\": \"tsx scripts/coverage-policy.ts\",\n \"test:policy\": \"tsx scripts/test-policy.ts\",\n \"test:architecture\": \"tsx scripts/architecture-policy.ts && tsx scripts/quality-workflow-policy.ts && knip --no-progress --treat-config-hints-as-errors\",\n \"test:property\": \"vitest run tests/unit/property\",\n \"test:mutation\": \"stryker run stryker.config.js\",\n \"test:mutation:policy:pr\": \"tsx scripts/mutation-policy.ts --policy quality/mutation-policy-pr.json --report test-results/stryker-pr.json\",\n \"test:mutation:policy\": \"tsx scripts/mutation-policy.ts\",\n \"test:leak\": \"node --expose-gc --import tsx scripts/leak-soak.ts\",\n \"test:leak:quick\": \"node --expose-gc --import tsx scripts/leak-soak.ts --quick\",\n \"api:update\": \"npm run build && tsx scripts/check-package.ts --update-api-reports\",\n \"typecheck\": \"tsc --noEmit\",\n \"lint\": \"eslint .\",\n \"lint:fix\": \"eslint . --fix\",\n \"format\": \"prettier --write \\\"src/**/*.ts\\\" \\\"tests/**/*.ts\\\" \\\"scripts/**/*.ts\\\" \\\"*.{js,cjs,mjs,ts,json,jsonc,yml,yaml,md}\\\" \\\"quality/**/*.json\\\" \\\"docs/**/*.md\\\" \\\"type-tests/**/*.md\\\" \\\".prettierrc.json\\\" \\\".changeset/*.{json,md}\\\" \\\".github/**/*.{yml,yaml,json}\\\" \\\"examples/**/*.{ts,tsx,js,cjs,mjs,json}\\\" && prettier --write \\\"type-tests/packed/*.fixture\\\" --parser typescript\",\n \"format:check\": \"prettier --check \\\"src/**/*.ts\\\" \\\"tests/**/*.ts\\\" \\\"scripts/**/*.ts\\\" \\\"*.{js,cjs,mjs,ts,json,jsonc,yml,yaml,md}\\\" \\\"quality/**/*.json\\\" \\\"docs/**/*.md\\\" \\\"type-tests/**/*.md\\\" \\\".prettierrc.json\\\" \\\".changeset/*.{json,md}\\\" \\\".github/**/*.{yml,yaml,json}\\\" \\\"examples/**/*.{ts,tsx,js,cjs,mjs,json}\\\" && prettier --check \\\"type-tests/packed/*.fixture\\\" --parser typescript\",\n \"check\": \"npm run typecheck && npm run lint && npm run test:policy && npm run test:architecture && npm run test\",\n \"prepublishOnly\": \"npm run build && npm run check && npm run format:check && npm run test:package\",\n \"changeset\": \"changeset\",\n \"version\": \"changeset version && tsx scripts/sync-lockfile-metadata.ts\",\n \"release\": \"tsx scripts/publish-artifact.ts\"\n },\n \"devDependencies\": {\n \"@arethetypeswrong/cli\": \"^0.18.5\",\n \"@axe-core/playwright\": \"^4.13.0\",\n \"@changesets/cli\": \"^2.31.1\",\n \"@codspeed/vitest-plugin\": \"^5.7.1\",\n \"@eslint/js\": \"^10.0.1\",\n \"@fast-check/vitest\": \"^0.4.1\",\n \"@microsoft/api-extractor\": \"^7.58.12\",\n \"@playwright/test\": \"^1.62.1\",\n \"@stryker-mutator/core\": \"^9.6.1\",\n \"@stryker-mutator/vitest-runner\": \"^9.6.1\",\n \"@types/jsdom\": \"^30.0.0\",\n \"@types/node\": \"^22.20.1\",\n \"@vitest/coverage-v8\": \"^4.1.10\",\n \"esbuild\": \"^0.28.2\",\n \"eslint\": \"^10.8.1\",\n \"fast-check\": \"^4.9.0\",\n \"globals\": \"^17.11.0\",\n \"jsdom\": \"^29.1.1\",\n \"knip\": \"^6.32.2\",\n \"prettier\": \"^3.9.6\",\n \"publint\": \"^0.3.23\",\n \"terser\": \"^5.46.1\",\n \"ts-morph\": \"^28.0.0\",\n \"tsup\": \"^8.5.1\",\n \"tsx\": \"^4.23.12\",\n \"typescript\": \"^5.9.3\",\n \"typescript-eslint\": \"^8.67.0\",\n \"vitest\": \"^4.1.10\"\n },\n \"overrides\": {\n \"qs\": \"6.15.3\",\n \"tsup\": {\n \"esbuild\": \"0.28.2\"\n }\n },\n \"allowScripts\": {\n \"esbuild@0.28.2\": true,\n \"fsevents@2.3.2\": false,\n \"fsevents@2.3.3\": false\n },\n \"keywords\": [\n \"astro\",\n \"astro-payload\",\n \"astro-cms\",\n \"astro-integration\",\n \"astro-live-preview\",\n \"payload\",\n \"payload-cms\",\n \"payload-live-preview\",\n \"payload-plugin\",\n \"live-preview\",\n \"preview\",\n \"cms\",\n \"headless\",\n \"headless-cms\",\n \"lexical\",\n \"sveltekit\",\n \"nuxt\",\n \"nextjs\",\n \"ssr\",\n \"framework-agnostic\"\n ],\n \"peerDependencies\": {\n \"astro\": \">=4.0.0 <8.0.0\",\n \"ts-morph\": \"^28.0.0\"\n },\n \"peerDependenciesMeta\": {\n \"astro\": {\n \"optional\": true\n },\n \"ts-morph\": {\n \"optional\": true\n }\n },\n \"engines\": {\n \"node\": \">=20.19.0\"\n },\n \"publishConfig\": {\n \"access\": \"public\",\n \"provenance\": true\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/relative23/payload-live-preview.git\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/relative23/payload-live-preview/issues\"\n },\n \"homepage\": \"https://github.com/relative23/payload-live-preview#readme\"\n}\n","/**\n * Element cache.\n *\n * Stores the mapping from Payload field name to one-or-more cached\n * DOM bindings. Building the cache once at init (and rebuilding it\n * via MutationObserver) is the foundation of update-time performance:\n * an update walks the cache, not the entire DOM.\n *\n * Cache lookup is O(1) by field name; cache iteration is O(n) over\n * the bound elements only.\n *\n * Notes:\n * - Field types are inferred from element attributes when not given\n * explicitly. The resolver lives here so both runtime and tests\n * share the same logic.\n * - The cache holds *direct references* to elements — that is fine\n * for normal lifecycle because we tear down on `destroy()`. We do\n * not use WeakRefs because we need stable iteration order during\n * updates.\n *\n * @module @core/cache\n */\n\nimport type { CachedElement, ElementPredicate, FieldType } from './types';\n\nexport const FIELD_ATTRIBUTE = 'data-payload-field';\nexport const TYPE_ATTRIBUTE = 'data-payload-type';\nexport const TARGET_ATTRIBUTE_ATTRIBUTE = 'data-payload-attribute';\nexport const HREF_ATTRIBUTE = 'data-payload-href';\nexport const SRC_ATTRIBUTE = 'data-payload-src';\nexport const ALT_ATTRIBUTE = 'data-payload-alt';\nexport const ARRAY_TEMPLATE_ATTRIBUTE = 'data-payload-array-template';\nexport const ARRAY_SEPARATOR_ATTRIBUTE = 'data-payload-array-separator';\nexport const LOCALE_ATTRIBUTE = 'data-payload-locale';\nexport const RICH_TEXT_ATTRIBUTE = 'data-payload-richtext';\nexport const HTML_ATTRIBUTE = 'data-payload-html';\nexport const ARRAY_ATTRIBUTE = 'data-payload-array';\nexport const STRUCTURAL_ATTRIBUTE = 'data-payload-structural';\nexport const OWNER_ATTRIBUTE = 'data-payload-owner';\nexport const INPUT_TYPE_ATTRIBUTE = 'type';\n\n/**\n * Attributes whose values are captured in a {@link CachedElement} snapshot.\n *\n * Mutation observation consumes this list directly. Keep the cache resolver\n * and observer filter coupled here so adding binding metadata cannot leave\n * already-mounted elements with stale cached values.\n */\nexport const BINDING_ATTRIBUTES: readonly string[] = [\n FIELD_ATTRIBUTE,\n TYPE_ATTRIBUTE,\n TARGET_ATTRIBUTE_ATTRIBUTE,\n HREF_ATTRIBUTE,\n SRC_ATTRIBUTE,\n ALT_ATTRIBUTE,\n ARRAY_TEMPLATE_ATTRIBUTE,\n ARRAY_SEPARATOR_ATTRIBUTE,\n LOCALE_ATTRIBUTE,\n RICH_TEXT_ATTRIBUTE,\n HTML_ATTRIBUTE,\n ARRAY_ATTRIBUTE,\n STRUCTURAL_ATTRIBUTE,\n OWNER_ATTRIBUTE,\n INPUT_TYPE_ATTRIBUTE,\n];\n\nconst FIELD_SELECTOR = `[${FIELD_ATTRIBUTE}]`;\nconst OWNER_SELECTOR = `[${OWNER_ATTRIBUTE}]`;\n\n/**\n * Resolve the document a binding belongs to from its nearest marked ancestor,\n * the element itself included.\n *\n * Nearest-ancestor resolution lets a shell component own a whole subtree\n * without repeating the marker on every safe text child, and lets a nested\n * document (a card inside a page) override the owner it inherits.\n */\nexport function resolveBindingOwner(element: Element): string | undefined {\n const owner = element.closest(OWNER_SELECTOR)?.getAttribute(OWNER_ATTRIBUTE);\n return owner === null || owner === undefined || owner.length === 0 ? undefined : owner;\n}\n\nconst VALID_FIELD_TYPES: ReadonlySet<FieldType> = new Set<FieldType>([\n 'text',\n 'textarea',\n 'richText',\n 'email',\n 'number',\n 'checkbox',\n 'date',\n 'select',\n 'radio',\n 'array',\n 'blocks',\n 'group',\n 'tabs',\n 'row',\n 'collapsible',\n 'relationship',\n 'upload',\n 'point',\n 'json',\n 'code',\n 'ui',\n 'html',\n 'url',\n 'image',\n 'structural-array',\n]);\n\n/**\n * Statistics produced after each cache rebuild.\n */\nexport interface CacheBuildStats {\n readonly elementCount: number;\n readonly fieldCount: number;\n readonly durationMs: number;\n}\n\nexport interface ElementCacheOptions {\n /** Predicate restricting which elements are accepted. Defaults to \"accept all\". */\n readonly filter?: ElementPredicate;\n}\n\n/**\n * Element cache built from `data-payload-field` annotations.\n *\n * Multiple elements can share the same field name; iteration order\n * within a field is insertion order, mirroring DOM order when built\n * via `buildFromRoot()`.\n */\nexport class ElementCache {\n readonly #entries = new Map<string, CachedElement[]>();\n #elementToEntry = new WeakMap<Element, CachedElement>();\n readonly #filter: ElementPredicate;\n\n constructor(options: ElementCacheOptions = {}) {\n this.#filter = options.filter ?? alwaysTrue;\n }\n\n /**\n * Rebuild the cache from `root`'s descendants. Pre-existing entries\n * are discarded. Returns build statistics so callers can emit\n * cache-refresh events with the durations populated.\n */\n buildFromRoot(root: ParentNode): CacheBuildStats {\n const t0 = performance.now();\n this.clear();\n\n const elements = root.querySelectorAll(FIELD_SELECTOR);\n let elementCount = 0;\n for (const element of elements) {\n if (this.add(element) !== undefined) elementCount += 1;\n }\n\n return {\n elementCount,\n fieldCount: this.#entries.size,\n durationMs: performance.now() - t0,\n };\n }\n\n /**\n * Insert or replace a single element's binding, returning the new entry.\n *\n * The element identity is unique in the cache. Re-adding it refreshes its\n * complete metadata snapshot without duplicating the binding. If its new\n * state is filtered or invalid, any previous binding is removed.\n */\n add(element: Element): CachedElement | undefined {\n // Resolve first so a throwing consumer filter cannot partially mutate a\n // previously valid registration. Once resolved, replacement is one\n // synchronous operation with no externally observable intermediate state.\n const entry = this.#filter(element) ? this.#resolveBinding(element) : undefined;\n const previous = this.#elementToEntry.get(element);\n\n if (entry === undefined) {\n if (previous !== undefined) this.#removeEntry(element, previous);\n return undefined;\n }\n\n if (previous !== undefined && this.#replaceEntry(previous, entry)) {\n this.#elementToEntry.set(element, entry);\n return entry;\n }\n\n if (previous !== undefined) this.#removeEntry(element, previous);\n this.#append(entry);\n this.#elementToEntry.set(element, entry);\n return entry;\n }\n\n /**\n * Remove the entry bound to `element`, if any. Returns `true` when a\n * binding was actually removed.\n */\n remove(element: Element): boolean {\n const entry = this.#elementToEntry.get(element);\n if (!entry) return false;\n return this.#removeEntry(element, entry);\n }\n\n /** Replace in place when the field bucket is unchanged, preserving order. */\n #replaceEntry(previous: CachedElement, next: CachedElement): boolean {\n if (previous.fieldName !== next.fieldName) return false;\n const bucket = this.#entries.get(previous.fieldName);\n if (!bucket) return false;\n const index = bucket.indexOf(previous);\n if (index < 0) return false;\n bucket[index] = next;\n return true;\n }\n\n #removeEntry(element: Element, entry: CachedElement): boolean {\n const bucket = this.#entries.get(entry.fieldName);\n if (!bucket) {\n this.#elementToEntry.delete(element);\n return false;\n }\n const index = bucket.indexOf(entry);\n if (index < 0) {\n this.#elementToEntry.delete(element);\n return false;\n }\n bucket.splice(index, 1);\n if (bucket.length === 0) this.#entries.delete(entry.fieldName);\n this.#elementToEntry.delete(element);\n return true;\n }\n\n /** Returns the cached bindings for `fieldName`, or `undefined`. */\n get(fieldName: string): readonly CachedElement[] | undefined {\n return this.#entries.get(fieldName);\n }\n\n /** Returns the cache entry for `element`, or `undefined`. */\n getByElement(element: Element): CachedElement | undefined {\n return this.#elementToEntry.get(element);\n }\n\n /** Number of distinct field names currently cached. */\n get fieldCount(): number {\n return this.#entries.size;\n }\n\n /** Total number of cached element bindings. */\n get elementCount(): number {\n let count = 0;\n for (const bucket of this.#entries.values()) count += bucket.length;\n return count;\n }\n\n /** Iterate `[fieldName, bindings]` pairs. */\n entries(): IterableIterator<[string, readonly CachedElement[]]> {\n return this.#entries.entries() as IterableIterator<[string, readonly CachedElement[]]>;\n }\n\n /** Iterate every cached binding. */\n *values(): IterableIterator<CachedElement> {\n for (const bucket of this.#entries.values()) yield* bucket;\n }\n\n /** Test whether `element` is registered with the cache. */\n has(element: Element): boolean {\n return this.#elementToEntry.has(element);\n }\n\n /** Remove every entry. */\n clear(): void {\n this.#entries.clear();\n // WeakMap has no clear operation. Replacing it is required so callers\n // retaining a detached Element cannot observe stale cache membership.\n this.#elementToEntry = new WeakMap<Element, CachedElement>();\n }\n\n #append(entry: CachedElement): void {\n const bucket = this.#entries.get(entry.fieldName);\n if (bucket) {\n bucket.push(entry);\n return;\n }\n this.#entries.set(entry.fieldName, [entry]);\n }\n\n #resolveBinding(element: Element): CachedElement | undefined {\n const fieldName = element.getAttribute(FIELD_ATTRIBUTE);\n if (fieldName === null || fieldName.length === 0) return undefined;\n const explicit = element.getAttribute(TYPE_ATTRIBUTE);\n const fieldType = resolveFieldType(element);\n const targetAttribute = element.getAttribute(TARGET_ATTRIBUTE_ATTRIBUTE);\n const hrefField = element.getAttribute(HREF_ATTRIBUTE);\n const srcField = element.getAttribute(SRC_ATTRIBUTE);\n const altField = element.getAttribute(ALT_ATTRIBUTE);\n const arrayTemplate = element.getAttribute(ARRAY_TEMPLATE_ATTRIBUTE);\n const arraySeparator = element.getAttribute(ARRAY_SEPARATOR_ATTRIBUTE);\n const locale = element.getAttribute(LOCALE_ATTRIBUTE);\n const owner = resolveBindingOwner(element);\n\n const entry: CachedElement = {\n element,\n fieldName,\n fieldType,\n explicitFieldType: explicit !== null && VALID_FIELD_TYPES.has(explicit as FieldType),\n ...(targetAttribute !== null && targetAttribute.length > 0 ? { targetAttribute } : {}),\n ...(hrefField !== null && hrefField.length > 0 ? { hrefField } : {}),\n ...(srcField !== null && srcField.length > 0 ? { srcField } : {}),\n ...(altField !== null && altField.length > 0 ? { altField } : {}),\n ...(arrayTemplate !== null ? { arrayTemplate } : {}),\n ...(arraySeparator !== null ? { arraySeparator } : {}),\n ...(locale !== null && locale.length > 0 ? { locale } : {}),\n ...(owner !== undefined ? { owner } : {}),\n };\n return entry;\n }\n}\n\n/**\n * Resolve the field type for an element by combining the explicit\n * `data-payload-type` attribute with element-tag heuristics. Falls\n * back to `text`.\n */\nexport function resolveFieldType(element: Element): FieldType {\n const explicit = element.getAttribute(TYPE_ATTRIBUTE);\n if (explicit !== null && VALID_FIELD_TYPES.has(explicit as FieldType)) {\n return explicit as FieldType;\n }\n if (element.hasAttribute(RICH_TEXT_ATTRIBUTE)) return 'richText';\n if (element.hasAttribute(HTML_ATTRIBUTE)) return 'html';\n if (element.hasAttribute(STRUCTURAL_ATTRIBUTE)) return 'structural-array';\n if (element.hasAttribute(ARRAY_ATTRIBUTE)) return 'array';\n if (element.tagName === 'IMG') return 'image';\n if (element.tagName === 'A') return 'url';\n if (element.tagName === 'TIME') return 'date';\n if (element.tagName === 'INPUT') {\n const inputType = (element as HTMLInputElement).type;\n if (inputType === 'checkbox') return 'checkbox';\n if (inputType === 'number') return 'number';\n if (inputType === 'date' || inputType === 'datetime-local') return 'date';\n }\n return 'text';\n}\n\nfunction alwaysTrue(): boolean {\n return true;\n}\n","/**\n * Document ownership for bindings.\n *\n * A field name alone cannot identify a binding on a page that previews more\n * than one document. `title` may belong to the page global, to shared SEO\n * metadata, and to every card of a collection at the same time, and an update\n * for any one of them would otherwise reach all three.\n *\n * An owner marker names the document a subtree belongs to. Payload already\n * sends the identity of the edited document on every message, so scoping needs\n * no additional consumer configuration beyond the markers themselves.\n *\n * The grammar is deliberately small and comparable as a plain string:\n *\n * - `global:<slug>`\n * - `collection:<slug>`\n * - `collection:<slug>:<id>`\n *\n * @module @core/binding-owner\n */\n\n/** Identity of the document an incoming message describes. */\nexport interface MessageDocumentIdentity {\n readonly globalSlug?: string | undefined;\n readonly collectionSlug?: string | undefined;\n /** Primary key of the edited document, when the payload carries one. */\n readonly documentId?: string | undefined;\n}\n\n/** Owner key naming one Payload global. */\nexport function globalOwnerKey(slug: string): string {\n return `global:${slug}`;\n}\n\n/**\n * Owner key naming a collection, optionally narrowed to one document.\n *\n * A marker without an id claims every document of that collection, which is\n * the right granularity for a page that renders exactly one of them.\n */\nexport function collectionOwnerKey(slug: string, documentId?: string): string {\n return documentId === undefined || documentId === ''\n ? `collection:${slug}`\n : `collection:${slug}:${documentId}`;\n}\n\nfunction nonEmpty(value: string | undefined): value is string {\n return typeof value === 'string' && value.length > 0;\n}\n\n/**\n * Owner keys the given message is allowed to address.\n *\n * Returns `null` when the message carries no usable document identity. That is\n * not the same as \"addresses nothing\": the caller decides, and the runtime\n * treats it as fail-closed rather than guessing an owner.\n *\n * A collection message addresses both the collection-wide key and — when the\n * document id is known — its exact document key. A marker that names an id is\n * therefore unreachable while the id is unknown, which is intentional: an\n * unproven identity must not satisfy an exact claim.\n */\nexport function messageOwnerKeys(identity: MessageDocumentIdentity): readonly string[] | null {\n if (nonEmpty(identity.globalSlug)) return [globalOwnerKey(identity.globalSlug)];\n if (!nonEmpty(identity.collectionSlug)) return null;\n const collectionKey = collectionOwnerKey(identity.collectionSlug);\n return nonEmpty(identity.documentId)\n ? [collectionKey, collectionOwnerKey(identity.collectionSlug, identity.documentId)]\n : [collectionKey];\n}\n\n/**\n * Whether a binding may receive an update addressed to `keys`.\n *\n * An unowned binding is out of scope whenever scoping is active. Ownership is\n * opt-in precisely so that this stays a deliberate, verifiable claim rather\n * than a default that silently downgrades to \"matches everything\".\n */\nexport function isBindingInScope(\n owner: string | undefined,\n keys: readonly string[] | null,\n): boolean {\n if (keys === null || owner === undefined) return false;\n return keys.includes(owner);\n}\n\n/**\n * Read a document id out of an already-resolved field payload.\n *\n * Payload sends the primary key alongside the edited values. Only scalars are\n * accepted; anything else leaves the identity unproven.\n */\nexport function readDocumentId(fields: Record<string, unknown>): string | undefined {\n const id: unknown = fields['id'];\n if (typeof id === 'string' && id.length > 0) return id;\n if (typeof id === 'number' && Number.isFinite(id)) return String(id);\n return undefined;\n}\n","/**\n * DOM observers — mutation tracking + visibility tracking.\n *\n * Two purposes:\n *\n * 1. Detect when new `data-payload-field` elements appear, when\n * existing ones disappear, and when cached binding metadata changes.\n * The observer debounces these mutations and then asks its host to\n * rebuild the cache.\n * 2. Track which cached elements are within the viewport (with a\n * configurable rootMargin). Updates for off-screen elements are\n * queued by the scheduler and replayed when the element scrolls\n * into view — solving the \"stale offscreen content\" bug from the\n * legacy implementation.\n *\n * The observers are split from the cache and the scheduler because:\n * - They are environment-specific (need `MutationObserver` and\n * `IntersectionObserver`).\n * - Tests can supply mock observers for deterministic timing.\n *\n * @module @core/observers\n */\n\nimport { BINDING_ATTRIBUTES, FIELD_ATTRIBUTE, OWNER_ATTRIBUTE } from './cache';\n\n/**\n * Callbacks the observer manager invokes back into its host.\n */\nexport interface ObserverCallbacks {\n /** Invoked when the cache likely needs a rebuild. */\n readonly onStructuralChange: () => void;\n /** Invoked when an element enters or leaves the viewport. */\n readonly onVisibilityChange: (element: Element, isVisible: boolean) => void;\n}\n\n/**\n * Tunable parameters for the observer manager.\n */\nexport interface ObserverOptions {\n /** Debounce window for mutation events (ms). Default: 100. */\n readonly mutationDebounceMs?: number;\n /** rootMargin passed to IntersectionObserver. Default: `200px`. */\n readonly intersectionRootMargin?: string;\n}\n\nconst DEFAULT_DEBOUNCE_MS = 100;\nconst DEFAULT_ROOT_MARGIN = '200px';\n// `nodeType` values are stable across DOM realms; the global `Node`\n// constructor is not (and is absent in pure Node/SSR environments).\nconst ELEMENT_NODE = 1;\n\nconst enum ObserverSlot {\n Callbacks,\n DebounceMs,\n RootMargin,\n Visible,\n Mutation,\n Intersection,\n DebounceTimer,\n Generation,\n}\n\n/**\n * One TS-private state record avoids private-field scaffolding in the inlined\n * runtime. Named slots keep lifecycle ownership explicit without property-name\n * mangling; this internal class never crosses the package boundary.\n */\ntype ObserverState = [\n callbacks: ObserverCallbacks,\n debounceMs: number,\n rootMargin: string,\n visible: Set<Element>,\n mutation: MutationObserver | null,\n intersection: IntersectionObserver | null,\n debounceTimer: ReturnType<typeof setTimeout> | null,\n generation: number,\n];\n\n/**\n * Combined Mutation + Intersection observer.\n *\n * Lifecycle:\n * - `start(root)` attaches the mutation observer to `root`.\n * - `observeElement(el)` adds `el` to the intersection observer.\n * - `unobserveElement(el)` removes it.\n * - `stop()` disconnects everything; safe to call repeatedly.\n */\nexport class ObserverManager {\n private readonly s: ObserverState;\n\n constructor(callbacks: ObserverCallbacks, options: ObserverOptions = {}) {\n this.s = [\n callbacks,\n options.mutationDebounceMs ?? DEFAULT_DEBOUNCE_MS,\n options.intersectionRootMargin ?? DEFAULT_ROOT_MARGIN,\n new Set<Element>(),\n null,\n null,\n null,\n 0,\n ];\n }\n\n /** Begin observing `root` for mutations and create the intersection observer. */\n start(root: Node): void {\n // Restarting is an explicit resource hand-off. Disconnect before replacing\n // either handle so repeated starts cannot orphan observers or timers.\n const previousGeneration = this.s[ObserverSlot.Generation];\n this.stop();\n const generation = previousGeneration + 1;\n // A disconnect hook may synchronously start a newer observer generation.\n // That nested start owns the lifecycle; this older stack must build nothing.\n if (this.s[ObserverSlot.Generation] !== generation) return;\n let mutation: MutationObserver | null = null;\n let intersection: IntersectionObserver | null = null;\n try {\n mutation = new MutationObserver((mutations) => {\n this.#handleMutations(mutations, generation);\n });\n // Construct both resources before activating either one. If a host lacks\n // a usable IntersectionObserver, no MutationObserver may be left live.\n intersection = new IntersectionObserver(\n (entries) => {\n this.#handleIntersection(entries, generation);\n },\n { rootMargin: this.s[ObserverSlot.RootMargin], threshold: 0 },\n );\n mutation.observe(root, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: [...BINDING_ATTRIBUTES],\n });\n } catch (error) {\n mutation?.disconnect();\n intersection?.disconnect();\n throw error;\n }\n // Constructors/observe are host boundaries. A re-entrant stop or start\n // invalidates these candidates before they can replace newer resources.\n if (this.s[ObserverSlot.Generation] !== generation) {\n mutation.disconnect();\n intersection.disconnect();\n return;\n }\n this.s[ObserverSlot.Mutation] = mutation;\n this.s[ObserverSlot.Intersection] = intersection;\n }\n\n /** Add an element to the intersection observer. */\n observeElement(element: Element): void {\n this.s[ObserverSlot.Intersection]?.observe(element);\n }\n\n /** Remove an element from the intersection observer. */\n unobserveElement(element: Element): void {\n this.s[ObserverSlot.Intersection]?.unobserve(element);\n this.s[ObserverSlot.Visible].delete(element);\n }\n\n /** Mark an element as currently visible. Useful for tests/seeding. */\n markVisible(element: Element, visible: boolean): void {\n if (visible) this.s[ObserverSlot.Visible].add(element);\n else this.s[ObserverSlot.Visible].delete(element);\n }\n\n /** Is `element` currently within the (margined) viewport? */\n isVisible(element: Element): boolean {\n return this.s[ObserverSlot.Visible].has(element);\n }\n\n /** Disconnect all observers and clear pending timers. */\n stop(): void {\n // Invalidate callbacks first. Queued observer deliveries and timers must\n // become inert before any owned resource is disconnected or cleared.\n this.s[ObserverSlot.Generation] += 1;\n const timer = this.s[ObserverSlot.DebounceTimer];\n const mutation = this.s[ObserverSlot.Mutation];\n const intersection = this.s[ObserverSlot.Intersection];\n this.s[ObserverSlot.DebounceTimer] = null;\n this.s[ObserverSlot.Mutation] = null;\n this.s[ObserverSlot.Intersection] = null;\n this.s[ObserverSlot.Visible].clear();\n if (timer !== null) clearTimeout(timer);\n try {\n mutation?.disconnect();\n } finally {\n intersection?.disconnect();\n }\n }\n\n #handleMutations(mutations: readonly MutationRecord[], generation: number): void {\n if (!this.#isCurrentGeneration(generation)) return;\n if (!hasStructuralImpact(mutations)) return;\n if (!this.#isCurrentGeneration(generation)) return;\n if (this.s[ObserverSlot.DebounceTimer] !== null) {\n clearTimeout(this.s[ObserverSlot.DebounceTimer]);\n }\n const timer = setTimeout(() => {\n if (!this.#isCurrentGeneration(generation) || this.s[ObserverSlot.DebounceTimer] !== timer) {\n return;\n }\n this.s[ObserverSlot.DebounceTimer] = null;\n this.s[ObserverSlot.Callbacks].onStructuralChange();\n }, this.s[ObserverSlot.DebounceMs]);\n this.s[ObserverSlot.DebounceTimer] = timer;\n }\n\n #handleIntersection(entries: readonly IntersectionObserverEntry[], generation: number): void {\n for (const entry of entries) {\n if (!this.#isCurrentGeneration(generation)) return;\n const target = entry.target;\n if (entry.isIntersecting) {\n if (!this.s[ObserverSlot.Visible].has(target)) {\n this.s[ObserverSlot.Visible].add(target);\n this.s[ObserverSlot.Callbacks].onVisibilityChange(target, true);\n if (!this.#isCurrentGeneration(generation)) return;\n }\n } else if (this.s[ObserverSlot.Visible].has(target)) {\n this.s[ObserverSlot.Visible].delete(target);\n this.s[ObserverSlot.Callbacks].onVisibilityChange(target, false);\n if (!this.#isCurrentGeneration(generation)) return;\n }\n }\n }\n\n #isCurrentGeneration(generation: number): boolean {\n return (\n this.s[ObserverSlot.Generation] === generation && this.s[ObserverSlot.Intersection] !== null\n );\n }\n}\n\n/**\n * Returns true iff any mutation in the batch affects the live preview\n * tracking attributes. This short-circuits the common case where DOM\n * activity is unrelated to the preview, avoiding spurious rebuilds.\n */\nfunction hasStructuralImpact(mutations: readonly MutationRecord[]): boolean {\n for (const m of mutations) {\n if (\n m.type === 'attributes' &&\n m.attributeName !== null &&\n BINDING_ATTRIBUTES.includes(m.attributeName)\n ) {\n // The field attribute itself can add, remove, or retarget a binding, and\n // the owner attribute re-attributes every binding below it — neither is\n // required to sit on a binding element. All other metadata — especially\n // the generic native `type` attribute — only matters on an element that\n // is still a live-preview binding. This keeps unrelated form activity\n // from causing whole-cache rebuilds.\n if (\n m.attributeName === FIELD_ATTRIBUTE ||\n m.attributeName === OWNER_ATTRIBUTE ||\n (m.target.nodeType === ELEMENT_NODE && (m.target as Element).hasAttribute(FIELD_ATTRIBUTE))\n ) {\n return true;\n }\n }\n for (const node of m.addedNodes) {\n if (containsTrackedElement(node)) return true;\n }\n for (const node of m.removedNodes) {\n if (containsTrackedElement(node)) return true;\n }\n }\n return false;\n}\n\nfunction containsTrackedElement(node: Node): boolean {\n if (node.nodeType !== ELEMENT_NODE) return false;\n const element = node as Element;\n if (element.hasAttribute(FIELD_ATTRIBUTE)) return true;\n return element.querySelector(`[${FIELD_ATTRIBUTE}]`) !== null;\n}\n","/**\n * Schema parser.\n *\n * Validates and normalises the `fieldSchemaJSON` Payload sends along\n * with every live-preview message. The runtime uses the parsed schema\n * to auto-resolve field types (no DOM annotation needed for\n * type detection) and to drive the structural diff for arrays/blocks.\n *\n * The parser is **defensive**: schema entries that fail validation are\n * dropped silently rather than throwing. Payload's schema format is\n * stable, but a mismatch between Payload's version and ours must never\n * crash the preview.\n *\n * @module @schema/parser\n */\n\nimport type { PayloadBlockSchema, PayloadFieldSchema } from '@/types/payload-protocol';\n\n/**\n * Parse a raw schema array.\n *\n * Accepts the JSON-decoded value from Payload's `fieldSchemaJSON`.\n * Returns an array of validated schemas with `unknown` extras stripped\n * back to a plain `Record<string, unknown>` shape.\n */\nexport function parseFieldSchema(raw: unknown): readonly PayloadFieldSchema[] {\n if (!Array.isArray(raw)) return [];\n const out: PayloadFieldSchema[] = [];\n for (const entry of raw) {\n const parsed = parseFieldEntry(entry);\n if (parsed) out.push(parsed);\n }\n return out;\n}\n\nfunction parseFieldEntry(value: unknown): PayloadFieldSchema | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const record = value as Record<string, unknown>;\n const name = record['name'];\n const type = record['type'];\n if (typeof name !== 'string' || name.length === 0) return undefined;\n if (typeof type !== 'string' || type.length === 0) return undefined;\n\n const fields = parseFieldSchema(record['fields']);\n const blocks = parseBlockSchema(record['blocks']);\n\n const result: Record<string, unknown> = { ...record, name, type };\n if (fields.length > 0) result['fields'] = fields;\n else delete result['fields'];\n if (blocks.length > 0) result['blocks'] = blocks;\n else delete result['blocks'];\n\n return result as unknown as PayloadFieldSchema;\n}\n\nfunction parseBlockSchema(raw: unknown): readonly PayloadBlockSchema[] {\n if (!Array.isArray(raw)) return [];\n const out: PayloadBlockSchema[] = [];\n for (const entry of raw) {\n if (typeof entry !== 'object' || entry === null) continue;\n const record = entry as Record<string, unknown>;\n const slug = record['slug'];\n if (typeof slug !== 'string' || slug.length === 0) continue;\n const fields = parseFieldSchema(record['fields']);\n out.push({ ...record, slug, fields });\n }\n return out;\n}\n","/**\n * Protocol-version negotiation.\n *\n * ⚠️ Reality check: **stock Payload does not version its live-preview\n * postMessage protocol.** The admin never sends a `protocolVersion`\n * field and ignores extra fields in our `ready` handshake. Observed\n * wire behaviour:\n *\n * - Payload **2.x** sent `fieldSchemaJSON` with the first update\n * (client-side merge era).\n * - Payload **3.x** removed `fieldSchemaJSON` entirely; the official\n * client re-fetches merged documents through the REST API instead.\n * - No Payload version sends `previewToken` or any keepalive.\n *\n * This module therefore only matters for NON-stock admin panels — a\n * custom `window.postMessage` sender can advertise a version and this\n * library will negotiate `min(ours, theirs)` and expose capability\n * flags. Against stock Payload, `theirs` stays `undefined`, negotiation\n * collapses to v1, and nothing is gated on it: schema handling\n * activates whenever `fieldSchemaJSON` is actually present, and token\n * validation only runs when the consumer opts in.\n *\n * Version ladder (this library's own numbering, not Payload's):\n *\n * - **v1** — data + slug + locale (matches stock Payload of any era).\n * - **v2** — remote sends `fieldSchemaJSON` (Payload 2.x behaviour).\n * - **v3** — remote sends `previewToken` (custom senders only).\n * - **v4** — nested-array recursion / richer document events\n * (custom senders only).\n *\n * @module @core/protocol-version\n */\n\nexport const LIBRARY_PROTOCOL_VERSION = 4;\n\n/** Capability flag → minimum protocol version it requires. */\nconst CAPABILITY_REQUIREMENTS: Readonly<Record<string, number>> = {\n basic: 1,\n 'schema-json': 2,\n 'preview-token': 3,\n 'nested-arrays': 4,\n 'recursive-diffs': 4,\n} as const;\n\nexport type ProtocolCapability = keyof typeof CAPABILITY_REQUIREMENTS;\n\nexport interface ProtocolNegotiation {\n /** This library's protocol version. */\n readonly ours: number;\n /** The remote party's version, when known. */\n readonly theirs: number | undefined;\n /** `min(ours, theirs ?? 1)` — the version both sides actually share. */\n readonly negotiated: number;\n /** Capability flags enabled at the negotiated version. */\n readonly capabilities: ReadonlySet<string>;\n}\n\n/**\n * Compute the negotiated view of the protocol.\n *\n * `theirs === undefined` collapses to v1 — assume the remote party is\n * an older Payload that does not advertise a version.\n *\n * Non-finite or non-positive `theirs` values fall back to v1 as well —\n * we never trust an obviously-corrupted negotiation byte.\n */\nexport function negotiateProtocol(theirs: number | undefined): ProtocolNegotiation {\n const sanitisedTheirs =\n typeof theirs === 'number' && Number.isFinite(theirs) && theirs >= 1\n ? Math.floor(theirs)\n : undefined;\n const effectiveTheirs = sanitisedTheirs ?? 1;\n const negotiated = Math.min(LIBRARY_PROTOCOL_VERSION, effectiveTheirs);\n const capabilities = new Set<string>();\n for (const [flag, minVersion] of Object.entries(CAPABILITY_REQUIREMENTS)) {\n if (negotiated >= minVersion) capabilities.add(flag);\n }\n return {\n ours: LIBRARY_PROTOCOL_VERSION,\n ...(sanitisedTheirs !== undefined ? { theirs: sanitisedTheirs } : { theirs: undefined }),\n negotiated,\n capabilities,\n };\n}\n\nexport function hasCapability(\n negotiation: ProtocolNegotiation,\n capability: ProtocolCapability,\n): boolean {\n return negotiation.capabilities.has(capability);\n}\n","/**\n * Detect an invalid async result in a synchronous extension point.\n *\n * Rejected native Promises otherwise become unhandled after the caller falls\n * back synchronously. Assimilating the result through a handled Promise keeps\n * that contract violation observable only through the runtime's explicit\n * error channel.\n */\nexport function observeThenableResult(value: unknown): boolean {\n if ((typeof value !== 'object' || value === null) && typeof value !== 'function') return false;\n if (typeof (value as { readonly then?: unknown }).then !== 'function') return false;\n void Promise.resolve(value).catch(() => undefined);\n return true;\n}\n","/**\n * Message bus — postMessage receive + send with strict validation.\n *\n * Responsibilities:\n *\n * 1. Subscribe to the `message` event and reject anything that does\n * not come from a trusted origin (matcher injected by the caller).\n * 2. Validate message shape with a per-type guard before exposing the\n * payload downstream: a `payload-live-preview` update must carry a\n * `data` object (or none, for the `ready` handshake); anything\n * whose `data` is a non-object is dropped as `'shape'`. So the\n * `PayloadLivePreviewMessage.data?: Record<string, unknown>` type\n * is genuinely enforced at runtime, not just asserted.\n * 3. Send the `ready` handshake to potential parent windows.\n *\n * The matcher pattern decouples origin policy from message handling:\n * - the runtime's origin detector decides which origins are valid;\n * - the bus simply asks \"is this origin valid?\" for every message.\n *\n * The bus never throws. Every validation failure becomes either a\n * silent drop or a routed `onInvalid` callback.\n *\n * @module @core/message-bus\n */\n\nimport type {\n PayloadLivePreviewMessage,\n PayloadDocumentEventMessage,\n PayloadFieldSchema,\n} from '@/types/payload-protocol';\nimport { parseFieldSchema } from '@schema/parser';\nimport { LIBRARY_PROTOCOL_VERSION } from './protocol-version';\nimport { observeThenableResult } from './thenable';\n\nexport type OriginMatcher = (origin: string) => boolean;\n\n/**\n * Stable identity assigned to a data-bearing update at message ingress.\n *\n * `revision` is monotonic for the lifetime of one `MessageBus` instance.\n * `generation` identifies the listener attachment in which the message\n * arrived; work from a detached generation is never dispatched.\n */\nexport interface MessageRevision {\n readonly revision: number;\n readonly generation: number;\n}\n\nexport interface MessageHandlers {\n /**\n * Validated live-preview message. Data-bearing updates include their\n * revision identity; data-less ready handshakes intentionally do not.\n */\n readonly onUpdate: (\n msg: PayloadLivePreviewMessage,\n origin: string,\n messageRevision?: MessageRevision,\n ) => void;\n /** Validated document save event. */\n readonly onDocumentEvent: (msg: PayloadDocumentEventMessage, origin: string) => void;\n /**\n * Invoked when a message is rejected. Optional — used by debug logging.\n *\n * `reason` is one of `origin`, `shape`, `type`, `token`.\n */\n readonly onInvalid?: (reason: 'origin' | 'shape' | 'type' | 'token', origin: string) => void;\n /**\n * Optional preview-token gate. When set, every `payload-live-preview`\n * update message must carry a `previewToken` that this function\n * approves; otherwise the message is dropped with reason `'token'`.\n *\n * Returning a Promise is supported. Async validations are **serialised\n * in arrival order** through a single chain, so update A is always\n * dispatched before update B when A arrived first — even if B's\n * validation would otherwise resolve sooner. Validation errors are\n * treated as rejection and routed to `onInvalid('token')` when provided.\n */\n readonly validateToken?: (\n token: string | undefined,\n origin: string,\n ) => boolean | Promise<boolean>;\n}\n\ninterface PendingValidation {\n readonly generation: number;\n readonly message: PayloadLivePreviewMessage;\n readonly origin: string;\n readonly messageRevision: MessageRevision | undefined;\n settled: boolean;\n approved: boolean;\n}\n\n/**\n * A consumed prefix is compacted only after it is both substantial and at\n * least half of the backing array. This bounds retained settled entries while\n * keeping dequeue amortized O(1); a fully drained or invalidated generation\n * always drops the backing array immediately.\n */\nconst VALIDATION_QUEUE_COMPACTION_THRESHOLD = 1_024;\n\nconst enum BusSlot {\n Matcher,\n Handlers,\n BoundListener,\n AttachedTarget,\n Generation,\n Revision,\n ValidationQueue,\n ValidationQueueHead,\n}\n\n/**\n * One TS-private record keeps all mutable ingress state instance-local while\n * avoiding private-field lowering in the ES2020 inline build. Named slots\n * preserve queue and generation invariants without property-name mangling;\n * this internal class never crosses the package boundary.\n */\ntype MessageBusState = [\n matcher: OriginMatcher,\n handlers: MessageHandlers,\n boundListener: ((event: MessageEvent) => void) | undefined,\n attachedTarget: Window | undefined,\n generation: number,\n revision: number,\n validationQueue: PendingValidation[],\n validationQueueHead: number,\n];\n\nexport class MessageBus {\n private readonly s: MessageBusState;\n /**\n * Validator calls start eagerly, but their outcomes commit from the\n * head of this queue. This deliberately includes booleans and thrown\n * errors: a synchronous result can never overtake an older promise.\n * Detach replaces the queue, so a new generation is never blocked by\n * unresolved work from its predecessor.\n */\n constructor(matcher: OriginMatcher, handlers: MessageHandlers) {\n this.s = [matcher, handlers, undefined, undefined, 0, 0, [], 0];\n }\n\n /** Begin listening for window-level `message` events. Idempotent. */\n attach(target: Window = window): void {\n if (this.s[BusSlot.AttachedTarget] !== undefined) return;\n let committed = false;\n const listener = (event: MessageEvent): void => {\n // Each attachment owns a distinct listener. An ineffectively removed\n // listener from an older transaction must not borrow the new generation.\n if (!committed || this.s[BusSlot.BoundListener] !== listener) return;\n const generation = this.s[BusSlot.Generation];\n try {\n this.#receive(event, generation);\n } catch {\n // The guards below deliberately handle every expected protocol failure.\n // Keep one final trust-boundary safety net for hostile accessors or other\n // unexpected JavaScript values delivered through postMessage.\n let origin = '';\n try {\n origin = event.origin;\n } catch {\n // A synthetic MessageEvent can itself expose hostile accessors.\n }\n this.#reportInvalid('shape', origin, generation);\n }\n };\n this.s[BusSlot.Generation] += 1;\n this.#resetValidationQueue();\n this.s[BusSlot.AttachedTarget] = target;\n this.s[BusSlot.BoundListener] = listener;\n try {\n target.addEventListener('message', listener);\n } catch (error) {\n // Invalidate this attempt before external rollback. A remove hook may\n // attach a newer generation, which this older catch must not clobber.\n if (this.s[BusSlot.BoundListener] === listener) {\n this.s[BusSlot.AttachedTarget] = undefined;\n this.s[BusSlot.BoundListener] = undefined;\n this.#resetValidationQueue();\n }\n try {\n target.removeEventListener('message', listener);\n } catch {\n // Preserve the original addEventListener failure.\n }\n throw error;\n }\n // addEventListener is a host boundary. Reentrant detach/attach may have\n // installed a newer resource; remove only this attempt's unique listener.\n if (this.s[BusSlot.BoundListener] === listener) {\n committed = true;\n } else {\n try {\n target.removeEventListener('message', listener);\n } catch {\n // The obsolete listener is identity-gated above even if removal fails.\n }\n }\n }\n\n /** Stop listening. Idempotent. */\n detach(_target?: Window): void {\n const target = this.s[BusSlot.AttachedTarget];\n const listener = this.s[BusSlot.BoundListener];\n if (target === undefined || listener === undefined) return;\n\n // Invalidate first. A listener already on the stack, or a validator\n // settling during removal, must observe the generation as obsolete.\n this.s[BusSlot.AttachedTarget] = undefined;\n this.s[BusSlot.BoundListener] = undefined;\n this.#resetValidationQueue();\n target.removeEventListener('message', listener);\n }\n\n /**\n * Invalidate every pending validation while keeping the current listener\n * attached. Used when the surrounding connection lifecycle expires: work\n * accepted after this point belongs to a fresh generation and cannot be\n * blocked or revived by an older validator.\n */\n advanceGeneration(): boolean {\n if (this.s[BusSlot.AttachedTarget] === undefined) return false;\n this.s[BusSlot.Generation] += 1;\n this.#resetValidationQueue();\n return true;\n }\n\n /**\n * Send a `ready` handshake message to one or more parent windows.\n *\n * `targets` are the windows to notify (parent and/or opener). For\n * each target the message is sent to every `origin` so the Payload\n * admin in the parent receives it regardless of which origin it\n * happens to be served on.\n */\n static sendReady(targets: readonly Window[], origins: readonly string[]): void {\n const hasTargets = targets.length > 0;\n if (!hasTargets || origins.length === 0) return;\n const payload: PayloadLivePreviewMessage = {\n type: 'payload-live-preview',\n // Keep this as a runtime boolean expression. The inline build compacts\n // literal booleans, but the ready handshake must remain a real boolean.\n ready: hasTargets,\n protocolVersion: LIBRARY_PROTOCOL_VERSION,\n };\n for (const target of targets) {\n for (const origin of origins) {\n try {\n target.postMessage(payload, origin);\n } catch {\n // postMessage can throw if the origin string is malformed.\n // Swallow silently — invalid origins are someone else's\n // configuration problem and we already log via onInvalid.\n }\n }\n }\n }\n\n #receive(event: MessageEvent, generation: number): void {\n if (!this.#isCurrentGeneration(generation)) return;\n\n // Every read below can cross user-controlled JavaScript through a\n // synthetic MessageEvent, Proxy, accessor, schema value, or callback.\n // Re-check the captured generation after each such boundary so re-entry\n // cannot continue an obsolete ingress into the fresh validation queue.\n const origin = event.origin;\n if (!this.#isCurrentGeneration(generation)) return;\n if (!this.#matchesOrigin(origin, generation)) {\n this.#reportInvalid('origin', origin, generation);\n return;\n }\n\n const data: unknown = event.data;\n if (!this.#isCurrentGeneration(generation)) return;\n const isMessage = isObjectMessage(data);\n if (!this.#isCurrentGeneration(generation)) return;\n if (!isMessage) {\n this.#reportInvalid('shape', origin, generation);\n return;\n }\n\n const type = data.type;\n if (!this.#isCurrentGeneration(generation)) return;\n switch (type) {\n case 'payload-live-preview': {\n const isLivePreview = isLivePreviewMessage(data);\n if (!this.#isCurrentGeneration(generation)) return;\n if (!isLivePreview) {\n this.#reportInvalid('shape', origin, generation);\n return;\n }\n const message = normalizeLivePreviewMessage(data);\n if (!this.#isCurrentGeneration(generation)) return;\n this.#dispatchUpdate(message, origin, generation);\n return;\n }\n case 'payload-document-event': {\n const isDocumentEvent = isDocumentEventMessage(data);\n if (!this.#isCurrentGeneration(generation)) return;\n if (!isDocumentEvent) {\n this.#reportInvalid('shape', origin, generation);\n return;\n }\n let onDocumentEvent: MessageHandlers['onDocumentEvent'];\n try {\n onDocumentEvent = this.s[BusSlot.Handlers].onDocumentEvent;\n } catch {\n return;\n }\n if (!this.#isCurrentGeneration(generation)) return;\n this.#invokeHandler(onDocumentEvent, data, origin);\n return;\n }\n default:\n this.#reportInvalid('type', origin, generation);\n }\n }\n\n #dispatchUpdate(message: PayloadLivePreviewMessage, origin: string, generation: number): void {\n if (!this.#isCurrentGeneration(generation)) return;\n\n const data = message.data;\n if (!this.#isCurrentGeneration(generation)) return;\n const hasUpdateData = isPlainObject(data);\n if (!this.#isCurrentGeneration(generation)) return;\n\n // Shape-valid data updates consume their revision before validation.\n // A rejected token therefore leaves an intentional gap.\n const messageRevision = hasUpdateData\n ? { generation, revision: (this.s[BusSlot.Revision] += 1) }\n : undefined;\n let validator: MessageHandlers['validateToken'];\n try {\n validator = this.s[BusSlot.Handlers].validateToken;\n } catch {\n return;\n }\n if (!this.#isCurrentGeneration(generation)) return;\n if (validator === undefined) {\n this.#commitUpdate(message, origin, generation, messageRevision);\n return;\n }\n // The `ready` handshake doesn't carry a token; let it\n // through so the parent learns we're listening even when auth is\n // enabled. Only `data`-bearing updates are gated.\n if (message.ready === true && data === undefined) {\n this.#commitUpdate(message, origin, generation, undefined);\n return;\n }\n\n const pending: PendingValidation = {\n generation,\n message,\n origin,\n messageRevision,\n settled: false,\n approved: false,\n };\n this.s[BusSlot.ValidationQueue].push(pending);\n\n let verdict: unknown;\n try {\n // Invocation is intentionally eager. Only committing the outcome\n // waits for earlier queue entries.\n verdict = validator(message.previewToken, origin);\n } catch {\n this.#settleValidation(pending, false);\n return;\n }\n\n if (typeof verdict === 'boolean') {\n this.#settleValidation(pending, verdict);\n return;\n }\n\n // Normalize even an incorrectly typed JavaScript return value through a\n // real Promise. This safely assimilates thenables (including a throwing\n // `then` getter), while the literal-true comparison below fails closed for\n // strings, objects, and every other non-boolean fulfillment.\n void Promise.resolve(verdict).then(\n (approved) => {\n this.#settleValidation(pending, approved === true);\n },\n () => {\n this.#settleValidation(pending, false);\n },\n );\n }\n\n #settleValidation(pending: PendingValidation, approved: boolean): void {\n if (!this.#isCurrentGeneration(pending.generation)) return;\n pending.approved = approved;\n pending.settled = true;\n this.#drainValidationQueue(pending.generation);\n }\n\n #drainValidationQueue(generation: number): void {\n while (this.#isCurrentGeneration(generation)) {\n const pending = this.s[BusSlot.ValidationQueue][this.s[BusSlot.ValidationQueueHead]];\n if (pending === undefined) return;\n\n // The matcher may have narrowed since ingress (for example the client\n // locks to the first committed origin). Re-check at the ordered commit\n // boundary before waiting for the verdict. An obsolete origin must not\n // retain the queue head and block newer work from the locked origin.\n if (!this.#matchesOrigin(pending.origin, generation)) {\n if (!this.#dequeueValidation(pending)) continue;\n this.#reportInvalid('origin', pending.origin, pending.generation);\n continue;\n }\n if (!pending.settled) return;\n if (!this.#dequeueValidation(pending)) continue;\n\n if (pending.approved) {\n this.#commitUpdate(\n pending.message,\n pending.origin,\n pending.generation,\n pending.messageRevision,\n );\n } else {\n this.#reportInvalid('token', pending.origin, pending.generation);\n }\n }\n }\n\n #commitUpdate(\n message: PayloadLivePreviewMessage,\n origin: string,\n generation: number,\n messageRevision: MessageRevision | undefined,\n ): void {\n if (!this.#isCurrentGeneration(generation)) return;\n let onUpdate: MessageHandlers['onUpdate'];\n try {\n onUpdate = this.s[BusSlot.Handlers].onUpdate;\n } catch {\n return;\n }\n if (!this.#isCurrentGeneration(generation)) return;\n if (messageRevision === undefined) {\n this.#invokeHandler(onUpdate, message, origin);\n } else {\n this.#invokeHandler(onUpdate, message, origin, messageRevision);\n }\n }\n\n #reportInvalid(\n reason: 'origin' | 'shape' | 'type' | 'token',\n origin: string,\n generation: number,\n ): void {\n if (!this.#isCurrentGeneration(generation)) return;\n let onInvalid: MessageHandlers['onInvalid'];\n try {\n onInvalid = this.s[BusSlot.Handlers].onInvalid;\n } catch {\n return;\n }\n if (!this.#isCurrentGeneration(generation)) return;\n if (onInvalid !== undefined) {\n this.#invokeHandler(onInvalid, reason, origin);\n }\n }\n\n /** Origin policy is a fail-closed trust boundary, including faulty matchers. */\n #matchesOrigin(origin: string, generation: number): boolean {\n if (!this.#isCurrentGeneration(generation)) return false;\n try {\n // Treat this as an untyped JavaScript boundary despite the TypeScript\n // signature: only literal `true` grants trust, and that approval belongs\n // only to the generation in which the matcher was invoked.\n const approved: unknown = this.s[BusSlot.Matcher](origin);\n return approved === true && this.#isCurrentGeneration(generation);\n } catch {\n return false;\n }\n }\n\n /**\n * Consumer callbacks cannot be allowed to unwind the window listener or the\n * ordered validation drain.\n */\n #invokeHandler<TArgs extends unknown[]>(\n handler: (...args: TArgs) => unknown,\n ...args: TArgs\n ): void {\n try {\n observeThenableResult(handler(...args));\n } catch {\n // Boundary callbacks are isolated by contract; the bus keeps draining.\n }\n }\n\n #isCurrentGeneration(generation: number): boolean {\n return (\n this.s[BusSlot.AttachedTarget] !== undefined && this.s[BusSlot.Generation] === generation\n );\n }\n\n #dequeueValidation(expected: PendingValidation): boolean {\n // Origin matchers are consumer callbacks. They may synchronously advance\n // the generation and reset the queue during the commit-boundary recheck;\n // never move the fresh generation's head on behalf of the old entry.\n const state = this.s;\n if (state[BusSlot.ValidationQueue][state[BusSlot.ValidationQueueHead]] !== expected) {\n return false;\n }\n state[BusSlot.ValidationQueueHead] += 1;\n if (state[BusSlot.ValidationQueueHead] === state[BusSlot.ValidationQueue].length) {\n this.#resetValidationQueue();\n return true;\n }\n if (\n state[BusSlot.ValidationQueueHead] >= VALIDATION_QUEUE_COMPACTION_THRESHOLD &&\n state[BusSlot.ValidationQueueHead] * 2 >= state[BusSlot.ValidationQueue].length\n ) {\n state[BusSlot.ValidationQueue] = state[BusSlot.ValidationQueue].slice(\n state[BusSlot.ValidationQueueHead],\n );\n state[BusSlot.ValidationQueueHead] = 0;\n }\n return true;\n }\n\n #resetValidationQueue(): void {\n this.s[BusSlot.ValidationQueue] = [];\n this.s[BusSlot.ValidationQueueHead] = 0;\n }\n}\n\n/**\n * Shallow guard: is this an object carrying a string `type`? Enough to\n * route by type; the per-type guards below enforce the payload shape.\n */\nfunction isObjectMessage(value: unknown): value is { type: string } {\n if (typeof value !== 'object' || value === null) return false;\n if (!('type' in value)) return false;\n return typeof value.type === 'string';\n}\n\n/**\n * Full guard for a `payload-live-preview` message. Requires `data` to be\n * a plain object when present (a non-object `data` — string, array,\n * number — is rejected), and each optional scalar to have the right\n * primitive type *or* be absent. `null` counts as absent: the real\n * Payload admin sends `collectionSlug: undefined` for a global, and a\n * JSON round-trip (or some serializers) turns that into `null` — both\n * mean \"no value\", not \"malformed\". Unknown extra fields (e.g.\n * `externallyUpdatedRelationship`) are tolerated.\n */\nfunction isLivePreviewMessage(value: { type: string }): value is PayloadLivePreviewMessage {\n const v = value as Record<string, unknown>;\n if (v['data'] !== undefined && v['data'] !== null && !isPlainObject(v['data'])) return false;\n if (!optionalTypeOk(v['fieldSchemaJSON'], (x) => Array.isArray(x))) return false;\n if (!optionalTypeOk(v['globalSlug'], (x) => typeof x === 'string')) return false;\n if (!optionalTypeOk(v['collectionSlug'], (x) => typeof x === 'string')) return false;\n if (!optionalTypeOk(v['locale'], (x) => typeof x === 'string')) return false;\n if (!optionalTypeOk(v['ready'], (x) => typeof x === 'boolean')) return false;\n if (!optionalTypeOk(v['previewToken'], (x) => typeof x === 'string')) return false;\n if (!optionalTypeOk(v['protocolVersion'], (x) => typeof x === 'number')) return false;\n return true;\n}\n\n/**\n * Runtime guard for Payload's document-save notification. Stock Payload\n * sends only the `type`; custom senders may add the optional typed fields.\n */\nfunction isDocumentEventMessage(value: { type: string }): value is PayloadDocumentEventMessage {\n const v = value as Record<string, unknown>;\n if (\n !optionalDocumentFieldOk(\n v['action'],\n (x) => x === 'updated' || x === 'created' || x === 'deleted',\n )\n ) {\n return false;\n }\n if (!optionalDocumentFieldOk(v['slug'], (x) => typeof x === 'string')) return false;\n if (\n !optionalDocumentFieldOk(\n v['id'],\n (x) => typeof x === 'string' || (typeof x === 'number' && Number.isFinite(x)),\n )\n ) {\n return false;\n }\n return true;\n}\n\n/** Document-event extensions use omission, not `null`, for absence. */\nfunction optionalDocumentFieldOk(value: unknown, check: (v: unknown) => boolean): boolean {\n return value === undefined || check(value);\n}\n\n/** `undefined`/`null` (absent) pass; otherwise the value must match `check`. */\nfunction optionalTypeOk(value: unknown, check: (v: unknown) => boolean): boolean {\n if (value === undefined || value === null) return true;\n return check(value);\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null) return false;\n const prototype = Object.getPrototypeOf(value) as object | null;\n return prototype === null || Object.getPrototypeOf(prototype) === null;\n}\n\nconst NULL_AS_ABSENT_FIELDS = [\n 'data',\n 'fieldSchemaJSON',\n 'globalSlug',\n 'collectionSlug',\n 'locale',\n 'ready',\n 'previewToken',\n 'protocolVersion',\n] as const satisfies readonly (keyof PayloadLivePreviewMessage)[];\n\n/**\n * Normalize the permissive wire boundary into the stricter public type.\n *\n * Payload/JSON bridges may encode absent optional properties as `null`; the\n * guard accepts that representation, so it must be removed before downstream\n * classification (especially the data-less ready handshake). Unknown fields,\n * including Payload's nullable relationship event, remain untouched for\n * protocol evolution.\n *\n * The schema guard establishes only that the outer value is an array;\n * `parseFieldSchema()` validates every nested entry and drops malformed ones.\n * A defensive catch also contains pathological cyclic/deep values supplied by\n * direct JavaScript `MessageEvent` construction.\n */\nfunction normalizeLivePreviewMessage(\n message: PayloadLivePreviewMessage,\n): PayloadLivePreviewMessage {\n const normalized = { ...message };\n for (const field of NULL_AS_ABSENT_FIELDS) {\n const wireValue: unknown = Reflect.get(normalized, field);\n if (wireValue === null) Reflect.deleteProperty(normalized, field);\n }\n if (!Array.isArray(normalized.fieldSchemaJSON)) return normalized;\n let fieldSchemaJSON: readonly PayloadFieldSchema[];\n try {\n fieldSchemaJSON = parseFieldSchema(normalized.fieldSchemaJSON);\n } catch {\n fieldSchemaJSON = [];\n }\n return { ...normalized, fieldSchemaJSON };\n}\n","/**\n * Connection state + heartbeat.\n *\n * Tracks whether the runtime is currently receiving updates from a\n * trusted origin and fires a callback when the heartbeat times out.\n *\n * The heartbeat is reset on every valid message and considered dead\n * after `timeoutMs` of silence. The host typically responds by\n * re-sending the `ready` handshake to attempt reconnection.\n *\n * @module @core/state\n */\n\nexport type ConnectionStatus = 'disconnected' | 'connecting' | 'connected';\n\nexport interface HeartbeatOptions {\n /**\n * Milliseconds of silence before declaring a timeout. `0` disables\n * the timer entirely — the correct default for the real Payload\n * protocol, which sends messages only on form edits and therefore\n * has no keepalive: any idle-based timeout would produce false\n * disconnects while the editor simply isn't typing.\n */\n readonly timeoutMs?: number;\n /** Callback invoked when the heartbeat times out. */\n readonly onTimeout: () => void;\n}\n\nconst DEFAULT_TIMEOUT_MS = 0;\n\nconst enum HeartbeatSlot {\n TimeoutMs,\n OnTimeout,\n Handle,\n LastKick,\n}\n\ntype HeartbeatState = [\n timeoutMs: number,\n onTimeout: () => void,\n handle: ReturnType<typeof setTimeout> | null,\n lastKick: number,\n];\n\n/**\n * Heartbeat timer with `kick`/`stop` semantics. `kick()` is invoked\n * on every valid incoming message; if it is not called within\n * `timeoutMs` the `onTimeout` callback fires. A `timeoutMs` of `0`\n * (the default) disables the timer.\n */\nexport class HeartbeatTimer {\n private readonly s: HeartbeatState;\n\n constructor(options: HeartbeatOptions) {\n this.s = [options.timeoutMs ?? DEFAULT_TIMEOUT_MS, options.onTimeout, null, 0];\n }\n\n /** Reset the timer. Schedules `onTimeout` after `timeoutMs`. */\n kick(): void {\n this.s[HeartbeatSlot.LastKick] = Date.now();\n if (this.s[HeartbeatSlot.TimeoutMs] <= 0) return;\n if (this.s[HeartbeatSlot.Handle] !== null) {\n clearTimeout(this.s[HeartbeatSlot.Handle]);\n }\n const handle = setTimeout(() => {\n if (this.s[HeartbeatSlot.Handle] !== handle) return;\n this.s[HeartbeatSlot.Handle] = null;\n this.s[HeartbeatSlot.OnTimeout]();\n }, this.s[HeartbeatSlot.TimeoutMs]);\n this.s[HeartbeatSlot.Handle] = handle;\n }\n\n /** Cancel any pending timeout. Safe to call repeatedly. */\n stop(): void {\n if (this.s[HeartbeatSlot.Handle] === null) return;\n clearTimeout(this.s[HeartbeatSlot.Handle]);\n this.s[HeartbeatSlot.Handle] = null;\n }\n\n /** Test introspection: timestamp of the most recent kick (ms epoch). */\n get lastKickAt(): number {\n return this.s[HeartbeatSlot.LastKick];\n }\n\n /** Test introspection: is a timeout currently scheduled? */\n get pending(): boolean {\n return this.s[HeartbeatSlot.Handle] !== null;\n }\n}\n\n/**\n * Pure-data connection-status tracker. Exposes transitions through\n * a callback so the host can wire it to its event emitter.\n */\nexport class ConnectionState {\n private readonly s: [\n status: ConnectionStatus,\n onChange: (next: ConnectionStatus, previous: ConnectionStatus) => void,\n ];\n\n constructor(onChange: (next: ConnectionStatus, previous: ConnectionStatus) => void) {\n this.s = ['disconnected', onChange];\n }\n\n get status(): ConnectionStatus {\n return this.s[0];\n }\n\n /** Mark as `connected`; idempotent. Returns true if state transitioned. */\n markConnected(): boolean {\n return this.transition('connected');\n }\n\n /** Mark as `connecting`; idempotent. */\n markConnecting(): boolean {\n return this.transition('connecting');\n }\n\n /** Mark as `disconnected`; idempotent. */\n markDisconnected(): boolean {\n return this.transition('disconnected');\n }\n\n private transition(next: ConnectionStatus): boolean {\n if (this.s[0] === next) return false;\n const previous = this.s[0];\n this.s[0] = next;\n this.s[1](next, previous);\n return true;\n }\n}\n","import { observeThenableResult } from './thenable';\n\n/**\n * Consumer diagnostics are best-effort observability, never control flow.\n *\n * Logger callbacks are arbitrary application code: they may throw, return a\n * rejected Promise, or expose a hostile thenable. This wrapper contains every\n * one of those outcomes while keeping invocation synchronous for ordinary\n * loggers. Callers can therefore report a failure without weakening the\n * lifecycle, merge-fallback, renderer, or teardown guarantee being reported.\n */\nexport function isolateDiagnostic(\n diagnostic: (...args: unknown[]) => unknown,\n): (...args: unknown[]) => void {\n return (...args): void => {\n try {\n observeThenableResult(diagnostic(...args));\n } catch {\n // Diagnostics must not become a second failure boundary.\n }\n };\n}\n\n/** Shared allocation-free default for disabled diagnostic channels. */\nexport function noopDiagnostic(): void {\n // Intentionally empty.\n}\n\n// Property access, invocation, and thenable inspection all happen inside the\n// wrapper, so missing/hostile console implementations cannot escape.\nexport const safeConsoleError = isolateDiagnostic((...args) =>\n (console.error as (...values: unknown[]) => unknown)(...args),\n);\n\nexport const safeConsoleWarn = isolateDiagnostic((...args) =>\n (console.warn as (...values: unknown[]) => unknown)(...args),\n);\n\nexport const safeConsoleDebug = isolateDiagnostic((...args) =>\n // eslint-disable-next-line no-console -- best-effort development diagnostics\n (console.debug as (...values: unknown[]) => unknown)(...args),\n);\n","/**\n * Server-side data merging for Payload 3.x.\n *\n * The Payload 3.x admin posts **raw form values** on every edit:\n * relationship and upload fields arrive as bare IDs, and nothing is\n * depth-populated. The official `@payloadcms/live-preview` client\n * solves this by re-fetching the document through the Payload REST\n * API with an `X-Payload-HTTP-Method-Override: GET` request — the\n * server merges the form values into the stored document and returns\n * the populated result.\n *\n * `DataMerger` replicates that exact request shape. It is optional:\n * when no `serverURL` is configured the runtime renders the raw form\n * values directly, which is fine for scalar fields but leaves\n * relationship/upload fields as IDs.\n *\n * Coalescing: only the most recent update matters, so an in-flight\n * request is aborted whenever a newer one starts. Failures degrade\n * gracefully — the caller falls back to the raw values.\n *\n * @module @core/data-merger\n */\n\nimport { isolateDiagnostic, noopDiagnostic } from './diagnostics';\n\nexport interface DataMergerOptions {\n /** Payload server origin, e.g. `https://cms.example.com`. */\n readonly serverURL: string;\n /** REST API route prefix. Defaults to `/api`. */\n readonly apiRoute?: string;\n /** Population depth requested from the server. Defaults to `1`. */\n readonly depth?: number;\n /** Injectable fetch implementation (tests, SSR shims). */\n readonly fetchFn?: typeof fetch;\n /** Diagnostic logger. */\n readonly log?: (...args: unknown[]) => void;\n}\n\nexport interface MergeRequest {\n readonly collectionSlug?: string | undefined;\n readonly globalSlug?: string | undefined;\n readonly data: Record<string, unknown>;\n readonly locale?: string | undefined;\n}\n\n/**\n * Outcome of a merge attempt.\n *\n * - `merged` — the server returned a populated document.\n * - `superseded` — a newer update aborted this one; drop it silently.\n * - `unavailable` — not mergeable / fetch failed; fall back to the\n * raw form values.\n */\nexport type MergeResult =\n | { readonly status: 'merged'; readonly doc: Record<string, unknown> }\n | { readonly status: 'superseded' }\n | { readonly status: 'unavailable' };\n\nfunction hasControlCharacter(value: string): boolean {\n for (const character of value) {\n const codePoint = character.codePointAt(0);\n if (codePoint !== undefined && (codePoint <= 0x1f || codePoint === 0x7f)) return true;\n }\n return false;\n}\n\nfunction isSafeSlug(value: string | undefined): value is string {\n if (\n value === undefined ||\n value.length === 0 ||\n value.length > 128 ||\n value === '.' ||\n value === '..' ||\n value.includes('/') ||\n value.includes('\\\\') ||\n value.includes('?') ||\n value.includes('#') ||\n hasControlCharacter(value)\n ) {\n return false;\n }\n try {\n encodeURIComponent(value);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction isSafeId(value: unknown): value is string | number {\n if (typeof value === 'number') return Number.isFinite(value);\n if (\n typeof value !== 'string' ||\n value.length === 0 ||\n value.length > 512 ||\n value === '.' ||\n value === '..' ||\n value.includes('/') ||\n value.includes('\\\\') ||\n hasControlCharacter(value)\n ) {\n return false;\n }\n try {\n encodeURIComponent(value);\n return true;\n } catch {\n // Lone UTF-16 surrogates cannot be encoded into a valid URL segment.\n return false;\n }\n}\n\nconst enum MergerSlot {\n ServerURL,\n ApiRoute,\n Depth,\n FetchFn,\n Log,\n Inflight,\n Attempt,\n DestroyDepth,\n}\n\ntype DataMergerState = [\n serverURL: string,\n apiRoute: string,\n depth: number,\n fetchFn: typeof fetch | undefined,\n log: (...args: unknown[]) => void,\n inflight: AbortController | null,\n attempt: number,\n destroyDepth: number,\n];\n\nexport class DataMerger {\n private readonly s: DataMergerState;\n\n constructor(options: DataMergerOptions) {\n // Normalise: no trailing slash on the origin, leading slash on the route.\n const serverURL = options.serverURL.replace(/\\/+$/, '');\n const route = options.apiRoute ?? '/api';\n this.s = [\n serverURL,\n route.startsWith('/') ? route : `/${route}`,\n options.depth ?? 1,\n options.fetchFn,\n options.log === undefined ? noopDiagnostic : isolateDiagnostic(options.log),\n null,\n 0,\n 0,\n ];\n }\n\n /**\n * Whether this message can be merged at all: collections need an\n * `id` in the form values (the admin always includes one), globals\n * only need their slug.\n */\n canMerge(request: MergeRequest): boolean {\n try {\n // Payload 1.x integrations historically use an empty global slug to mean\n // “collection document”; preserve that wire representation as absence.\n if (request.globalSlug) return isSafeSlug(request.globalSlug);\n if (!isSafeSlug(request.collectionSlug)) return false;\n const id = request.data['id'];\n return isSafeId(id);\n } catch {\n // This is a public trust-boundary predicate. Hostile accessors fail closed.\n return false;\n }\n }\n\n /**\n * Merge raw form values into the stored document via the Payload\n * REST API. See {@link MergeResult} for the outcome semantics.\n */\n async merge(request: MergeRequest): Promise<MergeResult> {\n if (this.s[MergerSlot.DestroyDepth] > 0) return { status: 'superseded' };\n // Every merge attempt supersedes the previous one, including attempts\n // that fail validation or cannot fetch. Claim attempt ownership before\n // aborting: AbortSignal listeners and request/fetch shims are reentrant and\n // a newer call they start must not be overwritten by this older stack.\n const attempt = this.s[MergerSlot.Attempt] + 1;\n this.s[MergerSlot.Attempt] = attempt;\n const previous = this.s[MergerSlot.Inflight];\n this.s[MergerSlot.Inflight] = null;\n let controller: AbortController | null = null;\n\n try {\n previous?.abort();\n if (!isLatestAttempt(this.s, attempt)) return { status: 'superseded' };\n\n if (!this.canMerge(request)) {\n return isLatestAttempt(this.s, attempt)\n ? { status: 'unavailable' }\n : { status: 'superseded' };\n }\n if (!isLatestAttempt(this.s, attempt)) return { status: 'superseded' };\n const fetchFn =\n this.s[MergerSlot.FetchFn] ?? (typeof fetch === 'function' ? fetch : undefined);\n if (!isLatestAttempt(this.s, attempt)) return { status: 'superseded' };\n if (fetchFn === undefined) return { status: 'unavailable' };\n\n controller = new AbortController();\n if (!isLatestAttempt(this.s, attempt)) {\n controller.abort();\n return { status: 'superseded' };\n }\n this.s[MergerSlot.Inflight] = controller;\n\n const endpoint = request.globalSlug\n ? `globals/${encodeURIComponent(request.globalSlug)}`\n : `${encodeURIComponent(request.collectionSlug ?? '')}/${encodeURIComponent(\n String(request.data['id']),\n )}`;\n const url = `${this.s[MergerSlot.ServerURL]}${this.s[MergerSlot.ApiRoute]}/${endpoint}`;\n const body = JSON.stringify({\n data: request.data,\n depth: this.s[MergerSlot.Depth],\n // The admin already flattens locales before posting.\n flattenLocales: false,\n ...(request.locale !== undefined ? { locale: request.locale } : {}),\n });\n if (!isLatestAttempt(this.s, attempt)) return { status: 'superseded' };\n const response = await fetchFn(url, {\n method: 'POST',\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n // Payload's REST layer treats this POST as a GET with a body:\n // the body's `data` is merged into the stored document and the\n // populated result is returned.\n 'X-Payload-HTTP-Method-Override': 'GET',\n },\n body,\n signal: controller.signal,\n });\n // Fetch implementations are allowed to ignore AbortSignal. Treat the\n // attempt identity as authoritative before observing any response state\n // so a superseded request can never be reported as merged/unavailable.\n if (!isLatestAttempt(this.s, attempt) || isAborted(controller.signal)) {\n return { status: 'superseded' };\n }\n const ok = response.ok;\n if (!isLatestAttempt(this.s, attempt)) return { status: 'superseded' };\n if (!ok) {\n const status = response.status;\n if (!isLatestAttempt(this.s, attempt)) return { status: 'superseded' };\n this.s[MergerSlot.Log]('merge HTTP', status, url);\n if (!isLatestAttempt(this.s, attempt)) return { status: 'superseded' };\n return { status: 'unavailable' };\n }\n const merged: unknown = await response.json();\n // Parsing can be asynchronous too (or supplied by a test/SSR shim) and\n // may likewise ignore cancellation.\n if (!isLatestAttempt(this.s, attempt) || isAborted(controller.signal)) {\n return { status: 'superseded' };\n }\n if (merged === null || typeof merged !== 'object' || Array.isArray(merged)) {\n this.s[MergerSlot.Log]('merge invalid', url);\n if (!isLatestAttempt(this.s, attempt)) return { status: 'superseded' };\n return { status: 'unavailable' };\n }\n return { status: 'merged', doc: merged as Record<string, unknown> };\n } catch (error) {\n if (\n !isLatestAttempt(this.s, attempt) ||\n (controller !== null && isAborted(controller.signal))\n ) {\n return { status: 'superseded' };\n }\n this.s[MergerSlot.Log]('merge exception', error);\n return isLatestAttempt(this.s, attempt)\n ? { status: 'unavailable' }\n : { status: 'superseded' };\n } finally {\n if (\n controller !== null &&\n isLatestAttempt(this.s, attempt) &&\n this.s[MergerSlot.Inflight] === controller\n ) {\n this.s[MergerSlot.Inflight] = null;\n }\n }\n }\n\n /** Abort any in-flight merge request. */\n destroy(): void {\n this.s[MergerSlot.Attempt] += 1;\n const inflight = this.s[MergerSlot.Inflight];\n this.s[MergerSlot.Inflight] = null;\n this.s[MergerSlot.DestroyDepth] += 1;\n try {\n inflight?.abort();\n } finally {\n // DataMerger is reusable by the runtime after a stop/start cycle; only\n // calls entered reentrantly during the abort transaction are rejected.\n this.s[MergerSlot.DestroyDepth] -= 1;\n }\n }\n}\n\nfunction isLatestAttempt(state: DataMergerState, attempt: number): boolean {\n return state[MergerSlot.Attempt] === attempt;\n}\n\nfunction isAborted(signal: AbortSignal): boolean {\n // Keep cancellation checks opaque to static control-flow narrowing: an\n // injected fetch/body parser may await while another task aborts the signal.\n return signal.aborted;\n}\n","/**\n * URL safety validation.\n *\n * Single source of truth for URL-protocol decisions used by both the\n * inline runtime and the high-level client. The previous version of\n * this library had two implementations that subtly disagreed; this\n * module replaces both.\n *\n * Policy:\n * - Allow only the protocols in `SAFE_PROTOCOLS`.\n * - Reject every other protocol explicitly, including `javascript:`,\n * `data:`, `vbscript:`, `file:`, `blob:`, and any custom scheme.\n * - Empty strings are NOT considered safe (this is a tightening from\n * the legacy behaviour and avoids producing `<a href=\"\">` markup).\n *\n * @module @security/url-validator\n */\n\nconst SAFE_PROTOCOLS: ReadonlySet<string> = new Set(['http:', 'https:', 'mailto:', 'tel:']);\n\n// Matches dangerous-scheme prefixes even with leading whitespace that some\n// browsers strip before scheme detection.\nconst DANGEROUS_PROTOCOL_PATTERN = /^\\s*(?:javascript|data|vbscript|file|blob|about)\\s*:/i;\n\nconst RELATIVE_PATH = /^(?:\\.{1,2}\\/|[a-zA-Z0-9_-]+\\/?)/;\n\n/**\n * Returns `true` only when `url` is one of the explicitly allowed forms:\n *\n * - Absolute URL with `http:`, `https:`, `mailto:`, or `tel:` protocol\n * - Protocol-relative URL (`//example.com/...`)\n * - Same-origin absolute path (`/foo`)\n * - Hash or query fragment (`#section`, `?q=1`)\n * - Plain relative path (`foo/bar`, `./foo`, `../foo`)\n */\nexport function isSafeUrl(url: unknown): boolean {\n if (typeof url !== 'string' || url.length === 0) return false;\n const trimmed = url.trim();\n if (trimmed.length === 0) return false;\n\n // Eliminate dangerous schemes before any parsing.\n if (DANGEROUS_PROTOCOL_PATTERN.test(trimmed)) return false;\n\n // Same-document fragments and query-only URLs are always safe.\n if (trimmed.startsWith('#') || trimmed.startsWith('?')) return true;\n\n // Protocol-relative URLs inherit the page scheme; treat as safe.\n if (trimmed.startsWith('//')) return true;\n\n // Same-origin absolute paths are safe.\n if (trimmed.startsWith('/')) return true;\n\n // Try to parse as a fully qualified URL; fall back to a relative-path\n // heuristic if the input has no scheme at all.\n try {\n const parsed = new URL(trimmed);\n return SAFE_PROTOCOLS.has(parsed.protocol);\n } catch {\n return RELATIVE_PATH.test(trimmed);\n }\n}\n\n/**\n * Returns `true` when the URL points to an external HTTP(S) origin.\n * Protocol-relative URLs (`//example.com/...`) count as external —\n * they resolve to another origin and need the same `noopener`\n * hardening as absolute ones.\n *\n * Used by renderers to decide whether to add `target=\"_blank\"` and the\n * `noopener noreferrer` rel attributes to anchors. Inputs that fail\n * `isSafeUrl()` always return `false`.\n */\nexport function isExternalHttpUrl(url: string): boolean {\n if (!isSafeUrl(url)) return false;\n const trimmed = url.trim();\n return /^https?:\\/\\//i.test(trimmed) || /^\\/\\/[^/]/.test(trimmed);\n}\n\n/**\n * The set of protocols this library considers safe. Exposed for tests\n * and consumer introspection; do not mutate.\n */\nexport const SAFE_URL_PROTOCOLS: ReadonlySet<string> = SAFE_PROTOCOLS;\n","/**\n * Policed attribute writes for `data-payload-attribute` bindings.\n *\n * The binding writes an incoming CMS value into an arbitrary attribute\n * (`<img data-payload-field=\"hero\" data-payload-attribute=\"src\">`,\n * `<time ... data-payload-attribute=\"datetime\">`). Because the value is\n * remote-controlled, the write path enforces:\n *\n * - no event handlers (`on*`), no `style`, no `srcdoc`,\n * no `formaction`/`form`, no `id`/`name` (DOM clobbering);\n * - URL-bearing attributes (`href`, `src`, `poster`, `cite`,\n * `action`, `xlink:href`) must pass `isSafeUrl`;\n * - `srcset` is refused outright (multi-URL syntax — bind `src`\n * instead);\n * - non-scalar values are refused.\n *\n * @module @core/attribute-binding\n */\n\nimport { isSafeUrl } from '@security/url-validator';\n\nconst BLOCKED_ATTRIBUTES: ReadonlySet<string> = new Set([\n 'style',\n 'srcdoc',\n 'formaction',\n 'form',\n 'id',\n 'name',\n 'is',\n 'srcset',\n 'imagesrcset',\n]);\n\nconst URL_ATTRIBUTES: ReadonlySet<string> = new Set([\n 'href',\n 'src',\n 'poster',\n 'cite',\n 'action',\n 'xlink:href',\n 'data',\n]);\n\nexport type AttributeApplyResult = 'applied' | 'blocked';\n\n/**\n * Write `value` to `attribute` on `element`, subject to the policy in\n * the module docblock. Returns `'blocked'` (without touching the DOM)\n * when the write is refused.\n */\nexport function applyAttributeBinding(\n element: Element,\n attribute: string,\n value: unknown,\n): AttributeApplyResult {\n const name = attribute.toLowerCase().trim();\n if (name.length === 0) return 'blocked';\n if (name.startsWith('on')) return 'blocked';\n if (BLOCKED_ATTRIBUTES.has(name)) return 'blocked';\n\n if (value === null || value === undefined) {\n element.removeAttribute(name);\n return 'applied';\n }\n if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') {\n return 'blocked';\n }\n const stringValue = String(value);\n\n if (URL_ATTRIBUTES.has(name) && !isSafeUrl(stringValue)) return 'blocked';\n\n element.setAttribute(name, stringValue);\n return 'applied';\n}\n","/**\n * Internal no-write outcome ownership.\n *\n * Public 1.x callbacks deliberately return `void`; JavaScript implementations\n * may nevertheless return arbitrary values. Only callbacks registered through\n * this module may reserve exact `false` as a no-write sentinel. This prevents a\n * custom callback's incidental boolean result from changing lifecycle counts.\n *\n * @module @core/internal-outcome\n */\n\ntype Callback = (...args: never[]) => unknown;\n\nconst noWriteCallbacks = new WeakSet<Callback>();\n\n/** Mark a package-owned callback whose exact `false` return means no write. */\nexport function markNoWriteCallback<T extends Callback>(callback: T): T {\n noWriteCallbacks.add(callback);\n return callback;\n}\n\n/** Whether `callback` owns the internal exact-false sentinel contract. */\nexport function usesNoWriteOutcome(callback: Callback): boolean {\n return noWriteCallbacks.has(callback);\n}\n\n/** Check a renderer object without detaching its public method at the call site. */\nexport function rendererUsesNoWriteOutcome(renderer: { readonly render: Callback }): boolean {\n return noWriteCallbacks.has(renderer.render);\n}\n","/**\n * Update scheduler — debounce + RAF batching + offscreen replay.\n *\n * The scheduler is the heart of the update pipeline:\n *\n * 1. Incoming updates are debounced. Rapid typing in the admin\n * panel collapses into a single DOM write per debounce window.\n * 2. After the debounce, the actual writes run inside\n * `requestAnimationFrame` so they batch with the browser's\n * paint cycle.\n * 3. Elements that are not currently within the viewport are not\n * written — their *latest* value is stored in a per-element\n * replay buffer. When the element becomes visible, the buffered\n * value is applied. This fixes the stale-offscreen-content bug\n * from the legacy implementation.\n *\n * The scheduler does not touch the DOM directly. It calls an injected\n * `applyUpdate(target, value)` function so renderer dispatch lives\n * outside this module, keeping the scheduler dependency-free and\n * easily testable.\n *\n * @module @core/update-scheduler\n */\n\nimport type { CachedElement } from './types';\nimport type { MessageRevision } from './message-bus';\nimport type { PayloadLivePreviewData } from '@/types/payload-protocol';\nimport { usesNoWriteOutcome } from './internal-outcome';\n\nexport interface ScheduledUpdate {\n readonly target: CachedElement;\n readonly value: unknown;\n readonly allFields: Record<string, unknown>;\n /** Lifecycle identity. Runtime-produced entries always include this. */\n readonly identity?: MessageRevision | undefined;\n /** Stable merged-or-fallback snapshot associated with `identity`. */\n readonly data?: PayloadLivePreviewData | undefined;\n}\n\n/**\n * Function the scheduler invokes to apply a single update.\n *\n * Renderer dispatch and any sanitization happens inside this callback;\n * the scheduler is intentionally ignorant of field types.\n */\nexport type ApplyUpdate = (update: ScheduledUpdate) => void;\n\nexport interface UpdateSchedulerOptions {\n /** Debounce window in ms. Default: 50. */\n readonly debounceMs?: number;\n /**\n * Visibility predicate. The scheduler defers updates for elements\n * that return `false` here, replaying them when the host signals\n * visibility via `notifyVisible()`.\n */\n readonly isVisible: (element: Element) => boolean;\n /**\n * `true` to skip the visibility optimization (apply every update\n * immediately regardless of viewport). Useful for tests and for\n * pages with few bindings. Default: `false`.\n */\n readonly disableVisibilityGate?: boolean;\n /** Threshold (in cached elements) above which the gate activates. Default: 50. */\n readonly visibilityGateThreshold?: number;\n /** Function returning the current cache size (used by the threshold). */\n readonly getCacheSize: () => number;\n /** Hook fired after every flush. Used by tests + analytics. */\n readonly onFlush?: (stats: FlushStats) => void;\n /**\n * Function used to schedule the actual DOM-write callback. Defaults\n * to `requestAnimationFrame` when available. Tests inject a synchronous\n * stand-in.\n */\n readonly scheduleFrame?: (callback: FrameRequestCallback) => number;\n /** Counterpart to `scheduleFrame` for cancellation. */\n readonly cancelFrame?: (handle: number) => void;\n}\n\nexport interface FlushStats {\n readonly applied: number;\n /**\n * Field names this flush actually applied, in application order.\n *\n * `applied` alone cannot distinguish \"the field was written\" from \"the\n * field was never scheduled\": a flush that applies three entries and a\n * binding that stays stale are consistent with either. The names settle it.\n */\n readonly appliedFields: readonly string[];\n readonly deferred: number;\n readonly durationMs: number;\n readonly identity?: MessageRevision;\n readonly data?: PayloadLivePreviewData;\n}\n\nconst DEFAULT_DEBOUNCE_MS = 50;\n/**\n * Binding count above which the gate starts deferring offscreen writes.\n *\n * Exported so `pll doctor`'s test can prove its own copy of this number has\n * not drifted. The audit runs outside the runtime bundle and restates the\n * value rather than importing it.\n */\nexport const DEFAULT_VISIBILITY_THRESHOLD = 50;\n\n/**\n * Buffer entry — one per (field, element) pair. The latest write\n * supersedes any pending one.\n */\ninterface BufferEntry {\n target: CachedElement;\n value: unknown;\n allFields: Record<string, unknown>;\n identity: MessageRevision | undefined;\n data: PayloadLivePreviewData | undefined;\n}\n\nconst enum SchedulerSlot {\n Apply,\n DebounceMs,\n IsVisible,\n GateThreshold,\n GateDisabled,\n GetCacheSize,\n OnFlush,\n ScheduleFrame,\n CancelFrame,\n Pending,\n Replay,\n ActiveFlushes,\n DebounceTimer,\n DebounceToken,\n FrameHandle,\n FrameToken,\n ActiveIdentity,\n ActiveRevisionCancelled,\n}\n\n/**\n * One TS-private state record avoids emitting ES2020 private-field scaffolding.\n * Named tuple slots keep the source readable while compiling to compact numeric\n * access; this internal class and its tuple never cross the package boundary.\n */\ntype SchedulerState = [\n apply: ApplyUpdate,\n debounceMs: number,\n isVisible: (element: Element) => boolean,\n gateThreshold: number,\n gateDisabled: boolean,\n getCacheSize: () => number,\n onFlush: ((stats: FlushStats) => void) | undefined,\n scheduleFrame: (callback: FrameRequestCallback) => number,\n cancelFrame: (handle: number) => void,\n pending: Map<Element, BufferEntry>,\n replay: Map<Element, BufferEntry>,\n activeFlushes: Set<Map<Element, BufferEntry>>,\n debounceTimer: ReturnType<typeof setTimeout> | null,\n debounceToken: number,\n frameHandle: number | null,\n frameToken: number,\n activeIdentity: MessageRevision | null,\n activeRevisionCancelled: boolean,\n];\n\nexport class UpdateScheduler {\n private readonly s: SchedulerState;\n\n constructor(apply: ApplyUpdate, options: UpdateSchedulerOptions) {\n const scheduleFrame =\n options.scheduleFrame ??\n (typeof requestAnimationFrame === 'function'\n ? requestAnimationFrame.bind(globalThis)\n : (cb) => {\n return setTimeout(() => {\n cb(performance.now());\n }, 0) as unknown as number;\n });\n const cancelFrame =\n options.cancelFrame ??\n (typeof cancelAnimationFrame === 'function'\n ? cancelAnimationFrame.bind(globalThis)\n : (handle) => {\n clearTimeout(handle as unknown as ReturnType<typeof setTimeout>);\n });\n this.s = [\n apply,\n options.debounceMs ?? DEFAULT_DEBOUNCE_MS,\n options.isVisible,\n options.visibilityGateThreshold ?? DEFAULT_VISIBILITY_THRESHOLD,\n options.disableVisibilityGate ?? false,\n options.getCacheSize,\n options.onFlush,\n scheduleFrame,\n cancelFrame,\n new Map(),\n new Map(),\n new Set(),\n null,\n 0,\n null,\n 0,\n null,\n false,\n ];\n }\n\n /**\n * Queue an update. The same `(element)` pair is coalesced — only the\n * most-recent value survives until the next flush.\n */\n schedule(update: ScheduledUpdate): void {\n if (update.identity !== undefined) {\n if (this.s[SchedulerSlot.ActiveRevisionCancelled]) return;\n if (!sameIdentity(update.identity, this.s[SchedulerSlot.ActiveIdentity])) return;\n }\n const pending = this.s[SchedulerSlot.Pending];\n const existing = pending.get(update.target.element);\n if (existing) {\n existing.value = update.value;\n existing.allFields = update.allFields;\n existing.identity = update.identity;\n existing.data = update.data;\n } else {\n pending.set(update.target.element, {\n ...update,\n // BufferEntry makes these keys explicit so coalescing can overwrite\n // them deterministically even when an older entry had a value.\n identity: update.identity,\n data: update.data,\n });\n }\n this.#armDebounce();\n }\n\n /**\n * Make `identity` the sole revision allowed to schedule, flush, or replay.\n * Advancing is intentionally destructive even when the new revision is later\n * cancelled: accepting newer work must never revive an older DOM state.\n */\n acceptRevision(identity: MessageRevision): void {\n const activeIdentity = this.s[SchedulerSlot.ActiveIdentity];\n if (sameIdentity(identity, activeIdentity)) return;\n if (activeIdentity !== null && compareIdentity(identity, activeIdentity) < 0) {\n return;\n }\n this.#cancelScheduledWork();\n this.#clearWork();\n this.s[SchedulerSlot.ActiveIdentity] = identity;\n this.s[SchedulerSlot.ActiveRevisionCancelled] = false;\n }\n\n /** Cancel buffered work for exactly one revision without reviving its predecessor. */\n cancelRevision(identity: MessageRevision): void {\n if (!sameIdentity(identity, this.s[SchedulerSlot.ActiveIdentity])) return;\n this.#cancelScheduledWork();\n this.#clearWork();\n this.s[SchedulerSlot.ActiveRevisionCancelled] = true;\n }\n\n /**\n * Flush every pending write immediately, bypassing the debounce.\n * Useful for tests and explicit host-controlled flushing. `destroy()`\n * deliberately discards buffered work instead of draining it.\n */\n flushNow(): FlushStats {\n this.#cancelScheduledWork();\n return this.#flush();\n }\n\n /**\n * Signal that an element has become visible. Any buffered value for\n * that element is applied immediately.\n */\n notifyVisible(element: Element): void {\n const replay = this.s[SchedulerSlot.Replay];\n const entry = replay.get(element);\n if (!entry) return;\n replay.delete(element);\n if (!this.#isCurrent(entry)) return;\n const t0 = performance.now();\n const applied = this.#didApply(entry) ? 1 : 0;\n this.s[SchedulerSlot.OnFlush]?.(\n this.#statsFor(\n entry,\n applied,\n 0,\n performance.now() - t0,\n applied === 1 ? [entry.target.fieldName] : [],\n ),\n );\n }\n\n /**\n * Reconcile buffered work with a freshly rebuilt cache entry.\n *\n * A full cache scan deliberately creates new `CachedElement` snapshots. Work\n * for the same element + field binding survives, but must point at that fresh\n * snapshot so changed renderer/attribute/locale metadata is respected. A\n * field-name change is a different binding and therefore discards the stale\n * work rather than applying it under a new identity.\n */\n retarget(target: CachedElement): void {\n this.#retargetBuffer(this.s[SchedulerSlot.Pending], target);\n this.#retargetBuffer(this.s[SchedulerSlot.Replay], target);\n for (const flush of this.s[SchedulerSlot.ActiveFlushes]) {\n this.#retargetBuffer(flush, target);\n }\n }\n\n /**\n * Discard any replay state for an element. Called when the element\n * leaves the cache.\n */\n forget(element: Element): void {\n this.s[SchedulerSlot.Pending].delete(element);\n this.s[SchedulerSlot.Replay].delete(element);\n for (const flush of this.s[SchedulerSlot.ActiveFlushes]) flush.delete(element);\n }\n\n /** Cancel timers and drop buffered state. */\n destroy(): void {\n this.#cancelScheduledWork();\n this.#clearWork();\n this.s[SchedulerSlot.ActiveIdentity] = null;\n this.s[SchedulerSlot.ActiveRevisionCancelled] = false;\n }\n\n /** Test introspection: number of pending writes. */\n get pendingCount(): number {\n return this.s[SchedulerSlot.Pending].size;\n }\n\n /** Test introspection: number of buffered offscreen replays. */\n get replayCount(): number {\n return this.s[SchedulerSlot.Replay].size;\n }\n\n /** Binding count above which the visibility gate starts deferring writes. */\n get gateThreshold(): number {\n return this.s[SchedulerSlot.GateThreshold];\n }\n\n /**\n * Whether the gate is deferring right now. Mirrors the condition in\n * `#flush()` so a diagnostic read cannot drift from the real decision.\n */\n get gateActive(): boolean {\n return (\n !this.s[SchedulerSlot.GateDisabled] &&\n this.s[SchedulerSlot.GetCacheSize]() > this.s[SchedulerSlot.GateThreshold]\n );\n }\n\n #armDebounce(): void {\n const token = (this.s[SchedulerSlot.DebounceToken] += 1);\n const timer = this.s[SchedulerSlot.DebounceTimer];\n this.s[SchedulerSlot.DebounceTimer] = null;\n if (timer !== null) clearTimeout(timer);\n // Clearing a host timer is an external boundary. A re-entrant schedule\n // owns a newer token and must not be replaced by this older stack.\n if (this.s[SchedulerSlot.DebounceToken] !== token) return;\n const nextTimer = setTimeout(() => {\n if (this.s[SchedulerSlot.DebounceToken] !== token) return;\n this.s[SchedulerSlot.DebounceTimer] = null;\n this.#requestFrame();\n }, this.s[SchedulerSlot.DebounceMs]);\n if (this.s[SchedulerSlot.DebounceToken] === token) {\n this.s[SchedulerSlot.DebounceTimer] = nextTimer;\n }\n }\n\n #requestFrame(): void {\n const token = (this.s[SchedulerSlot.FrameToken] += 1);\n const handle = this.s[SchedulerSlot.FrameHandle];\n this.s[SchedulerSlot.FrameHandle] = null;\n if (handle !== null) this.s[SchedulerSlot.CancelFrame](handle);\n if (this.s[SchedulerSlot.FrameToken] !== token) return;\n // Test/SSR schedulers may invoke the callback before returning a handle.\n // Never publish that already-completed handle as cancellable work.\n let completed = false;\n const nextHandle = this.s[SchedulerSlot.ScheduleFrame](() => {\n if (this.s[SchedulerSlot.FrameToken] !== token) return;\n completed = true;\n this.s[SchedulerSlot.FrameHandle] = null;\n this.#flush();\n });\n // The injected scheduler can execute the callback synchronously, which\n // TypeScript's local control-flow analysis cannot observe.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!completed && this.s[SchedulerSlot.FrameToken] === token) {\n this.s[SchedulerSlot.FrameHandle] = nextHandle;\n }\n }\n\n #flush(): FlushStats {\n const t0 = performance.now();\n const gateActive =\n !this.s[SchedulerSlot.GateDisabled] &&\n this.s[SchedulerSlot.GetCacheSize]() > this.s[SchedulerSlot.GateThreshold];\n const pending = this.s[SchedulerSlot.Pending];\n this.s[SchedulerSlot.Pending] = new Map();\n\n let applied = 0;\n const appliedFields: string[] = [];\n let deferred = 0;\n let batchEntry: BufferEntry | undefined;\n this.s[SchedulerSlot.ActiveFlushes].add(pending);\n try {\n for (const entry of pending.values()) {\n if (!this.#isCurrent(entry)) continue;\n const visible = !gateActive || this.s[SchedulerSlot.IsVisible](entry.target.element);\n // Visibility is an injected consumer callback and may accept/cancel a\n // revision synchronously. Re-check before publishing replay or writes.\n if (!this.#isCurrent(entry)) continue;\n batchEntry ??= entry;\n if (!visible) {\n this.s[SchedulerSlot.Replay].set(entry.target.element, entry);\n deferred += 1;\n continue;\n }\n // A visible write for this element supersedes any older replay entry,\n // including legacy/unversioned callers of the scheduler.\n this.s[SchedulerSlot.Replay].delete(entry.target.element);\n if (this.#didApply(entry)) {\n applied += 1;\n appliedFields.push(entry.target.fieldName);\n }\n }\n } finally {\n this.s[SchedulerSlot.ActiveFlushes].delete(pending);\n }\n const stats = this.#statsFor(\n batchEntry,\n applied,\n deferred,\n performance.now() - t0,\n appliedFields,\n );\n this.s[SchedulerSlot.OnFlush]?.(stats);\n return stats;\n }\n\n #isCurrent(entry: BufferEntry): boolean {\n return (\n entry.identity === undefined ||\n (!this.s[SchedulerSlot.ActiveRevisionCancelled] &&\n sameIdentity(entry.identity, this.s[SchedulerSlot.ActiveIdentity]))\n );\n }\n\n #didApply(entry: BufferEntry): boolean {\n // The public callback remains `void`; only a package-owned callback marked\n // by the runtime may reserve exact false as a rejected/no-write result.\n const apply = this.s[SchedulerSlot.Apply];\n // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression\n const outcome: unknown = apply(entry);\n return outcome !== false || !usesNoWriteOutcome(apply);\n }\n\n #retargetBuffer(buffer: Map<Element, BufferEntry>, target: CachedElement): void {\n const entry = buffer.get(target.element);\n if (entry === undefined) return;\n if (entry.target.fieldName !== target.fieldName || entry.target.locale !== target.locale) {\n // Locale selects the value before scheduling and can also affect plugin\n // transforms. Retargeting only the metadata would pair a value prepared\n // for the old locale with the new locale. Discard that work; a later\n // revision can prepare the new binding coherently.\n buffer.delete(target.element);\n return;\n }\n entry.target = target;\n }\n\n #clearWork(): void {\n this.s[SchedulerSlot.Pending].clear();\n this.s[SchedulerSlot.Replay].clear();\n for (const flush of this.s[SchedulerSlot.ActiveFlushes]) flush.clear();\n }\n\n #statsFor(\n entry: BufferEntry | undefined,\n applied: number,\n deferred: number,\n durationMs: number,\n appliedFields: readonly string[],\n ): FlushStats {\n return {\n applied,\n appliedFields,\n deferred,\n durationMs,\n ...(entry?.identity !== undefined ? { identity: entry.identity } : {}),\n ...(entry?.data !== undefined ? { data: entry.data } : {}),\n };\n }\n\n #cancelScheduledWork(): void {\n const debounceTimer = this.s[SchedulerSlot.DebounceTimer];\n const frameHandle = this.s[SchedulerSlot.FrameHandle];\n // Revoke both ownership tokens and handles before calling cancellation\n // hooks. Ineffectively-cancelled callbacks remain inert; re-entrant newer\n // work published by a hook is not clobbered by this older cleanup stack.\n this.s[SchedulerSlot.DebounceToken] += 1;\n this.s[SchedulerSlot.FrameToken] += 1;\n this.s[SchedulerSlot.DebounceTimer] = null;\n this.s[SchedulerSlot.FrameHandle] = null;\n if (debounceTimer !== null) clearTimeout(debounceTimer);\n if (frameHandle !== null) this.s[SchedulerSlot.CancelFrame](frameHandle);\n }\n}\n\nfunction sameIdentity(a: MessageRevision, b: MessageRevision | null): boolean {\n return b !== null && a.generation === b.generation && a.revision === b.revision;\n}\n\nfunction compareIdentity(a: MessageRevision, b: MessageRevision): number {\n if (a.generation !== b.generation) return a.generation - b.generation;\n return a.revision - b.revision;\n}\n","/**\n * Safe field-path resolution shared by lifecycle bindings and sibling-field\n * renderer metadata.\n *\n * @module @core/field-value\n */\n\nconst BLOCKED_KEYS: ReadonlySet<string> = new Set(['__proto__', 'prototype', 'constructor']);\n\n/**\n * Resolve a field value from an update payload, walking nested dotted paths\n * and trying a locale-suffixed top-level fallback when a locale is active.\n * Prototype-chain properties and pollution-sensitive path segments are never\n * traversed.\n */\nexport function resolveFieldValue(\n fields: Record<string, unknown>,\n path: string,\n locale: string | undefined,\n preferLocale = false,\n): unknown {\n if (preferLocale && locale !== undefined) {\n const localized = readOwn(fields, `${path}_${locale}`);\n if (localized !== undefined) return localized;\n }\n const direct = readOwn(fields, path);\n if (direct !== undefined) return direct;\n\n if (path.includes('.')) {\n let current: unknown = fields;\n let resolved = true;\n for (const segment of path.split('.')) {\n if (BLOCKED_KEYS.has(segment) || current === null || typeof current !== 'object') {\n resolved = false;\n break;\n }\n current = readOwn(current as Record<string, unknown>, segment);\n if (current === undefined) {\n resolved = false;\n break;\n }\n }\n if (resolved) return current;\n }\n\n return locale === undefined ? undefined : readOwn(fields, `${path}_${locale}`);\n}\n\nfunction readOwn(object: Record<string, unknown>, key: string): unknown {\n if (BLOCKED_KEYS.has(key) || !Object.prototype.hasOwnProperty.call(object, key)) {\n return undefined;\n }\n return object[key];\n}\n","/**\n * Locale detection.\n *\n * The runtime needs a sensible default locale for date/number renders\n * before Payload tells us the active locale. Order of precedence:\n *\n * 1. The `lang` attribute on `<html>`.\n * 2. `navigator.language`.\n * 3. The hard-coded fallback `'en'`.\n *\n * The previous version of this library defaulted to `'de'` — a German\n * default that surprised consumers in other locales. We now use the\n * browser hint and fall back to English.\n *\n * @module @detection/locale\n */\n\nconst FALLBACK_LOCALE = 'en';\n\n/**\n * Returns a BCP-47 locale string suitable for `Intl.*` constructors.\n *\n * Always returns a non-empty string. When no signal is available the\n * fallback (`'en'`) is returned.\n */\nexport function detectInitialLocale(): string {\n const fromHtml = readHtmlLang();\n if (fromHtml !== undefined) return fromHtml;\n const fromNavigator = readNavigatorLanguage();\n if (fromNavigator !== undefined) return fromNavigator;\n return FALLBACK_LOCALE;\n}\n\nfunction readHtmlLang(): string | undefined {\n if (typeof document === 'undefined') return undefined;\n const lang = document.documentElement.getAttribute('lang');\n return lang === null || lang.length === 0 ? undefined : lang;\n}\n\nfunction readNavigatorLanguage(): string | undefined {\n if (typeof navigator === 'undefined') return undefined;\n const lang = navigator.language;\n return typeof lang === 'string' && lang.length > 0 ? lang : undefined;\n}\n","/**\n * Screen-reader live region.\n *\n * Mounts a single visually-hidden `<div role=\"status\" aria-live=\"polite\">`\n * into the document and pushes short messages to it on connect /\n * after-update / disconnect events.\n *\n * Why this matters: an editor using assistive technology hears\n * \"Vorschau verbunden\" / \"5 Inhalte aktualisiert\" instead of silently\n * watching the page mutate. The v0.1.0 line had this feature; the\n * 1.0.0 rewrite restores it.\n *\n * Design rules:\n * - **Exactly one** live region per document, regardless of how many\n * `LivePreviewClient` instances run on the page. Every announcer leases\n * that region independently.\n * - Polite — never interrupts ongoing speech (`aria-live=\"polite\"`).\n * - Throttled — clears itself after a short window so re-announcement\n * of the same string is heard a second time. Without the clear,\n * screen readers de-duplicate identical messages.\n * - Localized — strings come from the active locale via\n * `detectInitialLocale()`. Untranslated locales fall back to\n * English.\n *\n * @module @core/a11y\n */\n\nimport { detectInitialLocale } from '@detection/locale';\n\nconst ELEMENT_ID = 'payload-live-preview-a11y';\nconst CLEAR_DELAY_MS = 1500;\nconst STYLE =\n 'position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;' +\n 'clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap;border:0';\n\nfunction isGerman(locale: string): boolean {\n return /^de(?:[-_]|$)/i.test(locale);\n}\n\nconst enum LeaseSlot {\n Element,\n Owned,\n MessageNode,\n Refs,\n Timer,\n}\n\ntype DocumentLease = [\n element: HTMLElement | null,\n owned: boolean,\n messageNode: Text | null,\n refs: number,\n timer: ReturnType<typeof setTimeout> | null,\n];\n\nconst enum AnnouncerSlot {\n German,\n Document,\n Lease,\n}\n\ntype AnnouncerState = [german: boolean, document: Document | null, lease: DocumentLease | null];\n\n/**\n * DOM-keyed coordination must not retain discarded documents. The lease owns the\n * one shared timer as well as the region ownership flag, so one client can neither\n * clear a newer announcement nor remove a region that another client still uses.\n */\nconst documentLeases = new WeakMap<Document, DocumentLease>();\n\nfunction acquireDocumentLease(activeDocument: Document): DocumentLease {\n let lease = documentLeases.get(activeDocument);\n lease ??= [null, false, null, 0, null];\n documentLeases.set(activeDocument, lease);\n lease[LeaseSlot.Refs] += 1;\n return lease;\n}\n\n/** Remove only the package-owned message node, never consumer child nodes. */\nfunction clearLeaseMessage(lease: DocumentLease): void {\n if (lease[LeaseSlot.Timer] !== null) {\n clearTimeout(lease[LeaseSlot.Timer]);\n lease[LeaseSlot.Timer] = null;\n }\n lease[LeaseSlot.MessageNode]?.remove();\n lease[LeaseSlot.MessageNode] = null;\n}\n\n/**\n * Per-document live region. Announcers that successfully mount share a\n * reference-counted lease until each one detaches.\n */\nexport class A11yAnnouncer {\n // This class is internal to the runtime bundle. TypeScript-private members\n // preserve encapsulation without forcing ES2020 builds to lower every field\n // and method into separate WeakMaps/WeakSets.\n private readonly s: AnnouncerState;\n\n constructor(locale?: string, targetDocument?: Document | null) {\n const activeDocument = targetDocument ?? (typeof document === 'undefined' ? null : document);\n const documentLocale = activeDocument?.documentElement.getAttribute('lang') ?? '';\n this.s = [\n isGerman(locale ?? (documentLocale.length > 0 ? documentLocale : detectInitialLocale())),\n activeDocument,\n null,\n ];\n // The live region is mounted lazily on first announcement: the\n // announcer is constructed during runtime bootstrap, which can run\n // from a <head> inline script while `document.body` is still null.\n }\n\n /**\n * Create (or adopt) the shared live-region element. Returns `null`\n * when no DOM is available yet — announcements are then dropped,\n * which is fine: they are progress niceties, not state.\n */\n private mount(): HTMLElement | null {\n // lib.dom types body as always-present, but during <head> execution\n // it genuinely is null.\n const activeDocument = this.s[AnnouncerSlot.Document];\n if (activeDocument?.body == null) return null;\n\n let lease = this.s[AnnouncerSlot.Lease];\n if (lease === null) {\n lease = acquireDocumentLease(activeDocument);\n this.s[AnnouncerSlot.Lease] = lease;\n }\n\n const leasedElement = lease[LeaseSlot.Element];\n if (leasedElement?.isConnected && leasedElement.ownerDocument === activeDocument) {\n return leasedElement;\n }\n\n // A host can remove or replace the adopted region between announcements.\n // Revoke only our node before leasing the current element.\n if (leasedElement !== null) {\n const owned = lease[LeaseSlot.Owned];\n clearLeaseMessage(lease);\n if (owned) leasedElement.remove();\n }\n\n let element: HTMLElement | null = activeDocument.getElementById(ELEMENT_ID);\n lease[LeaseSlot.Owned] = element === null;\n if (!element) {\n element = activeDocument.createElement('div');\n element.id = ELEMENT_ID;\n element.setAttribute('role', 'status');\n element.setAttribute('aria-live', 'polite');\n element.setAttribute('aria-atomic', 'true');\n element.setAttribute('style', STYLE);\n activeDocument.body.appendChild(element);\n }\n lease[LeaseSlot.Element] = element;\n return element;\n }\n\n /** Announce that the preview successfully connected. */\n announceConnected(): void {\n this.say(this.s[AnnouncerSlot.German] ? 'Vorschau verbunden' : 'Live preview connected');\n }\n\n /** Announce that the preview lost its connection. */\n announceDisconnected(): void {\n this.say(this.s[AnnouncerSlot.German] ? 'Vorschau getrennt' : 'Live preview disconnected');\n }\n\n /** Announce that `count` updates were applied. */\n announceUpdate(count: number): void {\n if (count <= 0) return;\n this.say(\n this.s[AnnouncerSlot.German]\n ? `${String(count)} ${count === 1 ? 'Änderung' : 'Änderungen'} angewendet`\n : `${String(count)} ${count === 1 ? 'change' : 'changes'} applied`,\n );\n }\n\n /**\n * Release this announcer's live-region lease. The final release removes a\n * package-owned region but leaves an adopted consumer element in place.\n * Called by the runtime during `destroy()`. Idempotent.\n */\n detach(): void {\n const lease = this.s[AnnouncerSlot.Lease];\n const activeDocument = this.s[AnnouncerSlot.Document];\n if (lease === null || activeDocument === null) return;\n\n // Clear local ownership first so re-entrant or repeated detach calls cannot\n // release somebody else's reference.\n this.s[AnnouncerSlot.Lease] = null;\n lease[LeaseSlot.Refs] -= 1;\n if (lease[LeaseSlot.Refs] > 0) return;\n\n const element = lease[LeaseSlot.Element];\n if (element !== null) clearLeaseMessage(lease);\n if (lease[LeaseSlot.Owned]) element?.remove();\n lease[LeaseSlot.Element] = null;\n documentLeases.delete(activeDocument);\n }\n\n private say(message: string): void {\n const element = this.mount();\n const lease = this.s[AnnouncerSlot.Lease];\n if (element === null || lease === null) return;\n\n let messageNode = lease[LeaseSlot.MessageNode];\n if (messageNode?.parentNode !== element) {\n // If consumer code reparented our prior node, it remains package-owned:\n // revoke it before replacing the lease pointer so detach cannot orphan it.\n messageNode?.remove();\n // Appending a dedicated text node leaves every consumer-owned child in\n // place throughout the announcement, preserving identity and listeners.\n messageNode = element.ownerDocument.createTextNode(\n element.hasChildNodes() ? ` ${message}` : message,\n );\n lease[LeaseSlot.MessageNode] = messageNode;\n element.appendChild(messageNode);\n } else {\n messageNode.data = messageNode.previousSibling === null ? message : ` ${message}`;\n }\n if (lease[LeaseSlot.Timer] !== null) clearTimeout(lease[LeaseSlot.Timer]);\n const timer = setTimeout(() => {\n if (lease[LeaseSlot.Timer] === timer && lease[LeaseSlot.Element] === element) {\n clearLeaseMessage(lease);\n }\n }, CLEAR_DELAY_MS);\n lease[LeaseSlot.Timer] = timer;\n }\n}\n","/**\n * Schema walker.\n *\n * Walks a parsed Payload field schema and produces a flat index from\n * dotted-path field names (e.g., `hero.title`, `sections.0.heading`)\n * to the corresponding schema descriptor.\n *\n * The index is consumed by:\n * - The runtime, to decide which field-type renderer applies.\n * - The diff engine, to know when a structural change occurred.\n *\n * Tabs/rows/collapsibles are *structural* fields that have no `name`;\n * they are flattened into their inner fields.\n *\n * @module @schema/walker\n */\n\nimport type {\n PayloadBlockSchema,\n PayloadFieldSchema,\n PayloadFieldType,\n} from '@/types/payload-protocol';\n\n/**\n * Read-only view of a flattened schema. Keys are dotted-paths;\n * values are the original schema entries.\n */\nexport type SchemaIndex = ReadonlyMap<string, PayloadFieldSchema>;\n\nconst STRUCTURAL_TYPES: ReadonlySet<PayloadFieldType> = new Set<PayloadFieldType>([\n 'tabs',\n 'row',\n 'collapsible',\n]);\n\n/**\n * Walk `schemas` recursively and build a flat index. The base path is\n * appended to every produced key. Pass an empty string at the\n * top-level entry point.\n */\nexport function buildSchemaIndex(\n schemas: readonly PayloadFieldSchema[],\n basePath = '',\n): SchemaIndex {\n const out = new Map<string, PayloadFieldSchema>();\n walk(schemas, basePath, out);\n return out;\n}\n\nfunction walk(\n schemas: readonly PayloadFieldSchema[],\n basePath: string,\n out: Map<string, PayloadFieldSchema>,\n): void {\n for (const schema of schemas) {\n if (STRUCTURAL_TYPES.has(schema.type)) {\n if (schema.fields) walk(schema.fields, basePath, out);\n continue;\n }\n if (schema.type === 'group') {\n const path = basePath === '' ? schema.name : `${basePath}.${schema.name}`;\n out.set(path, schema);\n if (schema.fields) walk(schema.fields, path, out);\n continue;\n }\n const path = basePath === '' ? schema.name : `${basePath}.${schema.name}`;\n out.set(path, schema);\n if (schema.type === 'array' && schema.fields) {\n walk(schema.fields, `${path}.*`, out);\n } else if (schema.type === 'blocks' && schema.blocks) {\n for (const block of schema.blocks) {\n walk(block.fields, `${path}.*.${block.slug}`, out);\n }\n }\n }\n}\n\n/**\n * Look up the schema entry for `fieldPath`, walking through array\n * (`.*`) and block (`.*.<slug>`) segments. Returns `undefined` when\n * the path is not represented in the schema.\n */\nexport function lookupSchema(\n index: SchemaIndex,\n fieldPath: string,\n): PayloadFieldSchema | undefined {\n if (index.has(fieldPath)) return index.get(fieldPath);\n // Replace array indices (numeric segments) with wildcards.\n const wildcardPath = fieldPath.replace(/\\.\\d+(?=\\.|$)/g, '.*');\n if (index.has(wildcardPath)) return index.get(wildcardPath);\n return undefined;\n}\n\n/**\n * Discover the block schema for a `blocks` field at `arrayPath`,\n * given the runtime value carries a `blockType` discriminator.\n */\nexport function lookupBlockSchema(\n index: SchemaIndex,\n blocksFieldPath: string,\n blockType: string,\n): PayloadBlockSchema | undefined {\n const schema = lookupSchema(index, blocksFieldPath);\n if (!schema?.blocks) return undefined;\n return schema.blocks.find((b) => b.slug === blockType);\n}\n","/**\n * Structural diff for arrays and blocks.\n *\n * Compares the previous and next data shapes for an array field and\n * produces a minimal patch describing what changed:\n *\n * - `insert` → an item was inserted at index `i`\n * - `remove` → an item was removed at index `i`\n * - `move` → an item moved from `from` to `to`\n * - `update` → an item at index `i` had its scalar fields change\n * - `replace` → an item's block-type changed; treat as remove + insert\n *\n * The diff is *id-keyed* when items carry an `id` field (Payload's\n * default) — that lets us detect moves reliably. Without ids we fall\n * back to a positional diff.\n *\n * @module @schema/diff\n */\n\nexport type ArrayPatch =\n | { readonly kind: 'insert'; readonly index: number; readonly value: unknown }\n | { readonly kind: 'remove'; readonly index: number; readonly value: unknown }\n | {\n readonly kind: 'move';\n readonly from: number;\n readonly to: number;\n readonly value: unknown;\n }\n | { readonly kind: 'update'; readonly index: number; readonly value: unknown }\n | {\n readonly kind: 'replace';\n readonly index: number;\n readonly oldValue: unknown;\n readonly value: unknown;\n };\n\n/**\n * Identify items by their `id` field when present.\n */\nfunction getId(item: unknown): string | number | undefined {\n if (typeof item !== 'object' || item === null) return undefined;\n const id = (item as Record<string, unknown>)['id'];\n if (typeof id === 'string' || typeof id === 'number') return id;\n return undefined;\n}\n\nfunction getBlockType(item: unknown): string | undefined {\n if (typeof item !== 'object' || item === null) return undefined;\n const blockType = (item as Record<string, unknown>)['blockType'];\n return typeof blockType === 'string' ? blockType : undefined;\n}\n\n/**\n * Compute the patch transforming `prev` into `next`.\n *\n * - When items have stable `id` values, moves and updates are\n * detected accurately.\n * - When ids are absent, the diff is positional (replacement-only),\n * which still keeps the host consistent but cannot animate moves.\n */\nexport function diffArray(\n prev: readonly unknown[],\n next: readonly unknown[],\n): readonly ArrayPatch[] {\n const haveIds = next.every((item) => getId(item) !== undefined);\n if (haveIds) return diffById(prev, next);\n return diffByPosition(prev, next);\n}\n\nfunction diffById(prev: readonly unknown[], next: readonly unknown[]): readonly ArrayPatch[] {\n const patches: ArrayPatch[] = [];\n const prevIndexById = new Map<string | number, number>();\n for (let i = 0; i < prev.length; i += 1) {\n const id = getId(prev[i]);\n if (id !== undefined) prevIndexById.set(id, i);\n }\n\n const consumedFromPrev = new Set<number>();\n for (let to = 0; to < next.length; to += 1) {\n const item = next[to];\n const id = getId(item);\n if (id === undefined) {\n patches.push({ kind: 'insert', index: to, value: item });\n continue;\n }\n const from = prevIndexById.get(id);\n if (from === undefined) {\n patches.push({ kind: 'insert', index: to, value: item });\n continue;\n }\n consumedFromPrev.add(from);\n const prevItem = prev[from];\n if (getBlockType(prevItem) !== getBlockType(item)) {\n patches.push({ kind: 'replace', index: to, oldValue: prevItem, value: item });\n continue;\n }\n if (from !== to) {\n patches.push({ kind: 'move', from, to, value: item });\n }\n if (!shallowEqual(prevItem, item)) {\n patches.push({ kind: 'update', index: to, value: item });\n }\n }\n\n for (let i = 0; i < prev.length; i += 1) {\n if (consumedFromPrev.has(i)) continue;\n patches.push({ kind: 'remove', index: i, value: prev[i] });\n }\n return patches;\n}\n\nfunction diffByPosition(prev: readonly unknown[], next: readonly unknown[]): readonly ArrayPatch[] {\n const patches: ArrayPatch[] = [];\n const min = Math.min(prev.length, next.length);\n for (let i = 0; i < min; i += 1) {\n if (!shallowEqual(prev[i], next[i])) {\n patches.push({ kind: 'update', index: i, value: next[i] });\n }\n }\n if (next.length > prev.length) {\n for (let i = prev.length; i < next.length; i += 1) {\n patches.push({ kind: 'insert', index: i, value: next[i] });\n }\n }\n if (prev.length > next.length) {\n for (let i = next.length; i < prev.length; i += 1) {\n patches.push({ kind: 'remove', index: i, value: prev[i] });\n }\n }\n return patches;\n}\n\nfunction shallowEqual(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;\n const aRec = a as Record<string, unknown>;\n const bRec = b as Record<string, unknown>;\n const aKeys = Object.keys(aRec);\n const bKeys = Object.keys(bRec);\n if (aKeys.length !== bKeys.length) return false;\n for (const key of aKeys) {\n // Any reference difference triggers an update. Deep equality is\n // intentionally avoided — the renderer reconciles deeper diffs.\n if (!Object.is(aRec[key], bRec[key])) return false;\n }\n return true;\n}\n","/**\n * Translate Payload field types into our internal renderer names.\n *\n * Payload's type vocabulary is mostly 1:1 with ours, with a handful\n * of structural containers that get absorbed (the walker already\n * flattens `tabs`/`row`/`collapsible`, so the renderer never sees\n * them). Unknown / unmapped types fall back to `text` — that keeps\n * the preview functional even for new Payload field types we haven't\n * specifically renderer-supported yet.\n *\n * @module @schema/field-type-map\n */\n\nimport type { FieldType } from '@core/types';\nimport type { PayloadFieldType } from '@/types/payload-protocol';\n\nconst MAP: Readonly<Record<PayloadFieldType, FieldType>> = {\n text: 'text',\n textarea: 'textarea',\n richText: 'richText',\n email: 'email',\n number: 'number',\n checkbox: 'checkbox',\n date: 'date',\n select: 'select',\n radio: 'radio',\n array: 'array',\n blocks: 'blocks',\n group: 'text', // group itself has no display; bound element shows nothing useful\n tabs: 'text', // structural — walker should have stripped this\n row: 'text',\n collapsible: 'text',\n relationship: 'relationship',\n upload: 'upload',\n point: 'text',\n json: 'text',\n code: 'text',\n ui: 'text',\n};\n\n/**\n * Resolve a Payload field type to the renderer name we ship with.\n * Returns `undefined` when the type isn't in the table (unknown / new\n * Payload type) so the caller can decide whether to fall back to the\n * DOM-attribute or to `text`.\n */\nexport function payloadTypeToRenderer(type: string): FieldType | undefined {\n if (Object.prototype.hasOwnProperty.call(MAP, type)) {\n return MAP[type as PayloadFieldType];\n }\n return undefined;\n}\n","/**\n * Live preview runtime — the orchestrator that wires every primitive\n * into a single, manageable lifecycle.\n *\n * This module is the *seam* between the inline IIFE (Phase 6) and the\n * high-level client (Phase 12). Both import from here and add their\n * own glue:\n *\n * - The inline runtime instantiates `LivePreviewRuntime` with the\n * minimum required configuration and exposes a small global API.\n * - The high-level client instantiates the same runtime but layers\n * events, plugins, and configurable callbacks on top.\n *\n * The runtime never speaks postMessage directly — it relies on\n * `MessageBus`. It never queries the DOM during updates — it relies\n * on `ElementCache`. The separation keeps each module testable in\n * isolation while letting this file express the high-level flow.\n *\n * @module @core/lifecycle\n */\n\nimport type {\n PayloadFieldSchema,\n PayloadLivePreviewData,\n PayloadLivePreviewMessage,\n} from '@/types/payload-protocol';\nimport type { EventEmitter } from '@events/emitter';\nimport type { MessageRevision, OriginMatcher } from './message-bus';\nimport type { CachedElement, FieldRenderer, FieldType, RenderContext } from './types';\nimport { ElementCache } from './cache';\nimport { isBindingInScope, messageOwnerKeys, readDocumentId } from './binding-owner';\nimport { ObserverManager } from './observers';\nimport { MessageBus } from './message-bus';\nimport { ConnectionState, HeartbeatTimer } from './state';\nimport { DataMerger } from './data-merger';\nimport { applyAttributeBinding } from './attribute-binding';\nimport { UpdateScheduler, type FlushStats, type ScheduledUpdate } from './update-scheduler';\nimport type { LivePreviewInspection } from './inspection/types';\nimport type { DiagnosticCode } from './diagnostic-codes';\nimport { VERSION } from '../version';\nimport { observeThenableResult } from './thenable';\nimport { resolveFieldValue } from './field-value';\nimport { A11yAnnouncer } from './a11y';\nimport { isolateDiagnostic, noopDiagnostic, safeConsoleWarn } from './diagnostics';\nimport { markNoWriteCallback, rendererUsesNoWriteOutcome } from './internal-outcome';\nimport {\n buildSchemaIndex,\n lookupSchema,\n payloadTypeToRenderer,\n type SchemaIndex,\n} from '@schema/index';\nimport {\n LIBRARY_PROTOCOL_VERSION,\n negotiateProtocol,\n type ProtocolNegotiation,\n} from './protocol-version';\n\nconst READY_RETRY_DELAYS_MS = [0, 500, 1000, 2000] as const;\n\nexport interface RuntimeOptions {\n /** Document root containing the bindings. Defaults to `document`. */\n readonly root?: Document | Element;\n /** Map from field type to renderer. */\n readonly renderers: Readonly<Record<string, FieldRenderer>>;\n /** Resolve the currently active renderer layer for a field type. */\n readonly resolveRenderer?: (fieldType: FieldType) => FieldRenderer | undefined;\n /**\n * Transform a merged field value while preparing its per-binding scheduler\n * entry. The result is frozen for debounce/replay, then passes through all\n * downstream attribute or renderer security validation. `allFields` remains\n * the untransformed revision snapshot.\n */\n readonly transformValue?: (\n fieldName: string,\n value: unknown,\n context: {\n readonly element: Element;\n readonly allFields: Record<string, unknown>;\n },\n /** Stops a transform chain if synchronous re-entry supersedes this revision. */\n isCurrent?: () => boolean,\n ) => unknown;\n /** Origin matcher for incoming messages. */\n readonly originMatcher: OriginMatcher;\n /**\n * Reads the origin the host has locked onto, for the inspection snapshot.\n * The lock lives in the `OriginDetector` the caller owns, not in the\n * runtime, so the runtime has to be told how to read it.\n */\n readonly lockedOrigin?: () => string | undefined;\n /** Origins to broadcast `ready` to during the handshake. */\n readonly readyTargets: readonly string[];\n /** Event emitter (per-instance). */\n readonly emitter: EventEmitter;\n /** Debounce window in ms. */\n readonly debounceMs?: number;\n /** Heartbeat timeout. */\n readonly heartbeatMs?: number;\n /** Optional rootMargin for the IntersectionObserver. */\n readonly intersectionRootMargin?: string;\n /**\n * Restrict every update to the bindings owned by the document the message\n * describes, resolved from the nearest `data-payload-owner` ancestor.\n *\n * Off by default: a 1.x page whose bindings carry no owner keeps matching on\n * the field name alone. Once enabled, an unowned binding and a binding owned\n * by another document are both out of scope, so a page that previews several\n * documents stops sharing a field name between them.\n */\n readonly scopeBindingsByOwner?: boolean;\n /** When true, every update applies regardless of visibility. */\n readonly disableVisibilityGate?: boolean;\n /** Cache-size threshold above which off-screen updates are queued for replay. Default 50. */\n readonly visibilityGateThreshold?: number;\n /**\n * Mount an `aria-live` region and announce connections, applied updates,\n * and heartbeat-timeout disconnects while the runtime remains mounted.\n * Destroy releases the region synchronously and does not promise a final\n * audible announcement. Default `true`. Set `false` for runtimes that\n * already provide their own screen-reader announcements.\n */\n readonly enableA11y?: boolean;\n /**\n * Locale used to pick announcement strings. Defaults to the value\n * detected from `<html lang>` / `navigator.language` / `'en'`.\n */\n readonly a11yLocale?: string;\n /** Hook called when the runtime decides to (re)send the ready handshake. */\n readonly sendReady?: (origins: readonly string[]) => void;\n /**\n * Hook called when the heartbeat times out. Lets the host release\n * any origin lock so a different allow-listed origin can reconnect.\n * The default `LivePreviewClient` wires this to `OriginDetector.unlockOrigin()`.\n */\n readonly onHeartbeatTimeout?: () => void;\n /**\n * Optional preview-token validator. When provided, every data\n * update message must carry a `previewToken` that this function\n * approves; otherwise the message is dropped.\n *\n * ⚠️ `previewToken` is an extension of this library — the stock\n * Payload admin never sends one. Enable only when a custom admin\n * component attaches the token; otherwise every real update would\n * be dropped.\n */\n readonly validateToken?: (\n token: string | undefined,\n origin: string,\n ) => boolean | Promise<boolean>;\n /**\n * Server-side data merging (Payload 3.x). When configured, every\n * update is re-fetched through the Payload REST API so relationship\n * and upload fields arrive populated instead of as bare IDs — the\n * same strategy the official `@payloadcms/live-preview` client uses.\n * Failures fall back to rendering the raw form values.\n */\n readonly dataMerge?: {\n /** Payload server origin, e.g. `https://cms.example.com`. */\n readonly serverURL: string;\n /** REST API route prefix. Defaults to `/api`. */\n readonly apiRoute?: string;\n /** Population depth. Defaults to `1`. */\n readonly depth?: number;\n /** Injectable fetch implementation (tests). */\n readonly fetchFn?: typeof fetch;\n };\n /** Hook for the inline runtime to log to the console in debug mode. */\n readonly log?: (...args: unknown[]) => void;\n /**\n * Diagnostic warning channel — used by the runtime to surface\n * consumer-side mistakes that would otherwise produce silent\n * confusion (e.g., update arrived for a field that has no\n * `[data-payload-field]` anchor). Defaults to `console.warn`.\n *\n * Distinct from `log` because warnings should reach the editor\n * even when general debug logging is disabled — every warning is\n * deduped per field name so the channel cannot be spammed.\n */\n readonly warn?: (...args: unknown[]) => void;\n}\n\ninterface UpdateTransaction {\n readonly identity: MessageRevision;\n readonly message: PayloadLivePreviewMessage;\n readonly locale: string | undefined;\n readonly schema: readonly PayloadFieldSchema[] | undefined;\n readonly schemaIndex: SchemaIndex | undefined;\n cancelled: boolean;\n}\n\nconst enum RuntimeDependencySlot {\n Emitter,\n Cache,\n Observers,\n Scheduler,\n Bus,\n ConnectionState,\n Heartbeat,\n Renderers,\n ResolveRenderer,\n TransformValue,\n Root,\n ReadyTargets,\n SendReady,\n HeartbeatTimeoutHook,\n Log,\n Warn,\n ReadyTimers,\n A11y,\n Merger,\n ScopeBindingsByOwner,\n LockedOrigin,\n}\n\n/** Stable object/function references owned for the complete runtime lifetime. */\ntype RuntimeDependencies = readonly [\n emitter: EventEmitter,\n cache: ElementCache,\n observers: ObserverManager,\n scheduler: UpdateScheduler,\n bus: MessageBus,\n connectionState: ConnectionState,\n heartbeat: HeartbeatTimer,\n renderers: Readonly<Record<string, FieldRenderer>>,\n resolveRenderer: NonNullable<RuntimeOptions['resolveRenderer']>,\n transformValue: RuntimeOptions['transformValue'],\n root: Document | Element,\n readyTargets: readonly string[],\n sendReady: (origins: readonly string[]) => void,\n heartbeatTimeoutHook: RuntimeOptions['onHeartbeatTimeout'],\n log: (...args: unknown[]) => void,\n warn: (...args: unknown[]) => void,\n readyTimers: ReturnType<typeof setTimeout>[],\n a11y: A11yAnnouncer | null,\n merger: DataMerger | null,\n scopeBindingsByOwner: boolean,\n lockedOrigin: () => string | undefined,\n];\n\nconst enum RuntimeLifecycleSlot {\n CurrentLocale,\n CurrentSchema,\n SchemaIndex,\n ProtocolNegotiation,\n Started,\n DeferredStart,\n UpdateCount,\n ActiveUpdate,\n WarnedOrphanFields,\n WarnedUnattributableMessage,\n WarnedVisibilityGate,\n SupersededCount,\n LastFlush,\n AbsentFields,\n}\n\n/** State that changes as the runtime starts, accepts revisions, and stops. */\ntype RuntimeLifecycleState = [\n currentLocale: string | undefined,\n currentSchema: readonly PayloadFieldSchema[] | undefined,\n schemaIndex: SchemaIndex | undefined,\n protocolNegotiation: ProtocolNegotiation,\n started: boolean,\n deferredStart: (() => void) | null,\n updateCount: number,\n activeUpdate: UpdateTransaction | null,\n warnedOrphanFields: Set<string>,\n warnedUnattributableMessage: boolean,\n warnedVisibilityGate: boolean,\n supersededCount: number,\n lastFlush: FlushStats | null,\n absentFields: Set<string>,\n];\n\nexport class LivePreviewRuntime {\n /**\n * Consolidating internal storage avoids ES2020 private-field WeakMaps in the\n * inline build. Stable dependencies and mutable lifecycle state stay in\n * separate named tuples so ownership and mutation boundaries remain explicit.\n * This runtime class is not exported by a package entry.\n */\n private readonly d: RuntimeDependencies;\n private readonly l: RuntimeLifecycleState;\n\n constructor(options: RuntimeOptions) {\n const emitter = options.emitter;\n const renderers = options.renderers;\n const resolveRenderer = options.resolveRenderer ?? ((fieldType) => renderers[fieldType]);\n const transformValue = options.transformValue;\n const root =\n options.root ?? (typeof document !== 'undefined' ? document : (null as unknown as Document));\n const readyTargets = options.readyTargets;\n const sendReady = options.sendReady ?? defaultSendReady;\n const heartbeatTimeoutHook = options.onHeartbeatTimeout;\n const log = options.log === undefined ? noopDiagnostic : isolateDiagnostic(options.log);\n const warn = options.warn === undefined ? safeConsoleWarn : isolateDiagnostic(options.warn);\n const a11y = createA11y(options);\n const merger =\n options.dataMerge !== undefined\n ? new DataMerger({\n serverURL: options.dataMerge.serverURL,\n ...(options.dataMerge.apiRoute !== undefined\n ? { apiRoute: options.dataMerge.apiRoute }\n : {}),\n ...(options.dataMerge.depth !== undefined ? { depth: options.dataMerge.depth } : {}),\n ...(options.dataMerge.fetchFn !== undefined\n ? { fetchFn: options.dataMerge.fetchFn }\n : {}),\n log: (...args) => {\n log(...args);\n },\n })\n : null;\n\n const cache = new ElementCache();\n const observers = new ObserverManager(\n {\n onStructuralChange: () => {\n this.#rebuildCache();\n },\n onVisibilityChange: (element, visible) => {\n if (visible) {\n this.d[RuntimeDependencySlot.Scheduler].notifyVisible(element);\n }\n },\n },\n {\n ...(options.intersectionRootMargin !== undefined\n ? { intersectionRootMargin: options.intersectionRootMargin }\n : {}),\n },\n );\n const scheduler = new UpdateScheduler(\n markNoWriteCallback((update) => this.#applyUpdate(update)),\n {\n ...(options.debounceMs !== undefined ? { debounceMs: options.debounceMs } : {}),\n ...(options.disableVisibilityGate !== undefined\n ? { disableVisibilityGate: options.disableVisibilityGate }\n : {}),\n ...(options.visibilityGateThreshold !== undefined\n ? { visibilityGateThreshold: options.visibilityGateThreshold }\n : {}),\n isVisible: (element) => observers.isVisible(element),\n getCacheSize: () => cache.elementCount,\n onFlush: (stats) => {\n this.#onFlush(stats);\n },\n },\n );\n const bus = new MessageBus(options.originMatcher, {\n onUpdate: (msg, origin, identity) => {\n this.#handleUpdate(msg, origin, identity);\n },\n onDocumentEvent: () => {\n void emitter.emit('documentSave', { timestamp: Date.now() });\n },\n onInvalid: (reason, origin) => {\n if (reason === 'token') {\n const error = new Error(`Preview token rejected (origin: ${origin})`);\n void emitter.emit('error', { error, context: 'token', code: 'LP0502' });\n }\n log('LP0501 message rejected:', reason, origin);\n },\n ...(options.validateToken !== undefined ? { validateToken: options.validateToken } : {}),\n });\n // ConnectionState is deliberately callback-free here. Runtime transitions\n // have trust-boundary ordering requirements (notably timeout unlock before\n // disconnect observers), so arbitrary logging callbacks must not run from\n // inside the atomic state mutation.\n const connectionState = new ConnectionState(() => undefined);\n const heartbeat = new HeartbeatTimer({\n ...(options.heartbeatMs !== undefined ? { timeoutMs: options.heartbeatMs } : {}),\n onTimeout: () => {\n this.#onHeartbeatTimeout();\n },\n });\n\n this.d = [\n emitter,\n cache,\n observers,\n scheduler,\n bus,\n connectionState,\n heartbeat,\n renderers,\n resolveRenderer,\n transformValue,\n root,\n readyTargets,\n sendReady,\n heartbeatTimeoutHook,\n log,\n warn,\n [],\n a11y,\n merger,\n options.scopeBindingsByOwner === true,\n options.lockedOrigin ?? ((): undefined => undefined),\n ];\n this.l = [\n undefined,\n undefined,\n undefined,\n negotiateProtocol(undefined),\n false,\n null,\n 0,\n null,\n new Set<string>(),\n false,\n false,\n 0,\n null,\n new Set<string>(),\n ];\n }\n\n /**\n * Start the runtime: build cache, attach observers, listen for\n * messages, broadcast `ready`. Returns `true` when startup is accepted\n * (it refuses a second attempt while one is active).\n *\n * When the script executes while the document is still parsing\n * (e.g. injected via `<script>` in `<head>` — Astro's `head-inline`\n * stage), `document.body` does not exist yet and attaching the\n * MutationObserver would throw. In that case the actual startup is\n * deferred until `DOMContentLoaded`; `start()` still returns `true`\n * and `destroy()` cancels the pending startup.\n */\n start(): boolean {\n if (this.l[RuntimeLifecycleSlot.Started]) return false;\n this.l[RuntimeLifecycleSlot.Started] = true;\n\n const root = this.d[RuntimeDependencySlot.Root];\n if (isDocumentRoot(root) && root.readyState === 'loading') {\n const onReady = (): void => {\n if (!this.l[RuntimeLifecycleSlot.Started]) return;\n this.l[RuntimeLifecycleSlot.DeferredStart] = null;\n try {\n this.#startNow();\n } catch (error) {\n // The original start() has already returned, so a deferred failure\n // cannot be reported to its caller. Roll back every acquired resource\n // and surface the failure through the established runtime error event.\n this.#rollbackFailedStart();\n this.#reportError(error, 'startup', 'LP0605');\n }\n };\n this.l[RuntimeLifecycleSlot.DeferredStart] = onReady;\n try {\n root.addEventListener('DOMContentLoaded', onReady, { once: true });\n } catch (error) {\n this.#rollbackFailedStart();\n throw error;\n }\n return true;\n }\n\n try {\n this.#startNow();\n return true;\n } catch (error) {\n this.#rollbackFailedStart();\n throw error;\n }\n }\n\n #startNow(): void {\n if (!this.l[RuntimeLifecycleSlot.Started]) return;\n const observerRoot: Node | null = isDocumentRoot(this.d[RuntimeDependencySlot.Root])\n ? readDocumentBody(this.d[RuntimeDependencySlot.Root])\n : this.d[RuntimeDependencySlot.Root];\n if (observerRoot === null) {\n throw new Error('LivePreviewRuntime: document.body unavailable');\n }\n this.d[RuntimeDependencySlot.Observers].start(observerRoot);\n // The observer must exist before the cache scan registers its elements;\n // otherwise initial bindings can be deferred but never become replayable.\n this.#buildCacheAndObserve();\n if (!this.#isRunning()) return;\n this.d[RuntimeDependencySlot.Bus].attach();\n void this.d[RuntimeDependencySlot.Emitter].emitWhile(\n 'init',\n { timestamp: Date.now() },\n () => this.l[RuntimeLifecycleSlot.Started],\n );\n if (!this.#isRunning()) return;\n\n // Re-broadcast ready several times to absorb parent-side init latency.\n for (const delay of READY_RETRY_DELAYS_MS) {\n if (!this.#isRunning()) return;\n if (delay === 0) {\n this.d[RuntimeDependencySlot.SendReady](this.d[RuntimeDependencySlot.ReadyTargets]);\n if (!this.#isRunning()) return;\n } else {\n const handle = setTimeout(() => {\n if (!this.l[RuntimeLifecycleSlot.Started]) return;\n this.#sendReadyAfterStart();\n }, delay);\n this.d[RuntimeDependencySlot.ReadyTimers].push(handle);\n }\n }\n }\n\n /** Tear down all observers, timers, and listeners. Idempotent. */\n /**\n * Release the message ingress without tearing the instance down.\n *\n * A back/forward-cache restore never re-runs module scripts, so a runtime\n * that keeps its listener across `pagehide` comes back attached to a page the\n * browser froze and thawed: observers bound to nodes that were never\n * re-created, a heartbeat that measured the frozen interval, and pending\n * writes from before the freeze. It does not fail — it goes quiet, which is\n * the hardest symptom to attribute.\n *\n * Unlike `destroy()` this keeps everything the consumer configured: plugins,\n * renderers, transforms and the accessibility announcer all survive, and\n * `start()` brings the same instance back. `DataMerger` and `UpdateScheduler`\n * are reusable across a stop/start cycle by design, which is what makes this\n * a suspension rather than a rebuild.\n *\n * Emits `disconnect` with the existing `'unload'` reason, which the public\n * union has always carried for exactly this producer and nothing has emitted\n * until now.\n */\n suspend(): boolean {\n if (!this.l[RuntimeLifecycleSlot.Started]) return false;\n const wasConnected = this.#releaseRuntimeResources();\n if (wasConnected) {\n void this.d[RuntimeDependencySlot.Emitter].emit('disconnect', {\n reason: 'unload',\n timestamp: Date.now(),\n });\n }\n return true;\n }\n\n destroy(): void {\n if (!this.l[RuntimeLifecycleSlot.Started]) return;\n const wasConnected = this.#releaseRuntimeResources();\n if (wasConnected) {\n void this.d[RuntimeDependencySlot.Emitter].emit('disconnect', {\n reason: 'destroy',\n timestamp: Date.now(),\n });\n }\n this.d[RuntimeDependencySlot.A11y]?.detach();\n void this.d[RuntimeDependencySlot.Emitter].emit('destroy', {\n timestamp: Date.now(),\n });\n }\n\n /**\n * Invalidate first, then release every resource that startup may have acquired.\n * The same transaction boundary serves ordinary destroy and failed-start\n * rollback, preventing a partial observer/bus/timer/cache lifecycle.\n */\n #releaseRuntimeResources(): boolean {\n this.l[RuntimeLifecycleSlot.ActiveUpdate] = null;\n this.l[RuntimeLifecycleSlot.Started] = false;\n\n const deferredStart = this.l[RuntimeLifecycleSlot.DeferredStart];\n this.l[RuntimeLifecycleSlot.DeferredStart] = null;\n if (deferredStart !== null && isDocumentRoot(this.d[RuntimeDependencySlot.Root])) {\n this.#runCleanup(() => {\n this.d[RuntimeDependencySlot.Root].removeEventListener('DOMContentLoaded', deferredStart);\n });\n }\n\n for (const handle of this.d[RuntimeDependencySlot.ReadyTimers]) {\n this.#runCleanup(() => {\n clearTimeout(handle);\n });\n }\n this.d[RuntimeDependencySlot.ReadyTimers].length = 0;\n this.#runCleanup(() => {\n this.d[RuntimeDependencySlot.Heartbeat].stop();\n });\n this.#runCleanup(() => {\n this.d[RuntimeDependencySlot.Bus].detach();\n });\n this.#runCleanup(() => {\n this.d[RuntimeDependencySlot.Observers].stop();\n });\n this.#runCleanup(() => {\n this.d[RuntimeDependencySlot.Scheduler].destroy();\n });\n this.#runCleanup(() => {\n this.d[RuntimeDependencySlot.Merger]?.destroy();\n });\n this.d[RuntimeDependencySlot.Cache].clear();\n return this.d[RuntimeDependencySlot.ConnectionState].markDisconnected();\n }\n\n #rollbackFailedStart(): void {\n this.#releaseRuntimeResources();\n this.#runCleanup(() => {\n this.d[RuntimeDependencySlot.A11y]?.detach();\n });\n }\n\n #runCleanup(cleanup: () => void): void {\n try {\n cleanup();\n } catch (error) {\n this.d[RuntimeDependencySlot.Log]('cleanup failed:', error);\n }\n }\n\n /** Re-scan the DOM and re-register every binding. */\n refreshCache(): void {\n if (!this.l[RuntimeLifecycleSlot.Started]) return;\n this.#rebuildCache();\n }\n\n /** Current connection status, exposed for the high-level client. */\n get status(): 'disconnected' | 'connecting' | 'connected' {\n return this.d[RuntimeDependencySlot.ConnectionState].status;\n }\n\n /** Read-only view of the element cache. */\n get cache(): ElementCache {\n return this.d[RuntimeDependencySlot.Cache];\n }\n\n /** Read-only view of how many updates have been received. */\n get updateCount(): number {\n return this.l[RuntimeLifecycleSlot.UpdateCount];\n }\n\n /**\n * Negotiated protocol view — `min(library, remote)`. Useful for\n * consumers that want to branch on protocol capabilities without\n * hard-coding version numbers. Updates lazily as the remote party's\n * version arrives on incoming messages.\n */\n get protocol(): ProtocolNegotiation {\n return this.l[RuntimeLifecycleSlot.ProtocolNegotiation];\n }\n\n /**\n * Point-in-time read of runtime state for diagnosing a preview that is not\n * updating. Performs no I/O and sends nothing anywhere; see\n * `@core/inspection` for why this is not gated to development builds.\n *\n * Assembled inline rather than delegated to a helper because the inline\n * runtime pays for every byte of indirection, and because the values live\n * in private state no helper could reach without being handed all of it.\n */\n inspect(): LivePreviewInspection {\n const cache = this.d[RuntimeDependencySlot.Cache];\n const scheduler = this.d[RuntimeDependencySlot.Scheduler];\n const negotiation = this.l[RuntimeLifecycleSlot.ProtocolNegotiation];\n const active = this.l[RuntimeLifecycleSlot.ActiveUpdate];\n const flush = this.l[RuntimeLifecycleSlot.LastFlush];\n const fieldNames: string[] = [];\n const owners = new Set<string>();\n for (const [fieldName, bindings] of cache.entries()) {\n fieldNames.push(fieldName);\n for (const binding of bindings) {\n if (binding.owner !== undefined) owners.add(binding.owner);\n }\n }\n return {\n version: VERSION,\n started: this.l[RuntimeLifecycleSlot.Started],\n status: this.d[RuntimeDependencySlot.ConnectionState].status,\n origins: {\n trusted: [...this.d[RuntimeDependencySlot.ReadyTargets]],\n locked: this.d[RuntimeDependencySlot.LockedOrigin](),\n },\n protocol: {\n ours: negotiation.ours,\n theirs: negotiation.theirs,\n negotiated: negotiation.negotiated,\n capabilities: [...negotiation.capabilities].sort(),\n },\n revisions: {\n accepted: this.l[RuntimeLifecycleSlot.UpdateCount],\n superseded: this.l[RuntimeLifecycleSlot.SupersededCount],\n active: active === null ? undefined : active.identity.revision,\n },\n bindings: {\n elements: cache.elementCount,\n fields: cache.fieldCount,\n fieldNames: fieldNames.sort(),\n absentFields: [...this.l[RuntimeLifecycleSlot.AbsentFields]].sort(),\n orphanFields: [...this.l[RuntimeLifecycleSlot.WarnedOrphanFields]].sort(),\n ownerScoped: this.d[RuntimeDependencySlot.ScopeBindingsByOwner],\n owners: [...owners].sort(),\n },\n scheduler: {\n pending: scheduler.pendingCount,\n deferred: scheduler.replayCount,\n visibilityGateThreshold: scheduler.gateThreshold,\n visibilityGateActive: scheduler.gateActive,\n lastFlush:\n flush === null\n ? undefined\n : {\n applied: flush.applied,\n appliedFields: flush.appliedFields,\n deferred: flush.deferred,\n durationMs: flush.durationMs,\n },\n },\n renderers: Object.keys(this.d[RuntimeDependencySlot.Renderers]).sort(),\n };\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Internals\n // ──────────────────────────────────────────────────────────────────────────\n\n #buildCacheAndObserve(): void {\n if (!this.l[RuntimeLifecycleSlot.Started]) return;\n const stats = this.d[RuntimeDependencySlot.Cache].buildFromRoot(\n this.d[RuntimeDependencySlot.Root],\n );\n this.d[RuntimeDependencySlot.Log]('cache', stats);\n if (!this.#isRunning()) return;\n void this.d[RuntimeDependencySlot.Emitter].emitWhile(\n 'cacheRefresh',\n stats,\n () => this.l[RuntimeLifecycleSlot.Started],\n );\n if (!this.#isRunning()) return;\n for (const entry of this.d[RuntimeDependencySlot.Cache].values()) {\n if (!this.#isRunning()) return;\n this.d[RuntimeDependencySlot.Observers].observeElement(entry.element);\n }\n }\n\n #rebuildCache(): void {\n if (!this.l[RuntimeLifecycleSlot.Started]) return;\n const previousBindings = new Map<Element, CachedElement>();\n for (const entry of this.d[RuntimeDependencySlot.Cache].values()) {\n previousBindings.set(entry.element, entry);\n this.d[RuntimeDependencySlot.Observers].unobserveElement(entry.element);\n }\n this.#buildCacheAndObserve();\n if (!this.#isRunning()) return;\n\n // Rebuilding replaces every CachedElement snapshot. Buffered work may\n // survive only while the same DOM element is still bound to the same\n // field; retarget it so later flush/replay observes the rebuilt metadata.\n // Removed or rebound elements must never receive their former field's data.\n for (const entry of this.d[RuntimeDependencySlot.Cache].values()) {\n const previous = previousBindings.get(entry.element);\n if (previous?.fieldName === entry.fieldName) {\n this.d[RuntimeDependencySlot.Scheduler].retarget(entry);\n } else this.d[RuntimeDependencySlot.Scheduler].forget(entry.element);\n previousBindings.delete(entry.element);\n }\n for (const removed of previousBindings.values()) {\n this.d[RuntimeDependencySlot.Scheduler].forget(removed.element);\n }\n }\n\n #applyNegotiation(remoteVersion: number): void {\n const current = this.l[RuntimeLifecycleSlot.ProtocolNegotiation];\n // Every data message repeats the version, so the common case is that\n // nothing changed and there is nothing to record or say.\n if (current.theirs === remoteVersion) return;\n const next = negotiateProtocol(remoteVersion);\n this.l[RuntimeLifecycleSlot.ProtocolNegotiation] = next;\n // Record the announcement even when it does not move the negotiated\n // version — `theirs` is public, and comparing only `negotiated` left a\n // remote announcing version 1 indistinguishable from one that never\n // announced at all. Log only a real negotiation change.\n if (next.negotiated === current.negotiated) return;\n this.d[RuntimeDependencySlot.Log](\n 'protocol',\n `ours=${LIBRARY_PROTOCOL_VERSION}`,\n `theirs=${remoteVersion}`,\n `negotiated=${next.negotiated}`,\n );\n }\n\n /* eslint-disable @typescript-eslint/no-unnecessary-condition -- Each explicit\n * transaction check follows an arbitrary consumer/DOM callback that can\n * synchronously replace the active-update slot or destroy the runtime. TypeScript's\n * local control-flow narrowing cannot observe that re-entrancy. */\n #handleUpdate(\n message: PayloadLivePreviewMessage,\n origin: string,\n identity: MessageRevision | undefined,\n ): void {\n this.d[RuntimeDependencySlot.Heartbeat].kick();\n if (message.data === undefined) {\n if (message.protocolVersion !== undefined) {\n this.#applyNegotiation(message.protocolVersion);\n }\n return;\n }\n // MessageBus supplies an identity for every shape-valid data update.\n // Refuse identity-less work defensively so no alternate host path can\n // bypass the revision model.\n if (identity === undefined) return;\n if (typeof message.locale === 'string') {\n this.l[RuntimeLifecycleSlot.CurrentLocale] = message.locale;\n }\n if (Array.isArray(message.fieldSchemaJSON)) {\n this.l[RuntimeLifecycleSlot.CurrentSchema] = message.fieldSchemaJSON;\n this.l[RuntimeLifecycleSlot.SchemaIndex] = buildSchemaIndex(message.fieldSchemaJSON);\n }\n\n const transaction: UpdateTransaction = {\n identity,\n message,\n locale: this.l[RuntimeLifecycleSlot.CurrentLocale],\n schema: this.l[RuntimeLifecycleSlot.CurrentSchema],\n schemaIndex: this.l[RuntimeLifecycleSlot.SchemaIndex],\n cancelled: false,\n };\n\n // Acceptance is the single supersession point. It clears old pending and\n // replay work even if this revision is later cancelled or has no bindings.\n // A transaction still sitting here is therefore exactly one that never\n // finished, which is what the inspection snapshot counts.\n if (this.l[RuntimeLifecycleSlot.ActiveUpdate] !== null) {\n this.l[RuntimeLifecycleSlot.SupersededCount] += 1;\n }\n this.l[RuntimeLifecycleSlot.ActiveUpdate] = transaction;\n this.d[RuntimeDependencySlot.Scheduler].acceptRevision(identity);\n this.l[RuntimeLifecycleSlot.UpdateCount] += 1;\n\n // User-provided log and event handlers are reentrant. They may dispatch a\n // newer update synchronously, so the transaction must already be accepted\n // and every continuation below must re-check its identity.\n if (message.protocolVersion !== undefined) {\n this.#applyNegotiation(message.protocolVersion);\n if (!(\n this.l[RuntimeLifecycleSlot.Started] &&\n this.l[RuntimeLifecycleSlot.ActiveUpdate] === transaction\n )) {\n return;\n }\n }\n if (this.d[RuntimeDependencySlot.ConnectionState].markConnected()) {\n this.d[RuntimeDependencySlot.A11y]?.announceConnected();\n void this.d[RuntimeDependencySlot.Emitter].emit('connect', {\n origin,\n timestamp: Date.now(),\n });\n if (!(\n this.l[RuntimeLifecycleSlot.Started] &&\n this.l[RuntimeLifecycleSlot.ActiveUpdate] === transaction\n )) {\n return;\n }\n this.d[RuntimeDependencySlot.Log]('connection', 'disconnected', '→', 'connected');\n if (!(\n this.l[RuntimeLifecycleSlot.Started] &&\n this.l[RuntimeLifecycleSlot.ActiveUpdate] === transaction\n )) {\n return;\n }\n }\n void this.#processUpdate(transaction);\n }\n\n async #processUpdate(transaction: UpdateTransaction): Promise<void> {\n const fields = await this.#resolveIncomingFields(transaction);\n if (\n fields === null ||\n !(\n this.l[RuntimeLifecycleSlot.Started] &&\n this.l[RuntimeLifecycleSlot.ActiveUpdate] === transaction\n )\n ) {\n return;\n }\n\n const { message } = transaction;\n const data: PayloadLivePreviewData = {\n fields,\n ...(transaction.schema !== undefined ? { schema: transaction.schema } : {}),\n ...(typeof message.globalSlug === 'string' ? { globalSlug: message.globalSlug } : {}),\n ...(typeof message.collectionSlug === 'string'\n ? { collectionSlug: message.collectionSlug }\n : {}),\n ...(transaction.locale !== undefined ? { locale: transaction.locale } : {}),\n };\n\n if (this.d[RuntimeDependencySlot.Emitter].listenerCount('beforeUpdate') > 0) {\n const completed = await this.d[RuntimeDependencySlot.Emitter].emitWhile(\n 'beforeUpdate',\n {\n data,\n revision: transaction.identity.revision,\n cancel: (): void => {\n transaction.cancelled = true;\n this.d[RuntimeDependencySlot.Scheduler].cancelRevision(transaction.identity);\n },\n },\n () =>\n !transaction.cancelled &&\n this.l[RuntimeLifecycleSlot.Started] &&\n this.l[RuntimeLifecycleSlot.ActiveUpdate] === transaction,\n );\n if (\n !completed ||\n transaction.cancelled ||\n !(\n this.l[RuntimeLifecycleSlot.Started] &&\n this.l[RuntimeLifecycleSlot.ActiveUpdate] === transaction\n )\n ) {\n return;\n }\n }\n if (!(\n this.l[RuntimeLifecycleSlot.Started] &&\n this.l[RuntimeLifecycleSlot.ActiveUpdate] === transaction\n )) {\n return;\n }\n this.#scheduleAllFields(transaction, data);\n }\n\n /**\n * Resolve the field values to render for an incoming update. With a\n * configured `DataMerger` the raw form values are exchanged for the\n * server-populated document; without one (or on failure) the raw\n * values pass through unchanged. Returns `null` when a newer update\n * superseded this one mid-flight.\n */\n async #resolveIncomingFields(\n transaction: UpdateTransaction,\n ): Promise<Record<string, unknown> | null> {\n const { message } = transaction;\n // #handleUpdate has already returned when `data` is undefined.\n const raw = message.data ?? {};\n if (this.d[RuntimeDependencySlot.Merger] === null) return raw;\n const result = await this.d[RuntimeDependencySlot.Merger].merge({\n collectionSlug: message.collectionSlug,\n globalSlug: message.globalSlug,\n data: raw,\n locale: transaction.locale,\n });\n if (!(\n this.l[RuntimeLifecycleSlot.Started] &&\n this.l[RuntimeLifecycleSlot.ActiveUpdate] === transaction\n )) {\n return null;\n }\n if (result.status === 'merged') return result.doc;\n if (result.status === 'superseded') return null;\n return raw;\n }\n\n #scheduleAllFields(transaction: UpdateTransaction, data: PayloadLivePreviewData): void {\n if (!(\n this.l[RuntimeLifecycleSlot.Started] &&\n this.l[RuntimeLifecycleSlot.ActiveUpdate] === transaction\n )) {\n return;\n }\n const isCurrent = (): boolean =>\n this.l[RuntimeLifecycleSlot.Started] &&\n this.l[RuntimeLifecycleSlot.ActiveUpdate] === transaction;\n const ownerKeys = this.#ownerKeysForUpdate(transaction, data.fields);\n for (const [fieldName, bindings] of this.d[RuntimeDependencySlot.Cache].entries()) {\n if (!(\n this.l[RuntimeLifecycleSlot.Started] &&\n this.l[RuntimeLifecycleSlot.ActiveUpdate] === transaction\n )) {\n return;\n }\n for (const target of bindings) {\n if (ownerKeys !== false && !isBindingInScope(target.owner, ownerKeys)) continue;\n const value = resolveFieldValue(\n data.fields,\n fieldName,\n target.locale ?? transaction.locale,\n target.locale !== undefined,\n );\n if (value === undefined) {\n // Ein gebundenes Feld, fuer das die Nachricht keinen Wert traegt,\n // wird hier uebersprungen. Das ist der Gegenfall zu orphanFields (ein\n // Wert ohne Anker) und war von aussen unsichtbar: die Bindung bleibt\n // auf ihrem alten Text stehen, ohne jede Spur.\n this.l[RuntimeLifecycleSlot.AbsentFields].add(fieldName);\n continue;\n }\n // Transforms are arbitrary plugin code and may synchronously dispatch a\n // newer message. Stop the obsolete revision at that callback boundary\n // before invoking another transform or scheduling any of its result.\n if (!(\n this.l[RuntimeLifecycleSlot.Started] &&\n this.l[RuntimeLifecycleSlot.ActiveUpdate] === transaction\n )) {\n return;\n }\n const transformedValue = this.#transformForBinding(target, value, data.fields, isCurrent);\n if (!(\n this.l[RuntimeLifecycleSlot.Started] &&\n this.l[RuntimeLifecycleSlot.ActiveUpdate] === transaction\n )) {\n return;\n }\n const update: ScheduledUpdate = {\n target,\n value: transformedValue,\n allFields: data.fields,\n identity: transaction.identity,\n data,\n };\n if (!(\n this.l[RuntimeLifecycleSlot.Started] &&\n this.l[RuntimeLifecycleSlot.ActiveUpdate] === transaction\n )) {\n return;\n }\n this.d[RuntimeDependencySlot.Scheduler].schedule(update);\n }\n }\n this.#diagnoseOrphanFields(data.fields, transaction.locale, ownerKeys);\n }\n\n /**\n * Owner keys this update may address, or `false` when scoping is disabled.\n *\n * `false` and `null` are deliberately different: the first means \"ownership\n * is not in play, match on field name as 1.x always has\", the second means\n * \"scoping is active but this message names no document\", which is\n * fail-closed. Warned once, because a silent no-op is the hardest possible\n * symptom to diagnose.\n */\n #ownerKeysForUpdate(\n transaction: UpdateTransaction,\n fields: Record<string, unknown>,\n ): readonly string[] | null | false {\n if (!this.d[RuntimeDependencySlot.ScopeBindingsByOwner]) return false;\n const { message } = transaction;\n const keys = messageOwnerKeys({\n globalSlug: typeof message.globalSlug === 'string' ? message.globalSlug : undefined,\n collectionSlug:\n typeof message.collectionSlug === 'string' ? message.collectionSlug : undefined,\n documentId: readDocumentId(fields),\n });\n if (keys === null && !this.l[RuntimeLifecycleSlot.WarnedUnattributableMessage]) {\n this.l[RuntimeLifecycleSlot.WarnedUnattributableMessage] = true;\n this.d[RuntimeDependencySlot.Warn](\n '[live-preview] LP0202: scopeBindingsByOwner: update names no document; nothing applied',\n );\n }\n return keys;\n }\n\n /** Whether this document owns any binding currently on the page. */\n #ownsAnyBinding(ownerKeys: readonly string[] | null): boolean {\n for (const binding of this.d[RuntimeDependencySlot.Cache].values()) {\n if (isBindingInScope(binding.owner, ownerKeys)) return true;\n }\n return false;\n }\n\n /** Whether any cached binding for `fieldName` may receive this update. */\n #hasAddressableBinding(fieldName: string, ownerKeys: readonly string[] | null | false): boolean {\n const bindings = this.d[RuntimeDependencySlot.Cache].get(fieldName);\n if (bindings === undefined) return false;\n if (ownerKeys === false) return true;\n return bindings.some((binding) => isBindingInScope(binding.owner, ownerKeys));\n }\n\n /**\n * Walk the incoming `data` payload and warn (via `this.d[RuntimeDependencySlot.Warn]`) when an\n * editable-looking field arrives for which **no `[data-payload-field]`\n * anchor exists** in the page. This is the most common live-preview\n * footgun: an SSR template renders the binding only when the field is\n * non-empty, so editing a previously-empty field has nowhere to land.\n *\n * The warning remains active independently of verbose debug logging and is\n * gated by:\n * - per-field deduplication via `#warnedOrphanFields`\n * - scalar value heuristic (objects/arrays don't get warned)\n * - a small ignore-list of system fields Payload always ships\n *\n * The method intentionally lives on the runtime — not on the cache —\n * because it depends on the locale and on schema knowledge that the\n * cache does not own.\n */\n #diagnoseOrphanFields(\n fields: Record<string, unknown>,\n locale: string | undefined,\n ownerKeys: readonly string[] | null | false,\n ): void {\n if (this.d[RuntimeDependencySlot.Cache].fieldCount === 0) return;\n // With scoping active, a page that renders none of this document's\n // bindings is the normal case, not a missing anchor. Warning per field\n // there would report the whole document as broken on every keystroke.\n if (ownerKeys !== false && !this.#ownsAnyBinding(ownerKeys)) return;\n let localisedBindingNames: Set<string> | undefined;\n for (const [rawName, value] of Object.entries(fields)) {\n if (this.l[RuntimeLifecycleSlot.WarnedOrphanFields].has(rawName)) continue;\n if (SYSTEM_FIELD_NAMES.has(rawName)) continue;\n if (!isLiveBindableScalar(value)) continue;\n const baseName = stripLocaleSuffix(rawName, locale);\n if (this.#hasAddressableBinding(rawName, ownerKeys)) continue;\n if (baseName !== rawName && this.#hasAddressableBinding(baseName, ownerKeys)) {\n continue;\n }\n // Element-local locales can intentionally consume several suffixed\n // variants of one field while the message's global locale is different.\n // Build this alias set lazily only after the direct/common checks miss.\n if (localisedBindingNames === undefined) {\n localisedBindingNames = new Set<string>();\n for (const [fieldName, bindings] of this.d[RuntimeDependencySlot.Cache].entries()) {\n for (const binding of bindings) {\n if (ownerKeys !== false && !isBindingInScope(binding.owner, ownerKeys)) continue;\n if (binding.locale !== undefined) {\n localisedBindingNames.add(`${fieldName}_${binding.locale}`);\n }\n }\n }\n }\n if (localisedBindingNames.has(rawName)) continue;\n this.l[RuntimeLifecycleSlot.WarnedOrphanFields].add(rawName);\n this.d[RuntimeDependencySlot.Warn](\n `[live-preview] LP0201: update arrived for field \"${rawName}\" but no ` +\n `<… data-payload-field=\"${baseName}\"> element exists on this page. ` +\n `Render the binding anchor unconditionally in your template so ` +\n `live edits to an initially-empty field have somewhere to land.`,\n );\n }\n }\n\n /**\n * Freeze the per-binding transformed value into the revision's scheduler\n * entry. Replays therefore cannot observe plugins registered or removed\n * after this revision was prepared.\n */\n #transformForBinding(\n target: CachedElement,\n originalValue: unknown,\n allFields: Record<string, unknown>,\n isCurrent: () => boolean,\n ): unknown {\n if (this.d[RuntimeDependencySlot.TransformValue] === undefined) {\n return originalValue;\n }\n try {\n const transformed = this.d[RuntimeDependencySlot.TransformValue](\n target.fieldName,\n originalValue,\n {\n element: target.element,\n allFields,\n },\n isCurrent,\n );\n const returnedThenable = observeThenableResult(transformed);\n if (!isCurrent()) return originalValue;\n if (returnedThenable) {\n throw new TypeError(\n `Transform for \"${target.fieldName}\" returned a Promise/thenable; transforms must be synchronous`,\n );\n }\n return transformed;\n } catch (err) {\n if (!isCurrent()) return originalValue;\n const error = err instanceof Error ? err : new Error(String(err));\n void this.d[RuntimeDependencySlot.Emitter].emit('error', {\n error,\n context: 'transform',\n code: 'LP0602',\n });\n return originalValue;\n }\n }\n\n /** Re-read lifecycle state after an arbitrary reentrant callback. */\n #isRunning(): boolean {\n return this.l[RuntimeLifecycleSlot.Started];\n }\n\n /**\n * Report the first flush the visibility gate held back.\n *\n * The gate is off until the cache grows past `visibilityGateThreshold`, and\n * from then on an offscreen binding is buffered until it scrolls into view.\n * That is a deliberate trade, but it is also a cliff: a page that grows one\n * binding past the threshold changes its update semantics wholesale, and the\n * symptom — \"editing a field below the fold does nothing\" — looks exactly\n * like a broken runtime. Nothing else in the pipeline reports it, so a\n * consumer can only discover it by instrumenting this package.\n *\n * Warned once, on the same reasoning as the unattributable-message warning:\n * a silent no-op is the hardest possible symptom to diagnose.\n */\n #warnOnDeferredWrites(stats: FlushStats): void {\n if (stats.deferred === 0) return;\n if (this.l[RuntimeLifecycleSlot.WarnedVisibilityGate]) return;\n this.l[RuntimeLifecycleSlot.WarnedVisibilityGate] = true;\n this.d[RuntimeDependencySlot.Warn](\n `[live-preview] LP0301: visibility gate held ${String(stats.deferred)} offscreen ` +\n 'update(s) until scrolled into view; see visibilityGateThreshold.',\n );\n }\n\n #applyUpdate(update: ScheduledUpdate): boolean {\n const transaction = this.l[RuntimeLifecycleSlot.ActiveUpdate];\n if (\n transaction === null ||\n update.identity === undefined ||\n !sameRevision(transaction.identity, update.identity) ||\n !(\n this.l[RuntimeLifecycleSlot.Started] &&\n this.l[RuntimeLifecycleSlot.ActiveUpdate] === transaction\n )\n ) {\n return false;\n }\n const schemaEntry =\n transaction.schemaIndex !== undefined\n ? lookupSchema(transaction.schemaIndex, update.target.fieldName)\n : undefined;\n const value = update.value;\n let resolvedType = resolveRuntimeFieldType(update.target, schemaEntry?.type);\n // Payload 3.x sends no field schema, so rich-text fields would fall\n // through to the `text` heuristic and render \"[object Object]\".\n // A Lexical value is unmistakable — upgrade the renderer on sight.\n if (\n resolvedType === 'text' &&\n update.target.explicitFieldType !== true &&\n looksLikeLexicalRoot(value)\n ) {\n resolvedType = 'richText';\n }\n let renderer: FieldRenderer | undefined;\n try {\n renderer = this.d[RuntimeDependencySlot.ResolveRenderer](resolvedType);\n } catch (err) {\n if (!(\n this.l[RuntimeLifecycleSlot.Started] &&\n this.l[RuntimeLifecycleSlot.ActiveUpdate] === transaction\n )) {\n return false;\n }\n const error = err instanceof Error ? err : new Error(String(err));\n void this.d[RuntimeDependencySlot.Emitter].emitWhile(\n 'error',\n { error, context: 'renderer', code: 'LP0603' },\n () =>\n this.l[RuntimeLifecycleSlot.Started] &&\n this.l[RuntimeLifecycleSlot.ActiveUpdate] === transaction,\n );\n return false;\n }\n // Renderer resolution is plugin code and may synchronously accept a newer\n // message. Never let the obsolete transaction proceed to a DOM write.\n if (!(\n this.l[RuntimeLifecycleSlot.Started] &&\n this.l[RuntimeLifecycleSlot.ActiveUpdate] === transaction\n )) {\n return false;\n }\n // Element snapshots exist solely for `elementUpdate`. The inline runtime\n // normally has no listener for that event, so avoid a needless DOM read\n // and event Promise for every binding on the default hot path. Listener\n // presence is captured before renderer dispatch, alongside the value the\n // event describes; registrations made by that renderer begin with the\n // next element update.\n const emitElementUpdate =\n this.d[RuntimeDependencySlot.Emitter].listenerCount('elementUpdate') > 0;\n const previous = emitElementUpdate ? readElementSnapshot(update.target.element) : undefined;\n // Custom-element DOM accessors can execute application code. Treat the\n // optional snapshot as the same reentrant boundary as renderer lookup and\n // dispatch so a getter-triggered newer revision wins before any DOM write.\n if (!(\n this.l[RuntimeLifecycleSlot.Started] &&\n this.l[RuntimeLifecycleSlot.ActiveUpdate] === transaction\n )) {\n return false;\n }\n const context: RenderContext = {\n allFields: update.allFields,\n locale: update.target.locale ?? transaction.locale,\n schema: schemaEntry,\n };\n try {\n if (update.target.targetAttribute !== undefined) {\n const outcome = applyAttributeBinding(\n update.target.element,\n update.target.targetAttribute,\n value,\n );\n if (outcome === 'blocked') {\n this.d[RuntimeDependencySlot.Warn](\n `[live-preview] LP0401: refused to write field \"${update.target.fieldName}\" ` +\n `into attribute \"${update.target.targetAttribute}\" (unsafe attribute or value)`,\n );\n return false;\n }\n } else if (renderer) {\n // `FieldRenderer` intentionally retains its public 1.x `void` result.\n // Marked built-ins use an internal exact-false sentinel for known\n // no-write paths. Custom/plugin return values remain ignored exactly as\n // before, including a `false` produced by a real DOM mutation.\n const outcome = invokeRenderer(renderer, update.target, value, context);\n if (outcome === false && rendererUsesNoWriteOutcome(renderer)) return false;\n } else {\n this.d[RuntimeDependencySlot.Log]('no renderer for', resolvedType);\n return false;\n }\n } catch (err) {\n // A renderer or custom-element attribute reaction may have accepted a\n // newer revision before throwing. Its obsolete failure is not a current\n // runtime error and must not trigger any later lifecycle callbacks.\n if (!(\n this.l[RuntimeLifecycleSlot.Started] &&\n this.l[RuntimeLifecycleSlot.ActiveUpdate] === transaction\n )) {\n return false;\n }\n const error = err instanceof Error ? err : new Error(String(err));\n void this.d[RuntimeDependencySlot.Emitter].emitWhile(\n 'error',\n { error, context: 'renderer', code: 'LP0603' },\n () =>\n this.l[RuntimeLifecycleSlot.Started] &&\n this.l[RuntimeLifecycleSlot.ActiveUpdate] === transaction,\n );\n return false;\n }\n // Both renderer writes and setAttribute/removeAttribute can execute\n // consumer code synchronously (plugins or custom-element reactions).\n if (!(\n this.l[RuntimeLifecycleSlot.Started] &&\n this.l[RuntimeLifecycleSlot.ActiveUpdate] === transaction\n )) {\n return false;\n }\n if (emitElementUpdate) {\n void this.d[RuntimeDependencySlot.Emitter].emitWhile(\n 'elementUpdate',\n {\n element: update.target.element,\n fieldName: update.target.fieldName,\n previousValue: previous,\n nextValue: value,\n revision: transaction.identity.revision,\n },\n () =>\n this.l[RuntimeLifecycleSlot.Started] &&\n this.l[RuntimeLifecycleSlot.ActiveUpdate] === transaction,\n );\n }\n // emitWhile invokes its first handler before yielding. Account for a\n // synchronous reentrant update so the obsolete write is not counted as a\n // successful flush and cannot publish afterUpdate.\n return (\n this.l[RuntimeLifecycleSlot.Started] &&\n this.l[RuntimeLifecycleSlot.ActiveUpdate] === transaction\n );\n }\n\n #onFlush(stats: FlushStats): void {\n // Before every early return below. A flush that applied nothing is exactly\n // the flush this reports, and the `applied === 0` guard would swallow it.\n // The same reasoning holds for the inspection snapshot: an empty flush is\n // the one a diagnosing reader most needs to see.\n this.l[RuntimeLifecycleSlot.LastFlush] = stats;\n this.#warnOnDeferredWrites(stats);\n const { identity, data } = stats;\n if (stats.applied === 0 || identity === undefined || data === undefined) return;\n const transaction = this.l[RuntimeLifecycleSlot.ActiveUpdate];\n if (\n transaction === null ||\n !(\n this.l[RuntimeLifecycleSlot.Started] &&\n this.l[RuntimeLifecycleSlot.ActiveUpdate] === transaction\n ) ||\n !sameRevision(transaction.identity, identity)\n ) {\n return;\n }\n const isCurrent = (): boolean =>\n this.l[RuntimeLifecycleSlot.Started] &&\n this.l[RuntimeLifecycleSlot.ActiveUpdate] === transaction &&\n sameRevision(transaction.identity, identity);\n this.d[RuntimeDependencySlot.A11y]?.announceUpdate(stats.applied);\n if (!isCurrent()) return;\n if (this.d[RuntimeDependencySlot.Emitter].listenerCount('afterUpdate') === 0) {\n return;\n }\n void this.d[RuntimeDependencySlot.Emitter].emitWhile(\n 'afterUpdate',\n {\n data,\n updatedCount: stats.applied,\n durationMs: stats.durationMs,\n revision: identity.revision,\n },\n isCurrent,\n );\n }\n /* eslint-enable @typescript-eslint/no-unnecessary-condition */\n\n #onHeartbeatTimeout(): void {\n if (!this.#isRunning()) return;\n this.d[RuntimeDependencySlot.Bus].advanceGeneration();\n const active = this.l[RuntimeLifecycleSlot.ActiveUpdate];\n this.l[RuntimeLifecycleSlot.ActiveUpdate] = null;\n if (active !== null) {\n this.d[RuntimeDependencySlot.Scheduler].cancelRevision(active.identity);\n }\n this.d[RuntimeDependencySlot.Merger]?.destroy();\n const wasConnected = this.d[RuntimeDependencySlot.ConnectionState].markDisconnected();\n\n // Release the old origin before publishing the disconnect. A synchronous\n // disconnect listener may immediately dispatch from another allow-listed\n // origin; that update then connects and locks within the fresh generation,\n // and no later timeout step may undo its lock.\n try {\n this.d[RuntimeDependencySlot.HeartbeatTimeoutHook]?.();\n } catch (err) {\n this.d[RuntimeDependencySlot.Log]('heartbeat:', err);\n }\n if (!this.#isRunning()) return;\n if (wasConnected && this.#isDisconnectedWithoutActiveUpdate()) {\n this.d[RuntimeDependencySlot.A11y]?.announceDisconnected();\n void this.d[RuntimeDependencySlot.Emitter].emitWhile(\n 'disconnect',\n { reason: 'timeout', timestamp: Date.now() },\n () => this.#isDisconnectedWithoutActiveUpdate(),\n );\n if (!this.#isRunning()) return;\n if (this.#isDisconnectedWithoutActiveUpdate()) {\n this.d[RuntimeDependencySlot.Log]('connection', 'connected', '→', 'disconnected');\n if (!this.#isRunning()) return;\n }\n }\n if (!this.#isRunning()) return;\n this.#sendReadyAfterStart();\n }\n\n /** Later handshake retries are best-effort and must not escape timer callbacks. */\n #sendReadyAfterStart(): void {\n try {\n this.d[RuntimeDependencySlot.SendReady](this.d[RuntimeDependencySlot.ReadyTargets]);\n } catch (error) {\n this.#reportError(error, 'ready', 'LP0606');\n }\n }\n\n #reportError(cause: unknown, context: string, code: DiagnosticCode): void {\n const error = cause instanceof Error ? cause : new Error(String(cause));\n void this.d[RuntimeDependencySlot.Emitter].emit('error', {\n error,\n context,\n code,\n });\n }\n\n #isDisconnectedWithoutActiveUpdate(): boolean {\n return (\n this.l[RuntimeLifecycleSlot.Started] &&\n this.d[RuntimeDependencySlot.ConnectionState].status === 'disconnected' &&\n this.l[RuntimeLifecycleSlot.ActiveUpdate] === null\n );\n }\n}\n\n/** Resolve explicit binding metadata before schema and tag-name fallbacks. */\nfunction resolveRuntimeFieldType(target: CachedElement, schemaType: string | undefined): FieldType {\n if (target.explicitFieldType) return target.fieldType;\n if (schemaType !== undefined) {\n const mapped = payloadTypeToRenderer(schemaType);\n if (mapped !== undefined) return mapped;\n }\n return target.fieldType;\n}\n\n/**\n * Invoke the public 1.x void renderer contract without erasing its JavaScript\n * return value. Built-ins reserve exact `false` for a deliberate no-write;\n * every other result (including custom `void`) retains legacy success semantics.\n */\nfunction invokeRenderer(\n renderer: FieldRenderer,\n target: CachedElement,\n value: unknown,\n context: RenderContext,\n): unknown {\n // TypeScript's `void` is intentionally caller-facing: implementations may\n // return a value, while callers cannot depend on it. Reading it internally\n // here is the narrow compatibility bridge for the built-in sentinel.\n // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression\n return renderer.render(target, value, context);\n}\n\nfunction createA11y(options: RuntimeOptions): A11yAnnouncer | null {\n if (options.enableA11y === false) return null;\n const targetDocument =\n options.root === undefined\n ? undefined\n : options.root.nodeType === 9\n ? (options.root as Document)\n : options.root.ownerDocument;\n return new A11yAnnouncer(options.a11yLocale, targetDocument);\n}\n\n/** DOM node types are stable across realms; global constructors are not. */\nfunction isDocumentRoot(root: Document | Element): root is Document {\n return root.nodeType === 9;\n}\n\n/** lib.dom models body as present, although head-time documents can lack it. */\nfunction readDocumentBody(root: Document): HTMLElement | null {\n return root.body;\n}\n\n/**\n * Structural check for a Lexical root payload. Mirrors\n * `isLexicalContent` from `@lexical/render` — duplicated here (four\n * lines) so the lightweight `./core` entry does not transitively pull\n * the entire Lexical renderer just for this shape test.\n */\nfunction looksLikeLexicalRoot(value: unknown): boolean {\n if (typeof value !== 'object' || value === null) return false;\n if (!('root' in value)) return false;\n const root = value.root;\n if (typeof root !== 'object' || root === null) return false;\n return Array.isArray((root as { children?: unknown }).children);\n}\n\n/**\n * Default ready broadcaster used when the host does not inject one.\n * Posts to `window.parent` and `window.opener` for each origin.\n */\nfunction defaultSendReady(origins: readonly string[]): void {\n if (typeof window === 'undefined') return;\n const targets: Window[] = [];\n if (window.parent !== window) targets.push(window.parent);\n if (window.opener instanceof Window) targets.push(window.opener);\n MessageBus.sendReady(targets, origins);\n}\n\nfunction sameRevision(a: MessageRevision, b: MessageRevision): boolean {\n return a.generation === b.generation && a.revision === b.revision;\n}\n\n/**\n * Top-level Payload document fields the live-preview engine ships in\n * every update but consumers almost never want to bind to. Suppressing\n * them keeps the orphan-field diagnostic focused on the user's own\n * editable fields.\n */\nconst SYSTEM_FIELD_NAMES: ReadonlySet<string> = new Set([\n 'id',\n '_id',\n 'createdAt',\n 'updatedAt',\n 'createdBy',\n 'updatedBy',\n '_status',\n 'globalType',\n 'collection',\n 'locale',\n 'localized',\n]);\n\n/**\n * Decide whether a value looks like something a `<p data-payload-field>`\n * anchor would render. Strings, numbers, booleans, dates → yes. Objects\n * (Lexical content, relationships, uploads) and arrays → no.\n */\nfunction isLiveBindableScalar(value: unknown): boolean {\n if (value === null || value === undefined) return false;\n return (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean' ||\n typeof value === 'bigint'\n );\n}\n\n/**\n * Strip a trailing `_<locale>` suffix from a field name. Used by the\n * orphan-field diagnostic so a localized variant of a bound field\n * (e.g., `heroTitle_en`) doesn't fire a false warning when the binding\n * is `heroTitle`.\n */\nfunction stripLocaleSuffix(name: string, locale: string | undefined): string {\n if (!locale) return name;\n const suffix = `_${locale}`;\n return name.endsWith(suffix) ? name.slice(0, -suffix.length) : name;\n}\nfunction readElementSnapshot(element: Element): unknown {\n if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {\n return (element as HTMLInputElement).value;\n }\n if (element.tagName === 'IMG') {\n return (element as HTMLImageElement).src;\n }\n return element.textContent;\n}\n\nexport type { CachedElement };\nexport { resolveFieldValue } from './field-value';\n","/**\n * Per-instance, type-safe event emitter.\n *\n * Replaces the legacy module-level singleton. Each `LivePreviewClient`\n * instantiates its own emitter so that calling `destroy()` on one\n * instance cannot clobber listeners attached to another.\n *\n * Design notes:\n *\n * - Generic over an event map type. The default `LivePreviewEventMap`\n * captures every event this library emits, but the implementation\n * is reusable for any map.\n * - Handlers may be `async`. They are awaited sequentially in\n * registration order. This is intentional: `beforeUpdate.cancel()`\n * and similar synchronization rely on stable ordering.\n * - Errors thrown by one handler are logged via `console.error` and\n * do not prevent later handlers from running.\n * - `once()` semantics: registered into a separate map; the entire\n * snapshot for an event is claimed immediately before its dispatch,\n * and remains consumed even if individual handlers throw.\n *\n * @module @events/emitter\n */\n\nimport type { EventHandler, LivePreviewEventMap, Unsubscribe } from './types';\nimport { safeConsoleError } from '@core/diagnostics';\n\ntype AnyHandler = EventHandler<unknown>;\n\n// The constraint `object` (not `Record<string, unknown>`) accommodates\n// interfaces with readonly properties and exact-optional fields without\n// forcing consumers to weaken their type definitions.\nexport class EventEmitter<TMap extends object = LivePreviewEventMap> {\n readonly #regular = new Map<keyof TMap, Set<AnyHandler>>();\n readonly #once = new Map<keyof TMap, Set<AnyHandler>>();\n\n /**\n * Subscribe `handler` to `event`. Returns an unsubscribe function;\n * call it to remove the handler. The handler is invoked for every\n * subsequent emit until unsubscribed.\n */\n on<E extends keyof TMap>(event: E, handler: EventHandler<TMap[E]>): Unsubscribe {\n return this.#register(this.#regular, event, handler as AnyHandler);\n }\n\n /**\n * Subscribe `handler` for a single emit. After the first dispatch,\n * the handler is removed automatically.\n */\n once<E extends keyof TMap>(event: E, handler: EventHandler<TMap[E]>): Unsubscribe {\n return this.#register(this.#once, event, handler as AnyHandler);\n }\n\n /**\n * Remove `handler` from `event`. Works for both `on`- and\n * `once`-registered handlers. No-op when the handler isn't registered.\n */\n off<E extends keyof TMap>(event: E, handler: EventHandler<TMap[E]>): void {\n this.#remove(this.#regular, event, handler as AnyHandler);\n this.#remove(this.#once, event, handler as AnyHandler);\n }\n\n /**\n * Dispatch `payload` to every handler registered for `event`.\n *\n * Handlers run sequentially in registration order — regular ones\n * first, then `once` handlers. Async handlers are awaited. Synchronous\n * exceptions are caught, logged, and isolated to the offending handler.\n */\n async emit<E extends keyof TMap>(event: E, payload: TMap[E]): Promise<void> {\n await this.#emitSequential(event, payload);\n }\n\n /**\n * Lifecycle-only guarded dispatch. The predicate is checked before and after\n * every handler so an async boundary cannot let an obsolete transaction run\n * later callbacks. `emit()` intentionally keeps its established behaviour.\n *\n * Once-handlers are claimed only when dispatch reaches the once phase. Once\n * claimed, the whole snapshot remains consumed even if the predicate changes\n * while one of its handlers is awaiting, matching normal once semantics.\n *\n * @internal\n * @returns `true` when the complete handler sequence ran while eligible.\n */\n async emitWhile<E extends keyof TMap>(\n event: E,\n payload: TMap[E],\n shouldContinue: () => boolean,\n ): Promise<boolean> {\n return this.#emitSequential(event, payload, shouldContinue);\n }\n\n async #emitSequential<E extends keyof TMap>(\n event: E,\n payload: TMap[E],\n shouldContinue?: () => boolean,\n ): Promise<boolean> {\n const eligible = (): boolean => shouldContinue?.() ?? true;\n if (!eligible()) return false;\n const regular = this.#regular.get(event);\n if (regular) {\n for (const handler of [...regular]) {\n if (!eligible()) return false;\n await this.#invoke(handler, payload, event);\n if (!eligible()) return false;\n }\n }\n if (!eligible()) return false;\n const once = this.#once.get(event);\n if (once && once.size > 0) {\n const snapshot = [...once];\n this.#once.delete(event);\n for (const handler of snapshot) {\n if (!eligible()) return false;\n await this.#invoke(handler, payload, event);\n if (!eligible()) return false;\n }\n }\n return eligible();\n }\n\n /**\n * Number of handlers currently registered for `event`.\n * Sum of `on` and `once` registrations.\n */\n listenerCount(event: keyof TMap): number {\n return (this.#regular.get(event)?.size ?? 0) + (this.#once.get(event)?.size ?? 0);\n }\n\n /**\n * Remove every handler. Pass an event name to limit the removal to\n * one event; omit it to clear every event on this emitter.\n *\n * Crucially this only affects the current instance — there is no\n * shared global state.\n */\n removeAllListeners(event?: keyof TMap): void {\n if (event === undefined) {\n this.#regular.clear();\n this.#once.clear();\n return;\n }\n this.#regular.delete(event);\n this.#once.delete(event);\n }\n\n /**\n * Snapshot of all event names that currently have at least one\n * registered handler. Useful for debugging.\n */\n eventNames(): (keyof TMap)[] {\n const names = new Set<keyof TMap>();\n for (const key of this.#regular.keys()) names.add(key);\n for (const key of this.#once.keys()) names.add(key);\n return [...names];\n }\n\n #register(\n bucket: Map<keyof TMap, Set<AnyHandler>>,\n event: keyof TMap,\n handler: AnyHandler,\n ): Unsubscribe {\n let set = bucket.get(event);\n if (!set) {\n set = new Set();\n bucket.set(event, set);\n }\n set.add(handler);\n return () => {\n this.#remove(bucket, event, handler);\n };\n }\n\n #remove(bucket: Map<keyof TMap, Set<AnyHandler>>, event: keyof TMap, handler: AnyHandler): void {\n const set = bucket.get(event);\n if (set === undefined) return;\n set.delete(handler);\n if (set.size === 0) bucket.delete(event);\n }\n\n async #invoke(handler: AnyHandler, payload: unknown, event: keyof TMap): Promise<void> {\n try {\n await handler(payload);\n } catch (err) {\n const label =\n typeof event === 'string' || typeof event === 'number' ? String(event) : '<event>';\n safeConsoleError(`[live-preview] LP0601: handler for \"${label}\" threw:`, err);\n }\n }\n}\n","/**\n * Environment introspection helpers.\n *\n * The detection layer needs to know whether the runtime is currently\n * running inside an iframe, in a popup, in development mode, and\n * whether environment variables are accessible. None of these checks\n * is dramatic on its own, but having a single, tested module avoids\n * the duplicated, subtly-different `typeof process` snippets that\n * accumulated in the legacy implementation.\n *\n * @module @detection/environment\n */\n\n/**\n * Returns `true` when the current window is inside an iframe.\n *\n * Uses a try/catch around `window.self !== window.top` because the\n * comparison throws in cross-origin iframes — and that very throw is\n * itself a definitive \"yes, I am in an iframe\" signal.\n */\nexport function isInIframe(): boolean {\n if (typeof window === 'undefined') return false;\n try {\n return window.self !== window.top;\n } catch {\n return true;\n }\n}\n\n/**\n * Returns `true` when the current window was opened via `window.open()`\n * and the opener reference is still accessible.\n */\nexport function isInPopup(): boolean {\n if (typeof window === 'undefined') return false;\n return window.opener != null;\n}\n\n/**\n * Returns `true` when running in a preview-capable context: iframe or\n * popup. Anything else (top-level navigation) should skip live preview\n * initialisation entirely.\n */\nexport function isInPreviewContext(): boolean {\n return isInIframe() || isInPopup();\n}\n\n/**\n * Returns `true` when the runtime appears to be in development mode.\n *\n * Detection order:\n * 1. `process.env.NODE_ENV !== 'production'`\n * 2. `import.meta.env.DEV === true` (Vite / Astro / SvelteKit)\n * 3. `window.location.hostname` is `localhost`/`127.0.0.1`\n *\n * Returns `false` when none of those are available.\n */\nexport function isDevMode(): boolean {\n const nodeEnv = readNodeEnv();\n if (nodeEnv !== undefined) return nodeEnv !== 'production';\n const importMetaDev = readImportMetaDev();\n if (importMetaDev !== undefined) return importMetaDev;\n if (typeof window !== 'undefined') {\n const host = window.location.hostname;\n if (host === 'localhost' || host === '127.0.0.1') return true;\n }\n return false;\n}\n\n/**\n * Read a named environment variable from whichever runtime exposes it.\n *\n * The variable is first looked up via `process.env`, then via Vite's\n * `import.meta.env`. Returns `undefined` when neither has a value.\n */\nexport function getEnvVar(name: string): string | undefined {\n if (typeof process !== 'undefined') {\n const value = process.env[name];\n if (typeof value === 'string' && value.length > 0) return value;\n }\n const meta = tryReadImportMetaEnv();\n if (meta) {\n const value = meta[name];\n if (typeof value === 'string' && value.length > 0) return value;\n }\n return undefined;\n}\n\nfunction readNodeEnv(): string | undefined {\n if (typeof process === 'undefined') return undefined;\n const value = process.env['NODE_ENV'];\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction readImportMetaDev(): boolean | undefined {\n const meta = tryReadImportMetaEnv();\n if (!meta) return undefined;\n const dev = meta['DEV'];\n return typeof dev === 'boolean' ? dev : undefined;\n}\n\n/**\n * Compile-time flag injected by `scripts/build-runtime.ts`. Inside the\n * inline IIFE `import.meta` can never exist (classic scripts have no\n * module meta, and no bundler rewrites the inline tag), so the probe\n * below is statically disabled there — probing would run `new\n * Function`, which pages with a strict `script-src` (no\n * `unsafe-eval`) report as a CSP violation on every load.\n */\ndeclare const __INLINE_RUNTIME_BUILD__: boolean | undefined;\n\nlet importMetaEnvCache: Record<string, unknown> | null | undefined;\n\n/**\n * Safely read `import.meta.env` without throwing in runtimes that do\n * not support `import.meta`. Returns `undefined` when unavailable.\n *\n * The indirection through `Function('return import.meta...')` is\n * intentional: parsing `import.meta` in CJS bundles fails at parse\n * time. By wrapping it in `Function`, the parse happens lazily and\n * crashes are caught at call time. The result is memoised so the\n * probe (an eval in CSP terms) runs at most once per page.\n */\nfunction tryReadImportMetaEnv(): Record<string, unknown> | undefined {\n if (typeof __INLINE_RUNTIME_BUILD__ !== 'undefined' && __INLINE_RUNTIME_BUILD__) {\n return undefined;\n }\n if (importMetaEnvCache !== undefined) return importMetaEnvCache ?? undefined;\n importMetaEnvCache = null;\n try {\n // eslint-disable-next-line @typescript-eslint/no-implied-eval -- intentional lazy parse\n const reader = new Function(\n 'try { return import.meta && import.meta.env; } catch (_) { return undefined; }',\n ) as () => unknown;\n const result = reader();\n if (result && typeof result === 'object') {\n importMetaEnvCache = result as Record<string, unknown>;\n return importMetaEnvCache;\n }\n } catch {\n // ignore\n }\n return undefined;\n}\n","/**\n * Origin detection and matching.\n *\n * Builds the set of trusted Payload admin origins and exposes a fast\n * matcher used by the message bus. Three sources, in precedence order:\n *\n * 1. Explicit origins passed via configuration. Always trusted.\n * 2. `document.referrer` — **only when no explicit origins are\n * configured**. The browser writes the embedder's origin here\n * when the iframe loads; using it as a fallback gives a\n * zero-config path, but it must never widen an explicit\n * allow-list (the referrer is whoever framed the page, which in\n * an attack is the attacker).\n * 3. Localhost pattern (any port on `localhost` / `127.0.0.1`),\n * enabled when development mode is detected. Replaces the\n * legacy hand-rolled port list.\n *\n * Once the parent's origin is confirmed by an accepted data-bearing\n * update, callers can call `lockOrigin()` to drop every other candidate,\n * making subsequent matches exact. A data-less `ready` handshake does\n * not lock the detector.\n *\n * @module @detection/origin\n */\n\nimport { getEnvVar, isDevMode, isInIframe } from './environment';\n\nconst LOCALHOST_PATTERN = /^https?:\\/\\/(localhost|127\\.0\\.0\\.1)(?::\\d+)?$/i;\nconst VALID_ORIGIN_PATTERN = /^https?:\\/\\/[^/?#\\s]+$/i;\n\nconst ENV_VAR_NAMES = [\n 'PAYLOAD_ADMIN_ORIGIN',\n 'PUBLIC_PAYLOAD_ADMIN_ORIGIN',\n 'NEXT_PUBLIC_PAYLOAD_ADMIN_ORIGIN',\n] as const;\n\nexport interface OriginDetectorOptions {\n /** Explicit additional origins to trust. Always allowed. */\n readonly additionalOrigins?: readonly string[];\n /** Set to `false` to opt out of `document.referrer` detection. */\n readonly enableReferrerDetection?: boolean;\n /** Set to `false` to opt out of localhost-pattern matching. */\n readonly enableLocalhostMatching?: boolean;\n /**\n * Override the dev-mode detection. When `undefined`, dev mode is\n * inferred from the runtime (see `isDevMode`).\n */\n readonly forceDevMode?: boolean;\n /** Override `document.referrer` for tests. */\n readonly referrer?: string;\n}\n\nconst enum OriginSlot {\n ExplicitOrigins,\n ReferrerOrigin,\n AllowLocalhost,\n ReferrerWasAvailable,\n LockedOrigin,\n}\n\ntype OriginState = [\n explicitOrigins: ReadonlySet<string>,\n referrerOrigin: string | undefined,\n allowLocalhost: boolean,\n referrerWasAvailable: boolean,\n lockedOrigin: string | undefined,\n];\n\n/**\n * Holds the resolved origin policy and exposes a matcher.\n *\n * The detector is stateful: it starts with the union of all candidate\n * sources, then narrows down to a single, verified origin once the\n * lifecycle calls `lockOrigin()` for its first accepted data-bearing\n * update.\n */\nexport class OriginDetector {\n readonly #state: OriginState;\n\n constructor(options: OriginDetectorOptions = {}) {\n const explicit = new Set<string>();\n for (const origin of options.additionalOrigins ?? []) {\n const normalised = normaliseOrigin(origin);\n if (normalised !== undefined) explicit.add(normalised);\n }\n for (const envName of ENV_VAR_NAMES) {\n const value = getEnvVar(envName);\n if (value === undefined) continue;\n for (const raw of value.split(',')) {\n const normalised = normaliseOrigin(raw);\n if (normalised !== undefined) explicit.add(normalised);\n }\n }\n const useReferrer = options.enableReferrerDetection ?? true;\n let referrerOrigin: string | undefined;\n if (useReferrer) {\n const referrer =\n options.referrer ?? (typeof document !== 'undefined' ? document.referrer : '');\n if (referrer.length > 0) {\n try {\n const origin = new URL(referrer).origin;\n if (origin && origin !== 'null') referrerOrigin = origin;\n } catch {\n // ignore — referrer is opaque\n }\n }\n }\n const allowLocalhost =\n (options.enableLocalhostMatching ?? true) && (options.forceDevMode ?? isDevMode());\n this.#state = [\n explicit,\n referrerOrigin,\n allowLocalhost,\n referrerOrigin !== undefined,\n undefined,\n ];\n }\n\n /**\n * Returns `true` when `origin` is trusted under the current policy.\n *\n * If an origin has been locked, only that exact value matches.\n * Otherwise explicit origins and (in dev mode) localhost-pattern\n * matches are accepted. The referrer-derived origin is a **fallback,\n * not a union member**: it only counts when NO explicit origins are\n * configured. `document.referrer` always names whoever actually\n * framed the page — if it were unioned with the explicit list, any\n * site embedding the page in an iframe would become a trusted\n * postMessage sender despite the consumer having pinned the admin\n * origin explicitly.\n */\n matches(origin: string): boolean {\n if (origin.length === 0 || origin === 'null') return false;\n if (this.#state[OriginSlot.LockedOrigin] !== undefined) {\n return origin === this.#state[OriginSlot.LockedOrigin];\n }\n if (this.#state[OriginSlot.ExplicitOrigins].has(origin)) return true;\n if (\n this.#state[OriginSlot.ExplicitOrigins].size === 0 &&\n this.#state[OriginSlot.ReferrerOrigin] !== undefined &&\n origin === this.#state[OriginSlot.ReferrerOrigin]\n ) {\n return true;\n }\n if (this.#state[OriginSlot.AllowLocalhost] && LOCALHOST_PATTERN.test(origin)) return true;\n return false;\n }\n\n /**\n * Narrow the trusted set to a single origin after an accepted\n * data-bearing update. Subsequent calls to `matches()` only allow\n * `origin`.\n *\n * Returns `true` if locking succeeded; `false` if the candidate is\n * not currently considered trusted (which would defeat the purpose\n * of locking).\n */\n lockOrigin(origin: string): boolean {\n if (!this.matches(origin)) return false;\n this.#state[OriginSlot.LockedOrigin] = origin;\n return true;\n }\n\n /**\n * Release the origin lock so any allow-listed origin is trusted\n * again until the next accepted data-bearing update. The lifecycle\n * calls this on heartbeat timeout — after the trusted parent disappears,\n * a different (still-allowed) origin should be free to reconnect.\n *\n * Returns the previously-locked origin, or `undefined` when nothing\n * was locked.\n */\n unlockOrigin(): string | undefined {\n const previous = this.#state[OriginSlot.LockedOrigin];\n this.#state[OriginSlot.LockedOrigin] = undefined;\n return previous;\n }\n\n /** The currently locked origin, or `undefined`. */\n get lockedOrigin(): string | undefined {\n return this.#state[OriginSlot.LockedOrigin];\n }\n\n /**\n * Snapshot of every origin currently allowed by the policy. Used by\n * the message bus to broadcast `ready` messages.\n *\n * Localhost pattern matches are expanded into the common dev ports\n * so the handshake can find a Payload running on its usual port.\n */\n enumerate(): string[] {\n if (this.#state[OriginSlot.LockedOrigin] !== undefined) {\n return [this.#state[OriginSlot.LockedOrigin]];\n }\n const result = new Set<string>(this.#state[OriginSlot.ExplicitOrigins]);\n // Referrer is a zero-config fallback only — mirroring matches().\n if (\n this.#state[OriginSlot.ExplicitOrigins].size === 0 &&\n this.#state[OriginSlot.ReferrerOrigin] !== undefined\n ) {\n result.add(this.#state[OriginSlot.ReferrerOrigin]);\n }\n if (this.#state[OriginSlot.AllowLocalhost]) {\n for (const port of LOCALHOST_HANDSHAKE_PORTS) {\n result.add(`http://localhost:${String(port)}`);\n result.add(`http://127.0.0.1:${String(port)}`);\n }\n }\n return [...result];\n }\n\n /**\n * Reports whether `document.referrer` contributed at least one\n * origin. Useful for surfacing a console warning when running in\n * production without an explicit origin and the referrer is absent\n * (because of a `Referrer-Policy: no-referrer` header).\n */\n get referrerWasAvailable(): boolean {\n return this.#state[OriginSlot.ReferrerWasAvailable];\n }\n\n /**\n * Indicates whether the detector is operating in a \"production-without-\n * explicit-origin\" configuration. When `true`, the host should log a\n * loud warning — silent connection failure is the worst outcome.\n */\n get isProductionUnconfigured(): boolean {\n if (!isInIframe()) return false;\n if (this.#state[OriginSlot.ExplicitOrigins].size > 0) return false;\n if (this.#state[OriginSlot.AllowLocalhost]) return false;\n if (this.#state[OriginSlot.ReferrerOrigin] !== undefined) return false;\n return true;\n }\n\n /**\n * `true` when the referrer is the ONLY trust source (no explicit\n * origins, no localhost matching). In that mode any site that frames\n * the page becomes a trusted postMessage sender — `document.referrer`\n * always names the actual embedder. Content is still sanitized, but\n * the origin allow-list no longer restricts who may drive it. Hosts\n * should surface a warning suggesting explicit `allowedOrigins` and\n * a `frame-ancestors` policy in production.\n */\n get isReferrerOnlyTrust(): boolean {\n if (this.#state[OriginSlot.ExplicitOrigins].size > 0) return false;\n if (this.#state[OriginSlot.AllowLocalhost]) return false;\n return this.#state[OriginSlot.ReferrerOrigin] !== undefined;\n }\n}\n\n/**\n * Common ports the inline runtime tries when broadcasting `ready` to\n * a localhost Payload admin. The detection itself uses a pattern, but\n * the handshake needs concrete targets.\n */\nconst LOCALHOST_HANDSHAKE_PORTS: readonly number[] = [\n 3000, 3001, 3333, 4000, 4321, 5000, 5173, 5174, 8000, 8080, 8888, 9000,\n];\n\n/**\n * Validate and canonicalise an origin string. Returns `undefined` for\n * inputs that are not absolute `http(s)://host[:port]` origins.\n */\nexport function normaliseOrigin(value: string): string | undefined {\n const trimmed = value.trim();\n if (trimmed.length === 0) return undefined;\n try {\n const url = new URL(trimmed);\n if (url.protocol !== 'http:' && url.protocol !== 'https:') return undefined;\n if (!VALID_ORIGIN_PATTERN.test(url.origin)) return undefined;\n return url.origin;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Pure-functional check used in inline scripts where instantiating a\n * full `OriginDetector` is overkill. The exported helper is also handy\n * for tests and for consumers that want to mimic the matcher policy\n * without holding state.\n */\nexport function isLocalhostOrigin(origin: string): boolean {\n return LOCALHOST_PATTERN.test(origin);\n}\n","/**\n * Per-instance plugin manager.\n *\n * Every registration receives an isolated resource scope. Event listeners,\n * transforms, renderer layers, and generic cleanups registered through the\n * context are revoked together before the plugin's `destroy()` hook runs.\n * Normal manager mutations are serialized so init, removal, and\n * re-registration cannot expose a partially initialized registration.\n * Mutations requested while an awaited lifecycle hook is pending take a\n * direct transactional path so the hook never waits on a queue entry blocked\n * by itself. Each registration still stages its resources until commit.\n *\n * @module @plugins/manager\n */\n\nimport type { FieldRenderer } from '@core/types';\nimport { isolateDiagnostic } from '@core/diagnostics';\nimport { observeThenableResult } from '@core/thenable';\nimport { EventEmitter } from '@events/emitter';\nimport type { EventHandler, LivePreviewEventMap, Unsubscribe } from '@events/types';\nimport type {\n FieldTransform,\n LivePreviewPlugin,\n PluginContext,\n PluginDisposer,\n PluginEvents,\n} from './types';\n\nexport interface PluginManagerOptions {\n readonly events: EventEmitter;\n readonly config: Readonly<Record<string, unknown>>;\n /** Add one renderer layer to the host. Retains the established void contract. */\n readonly registerFieldRenderer: (renderer: FieldRenderer) => void;\n /** Report transform contract failures to the owning runtime event channel. */\n readonly onTransformError?: (error: Error) => unknown;\n readonly log: (...args: unknown[]) => void;\n}\n\ninterface PluginRegistration {\n readonly plugin: LivePreviewPlugin;\n readonly scope: ResourceScope;\n}\n\ninterface InitializingPluginRegistration {\n readonly scope: ResourceScope;\n cancelled: boolean;\n}\n\ninterface TransformRegistration {\n readonly transform: FieldTransform;\n active: boolean;\n}\n\ninterface OwnedSubscription {\n readonly kind: 'on' | 'once';\n readonly event: keyof LivePreviewEventMap;\n readonly handler: EventHandler<unknown>;\n dispose: Unsubscribe;\n}\n\ninterface ScopedResource {\n readonly acquire: (() => PluginDisposer | undefined) | undefined;\n readonly finalize: (() => void) | undefined;\n cleanup: PluginDisposer | undefined;\n disposed: boolean;\n}\n\nconst noopDisposer: PluginDisposer = () => undefined;\n\nfunction isPluginDisposer(value: unknown): value is PluginDisposer {\n return typeof value === 'function';\n}\n\n/** Registration-local collection of exact, idempotent cleanup handles. */\nclass ResourceScope {\n readonly #pluginName: string;\n readonly #log: (...args: unknown[]) => void;\n // A Set preserves registration order for commit/reverse teardown while\n // allowing short-lived internal resources (notably once listeners) to leave\n // the scope immediately instead of accumulating until plugin removal.\n readonly #resources = new Set<ScopedResource>();\n #state: 'staging' | 'committing' | 'active' | 'closed' = 'staging';\n\n constructor(pluginName: string, log: (...args: unknown[]) => void) {\n this.#pluginName = pluginName;\n this.#log = log;\n }\n\n assertOpen(): void {\n if (this.#state === 'closed') {\n throw new Error(`Plugin context for \"${this.#pluginName}\" is no longer active`);\n }\n }\n\n get active(): boolean {\n return this.#state === 'active';\n }\n\n /** Whether retained facade operations still belong to this registration. */\n eligible(): boolean {\n return this.#state !== 'closed';\n }\n\n /** Own a resource that the plugin itself already acquired. */\n own(cleanup: PluginDisposer): PluginDisposer {\n this.assertOpen();\n return this.#track({\n acquire: undefined,\n finalize: undefined,\n cleanup,\n disposed: false,\n });\n }\n\n /**\n * Stage a manager-owned resource until init commits. Active contexts acquire\n * later registrations immediately; retained closed contexts are rejected.\n */\n stage(acquire: () => PluginDisposer | undefined, finalize?: () => void): PluginDisposer {\n this.assertOpen();\n const resource: ScopedResource = {\n acquire,\n finalize,\n cleanup: undefined,\n disposed: false,\n };\n const dispose = this.#track(resource);\n if (this.#state === 'active') {\n try {\n this.#activate(resource);\n } catch (error) {\n this.#dispose(resource);\n throw error;\n }\n }\n return dispose;\n }\n\n /** Atomically publish every context registration after init succeeds. */\n commit(): void {\n if (this.#state !== 'staging') {\n throw new Error(`Plugin context for \"${this.#pluginName}\" cannot be committed`);\n }\n this.#state = 'committing';\n try {\n for (const resource of this.#resources) this.#activate(resource);\n this.#state = 'active';\n } catch (error) {\n this.close();\n throw error;\n }\n }\n\n close(): void {\n if (this.#state === 'closed') return;\n this.#state = 'closed';\n for (const resource of [...this.#resources].reverse()) this.#dispose(resource);\n this.#resources.clear();\n }\n\n #track(resource: ScopedResource): PluginDisposer {\n this.#resources.add(resource);\n return (): void => {\n this.#dispose(resource);\n };\n }\n\n #activate(resource: ScopedResource): void {\n if (resource.disposed || resource.cleanup !== undefined || resource.acquire === undefined) {\n return;\n }\n const cleanup = resource.acquire();\n resource.cleanup = cleanup ?? noopDisposer;\n }\n\n #dispose(resource: ScopedResource): void {\n if (resource.disposed) return;\n resource.disposed = true;\n this.#resources.delete(resource);\n const cleanup = resource.cleanup;\n resource.cleanup = undefined;\n if (cleanup !== undefined) {\n try {\n // TypeScript's `void` callback convention still permits a JavaScript\n // implementation to return a value. View it through an unknown-return\n // boundary so accidental thenables can be observed without awaiting.\n const cleanupWithResult: () => unknown = cleanup;\n const result = cleanupWithResult();\n if (observeThenableResult(result)) {\n this.#log(\n `plugin \"${this.#pluginName}\" cleanup returned a Promise/thenable; cleanups must be synchronous`,\n );\n }\n } catch (error) {\n this.#log(`plugin \"${this.#pluginName}\" cleanup failed:`, error);\n }\n }\n try {\n resource.finalize?.();\n } catch (error) {\n this.#log(`plugin \"${this.#pluginName}\" cleanup failed:`, error);\n }\n }\n}\n\n/** Event facade that wraps handler identity and owns only this scope's handles. */\nclass ScopedPluginEvents extends EventEmitter implements PluginEvents {\n readonly #events: EventEmitter;\n readonly #scope: ResourceScope;\n readonly #subscriptions = new Set<OwnedSubscription>();\n\n constructor(events: EventEmitter, scope: ResourceScope) {\n super();\n this.#events = events;\n this.#scope = scope;\n }\n\n override on<E extends keyof LivePreviewEventMap>(\n event: E,\n handler: EventHandler<LivePreviewEventMap[E]>,\n ): Unsubscribe {\n return this.#subscribe('on', event, handler);\n }\n\n override once<E extends keyof LivePreviewEventMap>(\n event: E,\n handler: EventHandler<LivePreviewEventMap[E]>,\n ): Unsubscribe {\n return this.#subscribe('once', event, handler);\n }\n\n override off<E extends keyof LivePreviewEventMap>(\n event: E,\n handler: EventHandler<LivePreviewEventMap[E]>,\n ): void {\n const untypedHandler = handler as EventHandler<unknown>;\n for (const subscription of [...this.#subscriptions]) {\n if (subscription.event === event && subscription.handler === untypedHandler) {\n subscription.dispose();\n }\n }\n }\n\n override emit<E extends keyof LivePreviewEventMap>(\n event: E,\n payload: LivePreviewEventMap[E],\n ): Promise<void> {\n this.#scope.assertOpen();\n return this.#events.emit(event, payload);\n }\n\n override emitWhile<E extends keyof LivePreviewEventMap>(\n event: E,\n payload: LivePreviewEventMap[E],\n shouldContinue: () => boolean,\n ): Promise<boolean> {\n this.#scope.assertOpen();\n return this.#events.emitWhile(event, payload, () => {\n if (!this.#scope.eligible()) return false;\n const callerEligible = shouldContinue();\n // The caller predicate is arbitrary, re-entrant plugin code. It may close\n // this scope before returning, so eligibility must bracket its invocation.\n if (!this.#scope.eligible()) return false;\n return callerEligible;\n });\n }\n\n override listenerCount(event: keyof LivePreviewEventMap): number {\n let count = 0;\n for (const subscription of this.#subscriptions) {\n if (subscription.event === event) count += 1;\n }\n return count;\n }\n\n override removeAllListeners(event?: keyof LivePreviewEventMap): void {\n for (const subscription of [...this.#subscriptions]) {\n if (event === undefined || subscription.event === event) subscription.dispose();\n }\n }\n\n override eventNames(): (keyof LivePreviewEventMap)[] {\n const names = new Set<keyof LivePreviewEventMap>();\n for (const subscription of this.#subscriptions) names.add(subscription.event);\n return [...names];\n }\n\n #subscribe<E extends keyof LivePreviewEventMap>(\n kind: 'on' | 'once',\n event: E,\n handler: EventHandler<LivePreviewEventMap[E]>,\n ): Unsubscribe {\n this.#scope.assertOpen();\n\n const untypedHandler = handler as EventHandler<unknown>;\n const existing = [...this.#subscriptions].find(\n (subscription) =>\n subscription.kind === kind &&\n subscription.event === event &&\n subscription.handler === untypedHandler,\n );\n if (existing !== undefined) return existing.dispose;\n\n // Each scope gets a distinct wrapper even when two plugins pass the same\n // handler reference. EventEmitter's Set-based storage can therefore revoke\n // one plugin without accidentally revoking the other.\n let dispose = noopDisposer;\n let subscriptionActive = true;\n const wrapped: EventHandler<LivePreviewEventMap[E]> = async (payload) => {\n if (!this.#scope.active || !subscriptionActive) return;\n // The base emitter removes its once bucket before dispatch. Mirror that\n // timing in scoped introspection and release ownership before invoking\n // arbitrary/re-entrant plugin code.\n if (kind === 'once') dispose();\n await handler(payload);\n };\n const subscription: OwnedSubscription = {\n kind,\n event,\n handler: untypedHandler,\n dispose: noopDisposer,\n };\n dispose = this.#scope.stage(\n () => this.#events[kind](event, wrapped),\n () => {\n subscriptionActive = false;\n this.#subscriptions.delete(subscription);\n },\n );\n subscription.dispose = dispose;\n this.#subscriptions.add(subscription);\n return dispose;\n }\n}\n\nexport class PluginManager {\n readonly #events: EventEmitter;\n readonly #config: Readonly<Record<string, unknown>>;\n // JavaScript preserves an expression callback's actual return even when its\n // public TypeScript contract is void. The client host uses that internal\n // channel for exact renderer ownership; other legacy return values are ignored.\n readonly #registerRenderer: (renderer: FieldRenderer) => unknown;\n readonly #onTransformError: ((error: Error) => void) | undefined;\n readonly #log: (...args: unknown[]) => void;\n readonly #plugins = new Map<string, PluginRegistration>();\n readonly #initializing = new Map<string, InitializingPluginRegistration>();\n readonly #teardowns = new Map<string, Promise<void>>();\n readonly #destroying = new Set<string>();\n readonly #transforms = new Map<string, TransformRegistration[]>();\n #mutationQueue: Promise<void> = Promise.resolve();\n #hookDepth = 0;\n\n constructor(options: PluginManagerOptions) {\n this.#events = options.events;\n this.#config = options.config;\n this.#registerRenderer = options.registerFieldRenderer;\n this.#log = isolateDiagnostic(options.log);\n const onTransformError = options.onTransformError;\n this.#onTransformError =\n onTransformError === undefined\n ? undefined\n : isolateDiagnostic((...args: unknown[]): unknown => {\n const error = args[0];\n if (!(error instanceof Error)) return undefined;\n try {\n return onTransformError(error);\n } catch (reportError) {\n // Preserve the existing best-effort diagnostic for synchronous\n // reporter failures; the outer isolation also observes rejected\n // Promises and hostile thenables without changing transform flow.\n this.#log('transform error reporter failed:', reportError);\n return undefined;\n }\n });\n }\n\n /** Register a plugin transactionally. Concurrent mutations run in call order. */\n register(plugin: LivePreviewPlugin): Promise<void> {\n if (this.#hookDepth > 0) return this.#registerNow(plugin);\n return this.#enqueue(() => this.#registerNow(plugin));\n }\n\n /** Remove one plugin and every resource created by its registration. */\n unregister(name: string): Promise<void> {\n if (this.#hookDepth > 0) return this.#unregisterNow(name);\n return this.#enqueue(async () => {\n await this.#unregisterNow(name);\n });\n }\n\n /** Destroy every active registration without allowing one failure to strand another. */\n destroyAll(): Promise<void> {\n if (this.#hookDepth > 0) return this.#destroyAllNow();\n return this.#enqueue(async () => {\n await this.#destroyAllNow();\n });\n }\n\n /**\n * Apply active transforms in registration order. A failure stops the chain\n * and returns the original merged value, never a partially transformed one.\n */\n applyTransforms(\n fieldName: string,\n value: unknown,\n context: { readonly element: Element; readonly allFields: Record<string, unknown> },\n isCurrent?: () => boolean,\n ): unknown {\n const registrations = this.#transforms.get(fieldName);\n if (registrations === undefined || registrations.length === 0) return value;\n\n let result: unknown = value;\n for (const registration of [...registrations]) {\n if (!registration.active) continue;\n const { transform } = registration;\n if (isCurrent?.() === false) return value;\n try {\n result = transform(result, {\n fieldName,\n element: context.element,\n allFields: context.allFields,\n });\n const returnedThenable = observeThenableResult(result);\n // A transform may synchronously cause a newer live-preview message to\n // be accepted. Observe an invalid Promise to prevent a global\n // rejection, but do not report it or invoke another plugin for work\n // that no longer owns the active lifecycle revision.\n if (isCurrent?.() === false) return value;\n if (returnedThenable) {\n throw new TypeError(\n `Transform for \"${fieldName}\" returned a Promise/thenable; transforms must be synchronous`,\n );\n }\n } catch (error) {\n if (isCurrent?.() === false) return value;\n const normalized = error instanceof Error ? error : new Error(String(error));\n this.#log(`transform for \"${fieldName}\" failed:`, normalized);\n this.#onTransformError?.(normalized);\n return value;\n }\n }\n return result;\n }\n\n /** Names of currently registered plugins. */\n list(): readonly string[] {\n return [...this.#plugins.keys()];\n }\n\n /** Test introspection — number of active plugins. */\n get size(): number {\n return this.#plugins.size;\n }\n\n async #registerNow(plugin: LivePreviewPlugin): Promise<void> {\n if (\n this.#plugins.has(plugin.name) ||\n this.#initializing.has(plugin.name) ||\n this.#teardowns.has(plugin.name)\n ) {\n this.#log(`plugin \"${plugin.name}\" already registered`);\n return;\n }\n\n const scope = new ResourceScope(plugin.name, this.#log);\n const context = this.#createContext(plugin.name, scope);\n const initializing: InitializingPluginRegistration = { scope, cancelled: false };\n this.#initializing.set(plugin.name, initializing);\n try {\n await this.#runHook(() => plugin.init(context));\n if (initializing.cancelled) return;\n scope.commit();\n } catch (error) {\n scope.close();\n if (!initializing.cancelled) this.#log(`plugin \"${plugin.name}\" init failed:`, error);\n return;\n } finally {\n if (this.#initializing.get(plugin.name) === initializing) {\n this.#initializing.delete(plugin.name);\n }\n }\n\n this.#plugins.set(plugin.name, { plugin, scope });\n this.#log(`plugin \"${plugin.name}\" registered`);\n }\n\n #createContext(pluginName: string, scope: ResourceScope): PluginContext {\n return {\n events: new ScopedPluginEvents(this.#events, scope),\n registerFieldRenderer: (renderer) => {\n scope.stage(() => {\n const result = this.#registerRenderer(renderer);\n return isPluginDisposer(result) ? result : undefined;\n });\n },\n registerTransform: (fieldName, transform) => {\n const registration: TransformRegistration = { transform, active: false };\n scope.stage(() => {\n registration.active = true;\n const existing = this.#transforms.get(fieldName);\n if (existing === undefined) this.#transforms.set(fieldName, [registration]);\n else existing.push(registration);\n\n return () => {\n registration.active = false;\n const current = this.#transforms.get(fieldName);\n if (current === undefined) return;\n const index = current.indexOf(registration);\n if (index >= 0) current.splice(index, 1);\n if (current.length === 0) this.#transforms.delete(fieldName);\n };\n });\n },\n registerCleanup: (cleanup) => {\n scope.own(cleanup);\n },\n getConfig: () => this.#config,\n log: (...args) => {\n this.#log(`[${pluginName}]`, ...args);\n },\n };\n }\n\n #unregisterNow(name: string): Promise<void> {\n const initializing = this.#initializing.get(name);\n if (initializing !== undefined) {\n initializing.cancelled = true;\n initializing.scope.close();\n return Promise.resolve();\n }\n\n const existingTeardown = this.#teardowns.get(name);\n if (existingTeardown !== undefined) {\n // A destroy hook awaiting unregister(its own name) cannot await the\n // teardown promise that is awaiting that hook. Its owned resources were\n // already revoked before destroy began, so redundant removals made while\n // that hook is active are complete and resolve immediately.\n if (this.#destroying.has(name)) return Promise.resolve();\n return existingTeardown;\n }\n const registration = this.#plugins.get(name);\n if (registration === undefined) return Promise.resolve();\n\n // Make the registration inactive and revoke its context before invoking\n // consumer code. A throwing destroy hook therefore cannot retain access.\n this.#plugins.delete(name);\n registration.scope.close();\n // Publish the in-flight name reservation before entering arbitrary destroy\n // code. A destroy hook may synchronously try to register the same name; that\n // attempt must remain a duplicate until this teardown has fully settled.\n const teardown = Promise.resolve().then(() => this.#destroyPlugin(name, registration.plugin));\n this.#teardowns.set(name, teardown);\n void teardown.then(() => {\n if (this.#teardowns.get(name) === teardown) this.#teardowns.delete(name);\n });\n return teardown;\n }\n\n async #destroyPlugin(name: string, plugin: LivePreviewPlugin): Promise<void> {\n if (plugin.destroy === undefined) return;\n this.#destroying.add(name);\n try {\n await this.#runHook(() => plugin.destroy?.());\n } catch (error) {\n this.#log(`plugin \"${name}\" destroy failed:`, error);\n } finally {\n this.#destroying.delete(name);\n }\n }\n\n async #destroyAllNow(): Promise<void> {\n for (const initializing of this.#initializing.values()) {\n initializing.cancelled = true;\n initializing.scope.close();\n }\n const names = [...this.#plugins.keys()];\n for (const name of names) await this.#unregisterNow(name);\n }\n\n async #runHook(hook: () => void | Promise<void>): Promise<void> {\n this.#hookDepth += 1;\n try {\n await hook();\n } finally {\n this.#hookDepth -= 1;\n }\n }\n\n #enqueue(operation: () => void | Promise<void>): Promise<void> {\n const result = this.#mutationQueue.then(operation);\n // Keep the internal tail usable even if an unexpected manager error\n // escapes. The caller still receives `result` and can observe the error.\n this.#mutationQueue = result.catch((error: unknown) => {\n this.#log('plugin manager mutation failed:', error);\n });\n return result;\n }\n}\n","/**\n * HTML sanitizer.\n *\n * Uses the browser's parser (via `<template>`) for accurate sanitization\n * and walks the resulting DOM tree to:\n *\n * 1. Strip elements not on the allow-list (scripts removed entirely;\n * others are unwrapped to their text content).\n * 2. Strip every attribute not on the per-tag allow-list, including\n * every `on*` event handler.\n * 3. Validate `href`, `src`, and `srcset` values via `isSafeUrl`.\n * 4. Force `rel=\"noopener noreferrer\"` on external `<a>` elements.\n * 5. Strip `<style>` and any inline `style` attributes entirely\n * (CSS-injection vector eliminated).\n *\n * The DOM dependency is intentional — string-only sanitizers are\n * historically brittle. The function throws `SanitizerEnvironmentError`\n * when no DOM is available so callers fail loudly instead of producing\n * unsanitized output.\n *\n * @module @security/sanitizer\n */\n\nimport { isSafeUrl, isExternalHttpUrl } from './url-validator';\n\n/**\n * HTML elements that pass through sanitization with their content\n * intact. Anything not in this set is unwrapped (text preserved,\n * markup removed) unless it is on the `REMOVE_COMPLETELY` set, in\n * which case it is deleted with its children.\n */\nconst ALLOWED_TAGS: ReadonlySet<string> = new Set([\n 'p',\n 'br',\n 'strong',\n 'b',\n 'em',\n 'i',\n 'u',\n 's',\n 'strike',\n 'mark',\n 'small',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'ul',\n 'ol',\n 'li',\n 'dl',\n 'dt',\n 'dd',\n 'blockquote',\n 'code',\n 'pre',\n 'kbd',\n 'samp',\n 'var',\n 'a',\n 'span',\n 'div',\n 'section',\n 'article',\n 'aside',\n 'header',\n 'footer',\n 'nav',\n 'figure',\n 'figcaption',\n 'img',\n 'picture',\n 'source',\n 'audio',\n 'video',\n 'sub',\n 'sup',\n 'hr',\n 'time',\n 'abbr',\n 'cite',\n 'q',\n 'table',\n 'thead',\n 'tbody',\n 'tfoot',\n 'tr',\n 'th',\n 'td',\n 'caption',\n 'colgroup',\n 'col',\n]);\n\n/**\n * Elements removed entirely (children included). Distinct from the\n * unwrapping fallback because their contents are themselves harmful\n * (script source, CSS, raw HTML, etc.).\n */\nconst REMOVE_COMPLETELY: ReadonlySet<string> = new Set([\n 'script',\n 'style',\n 'iframe',\n 'object',\n 'embed',\n 'link',\n 'meta',\n 'base',\n 'form',\n 'input',\n 'button',\n 'select',\n 'textarea',\n 'svg',\n 'math',\n 'template',\n 'frame',\n 'frameset',\n 'noframes',\n 'noscript',\n]);\n\nconst ATTR_GLOBAL: ReadonlySet<string> = new Set([\n 'id',\n 'class',\n 'lang',\n 'dir',\n 'title',\n 'role',\n 'tabindex',\n]);\n\nconst ATTR_ARIA_PREFIX = 'aria-';\nconst ATTR_DATA_PREFIX = 'data-';\n\nconst ATTR_BY_TAG: Readonly<Record<string, ReadonlySet<string>>> = {\n a: new Set(['href', 'target', 'rel', 'download', 'hreflang', 'type']),\n img: new Set(['src', 'srcset', 'sizes', 'alt', 'width', 'height', 'loading', 'decoding']),\n picture: new Set([]),\n source: new Set(['src', 'srcset', 'sizes', 'type', 'media']),\n audio: new Set(['src', 'controls', 'autoplay', 'loop', 'muted', 'preload']),\n video: new Set([\n 'src',\n 'poster',\n 'controls',\n 'autoplay',\n 'loop',\n 'muted',\n 'preload',\n 'width',\n 'height',\n 'playsinline',\n ]),\n time: new Set(['datetime']),\n abbr: new Set(['title']),\n q: new Set(['cite']),\n blockquote: new Set(['cite']),\n table: new Set(['summary']),\n th: new Set(['colspan', 'rowspan', 'scope', 'headers', 'abbr']),\n td: new Set(['colspan', 'rowspan', 'headers']),\n col: new Set(['span']),\n colgroup: new Set(['span']),\n ol: new Set(['start', 'reversed', 'type']),\n li: new Set(['value']),\n code: new Set(['class']),\n pre: new Set(['class']),\n};\n\nconst URL_ATTRIBUTES: ReadonlySet<string> = new Set(['href', 'src', 'cite', 'poster']);\n\n// DOM nodeType values are standardized across realms. Numeric constants keep\n// an injected SSR document independent from a browser-global `Node` constructor.\nconst ELEMENT_NODE = 1;\nconst COMMENT_NODE = 8;\n\n/**\n * Thrown when `sanitizeHtml` is invoked in an environment without a\n * `document` (e.g., server-side rendering). Callers should catch this\n * and either degrade to plain-text rendering or route the work to a\n * deferred client-side render.\n */\nexport class SanitizerEnvironmentError extends Error {\n override readonly name = 'SanitizerEnvironmentError';\n}\n\nexport interface SanitizeOptions {\n /** Extra tags to allow beyond the built-in list. Lower-case, untrimmed. */\n readonly additionalAllowedTags?: readonly string[];\n /** Extra per-tag attributes to allow. Tag and attribute names must be lower-case. */\n readonly additionalAllowedAttributes?: Readonly<Record<string, readonly string[]>>;\n}\n\ninterface ResolvedPolicy {\n readonly allowedTags: ReadonlySet<string>;\n readonly attrByTag: ReadonlyMap<string, ReadonlySet<string>>;\n}\n\nfunction resolvePolicy(options: SanitizeOptions | undefined): ResolvedPolicy {\n if (!options) {\n const attrMap = new Map<string, ReadonlySet<string>>();\n for (const [tag, attrs] of Object.entries(ATTR_BY_TAG)) attrMap.set(tag, attrs);\n return { allowedTags: ALLOWED_TAGS, attrByTag: attrMap };\n }\n const allowed = new Set(ALLOWED_TAGS);\n for (const tag of options.additionalAllowedTags ?? []) allowed.add(tag);\n const attrMap = new Map<string, ReadonlySet<string>>();\n for (const [tag, attrs] of Object.entries(ATTR_BY_TAG)) attrMap.set(tag, attrs);\n for (const [tag, attrs] of Object.entries(options.additionalAllowedAttributes ?? {})) {\n const existing = attrMap.get(tag);\n const merged = new Set(existing ?? []);\n for (const attr of attrs) merged.add(attr);\n attrMap.set(tag, merged);\n }\n return { allowedTags: allowed, attrByTag: attrMap };\n}\n\n/**\n * Minimal `Document`-shaped surface the sanitizer needs. Any DOM\n * implementation (browser, jsdom, linkedom, happy-dom, parse5 + a\n * thin adapter) that produces `<template>`-style elements works.\n */\nexport interface SanitizerDocument {\n createElement: (tagName: string) => {\n innerHTML: string;\n readonly content: ParentNode;\n };\n}\n\nlet documentOverride: SanitizerDocument | undefined;\n\n/**\n * Inject a `Document` implementation for the sanitizer to use when\n * `globalThis.document` is unavailable.\n *\n * Server-side renderers (Node, Bun, Deno without DOM globals) can wire\n * this up once at startup with any of the popular pure-JS DOM\n * libraries:\n *\n * ```ts\n * // linkedom — recommended (smallest, fastest)\n * import { parseHTML } from 'linkedom';\n * import { setSanitizerDocument } from 'payload-live-preview';\n * const { document } = parseHTML('<!doctype html><html><body></body></html>');\n * setSanitizerDocument(document);\n * ```\n *\n * ```ts\n * // jsdom — heavier, but already in many SSR pipelines\n * import { JSDOM } from 'jsdom';\n * setSanitizerDocument(new JSDOM().window.document);\n * ```\n *\n * Pass `null` to clear a previous override (mostly useful for tests).\n */\nexport function setSanitizerDocument(doc: SanitizerDocument | null): void {\n documentOverride = doc ?? undefined;\n}\n\n/**\n * Sanitize `html` and return safe HTML.\n *\n * The function never returns `undefined`/`null`. On malformed input the\n * browser parser silently recovers and the sanitizer continues from\n * the recovered tree.\n *\n * @throws {SanitizerEnvironmentError} when no DOM is available.\n */\nexport function sanitizeHtml(html: string, options?: SanitizeOptions): string {\n const doc = resolveDocument();\n if (!doc) {\n throw new SanitizerEnvironmentError(\n 'sanitizeHtml needs a DOM; provide one with setSanitizerDocument() during SSR.',\n );\n }\n if (html === '') return '';\n\n const policy = resolvePolicy(options);\n const template = doc.createElement('template');\n template.innerHTML = html;\n sanitizeFragment(template.content, policy);\n return template.innerHTML;\n}\n\nfunction resolveDocument(): SanitizerDocument | undefined {\n if (documentOverride) return documentOverride;\n if (typeof document === 'undefined') return undefined;\n return document;\n}\n\n/**\n * Whether `sanitizeHtml` currently has a DOM to work with — either the\n * global `document` or an override injected via `setSanitizerDocument`.\n * Callers that treat sanitization as an optional defence-in-depth layer\n * (e.g. `lexicalToHtml` during SSR) use this to decide whether the\n * backstop is available instead of probing the `document` global\n * directly, which would ignore the override.\n */\nexport function hasSanitizerDocument(): boolean {\n return resolveDocument() !== undefined;\n}\n\nfunction sanitizeFragment(node: ParentNode, policy: ResolvedPolicy): void {\n // Iterate over a snapshot — we mutate children during the walk.\n for (const child of Array.from(node.childNodes)) {\n if (child.nodeType === ELEMENT_NODE) {\n sanitizeElement(child as Element, policy);\n } else if (child.nodeType === COMMENT_NODE) {\n child.remove();\n }\n }\n}\n\nfunction sanitizeElement(element: Element, policy: ResolvedPolicy): void {\n const tag = element.tagName.toLowerCase();\n\n if (REMOVE_COMPLETELY.has(tag)) {\n element.remove();\n return;\n }\n\n if (!policy.allowedTags.has(tag)) {\n // Unwrap: replace element with its sanitized children.\n sanitizeFragment(element, policy);\n const parent = element.parentNode;\n if (parent) {\n while (element.firstChild) parent.insertBefore(element.firstChild, element);\n element.remove();\n }\n return;\n }\n\n sanitizeAttributes(element, tag, policy);\n\n // Apply rel hardening to external links after attribute sanitization.\n if (tag === 'a') hardenAnchor(element);\n\n sanitizeFragment(element, policy);\n}\n\nfunction sanitizeAttributes(element: Element, tag: string, policy: ResolvedPolicy): void {\n const tagAttrs = policy.attrByTag.get(tag);\n\n for (const attr of Array.from(element.attributes)) {\n const name = attr.name.toLowerCase();\n\n // Strip every event-handler attribute.\n if (name.startsWith('on')) {\n element.removeAttribute(attr.name);\n continue;\n }\n // Strip every style attribute — CSS-injection vector.\n if (name === 'style') {\n element.removeAttribute(attr.name);\n continue;\n }\n // Allow global, ARIA, and data-* attributes universally. They can\n // carry arbitrary strings but no executable sinks (event handlers\n // and `style` were already stripped above).\n if (\n ATTR_GLOBAL.has(name) ||\n name.startsWith(ATTR_ARIA_PREFIX) ||\n name.startsWith(ATTR_DATA_PREFIX)\n ) {\n continue;\n }\n if (tagAttrs?.has(name)) {\n if (URL_ATTRIBUTES.has(name) && !isSafeUrl(attr.value)) {\n element.removeAttribute(attr.name);\n } else if (name === 'srcset' && !isSafeSrcset(attr.value)) {\n element.removeAttribute(attr.name);\n }\n continue;\n }\n element.removeAttribute(attr.name);\n }\n}\n\n/**\n * Validate every candidate URL inside a `srcset` value. The attribute\n * holds a comma-separated list of `<url> [<descriptor>]` pairs; each\n * URL must individually pass `isSafeUrl`. Rejecting the whole\n * attribute on any bad candidate is deliberate — partial rewriting\n * would silently change rendering semantics.\n */\nfunction isSafeSrcset(value: string): boolean {\n const candidates = value.split(',');\n for (const candidate of candidates) {\n const trimmed = candidate.trim();\n if (trimmed.length === 0) continue;\n // `trimmed` is non-empty. Only the URL prefix before the first descriptor\n // separator is needed; slicing avoids manufacturing an optional array item.\n const descriptorStart = trimmed.search(/\\s/);\n const url = descriptorStart === -1 ? trimmed : trimmed.slice(0, descriptorStart);\n if (!isSafeUrl(url)) return false;\n }\n return true;\n}\n\nfunction hardenAnchor(anchor: Element): void {\n const href = anchor.getAttribute('href');\n if (href === null || !isExternalHttpUrl(href)) return;\n anchor.setAttribute('rel', 'noopener noreferrer');\n if (!anchor.hasAttribute('target')) anchor.setAttribute('target', '_blank');\n}\n\n/**\n * Built-in allow-lists, exposed for documentation and tests.\n */\nexport const SANITIZER_POLICY = Object.freeze({\n allowedTags: ALLOWED_TAGS,\n removeCompletely: REMOVE_COMPLETELY,\n globalAttributes: ATTR_GLOBAL,\n attributesByTag: ATTR_BY_TAG,\n urlAttributes: URL_ATTRIBUTES,\n});\n","/**\n * Per-client renderer layers.\n *\n * Built-ins form the immutable base. Plugin registrations add removable\n * layers per field type; the newest active layer wins. Removing a layer by\n * identity leaves unrelated types and newer layers untouched.\n *\n * @module @plugins/renderer-registry\n */\n\nimport type { FieldRenderer, FieldType } from '@core/types';\nimport type { PluginDisposer } from './types';\n\ninterface RendererLayer {\n readonly renderer: FieldRenderer;\n}\n\nexport class RendererRegistry {\n readonly #base: Readonly<Record<string, FieldRenderer>>;\n readonly #active: Record<string, FieldRenderer>;\n readonly #layers = new Map<FieldType, RendererLayer[]>();\n\n constructor(base: Readonly<Record<string, FieldRenderer>>) {\n this.#base = base;\n this.#active = { ...base };\n }\n\n /** Stable live map retained for the legacy runtime renderer option. */\n get renderers(): Readonly<Record<string, FieldRenderer>> {\n return this.#active;\n }\n\n resolve(fieldType: FieldType): FieldRenderer | undefined {\n return this.#active[fieldType];\n }\n\n register(renderer: FieldRenderer): PluginDisposer {\n const fieldType = renderer.name;\n const layer: RendererLayer = { renderer };\n const stack = this.#layers.get(fieldType);\n if (stack === undefined) this.#layers.set(fieldType, [layer]);\n else stack.push(layer);\n this.#active[fieldType] = renderer;\n\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n\n const current = this.#layers.get(fieldType);\n if (current === undefined) return;\n const index = current.indexOf(layer);\n if (index < 0) return;\n const wasTop = index === current.length - 1;\n current.splice(index, 1);\n if (current.length === 0) this.#layers.delete(fieldType);\n if (!wasTop) return;\n\n const previousLayer = current.at(-1);\n const previousRenderer = previousLayer?.renderer ?? this.#base[fieldType];\n if (previousRenderer === undefined) Reflect.deleteProperty(this.#active, fieldType);\n else this.#active[fieldType] = previousRenderer;\n };\n }\n}\n","/**\n * Lexical node-renderer registry.\n *\n * Each Payload Lexical node type maps to one renderer module under\n * `./nodes/`. The registry pattern keeps each node's logic in its own\n * file (clean separation of concerns) and lets consumers register\n * custom renderers via the plugin system without touching this module.\n *\n * @module @lexical/registry\n */\n\nimport type { LexicalNode } from './types';\n\n/**\n * Context passed to node renderers. Includes the recursive renderer\n * for children and the `alignment` resolver so block-level nodes can\n * apply paragraph/heading alignment uniformly.\n */\nexport interface RenderNodeContext {\n /**\n * Render an arbitrary list of children. Handles whitespace, falls\n * through to text renderers, and honours the registry. Renderers\n * call this to render their own descendants.\n */\n readonly renderChildren: (children: readonly LexicalNode[]) => string;\n /**\n * Resolve the textual alignment for a block-level node. Returns\n * `undefined` when no alignment is specified.\n */\n readonly resolveAlignment: (node: LexicalNode) => string | undefined;\n /**\n * Resolve the indent count for a node. Used to build inline indent\n * styles for paragraphs and list items.\n */\n readonly resolveIndent: (node: LexicalNode) => number;\n}\n\n/** Renderer signature: `(node, ctx) => htmlString`. */\nexport type NodeRenderer = (node: LexicalNode, context: RenderNodeContext) => string;\n\n/**\n * Mutable registry. Built-in node renderers populate the map at\n * import time; consumer code may extend it via `register`.\n */\nconst registry = new Map<string, NodeRenderer>();\n\n/**\n * Register or replace the renderer for `type`.\n */\nexport function register(type: string, renderer: NodeRenderer): void {\n registry.set(type, renderer);\n}\n\n/** Look up the renderer for `type`, or `undefined`. */\nexport function lookup(type: string): NodeRenderer | undefined {\n return registry.get(type);\n}\n\n/** Snapshot of registered node types. Useful for diagnostics. */\nexport function registeredTypes(): readonly string[] {\n return [...registry.keys()];\n}\n\n/** Test-only helper: clear the registry. */\nexport function __resetForTests(): void {\n registry.clear();\n}\n","/**\n * Shared utilities for Lexical node renderers.\n *\n * @module @lexical/utils\n */\n\nimport type { LexicalNode } from './types';\n\nconst ALIGNMENT_NUMERIC: Readonly<Record<number, string>> = {\n 1: 'left',\n 2: 'center',\n 3: 'right',\n 4: 'justify',\n};\n\nconst ALIGNMENT_STRING = new Set(['left', 'center', 'right', 'justify', 'start', 'end']);\n\n/**\n * Resolve the `text-align` value for a block-level Lexical node.\n *\n * Payload's Lexical serializer historically emits both string formats\n * (`'left'`) and a numeric bitmask in `format`. We honour both forms.\n */\nexport function resolveAlignment(node: LexicalNode): string | undefined {\n const fmt = node.format;\n if (typeof fmt === 'string' && ALIGNMENT_STRING.has(fmt)) return fmt;\n if (typeof fmt === 'number') {\n const mapped = ALIGNMENT_NUMERIC[fmt];\n if (mapped !== undefined) return mapped;\n }\n return undefined;\n}\n\n/**\n * Resolve the indent depth for a node. Defaults to `0`.\n */\nexport function resolveIndent(node: LexicalNode): number {\n const indent = node.indent;\n return typeof indent === 'number' && indent > 0 ? indent : 0;\n}\n\n/**\n * Build the `dir=\"...\"` attribute for a node when a direction is set.\n */\nexport function dirAttribute(node: LexicalNode): string {\n if (node.direction === 'rtl') return ' dir=\"rtl\"';\n if (node.direction === 'ltr') return ' dir=\"ltr\"';\n return '';\n}\n\n/**\n * Build a `style` attribute combining `text-align` and `padding-inline-start`\n * (the standard way Lexical maps indent to CSS).\n */\nexport function styleAttribute(node: LexicalNode): string {\n const align = resolveAlignment(node);\n const indent = resolveIndent(node);\n const styles: string[] = [];\n if (align !== undefined) styles.push(`text-align:${align}`);\n if (indent > 0) styles.push(`padding-inline-start:${String(indent * 40)}px`);\n if (styles.length === 0) return '';\n return ` style=\"${styles.join(';')}\"`;\n}\n","/**\n * HTML-escape primitives.\n *\n * Implementations follow the OWASP XSS Prevention Cheat Sheet: each\n * special character is replaced with its decimal or hex entity. The\n * functions are isomorphic — they have no dependency on the DOM and\n * can run in any JavaScript environment (browser, Node, Deno, Bun).\n *\n * @module @security/escape\n */\n\nconst HTML_ESCAPES: Readonly<Record<string, string>> = Object.freeze({\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#x27;',\n '/': '&#x2F;',\n '`': '&#x60;',\n '=': '&#x3D;',\n});\n\nconst HTML_ESCAPE_PATTERN = /[&<>\"'/`=]/g;\n\n/**\n * Escape every HTML-significant character in `text` so the result is\n * safe to interpolate into any HTML context (element body or attribute).\n *\n * - Coerces non-strings via `String(value)`; pass `null`/`undefined`\n * intentionally — they become `\"null\"`/`\"undefined\"`.\n * - Cannot fail; returns `\"\"` for the empty input.\n */\nexport function escapeHtml(text: string): string {\n if (text === '') return '';\n // The regex character class and the HTML_ESCAPES map are intentionally\n // coupled — every match is guaranteed to be a key in the map.\n // eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style\n return text.replace(HTML_ESCAPE_PATTERN, (char) => HTML_ESCAPES[char] as string);\n}\n\n/**\n * Escape characters that have special meaning inside a CSS `url(...)`\n * literal so an attacker cannot break out of a value.\n *\n * Use only when constructing CSS at runtime (e.g.,\n * `style.backgroundImage`). Combined with a passing `isSafeUrl()` this\n * eliminates the CSS-injection vector for media URLs.\n */\nexport function escapeCssUrl(value: string): string {\n return value.replace(/['\"()\\\\]/g, '\\\\$&');\n}\n\nconst ATTR_ESCAPES: Readonly<Record<string, string>> = Object.freeze({\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#x27;',\n});\n\nconst ATTR_ESCAPE_PATTERN = /[&<>\"']/g;\n\n/**\n * Escape characters that would break out of a double-quoted HTML\n * attribute value. Stricter than `escapeHtml` for body content but\n * preserves URL characters (`/`, `=`, etc.) that are common in\n * `href` and `src` values.\n *\n * Only call this for values that have already been validated as safe\n * URLs or trusted strings; it does NOT block dangerous protocols.\n */\nexport function escapeHtmlAttribute(value: string): string {\n if (value === '') return '';\n // eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style\n return value.replace(ATTR_ESCAPE_PATTERN, (char) => ATTR_ESCAPES[char] as string);\n}\n\n/**\n * Escape newlines into `<br>` tags after HTML-escaping the input.\n *\n * The order is critical: escape first, then introduce the `<br>` markers.\n * Reversing the order would let an attacker inject HTML by smuggling\n * `<br>` boundaries around malicious content.\n */\nexport function escapeAndLinebreak(text: string): string {\n return escapeHtml(text).replace(/\\r\\n|\\r|\\n/g, '<br>');\n}\n","/**\n * Public Lexical node types.\n *\n * Mirrors the shape Payload's Lexical serializer emits in\n * `fields.<richTextField>` payloads. We only require the discriminator\n * `type` field and the optional `children` array — every other\n * property is opaque and forwarded as-is to the renderer that handles\n * the node type.\n *\n * @module @lexical/types\n */\n\n/**\n * Bitmask of Lexical text-format flags.\n *\n * Multiple flags can be combined: `BOLD | ITALIC = 3`.\n */\nexport const TextFormat = {\n BOLD: 1,\n ITALIC: 2,\n STRIKETHROUGH: 4,\n UNDERLINE: 8,\n CODE: 16,\n SUBSCRIPT: 32,\n SUPERSCRIPT: 64,\n HIGHLIGHT: 128,\n} as const;\n\n/**\n * Generic Lexical node. Concrete renderers consume specific subtypes\n * through narrow type guards in their own modules.\n */\nexport interface LexicalNode {\n readonly type: string;\n readonly version?: number;\n readonly format?: number | string;\n readonly indent?: number;\n readonly direction?: 'ltr' | 'rtl' | null;\n readonly children?: readonly LexicalNode[];\n readonly text?: string;\n readonly [extra: string]: unknown;\n}\n\n/**\n * Root of a Lexical document.\n */\nexport interface LexicalRoot {\n readonly root: {\n readonly type?: string;\n readonly children: readonly LexicalNode[];\n readonly direction?: 'ltr' | 'rtl' | null;\n readonly format?: number | string;\n readonly indent?: number;\n readonly [extra: string]: unknown;\n };\n}\n","/**\n * Renderer for Lexical `text` nodes.\n *\n * Applies every standard format flag in a stable order so identical\n * inputs always produce identical output (important for snapshot tests\n * and tree-diff workflows).\n *\n * @module @lexical/nodes/text\n */\n\nimport { escapeHtml } from '@security/escape';\nimport type { LexicalNode } from '../types';\nimport { TextFormat } from '../types';\nimport type { NodeRenderer } from '../registry';\n\nconst textRenderer: NodeRenderer = (node: LexicalNode): string => {\n const raw = typeof node.text === 'string' ? node.text : '';\n let out = escapeHtml(raw);\n const format = typeof node.format === 'number' ? node.format : 0;\n if ((format & TextFormat.CODE) !== 0) out = `<code>${out}</code>`;\n if ((format & TextFormat.BOLD) !== 0) out = `<strong>${out}</strong>`;\n if ((format & TextFormat.ITALIC) !== 0) out = `<em>${out}</em>`;\n if ((format & TextFormat.UNDERLINE) !== 0) out = `<u>${out}</u>`;\n if ((format & TextFormat.STRIKETHROUGH) !== 0) out = `<s>${out}</s>`;\n if ((format & TextFormat.SUBSCRIPT) !== 0) out = `<sub>${out}</sub>`;\n if ((format & TextFormat.SUPERSCRIPT) !== 0) out = `<sup>${out}</sup>`;\n if ((format & TextFormat.HIGHLIGHT) !== 0) out = `<mark>${out}</mark>`;\n return out;\n};\n\nexport { textRenderer };\n","/**\n * Renderer for Lexical `paragraph` nodes.\n *\n * Honours `direction`, `format` (alignment), and `indent`.\n *\n * @module @lexical/nodes/paragraph\n */\n\nimport type { NodeRenderer } from '../registry';\nimport { dirAttribute, styleAttribute } from '../utils';\n\nconst paragraphRenderer: NodeRenderer = (node, ctx): string => {\n const children = ctx.renderChildren(node.children ?? []);\n return `<p${dirAttribute(node)}${styleAttribute(node)}>${children}</p>`;\n};\n\nexport { paragraphRenderer };\n","/**\n * Renderer for Lexical `heading` nodes.\n *\n * Validates the `tag` against the standard H1-H6 set; falls back to\n * `h2` for unknown values (Lexical occasionally emits non-standard\n * tags during transient editor states).\n *\n * @module @lexical/nodes/heading\n */\n\nimport type { NodeRenderer } from '../registry';\nimport { dirAttribute, styleAttribute } from '../utils';\n\nconst VALID_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);\n\nconst headingRenderer: NodeRenderer = (node, ctx): string => {\n const tagRaw = typeof node['tag'] === 'string' ? node['tag'].toLowerCase() : 'h2';\n const tag = VALID_TAGS.has(tagRaw) ? tagRaw : 'h2';\n const children = ctx.renderChildren(node.children ?? []);\n return `<${tag}${dirAttribute(node)}${styleAttribute(node)}>${children}</${tag}>`;\n};\n\nexport { headingRenderer };\n","/**\n * Renderer for Lexical `list` and `listitem` nodes.\n *\n * Recognises three list types:\n * - `bullet` → `<ul>`\n * - `number` → `<ol>` (forwards `start` and `reversed` when present)\n * - `check` → `<ul role=\"list\">` with `aria-checked` per item\n *\n * @module @lexical/nodes/list\n */\n\nimport { escapeHtml } from '@security/escape';\nimport type { NodeRenderer } from '../registry';\nimport { dirAttribute, styleAttribute } from '../utils';\n\nconst listRenderer: NodeRenderer = (node, ctx): string => {\n const listType = typeof node['listType'] === 'string' ? node['listType'] : 'bullet';\n const tag = listType === 'number' ? 'ol' : 'ul';\n const startAttr =\n listType === 'number' && typeof node['start'] === 'number' && node['start'] > 1\n ? ` start=\"${String(node['start'])}\"`\n : '';\n const checkAttr = listType === 'check' ? ' role=\"list\"' : '';\n const children = ctx.renderChildren(node.children ?? []);\n return `<${tag}${dirAttribute(node)}${styleAttribute(node)}${startAttr}${checkAttr}>${children}</${tag}>`;\n};\n\nconst listItemRenderer: NodeRenderer = (node, ctx): string => {\n const children = ctx.renderChildren(node.children ?? []);\n if (typeof node['checked'] === 'boolean') {\n const state = node['checked'] ? 'true' : 'false';\n return `<li role=\"checkbox\" aria-checked=\"${state}\"${styleAttribute(node)}>${children}</li>`;\n }\n const valueAttr =\n typeof node['value'] === 'number' ? ` value=\"${escapeHtml(String(node['value']))}\"` : '';\n return `<li${dirAttribute(node)}${styleAttribute(node)}${valueAttr}>${children}</li>`;\n};\n\nexport { listRenderer, listItemRenderer };\n","/**\n * Renderer for Lexical `link` and `autolink` nodes.\n *\n * URLs are validated by `isSafeUrl`; unsafe URLs cause the renderer to\n * emit just the link's children, dropping the `<a>` wrapper entirely.\n *\n * External HTTP(S) targets get `target=\"_blank\"` and `rel=\"noopener\n * noreferrer\"` automatically.\n *\n * @module @lexical/nodes/link\n */\n\nimport { escapeHtml, escapeHtmlAttribute } from '@security/escape';\nimport { isExternalHttpUrl, isSafeUrl } from '@security/url-validator';\nimport type { NodeRenderer } from '../registry';\n\nconst linkRenderer: NodeRenderer = (node, ctx): string => {\n const url = typeof node['url'] === 'string' ? node['url'] : '';\n const children = ctx.renderChildren(node.children ?? []);\n\n if (url.length === 0 || !isSafeUrl(url)) return children;\n\n const targetAttr = isExternalHttpUrl(url)\n ? ' target=\"_blank\" rel=\"noopener noreferrer\"'\n : buildOptionalAttrs(node);\n const titleAttr =\n typeof node['title'] === 'string' ? ` title=\"${escapeHtml(node['title'])}\"` : '';\n return `<a href=\"${escapeHtmlAttribute(url)}\"${targetAttr}${titleAttr}>${children}</a>`;\n};\n\n/**\n * For non-external links Payload may still embed an explicit `target`.\n * We honour it but never let the consumer skip the `noopener noreferrer`\n * pair for `target=\"_blank\"` — security-critical.\n */\nfunction buildOptionalAttrs(node: Record<string, unknown>): string {\n const target = typeof node['target'] === 'string' ? node['target'] : '';\n if (target.length === 0) return '';\n const safeTarget = escapeHtml(target);\n if (target === '_blank') return ` target=\"_blank\" rel=\"noopener noreferrer\"`;\n return ` target=\"${safeTarget}\"`;\n}\n\nexport { linkRenderer };\n","/**\n * Renderer for Lexical `quote` nodes.\n *\n * @module @lexical/nodes/quote\n */\n\nimport type { NodeRenderer } from '../registry';\nimport { dirAttribute, styleAttribute } from '../utils';\n\nconst quoteRenderer: NodeRenderer = (node, ctx): string => {\n const children = ctx.renderChildren(node.children ?? []);\n return `<blockquote${dirAttribute(node)}${styleAttribute(node)}>${children}</blockquote>`;\n};\n\nexport { quoteRenderer };\n","/**\n * Renderer for Lexical `code` (block-level fenced code) and inline\n * `code-highlight` nodes.\n *\n * Block code: `<pre><code class=\"language-...\">` (language sanitised).\n * Inline highlight tokens: `<code class=\"...\">`.\n *\n * @module @lexical/nodes/code\n */\n\nimport { escapeHtml } from '@security/escape';\nimport type { NodeRenderer } from '../registry';\nimport type { LexicalNode } from '../types';\n\nconst codeRenderer: NodeRenderer = (node): string => {\n const language = sanitizeLangClass(typeof node['language'] === 'string' ? node['language'] : '');\n const inner = extractText(node);\n const langClass = language === '' ? '' : ` class=\"language-${language}\"`;\n return `<pre><code${langClass}>${escapeHtml(inner)}</code></pre>`;\n};\n\nconst codeHighlightRenderer: NodeRenderer = (node): string => {\n const text = typeof node.text === 'string' ? node.text : '';\n const highlight =\n typeof node['highlightType'] === 'string'\n ? ` class=\"token-${sanitizeLangClass(node['highlightType'])}\"`\n : '';\n return `<span${highlight}>${escapeHtml(text)}</span>`;\n};\n\nexport { codeRenderer, codeHighlightRenderer };\n\nfunction extractText(node: LexicalNode): string {\n if (typeof node.text === 'string') return node.text;\n if (!node.children) return '';\n let out = '';\n for (const child of node.children) out += extractText(child);\n return out;\n}\n\nfunction sanitizeLangClass(value: string): string {\n return value.replace(/[^a-zA-Z0-9_-]/g, '');\n}\n","/**\n * Renderers for `linebreak`, `horizontalrule`, and `tab` Lexical nodes.\n *\n * @module @lexical/nodes/linebreak\n */\n\nimport type { NodeRenderer } from '../registry';\n\nconst linebreakRenderer: NodeRenderer = () => '<br>';\nconst horizontalRuleRenderer: NodeRenderer = () => '<hr>';\nconst tabRenderer: NodeRenderer = () => '\\t';\n\nexport { linebreakRenderer, horizontalRuleRenderer, tabRenderer };\n","/**\n * Renderer for Lexical `upload` nodes — Payload's inline-media block.\n *\n * Recognises the standard Payload upload shape:\n * {\n * type: 'upload',\n * relationTo: 'media',\n * value: { url, alt, width, height, mimeType, ... },\n * }\n *\n * Renders an `<img>` for raster/SVG MIME types, a `<video>` for video\n * MIME types, a fallback `<a>` link otherwise. URLs are validated by\n * `isSafeUrl` — unsafe URLs collapse to an empty string rather than\n * exposing the user to a redirect-style attack.\n *\n * @module @lexical/nodes/upload\n */\n\nimport { escapeHtml, escapeHtmlAttribute } from '@security/escape';\nimport { isSafeUrl } from '@security/url-validator';\nimport type { NodeRenderer } from '../registry';\n\ninterface UploadValue {\n readonly url?: string;\n readonly alt?: string;\n readonly width?: number;\n readonly height?: number;\n readonly mimeType?: string;\n readonly filename?: string;\n}\n\nconst uploadRenderer: NodeRenderer = (node): string => {\n const value = readUploadValue(node);\n if (value === undefined) return '';\n const url = value.url;\n if (typeof url !== 'string' || !isSafeUrl(url)) return '';\n\n const mime = typeof value.mimeType === 'string' ? value.mimeType : '';\n if (mime.startsWith('video/')) return renderVideo(value, url);\n if (mime.startsWith('audio/')) return renderAudio(value, url);\n if (mime === '' || mime.startsWith('image/')) return renderImage(value, url);\n return renderFallbackLink(value, url);\n};\n\nexport { uploadRenderer };\n\nfunction readUploadValue(node: Record<string, unknown>): UploadValue | undefined {\n const raw = node['value'];\n if (typeof raw !== 'object' || raw === null) return undefined;\n return raw;\n}\n\nfunction renderImage(value: UploadValue, url: string): string {\n const alt = typeof value.alt === 'string' ? escapeHtml(value.alt) : '';\n const width = typeof value.width === 'number' ? ` width=\"${String(value.width)}\"` : '';\n const height = typeof value.height === 'number' ? ` height=\"${String(value.height)}\"` : '';\n return `<img src=\"${escapeHtmlAttribute(url)}\" alt=\"${alt}\"${width}${height} loading=\"lazy\" decoding=\"async\">`;\n}\n\nfunction renderVideo(value: UploadValue, url: string): string {\n const width = typeof value.width === 'number' ? ` width=\"${String(value.width)}\"` : '';\n const height = typeof value.height === 'number' ? ` height=\"${String(value.height)}\"` : '';\n const type =\n typeof value.mimeType === 'string' ? ` type=\"${escapeHtmlAttribute(value.mimeType)}\"` : '';\n return `<video controls${width}${height}><source src=\"${escapeHtmlAttribute(url)}\"${type}></video>`;\n}\n\nfunction renderAudio(value: UploadValue, url: string): string {\n const type =\n typeof value.mimeType === 'string' ? ` type=\"${escapeHtmlAttribute(value.mimeType)}\"` : '';\n return `<audio controls><source src=\"${escapeHtmlAttribute(url)}\"${type}></audio>`;\n}\n\nfunction renderFallbackLink(value: UploadValue, url: string): string {\n const label = typeof value.filename === 'string' ? escapeHtml(value.filename) : escapeHtml(url);\n return `<a href=\"${escapeHtmlAttribute(url)}\" target=\"_blank\" rel=\"noopener noreferrer\">${label}</a>`;\n}\n","/**\n * Renderer for Lexical `relationship` nodes — inline references to\n * documents in other collections.\n *\n * We do not know how the consumer wants to render relationships, so\n * we emit a semantic `<a>` (or `<span>` when no URL field is present)\n * and tag it with `data-relation-to` so consumers can post-process.\n *\n * @module @lexical/nodes/relationship\n */\n\nimport { escapeHtml, escapeHtmlAttribute } from '@security/escape';\nimport { isSafeUrl } from '@security/url-validator';\nimport type { NodeRenderer } from '../registry';\n\ninterface RelationshipValue {\n readonly title?: string;\n readonly name?: string;\n readonly slug?: string;\n readonly id?: string | number;\n readonly url?: string;\n}\n\nconst relationshipRenderer: NodeRenderer = (node): string => {\n const relationTo = typeof node['relationTo'] === 'string' ? node['relationTo'] : '';\n const value = readValue(node);\n const label = pickLabel(value, relationTo);\n const safeLabel = escapeHtml(label);\n const relAttr = relationTo === '' ? '' : ` data-relation-to=\"${escapeHtml(relationTo)}\"`;\n\n const url = value?.url;\n if (typeof url === 'string' && isSafeUrl(url)) {\n return `<a href=\"${escapeHtmlAttribute(url)}\"${relAttr}>${safeLabel}</a>`;\n }\n return `<span${relAttr}>${safeLabel}</span>`;\n};\n\nexport { relationshipRenderer };\n\nfunction readValue(node: Record<string, unknown>): RelationshipValue | undefined {\n const raw = node['value'];\n if (typeof raw !== 'object' || raw === null) return undefined;\n return raw;\n}\n\nfunction pickLabel(value: RelationshipValue | undefined, relationTo: string): string {\n if (value === undefined) return relationTo === '' ? '#' : `#${relationTo}`;\n if (typeof value.title === 'string' && value.title.length > 0) return value.title;\n if (typeof value.name === 'string' && value.name.length > 0) return value.name;\n if (typeof value.slug === 'string' && value.slug.length > 0) return value.slug;\n if (value.id !== undefined) return String(value.id);\n return relationTo === '' ? '#' : `#${relationTo}`;\n}\n","/**\n * Block-renderer sub-registry.\n *\n * Payload's BlocksFeature emits Lexical `block` nodes with a\n * `blockType` slug. The default `block`-node renderer (in\n * `../nodes/block.ts`) only emits a generic\n * `<div data-block-type=\"…\">` — useful as a hook, but unhelpful when\n * the consumer wants out-of-the-box rendering for common block types.\n *\n * This registry maps `blockType` → renderer. Default renderers ship\n * for the most common Payload block patterns (callout, image,\n * video, code, cta). Custom slugs override defaults via\n * `registerBlockRenderer(slug, renderer)`.\n *\n * @module @lexical/blocks/registry\n */\n\nimport type { LexicalNode } from '../types';\n\n/**\n * Context passed to a block renderer. Includes the recursive\n * `renderChildren` function so blocks that house nested Lexical\n * content can delegate back to the main renderer.\n */\nexport interface BlockRenderContext {\n /** Renders a list of Lexical children to HTML. */\n readonly renderChildren: (children: readonly LexicalNode[]) => string;\n}\n\n/**\n * Renderer signature. Receives the block node *and* its already-read\n * `fields` payload (the parser pulls these out so individual block\n * renderers don't have to reach into `node['fields']` themselves).\n */\nexport type BlockRenderer = (\n fields: Record<string, unknown>,\n context: BlockRenderContext,\n) => string;\n\nconst registry = new Map<string, BlockRenderer>();\n\n/** Register or replace the renderer for `blockType`. */\nexport function registerBlockRenderer(blockType: string, renderer: BlockRenderer): void {\n registry.set(blockType, renderer);\n}\n\n/** Look up the renderer for `blockType`, or `undefined`. */\nexport function lookupBlockRenderer(blockType: string): BlockRenderer | undefined {\n return registry.get(blockType);\n}\n\n/** Snapshot of registered block types — useful for diagnostics. */\nexport function registeredBlockTypes(): readonly string[] {\n return [...registry.keys()];\n}\n\n/** Test-only: clear the registry. */\nexport function __resetBlockRegistryForTests(): void {\n registry.clear();\n}\n","/**\n * Renderer for Lexical `block` nodes — Payload's custom-blocks feature\n * (the `BlocksFeature` of `@payloadcms/richtext-lexical`).\n *\n * The Lexical serializer emits a block as:\n * {\n * type: 'block',\n * fields: { blockType: 'callout', text: '...', ... },\n * }\n *\n * Dispatch order:\n *\n * 1. The blocks sub-registry (`./blocks/registry.ts`) is consulted\n * first. Consumers opt into the default renderer set via\n * `registerDefaultBlocks()`; custom slugs override via\n * `registerBlockRenderer()`.\n * 2. Falling through, the generic renderer emits a\n * `<div data-block-type=\"…\">` annotated with each field as a\n * `data-block-<key>` attribute, so consumer CSS / hydration can\n * pick the block up.\n *\n * @module @lexical/nodes/block\n */\n\nimport { escapeHtml } from '@security/escape';\nimport { lookupBlockRenderer } from '../blocks/registry';\nimport type { NodeRenderer } from '../registry';\n\nconst blockRenderer: NodeRenderer = (node, ctx): string => {\n const fields = readFields(node);\n const blockTypeRaw = typeof fields['blockType'] === 'string' ? fields['blockType'] : '';\n const slug = sanitizeIdent(blockTypeRaw);\n\n if (blockTypeRaw !== '') {\n const custom = lookupBlockRenderer(blockTypeRaw) ?? lookupBlockRenderer(slug);\n if (custom) {\n return custom(fields, { renderChildren: ctx.renderChildren });\n }\n }\n\n const attrs: string[] = [];\n if (slug !== '') attrs.push(`data-block-type=\"${escapeHtml(slug)}\"`);\n for (const [key, value] of Object.entries(fields)) {\n if (key === 'blockType' || key === 'id') continue;\n if (value === null || value === undefined) continue;\n const stringValue =\n typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean'\n ? String(value)\n : JSON.stringify(value);\n attrs.push(`data-block-${sanitizeIdent(key)}=\"${escapeHtml(stringValue)}\"`);\n }\n const attrString = attrs.length === 0 ? '' : ` ${attrs.join(' ')}`;\n return `<div${attrString}></div>`;\n};\n\nexport { blockRenderer };\n\nfunction readFields(node: Record<string, unknown>): Record<string, unknown> {\n const raw = node['fields'];\n if (typeof raw !== 'object' || raw === null) return {};\n return raw as Record<string, unknown>;\n}\n\nfunction sanitizeIdent(value: string): string {\n return value.replace(/[^a-zA-Z0-9_-]/g, '-').toLowerCase();\n}\n","/**\n * Top-level Lexical → HTML renderer.\n *\n * Walks the document tree, dispatching each node to the renderer\n * registered for its `type`. Unknown nodes are handled gracefully:\n * children are rendered (so the user sees content), the wrapper is\n * skipped.\n *\n * @module @lexical/render\n */\n\nimport { sanitizeHtml, hasSanitizerDocument } from '@security/sanitizer';\nimport { lookup, register, type RenderNodeContext } from './registry';\nimport type { LexicalNode, LexicalRoot } from './types';\nimport { resolveAlignment, resolveIndent } from './utils';\n\n// Named imports + explicit `register()` calls. The previous\n// architecture relied on each node module calling `register()` as a\n// side effect at import time, but bundlers that honour the package's\n// `sideEffects: false` field tree-shake side-effect-only imports.\n// Wiring the registry from a single point eliminates that risk —\n// every renderer is unambiguously referenced as a value.\nimport { textRenderer } from './nodes/text';\nimport { paragraphRenderer } from './nodes/paragraph';\nimport { headingRenderer } from './nodes/heading';\nimport { listRenderer, listItemRenderer } from './nodes/list';\nimport { linkRenderer } from './nodes/link';\nimport { quoteRenderer } from './nodes/quote';\nimport { codeRenderer, codeHighlightRenderer } from './nodes/code';\nimport { linebreakRenderer, horizontalRuleRenderer, tabRenderer } from './nodes/linebreak';\nimport { uploadRenderer } from './nodes/upload';\nimport { relationshipRenderer } from './nodes/relationship';\nimport { blockRenderer } from './nodes/block';\n\nregister('text', textRenderer);\nregister('paragraph', paragraphRenderer);\nregister('heading', headingRenderer);\nregister('list', listRenderer);\nregister('listitem', listItemRenderer);\nregister('link', linkRenderer);\nregister('autolink', linkRenderer);\nregister('quote', quoteRenderer);\nregister('code', codeRenderer);\nregister('code-highlight', codeHighlightRenderer);\nregister('linebreak', linebreakRenderer);\nregister('horizontalrule', horizontalRuleRenderer);\nregister('tab', tabRenderer);\nregister('upload', uploadRenderer);\nregister('relationship', relationshipRenderer);\nregister('block', blockRenderer);\n\nconst RENDER_CONTEXT: RenderNodeContext = {\n renderChildren,\n resolveAlignment,\n resolveIndent,\n};\n\nexport interface LexicalRenderOptions {\n /**\n * When `true` (default), the resulting HTML is passed through the\n * isomorphic `sanitizeHtml()` for defence-in-depth.\n */\n readonly sanitize?: boolean;\n}\n\n/**\n * Identify whether a value looks like a Lexical root payload.\n */\nexport function isLexicalContent(value: unknown): value is LexicalRoot {\n if (typeof value !== 'object' || value === null) return false;\n if (!('root' in value)) return false;\n const root = value.root;\n if (typeof root !== 'object' || root === null) return false;\n if (!('children' in root)) return false;\n return Array.isArray(root.children);\n}\n\n/**\n * Convert a Lexical root payload to an HTML string. By default the\n * result is sanitised through `sanitizeHtml`. The renderer is\n * security-first; per-node renderers already escape text and validate\n * URLs, but the final sanitiser closes any gap.\n */\nexport function lexicalToHtml(content: LexicalRoot, options: LexicalRenderOptions = {}): string {\n if (!isLexicalContent(content)) return '';\n const html = renderChildren(content.root.children);\n if (options.sanitize === false) return html;\n // Honour `setSanitizerDocument()` overrides (SSR with linkedom/jsdom)\n // instead of probing the `document` global — otherwise the sanitize\n // backstop would silently disappear server-side even when the\n // consumer wired a DOM for exactly this purpose. Without any DOM the\n // per-node renderers' escaping still guarantees safe output for the\n // built-in node set; custom block renderers should sanitize their own\n // output when SSR-rendering without a sanitizer document.\n if (!hasSanitizerDocument()) return html;\n return sanitizeHtml(html);\n}\n\n/**\n * Extract the plain text content of a Lexical document.\n *\n * Paragraphs are separated by `\\n`. Used by the text/textarea renderer\n * when a rich-text value is bound to a non-rich-text element.\n */\nexport function lexicalToPlainText(content: LexicalRoot): string {\n if (!isLexicalContent(content)) return '';\n return content.root.children.map(extractPlainText).join('\\n').trim();\n}\n\nfunction renderChildren(children: readonly LexicalNode[]): string {\n let out = '';\n for (const child of children) out += renderNode(child);\n return out;\n}\n\nfunction renderNode(node: LexicalNode): string {\n const renderer = lookup(node.type);\n if (renderer) return renderer(node, RENDER_CONTEXT);\n // Unknown node type — preserve content by rendering children verbatim.\n return node.children !== undefined ? renderChildren(node.children) : '';\n}\n\nfunction extractPlainText(node: LexicalNode): string {\n if (typeof node.text === 'string') return node.text;\n if (node.type === 'linebreak') return '\\n';\n if (node.children === undefined) return '';\n let out = '';\n for (const child of node.children) out += extractPlainText(child);\n return out;\n}\n","/**\n * `text` field renderer.\n *\n * Accepts any scalar and renders it via `textContent` (which is XSS-\n * safe by definition). Lexical content is reduced to plain text so\n * the renderer can serve as a sensible fallback for non-rich-text\n * bindings.\n *\n * Defensive design: when the bound element has structured *element*\n * children (not just text), replacing `textContent` would nuke that\n * markup. The renderer detects this case and:\n *\n * - If the element has `data-payload-text` → still does the replace\n * (explicit opt-in: \"yes I want my structured markup nuked\").\n * - Otherwise → logs a one-time console warning and skips the write,\n * preserving the consumer's layout. This protects against the\n * common annotation mistake of decorating a container that holds\n * styled children instead of plain text.\n *\n * @module @field-types/text\n */\n\nimport { isLexicalContent, lexicalToPlainText } from '@lexical/render';\nimport { escapeAndLinebreak } from '@security/escape';\nimport { safeConsoleWarn } from '@core/diagnostics';\nimport { markNoWriteCallback } from '@core/internal-outcome';\nimport type { FieldRenderer } from '@core/types';\n\nconst TEXT_OPT_IN_ATTRIBUTE = 'data-payload-text';\n\n/** Build a text renderer with registration-local warning deduplication state. */\nexport function createTextRenderer(): FieldRenderer {\n const warnedElements = new WeakSet<Element>();\n\n return {\n name: 'text',\n render: markNoWriteCallback((target, value) => {\n const element = target.element;\n const text = toPlainString(value);\n if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {\n (element as HTMLInputElement | HTMLTextAreaElement).value = text;\n return;\n }\n if (hasStructuredChildren(element) && !element.hasAttribute(TEXT_OPT_IN_ATTRIBUTE)) {\n warnOnce(warnedElements, element, target.fieldName);\n return false;\n }\n if (text.includes('\\n') || text.includes('\\r')) {\n element.innerHTML = escapeAndLinebreak(text);\n return;\n }\n element.textContent = text;\n return;\n }),\n };\n}\n\nfunction hasStructuredChildren(element: Element): boolean {\n // Elements with at least one element child (not a text node) are\n // considered \"structured\" — typically a template uses styled wrappers\n // around the actual field value.\n return element.firstElementChild !== null;\n}\n\nfunction warnOnce(warnedElements: WeakSet<Element>, element: Element, fieldName: string): void {\n if (warnedElements.has(element)) return;\n warnedElements.add(element);\n safeConsoleWarn(\n `[live-preview] LP0402: Skipping text update for \"${fieldName}\": ` +\n `<${element.tagName.toLowerCase()}> has structured children. Move ` +\n `data-payload-field to the value element, or add data-payload-text to replace them.`,\n );\n}\n\nfunction toPlainString(value: unknown): string {\n if (value === null || value === undefined) return '';\n if (isLexicalContent(value)) return lexicalToPlainText(value);\n if (typeof value === 'string') return value;\n if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n return JSON.stringify(value);\n}\n","/**\n * Shared helpers for field renderers.\n *\n * @module @field-types/utils\n */\n\n/**\n * Coerce an unknown value to a safe display string.\n *\n * Primitives render as their natural representation. Objects render\n * as their JSON form — never as the default `[object Object]`. `null`\n * and `undefined` collapse to the empty string.\n */\nexport function safeStringify(value: unknown): string {\n if (value === null || value === undefined) return '';\n if (typeof value === 'string') return value;\n if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {\n return String(value);\n }\n try {\n return JSON.stringify(value);\n } catch {\n return '';\n }\n}\n","/**\n * `textarea` field renderer.\n *\n * Differs from `text` only in that newlines are always preserved via\n * `<br>` insertion in non-input elements, even for single-line inputs.\n *\n * @module @field-types/textarea\n */\n\nimport { isLexicalContent, lexicalToPlainText } from '@lexical/render';\nimport { escapeAndLinebreak } from '@security/escape';\nimport type { FieldRenderer } from '@core/types';\nimport { safeStringify } from './utils';\n\nconst textareaRenderer: FieldRenderer = {\n name: 'textarea',\n render(target, value) {\n const element = target.element;\n const text = isLexicalContent(value) ? lexicalToPlainText(value) : safeStringify(value);\n if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {\n (element as HTMLInputElement | HTMLTextAreaElement).value = text;\n return;\n }\n element.innerHTML = escapeAndLinebreak(text);\n },\n};\n\nexport { textareaRenderer };\n","/**\n * `richText` field renderer.\n *\n * Accepts a Lexical root payload (Payload 3.x) or a plain HTML string\n * (Slate legacy + future-proofing). HTML goes through `sanitizeHtml`\n * before being injected; Lexical content is already sanitised by\n * `lexicalToHtml`.\n *\n * @module @field-types/rich-text\n */\n\nimport { isLexicalContent, lexicalToHtml } from '@lexical/render';\nimport { sanitizeHtml } from '@security/sanitizer';\nimport { markNoWriteCallback } from '@core/internal-outcome';\nimport type { FieldRenderer } from '@core/types';\n\nconst richTextRenderer: FieldRenderer = {\n name: 'richText',\n render: markNoWriteCallback((target, value) => {\n if (isLexicalContent(value)) {\n target.element.innerHTML = lexicalToHtml(value);\n return;\n }\n if (typeof value === 'string') {\n target.element.innerHTML = sanitizeHtml(value);\n return;\n }\n return false;\n }),\n};\n\nexport { richTextRenderer };\n","/**\n * `html` field renderer.\n *\n * Used when the consumer explicitly opts into raw-HTML rendering with\n * `data-payload-type=\"html\"`. The value is always run through\n * `sanitizeHtml` first. Non-string values are coerced via `String()`.\n *\n * @module @field-types/html\n */\n\nimport { sanitizeHtml } from '@security/sanitizer';\nimport type { FieldRenderer } from '@core/types';\nimport { safeStringify } from './utils';\n\nconst htmlRenderer: FieldRenderer = {\n name: 'html',\n render(target, value) {\n if (value === null || value === undefined) {\n target.element.textContent = '';\n return;\n }\n const html = typeof value === 'string' ? value : safeStringify(value);\n target.element.innerHTML = sanitizeHtml(html);\n },\n};\n\nexport { htmlRenderer };\n","/**\n * `url`/`email` field renderer.\n *\n * Sets the text content to the value and, when the element is an\n * `<a>`, updates the `href` attribute as well — pulling from a sibling\n * field when `data-payload-href` is set.\n *\n * @module @field-types/url\n */\n\nimport { isSafeUrl } from '@security/url-validator';\nimport { resolveFieldValue } from '@core/field-value';\nimport type { FieldRenderer } from '@core/types';\nimport { safeStringify } from './utils';\n\nconst urlRenderer: FieldRenderer = {\n name: 'url',\n render(target, value, context) {\n const element = target.element;\n const text = safeStringify(value);\n if (element.tagName === 'A') {\n const anchor = element as HTMLAnchorElement;\n const hrefField = target.hrefField;\n const hrefSource =\n hrefField === undefined || hrefField.length === 0\n ? value\n : resolveFieldValue(\n context.allFields,\n hrefField,\n context.locale,\n target.locale !== undefined,\n );\n if (typeof hrefSource === 'string' && isSafeUrl(hrefSource)) {\n anchor.href = hrefSource;\n }\n anchor.textContent = text;\n return;\n }\n if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {\n (element as HTMLInputElement | HTMLTextAreaElement).value = text;\n return;\n }\n element.textContent = text;\n },\n};\n\nexport { urlRenderer };\n","/**\n * `image` field renderer.\n *\n * For `<img>` elements: set `src`/`alt` from the value (which may be a\n * Payload media object or a plain URL string).\n *\n * For other elements: set the CSS `background-image` with CSS-escaped\n * URL — combined with `isSafeUrl()` this eliminates the CSS-injection\n * vector and lets consumers style hero sections with background images.\n *\n * @module @field-types/image\n */\n\nimport { escapeCssUrl } from '@security/escape';\nimport { isSafeUrl } from '@security/url-validator';\nimport { resolveFieldValue } from '@core/field-value';\nimport { markNoWriteCallback } from '@core/internal-outcome';\nimport type { FieldRenderer } from '@core/types';\nimport type { PayloadMedia } from './types';\n\nconst imageRenderer: FieldRenderer = {\n name: 'image',\n render: markNoWriteCallback((target, value, context) => {\n const element = target.element;\n const media = readMedia(value);\n const preferLocale = target.locale !== undefined;\n const url = pickUrl(\n media,\n value,\n target.srcField,\n context.allFields,\n context.locale,\n preferLocale,\n );\n if (url === undefined) return false;\n if (element.tagName === 'IMG') {\n const img = element as HTMLImageElement;\n img.src = url;\n const alt = pickAlt(media, target.altField, context.allFields, context.locale, preferLocale);\n if (alt !== undefined) img.alt = alt;\n return;\n }\n (element as HTMLElement).style.backgroundImage = `url('${escapeCssUrl(url)}')`;\n return;\n }),\n};\n\nfunction readMedia(value: unknown): PayloadMedia | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n return value;\n}\n\nfunction pickUrl(\n media: PayloadMedia | undefined,\n value: unknown,\n srcField: string | undefined,\n allFields: Record<string, unknown>,\n locale: string | undefined,\n preferLocale: boolean,\n): string | undefined {\n if (srcField !== undefined && srcField.length > 0) {\n const sibling = resolveFieldValue(allFields, srcField, locale, preferLocale);\n if (typeof sibling === 'string' && isSafeUrl(sibling)) return sibling;\n const siblingMedia = readMedia(sibling);\n if (siblingMedia?.url !== undefined && isSafeUrl(siblingMedia.url)) return siblingMedia.url;\n return undefined;\n }\n if (media?.url !== undefined && isSafeUrl(media.url)) return media.url;\n if (typeof value === 'string' && isSafeUrl(value)) return value;\n return undefined;\n}\n\nfunction pickAlt(\n media: PayloadMedia | undefined,\n altField: string | undefined,\n allFields: Record<string, unknown>,\n locale: string | undefined,\n preferLocale: boolean,\n): string | undefined {\n if (altField !== undefined && altField.length > 0) {\n const sibling = resolveFieldValue(allFields, altField, locale, preferLocale);\n if (typeof sibling === 'string') return sibling;\n return undefined;\n }\n if (media?.alt !== undefined) return media.alt;\n return undefined;\n}\n\nexport { imageRenderer };\n","/**\n * `upload` field renderer.\n *\n * Treats the value like an image upload when bound to an `<img>` element,\n * otherwise renders a download-style anchor with the filename.\n *\n * @module @field-types/upload\n */\n\nimport { escapeHtml, escapeHtmlAttribute } from '@security/escape';\nimport { isSafeUrl } from '@security/url-validator';\nimport { markNoWriteCallback } from '@core/internal-outcome';\nimport type { FieldRenderer } from '@core/types';\nimport type { PayloadMedia } from './types';\n\nconst uploadRenderer: FieldRenderer = {\n name: 'upload',\n render: markNoWriteCallback((target, value) => {\n const element = target.element;\n const media = readMedia(value);\n if (media === undefined) return false;\n const url = media.url;\n if (typeof url !== 'string' || !isSafeUrl(url)) return false;\n if (element.tagName === 'IMG') {\n const img = element as HTMLImageElement;\n img.src = url;\n if (media.alt !== undefined) img.alt = media.alt;\n return;\n }\n if (element.tagName === 'A') {\n const anchor = element as HTMLAnchorElement;\n anchor.href = url;\n anchor.textContent = media.filename ?? url;\n return;\n }\n const label = media.filename !== undefined ? escapeHtml(media.filename) : escapeHtml(url);\n element.innerHTML = `<a href=\"${escapeHtmlAttribute(url)}\">${label}</a>`;\n return;\n }),\n};\n\nfunction readMedia(value: unknown): PayloadMedia | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n return value;\n}\n\nexport { uploadRenderer };\n","/**\n * `relationship` field renderer.\n *\n * Renders the relation's `title` / `name` / `slug` / `id` (in that\n * order of preference). When the bound element is an `<a>` and the\n * value carries a `url`, the anchor's `href` is updated.\n *\n * Has-many relationships render the labels joined by \", \".\n *\n * @module @field-types/relationship\n */\n\nimport { isSafeUrl } from '@security/url-validator';\nimport type { FieldRenderer } from '@core/types';\nimport type { PayloadRelationship } from './types';\nimport { safeStringify } from './utils';\n\nconst relationshipRenderer: FieldRenderer = {\n name: 'relationship',\n render(target, value) {\n const element = target.element;\n const labels = collectLabels(value);\n const text = labels.join(', ');\n if (element.tagName === 'A' && !Array.isArray(value)) {\n const anchor = element as HTMLAnchorElement;\n const url = (value as PayloadRelationship | null)?.url;\n if (typeof url === 'string' && isSafeUrl(url)) anchor.href = url;\n anchor.textContent = text;\n return;\n }\n element.textContent = text;\n },\n};\n\nfunction collectLabels(value: unknown): readonly string[] {\n if (value === null || value === undefined) return [''];\n if (Array.isArray(value)) return value.map(pickLabel);\n return [pickLabel(value)];\n}\n\nfunction pickLabel(value: unknown): string {\n if (typeof value === 'object' && value !== null) {\n const rel = value as PayloadRelationship;\n if (typeof rel.title === 'string' && rel.title.length > 0) return rel.title;\n if (typeof rel.name === 'string' && rel.name.length > 0) return rel.name;\n if (typeof rel.slug === 'string' && rel.slug.length > 0) return rel.slug;\n if (rel.id !== undefined) return String(rel.id);\n return '';\n }\n return safeStringify(value);\n}\n\nexport { relationshipRenderer };\n","/**\n * `select` / `radio` field renderer.\n *\n * For `<select>` and `<input type=\"radio\">` elements: updates the\n * value/checked state. For arbitrary elements: text content.\n *\n * For has-many `select` fields the value is an array — we render the\n * joined labels.\n *\n * @module @field-types/select\n */\n\nimport type { FieldRenderer } from '@core/types';\nimport { safeStringify } from './utils';\n\nconst selectRenderer: FieldRenderer = {\n name: 'select',\n render(target, value) {\n const element = target.element;\n const text = stringify(value);\n if (element.tagName === 'SELECT') {\n (element as HTMLSelectElement).value = text;\n return;\n }\n if (element.tagName === 'INPUT' && (element as HTMLInputElement).type === 'radio') {\n const radio = element as HTMLInputElement;\n radio.checked = radio.value === text;\n return;\n }\n element.textContent = text;\n },\n};\n\nfunction stringify(value: unknown): string {\n if (Array.isArray(value)) return value.map((v) => stringify(v)).join(', ');\n return safeStringify(value);\n}\n\nexport { selectRenderer };\n","/**\n * `checkbox` field renderer.\n *\n * `<input type=\"checkbox\">`: updates `checked`.\n * `aria-checked`-capable elements: writes the attribute.\n * Other elements: text content `true` / `false`.\n *\n * @module @field-types/checkbox\n */\n\nimport type { FieldRenderer } from '@core/types';\n\nconst checkboxRenderer: FieldRenderer = {\n name: 'checkbox',\n render(target, value) {\n const element = target.element;\n const checked = Boolean(value);\n if (element.tagName === 'INPUT' && (element as HTMLInputElement).type === 'checkbox') {\n (element as HTMLInputElement).checked = checked;\n return;\n }\n if (element.hasAttribute('aria-checked')) {\n element.setAttribute('aria-checked', checked ? 'true' : 'false');\n return;\n }\n element.textContent = checked ? 'true' : 'false';\n },\n};\n\nexport { checkboxRenderer };\n","/**\n * Shared Intl formatter cache.\n *\n * Constructing `Intl.NumberFormat` / `Intl.DateTimeFormat` per call is\n * surprisingly expensive in tight loops — V8 cannot fully optimise them\n * because the locale → ICU resolution happens behind a `try { … }`.\n * On benchmark traces from the structural-array renderer, formatter\n * construction can dominate render time for arrays of 50+ numeric or\n * date fields.\n *\n * This module memoises formatters by a `(locale, options)` key. The\n * cache is module-scoped — formatters are pure functions of their key,\n * so the same `Intl.NumberFormat('de-DE')` instance is safe to share\n * across every consumer of the library on the page.\n *\n * A bounded LRU keeps the cache from growing without limit when a\n * page renders a wide variety of locales (admin tools, language\n * switchers). The default limit (64) is generous for normal sites and\n * tight enough that any leak would be visible in dev tools.\n *\n * @module @core/intl-cache\n */\n\nconst NUMBER_CACHE = new Map<string, Intl.NumberFormat>();\nconst DATE_CACHE = new Map<string, Intl.DateTimeFormat>();\n\nconst DEFAULT_MAX_ENTRIES = 64;\n\nlet maxEntries = DEFAULT_MAX_ENTRIES;\n\n/** Internal test helper — purges every cached formatter. */\nexport function __resetIntlCache(): void {\n NUMBER_CACHE.clear();\n DATE_CACHE.clear();\n maxEntries = DEFAULT_MAX_ENTRIES;\n}\n\n/** Adjust the LRU bound. Returns the previous value. */\nexport function setIntlCacheLimit(limit: number): number {\n if (!Number.isFinite(limit) || limit < 1) return maxEntries;\n const previous = maxEntries;\n maxEntries = Math.floor(limit);\n trimToLimit(NUMBER_CACHE);\n trimToLimit(DATE_CACHE);\n return previous;\n}\n\n/** Read-only telemetry — useful for tests and dev observability. */\nexport function intlCacheSize(): { readonly numbers: number; readonly dates: number } {\n return { numbers: NUMBER_CACHE.size, dates: DATE_CACHE.size };\n}\n\nexport function getNumberFormat(\n locale: string | undefined,\n options?: Intl.NumberFormatOptions,\n): Intl.NumberFormat {\n const key = buildKey(locale, options);\n const cached = NUMBER_CACHE.get(key);\n if (cached !== undefined) {\n // Touch → mark as MRU.\n NUMBER_CACHE.delete(key);\n NUMBER_CACHE.set(key, cached);\n return cached;\n }\n const formatter = new Intl.NumberFormat(locale, options);\n NUMBER_CACHE.set(key, formatter);\n trimToLimit(NUMBER_CACHE);\n return formatter;\n}\n\nexport function getDateTimeFormat(\n locale: string | undefined,\n options?: Intl.DateTimeFormatOptions,\n): Intl.DateTimeFormat {\n const key = buildKey(locale, options);\n const cached = DATE_CACHE.get(key);\n if (cached !== undefined) {\n DATE_CACHE.delete(key);\n DATE_CACHE.set(key, cached);\n return cached;\n }\n const formatter = new Intl.DateTimeFormat(locale, options);\n DATE_CACHE.set(key, formatter);\n trimToLimit(DATE_CACHE);\n return formatter;\n}\n\nfunction buildKey(locale: string | undefined, options: unknown): string {\n // `locale` first so the cache stays human-readable in dev tools.\n // `options` is JSON-encoded with a stable key order so equivalent\n // option objects hit the same slot regardless of authoring style.\n // An options object that stringifies to `{}` (all values undefined,\n // or genuinely empty) collapses to no suffix so it shares the same\n // cache slot as a bare call.\n const localePart = locale ?? '';\n if (options === undefined || options === null) return localePart;\n const serialised = stableStringify(options);\n if (serialised === '{}') return localePart;\n return `${localePart}|${serialised}`;\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value);\n if (Array.isArray(value)) {\n return `[${value.map((v) => stableStringify(v)).join(',')}]`;\n }\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record).sort();\n const parts: string[] = [];\n for (const key of keys) {\n const inner = record[key];\n if (inner === undefined) continue;\n parts.push(`${JSON.stringify(key)}:${stableStringify(inner)}`);\n }\n return `{${parts.join(',')}}`;\n}\n\nfunction trimToLimit(map: Map<string, unknown>): void {\n while (map.size > maxEntries) {\n const oldest = map.keys().next().value;\n if (oldest === undefined) break;\n map.delete(oldest);\n }\n}\n","/**\n * `date` field renderer.\n *\n * Uses `Intl.DateTimeFormat` with the active locale (defaults to\n * `navigator.language`, never the legacy hard-coded `'de'`). Recognises\n * `<time>` elements and updates their `datetime` attribute for SEO and\n * accessibility.\n *\n * @module @field-types/date\n */\n\nimport { detectInitialLocale } from '@detection/locale';\nimport { getDateTimeFormat } from '@core/intl-cache';\nimport type { FieldRenderer, RenderContext } from '@core/types';\nimport { safeStringify } from './utils';\n\nconst dateRenderer: FieldRenderer = {\n name: 'date',\n render(target, value, context) {\n const element = target.element;\n if (value === null || value === undefined || value === '') {\n if (element.tagName === 'INPUT') {\n (element as HTMLInputElement).value = '';\n } else if (element.tagName === 'TIME') {\n element.removeAttribute('datetime');\n element.textContent = '';\n } else {\n element.textContent = '';\n }\n return;\n }\n const iso = typeof value === 'string' ? value : safeStringify(value);\n const date = new Date(iso);\n const isValid = !Number.isNaN(date.getTime());\n if (element.tagName === 'INPUT') {\n (element as HTMLInputElement).value = isValid\n ? toIsoForInput((element as HTMLInputElement).type, date)\n : iso;\n return;\n }\n if (element.tagName === 'TIME') {\n element.setAttribute('datetime', isValid ? date.toISOString() : iso);\n element.textContent = isValid ? formatDate(date, context) : iso;\n return;\n }\n element.textContent = isValid ? formatDate(date, context) : iso;\n },\n};\n\nfunction formatDate(date: Date, context: RenderContext): string {\n const locale = context.locale ?? detectInitialLocale();\n try {\n return getDateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'short' }).format(date);\n } catch {\n return date.toISOString();\n }\n}\n\nfunction toIsoForInput(type: string, date: Date): string {\n if (type === 'date') return date.toISOString().slice(0, 10);\n if (type === 'datetime-local') return date.toISOString().slice(0, 16);\n return date.toISOString();\n}\n\nexport { dateRenderer };\n","/**\n * `number` field renderer.\n *\n * Inputs get `valueAsNumber`. Other elements get the value formatted\n * via `Intl.NumberFormat` with the active locale.\n *\n * @module @field-types/number\n */\n\nimport { detectInitialLocale } from '@detection/locale';\nimport { getNumberFormat } from '@core/intl-cache';\nimport type { FieldRenderer, RenderContext } from '@core/types';\nimport { safeStringify } from './utils';\n\nconst numberRenderer: FieldRenderer = {\n name: 'number',\n render(target, value, context) {\n const element = target.element;\n if (value === null || value === undefined || value === '') {\n if (element.tagName === 'INPUT') (element as HTMLInputElement).value = '';\n else element.textContent = '';\n return;\n }\n const num = typeof value === 'number' ? value : Number(safeStringify(value));\n if (Number.isNaN(num)) {\n element.textContent = safeStringify(value);\n return;\n }\n if (element.tagName === 'INPUT') {\n (element as HTMLInputElement).value = String(num);\n return;\n }\n element.textContent = format(num, context);\n },\n};\n\nfunction format(num: number, context: RenderContext): string {\n const locale = context.locale ?? detectInitialLocale();\n try {\n return getNumberFormat(locale).format(num);\n } catch {\n return String(num);\n }\n}\n\nexport { numberRenderer };\n","/**\n * Interpolate one array-item template in a single pass.\n *\n * A replacement value is data, not another template. Running one `replace()`\n * per object key would interpret `{{index}}` or `{{otherField}}` text introduced\n * by an earlier value as template syntax. Matching only the original template\n * tokens keeps CMS values literal and also avoids String.replace `$` semantics.\n *\n * @module @core/array-template\n */\n\nimport { escapeHtml } from '@security/escape';\n\nconst PLACEHOLDER_PATTERN = /\\{\\{([\\s\\S]*?)\\}\\}/g;\n\nfunction hasOwn(record: object, key: PropertyKey): boolean {\n return Object.prototype.hasOwnProperty.call(record, key);\n}\n\nexport function interpolateArrayTemplate(\n template: string,\n item: unknown,\n index: number,\n stringify: (value: unknown) => string,\n): string {\n const record = typeof item === 'object' && item !== null ? item : null;\n\n return template.replace(PLACEHOLDER_PATTERN, (placeholder, key: string) => {\n // Preserve the established object-field precedence when an object itself\n // has an `index` or `value` property. Otherwise these are reserved tokens.\n if (record !== null && hasOwn(record, key)) {\n return escapeHtml(stringify(Reflect.get(record, key)));\n }\n if (record === null && key === 'value') return escapeHtml(stringify(item));\n if (key === 'index') return String(index);\n return placeholder;\n });\n}\n","/**\n * `array` / `blocks` field renderer.\n *\n * Supports two modes:\n *\n * 1. **Template mode** (consumer sets `data-payload-array-template`):\n * each array item is interpolated into the template. Placeholders\n * are `{{key}}` for object fields, `{{value}}` for primitives,\n * and `{{index}}` for the loop counter. All replacements go\n * through `escapeHtml`.\n *\n * 2. **Separator mode** (no template): primitives are joined by\n * `data-payload-array-separator` (default `\", \"`). Object items\n * are serialised via `JSON.stringify` so the consumer sees the\n * raw data instead of `[object Object]`.\n *\n * @module @field-types/array\n */\n\nimport { sanitizeHtml } from '@security/sanitizer';\nimport { interpolateArrayTemplate } from '@core/array-template';\nimport { markNoWriteCallback } from '@core/internal-outcome';\nimport type { FieldRenderer } from '@core/types';\nimport { safeStringify } from './utils';\n\nconst arrayRenderer: FieldRenderer = {\n name: 'array',\n render: markNoWriteCallback((target, value) => {\n const element = target.element;\n if (!Array.isArray(value)) return false;\n const template = target.arrayTemplate;\n if (template !== undefined && template.length > 0) {\n const html = renderTemplate(template, value);\n element.innerHTML = sanitizeHtml(html);\n return;\n }\n const separator = target.arraySeparator ?? ', ';\n element.textContent = value.map(stringify).join(separator);\n return;\n }),\n};\n\nfunction renderTemplate(template: string, items: readonly unknown[]): string {\n let out = '';\n for (let i = 0; i < items.length; i += 1) {\n out += interpolate(template, items[i], i);\n }\n return out;\n}\n\nfunction interpolate(template: string, item: unknown, index: number): string {\n return interpolateArrayTemplate(template, item, index, safeStringify);\n}\n\nfunction stringify(value: unknown): string {\n return safeStringify(value);\n}\n\nexport { arrayRenderer };\n","/**\n * Apply `ArrayPatch[]` to a DOM container.\n *\n * The structural applier turns the diff produced by `@schema/diff`\n * into individual DOM operations — keyed placement, removal, and root\n * replacement — instead of rebuilding the whole list. The result is:\n *\n * - smaller paint area (browsers can keep most nodes alive),\n * - synchronous, lifecycle-attributable DOM updates,\n * - consumer JS state on existing child elements survives.\n *\n * Each child element is paired with the `id` of its source item via\n * the `data-payload-key` attribute. Items without an `id` use their\n * positional index — which means moves degrade to update-in-place,\n * but inserts/removes still work.\n *\n * @module @core/structural-applier\n */\n\nimport { sanitizeHtml } from '@security/sanitizer';\nimport { interpolateArrayTemplate } from './array-template';\nimport { safeStringify } from '@field-types/utils';\nimport { diffArray, type ArrayPatch } from '@schema/diff';\n\nexport const KEY_ATTRIBUTE = 'data-payload-key';\nconst NESTED_KEY_ATTRIBUTE = 'data-payload-nested-key';\nconst NESTED_TEMPLATE_ATTRIBUTE = 'data-payload-nested-template';\n\n/**\n * Per-render memory of the last value seen for each item key, used by\n * recursive nested diffs. It is **not** module-level: the caller owns\n * the store (one per runtime instance — see\n * `createStructuralArrayRenderer`), so two clients never share diff\n * state and `destroy()` drops it with the instance. The store is keyed\n * by the container element, then by the item's key from `readKey()`.\n */\nexport type StructuralStore = WeakMap<Element, Map<string, unknown>>;\n\n/** Create a fresh, instance-owned structural-diff store. */\nexport function createStructuralStore(): StructuralStore {\n return new WeakMap<Element, Map<string, unknown>>();\n}\n\nexport interface StructuralApplyOptions {\n readonly template: string;\n readonly container: Element;\n readonly patches: readonly ArrayPatch[];\n /**\n * The full new array, so inserts/replaces can render items by index.\n * The diff carries `value`, but a single value isn't enough to\n * render the item *via* a template — we still need the index to\n * substitute `{{index}}` correctly. The applier picks the value at\n * the patch's `to`/`index` from this snapshot.\n */\n readonly nextItems: readonly unknown[];\n /**\n * Instance-owned nested-diff memory. Pass the same store across\n * renders of the same runtime so nested arrays diff incrementally.\n */\n readonly store: StructuralStore;\n /** Re-render existing items even when their data comparison is unchanged. */\n readonly forceRender?: boolean;\n}\n\n/**\n * Reconcile patches in final-item order. Patch indices describe the `next`\n * snapshot, while live DOM indices change during moves; resolving keyed nodes\n * from the DOM before placing each final item avoids mixing those coordinate\n * systems. `nextItems` is authoritative and any unclaimed direct child is\n * removed after reconciliation.\n *\n * The applier mutates `container` in place. After a complete call, the\n * container's children mirror `nextItems`. It returns `true` for a real DOM\n * mutation, `false` for an already-current tree, and `null` when required item\n * markup has no sanitized element root. The latter is preflighted atomically,\n * so the previous DOM and diff memory stay intact.\n */\nexport function applyStructuralPatches(options: StructuralApplyOptions): boolean | null {\n const { template, container, patches, nextItems, store, forceRender = false } = options;\n const plan = prepareStructuralPlan(container, template, patches, nextItems, forceRender, store);\n if (plan === null) return null;\n return commitStructuralPlan(plan, store);\n}\n\n// Plans are short-lived internal transaction records. Named tuples keep their\n// positions explicit without emitting repeated object-property names into the\n// inline runtime for every recursive plan node.\ntype StructuralPlan = readonly [\n container: Element,\n entries: readonly ReconciliationEntry[],\n nextItems: readonly unknown[],\n];\ntype ReconciliationEntry = readonly [\n index: number,\n live: Element | null,\n rendered: Element | undefined,\n nestedSlots: readonly NestedSlotPlan[],\n];\ntype NestedSlotPlan = readonly [\n live: Element | null,\n rendered: Element,\n children: StructuralPlan | undefined,\n];\n\n/**\n * Materialize the complete recursive replacement tree before mutating live DOM.\n * Nested template failures therefore abort the same transaction as top-level\n * failures, while the plan still records which live slots can be transplanted\n * during commit to retain their DOM identity.\n */\nfunction prepareStructuralPlan(\n container: Element,\n template: string,\n patches: readonly ArrayPatch[],\n nextItems: readonly unknown[],\n forceRender: boolean,\n store: StructuralStore,\n): StructuralPlan | null {\n const patchPlan = createPatchPlan(patches);\n const memory = store.get(container);\n const entries = prepareReconciliation(\n container,\n template,\n nextItems,\n patchPlan,\n forceRender,\n memory,\n store,\n );\n if (entries === null) return null;\n return [container, entries, nextItems];\n}\n\n/** Commit a previously validated recursive plan; no rendering occurs here. */\nfunction commitStructuralPlan(plan: StructuralPlan, store: StructuralStore): boolean {\n const [container, entries, nextItems] = plan;\n const claimed = new Set<Element>();\n let mutated = false;\n\n for (const entry of entries) {\n const [index, live, rendered, nestedSlots] = entry;\n let node = live;\n\n if (rendered !== undefined) {\n for (const nested of nestedSlots) {\n if (nested[0] !== null) {\n synchronizeAttributes(nested[0], nested[1]);\n nested[1].replaceWith(nested[0]);\n }\n if (nested[2] !== undefined) {\n // The recursive plan targets either the transplanted live slot or the\n // detached new slot, so child identity survives exactly where valid.\n commitStructuralPlan(nested[2], store);\n }\n }\n if (live !== null) {\n live.replaceWith(rendered);\n mutated = true;\n }\n node = rendered;\n }\n\n // `prepareReconciliation()` materializes every missing node or returns\n // `null` before this loop, so each entry owns one final child.\n if (node === null) continue;\n const before = container.children[index] ?? null;\n if (node !== before) {\n container.insertBefore(node, before);\n mutated = true;\n }\n claimed.add(node);\n }\n\n // The final snapshot is the source of truth. This also removes SSR children\n // that were not represented in the first incoming value.\n for (const child of Array.from(container.children)) {\n if (!claimed.has(child)) {\n child.remove();\n mutated = true;\n }\n }\n\n const memory = getMemory(container, store);\n memory.clear();\n for (const value of nextItems) rememberItem(memory, value);\n return mutated;\n}\n\nfunction prepareReconciliation(\n container: Element,\n template: string,\n nextItems: readonly unknown[],\n plan: PatchPlan,\n forceRender: boolean,\n memory: ReadonlyMap<string, unknown> | undefined,\n store: StructuralStore,\n): readonly ReconciliationEntry[] | null {\n const initialChildren = Array.from(container.children);\n const keyedChildren = indexByAttribute(initialChildren, KEY_ATTRIBUTE);\n const reserved = new Set<Element>();\n const entries: ReconciliationEntry[] = [];\n\n for (let index = 0; index < nextItems.length; index += 1) {\n const value = nextItems[index];\n const key = readKey(value);\n let live =\n key === undefined\n ? (initialChildren[index] ?? null)\n : (takeIndexedElement(keyedChildren, key) ?? null);\n if (live !== null && reserved.has(live)) live = null;\n if (live !== null) reserved.add(live);\n\n const replace = plan.replaces.has(index);\n const needsRender = forceRender || plan.renders.has(index) || live === null;\n const rendered = needsRender\n ? renderItem(container.ownerDocument, template, value, index)\n : undefined;\n if (rendered === null) return null;\n const nestedSlots =\n rendered === undefined\n ? []\n : prepareNestedSlots(replace ? null : live, rendered, value, memory, store);\n if (nestedSlots === null) return null;\n entries.push([index, live, rendered ?? undefined, nestedSlots]);\n }\n return entries;\n}\n\ninterface PatchPlan {\n readonly renders: ReadonlySet<number>;\n readonly replaces: ReadonlySet<number>;\n}\n\nfunction createPatchPlan(patches: readonly ArrayPatch[]): PatchPlan {\n const renders = new Set<number>();\n const replaces = new Set<number>();\n for (const patch of patches) {\n if (patch.kind === 'insert' || patch.kind === 'update') renders.add(patch.index);\n else if (patch.kind === 'replace') {\n renders.add(patch.index);\n replaces.add(patch.index);\n }\n }\n return { renders, replaces };\n}\n\n/**\n * Prepare each direct nested slot. Compatible live slots are recorded for a\n * later transplant; new/replaced slots are populated entirely off-DOM. A\n * failure at any depth propagates before commit starts.\n */\nfunction prepareNestedSlots(\n oldItem: Element | null,\n newItem: Element,\n nextValue: unknown,\n memory: ReadonlyMap<string, unknown> | undefined,\n store: StructuralStore,\n): readonly NestedSlotPlan[] | null {\n const oldSlots = oldItem === null ? [] : findDirectNestedSlots(oldItem);\n const oldSlotsByKey = indexByAttribute(oldSlots, NESTED_KEY_ATTRIBUTE);\n const itemKey = readKey(nextValue);\n const prevValue = itemKey !== undefined ? memory?.get(itemKey) : undefined;\n const plans: NestedSlotPlan[] = [];\n for (const newSlot of findDirectNestedSlots(newItem)) {\n const key = newSlot.getAttribute(NESTED_KEY_ATTRIBUTE);\n if (key === null) continue;\n const oldSlot = takeIndexedElement(oldSlotsByKey, key) ?? null;\n const nextTemplate = newSlot.getAttribute(NESTED_TEMPLATE_ATTRIBUTE);\n // A slot without a usable nested template is no longer owned by recursive\n // reconciliation. Keep its fully preflighted static subtree authoritative\n // instead of transplanting stale children from the former managed slot.\n const liveSlot = nextTemplate ? oldSlot : null;\n const previousTemplate = liveSlot?.getAttribute(NESTED_TEMPLATE_ATTRIBUTE) ?? null;\n let children: StructuralPlan | undefined;\n if (nextTemplate) {\n const nextNested = readNestedArray(nextValue, key);\n if (nextNested !== undefined || liveSlot !== null) {\n const resolvedNext = nextNested ?? [];\n const prevNested = liveSlot === null ? [] : (readNestedArray(prevValue, key) ?? []);\n const patches = diffArray(prevNested, resolvedNext);\n const templateChanged = liveSlot !== null && previousTemplate !== nextTemplate;\n if (patches.length > 0 || templateChanged) {\n children =\n prepareStructuralPlan(\n liveSlot ?? newSlot,\n nextTemplate,\n patches,\n resolvedNext,\n templateChanged,\n store,\n ) ?? undefined;\n if (children === undefined) return null;\n }\n }\n }\n plans.push([liveSlot, newSlot, children]);\n }\n return plans;\n}\n\n/**\n * Return only this item's outermost nested slots. A transplanted slot owns the\n * recursion below it; visiting its descendants again from the parent would\n * reconcile detached template nodes and create a second source of truth.\n */\nfunction findDirectNestedSlots(item: Element): readonly Element[] {\n return Array.from(item.querySelectorAll(`[${NESTED_KEY_ATTRIBUTE}]`)).filter((slot) => {\n let ancestor = slot.parentElement;\n while (ancestor !== null && ancestor !== item) {\n if (ancestor.hasAttribute(NESTED_KEY_ATTRIBUTE)) return false;\n ancestor = ancestor.parentElement;\n }\n return ancestor === item;\n });\n}\n\n/** Copy new sanitized slot metadata without replacing its live child subtree. */\nfunction synchronizeAttributes(target: Element, source: Element): void {\n for (const attribute of Array.from(target.attributes)) {\n if (!source.hasAttribute(attribute.name)) target.removeAttribute(attribute.name);\n }\n for (const attribute of Array.from(source.attributes)) {\n if (target.getAttribute(attribute.name) !== attribute.value) {\n target.setAttribute(attribute.name, attribute.value);\n }\n }\n}\n\nfunction readNestedArray(value: unknown, key: string): readonly unknown[] | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const nested = (value as Record<string, unknown>)[key];\n if (!Array.isArray(nested)) return undefined;\n return nested as readonly unknown[];\n}\n\nfunction getMemory(container: Element, store: StructuralStore): Map<string, unknown> {\n let map = store.get(container);\n if (!map) {\n map = new Map();\n store.set(container, map);\n }\n return map;\n}\n\nfunction rememberItem(memory: Map<string, unknown>, value: unknown): void {\n const key = readKey(value);\n if (key === undefined) return;\n memory.set(key, value);\n}\n\nfunction readKey(value: unknown): string | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const id = (value as Record<string, unknown>)['id'];\n if (typeof id === 'string' || typeof id === 'number') return String(id);\n return undefined;\n}\n\nfunction indexByAttribute(elements: readonly Element[], attribute: string): Map<string, Element[]> {\n const indexed = new Map<string, Element[]>();\n // Reverse insertion lets pop() consume duplicate keys in DOM order without\n // the O(n) shifting cost of queue arrays.\n for (let index = elements.length - 1; index >= 0; index -= 1) {\n const element = elements[index];\n if (element === undefined) continue;\n const key = element.getAttribute(attribute);\n if (key === null) continue;\n const bucket = indexed.get(key);\n if (bucket === undefined) indexed.set(key, [element]);\n else bucket.push(element);\n }\n return indexed;\n}\n\nfunction takeIndexedElement(indexed: Map<string, Element[]>, key: string): Element | undefined {\n return indexed.get(key)?.pop();\n}\n\n/**\n * Render one template item, with its `id` stamped on the root as\n * `data-payload-key` so subsequent diffs can find it again.\n *\n * The template body is sanitised — the same defense-in-depth applied\n * elsewhere — and parsed via `<template>` so we get a real Element\n * back instead of a string concatenation.\n */\nfunction renderItem(\n ownerDocument: Document,\n template: string,\n value: unknown,\n index: number,\n): Element | null {\n const filled = fillTemplate(template, value, index);\n const safe = sanitizeHtml(filled);\n const host = ownerDocument.createElement('template');\n host.innerHTML = safe;\n const first = host.content.firstElementChild;\n if (!first) return null;\n const key = readKey(value);\n if (key !== undefined) first.setAttribute(KEY_ATTRIBUTE, key);\n return first;\n}\n\nfunction fillTemplate(template: string, value: unknown, index: number): string {\n return interpolateArrayTemplate(template, value, index, safeStringify);\n}\n","/**\n * `structural-array` renderer.\n *\n * Activates for elements that opt into structural updates via the\n * `data-payload-structural` attribute. Instead of rebuilding the\n * container's `innerHTML` on every update, the renderer diffs the\n * previous and next item lists and applies the minimal patch.\n *\n * All diff memory (previous top-level values, nested-diff store, and\n * the missing-template warning set) lives in closures created by\n * `createStructuralArrayRenderer()` — one set per runtime instance, so\n * two clients never share state and a destroyed client leaves nothing\n * behind at module scope. DOM mutations are applied synchronously: the\n * renderer contract is synchronous, so lifecycle completion can never\n * precede a deferred browser callback or outlive runtime destruction.\n *\n * @module @field-types/structural-array\n */\n\nimport { safeConsoleWarn } from '@core/diagnostics';\nimport { markNoWriteCallback } from '@core/internal-outcome';\nimport {\n applyStructuralPatches,\n createStructuralStore,\n KEY_ATTRIBUTE,\n type StructuralStore,\n} from '@core/structural-applier';\nimport { diffArray } from '@schema/diff';\nimport type { FieldRenderer } from '@core/types';\n\n/**\n * Build a `structural-array` renderer with its own, instance-local diff\n * state. Called once per `buildBuiltinRenderers()` (i.e. once per\n * client/runtime), so nothing is shared across instances.\n */\nexport function createStructuralArrayRenderer(): FieldRenderer {\n const states = new WeakMap<Element, StructuralRenderState>();\n const warnedContainers = new WeakSet<Element>();\n const store: StructuralStore = createStructuralStore();\n\n return {\n name: 'structural-array',\n render: markNoWriteCallback((target, value) => {\n if (!Array.isArray(value)) return false;\n const container = target.element;\n const template = target.arrayTemplate;\n if (template === undefined || template.length === 0) {\n warnMissingTemplate(warnedContainers, container, target.fieldName);\n return false;\n }\n const previousState = states.get(container);\n const domSnapshot = readDomKeySnapshot(container);\n const previous = previousState?.values ?? valuesFromDomSnapshot(domSnapshot);\n const patches = diffArray(previous, value);\n const forceRender = needsForcedRender(previousState, template, domSnapshot);\n if (patches.length === 0 && !forceRender) {\n states.set(container, {\n values: value.slice() as readonly unknown[],\n template,\n domSnapshot,\n });\n return false;\n }\n const applied = applyStructuralPatches({\n template,\n container,\n patches,\n nextItems: value,\n store,\n forceRender,\n });\n if (applied === null) return false;\n states.set(container, {\n values: value.slice() as readonly unknown[],\n template,\n domSnapshot: readDomKeySnapshot(container),\n });\n return applied ? undefined : false;\n }),\n };\n}\n\ninterface StructuralRenderState {\n readonly values: readonly unknown[];\n readonly template: string;\n readonly domSnapshot: readonly (string | null)[];\n}\n\nfunction needsForcedRender(\n previous: StructuralRenderState | undefined,\n template: string,\n domSnapshot: readonly (string | null)[],\n): boolean {\n if (previous === undefined) return true;\n return previous.template !== template || !sameDomKeySnapshot(previous.domSnapshot, domSnapshot);\n}\n\n/**\n * The DOM is part of first-render truth: SSR/static markup exists before this\n * renderer has an in-memory value snapshot. Direct-child keys let the first\n * update reconcile that markup rather than appending a second copy. Keeping the\n * last applied key snapshot also detects host replacement/reordering between\n * updates without retaining any extra element references.\n */\nfunction readDomKeySnapshot(container: Element): readonly (string | null)[] {\n return Array.from(container.children, (child) => child.getAttribute(KEY_ATTRIBUTE));\n}\n\nfunction valuesFromDomSnapshot(snapshot: readonly (string | null)[]): readonly unknown[] {\n return snapshot.map((key, position) =>\n key === null ? { __payloadDomPosition: position } : { id: key },\n );\n}\n\nfunction sameDomKeySnapshot(\n previous: readonly (string | null)[],\n current: readonly (string | null)[],\n): boolean {\n if (previous.length !== current.length) return false;\n return previous.every((key, index) => key === current[index]);\n}\n\nfunction warnMissingTemplate(\n warnedContainers: WeakSet<Element>,\n container: Element,\n fieldName: string,\n): void {\n if (warnedContainers.has(container)) return;\n warnedContainers.add(container);\n safeConsoleWarn(\n `[live-preview] LP0403: Skipping structural update for \"${fieldName}\": ` +\n `<${container.tagName.toLowerCase()} data-payload-structural> needs ` +\n `data-payload-array-template (for example \"<li>{{label}}</li>\").`,\n );\n}\n","/**\n * Field-renderer registry.\n *\n * Maps a `FieldType` to the function that mutates a DOM element with\n * the new value. The registry pattern decouples the lifecycle from the\n * concrete renderers, so:\n *\n * - Tests can substitute mock renderers.\n * - Plugins can register custom renderers via the high-level client.\n * - New field types ship without touching `lifecycle.ts`.\n *\n * The explicit aggregator in `@field-types/index` supplies the default\n * renderers as values, so it remains tree-shaking-safe without module import\n * side effects. This registry stores only explicit consumer overrides.\n *\n * @module @field-types/registry\n */\n\nimport type { FieldRenderer, FieldType } from '@core/types';\n\nconst builtinRenderers = new Map<FieldType, FieldRenderer>();\n\n/**\n * Assemble a fresh renderer map. Defaults are copied first and explicit\n * registrations are layered above them, so `registerBuiltinRenderer()` keeps\n * its documented override semantics. The registry never retains the defaults;\n * stateful defaults can therefore be recreated independently per client.\n */\nexport function buildBuiltinRenderers(\n defaults: readonly FieldRenderer[] = [],\n): Readonly<Record<string, FieldRenderer>> {\n const out: Record<string, FieldRenderer> = {};\n for (const renderer of defaults) out[renderer.name] = renderer;\n for (const [type, renderer] of builtinRenderers) out[type] = renderer;\n return Object.freeze(out);\n}\n\n/**\n * Register or replace an explicit renderer override for future snapshots.\n */\nexport function registerBuiltinRenderer(renderer: FieldRenderer): void {\n builtinRenderers.set(renderer.name, renderer);\n}\n\n/**\n * Test-only helper: clear the built-in renderer map.\n */\nexport function __resetBuiltinRenderersForTests(): void {\n builtinRenderers.clear();\n}\n","/**\n * Public barrel for built-in field renderers.\n *\n * Each renderer is imported as a named binding (not a side-effect)\n * and assembled into the registry through `buildBuiltinRenderers`.\n * The bundler keeps every reference reachable, so the registry is\n * fully populated at runtime even under `sideEffects: false`.\n *\n * @module @field-types\n */\n\nimport type { FieldRenderer } from '@core/types';\nimport { createTextRenderer } from './text';\nimport { textareaRenderer } from './textarea';\nimport { richTextRenderer } from './rich-text';\nimport { htmlRenderer } from './html';\nimport { urlRenderer } from './url';\nimport { imageRenderer } from './image';\nimport { uploadRenderer } from './upload';\nimport { relationshipRenderer } from './relationship';\nimport { selectRenderer } from './select';\nimport { checkboxRenderer } from './checkbox';\nimport { dateRenderer } from './date';\nimport { numberRenderer } from './number';\nimport { arrayRenderer } from './array';\nimport { createStructuralArrayRenderer } from './structural-array';\nimport {\n buildBuiltinRenderers as buildRegistry,\n registerBuiltinRenderer,\n __resetBuiltinRenderersForTests,\n} from './registry';\n\n/**\n * The stateless built-in renderers, shared safely across instances. Text and\n * structural-array renderers are intentionally NOT here: both own per-client\n * warning/diff state and are constructed fresh per build (below).\n */\nconst STATELESS_BUILTIN: readonly FieldRenderer[] = [\n textareaRenderer,\n richTextRenderer,\n htmlRenderer,\n urlRenderer,\n { ...urlRenderer, name: 'email' },\n imageRenderer,\n uploadRenderer,\n relationshipRenderer,\n selectRenderer,\n { ...selectRenderer, name: 'radio' },\n checkboxRenderer,\n dateRenderer,\n numberRenderer,\n arrayRenderer,\n { ...arrayRenderer, name: 'blocks' },\n];\n\n/**\n * Built-in renderer map. Called once per client/runtime; the\n * `structural-array` renderer gets a fresh instance with its own diff\n * state so nothing is shared between concurrent clients.\n */\nexport function buildBuiltinRenderers(): Readonly<Record<string, FieldRenderer>> {\n return buildRegistry([\n createTextRenderer(),\n ...STATELESS_BUILTIN,\n createStructuralArrayRenderer(),\n ]);\n}\n\nexport { registerBuiltinRenderer, __resetBuiltinRenderersForTests };\nexport type { PayloadMedia, PayloadRelationship } from './types';\n","/**\n * Public, high-level `LivePreviewClient`.\n *\n * The client wraps a `LivePreviewRuntime` with:\n *\n * - Per-instance event emitter (no singleton).\n * - Per-instance plugin manager.\n * - Custom-renderer registration.\n * - Field-name transforms frozen into revision-bound scheduler entries before\n * their later attribute or renderer dispatch.\n *\n * Consumers who want full programmatic control instantiate\n * `LivePreviewClient` directly. Consumers who just want a working\n * inline preview should use `generateInlineScript()` instead.\n *\n * @module @client\n */\n\nimport { LivePreviewRuntime } from '@core/lifecycle';\nimport type { LivePreviewInspection } from '@core/inspection/types';\nimport { EventEmitter } from '@events/emitter';\nimport { OriginDetector } from '@detection/origin';\nimport { PluginManager } from '@plugins/manager';\nimport { RendererRegistry } from '@plugins/renderer-registry';\nimport type { LivePreviewPlugin } from '@plugins/types';\nimport { isDevMode, isInPreviewContext } from '@detection/environment';\nimport { buildBuiltinRenderers } from '@field-types/index';\nimport type { FieldType } from '@core/types';\nimport type { LivePreviewClientConfig } from './config';\nimport { noopDiagnostic, safeConsoleDebug } from '@core/diagnostics';\n\nexport class LivePreviewClient {\n readonly #emitter = new EventEmitter();\n readonly #detector: OriginDetector;\n readonly #rendererRegistry: RendererRegistry;\n readonly #runtime: LivePreviewRuntime;\n readonly #plugins: PluginManager;\n readonly #log: (...args: unknown[]) => void;\n #started = false;\n #destroyed = false;\n #destroyPromise: Promise<void> | null = null;\n\n constructor(config: LivePreviewClientConfig = {}) {\n const debug = config.debug ?? isDevMode();\n this.#log = debug\n ? (...args): void => {\n safeConsoleDebug('[live-preview]', ...args);\n }\n : noopDiagnostic;\n\n this.#detector = new OriginDetector({\n ...(config.allowedOrigins !== undefined ? { additionalOrigins: config.allowedOrigins } : {}),\n ...(config.disableReferrerDetection !== undefined\n ? { enableReferrerDetection: !config.disableReferrerDetection }\n : {}),\n ...(config.disableLocalhostMatching !== undefined\n ? { enableLocalhostMatching: !config.disableLocalhostMatching }\n : {}),\n });\n\n if (this.#detector.isProductionUnconfigured) {\n this.#log('no trusted origin could be detected — set allowedOrigins or PAYLOAD_ADMIN_ORIGIN');\n }\n\n this.#rendererRegistry = new RendererRegistry(buildBuiltinRenderers());\n\n this.#plugins = new PluginManager({\n events: this.#emitter,\n config: Object.freeze({ ...config }),\n registerFieldRenderer: (renderer) => this.#rendererRegistry.register(renderer),\n onTransformError: (error) => {\n void this.#emitter.emit('error', { error, context: 'transform', code: 'LP0602' });\n },\n log: this.#log,\n });\n\n this.#runtime = new LivePreviewRuntime({\n ...(config.root !== undefined ? { root: config.root } : {}),\n renderers: this.#rendererRegistry.renderers,\n resolveRenderer: (fieldType: FieldType) => this.#rendererRegistry.resolve(fieldType),\n transformValue: (\n fieldName: string,\n value: unknown,\n context: { readonly element: Element; readonly allFields: Record<string, unknown> },\n isCurrent?: () => boolean,\n ) => this.#plugins.applyTransforms(fieldName, value, context, isCurrent),\n originMatcher: (origin) => this.#detector.matches(origin),\n readyTargets: this.#detector.enumerate(),\n emitter: this.#emitter,\n ...(config.serverURL !== undefined && config.serverURL !== ''\n ? {\n dataMerge: {\n serverURL: config.serverURL,\n ...(config.apiRoute !== undefined ? { apiRoute: config.apiRoute } : {}),\n ...(config.mergeDepth !== undefined ? { depth: config.mergeDepth } : {}),\n ...(config.mergeFetch !== undefined ? { fetchFn: config.mergeFetch } : {}),\n },\n }\n : {}),\n ...(config.debounceMs !== undefined ? { debounceMs: config.debounceMs } : {}),\n ...(config.heartbeatMs !== undefined ? { heartbeatMs: config.heartbeatMs } : {}),\n ...(config.intersectionRootMargin !== undefined\n ? { intersectionRootMargin: config.intersectionRootMargin }\n : {}),\n ...(config.scopeBindingsByOwner !== undefined\n ? { scopeBindingsByOwner: config.scopeBindingsByOwner }\n : {}),\n ...(config.disableVisibilityGate !== undefined\n ? { disableVisibilityGate: config.disableVisibilityGate }\n : {}),\n ...(config.visibilityGateThreshold !== undefined\n ? { visibilityGateThreshold: config.visibilityGateThreshold }\n : {}),\n ...(config.enableA11y !== undefined ? { enableA11y: config.enableA11y } : {}),\n ...(config.a11yLocale !== undefined ? { a11yLocale: config.a11yLocale } : {}),\n onHeartbeatTimeout: () => {\n this.#detector.unlockOrigin();\n },\n lockedOrigin: () => this.#detector.lockedOrigin,\n ...(config.validateToken !== undefined ? { validateToken: config.validateToken } : {}),\n log: this.#log,\n });\n\n this.#emitter.on('connect', (e) => {\n this.#detector.lockOrigin(e.origin);\n });\n\n if (config.autoStart !== false) {\n this.start();\n }\n }\n\n /**\n * Start the runtime. Returns `true` when this client is eligible and runtime\n * startup is active or scheduled for DOM readiness. Repeated calls on an\n * active client also return `true`; `false` means the client was destroyed or\n * the page is outside a preview context. A deferred startup can still fail,\n * roll back, and be retried by a later call.\n */\n start(): boolean {\n if (this.#destroyed) return false;\n if (this.#started) {\n // Normally the runtime is already active and returns false. Calling it is\n // intentional: a deferred DOM-ready startup can fail after this method has\n // returned; the runtime then rolls itself back and this call retries it.\n this.#runtime.start();\n return true;\n }\n if (!isInPreviewContext()) return false;\n const started = this.#runtime.start();\n if (started) this.#started = true;\n return started;\n }\n\n /**\n * Release the message ingress while keeping this client usable.\n *\n * For the document lifecycle, not for teardown: a back/forward-cache restore\n * does not re-run module scripts, so a client that stays attached across\n * `pagehide` returns bound to a frozen page and silently stops updating.\n * Plugins, renderers and transforms survive; `resume()` brings the same\n * client back. Returns `false` when there was nothing running to suspend.\n */\n suspend(): boolean {\n if (this.#destroyed || !this.#started) return false;\n return this.#runtime.suspend();\n }\n\n /**\n * Reacquire after `suspend()`.\n *\n * Deliberately the same path as `start()`: a restored document needs the\n * cache rebuilt, the observers rebound and the handshake rebroadcast, which\n * is exactly what starting does. Returns `false` for a destroyed client or\n * one that was never started.\n */\n resume(): boolean {\n if (this.#destroyed || !this.#started) return false;\n return this.#runtime.start();\n }\n\n /**\n * Stop the runtime and tear down every plugin. Idempotent.\n */\n destroy(): Promise<void> {\n if (this.#destroyPromise !== null) return this.#destroyPromise;\n this.#destroyed = true;\n let resolveDestroy!: () => void;\n let rejectDestroy!: (reason: unknown) => void;\n const inFlight = new Promise<void>((resolve, reject) => {\n resolveDestroy = resolve;\n rejectDestroy = reject;\n });\n // Publish the shared promise before synchronous runtime teardown. A destroy\n // event handler may call destroy() re-entrantly and must receive this same\n // in-flight completion rather than starting or observing a partial teardown.\n this.#destroyPromise = inFlight;\n try {\n this.#runtime.destroy();\n void this.#plugins\n .destroyAll()\n .finally(() => {\n this.#emitter.removeAllListeners();\n })\n .then(resolveDestroy, rejectDestroy);\n } catch (error) {\n this.#emitter.removeAllListeners();\n rejectDestroy(error);\n }\n return inFlight;\n }\n\n /**\n * Register a plugin.\n */\n async use(plugin: LivePreviewPlugin): Promise<void> {\n if (this.#destroyed) throw new Error('LivePreviewClient: already destroyed');\n await this.#plugins.register(plugin);\n }\n\n /** Unregister a plugin and release all resources owned by that registration. */\n async unuse(name: string): Promise<void> {\n await this.#plugins.unregister(name);\n }\n\n /** Rebuild the element cache manually. */\n refreshCache(): void {\n this.#runtime.refreshCache();\n }\n\n /** Read-only access to the event emitter for `on`/`once`/`off`. */\n get events(): EventEmitter {\n return this.#emitter;\n }\n\n /** Names of currently registered plugins. */\n get plugins(): readonly string[] {\n return this.#plugins.list();\n }\n\n /** Current connection status. */\n get status(): 'disconnected' | 'connecting' | 'connected' {\n return this.#runtime.status;\n }\n\n /** Number of valid updates received so far. */\n /**\n * Point-in-time read of runtime state, for diagnosing a preview that is not\n * updating. Performs no I/O and transmits nothing.\n *\n * Read `bindings.orphanFields` when a field refuses to update, and\n * `scheduler.deferred` together with `scheduler.visibilityGateActive` when\n * updates stop below the fold.\n */\n inspect(): LivePreviewInspection {\n return this.#runtime.inspect();\n }\n\n get updateCount(): number {\n return this.#runtime.updateCount;\n }\n\n /** `true` once `destroy()` has been called. */\n get destroyed(): boolean {\n return this.#destroyed;\n }\n}\n\n/**\n * Convenience factory: instantiate the client, returning `null` when\n * the page is not currently a preview context (top-level navigation).\n * Useful for SSR-style integrations that import this from any context.\n */\nexport function initLivePreview(config: LivePreviewClientConfig = {}): LivePreviewClient | null {\n const client = new LivePreviewClient({ ...config, autoStart: false });\n return client.start() ? client : null;\n}\n\nexport type { LivePreviewClientConfig } from './config';\n","/**\n * Document-lifecycle owner for the live-preview client.\n *\n * The runtime learns about messages, not about navigation. Two browser\n * behaviours make that gap visible, and both are silent:\n *\n * - A **back/forward-cache restore** does not re-run module scripts. A client\n * that stays attached across `pagehide` comes back bound to a document the\n * browser froze and thawed, and simply stops updating.\n * - A **soft navigation** replaces page content without a new document. The\n * bindings the cache holds are gone, and nothing tells the runtime.\n *\n * This binds both to `suspend()`/`resume()`/`refreshCache()` in one place, so a\n * consumer that uses no framework adapter can own the lifecycle with one call\n * instead of re-deriving it — which is what every integration has had to do so\n * far.\n *\n * @module @core/navigation-lifecycle\n */\n\n/** The part of the client this owner drives. */\nexport interface NavigationLifecycleTarget {\n suspend(): boolean;\n resume(): boolean;\n refreshCache(): void;\n}\n\nexport interface NavigationLifecycleOptions {\n /**\n * Event target for `pagehide`/`pageshow`. Defaults to `window`.\n *\n * These fire on the window, not the document, and only there — binding them\n * anywhere else silently never fires.\n */\n readonly windowTarget?: EventTarget;\n /**\n * Event target for soft-navigation events. Defaults to `document`.\n */\n readonly documentTarget?: EventTarget;\n /**\n * Soft-navigation events after which the DOM has been replaced and the\n * binding cache has to be rebuilt — for example `astro:page-load`.\n *\n * Empty by default: the package cannot know which framework is present, and\n * guessing would either miss the event or rebuild on an unrelated one.\n */\n readonly softNavigationEvents?: readonly string[];\n}\n\n/**\n * Bind the document lifecycle. Returns an unbind function; calling it twice is\n * harmless.\n */\nexport function bindNavigationLifecycle(\n target: NavigationLifecycleTarget,\n options: NavigationLifecycleOptions = {},\n): () => void {\n const windowTarget = options.windowTarget ?? (globalThis as { window?: EventTarget }).window;\n const documentTarget =\n options.documentTarget ?? (globalThis as { document?: EventTarget }).document;\n const softEvents = options.softNavigationEvents ?? [];\n\n const onPageHide = (): void => {\n target.suspend();\n };\n const onPageShow = (event: Event): void => {\n // Only a *persisted* restore needs reacquiring. An ordinary load already\n // ran the module scripts, and resuming there would rebuild a cache the\n // startup just built.\n if ((event as Event & { readonly persisted?: boolean }).persisted === true) {\n target.resume();\n }\n };\n const onSoftNavigation = (): void => {\n target.refreshCache();\n };\n\n windowTarget?.addEventListener('pagehide', onPageHide);\n windowTarget?.addEventListener('pageshow', onPageShow);\n for (const name of softEvents) documentTarget?.addEventListener(name, onSoftNavigation);\n\n let unbound = false;\n return (): void => {\n if (unbound) return;\n unbound = true;\n windowTarget?.removeEventListener('pagehide', onPageHide);\n windowTarget?.removeEventListener('pageshow', onPageShow);\n for (const name of softEvents) documentTarget?.removeEventListener(name, onSoftNavigation);\n };\n}\n","/**\n * Stable identifiers for everything the runtime reports.\n *\n * Prose gets reworded; a code does not. A consumer filtering logs, an alert\n * rule, or a bug report referring to `LP0301` keeps meaning the same thing\n * after the sentence around it is rewritten, and a code is greppable in a way\n * that a sentence fragment is not.\n *\n * Codes are grouped by the question they answer:\n *\n * - `LP01xx` — configuration and origin trust: the runtime is running, but it\n * was set up in a way that will bite.\n * - `LP02xx` — bindings and markup: an update had nowhere to land.\n * - `LP03xx` — updates and scheduling: the update landed somewhere other than\n * the DOM, or not yet.\n * - `LP04xx` — rendering: a value reached an element and was refused.\n * - `LP05xx` — protocol and messages: something arrived that was not accepted.\n * - `LP06xx` — consumer callbacks: code the consumer supplied threw.\n * - `LP07xx` — audit findings from `pll doctor`, which reports on a served\n * response rather than on a running runtime.\n *\n * A code is part of the public contract. Codes are never reused for a\n * different meaning and never renumbered; a retired code stays retired.\n * `LP0604` is unassigned: a throwing token validator is deliberately treated\n * as a rejection and reported as `LP0502`, so there is nothing distinct to\n * report yet. The number stays reserved rather than being handed to something\n * else.\n *\n * The runtime writes these as string literals at each reporting site rather\n * than reading them from this record, so the inline build pays for the six\n * characters it prints and nothing more. This record exists so consumers can\n * refer to a code by name instead of copying a literal.\n *\n * @module @core/diagnostic-codes\n */\n\n/**\n * Every diagnostic code the runtime can report, by name.\n *\n * ```ts\n * client.events.on('error', (e) => {\n * if (e.code === DIAGNOSTIC_CODES.TransformThrew) reportToSentry(e.error);\n * });\n * ```\n */\nexport const DIAGNOSTIC_CODES = Object.freeze({\n /** No trusted origin configured in production; nothing will be accepted. */\n NoTrustedOrigin: 'LP0101',\n /** Origin trust rests on `document.referrer`, so any framing site is trusted. */\n ReferrerOnlyTrust: 'LP0102',\n\n /** An update named a field with no binding anchor on the page. */\n OrphanField: 'LP0201',\n /** Owner scoping is on and the update names no document it could belong to. */\n UnattributableUpdate: 'LP0202',\n\n /** The visibility gate held offscreen writes back until they scroll into view. */\n VisibilityGateDeferred: 'LP0301',\n\n /** A value was refused because the attribute or the value itself is unsafe. */\n UnsafeAttributeWrite: 'LP0401',\n /** A text element has structured children, so replacing its text was skipped. */\n TextTargetHasChildren: 'LP0402',\n /** A structural container has no array template, so the update was skipped. */\n MissingArrayTemplate: 'LP0403',\n\n /** A message was rejected before it reached the update pipeline. */\n MessageRejected: 'LP0501',\n /** A preview token was rejected. */\n TokenRejected: 'LP0502',\n\n /** A consumer event handler threw. */\n HandlerThrew: 'LP0601',\n /** A consumer transform threw; the original value was kept. */\n TransformThrew: 'LP0602',\n /** A renderer threw while writing a value. */\n RendererThrew: 'LP0603',\n /** Runtime startup failed. */\n StartupFailed: 'LP0605',\n /** Sending the ready handshake failed. */\n ReadyFailed: 'LP0606',\n\n /** The audit found no runtime in a response that carried preview intent. */\n AuditRuntimeMissing: 'LP0701',\n /** The preview response declares no `frame-ancestors`. */\n AuditNoFrameAncestors: 'LP0702',\n /** `X-Frame-Options` forbids framing, which no CSP can undo. */\n AuditFrameOptionsBlocks: 'LP0703',\n /** Binding attributes are served to anonymous visitors. */\n AuditBindingsExposed: 'LP0704',\n /** More bindings than the default visibility gate will write eagerly. */\n AuditGateThresholdExceeded: 'LP0705',\n /** Owner markers exist, but some bindings are outside all of them. */\n AuditUnownedBindings: 'LP0706',\n /** The preview response carries no bindings at all. */\n AuditNoBindings: 'LP0707',\n /** The URL did not return an HTML page, so nothing else can be judged. */\n AuditNotAPage: 'LP0708',\n} as const);\n\n/** A diagnostic code, as it appears in log output and on the `error` event. */\nexport type DiagnosticCode = (typeof DIAGNOSTIC_CODES)[keyof typeof DIAGNOSTIC_CODES];\n","// Auto-generated by scripts/build-runtime.ts — do not edit.\nexport interface RuntimeBuildInfo { readonly generatedAt: string; readonly size: number }\nexport const RUNTIME_SOURCE: string = \"(()=>{function t(t){return(\\\"object\\\"==typeof t&&null!==t||\\\"function\\\"==typeof t)&&\\\"function\\\"==typeof t.then&&(Promise.resolve(t).catch(()=>{}),!0)}function e(e){return(...i)=>{try{t(e(...i))}catch{}}}function i(){}function n(){return!0}function r(t){return`global:${t}`}function l(t,e){return void 0===e||\\\"\\\"===e?`collection:${t}`:`collection:${t}:${e}`}function s(t){return\\\"string\\\"==typeof t&&t.length>0}function o(t,e){return null!==e&&void 0!==t&&e.includes(t)}function a(t){let e=t.id;return\\\"string\\\"==typeof e&&e.length>0?e:\\\"number\\\"==typeof e&&Number.isFinite(e)?String(e):void 0}function u(t){if(t.nodeType!==Ze)return!1;let e=t;return!!e.hasAttribute(ke)||null!==e.querySelector(`[${ke}]`)}function h(t){if(!Array.isArray(t))return[];let e=[];for(let i of t){let t=d(i);t&&e.push(t)}return e}function d(t){if(\\\"object\\\"!=typeof t||null===t)return;let e=t,i=e.name,n=e.type;if(\\\"string\\\"!=typeof i||0===i.length||\\\"string\\\"!=typeof n||0===n.length)return;let r=h(e.fields),l=function(t){if(!Array.isArray(t))return[];let e=[];for(let i of t){if(\\\"object\\\"!=typeof i||null===i)continue;let t=i,n=t.slug;if(\\\"string\\\"!=typeof n||0===n.length)continue;let r=h(t.fields);e.push({...t,slug:n,fields:r})}return e}(e.blocks),s={...e,name:i,type:n};return r.length>0?s.fields=r:delete s.fields,l.length>0?s.blocks=l:delete s.blocks,s}function c(t){let e=\\\"number\\\"==typeof t&&Number.isFinite(t)&&t>=1?Math.floor(t):void 0,i=Math.min(4,e??1),n=new Set;for(let[t,e]of Object.entries(ni))i>=e&&n.add(t);return{ours:4,...void 0!==e?{theirs:e}:{theirs:void 0},negotiated:i,capabilities:n}}function f(t,e){return void 0===t||e(t)}function p(t,e){return null==t||e(t)}function g(t){if(\\\"object\\\"!=typeof t||null===t)return!1;let e=Object.getPrototypeOf(t);return null===e||null===Object.getPrototypeOf(e)}function m(t){for(let e of t){let t=e.codePointAt(0);if(void 0!==t&&(t<=31||127===t))return!0}return!1}function y(t){if(void 0===t||0===t.length||t.length>128||\\\".\\\"===t||\\\"..\\\"===t||t.includes(\\\"/\\\")||t.includes(\\\"\\\\\\\\\\\")||t.includes(\\\"?\\\")||t.includes(\\\"#\\\")||m(t))return!1;try{return encodeURIComponent(t),!0}catch{return!1}}function v(t,e){return t[6]===e}function b(t){return t.aborted}function w(t){if(\\\"string\\\"!=typeof t||0===t.length)return!1;let e=t.trim();if(0===e.length||$i.test(e))return!1;if(e.startsWith(\\\"#\\\")||e.startsWith(\\\"?\\\")||e.startsWith(\\\"//\\\")||e.startsWith(\\\"/\\\"))return!0;try{let t=new URL(e);return Si.has(t.protocol)}catch{return Ai.test(e)}}function S(t){if(!w(t))return!1;let e=t.trim();return/^https?:\\\\/\\\\//i.test(e)||/^\\\\/\\\\/[^/]/.test(e)}function $(t){return Ni.add(t),t}function A(t,e){return null!==e&&t.generation===e.generation&&t.revision===e.revision}function k(t,e,i,n=!1){if(n&&void 0!==i){let n=T(t,`${e}_${i}`);if(void 0!==n)return n}let r=T(t,e);if(void 0!==r)return r;if(e.includes(\\\".\\\")){let i=t,n=!0;for(let t of e.split(\\\".\\\")){if(Fi.has(t)||null===i||\\\"object\\\"!=typeof i){n=!1;break}if(i=T(i,t),void 0===i){n=!1;break}}if(n)return i}return void 0===i?void 0:T(t,`${e}_${i}`)}function T(t,e){if(!Fi.has(e)&&Object.prototype.hasOwnProperty.call(t,e))return t[e]}function N(){let t=function(){if(typeof document>\\\"u\\\")return;let t=document.documentElement.getAttribute(\\\"lang\\\");return null===t||0===t.length?void 0:t}();if(void 0!==t)return t;let e=function(){if(typeof navigator>\\\"u\\\")return;let t=navigator.language;return\\\"string\\\"==typeof t&&t.length>0?t:void 0}();return void 0!==e?e:\\\"en\\\"}function x(t){return/^de(?:[-_]|$)/i.test(t)}function M(t){null!==t[4]&&(clearTimeout(t[4]),t[4]=null),t[2]?.remove(),t[2]=null}function C(t,e=\\\"\\\"){let i=new Map;return O(t,e,i),i}function O(t,e,i){for(let n of t){if(Vi.has(n.type)){n.fields&&O(n.fields,e,i);continue}if(\\\"group\\\"===n.type){let t=\\\"\\\"===e?n.name:`${e}.${n.name}`;i.set(t,n),n.fields&&O(n.fields,t,i);continue}let t=\\\"\\\"===e?n.name:`${e}.${n.name}`;if(i.set(t,n),\\\"array\\\"===n.type&&n.fields)O(n.fields,`${t}.*`,i);else if(\\\"blocks\\\"===n.type&&n.blocks)for(let e of n.blocks)O(e.fields,`${t}.*.${e.slug}`,i)}}function L(t){if(\\\"object\\\"!=typeof t||null===t)return;let e=t.id;return\\\"string\\\"==typeof e||\\\"number\\\"==typeof e?e:void 0}function j(t){if(\\\"object\\\"!=typeof t||null===t)return;let e=t.blockType;return\\\"string\\\"==typeof e?e:void 0}function E(t,e){return e.every(t=>void 0!==L(t))?function(t,e){let i=[],n=new Map;for(let e=0;e<t.length;e+=1){let i=L(t[e]);void 0!==i&&n.set(i,e)}let r=new Set;for(let l=0;l<e.length;l+=1){let s=e[l],o=L(s);if(void 0===o){i.push({kind:\\\"insert\\\",index:l,value:s});continue}let a=n.get(o);if(void 0===a){i.push({kind:\\\"insert\\\",index:l,value:s});continue}r.add(a);let u=t[a];j(u)===j(s)?(a!==l&&i.push({kind:\\\"move\\\",from:a,to:l,value:s}),I(u,s)||i.push({kind:\\\"update\\\",index:l,value:s})):i.push({kind:\\\"replace\\\",index:l,oldValue:u,value:s})}for(let e=0;e<t.length;e+=1)r.has(e)||i.push({kind:\\\"remove\\\",index:e,value:t[e]});return i}(t,e):function(t,e){let i=[],n=Math.min(t.length,e.length);for(let r=0;r<n;r+=1)I(t[r],e[r])||i.push({kind:\\\"update\\\",index:r,value:e[r]});if(e.length>t.length)for(let n=t.length;n<e.length;n+=1)i.push({kind:\\\"insert\\\",index:n,value:e[n]});if(t.length>e.length)for(let n=e.length;n<t.length;n+=1)i.push({kind:\\\"remove\\\",index:n,value:t[n]});return i}(t,e)}function I(t,e){if(Object.is(t,e))return!0;if(\\\"object\\\"!=typeof t||\\\"object\\\"!=typeof e||null===t||null===e)return!1;let i=t,n=e,r=Object.keys(i),l=Object.keys(n);if(r.length!==l.length)return!1;for(let t of r)if(!Object.is(i[t],n[t]))return!1;return!0}function P(t){return 9===t.nodeType}function R(t){if(typeof window>\\\"u\\\")return;let e=[];window.parent!==window&&e.push(window.parent),window.opener instanceof Window&&e.push(window.opener),ri.sendReady(e,t)}function _(t,e){return t.generation===e.generation&&t.revision===e.revision}function W(t){return null!=t&&(\\\"string\\\"==typeof t||\\\"number\\\"==typeof t||\\\"boolean\\\"==typeof t||\\\"bigint\\\"==typeof t)}function F(t,e){if(!e)return t;let i=`_${e}`;return t.endsWith(i)?t.slice(0,-i.length):t}function D(){if(typeof window>\\\"u\\\")return!1;try{return window.self!==window.top}catch{return!0}}function U(t){if(typeof process<\\\"u\\\"){let e=process.env[t];if(\\\"string\\\"==typeof e&&e.length>0)return e}}function z(t){let e=t.trim();if(0!==e.length)try{let t=new URL(e);return\\\"http:\\\"!==t.protocol&&\\\"https:\\\"!==t.protocol||!Sn.test(t.origin)?void 0:t.origin}catch{return}}function V(t,e){let i=G();if(!i)throw new Pn(\\\"sanitizeHtml needs a DOM; provide one with setSanitizerDocument() during SSR.\\\");if(\\\"\\\"===t)return\\\"\\\";let n=function(t){if(!t){let t=new Map;for(let[e,i]of Object.entries(Ln))t.set(e,i);return{allowedTags:Nn,attrByTag:t}}let e=new Set(Nn);for(let i of t.additionalAllowedTags??[])e.add(i);let i=new Map;for(let[t,e]of Object.entries(Ln))i.set(t,e);for(let[e,n]of Object.entries(t.additionalAllowedAttributes??{})){let t=i.get(e),r=new Set(t??[]);for(let t of n)r.add(t);i.set(e,r)}return{allowedTags:e,attrByTag:i}}(e),r=i.createElement(\\\"template\\\");return r.innerHTML=t,B(r.content,n),r.innerHTML}function G(){if(!(typeof document>\\\"u\\\"))return document}function B(t,e){for(let i of Array.from(t.childNodes))i.nodeType===En?H(i,e):i.nodeType===In&&i.remove()}function H(t,e){let i=t.tagName.toLowerCase();if(xn.has(i))t.remove();else{if(!e.allowedTags.has(i)){B(t,e);let i=t.parentNode;if(i){for(;t.firstChild;)i.insertBefore(t.firstChild,t);t.remove()}return}(function(t,e,i){let n=i.attrByTag.get(e);for(let e of Array.from(t.attributes)){let i=e.name.toLowerCase();if(i.startsWith(\\\"on\\\"))t.removeAttribute(e.name);else if(\\\"style\\\"!==i){if(!(Mn.has(i)||i.startsWith(Cn)||i.startsWith(On))){if(n?.has(i)){(jn.has(i)&&!w(e.value)||\\\"srcset\\\"===i&&!q(e.value))&&t.removeAttribute(e.name);continue}t.removeAttribute(e.name)}}else t.removeAttribute(e.name)}})(t,i,e),\\\"a\\\"===i&&function(t){let e=t.getAttribute(\\\"href\\\");null===e||!S(e)||(t.setAttribute(\\\"rel\\\",\\\"noopener noreferrer\\\"),t.hasAttribute(\\\"target\\\")||t.setAttribute(\\\"target\\\",\\\"_blank\\\"))}(t),B(t,e)}}function q(t){let e=t.split(\\\",\\\");for(let t of e){let e=t.trim();if(0===e.length)continue;let i=e.search(/\\\\s/);if(!w(-1===i?e:e.slice(0,i)))return!1}return!0}function J(t,e){Rn.set(t,e)}function X(t){let e=t.format;if(\\\"string\\\"==typeof e&&Wn.has(e))return e;if(\\\"number\\\"==typeof e){let t=_n[e];if(void 0!==t)return t}}function Y(t){let e=t.indent;return\\\"number\\\"==typeof e&&e>0?e:0}function Z(t){return\\\"rtl\\\"===t.direction?' dir=\\\"rtl\\\"':\\\"ltr\\\"===t.direction?' dir=\\\"ltr\\\"':\\\"\\\"}function K(t){let e=X(t),i=Y(t),n=[];return void 0!==e&&n.push(`text-align:${e}`),i>0&&n.push(`padding-inline-start:${String(40*i)}px`),0===n.length?\\\"\\\":` style=\\\"${n.join(\\\";\\\")}\\\"`}function Q(t){return\\\"\\\"===t?\\\"\\\":t.replace(Dn,t=>Fn[t])}function tt(t){return\\\"\\\"===t?\\\"\\\":t.replace(zn,t=>Un[t])}function et(t){return Q(t).replace(/\\\\r\\\\n|\\\\r|\\\\n/g,\\\"<br>\\\")}function it(t){if(\\\"string\\\"==typeof t.text)return t.text;if(!t.children)return\\\"\\\";let e=\\\"\\\";for(let i of t.children)e+=it(i);return e}function nt(t){return t.replace(/[^a-zA-Z0-9_-]/g,\\\"\\\")}function rt(t){return Bn.get(t)}function lt(t){return t.replace(/[^a-zA-Z0-9_-]/g,\\\"-\\\").toLowerCase()}function st(t){if(\\\"object\\\"!=typeof t||null===t||!(\\\"root\\\"in t))return!1;let e=t.root;return\\\"object\\\"==typeof e&&null!==e&&\\\"children\\\"in e&&Array.isArray(e.children)}function ot(t){return st(t)?t.root.children.map(ht).join(\\\"\\\\n\\\").trim():\\\"\\\"}function at(t){let e=\\\"\\\";for(let i of t)e+=ut(i);return e}function ut(t){let e=function(t){return Rn.get(t)}(t.type);return e?e(t,Rt):void 0!==t.children?at(t.children):\\\"\\\"}function ht(t){if(\\\"string\\\"==typeof t.text)return t.text;if(\\\"linebreak\\\"===t.type)return\\\"\\\\n\\\";if(void 0===t.children)return\\\"\\\";let e=\\\"\\\";for(let i of t.children)e+=ht(i);return e}function dt(){let t=new WeakSet;return{name:\\\"text\\\",render:$((e,i)=>{let n=e.element,r=function(t){return null==t?\\\"\\\":st(t)?ot(t):\\\"string\\\"==typeof t?t:\\\"number\\\"==typeof t||\\\"boolean\\\"==typeof t?String(t):JSON.stringify(t)}(i);if(\\\"INPUT\\\"!==n.tagName&&\\\"TEXTAREA\\\"!==n.tagName){if(function(t){return null!==t.firstElementChild}(n)&&!n.hasAttribute(_t))return function(t,e,i){t.has(e)||(t.add(e),pe(`[live-preview] LP0402: Skipping text update for \\\"${i}\\\": <${e.tagName.toLowerCase()}> has structured children. Move data-payload-field to the value element, or add data-payload-text to replace them.`))}(t,n,e.fieldName),!1;r.includes(\\\"\\\\n\\\")||r.includes(\\\"\\\\r\\\")?n.innerHTML=et(r):n.textContent=r}else n.value=r})}}function ct(t){if(null==t)return\\\"\\\";if(\\\"string\\\"==typeof t)return t;if(\\\"number\\\"==typeof t||\\\"boolean\\\"==typeof t||\\\"bigint\\\"==typeof t)return String(t);try{return JSON.stringify(t)}catch{return\\\"\\\"}}function ft(t){if(\\\"object\\\"==typeof t&&null!==t)return t}function pt(t){if(\\\"object\\\"==typeof t&&null!==t){let e=t;return\\\"string\\\"==typeof e.title&&e.title.length>0?e.title:\\\"string\\\"==typeof e.name&&e.name.length>0?e.name:\\\"string\\\"==typeof e.slug&&e.slug.length>0?e.slug:void 0!==e.id?String(e.id):\\\"\\\"}return ct(t)}function gt(t){return Array.isArray(t)?t.map(t=>gt(t)).join(\\\", \\\"):ct(t)}function mt(t,e){let i=t??\\\"\\\";if(null==e)return i;let n=yt(e);return\\\"{}\\\"===n?i:`${i}|${n}`}function yt(t){if(null===t||\\\"object\\\"!=typeof t)return JSON.stringify(t);if(Array.isArray(t))return`[${t.map(t=>yt(t)).join(\\\",\\\")}]`;let e=t,i=Object.keys(e).sort(),n=[];for(let t of i){let i=e[t];void 0!==i&&n.push(`${JSON.stringify(t)}:${yt(i)}`)}return`{${n.join(\\\",\\\")}}`}function vt(t){for(;t.size>Xt;){let e=t.keys().next().value;if(void 0===e)break;t.delete(e)}}function bt(t,e,i,n){let r=\\\"object\\\"==typeof e&&null!==e?e:null;return t.replace(Kt,(t,l)=>null!==r&&function(t,e){return Object.prototype.hasOwnProperty.call(t,e)}(r,l)?Q(n(Reflect.get(r,l))):null===r&&\\\"value\\\"===l?Q(n(e)):\\\"index\\\"===l?String(i):t)}function wt(t,e,i){return bt(t,e,i,ct)}function St(t){return ct(t)}function $t(t){let{template:e,container:i,patches:n,nextItems:r,store:l,forceRender:s=!1}=t,o=At(i,e,n,r,s,l);return null===o?null:kt(o,l)}function At(t,e,i,n,r,l){let s=function(t){let e=new Set,i=new Set;for(let n of t)\\\"insert\\\"===n.kind||\\\"update\\\"===n.kind?e.add(n.index):\\\"replace\\\"===n.kind&&(e.add(n.index),i.add(n.index));return{renders:e,replaces:i}}(i),o=function(t,e,i,n,r,l,s){let o=Array.from(t.children),a=Lt(o,te),u=new Set,h=[];for(let d=0;d<i.length;d+=1){let c=i[d],f=Ot(c),p=void 0===f?o[d]??null:jt(a,f)??null;null!==p&&u.has(p)&&(p=null),null!==p&&u.add(p);let g=n.replaces.has(d),m=r||n.renders.has(d)||null===p?Et(t.ownerDocument,e,c,d):void 0;if(null===m)return null;let y=void 0===m?[]:Tt(g?null:p,m,c,l,s);if(null===y)return null;h.push([d,p,m??void 0,y])}return h}(t,e,n,s,r,l.get(t),l);return null===o?null:[t,o,n]}function kt(t,e){let[i,n,r]=t,l=new Set,s=!1;for(let t of n){let[n,r,o,a]=t,u=r;if(void 0!==o){for(let t of a)null!==t[0]&&(xt(t[0],t[1]),t[1].replaceWith(t[0])),void 0!==t[2]&&kt(t[2],e);null!==r&&(r.replaceWith(o),s=!0),u=o}if(null===u)continue;let h=i.children[n]??null;u!==h&&(i.insertBefore(u,h),s=!0),l.add(u)}for(let t of Array.from(i.children))l.has(t)||(t.remove(),s=!0);let o=function(t,e){let i=e.get(t);return i||(i=new Map,e.set(t,i)),i}(i,e);o.clear();for(let t of r)Ct(o,t);return s}function Tt(t,e,i,n,r){let l=Lt(null===t?[]:Nt(t),ee),s=Ot(i),o=void 0!==s?n?.get(s):void 0,a=[];for(let t of Nt(e)){let e=t.getAttribute(ee);if(null===e)continue;let n,s=jt(l,e)??null,u=t.getAttribute(ie),h=u?s:null,d=h?.getAttribute(ie)??null;if(u){let l=Mt(i,e);if(void 0!==l||null!==h){let i=l??[],s=E(null===h?[]:Mt(o,e)??[],i),a=null!==h&&d!==u;if((s.length>0||a)&&(n=At(h??t,u,s,i,a,r)??void 0,void 0===n))return null}}a.push([h,t,n])}return a}function Nt(t){return Array.from(t.querySelectorAll(`[${ee}]`)).filter(e=>{let i=e.parentElement;for(;null!==i&&i!==t;){if(i.hasAttribute(ee))return!1;i=i.parentElement}return i===t})}function xt(t,e){for(let i of Array.from(t.attributes))e.hasAttribute(i.name)||t.removeAttribute(i.name);for(let i of Array.from(e.attributes))t.getAttribute(i.name)!==i.value&&t.setAttribute(i.name,i.value)}function Mt(t,e){if(\\\"object\\\"!=typeof t||null===t)return;let i=t[e];return Array.isArray(i)?i:void 0}function Ct(t,e){let i=Ot(e);void 0!==i&&t.set(i,e)}function Ot(t){if(\\\"object\\\"!=typeof t||null===t)return;let e=t.id;return\\\"string\\\"==typeof e||\\\"number\\\"==typeof e?String(e):void 0}function Lt(t,e){let i=new Map;for(let n=t.length-1;n>=0;n-=1){let r=t[n];if(void 0===r)continue;let l=r.getAttribute(e);if(null===l)continue;let s=i.get(l);void 0===s?i.set(l,[r]):s.push(r)}return i}function jt(t,e){return t.get(e)?.pop()}function Et(t,e,i,n){let r=function(t,e,i){return bt(t,e,i,ct)}(e,i,n),l=V(r),s=t.createElement(\\\"template\\\");s.innerHTML=l;let o=s.content.firstElementChild;if(!o)return null;let a=Ot(i);return void 0!==a&&o.setAttribute(te,a),o}function It(){let t=new WeakMap,e=new WeakSet,i=new WeakMap;return{name:\\\"structural-array\\\",render:$((n,r)=>{if(!Array.isArray(r))return!1;let l=n.element,s=n.arrayTemplate;if(void 0===s||0===s.length)return function(t,e,i){t.has(e)||(t.add(e),pe(`[live-preview] LP0403: Skipping structural update for \\\"${i}\\\": <${e.tagName.toLowerCase()} data-payload-structural> needs data-payload-array-template (for example \\\"<li>{{label}}</li>\\\").`))}(e,l,n.fieldName),!1;let o=t.get(l),a=Pt(l),u=o?.values??function(t){return t.map((t,e)=>null===t?{__payloadDomPosition:e}:{id:t})}(a),h=E(u,r),d=function(t,e,i){return void 0===t||t.template!==e||!function(t,e){return t.length===e.length&&t.every((t,i)=>t===e[i])}(t.domSnapshot,i)}(o,s,a);if(0===h.length&&!d)return t.set(l,{values:r.slice(),template:s,domSnapshot:a}),!1;let c=$t({template:s,container:l,patches:h,nextItems:r,store:i,forceRender:d});return null!==c&&(t.set(l,{values:r.slice(),template:s,domSnapshot:Pt(l)}),!!c&&void 0)})}}function Pt(t){return Array.from(t.children,t=>t.getAttribute(te))}var Rt,_t,Wt,Ft,Dt,Ut,zt,Vt,Gt,Bt,Ht,qt,Jt,Xt,Yt,Zt,Kt,Qt,te,ee,ie,ne,re,le=Object.defineProperty,se=t=>{throw TypeError(t)},oe=(t,e,i)=>((t,e,i)=>e in t?le(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i)(t,\\\"symbol\\\"!=typeof e?e+\\\"\\\":e,i),ae=(t,e,i)=>e.has(t)||se(\\\"Cannot \\\"+i),ue=(t,e,i)=>(ae(t,e,\\\"read from private field\\\"),i?i.call(t):e.get(t)),he=(t,e,i)=>e.has(t)?se(\\\"Cannot add the same private member more than once\\\"):e instanceof WeakSet?e.add(t):e.set(t,i),de=(t,e,i,n)=>(ae(t,e,\\\"write to private field\\\"),n?n.call(t,i):e.set(t,i),i),ce=(t,e,i)=>(ae(t,e,\\\"access private method\\\"),i),fe=e((...t)=>console.error(...t)),pe=e((...t)=>console.warn(...t)),ge=e((...t)=>console.debug(...t)),me=class{constructor(){he(this,be);he(this,ye,new Map);he(this,ve,new Map)}on(t,e){return ce(this,be,Se).call(this,ue(this,ye),t,e)}once(t,e){return ce(this,be,Se).call(this,ue(this,ve),t,e)}off(t,e){ce(this,be,$e).call(this,ue(this,ye),t,e),ce(this,be,$e).call(this,ue(this,ve),t,e)}async emit(t,e){await ce(this,be,we).call(this,t,e)}async emitWhile(t,e,i){return ce(this,be,we).call(this,t,e,i)}listenerCount(t){return(ue(this,ye).get(t)?.size??0)+(ue(this,ve).get(t)?.size??0)}removeAllListeners(t){void 0!==t?(ue(this,ye).delete(t),ue(this,ve).delete(t)):(ue(this,ye).clear(),ue(this,ve).clear())}eventNames(){let t=new Set;for(let e of ue(this,ye).keys())t.add(e);for(let e of ue(this,ve).keys())t.add(e);return[...t]}},ye=new WeakMap,ve=new WeakMap,be=new WeakSet,we=async function(t,e,i){let n=()=>i?.()??!0;if(!n())return!1;let r=ue(this,ye).get(t);if(r)for(let i of[...r])if(!n()||(await ce(this,be,Ae).call(this,i,e,t),!n()))return!1;if(!n())return!1;let l=ue(this,ve).get(t);if(l&&l.size>0){let i=[...l];ue(this,ve).delete(t);for(let r of i)if(!n()||(await ce(this,be,Ae).call(this,r,e,t),!n()))return!1}return n()},Se=function(t,e,i){let n=t.get(e);return n||(n=new Set,t.set(e,n)),n.add(i),()=>{ce(this,be,$e).call(this,t,e,i)}},$e=function(t,e,i){let n=t.get(e);void 0!==n&&(n.delete(i),0===n.size&&t.delete(e))},Ae=async function(t,e,i){try{await t(e)}catch(t){let e=\\\"string\\\"==typeof i||\\\"number\\\"==typeof i?String(i):\\\"<event>\\\";fe(`[live-preview] LP0601: handler for \\\"${e}\\\" threw:`,t)}},ke=\\\"data-payload-field\\\",Te=\\\"data-payload-type\\\",Ne=\\\"data-payload-attribute\\\",xe=\\\"data-payload-href\\\",Me=\\\"data-payload-src\\\",Ce=\\\"data-payload-alt\\\",Oe=\\\"data-payload-array-template\\\",Le=\\\"data-payload-array-separator\\\",je=\\\"data-payload-locale\\\",Ee=\\\"data-payload-richtext\\\",Ie=\\\"data-payload-html\\\",Pe=\\\"data-payload-array\\\",Re=\\\"data-payload-structural\\\",_e=\\\"data-payload-owner\\\",We=[ke,Te,Ne,xe,Me,Ce,Oe,Le,je,Ee,Ie,Pe,Re,_e,\\\"type\\\"],Fe=`[${ke}]`,De=`[${_e}]`,Ue=new Set([\\\"text\\\",\\\"textarea\\\",\\\"richText\\\",\\\"email\\\",\\\"number\\\",\\\"checkbox\\\",\\\"date\\\",\\\"select\\\",\\\"radio\\\",\\\"array\\\",\\\"blocks\\\",\\\"group\\\",\\\"tabs\\\",\\\"row\\\",\\\"collapsible\\\",\\\"relationship\\\",\\\"upload\\\",\\\"point\\\",\\\"json\\\",\\\"code\\\",\\\"ui\\\",\\\"html\\\",\\\"url\\\",\\\"image\\\",\\\"structural-array\\\"]),ze=class{constructor(t={}){he(this,He);he(this,Ve,new Map);he(this,Ge,new WeakMap);he(this,Be);de(this,Be,t.filter??n)}buildFromRoot(t){let e=performance.now();this.clear();let i=t.querySelectorAll(Fe),n=0;for(let t of i)void 0!==this.add(t)&&(n+=1);return{elementCount:n,fieldCount:ue(this,Ve).size,durationMs:performance.now()-e}}add(t){let e=ue(this,Be).call(this,t)?ce(this,He,Ye).call(this,t):void 0,i=ue(this,Ge).get(t);if(void 0!==e)return void 0!==i&&ce(this,He,qe).call(this,i,e)?(ue(this,Ge).set(t,e),e):(void 0!==i&&ce(this,He,Je).call(this,t,i),ce(this,He,Xe).call(this,e),ue(this,Ge).set(t,e),e);void 0!==i&&ce(this,He,Je).call(this,t,i)}remove(t){let e=ue(this,Ge).get(t);return!!e&&ce(this,He,Je).call(this,t,e)}get(t){return ue(this,Ve).get(t)}getByElement(t){return ue(this,Ge).get(t)}get fieldCount(){return ue(this,Ve).size}get elementCount(){let t=0;for(let e of ue(this,Ve).values())t+=e.length;return t}entries(){return ue(this,Ve).entries()}*values(){for(let t of ue(this,Ve).values())yield*t}has(t){return ue(this,Ge).has(t)}clear(){ue(this,Ve).clear(),de(this,Ge,new WeakMap)}},Ve=new WeakMap,Ge=new WeakMap,Be=new WeakMap,He=new WeakSet,qe=function(t,e){if(t.fieldName!==e.fieldName)return!1;let i=ue(this,Ve).get(t.fieldName);if(!i)return!1;let n=i.indexOf(t);return!(n<0||(i[n]=e,0))},Je=function(t,e){let i=ue(this,Ve).get(e.fieldName);if(!i)return ue(this,Ge).delete(t),!1;let n=i.indexOf(e);return n<0?(ue(this,Ge).delete(t),!1):(i.splice(n,1),0===i.length&&ue(this,Ve).delete(e.fieldName),ue(this,Ge).delete(t),!0)},Xe=function(t){let e=ue(this,Ve).get(t.fieldName);e?e.push(t):ue(this,Ve).set(t.fieldName,[t])},Ye=function(t){let e=t.getAttribute(ke);if(null===e||0===e.length)return;let i=t.getAttribute(Te),n=function(t){let e=t.getAttribute(Te);if(null!==e&&Ue.has(e))return e;if(t.hasAttribute(Ee))return\\\"richText\\\";if(t.hasAttribute(Ie))return\\\"html\\\";if(t.hasAttribute(Re))return\\\"structural-array\\\";if(t.hasAttribute(Pe))return\\\"array\\\";if(\\\"IMG\\\"===t.tagName)return\\\"image\\\";if(\\\"A\\\"===t.tagName)return\\\"url\\\";if(\\\"TIME\\\"===t.tagName)return\\\"date\\\";if(\\\"INPUT\\\"===t.tagName){let e=t.type;if(\\\"checkbox\\\"===e)return\\\"checkbox\\\";if(\\\"number\\\"===e)return\\\"number\\\";if(\\\"date\\\"===e||\\\"datetime-local\\\"===e)return\\\"date\\\"}return\\\"text\\\"}(t),r=t.getAttribute(Ne),l=t.getAttribute(xe),s=t.getAttribute(Me),o=t.getAttribute(Ce),a=t.getAttribute(Oe),u=t.getAttribute(Le),h=t.getAttribute(je),d=function(t){let e=t.closest(De)?.getAttribute(_e);return null==e||0===e.length?void 0:e}(t);return{element:t,fieldName:e,fieldType:n,explicitFieldType:null!==i&&Ue.has(i),...null!==r&&r.length>0?{targetAttribute:r}:{},...null!==l&&l.length>0?{hrefField:l}:{},...null!==s&&s.length>0?{srcField:s}:{},...null!==o&&o.length>0?{altField:o}:{},...null!==a?{arrayTemplate:a}:{},...null!==u?{arraySeparator:u}:{},...null!==h&&h.length>0?{locale:h}:{},...void 0!==d?{owner:d}:{}}},Ze=1,Ke=class{constructor(t,e={}){he(this,Qe);oe(this,\\\"s\\\");this.s=[t,e.mutationDebounceMs??100,e.intersectionRootMargin??\\\"200px\\\",new Set,null,null,null,0]}start(t){let e=this.s[7];this.stop();let i=e+1;if(this.s[7]!==i)return;let n=null,r=null;try{n=new MutationObserver(t=>{ce(this,Qe,ti).call(this,t,i)}),r=new IntersectionObserver(t=>{ce(this,Qe,ei).call(this,t,i)},{rootMargin:this.s[2],threshold:0}),n.observe(t,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[...We]})}catch(t){throw n?.disconnect(),r?.disconnect(),t}this.s[7]===i?(this.s[4]=n,this.s[5]=r):(n.disconnect(),r.disconnect())}observeElement(t){this.s[5]?.observe(t)}unobserveElement(t){this.s[5]?.unobserve(t),this.s[3].delete(t)}markVisible(t,e){e?this.s[3].add(t):this.s[3].delete(t)}isVisible(t){return this.s[3].has(t)}stop(){this.s[7]+=1;let t=this.s[6],e=this.s[4],i=this.s[5];this.s[6]=null,this.s[4]=null,this.s[5]=null,this.s[3].clear(),null!==t&&clearTimeout(t);try{e?.disconnect()}finally{i?.disconnect()}}},Qe=new WeakSet,ti=function(t,e){if(!ce(this,Qe,ii).call(this,e)||!function(t){for(let e of t){if(\\\"attributes\\\"===e.type&&null!==e.attributeName&&We.includes(e.attributeName)&&(e.attributeName===ke||e.attributeName===_e||e.target.nodeType===Ze&&e.target.hasAttribute(ke)))return!0;for(let t of e.addedNodes)if(u(t))return!0;for(let t of e.removedNodes)if(u(t))return!0}return!1}(t)||!ce(this,Qe,ii).call(this,e))return;null!==this.s[6]&&clearTimeout(this.s[6]);let i=setTimeout(()=>{!ce(this,Qe,ii).call(this,e)||this.s[6]!==i||(this.s[6]=null,this.s[0].onStructuralChange())},this.s[1]);this.s[6]=i},ei=function(t,e){for(let i of t){if(!ce(this,Qe,ii).call(this,e))return;let t=i.target;if(i.isIntersecting){if(!this.s[3].has(t)&&(this.s[3].add(t),this.s[0].onVisibilityChange(t,!0),!ce(this,Qe,ii).call(this,e)))return}else if(this.s[3].has(t)&&(this.s[3].delete(t),this.s[0].onVisibilityChange(t,!1),!ce(this,Qe,ii).call(this,e)))return}},ii=function(t){return this.s[7]===t&&null!==this.s[5]},ni={basic:1,\\\"schema-json\\\":2,\\\"preview-token\\\":3,\\\"nested-arrays\\\":4,\\\"recursive-diffs\\\":4},ri=class{constructor(t,e){he(this,li);oe(this,\\\"s\\\");this.s=[t,e,void 0,void 0,0,0,[],0]}attach(t=window){if(void 0!==this.s[3])return;let e=!1,i=t=>{if(!e||this.s[2]!==i)return;let n=this.s[4];try{ce(this,li,si).call(this,t,n)}catch{let e=\\\"\\\";try{e=t.origin}catch{}ce(this,li,di).call(this,\\\"shape\\\",e,n)}};this.s[4]+=1,ce(this,li,mi).call(this),this.s[3]=t,this.s[2]=i;try{t.addEventListener(\\\"message\\\",i)}catch(e){this.s[2]===i&&(this.s[3]=void 0,this.s[2]=void 0,ce(this,li,mi).call(this));try{t.removeEventListener(\\\"message\\\",i)}catch{}throw e}if(this.s[2]===i)e=!0;else try{t.removeEventListener(\\\"message\\\",i)}catch{}}detach(t){let e=this.s[3],i=this.s[2];void 0===e||void 0===i||(this.s[3]=void 0,this.s[2]=void 0,ce(this,li,mi).call(this),e.removeEventListener(\\\"message\\\",i))}advanceGeneration(){return void 0!==this.s[3]&&(this.s[4]+=1,ce(this,li,mi).call(this),!0)}static sendReady(t,e){let i=t.length>0;if(!i||0===e.length)return;let n={type:\\\"payload-live-preview\\\",ready:i,protocolVersion:4};for(let i of t)for(let t of e)try{i.postMessage(n,t)}catch{}}},li=new WeakSet,si=function(t,e){if(!ce(this,li,pi).call(this,e))return;let i=t.origin;if(!ce(this,li,pi).call(this,e))return;if(!ce(this,li,ci).call(this,i,e)){ce(this,li,di).call(this,\\\"origin\\\",i,e);return}let n=t.data;if(!ce(this,li,pi).call(this,e))return;let r=function(t){return\\\"object\\\"==typeof t&&null!==t&&\\\"type\\\"in t&&\\\"string\\\"==typeof t.type}(n);if(!ce(this,li,pi).call(this,e))return;if(!r){ce(this,li,di).call(this,\\\"shape\\\",i,e);return}let l=n.type;if(ce(this,li,pi).call(this,e))switch(l){case\\\"payload-live-preview\\\":{let t=function(t){let e=t;return!!((void 0===e.data||null===e.data||g(e.data))&&p(e.fieldSchemaJSON,t=>Array.isArray(t))&&p(e.globalSlug,t=>\\\"string\\\"==typeof t)&&p(e.collectionSlug,t=>\\\"string\\\"==typeof t)&&p(e.locale,t=>\\\"string\\\"==typeof t)&&p(e.ready,t=>\\\"boolean\\\"==typeof t)&&p(e.previewToken,t=>\\\"string\\\"==typeof t)&&p(e.protocolVersion,t=>\\\"number\\\"==typeof t))}(n);if(!ce(this,li,pi).call(this,e))return;if(!t){ce(this,li,di).call(this,\\\"shape\\\",i,e);return}let r=function(t){let e={...t};for(let t of yi)null===Reflect.get(e,t)&&Reflect.deleteProperty(e,t);if(!Array.isArray(e.fieldSchemaJSON))return e;let i;try{i=h(e.fieldSchemaJSON)}catch{i=[]}return{...e,fieldSchemaJSON:i}}(n);if(!ce(this,li,pi).call(this,e))return;ce(this,li,oi).call(this,r,i,e);return}case\\\"payload-document-event\\\":{let t=function(t){let e=t;return!(!f(e.action,t=>\\\"updated\\\"===t||\\\"created\\\"===t||\\\"deleted\\\"===t)||!f(e.slug,t=>\\\"string\\\"==typeof t)||!f(e.id,t=>\\\"string\\\"==typeof t||\\\"number\\\"==typeof t&&Number.isFinite(t)))}(n);if(!ce(this,li,pi).call(this,e))return;if(!t){ce(this,li,di).call(this,\\\"shape\\\",i,e);return}let r;try{r=this.s[1].onDocumentEvent}catch{return}if(!ce(this,li,pi).call(this,e))return;ce(this,li,fi).call(this,r,n,i);return}default:ce(this,li,di).call(this,\\\"type\\\",i,e)}},oi=function(t,e,i){if(!ce(this,li,pi).call(this,i))return;let n=t.data;if(!ce(this,li,pi).call(this,i))return;let r=g(n);if(!ce(this,li,pi).call(this,i))return;let l,s=r?{generation:i,revision:this.s[5]+=1}:void 0;try{l=this.s[1].validateToken}catch{return}if(!ce(this,li,pi).call(this,i))return;if(void 0===l){ce(this,li,hi).call(this,t,e,i,s);return}if(!0===t.ready&&void 0===n){ce(this,li,hi).call(this,t,e,i,void 0);return}let o={generation:i,message:t,origin:e,messageRevision:s,settled:!1,approved:!1};this.s[6].push(o);let a;try{a=l(t.previewToken,e)}catch{ce(this,li,ai).call(this,o,!1);return}\\\"boolean\\\"!=typeof a?Promise.resolve(a).then(t=>{ce(this,li,ai).call(this,o,!0===t)},()=>{ce(this,li,ai).call(this,o,!1)}):ce(this,li,ai).call(this,o,a)},ai=function(t,e){ce(this,li,pi).call(this,t.generation)&&(t.approved=e,t.settled=!0,ce(this,li,ui).call(this,t.generation))},ui=function(t){for(;ce(this,li,pi).call(this,t);){let e=this.s[6][this.s[7]];if(void 0===e)return;if(ce(this,li,ci).call(this,e.origin,t)){if(!e.settled)return;ce(this,li,gi).call(this,e)&&(e.approved?ce(this,li,hi).call(this,e.message,e.origin,e.generation,e.messageRevision):ce(this,li,di).call(this,\\\"token\\\",e.origin,e.generation))}else{if(!ce(this,li,gi).call(this,e))continue;ce(this,li,di).call(this,\\\"origin\\\",e.origin,e.generation)}}},hi=function(t,e,i,n){if(!ce(this,li,pi).call(this,i))return;let r;try{r=this.s[1].onUpdate}catch{return}ce(this,li,pi).call(this,i)&&(void 0===n?ce(this,li,fi).call(this,r,t,e):ce(this,li,fi).call(this,r,t,e,n))},di=function(t,e,i){if(!ce(this,li,pi).call(this,i))return;let n;try{n=this.s[1].onInvalid}catch{return}ce(this,li,pi).call(this,i)&&void 0!==n&&ce(this,li,fi).call(this,n,t,e)},ci=function(t,e){if(!ce(this,li,pi).call(this,e))return!1;try{return!0===this.s[0](t)&&ce(this,li,pi).call(this,e)}catch{return!1}},fi=function(e,...i){try{t(e(...i))}catch{}},pi=function(t){return void 0!==this.s[3]&&this.s[4]===t},gi=function(t){let e=this.s;return e[6][e[7]]===t&&(e[7]+=1,e[7]===e[6].length?(ce(this,li,mi).call(this),!0):(e[7]>=1024&&2*e[7]>=e[6].length&&(e[6]=e[6].slice(e[7]),e[7]=0),!0))},mi=function(){this.s[6]=[],this.s[7]=0},yi=[\\\"data\\\",\\\"fieldSchemaJSON\\\",\\\"globalSlug\\\",\\\"collectionSlug\\\",\\\"locale\\\",\\\"ready\\\",\\\"previewToken\\\",\\\"protocolVersion\\\"],vi=class{constructor(t){oe(this,\\\"s\\\");this.s=[t.timeoutMs??0,t.onTimeout,null,0]}kick(){if(this.s[3]=Date.now(),this.s[0]<=0)return;null!==this.s[2]&&clearTimeout(this.s[2]);let t=setTimeout(()=>{this.s[2]===t&&(this.s[2]=null,this.s[1]())},this.s[0]);this.s[2]=t}stop(){null!==this.s[2]&&(clearTimeout(this.s[2]),this.s[2]=null)}get lastKickAt(){return this.s[3]}get pending(){return null!==this.s[2]}},bi=class{constructor(t){oe(this,\\\"s\\\");this.s=[\\\"disconnected\\\",t]}get status(){return this.s[0]}markConnected(){return this.transition(\\\"connected\\\")}markConnecting(){return this.transition(\\\"connecting\\\")}markDisconnected(){return this.transition(\\\"disconnected\\\")}transition(t){if(this.s[0]===t)return!1;let e=this.s[0];return this.s[0]=t,this.s[1](t,e),!0}},wi=class{constructor(t){oe(this,\\\"s\\\");let n=t.serverURL.replace(/\\\\/+$/,\\\"\\\"),r=t.apiRoute??\\\"/api\\\";this.s=[n,r.startsWith(\\\"/\\\")?r:`/${r}`,t.depth??1,t.fetchFn,void 0===t.log?i:e(t.log),null,0,0]}canMerge(t){try{return t.globalSlug?y(t.globalSlug):!!y(t.collectionSlug)&&function(t){if(\\\"number\\\"==typeof t)return Number.isFinite(t);if(\\\"string\\\"!=typeof t||0===t.length||t.length>512||\\\".\\\"===t||\\\"..\\\"===t||t.includes(\\\"/\\\")||t.includes(\\\"\\\\\\\\\\\")||m(t))return!1;try{return encodeURIComponent(t),!0}catch{return!1}}(t.data.id)}catch{return!1}}async merge(t){if(this.s[7]>0)return{status:\\\"superseded\\\"};let e=this.s[6]+1;this.s[6]=e;let i=this.s[5];this.s[5]=null;let n=null;try{if(i?.abort(),!v(this.s,e))return{status:\\\"superseded\\\"};if(!this.canMerge(t))return v(this.s,e)?{status:\\\"unavailable\\\"}:{status:\\\"superseded\\\"};if(!v(this.s,e))return{status:\\\"superseded\\\"};let r=this.s[3]??(\\\"function\\\"==typeof fetch?fetch:void 0);if(!v(this.s,e))return{status:\\\"superseded\\\"};if(void 0===r)return{status:\\\"unavailable\\\"};if(n=new AbortController,!v(this.s,e))return n.abort(),{status:\\\"superseded\\\"};this.s[5]=n;let l=t.globalSlug?`globals/${encodeURIComponent(t.globalSlug)}`:`${encodeURIComponent(t.collectionSlug??\\\"\\\")}/${encodeURIComponent(String(t.data.id))}`,s=`${this.s[0]}${this.s[1]}/${l}`,o=JSON.stringify({data:t.data,depth:this.s[2],flattenLocales:!1,...void 0!==t.locale?{locale:t.locale}:{}});if(!v(this.s,e))return{status:\\\"superseded\\\"};let a=await r(s,{method:\\\"POST\\\",credentials:\\\"include\\\",headers:{\\\"Content-Type\\\":\\\"application/json\\\",\\\"X-Payload-HTTP-Method-Override\\\":\\\"GET\\\"},body:o,signal:n.signal});if(!v(this.s,e)||b(n.signal))return{status:\\\"superseded\\\"};let u=a.ok;if(!v(this.s,e))return{status:\\\"superseded\\\"};if(!u){let t=a.status;return v(this.s,e)?(this.s[4](\\\"merge HTTP\\\",t,s),v(this.s,e)?{status:\\\"unavailable\\\"}:{status:\\\"superseded\\\"}):{status:\\\"superseded\\\"}}let h=await a.json();return!v(this.s,e)||b(n.signal)?{status:\\\"superseded\\\"}:null===h||\\\"object\\\"!=typeof h||Array.isArray(h)?(this.s[4](\\\"merge invalid\\\",s),v(this.s,e)?{status:\\\"unavailable\\\"}:{status:\\\"superseded\\\"}):{status:\\\"merged\\\",doc:h}}catch(t){return!v(this.s,e)||null!==n&&b(n.signal)?{status:\\\"superseded\\\"}:(this.s[4](\\\"merge exception\\\",t),v(this.s,e)?{status:\\\"unavailable\\\"}:{status:\\\"superseded\\\"})}finally{null!==n&&v(this.s,e)&&this.s[5]===n&&(this.s[5]=null)}}destroy(){this.s[6]+=1;let t=this.s[5];this.s[5]=null,this.s[7]+=1;try{t?.abort()}finally{this.s[7]-=1}}},Si=new Set([\\\"http:\\\",\\\"https:\\\",\\\"mailto:\\\",\\\"tel:\\\"]),$i=/^\\\\s*(?:javascript|data|vbscript|file|blob|about)\\\\s*:/i,Ai=/^(?:\\\\.{1,2}\\\\/|[a-zA-Z0-9_-]+\\\\/?)/,ki=new Set([\\\"style\\\",\\\"srcdoc\\\",\\\"formaction\\\",\\\"form\\\",\\\"id\\\",\\\"name\\\",\\\"is\\\",\\\"srcset\\\",\\\"imagesrcset\\\"]),Ti=new Set([\\\"href\\\",\\\"src\\\",\\\"poster\\\",\\\"cite\\\",\\\"action\\\",\\\"xlink:href\\\",\\\"data\\\"]),Ni=new WeakSet,xi=class{constructor(t,e){he(this,Mi);oe(this,\\\"s\\\");let i=e.scheduleFrame??(\\\"function\\\"==typeof requestAnimationFrame?requestAnimationFrame.bind(globalThis):t=>setTimeout(()=>{t(performance.now())},0)),n=e.cancelFrame??(\\\"function\\\"==typeof cancelAnimationFrame?cancelAnimationFrame.bind(globalThis):t=>{clearTimeout(t)});this.s=[t,e.debounceMs??50,e.isVisible,e.visibilityGateThreshold??50,e.disableVisibilityGate??!1,e.getCacheSize,e.onFlush,i,n,new Map,new Map,new Set,null,0,null,0,null,!1]}schedule(t){if(void 0!==t.identity&&(this.s[17]||!A(t.identity,this.s[16])))return;let e=this.s[9],i=e.get(t.target.element);i?(i.value=t.value,i.allFields=t.allFields,i.identity=t.identity,i.data=t.data):e.set(t.target.element,{...t,identity:t.identity,data:t.data}),ce(this,Mi,Ci).call(this)}acceptRevision(t){let e=this.s[16];A(t,e)||null!==e&&function(t,e){return t.generation!==e.generation?t.generation-e.generation:t.revision-e.revision}(t,e)<0||(ce(this,Mi,_i).call(this),ce(this,Mi,Pi).call(this),this.s[16]=t,this.s[17]=!1)}cancelRevision(t){A(t,this.s[16])&&(ce(this,Mi,_i).call(this),ce(this,Mi,Pi).call(this),this.s[17]=!0)}flushNow(){return ce(this,Mi,_i).call(this),ce(this,Mi,Li).call(this)}notifyVisible(t){let e=this.s[10],i=e.get(t);if(!i||(e.delete(t),!ce(this,Mi,ji).call(this,i)))return;let n=performance.now(),r=ce(this,Mi,Ei).call(this,i)?1:0;this.s[6]?.(ce(this,Mi,Ri).call(this,i,r,0,performance.now()-n,1===r?[i.target.fieldName]:[]))}retarget(t){ce(this,Mi,Ii).call(this,this.s[9],t),ce(this,Mi,Ii).call(this,this.s[10],t);for(let e of this.s[11])ce(this,Mi,Ii).call(this,e,t)}forget(t){this.s[9].delete(t),this.s[10].delete(t);for(let e of this.s[11])e.delete(t)}destroy(){ce(this,Mi,_i).call(this),ce(this,Mi,Pi).call(this),this.s[16]=null,this.s[17]=!1}get pendingCount(){return this.s[9].size}get replayCount(){return this.s[10].size}get gateThreshold(){return this.s[3]}get gateActive(){return!this.s[4]&&this.s[5]()>this.s[3]}},Mi=new WeakSet,Ci=function(){let t=this.s[13]+=1,e=this.s[12];if(this.s[12]=null,null!==e&&clearTimeout(e),this.s[13]!==t)return;let i=setTimeout(()=>{this.s[13]===t&&(this.s[12]=null,ce(this,Mi,Oi).call(this))},this.s[1]);this.s[13]===t&&(this.s[12]=i)},Oi=function(){let t=this.s[15]+=1,e=this.s[14];if(this.s[14]=null,null!==e&&this.s[8](e),this.s[15]!==t)return;let i=!1,n=this.s[7](()=>{this.s[15]===t&&(i=!0,this.s[14]=null,ce(this,Mi,Li).call(this))});!i&&this.s[15]===t&&(this.s[14]=n)},Li=function(){let t=performance.now(),e=!this.s[4]&&this.s[5]()>this.s[3],i=this.s[9];this.s[9]=new Map;let n,r=0,l=[],s=0;this.s[11].add(i);try{for(let t of i.values()){if(!ce(this,Mi,ji).call(this,t))continue;let i=!e||this.s[2](t.target.element);if(ce(this,Mi,ji).call(this,t)){if(n??(n=t),!i){this.s[10].set(t.target.element,t),s+=1;continue}this.s[10].delete(t.target.element),ce(this,Mi,Ei).call(this,t)&&(r+=1,l.push(t.target.fieldName))}}}finally{this.s[11].delete(i)}let o=ce(this,Mi,Ri).call(this,n,r,s,performance.now()-t,l);return this.s[6]?.(o),o},ji=function(t){return void 0===t.identity||!this.s[17]&&A(t.identity,this.s[16])},Ei=function(t){let e=this.s[0];return!1!==e(t)||!function(t){return Ni.has(t)}(e)},Ii=function(t,e){let i=t.get(e.element);if(void 0!==i){if(i.target.fieldName!==e.fieldName||i.target.locale!==e.locale){t.delete(e.element);return}i.target=e}},Pi=function(){this.s[9].clear(),this.s[10].clear();for(let t of this.s[11])t.clear()},Ri=function(t,e,i,n,r){return{applied:e,appliedFields:r,deferred:i,durationMs:n,...void 0!==t?.identity?{identity:t.identity}:{},...void 0!==t?.data?{data:t.data}:{}}},_i=function(){let t=this.s[12],e=this.s[14];this.s[13]+=1,this.s[15]+=1,this.s[12]=null,this.s[14]=null,null!==t&&clearTimeout(t),null!==e&&this.s[8](e)},Wi=\\\"1.8.0\\\",Fi=new Set([\\\"__proto__\\\",\\\"prototype\\\",\\\"constructor\\\"]),Di=\\\"payload-live-preview-a11y\\\",Ui=new WeakMap,zi=class{constructor(t,e){oe(this,\\\"s\\\");let i=e??(typeof document>\\\"u\\\"?null:document),n=i?.documentElement.getAttribute(\\\"lang\\\")??\\\"\\\";this.s=[x(t??(n.length>0?n:N())),i,null]}mount(){let t=this.s[1];if(null==t?.body)return null;let e=this.s[2];null===e&&(e=function(t){let e=Ui.get(t);return e??(e=[null,!1,null,0,null]),Ui.set(t,e),e[3]+=1,e}(t),this.s[2]=e);let i=e[0];if(i?.isConnected&&i.ownerDocument===t)return i;if(null!==i){let t=e[1];M(e),t&&i.remove()}let n=t.getElementById(Di);return e[1]=null===n,n||(n=t.createElement(\\\"div\\\"),n.id=Di,n.setAttribute(\\\"role\\\",\\\"status\\\"),n.setAttribute(\\\"aria-live\\\",\\\"polite\\\"),n.setAttribute(\\\"aria-atomic\\\",\\\"true\\\"),n.setAttribute(\\\"style\\\",\\\"position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap;border:0\\\"),t.body.appendChild(n)),e[0]=n,n}announceConnected(){this.say(this.s[0]?\\\"Vorschau verbunden\\\":\\\"Live preview connected\\\")}announceDisconnected(){this.say(this.s[0]?\\\"Vorschau getrennt\\\":\\\"Live preview disconnected\\\")}announceUpdate(t){t<=0||this.say(this.s[0]?`${String(t)} ${1===t?\\\"\\\\xc4nderung\\\":\\\"\\\\xc4nderungen\\\"} angewendet`:`${String(t)} ${1===t?\\\"change\\\":\\\"changes\\\"} applied`)}detach(){let t=this.s[2],e=this.s[1];if(null===t||null===e||(this.s[2]=null,t[3]-=1,t[3]>0))return;let i=t[0];null!==i&&M(t),t[1]&&i?.remove(),t[0]=null,Ui.delete(e)}say(t){let e=this.mount(),i=this.s[2];if(null===e||null===i)return;let n=i[2];n?.parentNode!==e?(n?.remove(),n=e.ownerDocument.createTextNode(e.hasChildNodes()?` ${t}`:t),i[2]=n,e.appendChild(n)):n.data=null===n.previousSibling?t:` ${t}`,null!==i[4]&&clearTimeout(i[4]);let r=setTimeout(()=>{i[4]===r&&i[0]===e&&M(i)},1500);i[4]=r}},Vi=new Set([\\\"tabs\\\",\\\"row\\\",\\\"collapsible\\\"]),Gi={text:\\\"text\\\",textarea:\\\"textarea\\\",richText:\\\"richText\\\",email:\\\"email\\\",number:\\\"number\\\",checkbox:\\\"checkbox\\\",date:\\\"date\\\",select:\\\"select\\\",radio:\\\"radio\\\",array:\\\"array\\\",blocks:\\\"blocks\\\",group:\\\"text\\\",tabs:\\\"text\\\",row:\\\"text\\\",collapsible:\\\"text\\\",relationship:\\\"relationship\\\",upload:\\\"upload\\\",point:\\\"text\\\",json:\\\"text\\\",code:\\\"text\\\",ui:\\\"text\\\"},Bi=[0,500,1e3,2e3],Hi=class{constructor(t){he(this,qi);oe(this,\\\"d\\\");oe(this,\\\"l\\\");let n=t.emitter,r=t.renderers,l=t.resolveRenderer??(t=>r[t]),s=t.transformValue,o=t.root??(typeof document<\\\"u\\\"?document:null),a=t.readyTargets,u=t.sendReady??R,h=t.onHeartbeatTimeout,d=void 0===t.log?i:e(t.log),f=void 0===t.warn?pe:e(t.warn),p=function(t){if(!1===t.enableA11y)return null;let e=void 0===t.root?void 0:9===t.root.nodeType?t.root:t.root.ownerDocument;return new zi(t.a11yLocale,e)}(t),g=void 0!==t.dataMerge?new wi({serverURL:t.dataMerge.serverURL,...void 0!==t.dataMerge.apiRoute?{apiRoute:t.dataMerge.apiRoute}:{},...void 0!==t.dataMerge.depth?{depth:t.dataMerge.depth}:{},...void 0!==t.dataMerge.fetchFn?{fetchFn:t.dataMerge.fetchFn}:{},log:(...t)=>{d(...t)}}):null,m=new ze,y=new Ke({onStructuralChange:()=>{ce(this,qi,Qi).call(this)},onVisibilityChange:(t,e)=>{e&&this.d[3].notifyVisible(t)}},{...void 0!==t.intersectionRootMargin?{intersectionRootMargin:t.intersectionRootMargin}:{}}),v=new xi($(t=>ce(this,qi,fn).call(this,t)),{...void 0!==t.debounceMs?{debounceMs:t.debounceMs}:{},...void 0!==t.disableVisibilityGate?{disableVisibilityGate:t.disableVisibilityGate}:{},...void 0!==t.visibilityGateThreshold?{visibilityGateThreshold:t.visibilityGateThreshold}:{},isVisible:t=>y.isVisible(t),getCacheSize:()=>m.elementCount,onFlush:t=>{ce(this,qi,pn).call(this,t)}}),b=new ri(t.originMatcher,{onUpdate:(t,e,i)=>{ce(this,qi,en).call(this,t,e,i)},onDocumentEvent:()=>{n.emit(\\\"documentSave\\\",{timestamp:Date.now()})},onInvalid:(t,e)=>{if(\\\"token\\\"===t){let t=new Error(`Preview token rejected (origin: ${e})`);n.emit(\\\"error\\\",{error:t,context:\\\"token\\\",code:\\\"LP0502\\\"})}d(\\\"LP0501 message rejected:\\\",t,e)},...void 0!==t.validateToken?{validateToken:t.validateToken}:{}}),w=new bi(()=>{}),S=new vi({...void 0!==t.heartbeatMs?{timeoutMs:t.heartbeatMs}:{},onTimeout:()=>{ce(this,qi,gn).call(this)}});this.d=[n,m,y,v,b,w,S,r,l,s,o,a,u,h,d,f,[],p,g,!0===t.scopeBindingsByOwner,t.lockedOrigin??(()=>{})],this.l=[void 0,void 0,void 0,c(void 0),!1,null,0,null,new Set,!1,!1,0,null,new Set]}start(){if(this.l[4])return!1;this.l[4]=!0;let t=this.d[10];if(P(t)&&\\\"loading\\\"===t.readyState){let e=()=>{if(this.l[4]){this.l[5]=null;try{ce(this,qi,Ji).call(this)}catch(t){ce(this,qi,Yi).call(this),ce(this,qi,yn).call(this,t,\\\"startup\\\",\\\"LP0605\\\")}}};this.l[5]=e;try{t.addEventListener(\\\"DOMContentLoaded\\\",e,{once:!0})}catch(t){throw ce(this,qi,Yi).call(this),t}return!0}try{return ce(this,qi,Ji).call(this),!0}catch(t){throw ce(this,qi,Yi).call(this),t}}suspend(){return!!this.l[4]&&(ce(this,qi,Xi).call(this)&&this.d[0].emit(\\\"disconnect\\\",{reason:\\\"unload\\\",timestamp:Date.now()}),!0)}destroy(){this.l[4]&&(ce(this,qi,Xi).call(this)&&this.d[0].emit(\\\"disconnect\\\",{reason:\\\"destroy\\\",timestamp:Date.now()}),this.d[17]?.detach(),this.d[0].emit(\\\"destroy\\\",{timestamp:Date.now()}))}refreshCache(){this.l[4]&&ce(this,qi,Qi).call(this)}get status(){return this.d[5].status}get cache(){return this.d[1]}get updateCount(){return this.l[6]}get protocol(){return this.l[3]}inspect(){let t=this.d[1],e=this.d[3],i=this.l[3],n=this.l[7],r=this.l[12],l=[],s=new Set;for(let[e,i]of t.entries()){l.push(e);for(let t of i)void 0!==t.owner&&s.add(t.owner)}return{version:Wi,started:this.l[4],status:this.d[5].status,origins:{trusted:[...this.d[11]],locked:this.d[20]()},protocol:{ours:i.ours,theirs:i.theirs,negotiated:i.negotiated,capabilities:[...i.capabilities].sort()},revisions:{accepted:this.l[6],superseded:this.l[11],active:null===n?void 0:n.identity.revision},bindings:{elements:t.elementCount,fields:t.fieldCount,fieldNames:l.sort(),absentFields:[...this.l[13]].sort(),orphanFields:[...this.l[8]].sort(),ownerScoped:this.d[19],owners:[...s].sort()},scheduler:{pending:e.pendingCount,deferred:e.replayCount,visibilityGateThreshold:e.gateThreshold,visibilityGateActive:e.gateActive,lastFlush:null===r?void 0:{applied:r.applied,appliedFields:r.appliedFields,deferred:r.deferred,durationMs:r.durationMs}},renderers:Object.keys(this.d[7]).sort()}}},qi=new WeakSet,Ji=function(){if(!this.l[4])return;let t=P(this.d[10])?function(t){return t.body}(this.d[10]):this.d[10];if(null===t)throw new Error(\\\"LivePreviewRuntime: document.body unavailable\\\");if(this.d[2].start(t),ce(this,qi,Ki).call(this),ce(this,qi,dn).call(this)&&(this.d[4].attach(),this.d[0].emitWhile(\\\"init\\\",{timestamp:Date.now()},()=>this.l[4]),ce(this,qi,dn).call(this)))for(let t of Bi){if(!ce(this,qi,dn).call(this))return;if(0===t){if(this.d[12](this.d[11]),!ce(this,qi,dn).call(this))return}else{let e=setTimeout(()=>{this.l[4]&&ce(this,qi,mn).call(this)},t);this.d[16].push(e)}}},Xi=function(){this.l[7]=null,this.l[4]=!1;let t=this.l[5];this.l[5]=null,null!==t&&P(this.d[10])&&ce(this,qi,Zi).call(this,()=>{this.d[10].removeEventListener(\\\"DOMContentLoaded\\\",t)});for(let t of this.d[16])ce(this,qi,Zi).call(this,()=>{clearTimeout(t)});return this.d[16].length=0,ce(this,qi,Zi).call(this,()=>{this.d[6].stop()}),ce(this,qi,Zi).call(this,()=>{this.d[4].detach()}),ce(this,qi,Zi).call(this,()=>{this.d[2].stop()}),ce(this,qi,Zi).call(this,()=>{this.d[3].destroy()}),ce(this,qi,Zi).call(this,()=>{this.d[18]?.destroy()}),this.d[1].clear(),this.d[5].markDisconnected()},Yi=function(){ce(this,qi,Xi).call(this),ce(this,qi,Zi).call(this,()=>{this.d[17]?.detach()})},Zi=function(t){try{t()}catch(t){this.d[14](\\\"cleanup failed:\\\",t)}},Ki=function(){if(!this.l[4])return;let t=this.d[1].buildFromRoot(this.d[10]);if(this.d[14](\\\"cache\\\",t),ce(this,qi,dn).call(this)&&(this.d[0].emitWhile(\\\"cacheRefresh\\\",t,()=>this.l[4]),ce(this,qi,dn).call(this)))for(let t of this.d[1].values()){if(!ce(this,qi,dn).call(this))return;this.d[2].observeElement(t.element)}},Qi=function(){if(!this.l[4])return;let t=new Map;for(let e of this.d[1].values())t.set(e.element,e),this.d[2].unobserveElement(e.element);if(ce(this,qi,Ki).call(this),ce(this,qi,dn).call(this)){for(let e of this.d[1].values())t.get(e.element)?.fieldName===e.fieldName?this.d[3].retarget(e):this.d[3].forget(e.element),t.delete(e.element);for(let e of t.values())this.d[3].forget(e.element)}},tn=function(t){let e=this.l[3];if(e.theirs===t)return;let i=c(t);this.l[3]=i,i.negotiated!==e.negotiated&&this.d[14](\\\"protocol\\\",\\\"ours=4\\\",`theirs=${t}`,`negotiated=${i.negotiated}`)},en=function(t,e,i){if(this.d[6].kick(),void 0===t.data){void 0!==t.protocolVersion&&ce(this,qi,tn).call(this,t.protocolVersion);return}if(void 0===i)return;\\\"string\\\"==typeof t.locale&&(this.l[0]=t.locale),Array.isArray(t.fieldSchemaJSON)&&(this.l[1]=t.fieldSchemaJSON,this.l[2]=C(t.fieldSchemaJSON));let n={identity:i,message:t,locale:this.l[0],schema:this.l[1],schemaIndex:this.l[2],cancelled:!1};null!==this.l[7]&&(this.l[11]+=1),this.l[7]=n,this.d[3].acceptRevision(i),this.l[6]+=1,(void 0===t.protocolVersion||(ce(this,qi,tn).call(this,t.protocolVersion),this.l[4]&&this.l[7]===n))&&(this.d[5].markConnected()&&(this.d[17]?.announceConnected(),this.d[0].emit(\\\"connect\\\",{origin:e,timestamp:Date.now()}),!this.l[4]||this.l[7]!==n||(this.d[14](\\\"connection\\\",\\\"disconnected\\\",\\\"\\\\u2192\\\",\\\"connected\\\"),!this.l[4]||this.l[7]!==n))||ce(this,qi,nn).call(this,n))},nn=async function(t){let e=await ce(this,qi,rn).call(this,t);if(null===e||!this.l[4]||this.l[7]!==t)return;let{message:i}=t,n={fields:e,...void 0!==t.schema?{schema:t.schema}:{},...\\\"string\\\"==typeof i.globalSlug?{globalSlug:i.globalSlug}:{},...\\\"string\\\"==typeof i.collectionSlug?{collectionSlug:i.collectionSlug}:{},...void 0!==t.locale?{locale:t.locale}:{}};this.d[0].listenerCount(\\\"beforeUpdate\\\")>0&&(!await this.d[0].emitWhile(\\\"beforeUpdate\\\",{data:n,revision:t.identity.revision,cancel:()=>{t.cancelled=!0,this.d[3].cancelRevision(t.identity)}},()=>!t.cancelled&&this.l[4]&&this.l[7]===t)||t.cancelled||!this.l[4]||this.l[7]!==t)||this.l[4]&&this.l[7]===t&&ce(this,qi,ln).call(this,t,n)},rn=async function(t){let{message:e}=t,i=e.data??{};if(null===this.d[18])return i;let n=await this.d[18].merge({collectionSlug:e.collectionSlug,globalSlug:e.globalSlug,data:i,locale:t.locale});return this.l[4]&&this.l[7]===t?\\\"merged\\\"===n.status?n.doc:\\\"superseded\\\"===n.status?null:i:null},ln=function(t,e){if(!this.l[4]||this.l[7]!==t)return;let i=()=>this.l[4]&&this.l[7]===t,n=ce(this,qi,sn).call(this,t,e.fields);for(let[r,l]of this.d[1].entries()){if(!this.l[4]||this.l[7]!==t)return;for(let s of l){if(!1!==n&&!o(s.owner,n))continue;let l=k(e.fields,r,s.locale??t.locale,void 0!==s.locale);if(void 0===l){this.l[13].add(r);continue}if(!this.l[4]||this.l[7]!==t)return;let a=ce(this,qi,hn).call(this,s,l,e.fields,i);if(!this.l[4]||this.l[7]!==t)return;let u={target:s,value:a,allFields:e.fields,identity:t.identity,data:e};if(!this.l[4]||this.l[7]!==t)return;this.d[3].schedule(u)}}ce(this,qi,un).call(this,e.fields,t.locale,n)},sn=function(t,e){if(!this.d[19])return!1;let{message:i}=t,n=function(t){if(s(t.globalSlug))return[r(t.globalSlug)];if(!s(t.collectionSlug))return null;let e=l(t.collectionSlug);return s(t.documentId)?[e,l(t.collectionSlug,t.documentId)]:[e]}({globalSlug:\\\"string\\\"==typeof i.globalSlug?i.globalSlug:void 0,collectionSlug:\\\"string\\\"==typeof i.collectionSlug?i.collectionSlug:void 0,documentId:a(e)});return null===n&&!this.l[9]&&(this.l[9]=!0,this.d[15](\\\"[live-preview] LP0202: scopeBindingsByOwner: update names no document; nothing applied\\\")),n},on=function(t){for(let e of this.d[1].values())if(o(e.owner,t))return!0;return!1},an=function(t,e){let i=this.d[1].get(t);return void 0!==i&&(!1===e||i.some(t=>o(t.owner,e)))},un=function(t,e,i){if(0===this.d[1].fieldCount||!1!==i&&!ce(this,qi,on).call(this,i))return;let n;for(let[r,l]of Object.entries(t)){if(this.l[8].has(r)||bn.has(r)||!W(l))continue;let t=F(r,e);if(!(ce(this,qi,an).call(this,r,i)||t!==r&&ce(this,qi,an).call(this,t,i))){if(void 0===n){n=new Set;for(let[t,e]of this.d[1].entries())for(let r of e)!1!==i&&!o(r.owner,i)||void 0!==r.locale&&n.add(`${t}_${r.locale}`)}n.has(r)||(this.l[8].add(r),this.d[15](`[live-preview] LP0201: update arrived for field \\\"${r}\\\" but no <\\\\u2026 data-payload-field=\\\"${t}\\\"> element exists on this page. Render the binding anchor unconditionally in your template so live edits to an initially-empty field have somewhere to land.`))}}},hn=function(e,i,n,r){if(void 0===this.d[9])return i;try{let l=this.d[9](e.fieldName,i,{element:e.element,allFields:n},r),s=t(l);if(!r())return i;if(s)throw new TypeError(`Transform for \\\"${e.fieldName}\\\" returned a Promise/thenable; transforms must be synchronous`);return l}catch(t){if(!r())return i;let e=t instanceof Error?t:new Error(String(t));return this.d[0].emit(\\\"error\\\",{error:e,context:\\\"transform\\\",code:\\\"LP0602\\\"}),i}},dn=function(){return this.l[4]},cn=function(t){0!==t.deferred&&(this.l[10]||(this.l[10]=!0,this.d[15](`[live-preview] LP0301: visibility gate held ${String(t.deferred)} offscreen update(s) until scrolled into view; see visibilityGateThreshold.`)))},fn=function(t){let e=this.l[7];if(null===e||void 0===t.identity||!_(e.identity,t.identity)||!this.l[4]||this.l[7]!==e)return!1;let i=void 0!==e.schemaIndex?function(t,e){if(t.has(e))return t.get(e);let i=e.replace(/\\\\.\\\\d+(?=\\\\.|$)/g,\\\".*\\\");return t.has(i)?t.get(i):void 0}(e.schemaIndex,t.target.fieldName):void 0,n=t.value,r=function(t,e){if(t.explicitFieldType)return t.fieldType;if(void 0!==e){let t=function(t){if(Object.prototype.hasOwnProperty.call(Gi,t))return Gi[t]}(e);if(void 0!==t)return t}return t.fieldType}(t.target,i?.type);\\\"text\\\"===r&&!0!==t.target.explicitFieldType&&function(t){if(\\\"object\\\"!=typeof t||null===t||!(\\\"root\\\"in t))return!1;let e=t.root;return\\\"object\\\"==typeof e&&null!==e&&Array.isArray(e.children)}(n)&&(r=\\\"richText\\\");let l;try{l=this.d[8](r)}catch(t){if(!this.l[4]||this.l[7]!==e)return!1;let i=t instanceof Error?t:new Error(String(t));return this.d[0].emitWhile(\\\"error\\\",{error:i,context:\\\"renderer\\\",code:\\\"LP0603\\\"},()=>this.l[4]&&this.l[7]===e),!1}if(!this.l[4]||this.l[7]!==e)return!1;let s=this.d[0].listenerCount(\\\"elementUpdate\\\")>0,o=s?function(t){return\\\"INPUT\\\"===t.tagName||\\\"TEXTAREA\\\"===t.tagName?t.value:\\\"IMG\\\"===t.tagName?t.src:t.textContent}(t.target.element):void 0;if(!this.l[4]||this.l[7]!==e)return!1;let a={allFields:t.allFields,locale:t.target.locale??e.locale,schema:i};try{if(void 0!==t.target.targetAttribute){if(\\\"blocked\\\"===function(t,e,i){let n=e.toLowerCase().trim();if(0===n.length||n.startsWith(\\\"on\\\")||ki.has(n))return\\\"blocked\\\";if(null==i)return t.removeAttribute(n),\\\"applied\\\";if(\\\"string\\\"!=typeof i&&\\\"number\\\"!=typeof i&&\\\"boolean\\\"!=typeof i)return\\\"blocked\\\";let r=String(i);return Ti.has(n)&&!w(r)?\\\"blocked\\\":(t.setAttribute(n,r),\\\"applied\\\")}(t.target.element,t.target.targetAttribute,n))return this.d[15](`[live-preview] LP0401: refused to write field \\\"${t.target.fieldName}\\\" into attribute \\\"${t.target.targetAttribute}\\\" (unsafe attribute or value)`),!1}else{if(!l)return this.d[14](\\\"no renderer for\\\",r),!1;if(!1===function(t,e,i,n){return t.render(e,i,n)}(l,t.target,n,a)&&function(t){return Ni.has(t.render)}(l))return!1}}catch(t){if(!this.l[4]||this.l[7]!==e)return!1;let i=t instanceof Error?t:new Error(String(t));return this.d[0].emitWhile(\\\"error\\\",{error:i,context:\\\"renderer\\\",code:\\\"LP0603\\\"},()=>this.l[4]&&this.l[7]===e),!1}return!(!this.l[4]||this.l[7]!==e)&&(s&&this.d[0].emitWhile(\\\"elementUpdate\\\",{element:t.target.element,fieldName:t.target.fieldName,previousValue:o,nextValue:n,revision:e.identity.revision},()=>this.l[4]&&this.l[7]===e),this.l[4]&&this.l[7]===e)},pn=function(t){this.l[12]=t,ce(this,qi,cn).call(this,t);let{identity:e,data:i}=t;if(0===t.applied||void 0===e||void 0===i)return;let n=this.l[7];if(null===n||!this.l[4]||this.l[7]!==n||!_(n.identity,e))return;let r=()=>this.l[4]&&this.l[7]===n&&_(n.identity,e);this.d[17]?.announceUpdate(t.applied),r()&&0!==this.d[0].listenerCount(\\\"afterUpdate\\\")&&this.d[0].emitWhile(\\\"afterUpdate\\\",{data:i,updatedCount:t.applied,durationMs:t.durationMs,revision:e.revision},r)},gn=function(){if(!ce(this,qi,dn).call(this))return;this.d[4].advanceGeneration();let t=this.l[7];this.l[7]=null,null!==t&&this.d[3].cancelRevision(t.identity),this.d[18]?.destroy();let e=this.d[5].markDisconnected();try{this.d[13]?.()}catch(t){this.d[14](\\\"heartbeat:\\\",t)}ce(this,qi,dn).call(this)&&(e&&ce(this,qi,vn).call(this)&&(this.d[17]?.announceDisconnected(),this.d[0].emitWhile(\\\"disconnect\\\",{reason:\\\"timeout\\\",timestamp:Date.now()},()=>ce(this,qi,vn).call(this)),!ce(this,qi,dn).call(this)||ce(this,qi,vn).call(this)&&(this.d[14](\\\"connection\\\",\\\"connected\\\",\\\"\\\\u2192\\\",\\\"disconnected\\\"),!ce(this,qi,dn).call(this)))||ce(this,qi,dn).call(this)&&ce(this,qi,mn).call(this))},mn=function(){try{this.d[12](this.d[11])}catch(t){ce(this,qi,yn).call(this,t,\\\"ready\\\",\\\"LP0606\\\")}},yn=function(t,e,i){let n=t instanceof Error?t:new Error(String(t));this.d[0].emit(\\\"error\\\",{error:n,context:e,code:i})},vn=function(){return this.l[4]&&\\\"disconnected\\\"===this.d[5].status&&null===this.l[7]},bn=new Set([\\\"id\\\",\\\"_id\\\",\\\"createdAt\\\",\\\"updatedAt\\\",\\\"createdBy\\\",\\\"updatedBy\\\",\\\"_status\\\",\\\"globalType\\\",\\\"collection\\\",\\\"locale\\\",\\\"localized\\\"]),wn=/^https?:\\\\/\\\\/(localhost|127\\\\.0\\\\.0\\\\.1)(?::\\\\d+)?$/i,Sn=/^https?:\\\\/\\\\/[^/?#\\\\s]+$/i,$n=[\\\"PAYLOAD_ADMIN_ORIGIN\\\",\\\"PUBLIC_PAYLOAD_ADMIN_ORIGIN\\\",\\\"NEXT_PUBLIC_PAYLOAD_ADMIN_ORIGIN\\\"],An=class{constructor(t={}){he(this,kn);let e=new Set;for(let i of t.additionalOrigins??[]){let t=z(i);void 0!==t&&e.add(t)}for(let t of $n){let i=U(t);if(void 0!==i)for(let t of i.split(\\\",\\\")){let i=z(t);void 0!==i&&e.add(i)}}let i;if(t.enableReferrerDetection??1){let e=t.referrer??(typeof document<\\\"u\\\"?document.referrer:\\\"\\\");if(e.length>0)try{let t=new URL(e).origin;t&&\\\"null\\\"!==t&&(i=t)}catch{}}let n=(t.enableLocalhostMatching??!0)&&(t.forceDevMode??function(){let t=function(){if(!(typeof process>\\\"u\\\"))return\\\"production\\\"}();if(void 0!==t)return\\\"production\\\"!==t;0;if(typeof window<\\\"u\\\"){let t=window.location.hostname;if(\\\"localhost\\\"===t||\\\"127.0.0.1\\\"===t)return!0}return!1}());de(this,kn,[e,i,n,void 0!==i,void 0])}matches(t){return 0!==t.length&&\\\"null\\\"!==t&&(void 0!==ue(this,kn)[4]?t===ue(this,kn)[4]:!!(ue(this,kn)[0].has(t)||0===ue(this,kn)[0].size&&void 0!==ue(this,kn)[1]&&t===ue(this,kn)[1]||ue(this,kn)[2]&&wn.test(t)))}lockOrigin(t){return!!this.matches(t)&&(ue(this,kn)[4]=t,!0)}unlockOrigin(){let t=ue(this,kn)[4];return ue(this,kn)[4]=void 0,t}get lockedOrigin(){return ue(this,kn)[4]}enumerate(){if(void 0!==ue(this,kn)[4])return[ue(this,kn)[4]];let t=new Set(ue(this,kn)[0]);if(0===ue(this,kn)[0].size&&void 0!==ue(this,kn)[1]&&t.add(ue(this,kn)[1]),ue(this,kn)[2])for(let e of Tn)t.add(`http://localhost:${String(e)}`),t.add(`http://127.0.0.1:${String(e)}`);return[...t]}get referrerWasAvailable(){return ue(this,kn)[3]}get isProductionUnconfigured(){return!(!D()||ue(this,kn)[0].size>0||ue(this,kn)[2]||void 0!==ue(this,kn)[1])}get isReferrerOnlyTrust(){return!(ue(this,kn)[0].size>0||ue(this,kn)[2])&&void 0!==ue(this,kn)[1]}},kn=new WeakMap,Tn=[3e3,3001,3333,4e3,4321,5e3,5173,5174,8e3,8080,8888,9e3],Nn=new Set([\\\"p\\\",\\\"br\\\",\\\"strong\\\",\\\"b\\\",\\\"em\\\",\\\"i\\\",\\\"u\\\",\\\"s\\\",\\\"strike\\\",\\\"mark\\\",\\\"small\\\",\\\"h1\\\",\\\"h2\\\",\\\"h3\\\",\\\"h4\\\",\\\"h5\\\",\\\"h6\\\",\\\"ul\\\",\\\"ol\\\",\\\"li\\\",\\\"dl\\\",\\\"dt\\\",\\\"dd\\\",\\\"blockquote\\\",\\\"code\\\",\\\"pre\\\",\\\"kbd\\\",\\\"samp\\\",\\\"var\\\",\\\"a\\\",\\\"span\\\",\\\"div\\\",\\\"section\\\",\\\"article\\\",\\\"aside\\\",\\\"header\\\",\\\"footer\\\",\\\"nav\\\",\\\"figure\\\",\\\"figcaption\\\",\\\"img\\\",\\\"picture\\\",\\\"source\\\",\\\"audio\\\",\\\"video\\\",\\\"sub\\\",\\\"sup\\\",\\\"hr\\\",\\\"time\\\",\\\"abbr\\\",\\\"cite\\\",\\\"q\\\",\\\"table\\\",\\\"thead\\\",\\\"tbody\\\",\\\"tfoot\\\",\\\"tr\\\",\\\"th\\\",\\\"td\\\",\\\"caption\\\",\\\"colgroup\\\",\\\"col\\\"]),xn=new Set([\\\"script\\\",\\\"style\\\",\\\"iframe\\\",\\\"object\\\",\\\"embed\\\",\\\"link\\\",\\\"meta\\\",\\\"base\\\",\\\"form\\\",\\\"input\\\",\\\"button\\\",\\\"select\\\",\\\"textarea\\\",\\\"svg\\\",\\\"math\\\",\\\"template\\\",\\\"frame\\\",\\\"frameset\\\",\\\"noframes\\\",\\\"noscript\\\"]),Mn=new Set([\\\"id\\\",\\\"class\\\",\\\"lang\\\",\\\"dir\\\",\\\"title\\\",\\\"role\\\",\\\"tabindex\\\"]),Cn=\\\"aria-\\\",On=\\\"data-\\\",Ln={a:new Set([\\\"href\\\",\\\"target\\\",\\\"rel\\\",\\\"download\\\",\\\"hreflang\\\",\\\"type\\\"]),img:new Set([\\\"src\\\",\\\"srcset\\\",\\\"sizes\\\",\\\"alt\\\",\\\"width\\\",\\\"height\\\",\\\"loading\\\",\\\"decoding\\\"]),picture:new Set([]),source:new Set([\\\"src\\\",\\\"srcset\\\",\\\"sizes\\\",\\\"type\\\",\\\"media\\\"]),audio:new Set([\\\"src\\\",\\\"controls\\\",\\\"autoplay\\\",\\\"loop\\\",\\\"muted\\\",\\\"preload\\\"]),video:new Set([\\\"src\\\",\\\"poster\\\",\\\"controls\\\",\\\"autoplay\\\",\\\"loop\\\",\\\"muted\\\",\\\"preload\\\",\\\"width\\\",\\\"height\\\",\\\"playsinline\\\"]),time:new Set([\\\"datetime\\\"]),abbr:new Set([\\\"title\\\"]),q:new Set([\\\"cite\\\"]),blockquote:new Set([\\\"cite\\\"]),table:new Set([\\\"summary\\\"]),th:new Set([\\\"colspan\\\",\\\"rowspan\\\",\\\"scope\\\",\\\"headers\\\",\\\"abbr\\\"]),td:new Set([\\\"colspan\\\",\\\"rowspan\\\",\\\"headers\\\"]),col:new Set([\\\"span\\\"]),colgroup:new Set([\\\"span\\\"]),ol:new Set([\\\"start\\\",\\\"reversed\\\",\\\"type\\\"]),li:new Set([\\\"value\\\"]),code:new Set([\\\"class\\\"]),pre:new Set([\\\"class\\\"])},jn=new Set([\\\"href\\\",\\\"src\\\",\\\"cite\\\",\\\"poster\\\"]),En=1,In=8,Pn=class extends Error{constructor(){super(...arguments);oe(this,\\\"name\\\",\\\"SanitizerEnvironmentError\\\")}},Rn=(Object.freeze({allowedTags:Nn,removeCompletely:xn,globalAttributes:Mn,attributesByTag:Ln,urlAttributes:jn}),new Map),_n={1:\\\"left\\\",2:\\\"center\\\",3:\\\"right\\\",4:\\\"justify\\\"},Wn=new Set([\\\"left\\\",\\\"center\\\",\\\"right\\\",\\\"justify\\\",\\\"start\\\",\\\"end\\\"]),Fn=Object.freeze({\\\"&\\\":\\\"&amp;\\\",\\\"<\\\":\\\"&lt;\\\",\\\">\\\":\\\"&gt;\\\",'\\\"':\\\"&quot;\\\",\\\"'\\\":\\\"&#x27;\\\",\\\"/\\\":\\\"&#x2F;\\\",\\\"`\\\":\\\"&#x60;\\\",\\\"=\\\":\\\"&#x3D;\\\"}),Dn=/[&<>\\\"'/`=]/g,Un=Object.freeze({\\\"&\\\":\\\"&amp;\\\",\\\"<\\\":\\\"&lt;\\\",\\\">\\\":\\\"&gt;\\\",'\\\"':\\\"&quot;\\\",\\\"'\\\":\\\"&#x27;\\\"}),zn=/[&<>\\\"']/g,Vn=new Set([\\\"h1\\\",\\\"h2\\\",\\\"h3\\\",\\\"h4\\\",\\\"h5\\\",\\\"h6\\\"]),Gn=(t,e)=>{let i=\\\"string\\\"==typeof t.url?t.url:\\\"\\\",n=e.renderChildren(t.children??[]);if(0===i.length||!w(i))return n;let r=S(i)?' target=\\\"_blank\\\" rel=\\\"noopener noreferrer\\\"':function(t){let e=\\\"string\\\"==typeof t.target?t.target:\\\"\\\";if(0===e.length)return\\\"\\\";let i=Q(e);return\\\"_blank\\\"===e?' target=\\\"_blank\\\" rel=\\\"noopener noreferrer\\\"':` target=\\\"${i}\\\"`}(t),l=\\\"string\\\"==typeof t.title?` title=\\\"${Q(t.title)}\\\"`:\\\"\\\";return`<a href=\\\"${tt(i)}\\\"${r}${l}>${n}</a>`},Bn=new Map;J(\\\"text\\\",t=>{let e=Q(\\\"string\\\"==typeof t.text?t.text:\\\"\\\"),i=\\\"number\\\"==typeof t.format?t.format:0;return!!(16&i)&&(e=`<code>${e}</code>`),!!(1&i)&&(e=`<strong>${e}</strong>`),!!(2&i)&&(e=`<em>${e}</em>`),!!(8&i)&&(e=`<u>${e}</u>`),!!(4&i)&&(e=`<s>${e}</s>`),!!(32&i)&&(e=`<sub>${e}</sub>`),!!(64&i)&&(e=`<sup>${e}</sup>`),!!(128&i)&&(e=`<mark>${e}</mark>`),e});J(\\\"paragraph\\\",(t,e)=>{let i=e.renderChildren(t.children??[]);return`<p${Z(t)}${K(t)}>${i}</p>`});J(\\\"heading\\\",(t,e)=>{let i=\\\"string\\\"==typeof t.tag?t.tag.toLowerCase():\\\"h2\\\",n=Vn.has(i)?i:\\\"h2\\\",r=e.renderChildren(t.children??[]);return`<${n}${Z(t)}${K(t)}>${r}</${n}>`});J(\\\"list\\\",(t,e)=>{let i=\\\"string\\\"==typeof t.listType?t.listType:\\\"bullet\\\",n=\\\"number\\\"===i?\\\"ol\\\":\\\"ul\\\",r=\\\"number\\\"===i&&\\\"number\\\"==typeof t.start&&t.start>1?` start=\\\"${String(t.start)}\\\"`:\\\"\\\",l=\\\"check\\\"===i?' role=\\\"list\\\"':\\\"\\\",s=e.renderChildren(t.children??[]);return`<${n}${Z(t)}${K(t)}${r}${l}>${s}</${n}>`});J(\\\"listitem\\\",(t,e)=>{let i=e.renderChildren(t.children??[]);if(\\\"boolean\\\"==typeof t.checked)return`<li role=\\\"checkbox\\\" aria-checked=\\\"${t.checked?\\\"true\\\":\\\"false\\\"}\\\"${K(t)}>${i}</li>`;let n=\\\"number\\\"==typeof t.value?` value=\\\"${Q(String(t.value))}\\\"`:\\\"\\\";return`<li${Z(t)}${K(t)}${n}>${i}</li>`});J(\\\"link\\\",Gn);J(\\\"autolink\\\",Gn);J(\\\"quote\\\",(t,e)=>{let i=e.renderChildren(t.children??[]);return`<blockquote${Z(t)}${K(t)}>${i}</blockquote>`});J(\\\"code\\\",t=>{let e=nt(\\\"string\\\"==typeof t.language?t.language:\\\"\\\");return`<pre><code${\\\"\\\"===e?\\\"\\\":` class=\\\"language-${e}\\\"`}>${Q(it(t))}</code></pre>`});J(\\\"code-highlight\\\",t=>{let e=\\\"string\\\"==typeof t.text?t.text:\\\"\\\";return`<span${\\\"string\\\"==typeof t.highlightType?` class=\\\"token-${nt(t.highlightType)}\\\"`:\\\"\\\"}>${Q(e)}</span>`});J(\\\"linebreak\\\",()=>\\\"<br>\\\");J(\\\"horizontalrule\\\",()=>\\\"<hr>\\\");J(\\\"tab\\\",()=>\\\"\\\\t\\\");J(\\\"upload\\\",t=>{let e=function(t){let e=t.value;if(\\\"object\\\"==typeof e&&null!==e)return e}(t);if(void 0===e)return\\\"\\\";let i=e.url;if(\\\"string\\\"!=typeof i||!w(i))return\\\"\\\";let n=\\\"string\\\"==typeof e.mimeType?e.mimeType:\\\"\\\";return n.startsWith(\\\"video/\\\")?function(t,e){let i=\\\"number\\\"==typeof t.width?` width=\\\"${String(t.width)}\\\"`:\\\"\\\",n=\\\"number\\\"==typeof t.height?` height=\\\"${String(t.height)}\\\"`:\\\"\\\",r=\\\"string\\\"==typeof t.mimeType?` type=\\\"${tt(t.mimeType)}\\\"`:\\\"\\\";return`<video controls${i}${n}><source src=\\\"${tt(e)}\\\"${r}></video>`}(e,i):n.startsWith(\\\"audio/\\\")?function(t,e){let i=\\\"string\\\"==typeof t.mimeType?` type=\\\"${tt(t.mimeType)}\\\"`:\\\"\\\";return`<audio controls><source src=\\\"${tt(e)}\\\"${i}></audio>`}(e,i):\\\"\\\"===n||n.startsWith(\\\"image/\\\")?function(t,e){let i=\\\"string\\\"==typeof t.alt?Q(t.alt):\\\"\\\",n=\\\"number\\\"==typeof t.width?` width=\\\"${String(t.width)}\\\"`:\\\"\\\",r=\\\"number\\\"==typeof t.height?` height=\\\"${String(t.height)}\\\"`:\\\"\\\";return`<img src=\\\"${tt(e)}\\\" alt=\\\"${i}\\\"${n}${r} loading=\\\"lazy\\\" decoding=\\\"async\\\">`}(e,i):function(t,e){let i=\\\"string\\\"==typeof t.filename?Q(t.filename):Q(e);return`<a href=\\\"${tt(e)}\\\" target=\\\"_blank\\\" rel=\\\"noopener noreferrer\\\">${i}</a>`}(e,i)});J(\\\"relationship\\\",t=>{let e=\\\"string\\\"==typeof t.relationTo?t.relationTo:\\\"\\\",i=function(t){let e=t.value;if(\\\"object\\\"==typeof e&&null!==e)return e}(t),n=function(t,e){return void 0===t?\\\"\\\"===e?\\\"#\\\":`#${e}`:\\\"string\\\"==typeof t.title&&t.title.length>0?t.title:\\\"string\\\"==typeof t.name&&t.name.length>0?t.name:\\\"string\\\"==typeof t.slug&&t.slug.length>0?t.slug:void 0!==t.id?String(t.id):\\\"\\\"===e?\\\"#\\\":`#${e}`}(i,e),r=Q(n),l=\\\"\\\"===e?\\\"\\\":` data-relation-to=\\\"${Q(e)}\\\"`,s=i?.url;return\\\"string\\\"==typeof s&&w(s)?`<a href=\\\"${tt(s)}\\\"${l}>${r}</a>`:`<span${l}>${r}</span>`});J(\\\"block\\\",(t,e)=>{let i=function(t){let e=t.fields;return\\\"object\\\"!=typeof e||null===e?{}:e}(t),n=\\\"string\\\"==typeof i.blockType?i.blockType:\\\"\\\",r=lt(n);if(\\\"\\\"!==n){let t=rt(n)??rt(r);if(t)return t(i,{renderChildren:e.renderChildren})}let l=[];\\\"\\\"!==r&&l.push(`data-block-type=\\\"${Q(r)}\\\"`);for(let[t,e]of Object.entries(i)){if(\\\"blockType\\\"===t||\\\"id\\\"===t||null==e)continue;let i=\\\"string\\\"==typeof e||\\\"number\\\"==typeof e||\\\"boolean\\\"==typeof e?String(e):JSON.stringify(e);l.push(`data-block-${lt(t)}=\\\"${Q(i)}\\\"`)}return`<div${0===l.length?\\\"\\\":` ${l.join(\\\" \\\")}`}></div>`});Rt={renderChildren:at,resolveAlignment:X,resolveIndent:Y};_t=\\\"data-payload-text\\\";Wt={name:\\\"textarea\\\",render(t,e){let i=t.element,n=st(e)?ot(e):ct(e);\\\"INPUT\\\"!==i.tagName&&\\\"TEXTAREA\\\"!==i.tagName?i.innerHTML=et(n):i.value=n}};Ft={name:\\\"richText\\\",render:$((t,e)=>{if(st(e))t.element.innerHTML=function(t,e={}){if(!st(t))return\\\"\\\";let i=at(t.root.children);return!1===e.sanitize||void 0===G()?i:V(i)}(e);else{if(\\\"string\\\"!=typeof e)return!1;t.element.innerHTML=V(e)}})};Dt={name:\\\"html\\\",render(t,e){if(null==e){t.element.textContent=\\\"\\\";return}let i=\\\"string\\\"==typeof e?e:ct(e);t.element.innerHTML=V(i)}};Ut={name:\\\"url\\\",render(t,e,i){let n=t.element,r=ct(e);if(\\\"A\\\"===n.tagName){let l=n,s=t.hrefField,o=void 0===s||0===s.length?e:k(i.allFields,s,i.locale,void 0!==t.locale);\\\"string\\\"==typeof o&&w(o)&&(l.href=o),l.textContent=r;return}\\\"INPUT\\\"!==n.tagName&&\\\"TEXTAREA\\\"!==n.tagName?n.textContent=r:n.value=r}};zt={name:\\\"image\\\",render:$((t,e,i)=>{let n=t.element,r=ft(e),l=void 0!==t.locale,s=function(t,e,i,n,r,l){if(void 0!==i&&i.length>0){let t=k(n,i,r,l);if(\\\"string\\\"==typeof t&&w(t))return t;let e=ft(t);return void 0!==e?.url&&w(e.url)?e.url:void 0}return void 0!==t?.url&&w(t.url)?t.url:\\\"string\\\"==typeof e&&w(e)?e:void 0}(r,e,t.srcField,i.allFields,i.locale,l);if(void 0===s)return!1;if(\\\"IMG\\\"===n.tagName){let e=n;e.src=s;let o=function(t,e,i,n,r){if(void 0!==e&&e.length>0){let t=k(i,e,n,r);return\\\"string\\\"==typeof t?t:void 0}if(void 0!==t?.alt)return t.alt}(r,t.altField,i.allFields,i.locale,l);void 0!==o&&(e.alt=o);return}n.style.backgroundImage=`url('${function(t){return t.replace(/['\\\"()\\\\\\\\]/g,\\\"\\\\\\\\$&\\\")}(s)}')`})};Vt={name:\\\"upload\\\",render:$((t,e)=>{let i=t.element,n=function(t){if(\\\"object\\\"==typeof t&&null!==t)return t}(e);if(void 0===n)return!1;let r=n.url;if(\\\"string\\\"!=typeof r||!w(r))return!1;if(\\\"IMG\\\"===i.tagName){let t=i;t.src=r,void 0!==n.alt&&(t.alt=n.alt);return}if(\\\"A\\\"===i.tagName){let t=i;t.href=r,t.textContent=n.filename??r;return}let l=void 0!==n.filename?Q(n.filename):Q(r);i.innerHTML=`<a href=\\\"${tt(r)}\\\">${l}</a>`})};Gt={name:\\\"relationship\\\",render(t,e){let i=t.element,n=function(t){return null==t?[\\\"\\\"]:Array.isArray(t)?t.map(pt):[pt(t)]}(e).join(\\\", \\\");if(\\\"A\\\"===i.tagName&&!Array.isArray(e)){let t=i,r=e?.url;\\\"string\\\"==typeof r&&w(r)&&(t.href=r),t.textContent=n;return}i.textContent=n}};Bt={name:\\\"select\\\",render(t,e){let i=t.element,n=gt(e);if(\\\"SELECT\\\"!==i.tagName){if(\\\"INPUT\\\"===i.tagName&&\\\"radio\\\"===i.type){let t=i;t.checked=t.value===n;return}i.textContent=n}else i.value=n}};Ht={name:\\\"checkbox\\\",render(t,e){let i=t.element,n=!!e;\\\"INPUT\\\"!==i.tagName||\\\"checkbox\\\"!==i.type?i.hasAttribute(\\\"aria-checked\\\")?i.setAttribute(\\\"aria-checked\\\",n?\\\"true\\\":\\\"false\\\"):i.textContent=n?\\\"true\\\":\\\"false\\\":i.checked=n}};qt=new Map,Jt=new Map,Xt=64;Yt={name:\\\"date\\\",render(t,e,i){let n=t.element;if(null==e||\\\"\\\"===e){\\\"INPUT\\\"===n.tagName?n.value=\\\"\\\":(\\\"TIME\\\"===n.tagName&&n.removeAttribute(\\\"datetime\\\"),n.textContent=\\\"\\\");return}let r=\\\"string\\\"==typeof e?e:ct(e),l=new Date(r),s=!Number.isNaN(l.getTime());\\\"INPUT\\\"!==n.tagName?(\\\"TIME\\\"!==n.tagName||n.setAttribute(\\\"datetime\\\",s?l.toISOString():r),n.textContent=s?function(t,e){let i=e.locale??N();try{return function(t,e){let i=mt(t,e),n=Jt.get(i);if(void 0!==n)return Jt.delete(i),Jt.set(i,n),n;let r=new Intl.DateTimeFormat(t,e);return Jt.set(i,r),vt(Jt),r}(i,{dateStyle:\\\"medium\\\",timeStyle:\\\"short\\\"}).format(t)}catch{return t.toISOString()}}(l,i):r):n.value=s?function(t,e){return\\\"date\\\"===t?e.toISOString().slice(0,10):\\\"datetime-local\\\"===t?e.toISOString().slice(0,16):e.toISOString()}(n.type,l):r}};Zt={name:\\\"number\\\",render(t,e,i){let n=t.element;if(null==e||\\\"\\\"===e){\\\"INPUT\\\"===n.tagName?n.value=\\\"\\\":n.textContent=\\\"\\\";return}let r=\\\"number\\\"==typeof e?e:Number(ct(e));Number.isNaN(r)?n.textContent=ct(e):\\\"INPUT\\\"!==n.tagName?n.textContent=function(t,e){let i=e.locale??N();try{return function(t,e){let i=mt(t,e),n=qt.get(i);if(void 0!==n)return qt.delete(i),qt.set(i,n),n;let r=new Intl.NumberFormat(t,e);return qt.set(i,r),vt(qt),r}(i).format(t)}catch{return String(t)}}(r,i):n.value=String(r)}};Kt=/\\\\{\\\\{([\\\\s\\\\S]*?)\\\\}\\\\}/g;Qt={name:\\\"array\\\",render:$((t,e)=>{let i=t.element;if(!Array.isArray(e))return!1;let n=t.arrayTemplate;if(void 0!==n&&n.length>0){let t=function(t,e){let i=\\\"\\\";for(let n=0;n<e.length;n+=1)i+=wt(t,e[n],n);return i}(n,e);i.innerHTML=V(t);return}let r=t.arraySeparator??\\\", \\\";i.textContent=e.map(St).join(r)})};te=\\\"data-payload-key\\\",ee=\\\"data-payload-nested-key\\\",ie=\\\"data-payload-nested-template\\\";ne=new Map;re=[Wt,Ft,Dt,Ut,{...Ut,name:\\\"email\\\"},zt,Vt,Gt,Bt,{...Bt,name:\\\"radio\\\"},Ht,Yt,Zt,Qt,{...Qt,name:\\\"blocks\\\"}];!function(){if(typeof window>\\\"u\\\"||!D()&&(typeof window>\\\"u\\\"||null==window.opener))return;let t=window.__livePreview;if(void 0!==t)return t;let[e=[],i=\\\"\\\",n=\\\"/api\\\",r=1,l=!1,s=50,o=!0,a=0,u=!1,h=50,d=\\\"200px\\\",c=!1,f=!1,p=!1]=typeof __LIVE_PREVIEW_CONFIG__>\\\"u\\\"?[]:__LIVE_PREVIEW_CONFIG__,g=new An({additionalOrigins:e,enableReferrerDetection:!c,enableLocalhostMatching:!f});g.isProductionUnconfigured?pe(\\\"[live-preview] LP0101: No trusted origin. Set PAYLOAD_ADMIN_ORIGIN or pass allowedOrigins to generateInlineScript().\\\"):g.isReferrerOnlyTrust&&pe(\\\"[live-preview] LP0102: document.referrer fallback trusts any framing site. Set allowedOrigins and a frame-ancestors CSP in production.\\\");let m=new me,y=function(t=[]){let e={};for(let i of t)e[i.name]=i;for(let[t,i]of ne)e[t]=i;return Object.freeze(e)}([dt(),...re,It()]),v=new Hi({renderers:y,originMatcher:t=>g.matches(t),lockedOrigin:()=>g.lockedOrigin,readyTargets:g.enumerate(),emitter:m,...\\\"\\\"!==i?{dataMerge:{serverURL:i,apiRoute:n,depth:r}}:{},debounceMs:s,heartbeatMs:a,intersectionRootMargin:d,disableVisibilityGate:u,visibilityGateThreshold:h,enableA11y:o,scopeBindingsByOwner:p,onHeartbeatTimeout:()=>{g.unlockOrigin()},...l?{log:(...t)=>{ge(\\\"[live-preview]\\\",...t)}}:{}});m.on(\\\"connect\\\",t=>{g.lockOrigin(t.origin)}),v.start();let b=function(t,e={}){let i=e.windowTarget??globalThis.window,n=e.documentTarget??globalThis.document,r=e.softNavigationEvents??[],l=()=>{t.suspend()},s=e=>{!0===e.persisted&&t.resume()},o=()=>{t.refreshCache()};i?.addEventListener(\\\"pagehide\\\",l),i?.addEventListener(\\\"pageshow\\\",s);for(let t of r)n?.addEventListener(t,o);let a=!1;return()=>{if(!a){a=!0,i?.removeEventListener(\\\"pagehide\\\",l),i?.removeEventListener(\\\"pageshow\\\",s);for(let t of r)n?.removeEventListener(t,o)}}}({suspend:()=>v.suspend(),resume:()=>v.start(),refreshCache:()=>{v.refreshCache()}}),w=Object.freeze({version:Wi,destroy:()=>{b(),v.destroy();let t=window;t.__livePreview===w&&delete t.__livePreview},refresh:()=>{v.refreshCache()},enumerateOrigins:()=>g.enumerate(),inspect:()=>v.inspect()});try{Object.defineProperty(window,\\\"__livePreview\\\",{value:w,writable:!1,configurable:!0})}catch(t){throw b(),v.destroy(),t}}()})();\";\nexport const RUNTIME_CONTENT_HASH = \"82620c90d7307b6d\";\nexport const RUNTIME_INTEGRITY = \"sha384-xnuuxRgWkWDi/7WE4cxwZ9KX/pYzfs8zbXhlYw9E+N3soc8cJ+9MQtBFGbEG6V0C\";\nexport const RUNTIME_BUILD_INFO: RuntimeBuildInfo = { generatedAt: \"2026-08-25T22:49:43.000Z\", size: 67950 };\n","/**\n * Inline script generator.\n *\n * Wraps the build-time-generated runtime IIFE with consumer-provided\n * configuration. Returns a JavaScript string suitable for embedding\n * via `<script>` in any framework.\n *\n * The runtime body is identical to the one used by the high-level\n * client because both originate from `src/core/runtime.ts`. There is\n * no parallel implementation to drift out of sync.\n *\n * @module @inline/generator\n */\n\nimport { RUNTIME_SOURCE, RUNTIME_BUILD_INFO, type RuntimeBuildInfo } from './runtime.generated';\nimport { LOADER_SOURCE } from './loader.generated';\n\nexport interface InlineScriptConfig {\n /** Additional trusted origins to merge with auto-detected ones. */\n readonly allowedOrigins?: readonly string[];\n /**\n * Payload server origin, e.g. `https://cms.example.com`. When set,\n * every incoming update is re-fetched through the Payload REST API\n * (`X-Payload-HTTP-Method-Override: GET`, same strategy as the\n * official client) so relationship and upload fields render\n * populated instead of as bare IDs. Strongly recommended for\n * Payload 3.x. Requires the preview page to be able to reach the\n * API with credentials (same-site cookies or CORS `credentials`).\n */\n readonly serverURL?: string;\n /** REST API route prefix used with `serverURL`. Defaults to `/api`. */\n readonly apiRoute?: string;\n /** Population depth used with `serverURL`. Defaults to `1`. */\n readonly mergeDepth?: number;\n /** Enable verbose console logging. Defaults to `false`. */\n readonly debug?: boolean;\n /** Debounce window for incoming updates in ms. Defaults to `50`. */\n readonly debounceMs?: number;\n /** Enable screen-reader live region. Defaults to `true`. */\n readonly enableA11y?: boolean;\n /**\n * Heartbeat timeout in ms. Defaults to `0` (disabled). The Payload\n * admin only posts messages on form edits — there is no protocol\n * keepalive — so an idle-based timeout would fire spurious\n * disconnects while the editor pauses. Enable only if your admin\n * setup sends periodic messages.\n */\n readonly heartbeatMs?: number;\n /**\n * Bypass the visibility-gate optimisation and apply every update\n * regardless of viewport position. Default `false` — the gate kicks\n * in when the cache exceeds `visibilityGateThreshold` entries.\n */\n readonly disableVisibilityGate?: boolean;\n /**\n * Cache-size threshold above which the visibility gate activates.\n * Default `50`. Off-screen elements above this threshold are queued\n * for replay on intersection instead of being updated immediately.\n */\n readonly visibilityGateThreshold?: number;\n /**\n * `rootMargin` passed to the `IntersectionObserver` watching the\n * cached elements. Default `'200px'`. Increase to pre-render\n * further off-screen content; decrease for tighter visibility.\n */\n readonly intersectionRootMargin?: string;\n /**\n * Opt out of `document.referrer`-based origin auto-detection.\n * Useful when the page is loaded under `Referrer-Policy: no-referrer`\n * and you want predictable behaviour. Default `false`.\n */\n readonly disableReferrerDetection?: boolean;\n /**\n * Opt out of the dev-mode localhost-pattern matcher (any port on\n * `localhost` / `127.0.0.1`). Useful when running locally against\n * a production-like origin list. Default `false`.\n */\n readonly disableLocalhostMatching?: boolean;\n /**\n * Restrict each update to the bindings owned by the document it describes,\n * declared in markup with `data-payload-owner` and resolved from the nearest\n * ancestor. Default `false`, which keeps matching on the field name alone.\n *\n * Enable it when one page previews more than one document. While enabled a\n * binding without an owner is never updated.\n */\n readonly scopeBindingsByOwner?: boolean;\n /**\n * Retained for 1.x source compatibility, but has no effect here:\n * `generateInlineScript()` returns a script body and creates no tag.\n * Pass the nonce separately to `wrapWithScriptTag(body, { nonce })`.\n *\n * @deprecated Use the second argument of `wrapWithScriptTag()`.\n */\n readonly nonce?: string;\n}\n\n/**\n * Build an inline script body. The result is a self-contained IIFE\n * with the build-time runtime, prefixed by a configuration block.\n *\n * The string does NOT include the `<script>` tags — use\n * `wrapWithScriptTag()` when you need them.\n */\nexport function generateInlineScript(config: InlineScriptConfig = {}): string {\n if (RUNTIME_SOURCE.length === 0) {\n throw new Error(\n '[live-preview] runtime.generated.ts is empty. Run `npm run build:runtime` before bundling.',\n );\n }\n // The IIFE declares its own scope. We inject the config via a `var`\n // declaration that the bundled runtime reads back through the\n // `__LIVE_PREVIEW_CONFIG__` constant placeholder. The identifier is retained\n // across 1.0.x because existing deployments use it as a non-secret runtime\n // presence/leak signal in response-level integration tests.\n return [`var __LIVE_PREVIEW_CONFIG__=${buildConfigLiteral(config)};`, RUNTIME_SOURCE].join('\\n');\n}\n\n/**\n * Serialize the runtime configuration into the compact wire literal.\n *\n * Shared by the inline script and the static-delivery bootstrap so the two can\n * never disagree about the format. The runtime destructures this positionally.\n */\nfunction buildConfigLiteral(config: InlineScriptConfig): string {\n // Compact private wire format; keep this order aligned with\n // `RuntimeBuildConfig` in `src/core/runtime.ts`.\n const compactConfig: unknown[] = [\n config.allowedOrigins,\n config.serverURL,\n config.apiRoute,\n config.mergeDepth,\n config.debug,\n config.debounceMs,\n config.enableA11y,\n config.heartbeatMs,\n config.disableVisibilityGate,\n config.visibilityGateThreshold,\n config.intersectionRootMargin,\n config.disableReferrerDetection,\n config.disableLocalhostMatching,\n config.scopeBindingsByOwner,\n ];\n while (compactConfig.length > 0 && compactConfig.at(-1) === undefined) compactConfig.pop();\n // Preserve omitted interior options as sparse JavaScript slots. JSON arrays\n // encode `undefined` as `null`, which would bypass the runtime's destructuring\n // defaults and can turn an omitted serverURL into an invalid configured value.\n // `<` must never appear literally inside an inline <script> body — a\n // consumer-supplied string containing `</script>` would terminate the tag.\n const configLiteral = `[${compactConfig\n .map((value) => (value === undefined ? '' : JSON.stringify(value)))\n .join(',')}]`.replace(/</g, '\\\\u003C');\n return configLiteral;\n}\n\n/** Where the runtime asset lives, and how the browser should verify it. */\nexport interface LoaderScriptTarget {\n /** URL the bootstrap appends. Same-origin or absolute; hashed by the caller. */\n readonly runtimeSrc: string;\n /**\n * Subresource-integrity value for that asset, e.g. `sha384-…`.\n *\n * Empty disables the check and the `crossorigin` attribute that enforcement\n * requires. Only appropriate where the asset is served from the same origin\n * as the page and the deployment already guarantees they ship together.\n */\n readonly integrity?: string;\n}\n\n/**\n * Generate the static-delivery bootstrap instead of the whole runtime.\n *\n * Emits the configuration plus a few hundred bytes that check the preview\n * context and, only then, append the runtime as an external script. A\n * statically built site otherwise bakes the full runtime into every page,\n * charging every ordinary visitor for a feature only an editor uses.\n *\n * The runtime asset stays configuration-free: the config lives in this inline\n * body, so the asset is byte identical across sites and deployments — which is\n * what lets it be cached and hashed, and what makes it structurally incapable\n * of carrying a token.\n */\nexport function generateLoaderScript(\n config: InlineScriptConfig = {},\n target: LoaderScriptTarget,\n): string {\n if (LOADER_SOURCE.length === 0) {\n throw new Error(\n '[live-preview] loader.generated.ts is empty. Run `npm run build:runtime` before bundling.',\n );\n }\n if (target.runtimeSrc === '') {\n throw new Error('[live-preview] generateLoaderScript needs a runtimeSrc.');\n }\n // `<` must never appear literally inside an inline <script> body: a\n // consumer-supplied URL containing `</script>` would terminate the tag.\n const encode = (value: string): string => JSON.stringify(value).replace(/</gu, '\\\\u003C');\n return [\n `var __LIVE_PREVIEW_CONFIG__=${buildConfigLiteral(config)};`,\n `var __LP_RUNTIME_SRC__=${encode(target.runtimeSrc)};`,\n `var __LP_RUNTIME_INTEGRITY__=${encode(target.integrity ?? '')};`,\n LOADER_SOURCE,\n ].join('\\n');\n}\n\n/**\n * Wrap an inline script body in a `<script>` tag. When a nonce is\n * provided it is added as the `nonce` attribute so CSP policies that\n * require `'nonce-...'` accept the script.\n */\nexport function wrapWithScriptTag(body: string, options: { nonce?: string } = {}): string {\n const nonceAttr = options.nonce !== undefined ? ` nonce=\"${escapeNonce(options.nonce)}\"` : '';\n return `<script${nonceAttr}>${body}</script>`;\n}\n\n/**\n * Snapshot of the build-time information for diagnostics.\n */\nexport function runtimeBuildInfo(): RuntimeBuildInfo {\n return RUNTIME_BUILD_INFO;\n}\n\nfunction escapeNonce(nonce: string): string {\n if (!/^[A-Za-z0-9+/=_-]+$/.test(nonce)) {\n throw new RangeError('wrapWithScriptTag: nonce contains invalid characters');\n }\n return nonce;\n}\n","/**\n * Content-Security-Policy helpers.\n *\n * Two responsibilities:\n *\n * 1. Generate cryptographic nonces so consumers can opt into a strict\n * `script-src 'nonce-...'` policy and avoid `'unsafe-inline'`.\n * 2. Build the `frame-ancestors` directive value, restricting which\n * origins may embed the preview page in an iframe.\n *\n * Both functions are isomorphic — they work in browsers, Node, and\n * edge runtimes that expose Web Crypto via `globalThis.crypto`.\n *\n * @module @security/csp\n */\n\n/**\n * Default byte-length for nonces. 16 bytes → 22 base64url characters,\n * which exceeds the 128-bit entropy threshold recommended by OWASP.\n */\nconst DEFAULT_NONCE_BYTES = 16;\n\n/** CSP3's exact whitespace set: HTAB, LF, FF, CR, and SPACE. */\nconst CSP_ASCII_WHITESPACE = /[\\t\\n\\f\\r ]+/;\nconst CSP_EDGE_ASCII_WHITESPACE = /^[\\t\\n\\f\\r ]+|[\\t\\n\\f\\r ]+$/g;\n\n/** CSP names are ASCII strings; Unicode case folding must not create directives. */\nfunction asciiLowercase(value: string): string {\n return value.replace(/[A-Z]/g, (character) => character.toLowerCase());\n}\n\n/**\n * Minimal Web-Crypto surface area we actually call. The full `Crypto`\n * type drags in browser-only declarations that don't typecheck cleanly\n * against Node's `webcrypto` shape — this narrower interface accepts\n * both without an unsafe cast.\n */\ninterface WebCryptoLike {\n getRandomValues: <T extends ArrayBufferView | null>(array: T) => T;\n}\n\nlet cryptoOverride: WebCryptoLike | undefined;\n\n/**\n * Inject a Web Crypto implementation to use when `globalThis.crypto`\n * is unavailable.\n *\n * Node.js exposed `globalThis.crypto` globally starting with v19. On\n * Node 18 (still LTS at time of writing) consumers can flip the\n * `--experimental-global-webcrypto` flag *or* call this function once\n * at startup:\n *\n * ```ts\n * import { webcrypto } from 'node:crypto';\n * import { setCspCrypto } from 'payload-live-preview';\n * setCspCrypto(webcrypto as { getRandomValues: typeof webcrypto.getRandomValues });\n * ```\n *\n * Browser bundles never need to call this — `globalThis.crypto` is\n * always present there, and the override only matters when the global\n * is missing.\n *\n * Pass `null` to clear a previous override (mostly useful for tests).\n */\nexport function setCspCrypto(crypto: WebCryptoLike | null): void {\n cryptoOverride = crypto ?? undefined;\n}\n\n/**\n * Generate a base64url-encoded cryptographic nonce.\n *\n * Uses `crypto.getRandomValues` everywhere — falls back to throwing\n * if no Web Crypto implementation is available, because a predictable\n * nonce would silently defeat the entire CSP.\n *\n * @param bytes Number of random bytes (defaults to 16 → 128-bit entropy).\n */\nexport function generateCspNonce(bytes: number = DEFAULT_NONCE_BYTES): string {\n if (!Number.isInteger(bytes) || bytes < 8) {\n throw new RangeError(`generateCspNonce: bytes must be an integer >= 8, got ${String(bytes)}`);\n }\n const crypto = resolveCrypto();\n if (!crypto) {\n throw new Error(\n 'generateCspNonce: Web Crypto is unavailable. On Node 18 call setCspCrypto(webcrypto) ' +\n \"once at startup, or run with --experimental-global-webcrypto. We won't fabricate \" +\n 'a predictable nonce — that would silently defeat the entire CSP.',\n );\n }\n const buffer = new Uint8Array(bytes);\n crypto.getRandomValues(buffer);\n return base64UrlEncode(buffer);\n}\n\nfunction resolveCrypto(): WebCryptoLike | undefined {\n if (cryptoOverride?.getRandomValues) return cryptoOverride;\n const fromGlobal = (globalThis as { crypto?: WebCryptoLike }).crypto;\n if (fromGlobal?.getRandomValues) return fromGlobal;\n return undefined;\n}\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n const base64 = typeof btoa === 'function' ? btoa(binary) : Buffer.from(bytes).toString('base64');\n return base64.replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');\n}\n\n/**\n * Sources allowed in the `frame-ancestors` directive.\n *\n * Conceptually a union of `'self'`, `'none'`, or an explicit origin\n * string. TypeScript collapses literal-vs-string unions, so we expose\n * a `string` alias and document the special values.\n */\nexport type FrameAncestorSource = string;\n\nexport interface FrameAncestorsOptions {\n readonly self?: boolean;\n readonly origins?: readonly string[];\n readonly allowNone?: boolean;\n}\n\n/**\n * Build the value for `frame-ancestors` in a `Content-Security-Policy`\n * header.\n *\n * Returns `'none'` if `allowNone: true` and no other sources are\n * provided. Otherwise concatenates `'self'` (if requested) with the\n * given origins, deduplicating and trimming entries.\n *\n * @example\n * `frame-ancestors ${buildFrameAncestors({ self: true, origins: [adminUrl] })}`\n */\nexport function buildFrameAncestors(options: FrameAncestorsOptions = {}): string {\n const { self = true, origins = [], allowNone = false } = options;\n const seen = new Set<string>();\n const out: FrameAncestorSource[] = [];\n if (allowNone && !self && origins.length === 0) return \"'none'\";\n if (self) {\n out.push(\"'self'\");\n seen.add(\"'self'\");\n }\n for (const origin of origins) {\n const trimmed = origin.trim();\n if (trimmed.length === 0 || seen.has(trimmed)) continue;\n seen.add(trimmed);\n out.push(trimmed);\n }\n return out.length > 0 ? out.join(' ') : \"'none'\";\n}\n\n/**\n * Build a `script-src` value that permits a single nonce plus optional\n * extra sources.\n *\n * `'strict-dynamic'` is **opt-in**: under CSP 3 it makes browsers\n * ignore `'self'` and every host source in the directive, so any\n * parser-inserted script without a nonce (framework hydration scripts,\n * consumer `<script>` tags) would be blocked. Only enable it when every\n * script on the page carries the nonce.\n */\nexport function buildScriptSrcWithNonce(\n nonce: string,\n options: {\n readonly self?: boolean;\n readonly extra?: readonly string[];\n readonly strictDynamic?: boolean;\n } = {},\n): string {\n if (nonce.length === 0) throw new RangeError('buildScriptSrcWithNonce: nonce is empty');\n const { self = true, extra = [], strictDynamic = false } = options;\n const parts: string[] = [];\n if (self) parts.push(\"'self'\");\n parts.push(`'nonce-${nonce}'`);\n if (strictDynamic) parts.push(\"'strict-dynamic'\");\n for (const e of extra) {\n const trimmed = e.trim();\n if (trimmed.length > 0) parts.push(trimmed);\n }\n return parts.join(' ');\n}\n\n/**\n * How a directive is merged into an existing CSP header value.\n *\n * - `union` (default) — the new sources are added to the existing\n * directive's sources (deduplicated). An existing `'none'` is\n * dropped when real sources are added, since `'none'` may not be\n * combined with other sources.\n * - `replace` — the new value overwrites the existing directive.\n */\nexport interface CspDirectiveMerge {\n readonly value: string;\n readonly mode?: 'union' | 'replace';\n}\n\n/**\n * Merge directives into an existing `Content-Security-Policy` header\n * value without clobbering what a consumer (or another middleware)\n * already configured. Directives not mentioned in `additions` pass\n * through untouched; new directives are appended. Existing policy parsing\n * follows CSP3's ASCII-whitespace and first-duplicate-wins rules.\n *\n * This is the single CSP-merge implementation shared by every adapter.\n */\nexport function mergeCspHeader(\n existing: string,\n additions: Readonly<Record<string, string | CspDirectiveMerge>>,\n): string {\n const directives = new Map<string, string>();\n for (const part of existing.split(';')) {\n const trimmed = part.replace(CSP_EDGE_ASCII_WHITESPACE, '');\n if (trimmed.length === 0) continue;\n const whitespaceIndex = trimmed.search(CSP_ASCII_WHITESPACE);\n const name = asciiLowercase(whitespaceIndex < 0 ? trimmed : trimmed.slice(0, whitespaceIndex));\n\n // CSP3 §2.2.1 is first-wins: a user agent ignores every later\n // case-insensitive duplicate. Mirroring that rule before merging prevents a\n // later, looser duplicate from becoming the policy we serialize.\n if (directives.has(name)) continue;\n\n const value =\n whitespaceIndex < 0\n ? ''\n : trimmed.slice(whitespaceIndex).replace(CSP_EDGE_ASCII_WHITESPACE, '');\n directives.set(name, value);\n }\n\n for (const [rawName, rawAddition] of Object.entries(additions)) {\n const name = asciiLowercase(rawName);\n const addition: CspDirectiveMerge =\n typeof rawAddition === 'string' ? { value: rawAddition } : rawAddition;\n const mode = addition.mode ?? 'union';\n const current = directives.get(name);\n if (mode === 'replace' || current === undefined || current.length === 0) {\n directives.set(name, addition.value);\n continue;\n }\n const seen = new Set<string>();\n const merged: string[] = [];\n for (const token of [\n ...current.split(CSP_ASCII_WHITESPACE),\n ...addition.value.split(CSP_ASCII_WHITESPACE),\n ]) {\n if (token.length === 0 || seen.has(token)) continue;\n seen.add(token);\n merged.push(token);\n }\n // `'none'` cannot coexist with other sources.\n const withoutNone = merged.filter((token) => token !== \"'none'\");\n directives.set(name, (withoutNone.length > 0 ? withoutNone : merged).join(' '));\n }\n\n const out: string[] = [];\n for (const [name, value] of directives) {\n out.push(value.length === 0 ? name : `${name} ${value}`);\n }\n return out.join('; ');\n}\n","/**\n * Server-side preview-intent detection.\n *\n * The live-preview runtime only ever activates inside the Payload\n * admin's iframe, but the *server* still has to decide whether a\n * request expresses preview intent before doing optional preview\n * work. Adapters use this predicate as a delivery optimisation, and\n * consumers with hand-rolled middleware can import it directly.\n *\n * IMPORTANT: every signal inspected here is controlled or triggerable\n * by the client. A positive result is never proof of identity,\n * authentication, or permission to read drafts. Before forwarding\n * credentials, fetching draft data, bypassing caches, changing CSP,\n * or injecting the runtime, verify the request with an application-\n * owned server session or a short-lived signed authorization. Use the\n * same verified decision for all of those effects.\n *\n * Preview intent is present when any of these hold:\n *\n * 1. A preview query parameter is present (`?preview=true`,\n * `?draft=true`, `?livePreview=true` — configurable).\n * 2. `Sec-Fetch-Dest: iframe` — the document is being loaded as an\n * iframe, which is exactly how the Payload admin embeds it.\n * (Sent by all evergreen browsers; absence never *excludes* a\n * request, presence includes it.)\n * 3. The `Referer` points at one of the given admin origins.\n *\n * @module @adapters/shared/preview-request\n */\n\n/** The individual signals the predicate can consider. */\nexport type PreviewSignal = 'query' | 'fetch-dest' | 'referer';\n\nexport interface PreviewRequestOptions {\n /**\n * Which signals count as preview intent. Default: all three.\n * Restricting this to `['query']` reduces accidental activation, but\n * an explicit `?preview=true` is still client-controlled and must not\n * authorize response changes or privileged data access by itself.\n */\n readonly signals?: readonly PreviewSignal[];\n /**\n * Query parameters (with values `true` or `1`) that signal preview\n * intent. Default: `['preview', 'draft', 'livePreview']`.\n */\n readonly queryParams?: readonly string[];\n /**\n * Treat `Sec-Fetch-Dest: iframe` as a preview-intent signal. Default `true`.\n * Legacy alias for excluding `'fetch-dest'` from `signals`.\n */\n readonly checkFetchDest?: boolean;\n /**\n * Admin origins whose `Referer` signals preview intent, e.g.\n * `['https://cms.example.com']`. Referer matching is not HTTP-request\n * authentication.\n */\n readonly adminOrigins?: readonly string[];\n}\n\nconst DEFAULT_QUERY_PARAMS = ['preview', 'draft', 'livePreview'] as const;\n\n/**\n * The minimal request surface the predicate needs. The standard\n * `Request` satisfies it structurally, and server frameworks without\n * fetch-style requests (e.g. Nitro/H3) can supply a tiny shim.\n */\nexport interface PreviewRequestLike {\n readonly url: string;\n readonly headers: { get(name: string): string | null };\n}\n\n/**\n * Detect whether `request` carries live-preview intent. See the module\n * docblock for the exact signals and the required authorization\n * boundary. This compatibility name does not imply authentication.\n */\nexport function isPreviewRequest(\n request: PreviewRequestLike,\n options: PreviewRequestOptions = {},\n): boolean {\n const signals = new Set<PreviewSignal>(options.signals ?? ['query', 'fetch-dest', 'referer']);\n const queryParams = options.queryParams ?? DEFAULT_QUERY_PARAMS;\n const checkFetchDest = (options.checkFetchDest ?? true) && signals.has('fetch-dest');\n\n if (signals.has('query')) {\n let url: URL | undefined;\n try {\n url = new URL(request.url);\n } catch {\n url = undefined;\n }\n if (url !== undefined) {\n for (const param of queryParams) {\n const value = url.searchParams.get(param);\n if (value === 'true' || value === '1') return true;\n }\n }\n }\n\n if (checkFetchDest && request.headers.get('sec-fetch-dest') === 'iframe') {\n return true;\n }\n\n const adminOrigins = signals.has('referer') ? (options.adminOrigins ?? []) : [];\n if (adminOrigins.length > 0) {\n const referer = request.headers.get('referer');\n if (referer !== null) {\n try {\n const refererOrigin = new URL(referer).origin;\n for (const adminOrigin of adminOrigins) {\n try {\n if (new URL(adminOrigin).origin === refererOrigin) return true;\n } catch {\n // skip malformed configured origin\n }\n }\n } catch {\n // malformed referer — not a preview signal\n }\n }\n }\n\n return false;\n}\n","/**\n * Draft-aware document fetching for the initial preview render.\n *\n * The live-preview runtime patches the DOM *after* the page loads —\n * the initial server render is the consumer's job. With Payload\n * drafts enabled, an **authorized** preview should render the draft\n * version on first load, otherwise editors see stale published\n * content until their first keystroke.\n *\n * These helpers wrap the corresponding REST queries with `draft` and\n * `depth` options and an explicit nudge to keep `depth` in sync with\n * the runtime's `mergeDepth` — a mismatch makes populated\n * relationships degrade to IDs after the first edit.\n *\n * These helpers do not authenticate or authorize requests.\n * `isPreviewRequest()` detects client-controlled preview intent only.\n * Verify an application-owned server session or short-lived signed\n * authorization first, and use that one decision to gate `draft`, any\n * privileged headers, cache bypass, CSP changes, and runtime injection.\n * Never attach a long-lived service/API key merely because\n * `isPreviewRequest()` returned `true`.\n *\n * Isomorphic and dependency-free: works in Astro frontmatter,\n * SvelteKit `load`, Next.js server components, or any Node/edge\n * runtime with `fetch`.\n *\n * ```ts\n * // Astro frontmatter. `verifyAppPreviewSession` is application-owned,\n * // server-only code; it validates the request and returns only the\n * // minimal Payload session headers needed for this request.\n * const hasPreviewIntent = isPreviewRequest(Astro.request);\n * const authorization = hasPreviewIntent\n * ? await verifyAppPreviewSession(Astro.request)\n * : null;\n * const page = await fetchPreviewDocument<Page>({\n * serverURL: import.meta.env.PAYLOAD_URL,\n * collection: 'pages',\n * where: { slug: { equals: Astro.params.slug } },\n * draft: authorization !== null,\n * ...(authorization === null ? {} : { headers: authorization.payloadHeaders }),\n * });\n * ```\n *\n * @module @preview-fetch\n */\n\nexport interface PreviewFetchBaseOptions {\n /** Payload server origin, e.g. `https://cms.example.com`. */\n readonly serverURL: string;\n /** REST API route prefix. Defaults to `/api`. */\n readonly apiRoute?: string;\n /**\n * Population depth. Defaults to `1`. ⚠️ Keep this equal to the\n * runtime's `mergeDepth` — the live-merge re-fetches with that\n * depth, and a mismatch makes nested relationships flip between\n * objects and IDs mid-session.\n */\n readonly depth?: number;\n /**\n * Fetch the draft version. Defaults to `true` for 1.x compatibility.\n * Set this from a verified authorization decision, not directly\n * from `isPreviewRequest()`, whose result only expresses intent.\n */\n readonly draft?: boolean;\n /** Locale to fetch. */\n readonly locale?: string;\n /**\n * Extra request headers. Supply only credentials derived from the\n * current request's verified server-side session (or another\n * short-lived, scoped authorization). Do not attach a long-lived\n * service/API key based on a preview-intent signal.\n */\n readonly headers?: Readonly<Record<string, string>>;\n /** Injectable fetch implementation (tests, custom agents). */\n readonly fetchFn?: typeof fetch;\n}\n\n/** Payload `where` clause — kept loose on purpose (server validates). */\nexport type PreviewWhere = Readonly<Record<string, unknown>>;\n\nexport interface FetchPreviewDocumentOptions extends PreviewFetchBaseOptions {\n /** Collection slug. */\n readonly collection: string;\n /** Fetch a single document by id. Mutually exclusive with `where`. */\n readonly id?: string | number;\n /**\n * Fetch the first document matching this Payload `where` clause,\n * e.g. `{ slug: { equals: 'about' } }`.\n */\n readonly where?: PreviewWhere;\n}\n\nexport interface FetchPreviewGlobalOptions extends PreviewFetchBaseOptions {\n /** Global slug. */\n readonly global: string;\n}\n\n/**\n * Fetch a single collection document (draft-first by default for 1.x\n * compatibility; callers must authorize draft access).\n * Returns `null` when nothing matches or the request fails —\n * loaders should fall back to their regular data path or a 404.\n */\nexport async function fetchPreviewDocument<T = Record<string, unknown>>(\n options: FetchPreviewDocumentOptions,\n): Promise<T | null> {\n const params = baseParams(options);\n if (options.id !== undefined) {\n const url = `${apiBase(options)}/${encodeURIComponent(options.collection)}/${encodeURIComponent(\n String(options.id),\n )}?${params.toString()}`;\n return requestJson<T>(url, options);\n }\n\n if (options.where !== undefined) {\n appendWhere(params, options.where, ['where']);\n }\n params.set('limit', '1');\n const url = `${apiBase(options)}/${encodeURIComponent(options.collection)}?${params.toString()}`;\n const page = await requestJson<{ docs?: T[] }>(url, options);\n const first = page?.docs?.[0];\n return first ?? null;\n}\n\n/**\n * Fetch a global (draft-first by default for 1.x compatibility;\n * callers must authorize draft access). Returns `null` on failure.\n */\nexport async function fetchPreviewGlobal<T = Record<string, unknown>>(\n options: FetchPreviewGlobalOptions,\n): Promise<T | null> {\n const params = baseParams(options);\n const url = `${apiBase(options)}/globals/${encodeURIComponent(options.global)}?${params.toString()}`;\n return requestJson<T>(url, options);\n}\n\nfunction apiBase(options: PreviewFetchBaseOptions): string {\n const origin = options.serverURL.replace(/\\/+$/, '');\n const route = options.apiRoute ?? '/api';\n return `${origin}${route.startsWith('/') ? route : `/${route}`}`;\n}\n\nfunction baseParams(options: PreviewFetchBaseOptions): URLSearchParams {\n const params = new URLSearchParams();\n params.set('depth', String(options.depth ?? 1));\n if (options.draft ?? true) params.set('draft', 'true');\n if (options.locale !== undefined) params.set('locale', options.locale);\n return params;\n}\n\n/**\n * Serialise a nested `where` object into Payload's qs-style query\n * params: `{ slug: { equals: 'x' } }` → `where[slug][equals]=x`.\n */\nfunction appendWhere(params: URLSearchParams, node: PreviewWhere, path: string[]): void {\n for (const [key, value] of Object.entries(node)) {\n const nextPath = [...path, key];\n if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n appendWhere(params, value as PreviewWhere, nextPath);\n continue;\n }\n const name = nextPath.map((seg, i) => (i === 0 ? seg : `[${seg}]`)).join('');\n if (Array.isArray(value)) {\n params.set(name, value.map(String).join(','));\n } else {\n params.set(name, String(value));\n }\n }\n}\n\nasync function requestJson<T>(url: string, options: PreviewFetchBaseOptions): Promise<T | null> {\n const fetchFn = options.fetchFn ?? (typeof fetch === 'function' ? fetch : undefined);\n if (fetchFn === undefined) return null;\n try {\n const response = await fetchFn(url, {\n credentials: 'include',\n headers: {\n Accept: 'application/json',\n ...(options.headers ?? {}),\n },\n });\n if (!response.ok) return null;\n const body: unknown = await response.json();\n if (body === null || typeof body !== 'object') return null;\n return body as T;\n } catch {\n return null;\n }\n}\n","/**\n * `highlight` plugin — flashes an outline on updated elements so the\n * editor can see what changed.\n *\n * Respects `prefers-reduced-motion`. Adds at most one style tag per\n * document.\n *\n * @module @plugins/built-in/highlight\n */\n\nimport type { LivePreviewPlugin } from '../types';\nimport type { PluginDisposer } from '../types';\n\nconst STYLE_ID = 'payload-live-preview-highlight';\nconst REDUCED_MOTION_CSS =\n '.lp-highlight{outline:2px solid rgba(0,102,204,0.85);outline-offset:2px;}';\nconst ANIMATED_CSS =\n '@keyframes lp-highlight{0%{outline:2px solid rgba(0,102,204,0.85);outline-offset:2px}100%{outline:2px solid transparent;outline-offset:2px}}.lp-highlight{animation:lp-highlight 0.6s ease-out;}';\n\ninterface StyleLease {\n readonly element: HTMLStyleElement;\n readonly pluginOwned: boolean;\n owners: number;\n}\n\n// DOM-keyed shared leases prevent one client from removing resources still in\n// use by another client. WeakMaps do not retain discarded documents/elements.\nconst styleLeases = new WeakMap<Document, StyleLease>();\ninterface HighlightLease {\n owners: number;\n readonly pluginAdded: boolean;\n}\n\nconst highlightLeases = new WeakMap<Element, HighlightLease>();\n\nexport const highlightPlugin: LivePreviewPlugin = {\n name: 'highlight',\n version: '1.0.0',\n init: (ctx) => {\n if (typeof document === 'undefined' || typeof window === 'undefined') return;\n const prefersReducedMotion =\n typeof window.matchMedia === 'function' &&\n window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n const releaseStyle = acquireStyle(document, prefersReducedMotion);\n const duration = prefersReducedMotion ? 1000 : 600;\n const activeTimers = new WeakMap<Element, PluginDisposer>();\n // Only currently armed timers are strongly retained. Each completion\n // removes itself; one registration-owned cleanup drains the bounded set on\n // teardown without requiring a new public disposer-return contract.\n const timerCleanups = new Set<PluginDisposer>();\n ctx.registerCleanup?.(() => {\n for (const cleanup of [...timerCleanups]) cleanup();\n releaseStyle();\n });\n ctx.events.on('elementUpdate', (e) => {\n const element = e.element;\n activeTimers.get(element)?.();\n const releaseHighlight = acquireHighlight(element);\n let disposed = false;\n const disposeTimer: PluginDisposer = () => {\n if (disposed) return;\n disposed = true;\n window.clearTimeout(handle);\n if (activeTimers.get(element) === disposeTimer) activeTimers.delete(element);\n timerCleanups.delete(disposeTimer);\n releaseHighlight();\n };\n const handle = window.setTimeout(disposeTimer, duration);\n timerCleanups.add(disposeTimer);\n activeTimers.set(element, disposeTimer);\n });\n },\n};\n\nfunction acquireStyle(document: Document, prefersReducedMotion: boolean): PluginDisposer {\n let lease = styleLeases.get(document);\n // Tests, HMR, or a host DOM swap may remove an owned node without running\n // plugin teardown. Never reuse a disconnected lease.\n if (lease !== undefined && !lease.element.isConnected) {\n styleLeases.delete(document);\n lease = undefined;\n }\n if (lease === undefined) {\n const existing = document.getElementById(STYLE_ID);\n const style = existing instanceof HTMLStyleElement ? existing : document.createElement('style');\n const pluginOwned = existing === null;\n if (pluginOwned) {\n style.id = STYLE_ID;\n style.textContent = prefersReducedMotion ? REDUCED_MOTION_CSS : ANIMATED_CSS;\n document.head.appendChild(style);\n }\n lease = { element: style, pluginOwned, owners: 0 };\n styleLeases.set(document, lease);\n }\n const acquiredLease = lease;\n acquiredLease.owners += 1;\n\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n acquiredLease.owners -= 1;\n if (acquiredLease.owners > 0) return;\n if (styleLeases.get(document) === acquiredLease) styleLeases.delete(document);\n if (acquiredLease.pluginOwned) acquiredLease.element.remove();\n };\n}\n\nfunction acquireHighlight(element: Element): PluginDisposer {\n let lease = highlightLeases.get(element);\n if (lease === undefined) {\n lease = { owners: 0, pluginAdded: !element.classList.contains('lp-highlight') };\n highlightLeases.set(element, lease);\n }\n const acquiredLease = lease;\n acquiredLease.owners += 1;\n element.classList.add('lp-highlight');\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n acquiredLease.owners -= 1;\n if (acquiredLease.owners > 0) return;\n highlightLeases.delete(element);\n if (acquiredLease.pluginAdded) element.classList.remove('lp-highlight');\n };\n}\n","/**\n * `debug` plugin — logs every lifecycle event via the plugin context.\n *\n * @module @plugins/built-in/debug\n */\n\nimport type { LivePreviewPlugin } from '../types';\n\nexport const debugPlugin: LivePreviewPlugin = {\n name: 'debug',\n version: '1.0.0',\n init: (ctx) => {\n ctx.events.on('init', () => {\n ctx.log('init');\n });\n ctx.events.on('connect', (e) => {\n ctx.log('connect ←', e.origin);\n });\n ctx.events.on('disconnect', (e) => {\n ctx.log('disconnect (', e.reason, ')');\n });\n ctx.events.on('cacheRefresh', (e) => {\n ctx.log('cacheRefresh', e.elementCount, 'elements,', e.fieldCount, 'fields');\n });\n ctx.events.on('beforeUpdate', (e) => {\n ctx.log('beforeUpdate', Object.keys(e.data.fields).length, 'fields');\n });\n ctx.events.on('afterUpdate', (e) => {\n ctx.log('afterUpdate', e.updatedCount, 'in', e.durationMs.toFixed(2), 'ms');\n });\n ctx.events.on('error', (e) => {\n ctx.log('error in', e.context, ':', e.error.message);\n });\n },\n};\n","/**\n * `analytics` plugin — accumulates summary statistics about the\n * update stream. Useful for performance dashboards.\n *\n * The plugin owns its own state (no module singleton) and exposes it\n * via the `getStats` factory passed through the plugin's `init` hook\n * by closing over a local object.\n *\n * @module @plugins/built-in/analytics\n */\n\nimport type { LivePreviewPlugin } from '../types';\n\nexport interface AnalyticsSnapshot {\n readonly updateCount: number;\n readonly totalElements: number;\n readonly totalDurationMs: number;\n readonly averageDurationMs: number;\n}\n\nexport function createAnalyticsPlugin(): LivePreviewPlugin & {\n readonly getStats: () => AnalyticsSnapshot;\n} {\n let updateCount = 0;\n let totalElements = 0;\n let totalDurationMs = 0;\n\n return {\n name: 'analytics',\n version: '1.0.0',\n init: (ctx) => {\n ctx.events.on('afterUpdate', (e) => {\n updateCount += 1;\n totalElements += e.updatedCount;\n totalDurationMs += e.durationMs;\n });\n },\n getStats: (): AnalyticsSnapshot => ({\n updateCount,\n totalElements,\n totalDurationMs,\n averageDurationMs: updateCount === 0 ? 0 : totalDurationMs / updateCount,\n }),\n };\n}\n","/**\n * `documentSave` plugin — react to Payload document-save events with\n * out-of-the-box strategies. Most consumers just want one of these:\n *\n * - `'silent'` (default) → only emit the event, do nothing else.\n * - `'reload'` → reload the page, **preserving the scroll\n * position** across the reload (the\n * framework-agnostic analog of Payload's\n * `RefreshRouteOnSave`).\n * - `'revalidate'` → POST to a revalidation endpoint (Astro,\n * Next.js convention) so SSR caches refresh\n * without losing client state.\n * - `'fetch'` → custom async handler supplied by the user.\n *\n * Each strategy is intentionally narrow so consumers can compose them\n * — e.g. revalidate, then if revalidation fails, fall back to reload.\n *\n * @module @plugins/built-in/document-save\n */\n\nimport type { LivePreviewPlugin } from '../types';\n\n/** sessionStorage key for the scroll position saved across a reload. */\nconst SCROLL_KEY = 'payload-live-preview:scroll';\n\nfunction saveScrollPosition(): void {\n if (typeof window === 'undefined') return;\n try {\n sessionStorage.setItem(\n SCROLL_KEY,\n JSON.stringify({ href: window.location.href, x: window.scrollX, y: window.scrollY }),\n );\n } catch {\n // sessionStorage unavailable (sandboxed iframe without allow-same-origin)\n }\n}\n\nfunction restoreScrollPosition(): void {\n if (typeof window === 'undefined') return;\n try {\n const raw = sessionStorage.getItem(SCROLL_KEY);\n if (raw === null) return;\n sessionStorage.removeItem(SCROLL_KEY);\n const saved = JSON.parse(raw) as { href?: string; x?: number; y?: number };\n if (saved.href !== window.location.href) return;\n window.scrollTo(saved.x ?? 0, saved.y ?? 0);\n } catch {\n // corrupted entry or storage unavailable — nothing to restore\n }\n}\n\nfunction reloadPreservingScroll(): void {\n if (typeof window === 'undefined') return;\n saveScrollPosition();\n window.location.reload();\n}\n\nexport type DocumentSaveStrategy = 'silent' | 'reload' | 'revalidate' | 'fetch';\n\n/**\n * A fetch strategy handler. The optional parameter preserves calls through\n * pre-1.0.4 option objects (`options.handler?.()`), while method bivariance\n * also accepts explicitly signal-aware handlers. The built-in plugin always\n * supplies a live `AbortSignal`.\n */\nexport type DocumentSaveHandler = {\n bivarianceHack(signal?: AbortSignal): void | Promise<void>;\n}['bivarianceHack'];\n\nexport interface DocumentSavePluginOptions {\n /** Strategy to invoke on each `documentSave` event. Default `'silent'`. */\n readonly strategy?: DocumentSaveStrategy;\n /**\n * For `'revalidate'`: endpoint to POST to. Defaults to `/api/revalidate`.\n * The request body is `{ source: 'payload-live-preview' }` JSON.\n */\n readonly revalidateUrl?: string;\n /**\n * For `'revalidate'`: extra headers (e.g., `Authorization: Bearer …`).\n * The `Content-Type: application/json` header is set automatically.\n */\n readonly revalidateHeaders?: Readonly<Record<string, string>>;\n /**\n * For `'fetch'`: async handler called on each event. The plugin\n * awaits it; rejections are logged but don't crash the runtime. The signal\n * aborts when the plugin is removed. Existing zero-argument handlers remain\n * compatible because they may ignore the argument.\n */\n readonly handler?: DocumentSaveHandler;\n /**\n * Optional fallback strategy when `'revalidate'` POST fails (network\n * error or non-2xx). Set to `'reload'` to hard-refresh the page when\n * SSR-cache invalidation can't be confirmed.\n */\n readonly onRevalidateFailure?: 'silent' | 'reload';\n}\n\nconst DEFAULT_REVALIDATE_URL = '/api/revalidate';\n\n/**\n * Build the plugin. Pass it to `client.use(documentSavePlugin({ … }))`.\n */\nexport function documentSavePlugin(options: DocumentSavePluginOptions = {}): LivePreviewPlugin {\n const strategy = options.strategy ?? 'silent';\n return {\n name: 'document-save',\n version: '1.1.0',\n init: (ctx) => {\n let active = true;\n const controllers = new Set<AbortController>();\n ctx.registerCleanup?.(() => {\n active = false;\n for (const controller of controllers) controller.abort();\n controllers.clear();\n });\n // If the previous page load ended in a save-triggered reload,\n // put the editor back where they were.\n restoreScrollPosition();\n ctx.events.on('documentSave', () => {\n if (!active) return;\n if (strategy === 'silent') return;\n if (strategy === 'reload') {\n reloadPreservingScroll();\n return;\n }\n const controller = new AbortController();\n controllers.add(controller);\n const operation =\n strategy === 'fetch'\n ? runFetch(options, ctx.log, controller.signal, () => active)\n : runRevalidate(options, ctx.log, controller.signal, () => active);\n void operation.finally(() => {\n controllers.delete(controller);\n });\n });\n },\n };\n}\n\nasync function runFetch(\n options: DocumentSavePluginOptions,\n log: (...args: unknown[]) => void,\n signal: AbortSignal,\n isActive: () => boolean,\n): Promise<void> {\n if (!options.handler) {\n log('document-save: fetch strategy selected but no handler supplied');\n return;\n }\n try {\n await options.handler(signal);\n } catch (err) {\n if (!isActive() || signal.aborted) return;\n log('document-save handler threw:', err);\n }\n}\n\nasync function runRevalidate(\n options: DocumentSavePluginOptions,\n log: (...args: unknown[]) => void,\n signal: AbortSignal,\n isActive: () => boolean,\n): Promise<void> {\n if (typeof fetch === 'undefined') {\n log('document-save: revalidate strategy needs fetch — not available');\n return;\n }\n const url = options.revalidateUrl ?? DEFAULT_REVALIDATE_URL;\n let ok = false;\n try {\n const response = await fetch(url, {\n method: 'POST',\n signal,\n headers: {\n 'Content-Type': 'application/json',\n ...(options.revalidateHeaders ?? {}),\n },\n body: JSON.stringify({ source: 'payload-live-preview' }),\n });\n if (!isActive() || signal.aborted) return;\n ok = response.ok;\n if (!ok) log('document-save revalidate non-2xx:', response.status);\n } catch (err) {\n if (!isActive() || signal.aborted) return;\n log('document-save revalidate failed:', err);\n }\n if (!ok && options.onRevalidateFailure === 'reload') {\n reloadPreservingScroll();\n }\n}\n","/**\n * Typed binding helpers — emit the `data-payload-field` attribute pair\n * that the live-preview runtime reads, with compile-time validation\n * of the field name.\n *\n * Two forms are exposed:\n *\n * - **`bind<Schema>('heroTitle')`** — string-literal form. Lightest\n * possible runtime (no Proxy), but a rename in the IDE does NOT\n * follow into the string.\n * - **`bindByPath<Schema>(s => s.heroTitle)`** — proxy form. The\n * callback walks a Proxy that records the access path, returning\n * the same shape as `bind` so the two are interchangeable. Slightly\n * heavier runtime, but rename-safe and discourages typos.\n *\n * Both helpers also accept a richer return — `bind('image', 'src')` —\n * to bind an attribute other than the default `data-payload-field`,\n * matching the cache resolver's `data-payload-attribute` flow.\n *\n * @module @dsl/bind\n */\n\nimport type { FieldName } from './paths';\n\n/**\n * Shape returned by every binding helper — a spreadable HTML attribute\n * record. Astro / JSX / Svelte all accept this style directly:\n *\n * ```astro\n * <h1 {...bind<Homepage>('heroTitle')}>{data.heroTitle}</h1>\n * ```\n */\nexport interface FieldBindingAttributes {\n readonly 'data-payload-field': string;\n readonly 'data-payload-attribute'?: string;\n readonly 'data-payload-type'?: string;\n readonly 'data-payload-richtext'?: string;\n readonly 'data-payload-html'?: string;\n readonly 'data-payload-locale'?: string;\n}\n\nexport interface BindOptions {\n /** Override the bound attribute (e.g., `'src'` for `<img>`). Default: textContent. */\n readonly attribute?: string;\n /** Explicit field-type override — bypasses schema detection. */\n readonly type?: string;\n /**\n * Mark the binding as Lexical rich text. Usually detected automatically;\n * set it where the initial render is empty and there is nothing to detect.\n */\n readonly richtext?: boolean;\n /** Render the value as sanitised HTML rather than text. */\n readonly html?: boolean;\n /** Lock this element to one locale, overriding the message locale. */\n readonly locale?: string;\n}\n\n/**\n * String-literal binding helper.\n *\n * ```ts\n * import { bind } from 'payload-live-preview';\n * import type { Homepage } from './payload-types';\n *\n * <h1 {...bind<Homepage>('heroTitle')}>{data.heroTitle}</h1>\n * <img {...bind<Homepage>('heroImage', { attribute: 'src' })} />\n * ```\n *\n * The generic `T` is the schema interface emitted by `pll-codegen`.\n * `field` is constrained to `keyof T` so misspellings fail at compile\n * time. When `T` is omitted, the helper accepts any string — useful\n * for incremental adoption.\n */\nexport function bind<T = Record<string, unknown>>(\n field: FieldName<T>,\n options?: BindOptions,\n): FieldBindingAttributes {\n return buildAttributes(field, options);\n}\n\n/**\n * Proxy-path binding helper.\n *\n * ```ts\n * <h1 {...bindByPath<Homepage>(d => d.heroTitle)}>{data.heroTitle}</h1>\n * ```\n *\n * The picker is invoked once with a recording Proxy; the recorded path\n * is joined with `.` and emitted as the binding name. Property access\n * on nested objects and arrays both work — `d => d.slides[0].title`\n * becomes `slides.title` (array indices are normalised away because the\n * runtime resolves bindings against schema, not against positional\n * indices).\n */\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters\nexport function bindByPath<T = Record<string, unknown>>(\n picker: (data: T) => unknown,\n options?: BindOptions,\n): FieldBindingAttributes {\n const path = recordPath(picker);\n if (path.length === 0) {\n throw new Error(\n 'bindByPath: the picker did not read any field — return data.<field> instead of a constant',\n );\n }\n return buildAttributes(path.join('.'), options);\n}\n\nfunction buildAttributes(field: string, options: BindOptions | undefined): FieldBindingAttributes {\n if (field.length === 0) {\n throw new Error('bind: field name must be a non-empty string');\n }\n // A binding is one unit: the field and every companion that describes it are\n // built together so a caller cannot emit half of one.\n const attrs: {\n 'data-payload-field': string;\n 'data-payload-attribute'?: string;\n 'data-payload-type'?: string;\n 'data-payload-richtext'?: string;\n 'data-payload-html'?: string;\n 'data-payload-locale'?: string;\n } = { 'data-payload-field': field };\n if (options?.attribute !== undefined) attrs['data-payload-attribute'] = options.attribute;\n if (options?.type !== undefined) attrs['data-payload-type'] = options.type;\n // Presence attributes: the runtime tests for the attribute, not its value.\n if (options?.richtext === true) attrs['data-payload-richtext'] = '';\n if (options?.html === true) attrs['data-payload-html'] = '';\n if (options?.locale !== undefined) attrs['data-payload-locale'] = options.locale;\n return attrs;\n}\n\nfunction recordPath(picker: (data: never) => unknown): string[] {\n const path: string[] = [];\n const proxy: unknown = new Proxy(\n {},\n {\n get(_target, prop: string | symbol): unknown {\n if (typeof prop === 'symbol') return undefined;\n // Arrays surface numeric indices when iterated — skip those.\n if (/^\\d+$/.test(prop)) return proxy;\n path.push(prop);\n return proxy;\n },\n },\n );\n try {\n picker(proxy as never);\n } catch {\n // Pickers can throw when they attempt math/JSX on the proxy. We\n // still keep whatever path was recorded up to that point — that's\n // typically the binding the user intended.\n }\n return path;\n}\n","/**\n * Authorization-gated binding emission.\n *\n * Binding attributes are not neutral markup. `data-payload-field` names a CMS\n * field, and `data-payload-owner` names a global, a collection and often a\n * document id. Emitted unconditionally they publish the shape of the content\n * model — and the identity of documents — to every anonymous visitor and\n * crawler of the page.\n *\n * The gate belongs to the application, not to this package: it is the same\n * decision that already controls draft reads and cache policy. What this\n * module provides is a place to apply that decision **once per request** so no\n * individual call site can forget it, and an emission unit that cannot be\n * partially suppressed.\n *\n * That second property matters more than it looks. A binding is not one\n * attribute: a field travels with its type, its locale, its rich-text marker\n * and its owner. Gating only the field name leaves the companions behind,\n * which discloses the taxonomy anyway and leaves the runtime looking at a\n * binding whose field is gone.\n *\n * @module @dsl/preview-bindings\n */\n\nimport { bind, bindByPath, type BindOptions, type FieldBindingAttributes } from './bind';\nimport type { FieldName } from './paths';\n\n/** Owner marker naming the document a subtree belongs to. */\nexport interface OwnerBindingAttributes {\n readonly 'data-payload-owner': string;\n}\n\n/**\n * The complete absence of binding attributes.\n *\n * Spreading this into markup contributes nothing, which is the point: an\n * unauthorized response must be byte-identical to one that never knew about\n * live preview.\n */\nexport type SuppressedBinding = Readonly<Record<string, never>>;\n\nconst SUPPRESSED: SuppressedBinding = Object.freeze({});\n\nexport interface PreviewBindingsOptions {\n /**\n * The application's own authorization verdict for this request.\n *\n * Never derive this from `?preview=true`, an iframe destination or a\n * referer — those are client-controlled intent signals. Use the same\n * verified result that decides whether drafts may be read.\n */\n readonly authorized: boolean;\n /**\n * Document this subtree belongs to, emitted as `data-payload-owner` by\n * {@link PreviewBindings.owner}. Required only when the page previews more\n * than one document and the runtime runs with `scopeBindingsByOwner`.\n */\n readonly owner?: string;\n}\n\n/** Request-scoped binding helpers that carry one authorization decision. */\nexport interface PreviewBindings {\n /** The verdict these helpers were built with. */\n readonly authorized: boolean;\n /** Typed field binding, or nothing at all while unauthorized. */\n bind: <T = Record<string, unknown>>(\n field: FieldName<T>,\n options?: BindOptions,\n ) => FieldBindingAttributes | SuppressedBinding;\n /** Rename-safe field binding, or nothing at all while unauthorized. */\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters\n bindByPath: <T = Record<string, unknown>>(\n picker: (data: T) => unknown,\n options?: BindOptions,\n ) => FieldBindingAttributes | SuppressedBinding;\n /**\n * Owner marker for the element that owns this subtree, or nothing at all\n * while unauthorized or when no owner was configured.\n */\n owner: () => OwnerBindingAttributes | SuppressedBinding;\n}\n\n/**\n * Build request-scoped binding helpers around one authorization decision.\n *\n * ```ts\n * const preview = createPreviewBindings({\n * authorized: authorization !== null,\n * owner: `global:${slug}`,\n * });\n * ```\n * ```astro\n * <section {...preview.owner()}>\n * <h1 {...preview.bind<Homepage>('heroTitle')}>{data.heroTitle}</h1>\n * </section>\n * ```\n *\n * While unauthorized every helper returns an empty attribute set, so the\n * public response carries no `data-payload-*` at all.\n */\nexport function createPreviewBindings(options: PreviewBindingsOptions): PreviewBindings {\n const { authorized } = options;\n const owner = options.owner !== undefined && options.owner.length > 0 ? options.owner : undefined;\n\n return Object.freeze({\n authorized,\n bind: <T = Record<string, unknown>>(\n field: FieldName<T>,\n bindOptions?: BindOptions,\n ): FieldBindingAttributes | SuppressedBinding =>\n authorized ? bind<T>(field, bindOptions) : SUPPRESSED,\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters\n bindByPath: <T = Record<string, unknown>>(\n picker: (data: T) => unknown,\n bindOptions?: BindOptions,\n ): FieldBindingAttributes | SuppressedBinding =>\n authorized ? bindByPath<T>(picker, bindOptions) : SUPPRESSED,\n owner: (): OwnerBindingAttributes | SuppressedBinding =>\n authorized && owner !== undefined ? { 'data-payload-owner': owner } : SUPPRESSED,\n });\n}\n"],"mappings":"2EAgBaA,ECdA,QCuBAC,EAAkB,qBAClBC,EAAiB,oBACjBC,EAA6B,yBAC7BC,EAAiB,oBACjBC,EAAgB,mBAChBC,EAAgB,mBAChBC,EAA2B,8BAC3BC,EAA4B,+BAC5BC,EAAmB,sBACnBC,EAAsB,wBACtBC,EAAiB,oBACjBC,EAAkB,qBAClBC,EAAuB,0BACvBC,EAAkB,qBAUlBC,EAAwC,CACnDd,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAvBkC,QA2B9BE,EAAiB,IAAIf,KACrBgB,EAAiB,IAAIH,KAUpB,SAASI,EAAoBC,GAClC,IAAMC,EAAQD,EAAQE,QAAQJ,IAAiBK,aAAaR,GAC5D,OAAiB,MAAVM,GAA0D,IAAjBA,EAAMG,YAAe,EAAYH,CACnF,CAHgBI,EAAAN,EAAA,uBAKhB,IAAMO,EAA4C,IAAIC,IAAe,CACnE,OACA,WACA,WACA,QACA,SACA,WACA,OACA,SACA,QACA,QACA,SACA,QACA,OACA,MACA,cACA,eACA,SACA,QACA,OACA,OACA,KACA,OACA,MACA,QACA,qBAwBWC,EAAN,aAAmBH,EAAAI,KAAA,gBACfC,GAAW,IAAIC,IACxBC,GAAkB,IAAIC,QACbC,GAET,WAAAC,CAAYC,EAA+B,IACzCP,MAAKK,EAAUE,EAAQC,QAAUC,CACnC,CAOA,aAAAC,CAAcC,GACZ,IAAMC,EAAKC,YAAYC,MACvBd,KAAKe,QAEL,IAAMC,EAAWL,EAAKM,iBAAiB7B,GACnC8B,EAAe,EACnB,QAAW3B,KAAWyB,OACM,IAAtBhB,KAAKmB,IAAI5B,KAAwB2B,GAAgB,GAGvD,MAAO,CACLA,eACAE,WA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,QACtC,IAArB6tB,EAAgC/hB,QAAQC,eAAe7O,MAAKqwB,EAASvtB,GACpE9C,MAAKqwB,EAAQvtB,GAAa6tB,EAEnC,GDhCIE,GAAoC,IAAI/wB,IAAI,CAChD,IACA,KACA,SACA,IACA,KACA,IACA,IACA,IACA,SACA,OACA,QACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,aACA,OACA,MACA,MACA,OACA,MACA,IACA,OACA,MACA,UACA,UACA,QACA,SACA,SACA,MACA,SACA,aACA,MACA,UACA,SACA,QACA,QACA,MACA,MACA,KACA,OACA,OACA,OACA,IACA,QACA,QACA,QACA,QACA,KACA,KACA,KACA,UACA,WACA,QAQIgxB,GAAyC,IAAIhxB,IAAI,CACrD,SACA,QACA,SACA,SACA,QACA,OACA,OACA,OACA,OACA,QACA,SACA,SACA,WACA,MACA,OACA,WACA,QACA,WACA,WACA,aAGIixB,GAAmC,IAAIjxB,IAAI,CAC/C,KACA,QACA,OACA,MACA,QACA,OACA,aAMIkxB,GAA6D,CACjE/Y,EAAG,IAAInY,IAAI,CAAC,OAAQ,SAAU,MAAO,WAAY,WAAY,SAC7DmxB,IAAK,IAAInxB,IAAI,CAAC,MAAO,SAAU,QAAS,MAAO,QAAS,SAAU,UAAW,aAC7EoxB,QAAS,IAAIpxB,IAAI,IACjBqxB,OAAQ,IAAIrxB,IAAI,CAAC,MAAO,SAAU,QAAS,OAAQ,UACnDsxB,MAAO,IAAItxB,IAAI,CAAC,MAAO,WAAY,WAAY,OAAQ,QAAS,YAChEuxB,MAAO,IAAIvxB,IAAI,CACb,MACA,SACA,WACA,WACA,OACA,QACA,UACA,QACA,SACA,gBAEFwxB,KAAM,IAAIxxB,IAAI,CAAC,aACfyxB,KAAM,IAAIzxB,IAAI,CAAC,UACf0xB,EAAG,IAAI1xB,IAAI,CAAC,SACZ2xB,WAAY,IAAI3xB,IAAI,CAAC,SACrB4xB,MAAO,IAAI5xB,IAAI,CAAC,YAChB6x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,CACV2uC,EACAS,IAEAD,EAAaT,GAAcC,EAAQS,GAAeH,GAJxC,cAKZrvC,MAAOI,EAAA,IACLmvC,QAAwB,IAAVvvC,EAAsB,CAAE,qBAAsBA,GAAUqvC,GADjE,UAGX,CApBgBjvC,EAAAkvC,GAAA,gCAAAG,uBAAAC,mBAAAC,8BAAAC,wBAAAC,qBAAAC,aAAAC,WAAAC,iBAAAC,8BAAAC,4BAAAC,0BAAAC,8BAAAC,4BAAAC,4BAAAC,kBAAAC,0BAAAC,yBAAAC,iBAAAC,0BAAAC,2BAAAC,yBAAAzxB,uBAAA0xB,2BAAAC,mBAAAC,sBAAAC,sBAAAC,gBAAAC,wBAAAC,iBAAAC,gBAAAC,yBAAAC,uBAAAC,uBAAAC,gBAAAC,oBAAAC,yBAAAC,qBAAAC,uBAAAC,4BAAAC,8BAAAC,uBAAArjC,mBAAAsjC,mBAAAC,2BAAAC","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["VERSION","detectInitialLocale","document","lang","documentElement","getAttribute","length","readHtmlLang","navigator","language","readNavigatorLanguage","ELEMENT_ID","documentLeases","WeakMap","clearLeaseMessage","lease","timer","clearTimeout","messageNode","remove","A11yAnnouncer","german","constructor","locale","targetDocument","activeDocument","documentLocale","this","test","isGerman","mount","body","get","element","owned","refs","set","acquireDocumentLease","leased","isConnected","ownerDocument","getElementById","createElement","id","setAttribute","appendChild","announceConnected","say","announceDisconnected","announceUpdate","count","String","detach","delete","message","parentNode","createTextNode","hasChildNodes","data","previousSibling","setTimeout","parseFieldSchema","raw","Array","isArray","out","entry","parsed","parseFieldEntry","push","value","record","name","type","fields","blocks","slug","parseBlockSchema","result","STRUCTURAL_TYPES","Set","buildSchemaIndex","schemas","basePath","Map","walk","schema","has","path","block","getId","item","getBlockType","blockType","diffArray","prev","next","every","patches","prevIndexById","i","consumedFromPrev","to","kind","index","from","add","prevItem","shallowEqual","oldValue","diffById","min","Math","diffByPosition","a","b","Object","is","aRec","bRec","aKeys","keys","bKeys","key","MAP","text","textarea","richText","email","number","checkbox","date","select","radio","array","group","tabs","row","collapsible","relationship","upload","point","json","code","ui","SAFE_PROTOCOLS","DANGEROUS_PROTOCOL_PATTERN","RELATIVE_PATH","PROTOCOL_RELATIVE","PARSER_IGNORED","isSafeUrl","url","trimmed","trim","replace","startsWith","URL","protocol","isExternalHttpUrl","BLOCKED_ATTRIBUTES","URL_ATTRIBUTES","noWriteCallbacks","WeakSet","markNoWriteCallback","callback","valueIdentity","JSON","stringify","FieldChangeTracker","previous","diff","dependencies","changed","entries","identity","invalidated","source","dependents","dependent","reset","LIBRARY_PROTOCOL_VERSION","CAPABILITY_DECLARATIONS","basic","since","observed","PROTOCOL_CAPABILITIES","negotiateProtocol","theirs","sanitisedTheirs","Number","isFinite","floor","effectiveTheirs","negotiated","seen","capabilities","capability","ours","hasCapability","negotiation","ProtocolTracker","observe","log","fresh","filter","join","applyVersion","remoteVersion","current","prefersReducedMotion","win","matchMedia","matches","FieldRevealer","lastField","reveal","fieldName","rect","getBoundingClientRect","vertically","bottom","top","innerHeight","horizontally","right","left","innerWidth","isInViewport","scrollIntoView","behavior","revealElement","sameRevision","generation","revision","RuntimeState","started","suspended","deferredStart","activeUpdate","schemaIndex","updateCount","supersededCount","completedCount","skippedUnchangedCount","lastFlush","absentFields","warnedOrphanFields","warnedStrategy","warnedUnattributableMessage","warnedVisibilityGate","warnedFragmentFallback","lastAppliedIdentity","seenFieldIdentity","fragmentStats","rendered","failed","superseded","routeStats","refreshes","loopStopped","fragmentController","routeController","readyTimers","revealer","changes","isRunning","isCurrent","transaction","complete","completed","abortStrategies","controller","abort","BindingWriter","deps","state","apply","update","target","schemaEntry","fieldPath","wildcardPath","lookupSchema","renderer","schemaType","explicitFieldType","fieldType","mapped","prototype","hasOwnProperty","call","payloadTypeToRenderer","resolveFieldType","root","children","looksLikeLexicalRoot","resolveRenderer","error","fail","emitElementUpdate","emitter","listenerCount","tagName","src","textContent","context","allFields","renderRichText","boundary","toggleAttribute","isEmptyFieldValue","targetAttribute","attribute","toLowerCase","removeAttribute","stringValue","applyAttributeBinding","warn","outcome","render","invokeRenderer","rendererUsesNoWriteOutcome","emitWhile","previousValue","nextValue","receivedAt","applied","cause","Error","mergeDependencyMaps","maps","merged","map","bucket","dependencyMapFromBinding","dependsOn","ISLAND_EVENT","ISLAND_ATTRIBUTE","ISLAND_SELECTOR","isIslandRoot","hasAttribute","islandAllowsPatching","island","isInsideIsland","parentElement","enclosingFragment","closest","resolveStrategy","explicit","FIELD_ATTRIBUTE","TYPE_ATTRIBUTE","TARGET_ATTRIBUTE_ATTRIBUTE","HREF_ATTRIBUTE","SRC_ATTRIBUTE","ALT_ATTRIBUTE","ARRAY_TEMPLATE_ATTRIBUTE","ARRAY_SEPARATOR_ATTRIBUTE","LOCALE_ATTRIBUTE","RICH_TEXT_ATTRIBUTE","HTML_ATTRIBUTE","ARRAY_ATTRIBUTE","STRUCTURAL_ATTRIBUTE","OWNER_ATTRIBUTE","DEPENDS_ATTRIBUTE","STRATEGY_ATTRIBUTE","BOUNDARY_ATTRIBUTE","BINDING_ATTRIBUTES","FIELD_SELECTOR","OWNER_SELECTOR","CUSTOM_RENDERER_KEY","VALID_FIELD_TYPES","isRendererKey","ElementCache","entriesByField","entryByElement","islandRoots","options","alwaysTrue","dependencyMap","binding","values","islands","buildFromRoot","t0","performance","now","clear","elementCount","querySelectorAll","collectIslands","fieldCount","size","durationMs","resolveBinding","replaceEntry","removeEntry","append","getByElement","indexOf","splice","hrefField","srcField","altField","arrayTemplate","arraySeparator","owner","resolveBindingOwner","names","split","parseDependencyList","strategy","fragmentBoundary","strategyKind","inputType","observeThenableResult","then","Promise","resolve","catch","isolateDiagnostic","diagnostic","args","noopDiagnostic","safeConsoleError","console","safeConsoleWarn","safeConsoleDebug","debug","hasControlCharacter","character","codePoint","codePointAt","isSafeSlug","includes","encodeURIComponent","DataMerger","serverURL","apiRoute","depth","fetchFn","inflight","attempt","destroyDepth","route","canMerge","request","globalSlug","collectionSlug","isSafeId","merge","status","fetch","AbortController","endpoint","response","method","credentials","headers","flattenLocales","signal","isAborted","ok","doc","destroy","aborted","PAYLOAD_2","fieldTyping","populatesRelationships","documentEvents","PAYLOAD_3","UNKNOWN","detectProtocolProfile","optionalFieldOk","check","optionalTypeOk","isPlainObject","getPrototypeOf","NULL_AS_ABSENT_FIELDS","MessageBus","matcher","handlers","boundListener","attachedTarget","queue","queueHead","attach","window","committed","listener","event","receive","origin","reportInvalid","resetQueue","addEventListener","removeEventListener","advanceGeneration","sendReady","targets","origins","payload","ready","protocolVersion","postMessage","isCurrentGeneration","matchesOrigin","matchesSource","v","x","isLivePreviewMessage","dispatchUpdate","normalized","field","Reflect","deleteProperty","fieldSchemaJSON","normalizeLivePreviewMessage","isDocumentEventMessage","invokeHandler","onDocumentEvent","focusFieldOf","onFocusField","hasUpdateData","messageRevision","validator","validateToken","commitUpdate","pending","settled","approved","verdict","previewToken","settleValidation","drainQueue","dequeue","onUpdate","reason","onInvalid","sourcePolicy","parent","opener","handler","expected","slice","ObserverManager","callbacks","debounceMs","rootMargin","visible","mutation","intersection","debounceTimer","mutationDebounceMs","intersectionRootMargin","start","previousGeneration","stop","MutationObserver","mutations","handleMutations","IntersectionObserver","handleIntersection","threshold","childList","subtree","attributes","attributeFilter","disconnect","observeElement","unobserveElement","unobserve","markVisible","isVisible","m","attributeName","nodeType","node","addedNodes","containsTrackedElement","removedNodes","hasStructuralImpact","onStructuralChange","isIntersecting","onVisibilityChange","querySelector","HeartbeatTimer","timeoutMs","onTimeout","handle","lastKick","kick","Date","lastKickAt","ConnectionState","markConnected","transition","markDisconnected","collectionOwnerKey","documentId","nonEmpty","isBindingInScope","readDocumentId","BLOCKED_KEYS","resolveFieldValue","preferLocale","localized","readOwn","direct","resolved","segment","object","SYSTEM_FIELD_NAMES","hasAddressableBinding","cache","ownerKeys","bindings","some","localisedBindingNames","isBindableScalar","stripLocaleSuffix","suffix","endsWith","policyOverride","autoPolicy","TRUSTED_TYPES_POLICY_NAME","setTrustedTypesPolicy","policy","trustedHtml","html","api","candidate","globalThis","trustedTypes","createPolicy","factory","createHTML","input","resolvePolicy","STATE_ATTRIBUTES","keyOf","keyAttributes","isMorphBoundary","editable","morphElement","live","namespaceURI","isMorphCompatible","focus","active","activeElement","HTMLElement","contains","selection","HTMLInputElement","HTMLTextAreaElement","selectionStart","selectionEnd","captureFocus","syncAttributes","retainChildrenOf","liveKeyed","keyed","duplicate","child","onDuplicateKey","indexKeyed","keyedElements","liveUnkeyed","childNodes","claimed","usedKeys","renderedNodes","cursor","firstChild","unkeyedIndex","kept","Element","reconcile","replaceWith","nextSibling","sameKind","replaceChild","following","isBlankText","insertBefore","morphChildren","snapshot","preventScroll","end","setSelectionRange","restoreFocus","nodeValue","Node","TEXT_NODE","documentOverride","ALLOWED_TAGS","FORM_CONTROLS","REMOVE_COMPLETELY","ATTR_GLOBAL","ATTR_ARIA_PREFIX","ATTR_DATA_PREFIX","ATTR_BY_TAG","img","picture","audio","video","time","abbr","q","blockquote","table","th","td","col","colgroup","ol","li","pre","SanitizerEnvironmentError","TEMPLATE_ATTRIBUTES","defaultMode","setSanitizerPolicy","mode","setSanitizerDocument","sanitizeHtml","resolveDocument","__INLINE_BUILD__","attrMap","tag","attrs","allowedTags","attrByTag","allowFormControls","templateMode","allowedData","allowed","additionalAllowedTags","additionalAllowedAttributes","existing","attr","allowedDataAttributes","template","innerHTML","sanitizeFragment","content","sanitizeElement","tagAttrs","isSafeSrcset","sanitizeAttributes","anchor","href","hardenAnchor","descriptorStart","search","HTML_ESCAPES","freeze","HTML_ESCAPE_PATTERN","escapeHtml","char","ATTR_ESCAPES","ATTR_ESCAPE_PATTERN","escapeHtmlAttribute","PLACEHOLDER_PATTERN","interpolateArrayTemplate","placeholder","hasOwn","safeStringify","isEmptyValue","TEMPLATE_EXTRA_TAGS","TEMPLATE_EXTRA_ATTRIBUTES","CUSTOM_TAG_PATTERN","optionsByTemplate","templateSanitizeOptions","cached","tags","match","matchAll","KEY_ATTRIBUTE","NESTED_KEY_ATTRIBUTE","NESTED_TEMPLATE_ATTRIBUTE","applyStructuralPatches","container","nextItems","store","forceRender","plan","prepareStructuralPlan","commitStructuralPlan","morph","isManagedNestedSlot","_live","memory","initialChildren","keyedChildren","indexByAttribute","reserved","readKey","takeIndexedElement","replaces","renders","renderItem","nestedSlots","prepareNestedSlots","prepareReconciliation","patch","createPatchPlan","mutated","retained","liveSlot","renderedSlot","synchronizeAttributes","before","getMemory","rememberItem","oldItem","newItem","oldSlotsByKey","findDirectNestedSlots","itemKey","prevValue","plans","newSlot","oldSlot","nextTemplate","previousTemplate","nextNested","readNestedArray","resolvedNext","templateChanged","slot","ancestor","nested","elements","indexed","pop","safe","host","first","firstElementChild","StrategyRunner","planFragments","touched","strategies","fragment","boundaries","covered","covers","hasRouteBinding","runFragments","detail","cloneNode","morphFragment","patchFallback","pendingFragments","report","scheduler","pendingCount","revealPending","updatedCount","refreshRoute","stats","routeRefreshed","refresh","rebuildCache","reapply","warnFragmentFallback","warnUnsupportedStrategy","schedule","transform","UpdatePipeline","scheduleAllFields","transformForBinding","handleUpdate","heartbeat","externallyUpdatedRelationship","observeCapabilities","relationshipEdited","emit","timestamp","revealTarget","revealIdentities","cancelled","acceptRevision","connection","a11y","processUpdate","resolveIncomingFields","cancel","cancelRevision","merger","ownerKeysForUpdate","trackIdentity","skipUnchanged","scheduled","revealEditedField","noteRevealCandidate","rawValue","transformed","bindingIdentity","last","warned","ownsAnyBinding","localisedNames","rawName","baseName","diagnoseOrphanFields","scopeBindingsByOwner","collectionKey","messageOwnerKeys","originalValue","transformValue","returnedThenable","TypeError","err","onFlush","deferred","dispatchEvent","CustomEvent","bubbles","dispatchIslandUpdate","revealBinding","revealField","defaultView","own","siblings","combined","sibling","UpdateScheduler","maxWaitMs","gateThresholdValue","gateDisabled","getCacheSize","scheduleFrame","cancelFrame","replay","activeFlushes","debounceToken","deadlineTimer","frameHandle","frameToken","activeIdentity","activeRevisionCancelled","visibilityGateThreshold","disableVisibilityGate","requestAnimationFrame","bind","cancelAnimationFrame","sameIdentity","armDebounce","cancelScheduledWork","clearWork","flushNow","flush","notifyVisible","didApply","statsFor","retarget","retargetBuffer","forget","replayCount","gateThreshold","gateActive","token","requestFrame","clearDeadline","appliedFields","batchEntry","buffer","READY_RETRY_DELAYS_MS","LivePreviewRuntime","pipeline","writer","rootSentinel","observedRoot","renderers","observers","bus","originMatcher","eventSourcePolicy","dataMerge","heartbeatMs","onHeartbeatTimeout","readyTargets","defaultSendReady","createA11y","lockedOrigin","isDocumentRoot","readyState","onReady","startNow","rollbackFailedStart","reportError","once","observerRoot","readDocumentBody","watchRootReplacement","buildCacheAndObserve","delay","sendReadyAfterStart","suspend","wasConnected","release","runCleanup","cleanup","refreshCache","followReplacedRoot","inspect","fieldNames","owners","version","trusted","locked","sort","profile","revisions","accepted","skippedUnchanged","orphanFields","ownerScoped","fragments","inFlight","visibilityGateActive","plugins","buildInspection","removed","isIdleDisconnected","enableA11y","a11yLocale","Window","EventEmitter","regular","on","register","off","emitSequential","shouldContinue","eligible","invoke","removeAllListeners","eventNames","label","isInIframe","self","isInPopup","isInPreviewContext","isDevMode","nodeEnv","process","env","readNodeEnv","location","hostname","LOCALHOST_PATTERN","VALID_ORIGIN_PATTERN","LOCALHOST_HANDSHAKE_PORTS","OriginDetector","additionalOrigins","normalised","normaliseOrigin","referrerOrigin","enableReferrerDetection","referrer","allowLocalhost","enableLocalhostMatching","forceDevMode","lockOrigin","unlockOrigin","enumerate","port","referrerWasAvailable","isProductionUnconfigured","isReferrerOnlyTrust","noopDisposer","ResourceScope","pluginName","resources","assertOpen","track","acquire","finalize","disposed","stage","resource","dispose","activate","counts","subscription","commit","close","reverse","ScopedPluginEvents","events","scope","subscriptions","subscribe","untypedHandler","callerEligible","find","subscriptionActive","wrapped","async","PluginManager","config","registerRenderer","onTransformError","initializing","teardowns","destroying","transforms","mutationQueue","queuedHooks","registerFieldRenderer","plugin","registerNow","enqueue","unregister","unregisterNow","destroyAll","destroyAllNow","applyTransforms","registrations","registration","list","describe","cleanups","queued","incompatibility","compat","runtimeVersion","runtime","range","exec","parseVersion","alternative","comparators","part","comparator","operator","order","delta","compare","satisfiesComparator","satisfiesRange","isInteger","incompatibilityOf","refuse","createContext","runHook","init","registerTransform","registerCleanup","getConfig","existingTeardown","holdQueue","teardown","destroyPlugin","hook","operation","RendererRegistry","base","layers","layer","stack","wasTop","previousLayer","at","previousRenderer","ALIGNMENT_NUMERIC","ALIGNMENT_STRING","resolveAlignment","fmt","format","resolveIndent","indent","dirAttribute","direction","layoutClassAttribute","align","classes","VALID_TAGS","asRecord","readMedia","sanitizeIdent","pickRelationLabel","title","BLANK_TARGET","linkRenderer","ctx","renderChildren","internalUrl","resolveUrl","titleAttr","extractText","dimensionAttributes","width","height","typeAttribute","mimeType","registry","registerBlockRenderer","lookupBlockRenderer","renderBlockNode","baseClass","custom","spanAttribute","BUILTIN_NODE_RENDERERS","paragraph","heading","tagRaw","listType","startAttr","checkAttr","listitem","valueAttr","link","autolink","quote","linebreak","horizontalrule","tab","mime","renderVideo","renderAudio","alt","renderImage","filename","renderFallbackLink","relationTo","classAttr","inlineBlock","tablerow","tablecell","header","RENDER_CONTEXT","warnedNoSanitizer","isLexicalContent","lexicalToHtml","sanitize","warnNoSanitizerOnce","lexicalToPlainText","extractPlainText","renderNode","createTextRenderer","warnedElements","toPlainString","hasForeignChildren","warnOnce","escapeAndLinebreak","richTextRenderer","htmlRenderer","acceptUrl","createLinkRenderer","toHref","urlRenderer","HAS_SCHEME","emailRenderer","IMAGE_SOURCE_ATTRIBUTES","clearImage","writeImage","media","srcset","sizes","candidates","srcsetUrl","buildSrcset","imageRenderer","pickSource","pickAlt","style","backgroundImage","escapeCssUrl","uploadRenderer","relationshipRenderer","selectRenderer","toValues","checked","option","labelFor","multiple","selected","writeSelect","FALSE_STRINGS","checkboxRenderer","toBoolean","NUMBER_CACHE","DATE_CACHE","buildKey","localePart","serialised","stableStringify","parts","inner","trimToLimit","oldest","dateRenderer","valid","isNaN","getTime","fallback","toISOString","formatter","Intl","DateTimeFormat","getDateTimeFormat","dateStyle","timeStyle","formatDate","day","getFullYear","padStart","pad","getMonth","getDate","clock","getHours","getMinutes","formatForInput","numberRenderer","num","NumberFormat","getNumberFormat","arrayRenderer","items","renderTemplate","createStructuralArrayRenderer","states","warnedContainers","warnedKeys","warnMissingTemplate","previousState","domSnapshot","readDomKeySnapshot","position","__payloadDomPosition","sameDomKeySnapshot","needsForcedRender","nextKeys","warnDuplicateKey","previousKeys","stable","warnAboutKeys","codes","builtinRenderers","registerBuiltinRenderer","buildBuiltinRenderers","stateless","defaults","definedOnly","V2_RUNTIME_DEFAULTS","disableReferrerDetection","sanitizerPolicy","V1_RUNTIME_DEFAULTS","invert","LivePreviewClient","detector","rendererRegistry","destroyed","tornDown","destroyPromise","rawConfig","rows","withProfileDefaults","mergeDepth","allowedOrigins","disableLocalhostMatching","mergeFetch","e","autoStart","resume","resolveDestroy","rejectDestroy","reject","finish","finally","use","unuse","initLivePreview","client","reportPreviewFocus","targetOrigin","createPreviewFocusReporter","resolveTarget","bindNavigationLifecycle","windowTarget","documentTarget","softEvents","softNavigationEvents","onPageHide","onPageShow","persisted","onSoftNavigation","unbound","DIAGNOSTIC_CODES","NoTrustedOrigin","ReferrerOnlyTrust","PluginIncompatible","OrphanField","UnattributableUpdate","VisibilityGateDeferred","UnsafeAttributeWrite","TextTargetHasChildren","MissingArrayTemplate","StructuralItemUnkeyed","StructuralDuplicateKey","StructuralUnstableKeys","UnsupportedStrategy","MessageRejected","TokenRejected","HandlerThrew","TransformThrew","RendererThrew","StartupFailed","ReadyFailed","AuditRuntimeMissing","AuditNoFrameAncestors","AuditFrameOptionsBlocks","AuditBindingsExposed","AuditGateThresholdExceeded","AuditUnownedBindings","AuditNoBindings","AuditNotAPage","FragmentRequestFailed","FragmentResponseInvalid","FragmentUnauthorized","FragmentSuperseded","RouteRefreshLoop","FragmentStrategyUnavailable","V2ReadinessGap","RuntimeOnPublicPage","RUNTIME_SOURCE","RUNTIME_BUILD_INFO","generatedAt","FRAGMENT_SOURCE","INLINE_CONFIG_KEYS","assertBuilt","artifact","generateInlineScript","configStatement","fragmentPrelude","fragmentEndpoint","buildConfigLiteral","wrapWithScriptTag","nonce","RangeError","escapeNonce","runtimeBuildInfo","cryptoOverride","CSP_ASCII_WHITESPACE","isCspWhitespace","charCodeAt","trimCspWhitespace","asciiLowercase","setCspCrypto","crypto","generateCspNonce","bytes","getRandomValues","fromGlobal","resolveCrypto","Uint8Array","binary","byte","fromCharCode","btoa","Buffer","toString","replaceAll","base64UrlEncode","buildFrameAncestors","allowNone","buildScriptSrcWithNonce","extra","strictDynamic","mergeCspHeader","additions","policies","mergeCspPolicy","directives","whitespaceIndex","rawAddition","addition","withoutNone","AUTHORIZED_PREVIEW_BRAND_KEY","BRAND","Symbol","for","isAuthorizedPreviewContext","isFrozen","createAuthorizedPreviewContext","payloadHeaders","PreviewConfigurationError","refused","authorized","DEFAULT_USERS_SLUG","COOKIE_NAME_PATTERN","COOKIE_VALUE_PATTERN","cachedEncoder","DEFAULT_PURPOSE","TOKEN_VERSION","encoder","TextEncoder","secretBytes","secret","encode","byteLength","cryptoFor","configured","subtle","hmacKey","importKey","hash","toBase64Url","fromBase64Url","padded","repeat","atob","issuePreviewToken","claims","ttl","max","ttlMs","wire","aud","audience","pth","loc","subject","sub","pur","purpose","iat","exp","jti","signed","sign","authorizePreviewRequest","cookieName","cookieNameFor","serverOriginFor","maxLength","prefix","extractCookie","maxCookieLength","fetchImpl","usersSlug","forwarded","cookie","accept","AbortSignal","timeout","user","collection","readUser","expiresAt","readExpiry","authorizedAt","authorizeSession","transport","searchParams","getAll","param","readToken","payloadText","payloadBytes","signature","verified","verify","parse","TextDecoder","decode","c","optionalString","parseClaims","pathname","isUsed","markUsed","authorizeToken","authorizeVerifier","DEFAULT_QUERY_PARAMS","hasPreviewIntent","signals","queryParams","adminOrigins","referer","refererOrigin","adminOrigin","STYLE_ID","styleLeases","highlightLeases","highlightPlugin","releaseStyle","connected","css","HTMLStyleElement","pluginOwned","sheet","adoptedStyleSheets","CSSStyleSheet","replaceSync","adoptSheet","s","head","installStyle","acquiredLease","acquireStyle","duration","activeTimers","timerCleanups","releaseHighlight","pluginAdded","classList","acquireHighlight","disposeTimer","debugPlugin","toFixed","createAnalyticsPlugin","totalElements","totalDurationMs","getStats","averageDurationMs","SCROLL_KEY","reloadPreservingScroll","sessionStorage","setItem","scrollX","y","scrollY","saveScrollPosition","reload","documentSavePlugin","controllers","getItem","removeItem","saved","scrollTo","restoreScrollPosition","runFetch","isActive","revalidateUrl","revalidateHeaders","onRevalidateFailure","runRevalidate","CAPABILITY_DOCUMENTATION","gates","buildAttributes","bindByPath","picker","proxy","Proxy","_target","prop","recordPath","richtext","SUPPRESSED","createPreviewBindings","authorization","bindOptions"],"sources":["../package.json","../src/version.ts","../src/detection/locale.ts","../src/core/a11y.ts","../src/schema/parser.ts","../src/schema/walker.ts","../src/schema/diff.ts","../src/schema/field-type-map.ts","../src/security/url-validator.ts","../src/core/attribute-binding.ts","../src/core/internal-outcome.ts","../src/core/value-identity.ts","../src/core/field-changes.ts","../src/core/protocol-version.ts","../src/core/protocol-tracker.ts","../src/core/reveal.ts","../src/core/runtime-state.ts","../src/core/binding-writer.ts","../src/core/dependencies.ts","../src/core/islands.ts","../src/core/strategies.ts","../src/core/cache.ts","../src/core/thenable.ts","../src/core/diagnostics.ts","../src/core/data-merger.ts","../src/core/protocol-profile.ts","../src/core/message-guards.ts","../src/core/message-bus.ts","../src/core/observers.ts","../src/core/state.ts","../src/core/binding-owner.ts","../src/core/field-value.ts","../src/core/orphan-diagnostics.ts","../src/security/trusted-types.ts","../src/core/morph.ts","../src/security/sanitizer.ts","../src/security/escape.ts","../src/core/array-template.ts","../src/field-types/utils.ts","../src/core/template-sanitize.ts","../src/core/structural-applier.ts","../src/core/strategy-runner.ts","../src/core/update-pipeline.ts","../src/core/update-scheduler.ts","../src/core/lifecycle.ts","../src/core/inspection/snapshot.ts","../src/events/emitter.ts","../src/detection/environment.ts","../src/detection/origin.ts","../src/plugins/resource-scope.ts","../src/plugins/scoped-events.ts","../src/plugins/manager.ts","../src/plugins/compat.ts","../src/plugins/renderer-registry.ts","../src/lexical/utils.ts","../src/lexical/nodes/paragraph.ts","../src/lexical/nodes/heading.ts","../src/lexical/value-shapes.ts","../src/lexical/nodes/link.ts","../src/lexical/nodes/code.ts","../src/lexical/nodes/upload.ts","../src/lexical/nodes/relationship.ts","../src/lexical/blocks/registry.ts","../src/lexical/nodes/block.ts","../src/lexical/nodes/table.ts","../src/lexical/nodes/builtin.ts","../src/lexical/nodes/text.ts","../src/lexical/types.ts","../src/lexical/nodes/list.ts","../src/lexical/nodes/quote.ts","../src/lexical/nodes/linebreak.ts","../src/lexical/registry.ts","../src/lexical/render.ts","../src/field-types/text.ts","../src/field-types/rich-text.ts","../src/field-types/html.ts","../src/field-types/unsafe-url.ts","../src/field-types/url.ts","../src/field-types/email.ts","../src/field-types/media.ts","../src/field-types/image.ts","../src/field-types/upload.ts","../src/field-types/relationship.ts","../src/field-types/select.ts","../src/field-types/checkbox.ts","../src/core/intl-cache.ts","../src/field-types/date.ts","../src/field-types/number.ts","../src/field-types/array.ts","../src/field-types/structural-array.ts","../src/field-types/registry.ts","../src/field-types/index.ts","../src/types/defined-only.ts","../src/core/defaults-profile.ts","../src/client/index.ts","../src/client/config.ts","../src/client/preview-focus.ts","../src/core/navigation-lifecycle.ts","../src/core/diagnostic-codes.ts","../src/inline/runtime.generated.ts","../src/inline/fragment.generated.ts","../src/types/inline-config.ts","../src/inline/generator.ts","../src/security/csp.ts","../src/types/authorized-preview.ts","../src/security/preview-verdict.ts","../src/security/preview-session.ts","../src/security/preview-token.ts","../src/security/preview-authorization.ts","../src/adapters/shared/preview-request.ts","../src/plugins/built-in/highlight.ts","../src/plugins/built-in/debug.ts","../src/plugins/built-in/analytics.ts","../src/plugins/built-in/document-save.ts","../src/core/protocol-capability-docs.ts","../src/dsl/bind.ts","../src/dsl/preview-bindings.ts"],"sourcesContent":["{\n \"name\": \"payload-live-preview\",\n \"version\": \"2.0.0-beta.0\",\n \"description\": \"Live preview for Payload CMS in Astro and any SSR/static frontend (SvelteKit, Nuxt, Next.js, plain HTML). Patches the DOM live, no rebuild.\",\n \"author\": \"relative23\",\n \"license\": \"MIT\",\n \"type\": \"module\",\n \"packageManager\": \"npm@12.0.2\",\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n },\n \"./core\": {\n \"import\": {\n \"types\": \"./dist/core.d.ts\",\n \"default\": \"./dist/core.js\"\n },\n \"require\": {\n \"types\": \"./dist/core.d.cts\",\n \"default\": \"./dist/core.cjs\"\n }\n },\n \"./astro\": {\n \"import\": {\n \"types\": \"./dist/adapters/astro/index.d.ts\",\n \"default\": \"./dist/adapters/astro/index.js\"\n }\n },\n \"./nextjs\": {\n \"import\": {\n \"types\": \"./dist/adapters/nextjs/index.d.ts\",\n \"default\": \"./dist/adapters/nextjs/index.js\"\n }\n },\n \"./sveltekit\": {\n \"import\": {\n \"types\": \"./dist/adapters/sveltekit/index.d.ts\",\n \"default\": \"./dist/adapters/sveltekit/index.js\"\n }\n },\n \"./nuxt\": {\n \"import\": {\n \"types\": \"./dist/adapters/nuxt/index.d.ts\",\n \"default\": \"./dist/adapters/nuxt/index.js\"\n }\n },\n \"./codegen\": {\n \"import\": {\n \"types\": \"./dist/codegen.d.ts\",\n \"default\": \"./dist/codegen.js\"\n },\n \"require\": {\n \"types\": \"./dist/codegen.d.cts\",\n \"default\": \"./dist/codegen.cjs\"\n }\n },\n \"./codegen/astro\": {\n \"import\": {\n \"types\": \"./dist/codegen-astro.d.ts\",\n \"default\": \"./dist/codegen-astro.js\"\n }\n },\n \"./doctor\": {\n \"import\": {\n \"types\": \"./dist/doctor.d.ts\",\n \"default\": \"./dist/doctor.js\"\n }\n },\n \"./migrate\": {\n \"import\": {\n \"types\": \"./dist/migrate.d.ts\",\n \"default\": \"./dist/migrate.js\"\n }\n },\n \"./payload\": {\n \"import\": {\n \"types\": \"./dist/payload.d.ts\",\n \"default\": \"./dist/payload.js\"\n },\n \"require\": {\n \"types\": \"./dist/payload.d.cts\",\n \"default\": \"./dist/payload.cjs\"\n }\n },\n \"./server\": {\n \"import\": {\n \"types\": \"./dist/server.d.ts\",\n \"default\": \"./dist/server.js\"\n },\n \"require\": {\n \"types\": \"./dist/server.d.cts\",\n \"default\": \"./dist/server.cjs\"\n }\n },\n \"./client\": {\n \"import\": {\n \"types\": \"./dist/client.d.ts\",\n \"default\": \"./dist/client.js\"\n },\n \"require\": {\n \"types\": \"./dist/client.d.cts\",\n \"default\": \"./dist/client.cjs\"\n }\n },\n \"./structural\": {\n \"import\": {\n \"types\": \"./dist/structural.d.ts\",\n \"default\": \"./dist/structural.js\"\n },\n \"require\": {\n \"types\": \"./dist/structural.d.cts\",\n \"default\": \"./dist/structural.cjs\"\n }\n },\n \"./lexical\": {\n \"import\": {\n \"types\": \"./dist/lexical.d.ts\",\n \"default\": \"./dist/lexical.js\"\n },\n \"require\": {\n \"types\": \"./dist/lexical.d.cts\",\n \"default\": \"./dist/lexical.cjs\"\n }\n },\n \"./plugins\": {\n \"import\": {\n \"types\": \"./dist/plugins.d.ts\",\n \"default\": \"./dist/plugins.js\"\n },\n \"require\": {\n \"types\": \"./dist/plugins.d.cts\",\n \"default\": \"./dist/plugins.cjs\"\n }\n },\n \"./fragment\": {\n \"import\": {\n \"types\": \"./dist/fragment.d.ts\",\n \"default\": \"./dist/fragment.js\"\n },\n \"require\": {\n \"types\": \"./dist/fragment.d.cts\",\n \"default\": \"./dist/fragment.cjs\"\n }\n },\n \"./astro/RichText.astro\": \"./dist/adapters/astro/RichText.astro\",\n \"./astro/PreviewBoundary.astro\": \"./dist/adapters/astro/PreviewBoundary.astro\",\n \"./astro/middleware-entry\": {\n \"import\": {\n \"types\": \"./dist/adapters/astro/middleware-entry.d.ts\",\n \"default\": \"./dist/adapters/astro/middleware-entry.js\"\n }\n }\n },\n \"bin\": {\n \"pll-codegen\": \"./dist/codegen-cli.js\",\n \"pll\": \"./dist/doctor-cli.js\"\n },\n \"files\": [\n \"dist\",\n \"README.md\",\n \"LICENSE\"\n ],\n \"sideEffects\": false,\n \"scripts\": {\n \"build:runtime\": \"tsx scripts/build-runtime.ts\",\n \"build\": \"npm run build:runtime && tsx scripts/build-dist.ts && npm run build:assets && npm run test:bundle && npm run test:treeshake && npm run test:edge\",\n \"build:assets\": \"node -e \\\"const fs=require('node:fs');for(const f of ['RichText','PreviewBoundary'])fs.copyFileSync('src/adapters/astro/'+f+'.astro','dist/adapters/astro/'+f+'.astro')\\\"\",\n \"dev\": \"tsup --watch\",\n \"pretest\": \"npm run build:runtime\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"test:unit\": \"vitest run tests/unit\",\n \"test:integration\": \"vitest run tests/integration\",\n \"test:e2e\": \"playwright test\",\n \"check:fixtures\": \"tsx scripts/check-fixture-freshness.ts\",\n \"test:e2e:real-payload\": \"playwright test --config playwright.real-payload.config.ts\",\n \"test:a11y\": \"playwright test tests/e2e/specs/accessibility.spec.ts\",\n \"test:soak\": \"playwright test --config playwright.soak.config.ts\",\n \"test:browser-bench\": \"playwright test --config playwright.bench.config.ts\",\n \"test:bench\": \"vitest bench tests/benchmarks\",\n \"test:bench:codspeed\": \"vitest bench --run --config vitest.bench.config.ts\",\n \"test:bundle\": \"tsx scripts/check-bundle-size.ts\",\n \"test:treeshake\": \"tsx scripts/check-tree-shaking.ts\",\n \"test:edge\": \"NODE_OPTIONS='--experimental-vm-modules --no-warnings' tsx scripts/check-edge-runtime.ts\",\n \"compat:check\": \"tsx scripts/compat-table.ts --check\",\n \"compat:write\": \"tsx scripts/compat-table.ts --write\",\n \"test:package\": \"tsx scripts/check-package.ts\",\n \"audit:gate\": \"tsx scripts/audit-gate.ts\",\n \"test:smoke\": \"tsx scripts/post-publish-smoke.ts\",\n \"test:coverage\": \"vitest run --coverage\",\n \"test:coverage:diff\": \"tsx scripts/coverage-policy.ts\",\n \"test:policy\": \"tsx scripts/test-policy.ts\",\n \"test:architecture\": \"tsx scripts/architecture-policy.ts && tsx scripts/workflow-contracts.ts && tsx scripts/docs-contracts.ts && knip --no-progress --treat-config-hints-as-errors\",\n \"test:property\": \"vitest run tests/unit/property\",\n \"test:mutation\": \"stryker run stryker.config.js\",\n \"test:mutation:policy:pr\": \"tsx scripts/mutation-policy.ts --policy quality/mutation-policy-pr.json --report test-results/stryker-pr.json\",\n \"test:mutation:policy\": \"tsx scripts/mutation-policy.ts\",\n \"test:leak\": \"node --expose-gc --import tsx scripts/leak-soak.ts\",\n \"test:leak:quick\": \"node --expose-gc --import tsx scripts/leak-soak.ts --quick\",\n \"api:update\": \"npm run build && tsx scripts/check-package.ts --update-api-reports\",\n \"typecheck\": \"tsc --noEmit\",\n \"lint\": \"eslint .\",\n \"lint:fix\": \"eslint . --fix\",\n \"format\": \"prettier --write \\\"src/**/*.ts\\\" \\\"tests/**/*.ts\\\" \\\"scripts/**/*.ts\\\" \\\"*.{js,cjs,mjs,ts,json,jsonc,yml,yaml,md}\\\" \\\"quality/**/*.json\\\" \\\"docs/**/*.md\\\" \\\"type-tests/**/*.md\\\" \\\".prettierrc.json\\\" \\\".changeset/*.{json,md}\\\" \\\".github/**/*.{yml,yaml,json}\\\" \\\"examples/**/*.{ts,tsx,js,cjs,mjs,json}\\\" && prettier --write \\\"type-tests/packed/*.fixture\\\" --parser typescript\",\n \"format:check\": \"prettier --check \\\"src/**/*.ts\\\" \\\"tests/**/*.ts\\\" \\\"scripts/**/*.ts\\\" \\\"*.{js,cjs,mjs,ts,json,jsonc,yml,yaml,md}\\\" \\\"quality/**/*.json\\\" \\\"docs/**/*.md\\\" \\\"type-tests/**/*.md\\\" \\\".prettierrc.json\\\" \\\".changeset/*.{json,md}\\\" \\\".github/**/*.{yml,yaml,json}\\\" \\\"examples/**/*.{ts,tsx,js,cjs,mjs,json}\\\" && prettier --check \\\"type-tests/packed/*.fixture\\\" --parser typescript\",\n \"check\": \"npm run typecheck && npm run lint && npm run test:policy && npm run test:architecture && npm run test\",\n \"prepublishOnly\": \"npm run build && npm run check && npm run format:check && npm run test:package\",\n \"changeset\": \"changeset\",\n \"version\": \"changeset version && tsx scripts/sync-lockfile-metadata.ts\",\n \"release\": \"tsx scripts/publish-artifact.ts\",\n \"test:docs\": \"tsx scripts/docs-contracts.ts\"\n },\n \"devDependencies\": {\n \"@arethetypeswrong/cli\": \"^0.18.5\",\n \"@axe-core/playwright\": \"^4.13.0\",\n \"@changesets/cli\": \"^2.31.1\",\n \"@codspeed/vitest-plugin\": \"^5.7.1\",\n \"@eslint/js\": \"^10.0.1\",\n \"@fast-check/vitest\": \"^0.4.1\",\n \"@microsoft/api-extractor\": \"^7.58.12\",\n \"@playwright/test\": \"^1.62.1\",\n \"@stryker-mutator/core\": \"^9.6.1\",\n \"@stryker-mutator/vitest-runner\": \"^9.6.1\",\n \"@types/jsdom\": \"^30.0.0\",\n \"@types/node\": \"^22.20.1\",\n \"@vitest/coverage-v8\": \"^4.1.10\",\n \"esbuild\": \"^0.28.2\",\n \"eslint\": \"^10.8.1\",\n \"fast-check\": \"^4.9.0\",\n \"globals\": \"^17.11.0\",\n \"jsdom\": \"^29.1.1\",\n \"knip\": \"^6.32.2\",\n \"prettier\": \"^3.9.6\",\n \"publint\": \"^0.3.23\",\n \"terser\": \"^5.46.1\",\n \"ts-morph\": \"^28.0.0\",\n \"tsup\": \"^8.5.1\",\n \"tsx\": \"^4.23.12\",\n \"typescript\": \"^5.9.3\",\n \"typescript-eslint\": \"^8.67.0\",\n \"vite\": \"^7.3.6\",\n \"vitest\": \"^4.1.10\",\n \"yaml\": \"^2.9.0\"\n },\n \"overrides\": {\n \"qs\": \"6.15.3\",\n \"tsup\": {\n \"esbuild\": \"0.28.2\"\n }\n },\n \"allowScripts\": {\n \"esbuild@0.28.2\": true,\n \"fsevents@2.3.2\": false,\n \"fsevents@2.3.3\": false\n },\n \"keywords\": [\n \"astro\",\n \"astro-payload\",\n \"astro-cms\",\n \"astro-integration\",\n \"astro-live-preview\",\n \"payload\",\n \"payload-cms\",\n \"payload-live-preview\",\n \"payload-plugin\",\n \"live-preview\",\n \"preview\",\n \"cms\",\n \"headless\",\n \"headless-cms\",\n \"lexical\",\n \"sveltekit\",\n \"nuxt\",\n \"nextjs\",\n \"ssr\",\n \"framework-agnostic\"\n ],\n \"peerDependencies\": {\n \"astro\": \">=4.0.0 <8.0.0\",\n \"ts-morph\": \"^28.0.0\"\n },\n \"peerDependenciesMeta\": {\n \"astro\": {\n \"optional\": true\n },\n \"ts-morph\": {\n \"optional\": true\n }\n },\n \"engines\": {\n \"node\": \">=20.19.0\"\n },\n \"publishConfig\": {\n \"access\": \"public\",\n \"provenance\": true\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/relative23/payload-live-preview.git\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/relative23/payload-live-preview/issues\"\n },\n \"homepage\": \"https://github.com/relative23/payload-live-preview#readme\"\n}\n","/** The package version, read from package.json so the entries and the inline runtime cannot drift. */\n\nimport pkg from '../package.json' with { type: 'json' };\n\nexport const VERSION: string = pkg.version;\n","/** The locale for `Intl` renders before Payload names one: `<html lang>`, then `navigator.language`, then `'en'`. */\n\nconst FALLBACK_LOCALE = 'en';\n\nexport function detectInitialLocale(): string {\n return readHtmlLang() ?? readNavigatorLanguage() ?? FALLBACK_LOCALE;\n}\n\nfunction readHtmlLang(): string | undefined {\n if (typeof document === 'undefined') return undefined;\n const lang = document.documentElement.getAttribute('lang');\n return lang === null || lang.length === 0 ? undefined : lang;\n}\n\nfunction readNavigatorLanguage(): string | undefined {\n if (typeof navigator === 'undefined') return undefined;\n const lang = navigator.language;\n return typeof lang === 'string' && lang.length > 0 ? lang : undefined;\n}\n","/**\n * One polite `aria-live` region per document, leased by every announcer on\n * the page, for connect / update / disconnect announcements. The message\n * clears itself after a moment so a repeated string is heard again.\n */\n\nimport { detectInitialLocale } from '@detection/locale';\n\nconst ELEMENT_ID = 'payload-live-preview-a11y';\nconst CLEAR_DELAY_MS = 1500;\nconst STYLE =\n 'position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;' +\n 'clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap;border:0';\n\nfunction isGerman(locale: string): boolean {\n return /^de(?:[-_]|$)/i.test(locale);\n}\n\n/** Shared per document; reference-counted so one client cannot remove another's region. */\ninterface DocumentLease {\n element: HTMLElement | null;\n /** Created by this package (removable) rather than adopted from the page. */\n owned: boolean;\n messageNode: Text | null;\n refs: number;\n timer: ReturnType<typeof setTimeout> | null;\n}\n\nconst documentLeases = new WeakMap<Document, DocumentLease>();\n\nfunction acquireDocumentLease(activeDocument: Document): DocumentLease {\n let lease = documentLeases.get(activeDocument);\n if (lease === undefined) {\n lease = { element: null, owned: false, messageNode: null, refs: 0, timer: null };\n documentLeases.set(activeDocument, lease);\n }\n lease.refs += 1;\n return lease;\n}\n\n/** Remove only the package-owned message node, never consumer children. */\nfunction clearLeaseMessage(lease: DocumentLease): void {\n if (lease.timer !== null) {\n clearTimeout(lease.timer);\n lease.timer = null;\n }\n lease.messageNode?.remove();\n lease.messageNode = null;\n}\n\nexport class A11yAnnouncer {\n private readonly german: boolean;\n private readonly document: Document | null;\n private lease: DocumentLease | null = null;\n\n constructor(locale?: string, targetDocument?: Document | null) {\n const activeDocument = targetDocument ?? (typeof document === 'undefined' ? null : document);\n const documentLocale = activeDocument?.documentElement.getAttribute('lang') ?? '';\n this.german = isGerman(\n locale ?? (documentLocale.length > 0 ? documentLocale : detectInitialLocale()),\n );\n this.document = activeDocument;\n // The region mounts on the first announcement: a <head> inline script runs before `body` exists.\n }\n\n /** The shared region, or `null` without a body yet (announcements are then dropped). */\n private mount(): HTMLElement | null {\n const activeDocument = this.document;\n if (activeDocument?.body == null) return null;\n this.lease ??= acquireDocumentLease(activeDocument);\n const lease = this.lease;\n const leased = lease.element;\n if (leased?.isConnected && leased.ownerDocument === activeDocument) return leased;\n // The host removed or replaced the region between announcements.\n if (leased !== null) {\n const owned = lease.owned;\n clearLeaseMessage(lease);\n if (owned) leased.remove();\n }\n let element = activeDocument.getElementById(ELEMENT_ID);\n lease.owned = element === null;\n if (element === null) {\n element = activeDocument.createElement('div');\n element.id = ELEMENT_ID;\n element.setAttribute('role', 'status');\n element.setAttribute('aria-live', 'polite');\n element.setAttribute('aria-atomic', 'true');\n element.setAttribute('style', STYLE);\n activeDocument.body.appendChild(element);\n }\n lease.element = element;\n return element;\n }\n\n announceConnected(): void {\n this.say(this.german ? 'Vorschau verbunden' : 'Live preview connected');\n }\n\n announceDisconnected(): void {\n this.say(this.german ? 'Vorschau getrennt' : 'Live preview disconnected');\n }\n\n announceUpdate(count: number): void {\n if (count <= 0) return;\n this.say(\n this.german\n ? `${String(count)} ${count === 1 ? 'Änderung' : 'Änderungen'} angewendet`\n : `${String(count)} ${count === 1 ? 'change' : 'changes'} applied`,\n );\n }\n\n /** Release the lease; the last release removes an owned region but leaves an adopted one. Idempotent. */\n detach(): void {\n const lease = this.lease;\n const activeDocument = this.document;\n if (lease === null || activeDocument === null) return;\n this.lease = null;\n lease.refs -= 1;\n if (lease.refs > 0) return;\n const element = lease.element;\n if (element !== null) clearLeaseMessage(lease);\n if (lease.owned) element?.remove();\n lease.element = null;\n documentLeases.delete(activeDocument);\n }\n\n private say(message: string): void {\n const element = this.mount();\n const lease = this.lease;\n if (element === null || lease === null) return;\n let messageNode = lease.messageNode;\n if (messageNode?.parentNode !== element) {\n // A dedicated text node leaves consumer-owned children untouched.\n messageNode?.remove();\n messageNode = element.ownerDocument.createTextNode(\n element.hasChildNodes() ? ` ${message}` : message,\n );\n lease.messageNode = messageNode;\n element.appendChild(messageNode);\n } else {\n messageNode.data = messageNode.previousSibling === null ? message : ` ${message}`;\n }\n if (lease.timer !== null) clearTimeout(lease.timer);\n const timer = setTimeout(() => {\n if (lease.timer === timer && lease.element === element) clearLeaseMessage(lease);\n }, CLEAR_DELAY_MS);\n lease.timer = timer;\n }\n}\n","/**\n * Validates the `fieldSchemaJSON` the admin sends. Entries that fail\n * validation are dropped, never thrown: a Payload/runtime version mismatch\n * must not take the preview down.\n */\n\nimport type { PayloadBlockSchema, PayloadFieldSchema } from '@/types/payload-protocol';\n\nexport function parseFieldSchema(raw: unknown): readonly PayloadFieldSchema[] {\n if (!Array.isArray(raw)) return [];\n const out: PayloadFieldSchema[] = [];\n for (const entry of raw) {\n const parsed = parseFieldEntry(entry);\n if (parsed) out.push(parsed);\n }\n return out;\n}\n\nfunction parseFieldEntry(value: unknown): PayloadFieldSchema | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const record = value as Record<string, unknown>;\n const name = record['name'];\n const type = record['type'];\n if (typeof name !== 'string' || name.length === 0) return undefined;\n if (typeof type !== 'string' || type.length === 0) return undefined;\n\n const fields = parseFieldSchema(record['fields']);\n const blocks = parseBlockSchema(record['blocks']);\n\n const result: Record<string, unknown> = { ...record, name, type };\n if (fields.length > 0) result['fields'] = fields;\n else delete result['fields'];\n if (blocks.length > 0) result['blocks'] = blocks;\n else delete result['blocks'];\n\n return result as unknown as PayloadFieldSchema;\n}\n\nfunction parseBlockSchema(raw: unknown): readonly PayloadBlockSchema[] {\n if (!Array.isArray(raw)) return [];\n const out: PayloadBlockSchema[] = [];\n for (const entry of raw) {\n if (typeof entry !== 'object' || entry === null) continue;\n const record = entry as Record<string, unknown>;\n const slug = record['slug'];\n if (typeof slug !== 'string' || slug.length === 0) continue;\n const fields = parseFieldSchema(record['fields']);\n out.push({ ...record, slug, fields });\n }\n return out;\n}\n","/**\n * Flattens a parsed field schema into dotted paths (`hero.title`,\n * `sections.*.heading`). Tabs, rows and collapsibles have no name and\n * dissolve into their inner fields.\n */\n\nimport type {\n PayloadBlockSchema,\n PayloadFieldSchema,\n PayloadFieldType,\n} from '@/types/payload-protocol';\n\nexport type SchemaIndex = ReadonlyMap<string, PayloadFieldSchema>;\n\nconst STRUCTURAL_TYPES: ReadonlySet<PayloadFieldType> = new Set<PayloadFieldType>([\n 'tabs',\n 'row',\n 'collapsible',\n]);\n\nexport function buildSchemaIndex(\n schemas: readonly PayloadFieldSchema[],\n basePath = '',\n): SchemaIndex {\n const out = new Map<string, PayloadFieldSchema>();\n walk(schemas, basePath, out);\n return out;\n}\n\nfunction walk(\n schemas: readonly PayloadFieldSchema[],\n basePath: string,\n out: Map<string, PayloadFieldSchema>,\n): void {\n for (const schema of schemas) {\n if (STRUCTURAL_TYPES.has(schema.type)) {\n if (schema.fields) walk(schema.fields, basePath, out);\n continue;\n }\n const path = basePath === '' ? schema.name : `${basePath}.${schema.name}`;\n out.set(path, schema);\n if (schema.type === 'group') {\n if (schema.fields) walk(schema.fields, path, out);\n } else if (schema.type === 'array' && schema.fields) {\n walk(schema.fields, `${path}.*`, out);\n } else if (schema.type === 'blocks' && schema.blocks) {\n for (const block of schema.blocks) {\n walk(block.fields, `${path}.*.${block.slug}`, out);\n }\n }\n }\n}\n\n/** Schema for `fieldPath`; numeric segments are retried as `*` wildcards. */\nexport function lookupSchema(\n index: SchemaIndex,\n fieldPath: string,\n): PayloadFieldSchema | undefined {\n if (index.has(fieldPath)) return index.get(fieldPath);\n const wildcardPath = fieldPath.replace(/\\.\\d+(?=\\.|$)/g, '.*');\n if (index.has(wildcardPath)) return index.get(wildcardPath);\n return undefined;\n}\n\nexport function lookupBlockSchema(\n index: SchemaIndex,\n blocksFieldPath: string,\n blockType: string,\n): PayloadBlockSchema | undefined {\n const schema = lookupSchema(index, blocksFieldPath);\n if (!schema?.blocks) return undefined;\n return schema.blocks.find((b) => b.slug === blockType);\n}\n","/**\n * Structural diff for array and blocks fields. Items with an `id` are keyed\n * (moves are detected); without ids the diff is positional.\n */\n\nexport type ArrayPatch =\n | { readonly kind: 'insert'; readonly index: number; readonly value: unknown }\n | { readonly kind: 'remove'; readonly index: number; readonly value: unknown }\n | {\n readonly kind: 'move';\n readonly from: number;\n readonly to: number;\n readonly value: unknown;\n }\n | { readonly kind: 'update'; readonly index: number; readonly value: unknown }\n | {\n readonly kind: 'replace';\n readonly index: number;\n readonly oldValue: unknown;\n readonly value: unknown;\n };\n\nfunction getId(item: unknown): string | number | undefined {\n if (typeof item !== 'object' || item === null) return undefined;\n const id = (item as Record<string, unknown>)['id'];\n if (typeof id === 'string' || typeof id === 'number') return id;\n return undefined;\n}\n\nfunction getBlockType(item: unknown): string | undefined {\n if (typeof item !== 'object' || item === null) return undefined;\n const blockType = (item as Record<string, unknown>)['blockType'];\n return typeof blockType === 'string' ? blockType : undefined;\n}\n\n/** Patches that turn `prev` into `next`; a changed `blockType` is a `replace`, never an `update`. */\nexport function diffArray(\n prev: readonly unknown[],\n next: readonly unknown[],\n): readonly ArrayPatch[] {\n const haveIds = next.every((item) => getId(item) !== undefined);\n if (haveIds) return diffById(prev, next);\n return diffByPosition(prev, next);\n}\n\nfunction diffById(prev: readonly unknown[], next: readonly unknown[]): readonly ArrayPatch[] {\n const patches: ArrayPatch[] = [];\n const prevIndexById = new Map<string | number, number>();\n for (let i = 0; i < prev.length; i += 1) {\n const id = getId(prev[i]);\n if (id !== undefined) prevIndexById.set(id, i);\n }\n\n const consumedFromPrev = new Set<number>();\n for (let to = 0; to < next.length; to += 1) {\n const item = next[to];\n const id = getId(item);\n if (id === undefined) {\n patches.push({ kind: 'insert', index: to, value: item });\n continue;\n }\n const from = prevIndexById.get(id);\n if (from === undefined) {\n patches.push({ kind: 'insert', index: to, value: item });\n continue;\n }\n consumedFromPrev.add(from);\n const prevItem = prev[from];\n if (getBlockType(prevItem) !== getBlockType(item)) {\n patches.push({ kind: 'replace', index: to, oldValue: prevItem, value: item });\n continue;\n }\n if (from !== to) {\n patches.push({ kind: 'move', from, to, value: item });\n }\n if (!shallowEqual(prevItem, item)) {\n patches.push({ kind: 'update', index: to, value: item });\n }\n }\n\n for (let i = 0; i < prev.length; i += 1) {\n if (consumedFromPrev.has(i)) continue;\n patches.push({ kind: 'remove', index: i, value: prev[i] });\n }\n return patches;\n}\n\nfunction diffByPosition(prev: readonly unknown[], next: readonly unknown[]): readonly ArrayPatch[] {\n const patches: ArrayPatch[] = [];\n const min = Math.min(prev.length, next.length);\n for (let i = 0; i < min; i += 1) {\n if (!shallowEqual(prev[i], next[i])) {\n patches.push({ kind: 'update', index: i, value: next[i] });\n }\n }\n if (next.length > prev.length) {\n for (let i = prev.length; i < next.length; i += 1) {\n patches.push({ kind: 'insert', index: i, value: next[i] });\n }\n }\n if (prev.length > next.length) {\n for (let i = next.length; i < prev.length; i += 1) {\n patches.push({ kind: 'remove', index: i, value: prev[i] });\n }\n }\n return patches;\n}\n\n// Shallow on purpose: any nested reference change is an update, and the\n// renderer reconciles deeper differences itself.\nfunction shallowEqual(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;\n const aRec = a as Record<string, unknown>;\n const bRec = b as Record<string, unknown>;\n const aKeys = Object.keys(aRec);\n const bKeys = Object.keys(bRec);\n if (aKeys.length !== bKeys.length) return false;\n for (const key of aKeys) {\n if (!Object.is(aRec[key], bRec[key])) return false;\n }\n return true;\n}\n","/**\n * Payload field type → renderer name. Structural containers the walker has\n * already flattened, and types without a display, map to `text` so a new\n * Payload field type never leaves a binding without a renderer.\n */\n\nimport type { FieldType } from '@core/types';\nimport type { PayloadFieldType } from '@/types/payload-protocol';\n\nconst MAP: Readonly<Record<PayloadFieldType, FieldType>> = {\n text: 'text',\n textarea: 'textarea',\n richText: 'richText',\n email: 'email',\n number: 'number',\n checkbox: 'checkbox',\n date: 'date',\n select: 'select',\n radio: 'radio',\n array: 'array',\n blocks: 'blocks',\n group: 'text',\n tabs: 'text',\n row: 'text',\n collapsible: 'text',\n relationship: 'relationship',\n upload: 'upload',\n point: 'text',\n json: 'text',\n code: 'text',\n ui: 'text',\n};\n\n/** `undefined` for a type not in the table, so the caller can fall back to the DOM attribute. */\nexport function payloadTypeToRenderer(type: string): FieldType | undefined {\n if (Object.prototype.hasOwnProperty.call(MAP, type)) {\n return MAP[type as PayloadFieldType];\n }\n return undefined;\n}\n","/**\n * URL safety: the one scheme allow-list the runtime, the client and the\n * sanitizer share. Empty strings are not safe (`<a href=\"\">` is never emitted).\n */\n\nconst SAFE_PROTOCOLS: ReadonlySet<string> = new Set(['http:', 'https:', 'mailto:', 'tel:']);\n\n// Browsers strip leading whitespace before scheme detection.\nconst DANGEROUS_PROTOCOL_PATTERN = /^\\s*(?:javascript|data|vbscript|file|blob|about)\\s*:/i;\n\nconst RELATIVE_PATH = /^(?:\\.{1,2}\\/|[a-zA-Z0-9_-]+\\/?)/;\n\n// The URL parser treats `\\` as `/` for special schemes, so `/\\evil.com`\n// resolves to another origin rather than to a same-origin path.\nconst PROTOCOL_RELATIVE = /^[\\\\/]{2}/;\n\n/** The URL parser drops these anywhere in the input before it looks at anything. */\nconst PARSER_IGNORED = /[\\t\\n\\r]/g;\n\n/** `true` only for absolute `http`/`https`/`mailto`/`tel` URLs, protocol-relative URLs, paths, `#`/`?` fragments and relative paths. */\nexport function isSafeUrl(url: unknown): boolean {\n if (typeof url !== 'string' || url.length === 0) return false;\n const trimmed = url.trim().replace(PARSER_IGNORED, '');\n if (trimmed.length === 0) return false;\n if (DANGEROUS_PROTOCOL_PATTERN.test(trimmed)) return false;\n if (trimmed.startsWith('#') || trimmed.startsWith('?')) return true;\n if (PROTOCOL_RELATIVE.test(trimmed)) return true;\n if (trimmed.startsWith('/')) return true;\n try {\n const parsed = new URL(trimmed);\n return SAFE_PROTOCOLS.has(parsed.protocol);\n } catch {\n return RELATIVE_PATH.test(trimmed);\n }\n}\n\n/** Whether a safe URL points at another HTTP(S) origin, protocol-relative forms included, and so needs `noopener` hardening. */\nexport function isExternalHttpUrl(url: string): boolean {\n if (!isSafeUrl(url)) return false;\n const trimmed = url.trim().replace(PARSER_IGNORED, '');\n return /^https?:\\/\\//i.test(trimmed) || PROTOCOL_RELATIVE.test(trimmed);\n}\n\n/** The safe scheme set, for tests and introspection. */\nexport const SAFE_URL_PROTOCOLS: ReadonlySet<string> = SAFE_PROTOCOLS;\n","/**\n * Policed writes for `data-payload-attribute` bindings. The value is\n * remote-controlled, so event handlers, `style`, `srcdoc`, `formaction`/`form`,\n * `id`/`name` (DOM clobbering) and `srcset` (multi-URL syntax) are refused,\n * URL-bearing attributes must pass `isSafeUrl`, and non-scalars never write.\n */\n\nimport { isSafeUrl } from '@security/url-validator';\n\nconst BLOCKED_ATTRIBUTES: ReadonlySet<string> = new Set([\n 'style',\n 'srcdoc',\n 'formaction',\n 'form',\n 'id',\n 'name',\n 'is',\n 'srcset',\n 'imagesrcset',\n]);\n\nconst URL_ATTRIBUTES: ReadonlySet<string> = new Set([\n 'href',\n 'src',\n 'poster',\n 'cite',\n 'action',\n 'xlink:href',\n 'data',\n]);\n\nexport type AttributeApplyResult = 'applied' | 'blocked';\n\n/** Returns `'blocked'` without touching the DOM when the write is refused. */\nexport function applyAttributeBinding(\n element: Element,\n attribute: string,\n value: unknown,\n): AttributeApplyResult {\n const name = attribute.toLowerCase().trim();\n if (name.length === 0) return 'blocked';\n if (name.startsWith('on')) return 'blocked';\n if (BLOCKED_ATTRIBUTES.has(name)) return 'blocked';\n\n if (value === null || value === undefined) {\n element.removeAttribute(name);\n return 'applied';\n }\n if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') {\n return 'blocked';\n }\n const stringValue = String(value);\n\n if (URL_ATTRIBUTES.has(name) && !isSafeUrl(stringValue)) return 'blocked';\n\n element.setAttribute(name, stringValue);\n return 'applied';\n}\n","/**\n * Public renderer callbacks return `void`, but a JavaScript implementation may\n * return anything. Only callbacks marked here may reserve exact `false` as\n * \"no write\", so a custom renderer's incidental boolean cannot change the\n * lifecycle's applied counts.\n */\n\ntype Callback = (...args: never[]) => unknown;\n\nconst noWriteCallbacks = new WeakSet<Callback>();\n\n/** Mark a package-owned callback whose exact `false` return means no write. */\nexport function markNoWriteCallback<T extends Callback>(callback: T): T {\n noWriteCallbacks.add(callback);\n return callback;\n}\n\n/** Whether `callback` owns the internal exact-false sentinel contract. */\nexport function usesNoWriteOutcome(callback: Callback): boolean {\n return noWriteCallbacks.has(callback);\n}\n\n/** Check a renderer object without detaching its public method at the call site. */\nexport function rendererUsesNoWriteOutcome(renderer: { readonly render: Callback }): boolean {\n return noWriteCallbacks.has(renderer.render);\n}\n","/**\n * Stable identity for a field value, so two messages can be compared without\n * rendering either — every keystroke ships the whole document, of which one\n * field changed. Equality is structural (plain, unsorted JSON): Payload\n * allocates a fresh object graph per message, so reference identity would skip\n * nothing. A value JSON cannot represent has no identity and counts as\n * changed, which is the safe direction — a false \"equal\" leaves a stale\n * binding, a false \"different\" only renders once more.\n */\n\n/** Past this size the comparison is no longer obviously cheaper than the render it avoids. */\nexport const IDENTITY_SIZE_LIMIT = 64 * 1024;\n\n/**\n * Canonical string for `value`, or `undefined` when it cannot have one.\n * Primitives carry a type tag, so `1` and `'1'` differ even though a text\n * renderer prints them alike — that is the renderer's decision, not this one.\n */\nexport function valueIdentity(value: unknown): string | undefined {\n switch (typeof value) {\n case 'string':\n return value.length > IDENTITY_SIZE_LIMIT ? undefined : `s:${value}`;\n case 'number':\n // Object.is semantics at the top level: NaN equals NaN, -0 is not 0.\n return `n:${Object.is(value, -0) ? '-0' : String(value)}`;\n case 'boolean':\n return `b:${value ? '1' : '0'}`;\n case 'bigint':\n return `i:${String(value)}`;\n case 'undefined':\n return 'u';\n case 'object': {\n if (value === null) return 'z';\n let json: string;\n try {\n // Throws on a cycle and on a nested BigInt; both mean \"no identity\".\n json = JSON.stringify(value);\n } catch {\n return undefined;\n }\n return json.length > IDENTITY_SIZE_LIMIT ? undefined : `o:${json}`;\n }\n case 'symbol':\n case 'function':\n return undefined;\n }\n}\n","/**\n * The one per-message diff of top-level field values. Strategies, dependency\n * invalidation and reveal all consume it, so \"changed\" means the same thing\n * everywhere.\n */\n\nimport type { DependencyMap } from './dependencies';\nimport { valueIdentity } from './value-identity';\n\nexport interface FieldChanges {\n /** Fields whose value differs from the previous message; every field on the first one. */\n readonly changed: ReadonlySet<string>;\n /** Dependents of changed fields, per the dependency map. */\n readonly invalidated: ReadonlySet<string>;\n}\n\nexport class FieldChangeTracker {\n private previous: Map<string, string | undefined> | null = null;\n\n /** Diff `fields` against the previous message and remember them for the next call. */\n diff(fields: Readonly<Record<string, unknown>>, dependencies: DependencyMap): FieldChanges {\n const previous = this.previous;\n const next = new Map<string, string | undefined>();\n const changed = new Set<string>();\n for (const [name, value] of Object.entries(fields)) {\n const identity = valueIdentity(value);\n next.set(name, identity);\n // A value without an identity always counts as changed: rendering once\n // more is cheap, a stale binding is not.\n if (previous === null || identity === undefined || previous.get(name) !== identity) {\n changed.add(name);\n }\n }\n if (previous !== null) {\n for (const name of previous.keys()) if (!next.has(name)) changed.add(name);\n }\n this.previous = next;\n const invalidated = new Set<string>();\n for (const [source, dependents] of Object.entries(dependencies)) {\n if (!changed.has(source)) continue;\n for (const dependent of dependents) invalidated.add(dependent);\n }\n return { changed, invalidated };\n }\n\n reset(): void {\n this.previous = null;\n }\n}\n","/**\n * Protocol negotiation. A capability is granted either by the version a peer\n * announces or by observation, since the stock Payload admin announces none:\n * what it can do is read off the messages it sends. See ADR 0010.\n */\n\n/** Bumped only when this library's understanding of the wire format changes. */\nexport const LIBRARY_PROTOCOL_VERSION = 4;\n\n/** How a capability becomes active. */\nexport type CapabilitySource = 'version' | 'observed';\n\nexport interface CapabilityDeclaration {\n /** Enabled once the negotiated version reaches this (for announced peers). */\n readonly since: number;\n /** The wire signal that grants this capability to a peer announcing no version. */\n readonly observed?:\n 'schema' | 'locale' | 'preview-token' | 'document-event' | 'relationship-event';\n}\n\n/** What activates each capability; the prose lives in `CAPABILITY_DOCUMENTATION`. */\nexport const CAPABILITY_DECLARATIONS = {\n basic: { since: 1 },\n 'schema-json': { since: 2, observed: 'schema' },\n locale: { since: 2, observed: 'locale' },\n 'preview-token': { since: 3, observed: 'preview-token' },\n 'nested-arrays': { since: 4 },\n 'recursive-diffs': { since: 4 },\n 'document-events': { since: 4, observed: 'document-event' },\n 'relationship-events': { since: 4, observed: 'relationship-event' },\n} as const satisfies Record<string, CapabilityDeclaration>;\n\nexport type ProtocolCapability = keyof typeof CAPABILITY_DECLARATIONS;\n\n/** Every declared capability, in declaration order. */\nexport const PROTOCOL_CAPABILITIES = Object.keys(\n CAPABILITY_DECLARATIONS,\n) as readonly ProtocolCapability[];\n\nexport interface ProtocolNegotiation {\n /** This library's protocol version. */\n readonly ours: number;\n /** The remote party's version, when it announced one. */\n readonly theirs: number | undefined;\n /** `min(ours, theirs ?? 1)` — the version both sides actually share. */\n readonly negotiated: number;\n /** Capabilities active at the negotiated version or seen on the wire. */\n readonly capabilities: ReadonlySet<ProtocolCapability>;\n /** The subset that was observed on the wire rather than granted by version. */\n readonly observed: ReadonlySet<ProtocolCapability>;\n}\n\n/** Deterministic; the runtime re-runs it whenever either input changes. */\nexport function negotiateProtocol(\n theirs: number | undefined,\n observed: Iterable<ProtocolCapability> = [],\n): ProtocolNegotiation {\n const sanitisedTheirs =\n typeof theirs === 'number' && Number.isFinite(theirs) && theirs >= 1\n ? Math.floor(theirs)\n : undefined;\n const effectiveTheirs = sanitisedTheirs ?? 1;\n const negotiated = Math.min(LIBRARY_PROTOCOL_VERSION, effectiveTheirs);\n const seen = new Set<ProtocolCapability>(observed);\n const capabilities = new Set<ProtocolCapability>();\n for (const capability of PROTOCOL_CAPABILITIES) {\n if (negotiated >= CAPABILITY_DECLARATIONS[capability].since || seen.has(capability)) {\n capabilities.add(capability);\n }\n }\n return {\n ours: LIBRARY_PROTOCOL_VERSION,\n ...(sanitisedTheirs !== undefined ? { theirs: sanitisedTheirs } : { theirs: undefined }),\n negotiated,\n capabilities,\n observed: seen,\n };\n}\n\nexport function hasCapability(\n negotiation: ProtocolNegotiation,\n capability: ProtocolCapability,\n): boolean {\n return negotiation.capabilities.has(capability);\n}\n\n/** The capabilities a single message demonstrates, by its shape alone. */\nexport function observeCapabilities(message: {\n readonly fieldSchemaJSON?: unknown;\n readonly locale?: unknown;\n readonly previewToken?: unknown;\n readonly externallyUpdatedRelationship?: unknown;\n}): readonly ProtocolCapability[] {\n const seen: ProtocolCapability[] = [];\n if (Array.isArray(message.fieldSchemaJSON)) seen.push('schema-json');\n if (typeof message.locale === 'string') seen.push('locale');\n if (typeof message.previewToken === 'string') seen.push('preview-token');\n if (\n typeof message.externallyUpdatedRelationship === 'object' &&\n message.externallyUpdatedRelationship !== null\n ) {\n seen.push('relationship-events');\n }\n return seen;\n}\n","/** Tracks the announced protocol version and the capabilities seen on the wire. */\n\nimport {\n LIBRARY_PROTOCOL_VERSION,\n negotiateProtocol,\n type ProtocolCapability,\n type ProtocolNegotiation,\n} from './protocol-version';\n\nexport class ProtocolTracker {\n negotiation: ProtocolNegotiation = negotiateProtocol(undefined);\n readonly observed = new Set<ProtocolCapability>();\n\n /** Record capabilities a message demonstrated; the stock admin announces no version. */\n observe(capabilities: readonly ProtocolCapability[], log: (...args: unknown[]) => void): void {\n const fresh = capabilities.filter((capability) => !this.observed.has(capability));\n if (fresh.length === 0) return;\n for (const capability of fresh) this.observed.add(capability);\n this.negotiation = negotiateProtocol(this.negotiation.theirs, this.observed);\n log('protocol', `observed=${fresh.join(',')}`);\n }\n\n applyVersion(remoteVersion: number, log: (...args: unknown[]) => void): void {\n const current = this.negotiation;\n if (current.theirs === remoteVersion) return;\n const next = negotiateProtocol(remoteVersion, this.observed);\n this.negotiation = next;\n if (next.negotiated === current.negotiated) return;\n log(\n 'protocol',\n `ours=${LIBRARY_PROTOCOL_VERSION}`,\n `theirs=${remoteVersion}`,\n `negotiated=${next.negotiated}`,\n );\n }\n}\n","/**\n * Scroll the edited field's bound element into view. Deliberately quiet: only\n * when the target is off-screen and only when the edited field changed since\n * the last reveal, so continuous typing never re-scrolls and a deliberate\n * scroll-away is not fought. Honours `prefers-reduced-motion`.\n */\n\n/** The slice of `Window` this reads, so it tests without a browser. */\nexport interface RevealWindow {\n readonly innerHeight: number;\n readonly innerWidth: number;\n matchMedia?: (query: string) => { readonly matches: boolean };\n}\n\n/** The slice of `Element` this module needs. */\nexport interface RevealElement {\n getBoundingClientRect: () => {\n readonly top: number;\n readonly bottom: number;\n readonly left: number;\n readonly right: number;\n };\n scrollIntoView: (options?: {\n behavior?: 'auto' | 'smooth';\n block?: 'center' | 'nearest' | 'start';\n }) => void;\n}\n\n/** Whether the viewer asked for reduced motion; smooth scrolling is suppressed when so. */\nexport function prefersReducedMotion(win: RevealWindow): boolean {\n try {\n return win.matchMedia?.('(prefers-reduced-motion: reduce)').matches === true;\n } catch {\n return false;\n }\n}\n\n/** A visible sliver counts: an element the editor can already see is never scrolled to. */\nexport function isInViewport(element: RevealElement, win: RevealWindow): boolean {\n const rect = element.getBoundingClientRect();\n const vertically = rect.bottom > 0 && rect.top < win.innerHeight;\n const horizontally = rect.right > 0 && rect.left < win.innerWidth;\n return vertically && horizontally;\n}\n\n/** Outcome of a reveal attempt, for the caller's diagnostics. */\nexport type RevealOutcome = 'revealed' | 'already-visible';\n\n/** Scroll `element` into view only when it is off-screen. */\nexport function revealElement(element: RevealElement, win: RevealWindow): RevealOutcome {\n if (isInViewport(element, win)) return 'already-visible';\n element.scrollIntoView({\n behavior: prefersReducedMotion(win) ? 'auto' : 'smooth',\n block: 'center',\n });\n return 'revealed';\n}\n\n/** Remembers the last field revealed, so only a change of field scrolls again. */\nexport class FieldRevealer {\n #lastField: string | undefined;\n\n /** `skipped-same` when this is still the field last revealed. */\n reveal(\n fieldName: string,\n element: RevealElement,\n win: RevealWindow,\n ): RevealOutcome | 'skipped-same' {\n if (fieldName === this.#lastField) return 'skipped-same';\n this.#lastField = fieldName;\n return revealElement(element, win);\n }\n\n /** Forget the last field, after a navigation that rebuilt the page. */\n reset(): void {\n this.#lastField = undefined;\n }\n}\n","/**\n * What the runtime owns for its lifetime (`RuntimeDeps`) and what changes as it\n * runs (`RuntimeState`). Both are shared by the pipeline collaborators.\n */\n\nimport type { PayloadFieldSchema, PayloadLivePreviewMessage } from '@/types/payload-protocol';\nimport type { EventEmitter } from '@events/emitter';\nimport type { SchemaIndex } from '@schema/index';\nimport type { A11yAnnouncer } from './a11y';\nimport type { ElementCache } from './cache';\nimport type { DataMerger } from './data-merger';\nimport { FieldChangeTracker } from './field-changes';\nimport type { MessageBus, MessageRevision } from './message-bus';\nimport type { ObserverManager } from './observers';\nimport { ProtocolTracker } from './protocol-tracker';\nimport { FieldRevealer } from './reveal';\nimport type { RuntimeOptions } from './runtime-options';\nimport type { ConnectionState, HeartbeatTimer } from './state';\nimport type { StrategyHandlers } from './strategies';\nimport type { CachedElement, FieldRenderer, RichTextRenderer } from './types';\nimport type { FlushStats, UpdateScheduler } from './update-scheduler';\n\n/** One accepted message on its way to the DOM. See ADR 0004. */\nexport interface UpdateTransaction {\n readonly identity: MessageRevision;\n readonly message: PayloadLivePreviewMessage;\n readonly locale: string | undefined;\n readonly schema: readonly PayloadFieldSchema[] | undefined;\n readonly schemaIndex: SchemaIndex | undefined;\n readonly receivedAt: number;\n /** A relationship edit may change populated values only, so render everything. */\n readonly forceRender: boolean;\n /** Top-level fields whose value changed since the previous message, plus their dependents. */\n touched: ReadonlySet<string>;\n /** Dependents of changed fields; re-applied even when their own value is unchanged. */\n invalidated: ReadonlySet<string>;\n /**\n * First binding whose value changed; revealed once its write landed. The\n * binding itself, not its field name: several documents on one page share\n * field names, and only this one belongs to the edited document.\n */\n revealTarget: CachedElement | undefined;\n /**\n * Identities the reveal ledger will record once this revision reaches its\n * reveal point — not before. A revision superseded on the way there never\n * revealed, so the ledger must still show the previous value: the message\n * that supersedes it is then the one that owes the reveal.\n */\n revealIdentities: [key: string, identity: string][];\n pendingFragments: number;\n routeRefreshed: boolean;\n cancelled: boolean;\n /** Terminal: the scheduled writes reached the DOM (or there were none). */\n completed: boolean;\n}\n\nexport interface RuntimeDeps {\n readonly emitter: EventEmitter;\n readonly cache: ElementCache;\n readonly observers: ObserverManager;\n readonly scheduler: UpdateScheduler;\n readonly bus: MessageBus;\n readonly connection: ConnectionState;\n readonly heartbeat: HeartbeatTimer;\n readonly renderers: Readonly<Record<string, FieldRenderer>>;\n readonly resolveRenderer: NonNullable<RuntimeOptions['resolveRenderer']>;\n readonly transformValue: RuntimeOptions['transformValue'];\n readonly renderRichText: RichTextRenderer | undefined;\n readonly root: Document | Element;\n readonly readyTargets: () => readonly string[];\n readonly sendReady: (origins: readonly string[]) => void;\n readonly onHeartbeatTimeout: RuntimeOptions['onHeartbeatTimeout'];\n readonly log: (...args: unknown[]) => void;\n readonly warn: (...args: unknown[]) => void;\n readonly a11y: A11yAnnouncer | null;\n readonly merger: DataMerger | null;\n readonly scopeBindingsByOwner: boolean;\n readonly lockedOrigin: () => string | undefined;\n readonly skipUnchanged: boolean;\n readonly dependencies: Readonly<Record<string, readonly string[]>>;\n readonly strategies: StrategyHandlers;\n readonly revealEditedField: boolean;\n}\n\nexport function sameRevision(a: MessageRevision, b: MessageRevision): boolean {\n return a.generation === b.generation && a.revision === b.revision;\n}\n\nexport class RuntimeState {\n started = false;\n /** Set by `suspend()`; lets `destroy()` finish a suspended instance. */\n suspended = false;\n deferredStart: (() => void) | null = null;\n activeUpdate: UpdateTransaction | null = null;\n locale: string | undefined = undefined;\n schema: readonly PayloadFieldSchema[] | undefined = undefined;\n schemaIndex: SchemaIndex | undefined = undefined;\n updateCount = 0;\n supersededCount = 0;\n completedCount = 0;\n skippedUnchangedCount = 0;\n lastFlush: FlushStats | null = null;\n readonly absentFields = new Set<string>();\n readonly warnedOrphanFields = new Set<string>();\n readonly warnedStrategy = new WeakSet<Element>();\n warnedUnattributableMessage = false;\n warnedVisibilityGate = false;\n warnedFragmentFallback = false;\n /** Identity of the value each element last applied; reset when the markup is re-rendered. */\n lastAppliedIdentity = new WeakMap<Element, string>();\n /**\n * Identity of the value last seen per owned field, for the reveal decision\n * only. Keyed by document and field rather than by element, so a field the\n * server re-renders behind a fragment boundary — where no element survives\n * to carry the identity — is still known to have changed.\n */\n readonly seenFieldIdentity = new Map<string, string>();\n readonly fragmentStats = { rendered: 0, failed: 0, superseded: 0 };\n readonly routeStats = { refreshes: 0, failed: 0, loopStopped: 0 };\n fragmentController: AbortController | null = null;\n routeController: AbortController | null = null;\n readonly readyTimers: ReturnType<typeof setTimeout>[] = [];\n readonly revealer = new FieldRevealer();\n readonly changes = new FieldChangeTracker();\n readonly protocol = new ProtocolTracker();\n\n /** Read through a method: TypeScript keeps a narrowed `started` across the calls that can flip it. */\n isRunning(): boolean {\n return this.started;\n }\n\n /** Whether `transaction` may still touch the DOM; re-checked after every reentrant callback. */\n isCurrent(transaction: UpdateTransaction): boolean {\n return this.started && this.activeUpdate === transaction;\n }\n\n complete(transaction: UpdateTransaction): void {\n if (transaction.completed) return;\n transaction.completed = true;\n this.completedCount += 1;\n }\n\n /** Abort in-flight strategy work; a newer revision or a stop supersedes it. */\n abortStrategies(): void {\n for (const key of ['fragmentController', 'routeController'] as const) {\n const controller = this[key];\n if (controller === null) continue;\n this[key] = null;\n controller.abort();\n }\n }\n}\n","/**\n * Writes one scheduled value into its bound element: renderer resolution,\n * the attribute or renderer write, and the `elementUpdate` event. Every\n * consumer callback may accept a newer revision synchronously, so the\n * transaction is re-checked after each one (ADR 0004).\n */\n\nimport { lookupSchema, payloadTypeToRenderer } from '@schema/index';\nimport { applyAttributeBinding } from './attribute-binding';\nimport { rendererUsesNoWriteOutcome } from './internal-outcome';\nimport {\n sameRevision,\n type RuntimeDeps,\n type RuntimeState,\n type UpdateTransaction,\n} from './runtime-state';\nimport type { CachedElement, FieldRenderer, RenderContext, RendererKey } from './types';\nimport type { ScheduledUpdate } from './update-scheduler';\n\nexport class BindingWriter {\n constructor(\n private readonly deps: RuntimeDeps,\n private readonly state: RuntimeState,\n ) {}\n\n /** Scheduler callback. `false` means nothing reached the DOM. */\n apply(update: ScheduledUpdate): boolean {\n const { deps, state } = this;\n const transaction = state.activeUpdate;\n if (\n transaction === null ||\n update.identity === undefined ||\n !sameRevision(transaction.identity, update.identity) ||\n !state.isCurrent(transaction)\n ) {\n return false;\n }\n const { target, value } = update;\n const schemaEntry =\n transaction.schemaIndex !== undefined\n ? lookupSchema(transaction.schemaIndex, target.fieldName)\n : undefined;\n let type = resolveFieldType(target, schemaEntry?.type);\n // Payload 3.x sends no schema; a Lexical root is unmistakable.\n if (type === 'text' && target.explicitFieldType !== true && looksLikeLexicalRoot(value)) {\n type = 'richText';\n }\n let renderer: FieldRenderer | undefined;\n try {\n renderer = deps.resolveRenderer(type, target);\n } catch (error) {\n return this.fail(transaction, error);\n }\n if (!state.isCurrent(transaction)) return false;\n const emitElementUpdate = deps.emitter.listenerCount('elementUpdate') > 0;\n // Custom-element accessors run application code, so this is a boundary too.\n const previous = emitElementUpdate ? readElementSnapshot(target.element) : undefined;\n if (!state.isCurrent(transaction)) return false;\n const context: RenderContext = {\n allFields: update.allFields,\n locale: target.locale ?? transaction.locale,\n schema: schemaEntry,\n ...(deps.renderRichText !== undefined ? { renderRichText: deps.renderRichText } : {}),\n };\n // A boundary anchor stays out of layout and the accessibility tree while empty.\n if (target.boundary === true) {\n target.element.toggleAttribute('hidden', isEmptyFieldValue(value));\n }\n try {\n if (target.targetAttribute !== undefined) {\n if (applyAttributeBinding(target.element, target.targetAttribute, value) === 'blocked') {\n deps.warn(\n `[live-preview] LP0401: refused to write \"${target.fieldName}\" into attribute \"${target.targetAttribute}\"`,\n );\n return false;\n }\n } else if (renderer !== undefined) {\n const outcome = invokeRenderer(renderer, target, value, context);\n if (outcome === false && rendererUsesNoWriteOutcome(renderer)) return false;\n } else {\n deps.log('no renderer for', type);\n return false;\n }\n } catch (error) {\n return this.fail(transaction, error);\n }\n if (!state.isCurrent(transaction)) return false;\n if (emitElementUpdate) {\n void deps.emitter.emitWhile(\n 'elementUpdate',\n {\n element: target.element,\n fieldName: target.fieldName,\n previousValue: previous,\n nextValue: value,\n revision: transaction.identity.revision,\n receivedAt: transaction.receivedAt,\n source: 'patch',\n },\n () => state.isCurrent(transaction),\n );\n }\n // The first handler runs before emitWhile yields; a reentrant newer\n // revision must not count this write as applied.\n const applied = state.isCurrent(transaction);\n if (applied) {\n if (update.valueIdentity !== undefined) {\n state.lastAppliedIdentity.set(target.element, update.valueIdentity);\n } else {\n state.lastAppliedIdentity.delete(target.element);\n }\n }\n return applied;\n }\n\n private fail(transaction: UpdateTransaction, cause: unknown): false {\n if (!this.state.isCurrent(transaction)) return false;\n const error = cause instanceof Error ? cause : new Error(String(cause));\n void this.deps.emitter.emitWhile('error', { error, context: 'renderer', code: 'LP0603' }, () =>\n this.state.isCurrent(transaction),\n );\n return false;\n }\n}\n\n/** Explicit `data-payload-type` wins over the schema, which wins over tag heuristics. */\nfunction resolveFieldType(target: CachedElement, schemaType: string | undefined): RendererKey {\n if (target.explicitFieldType) return target.fieldType;\n if (schemaType !== undefined) {\n const mapped = payloadTypeToRenderer(schemaType);\n if (mapped !== undefined) return mapped;\n }\n return target.fieldType;\n}\n\n/** Built-in renderers may return exact `false` for a deliberate no-write; the public type stays `void`. */\nfunction invokeRenderer(\n renderer: FieldRenderer,\n target: CachedElement,\n value: unknown,\n context: RenderContext,\n): unknown {\n // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression\n return renderer.render(target, value, context);\n}\n\n/** Same shape test as `isLexicalContent`, duplicated so core does not pull the Lexical renderer. */\nfunction looksLikeLexicalRoot(value: unknown): boolean {\n if (typeof value !== 'object' || value === null || !('root' in value)) return false;\n const root = value.root;\n return (\n typeof root === 'object' &&\n root !== null &&\n Array.isArray((root as { children?: unknown }).children)\n );\n}\n\nfunction readElementSnapshot(element: Element): unknown {\n if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {\n return (element as HTMLInputElement).value;\n }\n if (element.tagName === 'IMG') return (element as HTMLImageElement).src;\n return element.textContent;\n}\n\nfunction isEmptyFieldValue(value: unknown): boolean {\n if (value === null || value === undefined) return true;\n if (typeof value === 'string') return value.trim().length === 0;\n return Array.isArray(value) && value.length === 0;\n}\n","/**\n * One source → dependents map for `skipUnchanged`. Markup declares it the\n * other way round (`data-payload-depends=\"price\"` on the element bound to\n * `priceLabel`) because an author names what a binding needs; the runtime\n * option is keyed by source because the scheduler asks what changed.\n */\n\nexport type DependencyMap = Readonly<Record<string, readonly string[]>>;\n\n/**\n * Field names from an attribute value. Separators are commas and\n * whitespace; empty entries are dropped; order is kept, duplicates removed.\n */\nexport function parseDependencyList(value: string | null | undefined): readonly string[] {\n if (value === null || value === undefined) return [];\n const seen = new Set<string>();\n const names: string[] = [];\n for (const raw of value.split(/[\\s,]+/)) {\n const name = raw.trim();\n if (name.length === 0 || seen.has(name)) continue;\n seen.add(name);\n names.push(name);\n }\n return names;\n}\n\n/**\n * Merge dependency maps (source → dependents). Later maps add to earlier\n * ones; a dependent is listed once per source.\n */\nexport function mergeDependencyMaps(...maps: readonly DependencyMap[]): DependencyMap {\n const merged = new Map<string, Set<string>>();\n for (const map of maps) {\n for (const [source, dependents] of Object.entries(map)) {\n let bucket = merged.get(source);\n if (bucket === undefined) {\n bucket = new Set();\n merged.set(source, bucket);\n }\n for (const dependent of dependents) bucket.add(dependent);\n }\n }\n const result: Record<string, readonly string[]> = {};\n for (const [source, dependents] of merged) result[source] = [...dependents];\n return result;\n}\n\n/**\n * The map an element's `data-payload-depends` contributes: every declared\n * source points at this binding's field.\n */\nexport function dependencyMapFromBinding(\n fieldName: string,\n dependsOn: readonly string[],\n): DependencyMap {\n const map: Record<string, readonly string[]> = {};\n for (const source of dependsOn) {\n if (source === fieldName) continue;\n map[source] = [fieldName];\n }\n return map;\n}\n","/**\n * Hydrated islands own their subtree, so the runtime never patches inside one.\n * Instead every flush dispatches `payload-live-preview:update` on each island\n * root with the update in `detail`. `data-payload-island=\"patch\"` opts back in.\n */\n\nexport const ISLAND_EVENT = 'payload-live-preview:update';\nexport const ISLAND_ATTRIBUTE = 'data-payload-island';\nexport const ISLAND_SELECTOR = `astro-island, [${ISLAND_ATTRIBUTE}]`;\n\nexport interface IslandUpdateDetail {\n readonly fields: Readonly<Record<string, unknown>>;\n readonly revision: number;\n readonly receivedAt: number;\n readonly locale: string | undefined;\n}\n\nfunction isIslandRoot(element: Element): boolean {\n return element.tagName.toLowerCase() === 'astro-island' || element.hasAttribute(ISLAND_ATTRIBUTE);\n}\n\nfunction islandAllowsPatching(island: Element): boolean {\n return island.getAttribute(ISLAND_ATTRIBUTE) === 'patch';\n}\n\n/** Whether `element` (or an ancestor) is an island that did not opt into patching. */\nexport function isInsideIsland(element: Element): boolean {\n let current: Element | null = element;\n while (current !== null) {\n if (isIslandRoot(current) && !islandAllowsPatching(current)) return true;\n current = current.parentElement;\n }\n return false;\n}\n\n/** Island roots under `root` that receive update events. */\nexport function collectIslands(root: ParentNode): Element[] {\n const islands: Element[] = [];\n for (const island of root.querySelectorAll(ISLAND_SELECTOR)) {\n if (!islandAllowsPatching(island)) islands.push(island);\n }\n return islands;\n}\n\nexport function dispatchIslandUpdate(\n islands: readonly Element[],\n detail: IslandUpdateDetail,\n): number {\n for (const island of islands) {\n island.dispatchEvent(\n new CustomEvent<IslandUpdateDetail>(ISLAND_EVENT, { detail, bubbles: false }),\n );\n }\n return islands.length;\n}\n","/**\n * How a bound region is brought up to date: the runtime patches it, a server\n * renders a `data-payload-fragment` boundary from the unsaved form state, or\n * the whole route refreshes. Core carries only the seam — which boundaries a\n * strategy owns and what it may do — so a patch-only page pays for nothing\n * more; the orchestration lives in `payload-live-preview/fragment`.\n */\nimport type { DiagnosticCode } from './diagnostic-codes';\n\n/** What produced an update: the runtime's DOM patching, a server-rendered fragment, or a route refresh. */\nexport type UpdateSource = 'patch' | 'fragment' | 'route';\n\n/** Marks a server-rendered boundary; the value is the registry id the server may render. */\nexport const FRAGMENT_ATTRIBUTE = 'data-payload-fragment';\n\n/** The nearest fragment boundary enclosing `element` (the element itself included). */\nexport function enclosingFragment(element: Element): Element | null {\n return element.closest(`[${FRAGMENT_ATTRIBUTE}]`);\n}\n\n/** One revision, as a strategy sees it, with the runtime capabilities it may use. */\nexport interface FragmentContext {\n readonly root: ParentNode;\n readonly revision: number;\n readonly receivedAt: number;\n readonly fields: Readonly<Record<string, unknown>>;\n readonly locale: string | undefined;\n readonly collectionSlug: string | undefined;\n readonly globalSlug: string | undefined;\n /** Aborted when a newer revision arrives or the runtime stops. */\n readonly signal: AbortSignal;\n /** Whether this revision is still the current one. */\n readonly isCurrent: () => boolean;\n /** Morph server-rendered HTML into a boundary (Trusted Types and the keyed morph apply). */\n readonly morph: (boundary: Element, html: string) => void;\n /** Patch the boundary's own bindings from this revision — the deterministic fallback. */\n readonly patch: (boundary: Element) => void;\n /** Debug log through the runtime's logger, with the diagnostic code. */\n readonly log: (code: DiagnosticCode, detail: string) => void;\n /** Report a boundary rendered. */\n readonly rendered: (boundary: Element, id: string, key: string | undefined) => void;\n /** Report a boundary failed and patched instead; emits the `error` and `fragmentRender` events. */\n readonly failed: (\n boundary: Element,\n id: string,\n key: string | undefined,\n code: DiagnosticCode,\n reason: string,\n ) => void;\n}\n\nexport interface FragmentReport {\n readonly rendered: number;\n readonly failed: number;\n readonly superseded: number;\n}\n\n/** A fragment strategy: which boundaries it owns for a revision, and how it renders them. */\nexport interface FragmentStrategy {\n /** The boundaries this update re-renders; their inner bindings are left to the strategy. */\n readonly plan: (root: ParentNode, changedFields: ReadonlySet<string>) => readonly Element[];\n /** Render the planned boundaries; resolves once every one settled. */\n readonly render: (\n context: FragmentContext,\n boundaries: readonly Element[],\n ) => Promise<FragmentReport>;\n}\n\n/** One revision, as the route strategy sees it. */\nexport interface RouteContext {\n readonly revision: number;\n readonly receivedAt: number;\n /** Aborted when a newer revision arrives or the runtime stops. */\n readonly signal: AbortSignal;\n readonly isCurrent: () => boolean;\n readonly log: (code: DiagnosticCode, detail: string) => void;\n}\n\n/**\n * Whether a revision needs the whole route re-rendered, and how. After a\n * refresh the runtime rescans and re-applies the revision, so the unsaved\n * state lands on the fresh markup.\n */\nexport interface RouteStrategy {\n readonly plan: (root: ParentNode, changedFields: ReadonlySet<string>) => boolean;\n readonly refresh: (context: RouteContext) => Promise<'refreshed' | 'failed' | 'superseded'>;\n}\n\nexport interface StrategyHandlers {\n readonly fragment?: FragmentStrategy;\n readonly route?: RouteStrategy;\n}\n\nconst STRATEGY_ATTRIBUTE = 'data-payload-strategy';\n\n/**\n * Explicit `data-payload-strategy` wins; otherwise a binding inside a fragment\n * boundary belongs to the fragment, one in `<head>` to the route, the rest is\n * patched. An unknown explicit value resolves to `undefined` (LP0407).\n */\nexport function resolveStrategy(element: Element): UpdateSource | undefined {\n const explicit = element.getAttribute(STRATEGY_ATTRIBUTE);\n if (explicit !== null && explicit.length > 0) {\n return explicit === 'patch' || explicit === 'fragment' || explicit === 'route'\n ? explicit\n : undefined;\n }\n if (enclosingFragment(element) !== null) return 'fragment';\n if (element.closest('head') !== null) return 'route';\n return 'patch';\n}\n","/**\n * Maps field names to their bound elements so an update walks the cache, not\n * the DOM. Everything an update needs about a binding is resolved here, once,\n * at build time.\n */\n\nimport {\n dependencyMapFromBinding,\n mergeDependencyMaps,\n parseDependencyList,\n type DependencyMap,\n} from './dependencies';\nimport { collectIslands } from './islands';\nimport { enclosingFragment, resolveStrategy } from './strategies';\nimport type { CachedElement, ElementPredicate, FieldType, RendererKey } from './types';\n\nexport const FIELD_ATTRIBUTE = 'data-payload-field';\nexport const TYPE_ATTRIBUTE = 'data-payload-type';\nexport const TARGET_ATTRIBUTE_ATTRIBUTE = 'data-payload-attribute';\nexport const HREF_ATTRIBUTE = 'data-payload-href';\nexport const SRC_ATTRIBUTE = 'data-payload-src';\nexport const ALT_ATTRIBUTE = 'data-payload-alt';\nexport const ARRAY_TEMPLATE_ATTRIBUTE = 'data-payload-array-template';\nexport const ARRAY_SEPARATOR_ATTRIBUTE = 'data-payload-array-separator';\nexport const LOCALE_ATTRIBUTE = 'data-payload-locale';\nexport const RICH_TEXT_ATTRIBUTE = 'data-payload-richtext';\nexport const HTML_ATTRIBUTE = 'data-payload-html';\nexport const ARRAY_ATTRIBUTE = 'data-payload-array';\nexport const STRUCTURAL_ATTRIBUTE = 'data-payload-structural';\nexport const OWNER_ATTRIBUTE = 'data-payload-owner';\nexport const DEPENDS_ATTRIBUTE = 'data-payload-depends';\nexport const STRATEGY_ATTRIBUTE = 'data-payload-strategy';\nexport const BOUNDARY_ATTRIBUTE = 'data-payload-boundary';\nexport const INPUT_TYPE_ATTRIBUTE = 'type';\n\n/**\n * Attributes captured in a `CachedElement`. The mutation observer watches\n * exactly this list, so a snapshot can never go stale on a mounted element.\n */\nexport const BINDING_ATTRIBUTES: readonly string[] = [\n FIELD_ATTRIBUTE,\n TYPE_ATTRIBUTE,\n TARGET_ATTRIBUTE_ATTRIBUTE,\n HREF_ATTRIBUTE,\n SRC_ATTRIBUTE,\n ALT_ATTRIBUTE,\n ARRAY_TEMPLATE_ATTRIBUTE,\n ARRAY_SEPARATOR_ATTRIBUTE,\n LOCALE_ATTRIBUTE,\n RICH_TEXT_ATTRIBUTE,\n HTML_ATTRIBUTE,\n ARRAY_ATTRIBUTE,\n STRUCTURAL_ATTRIBUTE,\n OWNER_ATTRIBUTE,\n DEPENDS_ATTRIBUTE,\n STRATEGY_ATTRIBUTE,\n BOUNDARY_ATTRIBUTE,\n INPUT_TYPE_ATTRIBUTE,\n];\n\nconst FIELD_SELECTOR = `[${FIELD_ATTRIBUTE}]`;\nconst OWNER_SELECTOR = `[${OWNER_ATTRIBUTE}]`;\n\n/** The document a binding belongs to: its nearest `data-payload-owner`, itself included. */\nexport function resolveBindingOwner(element: Element): string | undefined {\n const owner = element.closest(OWNER_SELECTOR)?.getAttribute(OWNER_ATTRIBUTE);\n return owner === null || owner === undefined || owner.length === 0 ? undefined : owner;\n}\n\n/** `namespace:name` — a project renderer key can never be a typo of a built-in type. */\nconst CUSTOM_RENDERER_KEY = /^[a-z][a-z0-9-]*:[a-z][a-z0-9-]*$/i;\n\nconst VALID_FIELD_TYPES: ReadonlySet<FieldType> = new Set<FieldType>([\n 'text',\n 'textarea',\n 'richText',\n 'email',\n 'number',\n 'checkbox',\n 'date',\n 'select',\n 'radio',\n 'array',\n 'blocks',\n 'group',\n 'tabs',\n 'row',\n 'collapsible',\n 'relationship',\n 'upload',\n 'point',\n 'json',\n 'code',\n 'ui',\n 'html',\n 'url',\n 'image',\n 'structural-array',\n]);\n\nfunction isRendererKey(value: string): value is RendererKey {\n return VALID_FIELD_TYPES.has(value as FieldType) || CUSTOM_RENDERER_KEY.test(value);\n}\n\nexport interface CacheBuildStats {\n readonly elementCount: number;\n readonly fieldCount: number;\n readonly durationMs: number;\n}\n\nexport interface ElementCacheOptions {\n /** Restricts which elements are accepted. Defaults to all. */\n readonly filter?: ElementPredicate;\n}\n\n/**\n * Elements share a field name when the same field is rendered in several\n * places; within a field the order is DOM order.\n */\nexport class ElementCache {\n private readonly entriesByField = new Map<string, CachedElement[]>();\n private entryByElement = new WeakMap<Element, CachedElement>();\n private readonly filter: ElementPredicate;\n private count = 0;\n private dependencies: DependencyMap | null = null;\n private islandRoots: readonly Element[] = [];\n\n constructor(options: ElementCacheOptions = {}) {\n this.filter = options.filter ?? alwaysTrue;\n }\n\n /** Source → dependents declared with `data-payload-depends`; memoised until the cache changes. */\n dependencyMap(): DependencyMap {\n if (this.dependencies !== null) return this.dependencies;\n const maps: DependencyMap[] = [];\n for (const binding of this.values()) {\n if (binding.dependsOn !== undefined) {\n maps.push(dependencyMapFromBinding(binding.fieldName, binding.dependsOn));\n }\n }\n this.dependencies = mergeDependencyMaps(...maps);\n return this.dependencies;\n }\n\n /** Island roots under the last built root, for update events. */\n get islands(): readonly Element[] {\n return this.islandRoots;\n }\n\n buildFromRoot(root: ParentNode): CacheBuildStats {\n const t0 = performance.now();\n this.clear();\n let elementCount = 0;\n for (const element of root.querySelectorAll(FIELD_SELECTOR)) {\n if (this.add(element) !== undefined) elementCount += 1;\n }\n this.islandRoots = collectIslands(root);\n return {\n elementCount,\n fieldCount: this.entriesByField.size,\n durationMs: performance.now() - t0,\n };\n }\n\n /**\n * Insert or replace a single element's binding. Re-adding refreshes the\n * snapshot in place; an element that is now filtered or unbound is removed.\n */\n add(element: Element): CachedElement | undefined {\n // Resolve before mutating so a throwing filter leaves the old entry intact.\n const entry = this.filter(element) ? this.resolveBinding(element) : undefined;\n const previous = this.entryByElement.get(element);\n this.dependencies = null;\n if (entry === undefined) {\n if (previous !== undefined) this.removeEntry(element, previous);\n return undefined;\n }\n if (previous !== undefined && this.replaceEntry(previous, entry)) {\n this.entryByElement.set(element, entry);\n return entry;\n }\n if (previous !== undefined) this.removeEntry(element, previous);\n this.append(entry);\n this.entryByElement.set(element, entry);\n return entry;\n }\n\n /** Returns whether a binding was removed. */\n remove(element: Element): boolean {\n const entry = this.entryByElement.get(element);\n if (!entry) return false;\n this.dependencies = null;\n return this.removeEntry(element, entry);\n }\n\n get(fieldName: string): readonly CachedElement[] | undefined {\n return this.entriesByField.get(fieldName);\n }\n\n getByElement(element: Element): CachedElement | undefined {\n return this.entryByElement.get(element);\n }\n\n get fieldCount(): number {\n return this.entriesByField.size;\n }\n\n get elementCount(): number {\n return this.count;\n }\n\n entries(): IterableIterator<[string, readonly CachedElement[]]> {\n return this.entriesByField.entries() as IterableIterator<[string, readonly CachedElement[]]>;\n }\n\n *values(): IterableIterator<CachedElement> {\n for (const bucket of this.entriesByField.values()) yield* bucket;\n }\n\n has(element: Element): boolean {\n return this.entryByElement.has(element);\n }\n\n clear(): void {\n this.entriesByField.clear();\n // WeakMap cannot be cleared; a detached element must not observe stale membership.\n this.entryByElement = new WeakMap();\n this.count = 0;\n this.dependencies = null;\n this.islandRoots = [];\n }\n\n /** Replace in place when the field bucket is unchanged, preserving order. */\n private replaceEntry(previous: CachedElement, next: CachedElement): boolean {\n if (previous.fieldName !== next.fieldName) return false;\n const bucket = this.entriesByField.get(previous.fieldName);\n const index = bucket === undefined ? -1 : bucket.indexOf(previous);\n if (bucket === undefined || index < 0) return false;\n bucket[index] = next;\n return true;\n }\n\n private removeEntry(element: Element, entry: CachedElement): boolean {\n this.entryByElement.delete(element);\n const bucket = this.entriesByField.get(entry.fieldName);\n const index = bucket === undefined ? -1 : bucket.indexOf(entry);\n if (bucket === undefined || index < 0) return false;\n bucket.splice(index, 1);\n if (bucket.length === 0) this.entriesByField.delete(entry.fieldName);\n this.count -= 1;\n return true;\n }\n\n private append(entry: CachedElement): void {\n const bucket = this.entriesByField.get(entry.fieldName);\n if (bucket) bucket.push(entry);\n else this.entriesByField.set(entry.fieldName, [entry]);\n this.count += 1;\n }\n\n private resolveBinding(element: Element): CachedElement | undefined {\n const fieldName = element.getAttribute(FIELD_ATTRIBUTE);\n if (fieldName === null || fieldName.length === 0) return undefined;\n const explicit = element.getAttribute(TYPE_ATTRIBUTE);\n const targetAttribute = element.getAttribute(TARGET_ATTRIBUTE_ATTRIBUTE);\n const hrefField = element.getAttribute(HREF_ATTRIBUTE);\n const srcField = element.getAttribute(SRC_ATTRIBUTE);\n const altField = element.getAttribute(ALT_ATTRIBUTE);\n const arrayTemplate = element.getAttribute(ARRAY_TEMPLATE_ATTRIBUTE);\n const arraySeparator = element.getAttribute(ARRAY_SEPARATOR_ATTRIBUTE);\n const locale = element.getAttribute(LOCALE_ATTRIBUTE);\n const owner = resolveBindingOwner(element);\n const dependsOn = parseDependencyList(element.getAttribute(DEPENDS_ATTRIBUTE));\n const strategy = element.getAttribute(STRATEGY_ATTRIBUTE);\n const fragmentBoundary = enclosingFragment(element);\n return {\n element,\n fieldName,\n fieldType: resolveFieldType(element),\n explicitFieldType: explicit !== null && isRendererKey(explicit),\n strategyKind: resolveStrategy(element) ?? 'unknown',\n ...(fragmentBoundary !== null ? { fragmentBoundary } : {}),\n ...(targetAttribute !== null && targetAttribute.length > 0 ? { targetAttribute } : {}),\n ...(hrefField !== null && hrefField.length > 0 ? { hrefField } : {}),\n ...(srcField !== null && srcField.length > 0 ? { srcField } : {}),\n ...(altField !== null && altField.length > 0 ? { altField } : {}),\n ...(arrayTemplate !== null ? { arrayTemplate } : {}),\n ...(arraySeparator !== null ? { arraySeparator } : {}),\n ...(locale !== null && locale.length > 0 ? { locale } : {}),\n ...(owner !== undefined ? { owner } : {}),\n ...(dependsOn.length > 0 ? { dependsOn } : {}),\n ...(strategy !== null && strategy.length > 0 ? { strategy } : {}),\n ...(element.hasAttribute(BOUNDARY_ATTRIBUTE) ? { boundary: true } : {}),\n };\n }\n}\n\n/** Explicit `data-payload-type`, then element heuristics, then `text`. */\nexport function resolveFieldType(element: Element): RendererKey {\n const explicit = element.getAttribute(TYPE_ATTRIBUTE);\n if (explicit !== null && isRendererKey(explicit)) return explicit;\n if (element.hasAttribute(RICH_TEXT_ATTRIBUTE)) return 'richText';\n if (element.hasAttribute(HTML_ATTRIBUTE)) return 'html';\n if (element.hasAttribute(STRUCTURAL_ATTRIBUTE)) return 'structural-array';\n if (element.hasAttribute(ARRAY_ATTRIBUTE)) return 'array';\n if (element.tagName === 'IMG') return 'image';\n if (element.tagName === 'A') return 'url';\n if (element.tagName === 'TIME') return 'date';\n if (element.tagName === 'INPUT') {\n const inputType = (element as HTMLInputElement).type;\n if (inputType === 'checkbox') return 'checkbox';\n if (inputType === 'number') return 'number';\n if (inputType === 'date' || inputType === 'datetime-local') return 'date';\n }\n return 'text';\n}\n\nfunction alwaysTrue(): boolean {\n return true;\n}\n","/**\n * Detect an invalid async result in a synchronous extension point.\n *\n * Rejected native Promises otherwise become unhandled after the caller falls\n * back synchronously. Assimilating the result through a handled Promise keeps\n * that contract violation observable only through the runtime's explicit\n * error channel.\n */\nexport function observeThenableResult(value: unknown): boolean {\n if ((typeof value !== 'object' || value === null) && typeof value !== 'function') return false;\n if (typeof (value as { readonly then?: unknown }).then !== 'function') return false;\n void Promise.resolve(value).catch(() => undefined);\n return true;\n}\n","import { observeThenableResult } from './thenable';\n\n/**\n * Diagnostics are observability, never control flow: a consumer logger may\n * throw or return a rejected thenable, and reporting a failure must not become\n * a second failure. Invocation stays synchronous for ordinary loggers.\n */\nexport function isolateDiagnostic(\n diagnostic: (...args: unknown[]) => unknown,\n): (...args: unknown[]) => void {\n return (...args): void => {\n try {\n observeThenableResult(diagnostic(...args));\n } catch {\n // Diagnostics must not become a second failure boundary.\n }\n };\n}\n\n/** Shared allocation-free default for disabled diagnostic channels. */\nexport function noopDiagnostic(): void {\n // Intentionally empty.\n}\n\n// Access, invocation and thenable inspection all happen inside the wrapper, so\n// a missing or hostile console cannot escape.\nexport const safeConsoleError = isolateDiagnostic((...args) =>\n (console.error as (...values: unknown[]) => unknown)(...args),\n);\n\nexport const safeConsoleWarn = isolateDiagnostic((...args) =>\n (console.warn as (...values: unknown[]) => unknown)(...args),\n);\n\nexport const safeConsoleDebug = isolateDiagnostic((...args) =>\n // eslint-disable-next-line no-console -- best-effort development diagnostics\n (console.debug as (...values: unknown[]) => unknown)(...args),\n);\n","/**\n * Server-side merge for Payload 3.x, whose admin posts raw form values with\n * relationships as bare ids. Like the official client, the update is re-fetched\n * through the REST API with `X-Payload-HTTP-Method-Override: GET`, which\n * merges the form values into the stored document and returns it populated.\n * Only the newest request matters: a newer merge aborts the one in flight.\n */\n\nimport { isolateDiagnostic, noopDiagnostic } from './diagnostics';\n\nexport interface DataMergerOptions {\n /** Payload server origin, e.g. `https://cms.example.com`. */\n readonly serverURL: string;\n /** REST route prefix. Defaults to `/api`. */\n readonly apiRoute?: string;\n /** Population depth requested from the server. Defaults to `1`. */\n readonly depth?: number;\n readonly fetchFn?: typeof fetch;\n readonly log?: (...args: unknown[]) => void;\n}\n\nexport interface MergeRequest {\n readonly collectionSlug?: string | undefined;\n readonly globalSlug?: string | undefined;\n readonly data: Record<string, unknown>;\n readonly locale?: string | undefined;\n}\n\n/** `superseded`: a newer merge replaced this one. `unavailable`: fall back to the raw values. */\nexport type MergeResult =\n | { readonly status: 'merged'; readonly doc: Record<string, unknown> }\n | { readonly status: 'superseded' }\n | { readonly status: 'unavailable' };\n\nfunction hasControlCharacter(value: string): boolean {\n for (const character of value) {\n const codePoint = character.codePointAt(0);\n if (codePoint !== undefined && (codePoint <= 0x1f || codePoint === 0x7f)) return true;\n }\n return false;\n}\n\nfunction isSafeSlug(value: string | undefined): value is string {\n if (\n value === undefined ||\n value.length === 0 ||\n value.length > 128 ||\n value === '.' ||\n value === '..' ||\n value.includes('/') ||\n value.includes('\\\\') ||\n value.includes('?') ||\n value.includes('#') ||\n hasControlCharacter(value)\n ) {\n return false;\n }\n try {\n encodeURIComponent(value);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction isSafeId(value: unknown): value is string | number {\n if (typeof value === 'number') return Number.isFinite(value);\n if (\n typeof value !== 'string' ||\n value.length === 0 ||\n value.length > 512 ||\n value === '.' ||\n value === '..' ||\n value.includes('/') ||\n value.includes('\\\\') ||\n hasControlCharacter(value)\n ) {\n return false;\n }\n try {\n encodeURIComponent(value);\n return true;\n } catch {\n // A lone surrogate cannot become a URL segment.\n return false;\n }\n}\n\nexport class DataMerger {\n private readonly serverURL: string;\n private readonly apiRoute: string;\n private readonly depth: number;\n private readonly fetchFn: typeof fetch | undefined;\n private readonly log: (...args: unknown[]) => void;\n private inflight: AbortController | null = null;\n private attempt = 0;\n private destroyDepth = 0;\n\n constructor(options: DataMergerOptions) {\n this.serverURL = options.serverURL.replace(/\\/+$/, '');\n const route = options.apiRoute ?? '/api';\n this.apiRoute = route.startsWith('/') ? route : `/${route}`;\n this.depth = options.depth ?? 1;\n this.fetchFn = options.fetchFn;\n this.log = options.log === undefined ? noopDiagnostic : isolateDiagnostic(options.log);\n }\n\n /** Collections need an `id` in the form values; globals only their slug. */\n canMerge(request: MergeRequest): boolean {\n try {\n // An empty global slug means \"collection document\" on the wire.\n if (request.globalSlug) return isSafeSlug(request.globalSlug);\n if (!isSafeSlug(request.collectionSlug)) return false;\n return isSafeId(request.data['id']);\n } catch {\n return false;\n }\n }\n\n async merge(request: MergeRequest): Promise<MergeResult> {\n if (this.destroyDepth > 0) return { status: 'superseded' };\n // Claim the attempt before aborting: abort listeners and fetch shims are\n // reentrant, and a newer merge they start must win.\n const attempt = (this.attempt += 1);\n const previous = this.inflight;\n this.inflight = null;\n let controller: AbortController | null = null;\n const superseded = (): boolean => this.attempt !== attempt;\n try {\n previous?.abort();\n if (superseded()) return { status: 'superseded' };\n // `canMerge` reads the request's own values, which may be consumer getters\n // that start a newer merge before throwing.\n if (!this.canMerge(request)) {\n return superseded() ? { status: 'superseded' } : { status: 'unavailable' };\n }\n const fetchFn = this.fetchFn ?? (typeof fetch === 'function' ? fetch : undefined);\n if (fetchFn === undefined) return { status: 'unavailable' };\n controller = new AbortController();\n this.inflight = controller;\n const endpoint = request.globalSlug\n ? `globals/${encodeURIComponent(request.globalSlug)}`\n : `${encodeURIComponent(request.collectionSlug ?? '')}/${encodeURIComponent(\n String(request.data['id']),\n )}`;\n const url = `${this.serverURL}${this.apiRoute}/${endpoint}`;\n const response = await fetchFn(url, {\n method: 'POST',\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n 'X-Payload-HTTP-Method-Override': 'GET',\n },\n body: JSON.stringify({\n data: request.data,\n depth: this.depth,\n // The admin already flattens locales before posting.\n flattenLocales: false,\n ...(request.locale !== undefined ? { locale: request.locale } : {}),\n }),\n signal: controller.signal,\n });\n // A fetch shim may ignore the signal; the attempt is authoritative.\n if (superseded() || isAborted(controller.signal)) return { status: 'superseded' };\n if (!response.ok) {\n this.log('merge HTTP', response.status, url);\n return { status: 'unavailable' };\n }\n const merged: unknown = await response.json();\n if (superseded() || isAborted(controller.signal)) return { status: 'superseded' };\n if (merged === null || typeof merged !== 'object' || Array.isArray(merged)) {\n this.log('merge invalid', url);\n return { status: 'unavailable' };\n }\n return { status: 'merged', doc: merged as Record<string, unknown> };\n } catch (error) {\n if (superseded() || (controller !== null && isAborted(controller.signal))) {\n return { status: 'superseded' };\n }\n this.log('merge exception', error);\n return { status: 'unavailable' };\n } finally {\n if (controller !== null && !superseded() && this.inflight === controller) {\n this.inflight = null;\n }\n }\n }\n\n /** Abort any in-flight merge. The merger stays usable across a stop/start cycle. */\n destroy(): void {\n this.attempt += 1;\n const inflight = this.inflight;\n this.inflight = null;\n this.destroyDepth += 1;\n try {\n inflight?.abort();\n } finally {\n this.destroyDepth -= 1;\n }\n }\n}\n\n/** Opaque to control-flow narrowing: an injected fetch or parser may await while another task aborts. */\nfunction isAborted(signal: AbortSignal): boolean {\n return signal.aborted;\n}\n","/**\n * What the peer does, derived from the capabilities its messages showed —\n * the runtime never asks which Payload version it is talking to. Unknown\n * until the admin reveals its shape. See ADR 0010.\n */\nimport type { ProtocolCapability } from './protocol-version';\n\nexport type ProtocolProfileName = 'unknown' | 'payload-2' | 'payload-3';\n\nexport interface ProtocolProfile {\n readonly name: ProtocolProfileName;\n /** Where field types come from. */\n readonly fieldTyping: 'schema' | 'heuristic';\n /**\n * Who populates relationships. Payload 2.x's admin posts populated data\n * (it merges client-side with `fieldSchemaJSON`); Payload 3.x posts raw\n * form values and the runtime asks the REST API when `serverURL` is set.\n */\n readonly populatesRelationships: 'admin' | 'server';\n /** Whether the peer reports document saves and relationship edits. */\n readonly documentEvents: boolean;\n}\n\nconst PAYLOAD_2: ProtocolProfile = {\n name: 'payload-2',\n fieldTyping: 'schema',\n populatesRelationships: 'admin',\n documentEvents: false,\n};\nconst PAYLOAD_3: ProtocolProfile = {\n name: 'payload-3',\n fieldTyping: 'heuristic',\n populatesRelationships: 'server',\n documentEvents: true,\n};\nconst UNKNOWN: ProtocolProfile = {\n name: 'unknown',\n fieldTyping: 'heuristic',\n populatesRelationships: 'server',\n documentEvents: false,\n};\n\n/**\n * `schema-json` on the wire is the Payload 2.x signature: 3.x removed\n * `fieldSchemaJSON`. Document or relationship events are 3.x-only. Until\n * either shows, the peer is unknown and treated like 3.x for merging — the\n * conservative choice, because a needless REST merge costs a request while\n * a missing one loses populated relationships.\n */\nexport function detectProtocolProfile(observed: ReadonlySet<ProtocolCapability>): ProtocolProfile {\n if (observed.has('schema-json')) return PAYLOAD_2;\n if (observed.has('document-events') || observed.has('relationship-events')) return PAYLOAD_3;\n return UNKNOWN;\n}\n","/** Shape guards for the messages the bus accepts. `null` counts as absent, as JSON bridges send it. */\n\nimport type {\n PayloadDocumentEventMessage,\n PayloadFieldSchema,\n PayloadLivePreviewMessage,\n} from '@/types/payload-protocol';\nimport { parseFieldSchema } from '@schema/parser';\n\nexport function isObjectMessage(value: unknown): value is { type: string } {\n return (\n typeof value === 'object' && value !== null && 'type' in value && typeof value.type === 'string'\n );\n}\n\n/** A `payload-live-preview` message: `data` a plain object when present, scalars of the right type or absent. */\nexport function isLivePreviewMessage(value: { type: string }): value is PayloadLivePreviewMessage {\n const v = value as Record<string, unknown>;\n if (v['data'] !== undefined && v['data'] !== null && !isPlainObject(v['data'])) return false;\n return (\n optionalTypeOk(v['fieldSchemaJSON'], (x) => Array.isArray(x)) &&\n optionalTypeOk(v['globalSlug'], (x) => typeof x === 'string') &&\n optionalTypeOk(v['collectionSlug'], (x) => typeof x === 'string') &&\n optionalTypeOk(v['locale'], (x) => typeof x === 'string') &&\n optionalTypeOk(v['ready'], (x) => typeof x === 'boolean') &&\n optionalTypeOk(v['previewToken'], (x) => typeof x === 'string') &&\n optionalTypeOk(v['protocolVersion'], (x) => typeof x === 'number')\n );\n}\n\n/** The non-empty field name of a `payload-live-preview-focus` message, else `undefined`. */\nexport function focusFieldOf(value: { type: string }): string | undefined {\n const field = (value as Record<string, unknown>)['field'];\n return typeof field === 'string' && field.length > 0 ? field : undefined;\n}\n\n/** Stock Payload sends only the `type`; custom senders may add the typed fields (omitted, never `null`). */\nexport function isDocumentEventMessage(value: {\n type: string;\n}): value is PayloadDocumentEventMessage {\n const v = value as Record<string, unknown>;\n return (\n optionalFieldOk(v['action'], (x) => x === 'updated' || x === 'created' || x === 'deleted') &&\n optionalFieldOk(v['slug'], (x) => typeof x === 'string') &&\n optionalFieldOk(\n v['id'],\n (x) => typeof x === 'string' || (typeof x === 'number' && Number.isFinite(x)),\n )\n );\n}\n\nfunction optionalFieldOk(value: unknown, check: (v: unknown) => boolean): boolean {\n return value === undefined || check(value);\n}\n\nfunction optionalTypeOk(value: unknown, check: (v: unknown) => boolean): boolean {\n return value === undefined || value === null || check(value);\n}\n\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null) return false;\n const prototype = Object.getPrototypeOf(value) as object | null;\n return prototype === null || Object.getPrototypeOf(prototype) === null;\n}\n\nconst NULL_AS_ABSENT_FIELDS = [\n 'data',\n 'fieldSchemaJSON',\n 'globalSlug',\n 'collectionSlug',\n 'locale',\n 'ready',\n 'previewToken',\n 'protocolVersion',\n] as const satisfies readonly (keyof PayloadLivePreviewMessage)[];\n\n/**\n * Drop `null` optionals so downstream sees the strict public type, and parse\n * the field schema entry by entry (malformed entries are dropped). Unknown\n * fields stay, for protocol evolution.\n */\nexport function normalizeLivePreviewMessage(\n message: PayloadLivePreviewMessage,\n): PayloadLivePreviewMessage {\n const normalized = { ...message };\n for (const field of NULL_AS_ABSENT_FIELDS) {\n const wireValue: unknown = Reflect.get(normalized, field);\n if (wireValue === null) Reflect.deleteProperty(normalized, field);\n }\n if (!Array.isArray(normalized.fieldSchemaJSON)) return normalized;\n let fieldSchemaJSON: readonly PayloadFieldSchema[];\n try {\n fieldSchemaJSON = parseFieldSchema(normalized.fieldSchemaJSON);\n } catch {\n fieldSchemaJSON = [];\n }\n return { ...normalized, fieldSchemaJSON };\n}\n","/**\n * postMessage ingress: origin and source checks, per-type shape guards, the\n * ordered preview-token validation queue, and the `ready` handshake. The bus\n * never throws; a rejected message is dropped or reported via `onInvalid`.\n * Consumer callbacks may detach or re-attach the bus synchronously, so\n * anything that runs after one re-checks the generation it started in.\n * See ADR 0004.\n */\n\nimport type {\n PayloadDocumentEventMessage,\n PayloadLivePreviewMessage,\n} from '@/types/payload-protocol';\nimport {\n focusFieldOf,\n isDocumentEventMessage,\n isLivePreviewMessage,\n isObjectMessage,\n isPlainObject,\n normalizeLivePreviewMessage,\n} from './message-guards';\nimport { LIBRARY_PROTOCOL_VERSION } from './protocol-version';\nimport { observeThenableResult } from './thenable';\n\nexport type OriginMatcher = (origin: string) => boolean;\n\n/** Identity of a data-bearing update: `revision` is monotonic, `generation` names the listener attachment. */\nexport interface MessageRevision {\n readonly revision: number;\n readonly generation: number;\n}\n\nexport type InvalidReason = 'origin' | 'shape' | 'type' | 'token' | 'source';\n\nexport interface MessageHandlers {\n /** A validated update; data-bearing ones carry their revision, ready handshakes do not. */\n readonly onUpdate: (\n msg: PayloadLivePreviewMessage,\n origin: string,\n messageRevision?: MessageRevision,\n ) => void;\n readonly onDocumentEvent: (msg: PayloadDocumentEventMessage, origin: string) => void;\n /** The admin reports the cursor moved into a field (reveal tier 2). */\n readonly onFocusField?: (field: string, origin: string) => void;\n readonly onInvalid?: (reason: InvalidReason, origin: string) => void;\n /** `'parent-or-opener'` refuses every window but the framing/opening one, even from an allowed origin. */\n readonly sourcePolicy?: 'any' | 'parent-or-opener';\n /**\n * Gate for data-bearing updates. Verdicts commit in arrival order, so an\n * earlier update is dispatched before a later one even when its validation\n * resolves later; an error counts as rejection.\n */\n readonly validateToken?: (\n token: string | undefined,\n origin: string,\n ) => boolean | Promise<boolean>;\n}\n\ninterface PendingValidation {\n readonly generation: number;\n readonly message: PayloadLivePreviewMessage;\n readonly origin: string;\n readonly messageRevision: MessageRevision | undefined;\n settled: boolean;\n approved: boolean;\n}\n\n/** Compact the consumed queue prefix only once it is both large and at least half the array. */\nconst QUEUE_COMPACTION_THRESHOLD = 1_024;\n\nexport class MessageBus {\n private readonly matcher: OriginMatcher;\n private readonly handlers: MessageHandlers;\n private boundListener: ((event: MessageEvent) => void) | undefined = undefined;\n private attachedTarget: Window | undefined = undefined;\n private generation = 0;\n private revision = 0;\n private queue: PendingValidation[] = [];\n private queueHead = 0;\n\n constructor(matcher: OriginMatcher, handlers: MessageHandlers) {\n this.matcher = matcher;\n this.handlers = handlers;\n }\n\n /** Start listening on `target`. Idempotent. */\n attach(target: Window = window): void {\n if (this.attachedTarget !== undefined) return;\n let committed = false;\n const listener = (event: MessageEvent): void => {\n // Each attachment owns its listener; a stale one must not borrow the new generation.\n if (!committed || this.boundListener !== listener) return;\n const generation = this.generation;\n try {\n this.receive(event, generation);\n } catch {\n // A synthetic event can carry throwing accessors; that is a shape failure.\n let origin: string;\n try {\n origin = event.origin;\n } catch {\n origin = '';\n }\n this.reportInvalid('shape', origin, generation);\n }\n };\n this.generation += 1;\n this.resetQueue();\n this.attachedTarget = target;\n this.boundListener = listener;\n try {\n target.addEventListener('message', listener);\n } catch (error) {\n // Invalidate before rollback: a hook may already have attached a newer generation.\n if (this.boundListener === listener) {\n this.attachedTarget = undefined;\n this.boundListener = undefined;\n this.resetQueue();\n }\n try {\n target.removeEventListener('message', listener);\n } catch {\n // Keep the original failure.\n }\n throw error;\n }\n if (this.boundListener === listener) {\n committed = true;\n } else {\n try {\n target.removeEventListener('message', listener);\n } catch {\n // The listener is identity-gated above even if removal fails.\n }\n }\n }\n\n /** Stop listening. Idempotent. */\n detach(): void {\n const target = this.attachedTarget;\n const listener = this.boundListener;\n if (target === undefined || listener === undefined) return;\n // Invalidate first so a listener already on the stack sees an obsolete generation.\n this.attachedTarget = undefined;\n this.boundListener = undefined;\n this.resetQueue();\n target.removeEventListener('message', listener);\n }\n\n /** Invalidate pending validations while staying attached (heartbeat expiry). */\n advanceGeneration(): boolean {\n if (this.attachedTarget === undefined) return false;\n this.generation += 1;\n this.resetQueue();\n return true;\n }\n\n /** Post the `ready` handshake to every target for every origin. */\n static sendReady(targets: readonly Window[], origins: readonly string[]): void {\n if (targets.length === 0 || origins.length === 0) return;\n const payload: PayloadLivePreviewMessage = {\n type: 'payload-live-preview',\n ready: true,\n protocolVersion: LIBRARY_PROTOCOL_VERSION,\n };\n for (const target of targets) {\n for (const origin of origins) {\n try {\n target.postMessage(payload, origin);\n } catch {\n // A malformed origin is the consumer's configuration problem.\n }\n }\n }\n }\n\n private receive(event: MessageEvent, generation: number): void {\n if (!this.isCurrentGeneration(generation)) return;\n const origin = event.origin;\n if (!this.matchesOrigin(origin, generation)) {\n this.reportInvalid('origin', origin, generation);\n return;\n }\n if (!this.matchesSource(event)) {\n this.reportInvalid('source', origin, generation);\n return;\n }\n const data: unknown = event.data;\n if (!isObjectMessage(data)) {\n this.reportInvalid('shape', origin, generation);\n return;\n }\n switch (data.type) {\n case 'payload-live-preview':\n if (!isLivePreviewMessage(data)) {\n this.reportInvalid('shape', origin, generation);\n return;\n }\n this.dispatchUpdate(normalizeLivePreviewMessage(data), origin, generation);\n return;\n case 'payload-document-event':\n if (!isDocumentEventMessage(data)) {\n this.reportInvalid('shape', origin, generation);\n return;\n }\n this.invokeHandler(generation, this.handlers.onDocumentEvent, data, origin);\n return;\n case 'payload-live-preview-focus': {\n const field = focusFieldOf(data);\n if (field === undefined) {\n this.reportInvalid('shape', origin, generation);\n return;\n }\n const onFocusField = this.handlers.onFocusField;\n if (onFocusField !== undefined) this.invokeHandler(generation, onFocusField, field, origin);\n return;\n }\n default:\n this.reportInvalid('type', origin, generation);\n }\n }\n\n private dispatchUpdate(\n message: PayloadLivePreviewMessage,\n origin: string,\n generation: number,\n ): void {\n const hasUpdateData = isPlainObject(message.data);\n if (!this.isCurrentGeneration(generation)) return;\n // A shape-valid data update consumes its revision before validation; a rejected token leaves a gap.\n const messageRevision = hasUpdateData\n ? { generation, revision: (this.revision += 1) }\n : undefined;\n const validator = this.handlers.validateToken;\n if (!this.isCurrentGeneration(generation)) return;\n if (validator === undefined) {\n this.commitUpdate(message, origin, generation, messageRevision);\n return;\n }\n // The data-less ready handshake carries no token and passes, so the admin learns we listen.\n if (message.ready === true && message.data === undefined) {\n this.commitUpdate(message, origin, generation, undefined);\n return;\n }\n const pending: PendingValidation = {\n generation,\n message,\n origin,\n messageRevision,\n settled: false,\n approved: false,\n };\n this.queue.push(pending);\n let verdict: unknown;\n try {\n // Invoked eagerly; only the commit waits for earlier queue entries.\n verdict = validator(message.previewToken, origin);\n } catch {\n this.settleValidation(pending, false);\n return;\n }\n if (typeof verdict === 'boolean') {\n this.settleValidation(pending, verdict);\n return;\n }\n // Assimilate any thenable; only literal `true` approves.\n void Promise.resolve(verdict).then(\n (approved) => {\n this.settleValidation(pending, approved === true);\n },\n () => {\n this.settleValidation(pending, false);\n },\n );\n }\n\n private settleValidation(pending: PendingValidation, approved: boolean): void {\n if (!this.isCurrentGeneration(pending.generation)) return;\n pending.approved = approved;\n pending.settled = true;\n this.drainQueue(pending.generation);\n }\n\n private drainQueue(generation: number): void {\n while (this.isCurrentGeneration(generation)) {\n const pending = this.queue[this.queueHead];\n if (pending === undefined) return;\n // The matcher may have narrowed since ingress (origin lock); an obsolete\n // origin must not hold the queue head and block the locked origin's work.\n if (!this.matchesOrigin(pending.origin, generation)) {\n if (!this.dequeue(pending)) continue;\n this.reportInvalid('origin', pending.origin, pending.generation);\n continue;\n }\n if (!pending.settled) return;\n if (!this.dequeue(pending)) continue;\n if (pending.approved) {\n this.commitUpdate(\n pending.message,\n pending.origin,\n pending.generation,\n pending.messageRevision,\n );\n } else {\n this.reportInvalid('token', pending.origin, pending.generation);\n }\n }\n }\n\n private commitUpdate(\n message: PayloadLivePreviewMessage,\n origin: string,\n generation: number,\n messageRevision: MessageRevision | undefined,\n ): void {\n if (!this.isCurrentGeneration(generation)) return;\n if (messageRevision === undefined) {\n this.invokeHandler(generation, this.handlers.onUpdate, message, origin);\n } else {\n this.invokeHandler(generation, this.handlers.onUpdate, message, origin, messageRevision);\n }\n }\n\n private reportInvalid(reason: InvalidReason, origin: string, generation: number): void {\n if (!this.isCurrentGeneration(generation)) return;\n const onInvalid = this.handlers.onInvalid;\n if (onInvalid !== undefined) this.invokeHandler(generation, onInvalid, reason, origin);\n }\n\n /** Under `'parent-or-opener'`, whether the event came from the attached window's parent or opener. */\n private matchesSource(event: MessageEvent): boolean {\n if (this.handlers.sourcePolicy !== 'parent-or-opener') return true;\n const target = this.attachedTarget;\n if (target === undefined) return false;\n try {\n const source = event.source;\n if (source === null) return false;\n const parent = target.parent;\n if (parent !== target && source === parent) return true;\n const opener: unknown = target.opener;\n return opener !== null && opener !== undefined && source === opener;\n } catch {\n return false;\n }\n }\n\n /** Fail-closed: only literal `true` from the matcher, and only within the generation it ran in. */\n private matchesOrigin(origin: string, generation: number): boolean {\n if (!this.isCurrentGeneration(generation)) return false;\n try {\n const approved: unknown = this.matcher(origin);\n return approved === true && this.isCurrentGeneration(generation);\n } catch {\n return false;\n }\n }\n\n /** Callbacks run only in a current generation and must not unwind the listener or the drain. */\n private invokeHandler<TArgs extends unknown[]>(\n generation: number,\n handler: (...args: TArgs) => unknown,\n ...args: TArgs\n ): void {\n if (!this.isCurrentGeneration(generation)) return;\n try {\n observeThenableResult(handler(...args));\n } catch {\n // Isolated by contract.\n }\n }\n\n private isCurrentGeneration(generation: number): boolean {\n return this.attachedTarget !== undefined && this.generation === generation;\n }\n\n /** Advance the head past `expected`, unless a matcher reset the queue meanwhile. */\n private dequeue(expected: PendingValidation): boolean {\n if (this.queue[this.queueHead] !== expected) return false;\n this.queueHead += 1;\n if (this.queueHead === this.queue.length) {\n this.resetQueue();\n return true;\n }\n if (this.queueHead >= QUEUE_COMPACTION_THRESHOLD && this.queueHead * 2 >= this.queue.length) {\n this.queue = this.queue.slice(this.queueHead);\n this.queueHead = 0;\n }\n return true;\n }\n\n private resetQueue(): void {\n this.queue = [];\n this.queueHead = 0;\n }\n}\n","/**\n * Mutation and intersection observers: ask the host to rebuild the cache when\n * bindings appear, vanish or change metadata, and track which bound elements\n * are in the viewport so off-screen writes can wait. Kept apart from cache and\n * scheduler so tests can run without the browser observer APIs.\n */\n\nimport { BINDING_ATTRIBUTES, FIELD_ATTRIBUTE, OWNER_ATTRIBUTE } from './cache';\n\nexport interface ObserverCallbacks {\n readonly onStructuralChange: () => void;\n readonly onVisibilityChange: (element: Element, isVisible: boolean) => void;\n}\n\nexport interface ObserverOptions {\n /** Debounce for mutation batches in ms. Default 100. */\n readonly mutationDebounceMs?: number;\n /** `rootMargin` for the IntersectionObserver. Default `200px`. */\n readonly intersectionRootMargin?: string;\n}\n\nconst DEFAULT_DEBOUNCE_MS = 100;\nconst DEFAULT_ROOT_MARGIN = '200px';\n/** `nodeType` is stable across realms; the global `Node` constructor is not. */\nconst ELEMENT_NODE = 1;\n\nexport class ObserverManager {\n private readonly callbacks: ObserverCallbacks;\n private readonly debounceMs: number;\n private readonly rootMargin: string;\n private readonly visible = new Set<Element>();\n private mutation: MutationObserver | null = null;\n private intersection: IntersectionObserver | null = null;\n private debounceTimer: ReturnType<typeof setTimeout> | null = null;\n /** Bumped by every start/stop so deliveries from an older lifetime are inert. */\n private generation = 0;\n\n constructor(callbacks: ObserverCallbacks, options: ObserverOptions = {}) {\n this.callbacks = callbacks;\n this.debounceMs = options.mutationDebounceMs ?? DEFAULT_DEBOUNCE_MS;\n this.rootMargin = options.intersectionRootMargin ?? DEFAULT_ROOT_MARGIN;\n }\n\n /** Observe `root`; a repeated start hands over cleanly. */\n start(root: Node): void {\n const previousGeneration = this.generation;\n this.stop();\n const generation = previousGeneration + 1;\n // A disconnect hook may have started a newer generation; it owns the lifecycle.\n if (this.generation !== generation) return;\n let mutation: MutationObserver | null = null;\n let intersection: IntersectionObserver | null = null;\n try {\n mutation = new MutationObserver((mutations) => {\n this.handleMutations(mutations, generation);\n });\n // Both resources exist before either is live, so a missing IntersectionObserver leaves nothing behind.\n intersection = new IntersectionObserver(\n (entries) => {\n this.handleIntersection(entries, generation);\n },\n { rootMargin: this.rootMargin, threshold: 0 },\n );\n mutation.observe(root, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: [...BINDING_ATTRIBUTES],\n });\n } catch (error) {\n mutation?.disconnect();\n intersection?.disconnect();\n throw error;\n }\n if (this.generation !== generation) {\n mutation.disconnect();\n intersection.disconnect();\n return;\n }\n this.mutation = mutation;\n this.intersection = intersection;\n }\n\n observeElement(element: Element): void {\n this.intersection?.observe(element);\n }\n\n unobserveElement(element: Element): void {\n this.intersection?.unobserve(element);\n this.visible.delete(element);\n }\n\n /** Seed visibility (tests). */\n markVisible(element: Element, visible: boolean): void {\n if (visible) this.visible.add(element);\n else this.visible.delete(element);\n }\n\n isVisible(element: Element): boolean {\n return this.visible.has(element);\n }\n\n /** Disconnect everything; safe to repeat. */\n stop(): void {\n // Invalidate first so queued deliveries and the timer are inert before disconnecting.\n this.generation += 1;\n const timer = this.debounceTimer;\n const mutation = this.mutation;\n const intersection = this.intersection;\n this.debounceTimer = null;\n this.mutation = null;\n this.intersection = null;\n this.visible.clear();\n if (timer !== null) clearTimeout(timer);\n try {\n mutation?.disconnect();\n } finally {\n intersection?.disconnect();\n }\n }\n\n private handleMutations(mutations: readonly MutationRecord[], generation: number): void {\n if (!this.isCurrentGeneration(generation) || !hasStructuralImpact(mutations)) return;\n if (this.debounceTimer !== null) clearTimeout(this.debounceTimer);\n const timer = setTimeout(() => {\n if (!this.isCurrentGeneration(generation) || this.debounceTimer !== timer) return;\n this.debounceTimer = null;\n this.callbacks.onStructuralChange();\n }, this.debounceMs);\n this.debounceTimer = timer;\n }\n\n private handleIntersection(\n entries: readonly IntersectionObserverEntry[],\n generation: number,\n ): void {\n for (const entry of entries) {\n if (!this.isCurrentGeneration(generation)) return;\n const { target } = entry;\n if (entry.isIntersecting) {\n if (this.visible.has(target)) continue;\n this.visible.add(target);\n this.callbacks.onVisibilityChange(target, true);\n } else if (this.visible.has(target)) {\n this.visible.delete(target);\n this.callbacks.onVisibilityChange(target, false);\n }\n }\n }\n\n private isCurrentGeneration(generation: number): boolean {\n return this.generation === generation && this.intersection !== null;\n }\n}\n\n/** Whether a mutation batch can change what is bound; unrelated DOM activity never rebuilds. */\nfunction hasStructuralImpact(mutations: readonly MutationRecord[]): boolean {\n for (const m of mutations) {\n if (\n m.type === 'attributes' &&\n m.attributeName !== null &&\n BINDING_ATTRIBUTES.includes(m.attributeName)\n ) {\n // The field and owner attributes matter anywhere; other metadata (notably\n // the native `type`) only on an element that is a binding.\n if (\n m.attributeName === FIELD_ATTRIBUTE ||\n m.attributeName === OWNER_ATTRIBUTE ||\n (m.target.nodeType === ELEMENT_NODE && (m.target as Element).hasAttribute(FIELD_ATTRIBUTE))\n ) {\n return true;\n }\n }\n for (const node of m.addedNodes) if (containsTrackedElement(node)) return true;\n for (const node of m.removedNodes) if (containsTrackedElement(node)) return true;\n }\n return false;\n}\n\nfunction containsTrackedElement(node: Node): boolean {\n if (node.nodeType !== ELEMENT_NODE) return false;\n const element = node as Element;\n return (\n element.hasAttribute(FIELD_ATTRIBUTE) || element.querySelector(`[${FIELD_ATTRIBUTE}]`) !== null\n );\n}\n","/** Connection status and the heartbeat that decides a disconnect. */\n\nexport type ConnectionStatus = 'disconnected' | 'connecting' | 'connected';\n\nexport interface HeartbeatOptions {\n /**\n * Silence before declaring a timeout. `0` disables the timer, which is right\n * for the stock Payload protocol: it sends messages only on edits, so any\n * idle timeout would report false disconnects.\n */\n readonly timeoutMs?: number;\n readonly onTimeout: () => void;\n}\n\nexport class HeartbeatTimer {\n private readonly timeoutMs: number;\n private readonly onTimeout: () => void;\n private handle: ReturnType<typeof setTimeout> | null = null;\n private lastKick = 0;\n\n constructor(options: HeartbeatOptions) {\n this.timeoutMs = options.timeoutMs ?? 0;\n this.onTimeout = options.onTimeout;\n }\n\n /** Called on every valid message; re-arms the timeout. */\n kick(): void {\n this.lastKick = Date.now();\n if (this.timeoutMs <= 0) return;\n if (this.handle !== null) clearTimeout(this.handle);\n const handle = setTimeout(() => {\n if (this.handle !== handle) return;\n this.handle = null;\n this.onTimeout();\n }, this.timeoutMs);\n this.handle = handle;\n }\n\n stop(): void {\n if (this.handle === null) return;\n clearTimeout(this.handle);\n this.handle = null;\n }\n\n get lastKickAt(): number {\n return this.lastKick;\n }\n\n get pending(): boolean {\n return this.handle !== null;\n }\n}\n\nexport class ConnectionState {\n private current: ConnectionStatus = 'disconnected';\n\n get status(): ConnectionStatus {\n return this.current;\n }\n\n /** Returns whether the status changed. */\n markConnected(): boolean {\n return this.transition('connected');\n }\n\n markDisconnected(): boolean {\n return this.transition('disconnected');\n }\n\n private transition(next: ConnectionStatus): boolean {\n if (this.current === next) return false;\n this.current = next;\n return true;\n }\n}\n","/**\n * Document ownership for bindings. A field name alone cannot identify a\n * binding on a page that previews several documents — `title` may belong to a\n * global, to shared SEO metadata and to every card at once. An owner marker\n * names the document a subtree belongs to, as a plain comparable string:\n * `global:<slug>`, `collection:<slug>`, `collection:<slug>:<id>`.\n */\n\n/** Identity of the document an incoming message describes. */\nexport interface MessageDocumentIdentity {\n readonly globalSlug?: string | undefined;\n readonly collectionSlug?: string | undefined;\n /** Primary key of the edited document, when the payload carries one. */\n readonly documentId?: string | undefined;\n}\n\n/** Owner key naming one Payload global. */\nexport function globalOwnerKey(slug: string): string {\n return `global:${slug}`;\n}\n\n/** Owner key for a collection; without an id it claims every document of it. */\nexport function collectionOwnerKey(slug: string, documentId?: string): string {\n return documentId === undefined || documentId === ''\n ? `collection:${slug}`\n : `collection:${slug}:${documentId}`;\n}\n\nfunction nonEmpty(value: string | undefined): value is string {\n return typeof value === 'string' && value.length > 0;\n}\n\n/**\n * Owner keys this message may address, or `null` when it carries no usable\n * identity — the runtime treats that as fail-closed rather than guessing. A\n * marker naming an id stays unreachable while the id is unknown: an unproven\n * identity must not satisfy an exact claim.\n */\nexport function messageOwnerKeys(identity: MessageDocumentIdentity): readonly string[] | null {\n if (nonEmpty(identity.globalSlug)) return [globalOwnerKey(identity.globalSlug)];\n if (!nonEmpty(identity.collectionSlug)) return null;\n const collectionKey = collectionOwnerKey(identity.collectionSlug);\n return nonEmpty(identity.documentId)\n ? [collectionKey, collectionOwnerKey(identity.collectionSlug, identity.documentId)]\n : [collectionKey];\n}\n\n/** Whether a binding may receive an update addressed to `keys`; an unowned binding never may. */\nexport function isBindingInScope(\n owner: string | undefined,\n keys: readonly string[] | null,\n): boolean {\n if (keys === null || owner === undefined) return false;\n return keys.includes(owner);\n}\n\n/** The document id Payload sends alongside the edited values; only scalars prove an identity. */\nexport function readDocumentId(fields: Record<string, unknown>): string | undefined {\n const id: unknown = fields['id'];\n if (typeof id === 'string' && id.length > 0) return id;\n if (typeof id === 'number' && Number.isFinite(id)) return String(id);\n return undefined;\n}\n","/** Field-path resolution for bindings and sibling-field metadata, prototype-safe. */\n\nconst BLOCKED_KEYS: ReadonlySet<string> = new Set(['__proto__', 'prototype', 'constructor']);\n\n/**\n * Resolve a dotted field path, preferring a `_<locale>` suffix when one is\n * active. Prototype-chain properties and pollution-prone segments never resolve.\n */\nexport function resolveFieldValue(\n fields: Record<string, unknown>,\n path: string,\n locale: string | undefined,\n preferLocale = false,\n): unknown {\n if (preferLocale && locale !== undefined) {\n const localized = readOwn(fields, `${path}_${locale}`);\n if (localized !== undefined) return localized;\n }\n const direct = readOwn(fields, path);\n if (direct !== undefined) return direct;\n\n if (path.includes('.')) {\n let current: unknown = fields;\n let resolved = true;\n for (const segment of path.split('.')) {\n if (BLOCKED_KEYS.has(segment) || current === null || typeof current !== 'object') {\n resolved = false;\n break;\n }\n current = readOwn(current as Record<string, unknown>, segment);\n if (current === undefined) {\n resolved = false;\n break;\n }\n }\n if (resolved) return current;\n }\n\n return locale === undefined ? undefined : readOwn(fields, `${path}_${locale}`);\n}\n\nfunction readOwn(object: Record<string, unknown>, key: string): unknown {\n if (BLOCKED_KEYS.has(key) || !Object.prototype.hasOwnProperty.call(object, key)) {\n return undefined;\n }\n return object[key];\n}\n","/**\n * LP0201: a scalar field arrived for which the page has no binding. The usual\n * cause is a template that renders the anchor only when the field is non-empty.\n */\n\nimport { isBindingInScope } from './binding-owner';\nimport type { ElementCache } from './cache';\n\n/** Document fields Payload ships in every update that nobody binds to. */\nconst SYSTEM_FIELD_NAMES: ReadonlySet<string> = new Set([\n 'id',\n '_id',\n 'createdAt',\n 'updatedAt',\n 'createdBy',\n 'updatedBy',\n '_status',\n 'globalType',\n 'collection',\n 'locale',\n 'localized',\n]);\n\nexport interface OrphanDiagnosticContext {\n readonly cache: ElementCache;\n readonly warned: Set<string>;\n readonly warn: (...args: unknown[]) => void;\n}\n\nexport function diagnoseOrphanFields(\n context: OrphanDiagnosticContext,\n fields: Readonly<Record<string, unknown>>,\n locale: string | undefined,\n ownerKeys: readonly string[] | null | false,\n): void {\n const { cache, warned, warn } = context;\n if (cache.fieldCount === 0) return;\n // With scoping on, a page that renders none of this document is normal.\n if (ownerKeys !== false && !ownsAnyBinding(cache, ownerKeys)) return;\n let localisedNames: Set<string> | undefined;\n for (const [rawName, value] of Object.entries(fields)) {\n if (warned.has(rawName) || SYSTEM_FIELD_NAMES.has(rawName)) continue;\n if (!isBindableScalar(value)) continue;\n const baseName = stripLocaleSuffix(rawName, locale);\n if (hasAddressableBinding(cache, rawName, ownerKeys)) continue;\n if (baseName !== rawName && hasAddressableBinding(cache, baseName, ownerKeys)) continue;\n localisedNames ??= localisedBindingNames(cache, ownerKeys);\n if (localisedNames.has(rawName)) continue;\n warned.add(rawName);\n warn(\n `[live-preview] LP0201: no <… data-payload-field=\"${baseName}\"> for field \"${rawName}\"; ` +\n 'render the anchor unconditionally so edits to an empty field have somewhere to land.',\n );\n }\n}\n\nfunction ownsAnyBinding(cache: ElementCache, ownerKeys: readonly string[] | null): boolean {\n for (const binding of cache.values()) {\n if (isBindingInScope(binding.owner, ownerKeys)) return true;\n }\n return false;\n}\n\nfunction hasAddressableBinding(\n cache: ElementCache,\n fieldName: string,\n ownerKeys: readonly string[] | null | false,\n): boolean {\n const bindings = cache.get(fieldName);\n if (bindings === undefined) return false;\n if (ownerKeys === false) return true;\n return bindings.some((binding) => isBindingInScope(binding.owner, ownerKeys));\n}\n\n/** `field_locale` names an element-local locale may consume while the message locale differs. */\nfunction localisedBindingNames(\n cache: ElementCache,\n ownerKeys: readonly string[] | null | false,\n): Set<string> {\n const names = new Set<string>();\n for (const [fieldName, bindings] of cache.entries()) {\n for (const binding of bindings) {\n if (ownerKeys !== false && !isBindingInScope(binding.owner, ownerKeys)) continue;\n if (binding.locale !== undefined) names.add(`${fieldName}_${binding.locale}`);\n }\n }\n return names;\n}\n\nfunction isBindableScalar(value: unknown): boolean {\n const type = typeof value;\n return type === 'string' || type === 'number' || type === 'boolean' || type === 'bigint';\n}\n\nfunction stripLocaleSuffix(name: string, locale: string | undefined): string {\n if (locale === undefined || locale.length === 0) return name;\n const suffix = `_${locale}`;\n return name.endsWith(suffix) ? name.slice(0, -suffix.length) : name;\n}\n","/**\n * Trusted Types: every HTML sink routes through one policy, `payload-live-preview`,\n * whose `createHTML` is the identity — what reaches a sink is already sanitized\n * or escaped. Without the API, strings pass through untouched.\n */\n\n/** The subset of the Trusted Types API this module needs. */\nexport interface TrustedHtmlPolicyLike {\n createHTML(input: string): unknown;\n}\n\ninterface TrustedTypesFactoryLike {\n createPolicy(\n name: string,\n rules: { createHTML: (input: string) => string },\n ): TrustedHtmlPolicyLike;\n}\n\nexport const TRUSTED_TYPES_POLICY_NAME = 'payload-live-preview';\n\nlet policyOverride: TrustedHtmlPolicyLike | null | undefined;\nlet autoPolicy: TrustedHtmlPolicyLike | null | undefined;\n\n/**\n * Use `policy` for every sink, `null` to assign plain strings, `undefined` to\n * return to the auto-created package policy.\n */\nexport function setTrustedTypesPolicy(policy: TrustedHtmlPolicyLike | null | undefined): void {\n policyOverride = policy;\n}\n\nfunction factory(): TrustedTypesFactoryLike | undefined {\n const candidate = (globalThis as { trustedTypes?: unknown }).trustedTypes;\n if (typeof candidate !== 'object' || candidate === null) return undefined;\n const create = (candidate as { createPolicy?: unknown }).createPolicy;\n return typeof create === 'function' ? (candidate as TrustedTypesFactoryLike) : undefined;\n}\n\nfunction resolvePolicy(): TrustedHtmlPolicyLike | null {\n if (policyOverride !== undefined) return policyOverride;\n if (autoPolicy !== undefined) return autoPolicy;\n const api = factory();\n if (api === undefined) {\n autoPolicy = null;\n return null;\n }\n try {\n autoPolicy = api.createPolicy(TRUSTED_TYPES_POLICY_NAME, { createHTML: (input) => input });\n } catch {\n // The site's `trusted-types` directive does not list this name; the\n // sink assignment will surface the enforcement error.\n autoPolicy = null;\n }\n return autoPolicy;\n}\n\n/** `html` as a `TrustedHTML` when a policy exists, else the string. Typed `string` for `innerHTML`. */\nexport function trustedHtml(html: string): string {\n const policy = resolvePolicy();\n if (policy === null) return html;\n return policy.createHTML(html) as string;\n}\n\n/** Test hook: forget the auto-created policy. */\nexport function __resetTrustedTypesForTests(): void {\n policyOverride = undefined;\n autoPolicy = undefined;\n}\n","/**\n * Keyed DOM morph: edits a live element toward a freshly rendered one while\n * keeping the live nodes, and with them focus, selection, scroll, playback and\n * listeners. Custom elements, islands, `contenteditable` and\n * `data-payload-owned` subtrees are boundaries the morph never enters.\n * See ADR 0008.\n */\n\nimport { ISLAND_ATTRIBUTE } from './islands';\n\nexport { ISLAND_ATTRIBUTE };\nexport const OWNED_ATTRIBUTE = 'data-payload-owned';\n\n/** Attributes the CMS controls only when the template names them (ADR 0008 §3). */\nconst STATE_ATTRIBUTES: ReadonlySet<string> = new Set(['open', 'value', 'checked', 'selected']);\n\nexport interface MorphOptions {\n /** Attributes that key child elements for pairing, tried in order; unkeyed children pair by position. */\n readonly keyAttributes: readonly string[];\n /** Called once per parent when two children share a key; the later ones pair by position. */\n readonly onDuplicateKey?: (parent: Element, key: string) => void;\n /** Elements whose attributes are synchronised but whose children are left alone (nested structural slots). */\n readonly retainChildrenOf?: (live: Element, rendered: Element) => boolean;\n}\n\n/** Empty attribute values (boolean markers such as `data-payload-island`) are not keys. */\nfunction keyOf(element: Element, options: MorphOptions): string | undefined {\n for (const attribute of options.keyAttributes) {\n const value = element.getAttribute(attribute);\n if (value !== null && value.length > 0) return `${attribute}=${value}`;\n }\n return undefined;\n}\n\nexport function isMorphBoundary(element: Element): boolean {\n if (element.tagName.toLowerCase().includes('-')) return true;\n if (element.hasAttribute(ISLAND_ATTRIBUTE) || element.hasAttribute(OWNED_ATTRIBUTE)) return true;\n const editable = element.getAttribute('contenteditable');\n return editable !== null && editable !== 'false';\n}\n\n/** Whether `live` can be edited toward `rendered` instead of being replaced by it. */\nexport function isMorphCompatible(live: Element, rendered: Element): boolean {\n return (\n live.tagName === rendered.tagName &&\n live.namespaceURI === rendered.namespaceURI &&\n !isMorphBoundary(live) &&\n !isMorphBoundary(rendered)\n );\n}\n\n/**\n * Morph `live` toward `rendered`. Returns `live` when it was retained, or\n * `rendered` when the two are incompatible and the caller must replace.\n * `rendered` is consumed: its children may move into `live`.\n */\nexport function morphElement(live: Element, rendered: Element, options: MorphOptions): Element {\n if (!isMorphCompatible(live, rendered)) return rendered;\n const focus = captureFocus(live);\n syncAttributes(live, rendered);\n if (options.retainChildrenOf?.(live, rendered) !== true) morphChildren(live, rendered, options);\n restoreFocus(focus);\n return live;\n}\n\n/** Match attributes, except that state-bearing ones change only when `rendered` carries them. */\nexport function syncAttributes(live: Element, rendered: Element): void {\n for (const attribute of Array.from(live.attributes)) {\n if (rendered.hasAttribute(attribute.name)) continue;\n if (STATE_ATTRIBUTES.has(attribute.name.toLowerCase())) continue;\n live.removeAttribute(attribute.name);\n }\n for (const attribute of Array.from(rendered.attributes)) {\n if (live.getAttribute(attribute.name) !== attribute.value) {\n live.setAttribute(attribute.name, attribute.value);\n }\n }\n}\n\nfunction morphChildren(live: Element, rendered: Element, options: MorphOptions): void {\n const liveKeyed = indexKeyed(live, options);\n const keyedElements = new Set<Node>(liveKeyed.values());\n const liveUnkeyed = Array.from(live.childNodes).filter((node) => !keyedElements.has(node));\n const claimed = new Set<Node>();\n const usedKeys = new Set<string>();\n const renderedNodes = Array.from(rendered.childNodes);\n let cursor: Node | null = live.firstChild;\n let unkeyedIndex = 0;\n\n for (let i = 0; i < renderedNodes.length; i += 1) {\n const next = renderedNodes[i] as Node;\n let kept: Node | null = null;\n let key = next instanceof Element ? keyOf(next, options) : undefined;\n // A repeated key on the rendered side pairs positionally like a live duplicate.\n if (key !== undefined && usedKeys.has(key)) key = undefined;\n if (key !== undefined) {\n usedKeys.add(key);\n const candidate = liveKeyed.get(key);\n if (candidate !== undefined && !claimed.has(candidate)) {\n kept = reconcile(candidate, next, options) === candidate ? candidate : null;\n if (kept === null) {\n candidate.replaceWith(next);\n claimed.add(next);\n cursor = next.nextSibling;\n continue;\n }\n }\n } else {\n while (unkeyedIndex < liveUnkeyed.length) {\n const candidate = liveUnkeyed[unkeyedIndex] as Node;\n unkeyedIndex += 1;\n if (claimed.has(candidate)) continue;\n if (sameKind(candidate, next)) {\n kept = reconcile(candidate, next, options) === candidate ? candidate : null;\n if (kept === null) {\n live.replaceChild(next, candidate);\n claimed.add(next);\n cursor = next.nextSibling;\n }\n break;\n }\n if (candidate instanceof Element) {\n // `next` is a text/comment, or an element whose kind the following\n // rendered node matches: an insertion, so the live element stays for it.\n const following = renderedNodes[i + 1];\n if (\n !(next instanceof Element) ||\n (following !== undefined && sameKind(candidate, following))\n ) {\n unkeyedIndex -= 1;\n break;\n }\n live.replaceChild(next, candidate);\n claimed.add(next);\n cursor = next.nextSibling;\n break;\n }\n if (!(next instanceof Element)) {\n // Text vs comment: replace rather than rewrite one node type's value into the other.\n live.replaceChild(next, candidate);\n claimed.add(next);\n cursor = next.nextSibling;\n break;\n }\n // A surplus live text/comment before the element `next` needs; removed below.\n }\n if (kept === null && claimed.has(next)) continue;\n }\n\n const node: Node = kept ?? next;\n claimed.add(node);\n // Whitespace-only text the template did not render is surplus. Stepping the\n // cursor over it keeps a retained element where it is: `insertBefore` on a\n // node already in the tree is a remove-and-insert, which blurs a focused input.\n while (cursor !== null && cursor !== node && !claimed.has(cursor) && isBlankText(cursor)) {\n cursor = cursor.nextSibling;\n }\n if (node !== cursor) live.insertBefore(node, cursor);\n cursor = node.nextSibling;\n }\n\n for (const child of Array.from(live.childNodes)) {\n if (!claimed.has(child)) child.remove();\n }\n}\n\n/** Retain `candidate` when it can be edited toward `next`; otherwise report `next`. */\nfunction reconcile(candidate: Node, next: Node, options: MorphOptions): Node {\n if (candidate instanceof Element && next instanceof Element) {\n // A compatible boundary stays exactly as it is (ADR 0008 §4).\n if (isMorphBoundary(candidate) && isMorphBoundary(next)) return candidate;\n return morphElement(candidate, next, options);\n }\n if (candidate.nodeValue !== next.nodeValue) candidate.nodeValue = next.nodeValue;\n return candidate;\n}\n\nfunction isBlankText(node: Node): boolean {\n return node.nodeType === Node.TEXT_NODE && (node.nodeValue ?? '').trim().length === 0;\n}\n\nfunction sameKind(a: Node, b: Node): boolean {\n if (a.nodeType !== b.nodeType) return false;\n if (a instanceof Element && b instanceof Element) {\n return a.tagName === b.tagName && a.namespaceURI === b.namespaceURI;\n }\n return true;\n}\n\n/** First element per key; later duplicates are left as they are and pair positionally. */\nfunction indexKeyed(parent: Element, options: MorphOptions): Map<string, Element> {\n const keyed = new Map<string, Element>();\n let duplicate: string | undefined;\n for (const child of Array.from(parent.children)) {\n const key = keyOf(child, options);\n if (key === undefined) continue;\n if (keyed.has(key)) {\n duplicate ??= key.slice(key.indexOf('=') + 1);\n continue;\n }\n keyed.set(key, child);\n }\n if (duplicate !== undefined) options.onDuplicateKey?.(parent, duplicate);\n return keyed;\n}\n\ninterface FocusSnapshot {\n readonly element: HTMLElement;\n readonly selection: readonly [number | null, number | null] | null;\n}\n\n/** A keyed move is a remove-and-insert, which blurs; remember what had focus. */\nfunction captureFocus(live: Element): FocusSnapshot | null {\n const active = live.ownerDocument.activeElement;\n if (!(active instanceof HTMLElement) || !live.contains(active)) return null;\n const selection =\n active instanceof HTMLInputElement || active instanceof HTMLTextAreaElement\n ? ([active.selectionStart, active.selectionEnd] as const)\n : null;\n return { element: active, selection };\n}\n\nfunction restoreFocus(snapshot: FocusSnapshot | null): void {\n if (snapshot === null) return;\n const { element, selection } = snapshot;\n if (element.ownerDocument.activeElement === element || !element.isConnected) return;\n try {\n element.focus({ preventScroll: true });\n const [start, end] = selection ?? [null, null];\n if (start !== null && end !== null) {\n (element as HTMLInputElement).setSelectionRange(start, end);\n }\n } catch {\n // Not focusable any more; nothing to restore.\n }\n}\n","/**\n * HTML sanitizer built on the host parser (`<template>`): allow-listed tags\n * and attributes, validated URLs, hardened external links, no `style`.\n * Needs a DOM; string-only sanitizers are historically brittle.\n */\n\nimport { trustedHtml } from './trusted-types';\nimport { isSafeUrl, isExternalHttpUrl } from './url-validator';\n\ndeclare const __INLINE_BUILD__: boolean | undefined;\n\n/** Tags kept with their content. Others are unwrapped unless in `REMOVE_COMPLETELY`. */\nconst ALLOWED_TAGS: ReadonlySet<string> = new Set([\n 'p',\n 'br',\n 'strong',\n 'b',\n 'em',\n 'i',\n 'u',\n 's',\n 'strike',\n 'mark',\n 'small',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'ul',\n 'ol',\n 'li',\n 'dl',\n 'dt',\n 'dd',\n 'blockquote',\n 'code',\n 'pre',\n 'kbd',\n 'samp',\n 'var',\n 'a',\n 'span',\n 'div',\n 'section',\n 'article',\n 'aside',\n 'header',\n 'footer',\n 'nav',\n 'figure',\n 'figcaption',\n 'img',\n 'picture',\n 'source',\n 'audio',\n 'video',\n 'sub',\n 'sup',\n 'hr',\n 'time',\n 'abbr',\n 'cite',\n 'q',\n 'table',\n 'thead',\n 'tbody',\n 'tfoot',\n 'tr',\n 'th',\n 'td',\n 'caption',\n 'colgroup',\n 'col',\n]);\n\n/** Tags `allowFormControls` re-admits for author templates; `form` is deliberately not one. */\nconst FORM_CONTROLS: ReadonlySet<string> = new Set([\n 'input',\n 'button',\n 'textarea',\n 'select',\n 'option',\n 'label',\n]);\n\n/** Removed with their children: the content itself is the hazard. */\nconst REMOVE_COMPLETELY: ReadonlySet<string> = new Set([\n 'script',\n 'style',\n 'iframe',\n 'object',\n 'embed',\n 'link',\n 'meta',\n 'base',\n 'form',\n 'input',\n 'button',\n 'select',\n 'textarea',\n 'svg',\n 'math',\n 'template',\n 'frame',\n 'frameset',\n 'noframes',\n 'noscript',\n]);\n\nconst ATTR_GLOBAL: ReadonlySet<string> = new Set([\n 'id',\n 'class',\n 'lang',\n 'dir',\n 'title',\n 'role',\n 'tabindex',\n]);\n\nconst ATTR_ARIA_PREFIX = 'aria-';\nconst ATTR_DATA_PREFIX = 'data-';\nconst BINDING_DATA_PREFIX = 'data-payload-';\n\nconst ATTR_BY_TAG: Readonly<Record<string, ReadonlySet<string>>> = {\n a: new Set(['href', 'target', 'rel', 'download', 'hreflang', 'type']),\n img: new Set(['src', 'srcset', 'sizes', 'alt', 'width', 'height', 'loading', 'decoding']),\n picture: new Set([]),\n source: new Set(['src', 'srcset', 'sizes', 'type', 'media']),\n audio: new Set(['src', 'controls', 'autoplay', 'loop', 'muted', 'preload']),\n video: new Set([\n 'src',\n 'poster',\n 'controls',\n 'autoplay',\n 'loop',\n 'muted',\n 'preload',\n 'width',\n 'height',\n 'playsinline',\n ]),\n time: new Set(['datetime']),\n abbr: new Set(['title']),\n q: new Set(['cite']),\n blockquote: new Set(['cite']),\n table: new Set(['summary']),\n th: new Set(['colspan', 'rowspan', 'scope', 'headers', 'abbr']),\n td: new Set(['colspan', 'rowspan', 'headers']),\n col: new Set(['span']),\n colgroup: new Set(['span']),\n ol: new Set(['start', 'reversed', 'type']),\n li: new Set(['value']),\n code: new Set(['class']),\n pre: new Set(['class']),\n};\n\nconst URL_ATTRIBUTES: ReadonlySet<string> = new Set(['href', 'src', 'cite', 'poster']);\n\n// Numeric nodeType constants keep an injected SSR document independent of a\n// browser-global `Node` constructor.\nconst ELEMENT_NODE = 1;\nconst COMMENT_NODE = 8;\n\n/** Thrown by `sanitizeHtml()` when no `document` is available (SSR without `setSanitizerDocument()`). */\nexport class SanitizerEnvironmentError extends Error {\n override readonly name = 'SanitizerEnvironmentError';\n}\n\n/**\n * `'strict'` (default) strips `id`, `name` and `data-payload-*` and passes\n * other `data-*` only via `allowedDataAttributes`; `'compat'` keeps them.\n */\nexport type SanitizerPolicyMode = 'compat' | 'strict';\n\nexport interface SanitizeOptions {\n /** Overrides the module default set by `setSanitizerPolicy()`. */\n readonly policy?: SanitizerPolicyMode;\n /** `data-*` attributes (full names) that pass under `'strict'`; `data-payload-*` never does. */\n readonly allowedDataAttributes?: readonly string[];\n /**\n * Keep `input`, `button`, `textarea`, `select`, `option` and `label` — only\n * for markup the page author wrote, never for CMS content. `form`,\n * handlers, `style` and unsafe URLs stay dropped.\n */\n readonly allowFormControls?: boolean;\n /** Extra tags to allow. Lower-case, untrimmed. */\n readonly additionalAllowedTags?: readonly string[];\n /**\n * Extra per-tag attributes, lower-case. Cannot re-admit handlers, `style`,\n * or — under `'strict'` — `id`, `name` and `data-payload-*`.\n */\n readonly additionalAllowedAttributes?: Readonly<Record<string, readonly string[]>>;\n /**\n * The input is a page-author item template, so `'strict'` keeps the\n * applier's reconciliation attributes (`TEMPLATE_ATTRIBUTES`) and nothing\n * else — every other `data-payload-*` is still stripped, so a template can\n * never add a binding.\n */\n readonly templateMode?: boolean;\n}\n\n/** What `templateMode` keeps under `'strict'`. */\nconst TEMPLATE_ATTRIBUTES: ReadonlySet<string> = new Set([\n 'id',\n 'name',\n 'data-payload-key',\n 'data-payload-nested-key',\n 'data-payload-nested-template',\n]);\n\ninterface ResolvedPolicy {\n readonly allowedTags: ReadonlySet<string>;\n readonly allowFormControls: boolean;\n readonly templateMode: boolean;\n readonly mode: SanitizerPolicyMode;\n readonly allowedData: ReadonlySet<string>;\n readonly attrByTag: ReadonlyMap<string, ReadonlySet<string>>;\n}\n\nlet defaultMode: SanitizerPolicyMode = 'strict';\n\n/** Set the policy for calls without an explicit `policy`. The runtime sets it from `sanitizerPolicy`. */\nexport function setSanitizerPolicy(mode: SanitizerPolicyMode): void {\n defaultMode = mode;\n}\n\nfunction resolvePolicy(options: SanitizeOptions | undefined): ResolvedPolicy {\n if (!options) {\n const attrMap = new Map<string, ReadonlySet<string>>();\n for (const [tag, attrs] of Object.entries(ATTR_BY_TAG)) attrMap.set(tag, attrs);\n return {\n allowedTags: ALLOWED_TAGS,\n attrByTag: attrMap,\n allowFormControls: false,\n templateMode: false,\n mode: defaultMode,\n allowedData: new Set(),\n };\n }\n const allowed = new Set(ALLOWED_TAGS);\n for (const tag of options.additionalAllowedTags ?? []) allowed.add(tag);\n if (options.allowFormControls === true) for (const tag of FORM_CONTROLS) allowed.add(tag);\n const attrMap = new Map<string, ReadonlySet<string>>();\n for (const [tag, attrs] of Object.entries(ATTR_BY_TAG)) attrMap.set(tag, attrs);\n for (const [tag, attrs] of Object.entries(options.additionalAllowedAttributes ?? {})) {\n const existing = attrMap.get(tag);\n const merged = new Set(existing ?? []);\n for (const attr of attrs) merged.add(attr);\n attrMap.set(tag, merged);\n }\n return {\n allowedTags: allowed,\n attrByTag: attrMap,\n allowFormControls: options.allowFormControls === true,\n templateMode: options.templateMode === true,\n mode: options.policy ?? defaultMode,\n allowedData: new Set((options.allowedDataAttributes ?? []).map((name) => name.toLowerCase())),\n };\n}\n\n/** The `Document` surface the sanitizer needs; jsdom, linkedom and happy-dom all provide it. */\nexport interface SanitizerDocument {\n createElement: (tagName: string) => {\n innerHTML: string;\n readonly content: ParentNode;\n };\n}\n\nlet documentOverride: SanitizerDocument | undefined;\n\n/** Supply a `Document` for SSR, e.g. linkedom's `parseHTML(...).document`; `null` clears it. */\nexport function setSanitizerDocument(doc: SanitizerDocument | null): void {\n documentOverride = doc ?? undefined;\n}\n\n/**\n * Sanitize `html`; malformed input is recovered by the parser first.\n *\n * @throws {SanitizerEnvironmentError} when no DOM is available.\n */\nexport function sanitizeHtml(html: string, options?: SanitizeOptions): string {\n const doc = resolveDocument();\n if (!doc) throw environmentError();\n if (html === '') return '';\n\n const policy = resolvePolicy(options);\n const template = doc.createElement('template');\n // The sanitizer's own parse is a sink too: under Trusted Types it needs the policy.\n template.innerHTML = trustedHtml(html);\n sanitizeFragment(template.content, policy);\n return template.innerHTML;\n}\n\n// Read the define at each branch rather than through a helper: a bundler\n// folds the substituted literal in place, but will not inline a call, and the\n// SSR-only class and override must not reach the browser runtime.\nfunction environmentError(): Error {\n if (typeof __INLINE_BUILD__ !== 'undefined' && __INLINE_BUILD__) {\n return new Error('sanitizeHtml needs a DOM');\n }\n return new SanitizerEnvironmentError(\n 'sanitizeHtml needs a DOM; provide one with setSanitizerDocument() during SSR.',\n );\n}\n\nfunction resolveDocument(): SanitizerDocument | undefined {\n if (typeof __INLINE_BUILD__ === 'undefined' || !__INLINE_BUILD__) {\n if (documentOverride) return documentOverride;\n }\n if (typeof document === 'undefined') return undefined;\n return document;\n}\n\n/** Whether a DOM is available — the global or an injected one — for callers that treat sanitizing as optional. */\nexport function hasSanitizerDocument(): boolean {\n return resolveDocument() !== undefined;\n}\n\nfunction sanitizeFragment(node: ParentNode, policy: ResolvedPolicy): void {\n // Snapshot: children are mutated during the walk.\n for (const child of Array.from(node.childNodes)) {\n if (child.nodeType === ELEMENT_NODE) {\n sanitizeElement(child as Element, policy);\n } else if (child.nodeType === COMMENT_NODE) {\n child.remove();\n }\n }\n}\n\nfunction sanitizeElement(element: Element, policy: ResolvedPolicy): void {\n const tag = element.tagName.toLowerCase();\n\n if (REMOVE_COMPLETELY.has(tag) && !(policy.allowFormControls && FORM_CONTROLS.has(tag))) {\n element.remove();\n return;\n }\n\n if (!policy.allowedTags.has(tag)) {\n sanitizeFragment(element, policy);\n const parent = element.parentNode;\n if (parent) {\n while (element.firstChild) parent.insertBefore(element.firstChild, element);\n element.remove();\n }\n return;\n }\n\n sanitizeAttributes(element, tag, policy);\n if (tag === 'a') hardenAnchor(element);\n sanitizeFragment(element, policy);\n}\n\nfunction sanitizeAttributes(element: Element, tag: string, policy: ResolvedPolicy): void {\n const tagAttrs = policy.attrByTag.get(tag);\n\n for (const attr of Array.from(element.attributes)) {\n const name = attr.name.toLowerCase();\n if (name.startsWith('on') || name === 'style') {\n element.removeAttribute(attr.name);\n continue;\n }\n if (policy.mode === 'strict') {\n if (policy.templateMode && TEMPLATE_ATTRIBUTES.has(name)) continue;\n // DOM clobbering and binding injection (docs/security.md §5c). Checked\n // before the allow-list so an extension cannot re-admit them.\n if (name === 'id' || name === 'name' || name.startsWith(BINDING_DATA_PREFIX)) {\n element.removeAttribute(attr.name);\n continue;\n }\n if (name.startsWith(ATTR_DATA_PREFIX)) {\n if (!policy.allowedData.has(name)) element.removeAttribute(attr.name);\n continue;\n }\n if (ATTR_GLOBAL.has(name) || name.startsWith(ATTR_ARIA_PREFIX)) continue;\n } else if (\n ATTR_GLOBAL.has(name) ||\n name.startsWith(ATTR_ARIA_PREFIX) ||\n name.startsWith(ATTR_DATA_PREFIX)\n ) {\n continue;\n }\n if (tagAttrs?.has(name)) {\n if (URL_ATTRIBUTES.has(name) && !isSafeUrl(attr.value)) {\n element.removeAttribute(attr.name);\n } else if (name === 'srcset' && !isSafeSrcset(attr.value)) {\n element.removeAttribute(attr.name);\n }\n continue;\n }\n element.removeAttribute(attr.name);\n }\n}\n\n/** Every `srcset` candidate must pass; partial rewriting would silently change what renders. */\nfunction isSafeSrcset(value: string): boolean {\n for (const candidate of value.split(',')) {\n const trimmed = candidate.trim();\n if (trimmed.length === 0) continue;\n const descriptorStart = trimmed.search(/\\s/);\n const url = descriptorStart === -1 ? trimmed : trimmed.slice(0, descriptorStart);\n if (!isSafeUrl(url)) return false;\n }\n return true;\n}\n\nfunction hardenAnchor(anchor: Element): void {\n const href = anchor.getAttribute('href');\n if (href === null || !isExternalHttpUrl(href)) return;\n anchor.setAttribute('rel', 'noopener noreferrer');\n if (!anchor.hasAttribute('target')) anchor.setAttribute('target', '_blank');\n}\n\n/** The built-in allow-lists, for documentation and tests. */\nexport const SANITIZER_POLICY = Object.freeze({\n allowedTags: ALLOWED_TAGS,\n removeCompletely: REMOVE_COMPLETELY,\n globalAttributes: ATTR_GLOBAL,\n attributesByTag: ATTR_BY_TAG,\n urlAttributes: URL_ATTRIBUTES,\n});\n","/** HTML and CSS escaping primitives (OWASP XSS Prevention Cheat Sheet). DOM-free. */\n\nconst HTML_ESCAPES: Readonly<Record<string, string>> = Object.freeze({\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#x27;',\n '/': '&#x2F;',\n '`': '&#x60;',\n '=': '&#x3D;',\n});\n\nconst HTML_ESCAPE_PATTERN = /[&<>\"'/`=]/g;\n\n/** Escape `text` for an element body or a *quoted* attribute value; strings only, and unquoted attributes are not covered. */\nexport function escapeHtml(text: string): string {\n if (text === '') return '';\n // The character class and the map are coupled: every match is a key.\n // eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style\n return text.replace(HTML_ESCAPE_PATTERN, (char) => HTML_ESCAPES[char] as string);\n}\n\n/** Escape a value for a CSS `url(...)` literal; this stops the break-out, not the scheme, so pair it with `isSafeUrl()`. */\nexport function escapeCssUrl(value: string): string {\n return value.replace(/['\"()\\\\]/g, '\\\\$&');\n}\n\nconst ATTR_ESCAPES: Readonly<Record<string, string>> = Object.freeze({\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#x27;',\n});\n\nconst ATTR_ESCAPE_PATTERN = /[&<>\"']/g;\n\n/** Escape a value for a *quoted* HTML attribute, leaving URL characters intact; it validates no scheme, so run `isSafeUrl()` on `href`/`src` first. */\nexport function escapeHtmlAttribute(value: string): string {\n if (value === '') return '';\n // eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style\n return value.replace(ATTR_ESCAPE_PATTERN, (char) => ATTR_ESCAPES[char] as string);\n}\n\n/** `escapeHtml()` then newlines to `<br>`; the order is what makes it safe. */\nexport function escapeAndLinebreak(text: string): string {\n return escapeHtml(text).replace(/\\r\\n|\\r|\\n/g, '<br>');\n}\n","/**\n * Interpolate one array-item template in a single pass. A replacement value is\n * data, not template syntax: one `replace()` per key would re-interpret\n * `{{index}}` text that an earlier value introduced, and would apply\n * `String.replace`'s `$` semantics to CMS content.\n */\n\nimport { escapeHtml } from '@security/escape';\n\nconst PLACEHOLDER_PATTERN = /\\{\\{([\\s\\S]*?)\\}\\}/g;\n\nfunction hasOwn(record: object, key: PropertyKey): boolean {\n return Object.prototype.hasOwnProperty.call(record, key);\n}\n\nexport function interpolateArrayTemplate(\n template: string,\n item: unknown,\n index: number,\n stringify: (value: unknown) => string,\n): string {\n const record = typeof item === 'object' && item !== null ? item : null;\n\n return template.replace(PLACEHOLDER_PATTERN, (placeholder, key: string) => {\n // Preserve the established object-field precedence when an object itself\n // has an `index` or `value` property. Otherwise these are reserved tokens.\n if (record !== null && hasOwn(record, key)) {\n return escapeHtml(stringify(Reflect.get(record, key)));\n }\n if (record === null && key === 'value') return escapeHtml(stringify(item));\n if (key === 'index') return String(index);\n return placeholder;\n });\n}\n","/** Value coercion shared by the field renderers. */\n\n/** Display string for any value: primitives as-is, objects as JSON, `null`/`undefined` as `''`. */\nexport function safeStringify(value: unknown): string {\n if (value === null || value === undefined) return '';\n if (typeof value === 'string') return value;\n if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {\n return String(value);\n }\n try {\n return JSON.stringify(value);\n } catch {\n return '';\n }\n}\n\n/** The three values every renderer treats as \"clear\" (docs/renderers.md, value semantics). */\nexport function isEmptyValue(value: unknown): value is null | undefined | '' {\n return value === null || value === undefined || value === '';\n}\n","/**\n * Sanitizer options for item templates (`data-payload-array-template`,\n * nested templates). A template is the page author's markup and every\n * interpolated value is escaped to text before the sanitizer runs, so it may\n * carry form controls and custom elements the rich-text policy refuses.\n * Event handlers, `style` and unsafe URLs are still stripped.\n *\n * Some entries below are already admitted by the sanitizer through another\n * route — `video` and `audio` by the tag allow-list, `select` by\n * `allowFormControls`, `name` by `templateMode`, and `controls`, `muted`,\n * `loop`, `poster` and `src` by the per-tag attribute map. They are kept\n * because this list states what a template may contain, and an allow-list\n * that depends on a second list staying unchanged is the more fragile of the\n * two arrangements. Mutating those entries changes nothing observable, so\n * they survive mutation testing by construction; the behaviour they describe\n * is pinned in `tests/unit/core/template-sanitize.test.ts` instead.\n */\n\nimport type { SanitizeOptions } from '@security/sanitizer';\n\nconst TEMPLATE_EXTRA_TAGS: readonly string[] = [\n 'input',\n 'textarea',\n 'select',\n 'option',\n 'button',\n 'label',\n 'details',\n 'summary',\n 'dialog',\n 'video',\n 'audio',\n 'progress',\n 'meter',\n];\n\nconst TEMPLATE_EXTRA_ATTRIBUTES: readonly string[] = [\n 'type',\n 'name',\n 'placeholder',\n 'open',\n 'disabled',\n 'readonly',\n 'required',\n 'checked',\n 'selected',\n 'value',\n 'min',\n 'max',\n 'step',\n 'rows',\n 'cols',\n 'for',\n 'controls',\n 'muted',\n 'loop',\n 'poster',\n 'src',\n];\n\nconst CUSTOM_TAG_PATTERN = /<([a-z][a-z0-9]*(?:-[a-z0-9]+)+)\\b/gi;\nconst optionsByTemplate = new Map<string, SanitizeOptions>();\n\n/** Options for one template; memoised per template string. */\nexport function templateSanitizeOptions(template: string): SanitizeOptions {\n const cached = optionsByTemplate.get(template);\n if (cached !== undefined) return cached;\n const tags = new Set(TEMPLATE_EXTRA_TAGS);\n for (const match of template.matchAll(CUSTOM_TAG_PATTERN)) {\n const tag = match[1]?.toLowerCase();\n if (tag !== undefined) tags.add(tag);\n }\n const attributes: Record<string, readonly string[]> = {};\n for (const tag of tags) attributes[tag] = TEMPLATE_EXTRA_ATTRIBUTES;\n const options: SanitizeOptions = {\n additionalAllowedTags: [...tags],\n additionalAllowedAttributes: attributes,\n allowFormControls: true,\n templateMode: true,\n };\n optionsByTemplate.set(template, options);\n return options;\n}\n","/**\n * Applies an `ArrayPatch[]` diff to a container as keyed DOM operations\n * instead of rebuilding the list, so consumer state on surviving children is\n * kept. Items are paired by `data-payload-key` (the item `id`); items without\n * one pair by position. Nested arrays reconcile recursively through\n * `data-payload-nested-key` slots. See ADR 0008.\n */\n\nimport { sanitizeHtml } from '@security/sanitizer';\nimport { trustedHtml } from '@security/trusted-types';\nimport { interpolateArrayTemplate } from './array-template';\nimport { safeStringify } from '@field-types/utils';\nimport { diffArray, type ArrayPatch } from '@schema/diff';\nimport { morphElement } from './morph';\nimport { templateSanitizeOptions } from './template-sanitize';\n\nexport const KEY_ATTRIBUTE = 'data-payload-key';\nconst NESTED_KEY_ATTRIBUTE = 'data-payload-nested-key';\nconst NESTED_TEMPLATE_ATTRIBUTE = 'data-payload-nested-template';\n\n/** Last value seen per item key, per container; owned by the caller so instances never share it. */\nexport type StructuralStore = WeakMap<Element, Map<string, unknown>>;\n\nexport function createStructuralStore(): StructuralStore {\n return new WeakMap<Element, Map<string, unknown>>();\n}\n\nexport interface StructuralApplyOptions {\n readonly template: string;\n readonly container: Element;\n readonly patches: readonly ArrayPatch[];\n /** The full new array; inserts and replaces render by index from it. */\n readonly nextItems: readonly unknown[];\n /** Pass the same store across renders so nested arrays diff incrementally. */\n readonly store: StructuralStore;\n /** Re-render existing items even when unchanged. */\n readonly forceRender?: boolean;\n /** Edit a changed item in place instead of replacing it. Default `true`. */\n readonly morph?: boolean;\n /** Reported once per container when two items share a key (`LP0405`). */\n readonly onDuplicateKey?: (container: Element, key: string) => void;\n}\n\n/**\n * Returns `true` for a DOM mutation, `false` for an already-current tree, and\n * `null` when an item's markup has no sanitized element root — preflighted\n * before any mutation, so the previous DOM and memory stay intact.\n */\nexport function applyStructuralPatches(options: StructuralApplyOptions): boolean | null {\n const { template, container, patches, nextItems, store, forceRender = false } = options;\n const plan = prepareStructuralPlan(container, template, patches, nextItems, forceRender, store);\n if (plan === null) return null;\n return commitStructuralPlan(plan, store, {\n morph: options.morph ?? true,\n onDuplicateKey: options.onDuplicateKey,\n });\n}\n\n// Plan records are tuples: many are created per recursive render, and named\n// keys would repeat in the inline bundle.\ntype StructuralPlan = readonly [\n container: Element,\n entries: readonly ReconciliationEntry[],\n nextItems: readonly unknown[],\n];\ntype ReconciliationEntry = readonly [\n index: number,\n live: Element | null,\n rendered: Element | undefined,\n nestedSlots: readonly NestedSlotPlan[],\n /** A `replace` patch: a different item, never morphed toward. */\n replace: boolean,\n];\ntype NestedSlotPlan = readonly [\n live: Element | null,\n rendered: Element,\n children: StructuralPlan | undefined,\n];\n\ninterface CommitOptions {\n readonly morph: boolean;\n readonly onDuplicateKey: ((container: Element, key: string) => void) | undefined;\n}\n\n/** A rendered slot that still carries a nested template keeps its children for its own plan. */\nfunction isManagedNestedSlot(_live: Element, rendered: Element): boolean {\n return (\n rendered.hasAttribute(NESTED_KEY_ATTRIBUTE) && rendered.hasAttribute(NESTED_TEMPLATE_ATTRIBUTE)\n );\n}\n\n/** Materialise the whole recursive replacement tree before touching live DOM. */\nfunction prepareStructuralPlan(\n container: Element,\n template: string,\n patches: readonly ArrayPatch[],\n nextItems: readonly unknown[],\n forceRender: boolean,\n store: StructuralStore,\n): StructuralPlan | null {\n const entries = prepareReconciliation(\n container,\n template,\n nextItems,\n createPatchPlan(patches),\n forceRender,\n store.get(container),\n store,\n );\n return entries === null ? null : [container, entries, nextItems];\n}\n\nfunction commitStructuralPlan(\n plan: StructuralPlan,\n store: StructuralStore,\n options: CommitOptions,\n): boolean {\n const [container, entries, nextItems] = plan;\n const claimed = new Set<Element>();\n let mutated = false;\n for (const [index, live, rendered, nestedSlots, replace] of entries) {\n let node = live;\n if (rendered !== undefined) {\n // Morph a compatible live item in place; otherwise transplant its live\n // nested slots into the rendered item and swap.\n const retained =\n options.morph && !replace && live !== null\n ? morphElement(live, rendered, {\n keyAttributes: [KEY_ATTRIBUTE, NESTED_KEY_ATTRIBUTE],\n retainChildrenOf: isManagedNestedSlot,\n ...(options.onDuplicateKey !== undefined\n ? { onDuplicateKey: options.onDuplicateKey }\n : {}),\n }) === live\n : false;\n if (!retained) {\n for (const [liveSlot, renderedSlot] of nestedSlots) {\n if (liveSlot === null) continue;\n synchronizeAttributes(liveSlot, renderedSlot);\n renderedSlot.replaceWith(liveSlot);\n }\n }\n for (const [, , children] of nestedSlots) {\n if (children !== undefined) commitStructuralPlan(children, store, options);\n }\n if (retained) {\n mutated = true;\n } else {\n if (live !== null) {\n live.replaceWith(rendered);\n mutated = true;\n }\n node = rendered;\n }\n }\n if (node === null) continue;\n const before = container.children[index] ?? null;\n if (node !== before) {\n container.insertBefore(node, before);\n mutated = true;\n }\n claimed.add(node);\n }\n // `nextItems` is the source of truth; this also drops SSR children the first value did not carry.\n for (const child of Array.from(container.children)) {\n if (claimed.has(child)) continue;\n child.remove();\n mutated = true;\n }\n const memory = getMemory(container, store);\n memory.clear();\n for (const value of nextItems) rememberItem(memory, value);\n return mutated;\n}\n\n/**\n * Pair every final item with a live child (by key, else by position) and\n * render what needs rendering. Patch indices describe `next`, live indices\n * move during reconciliation, so keyed nodes are resolved from the DOM first.\n */\nfunction prepareReconciliation(\n container: Element,\n template: string,\n nextItems: readonly unknown[],\n plan: PatchPlan,\n forceRender: boolean,\n memory: ReadonlyMap<string, unknown> | undefined,\n store: StructuralStore,\n): readonly ReconciliationEntry[] | null {\n const initialChildren = Array.from(container.children);\n const keyedChildren = indexByAttribute(initialChildren, KEY_ATTRIBUTE);\n const reserved = new Set<Element>();\n const entries: ReconciliationEntry[] = [];\n for (let index = 0; index < nextItems.length; index += 1) {\n const value = nextItems[index];\n const key = readKey(value);\n let live =\n key === undefined\n ? (initialChildren[index] ?? null)\n : (takeIndexedElement(keyedChildren, key) ?? null);\n if (live !== null && reserved.has(live)) live = null;\n if (live !== null) reserved.add(live);\n const replace = plan.replaces.has(index);\n const needsRender = forceRender || plan.renders.has(index) || live === null;\n const rendered = needsRender\n ? renderItem(container.ownerDocument, template, value, index)\n : undefined;\n if (rendered === null) return null;\n const nestedSlots =\n rendered === undefined\n ? []\n : prepareNestedSlots(replace ? null : live, rendered, value, memory, store);\n if (nestedSlots === null) return null;\n entries.push([index, live, rendered ?? undefined, nestedSlots, replace]);\n }\n return entries;\n}\n\ninterface PatchPlan {\n readonly renders: ReadonlySet<number>;\n readonly replaces: ReadonlySet<number>;\n}\n\nfunction createPatchPlan(patches: readonly ArrayPatch[]): PatchPlan {\n const renders = new Set<number>();\n const replaces = new Set<number>();\n for (const patch of patches) {\n if (patch.kind === 'insert' || patch.kind === 'update') renders.add(patch.index);\n else if (patch.kind === 'replace') {\n renders.add(patch.index);\n replaces.add(patch.index);\n }\n }\n return { renders, replaces };\n}\n\n/** Plan each direct nested slot; a failure at any depth aborts before commit. */\nfunction prepareNestedSlots(\n oldItem: Element | null,\n newItem: Element,\n nextValue: unknown,\n memory: ReadonlyMap<string, unknown> | undefined,\n store: StructuralStore,\n): readonly NestedSlotPlan[] | null {\n const oldSlots = oldItem === null ? [] : findDirectNestedSlots(oldItem);\n const oldSlotsByKey = indexByAttribute(oldSlots, NESTED_KEY_ATTRIBUTE);\n const itemKey = readKey(nextValue);\n const prevValue = itemKey !== undefined ? memory?.get(itemKey) : undefined;\n const plans: NestedSlotPlan[] = [];\n for (const newSlot of findDirectNestedSlots(newItem)) {\n const key = newSlot.getAttribute(NESTED_KEY_ATTRIBUTE);\n if (key === null) continue;\n const oldSlot = takeIndexedElement(oldSlotsByKey, key) ?? null;\n const nextTemplate = newSlot.getAttribute(NESTED_TEMPLATE_ATTRIBUTE);\n // Without a nested template the slot's rendered static content is authoritative.\n const liveSlot = nextTemplate ? oldSlot : null;\n const previousTemplate = liveSlot?.getAttribute(NESTED_TEMPLATE_ATTRIBUTE) ?? null;\n let children: StructuralPlan | undefined;\n if (nextTemplate) {\n const nextNested = readNestedArray(nextValue, key);\n if (nextNested !== undefined || liveSlot !== null) {\n const resolvedNext = nextNested ?? [];\n const prevNested = liveSlot === null ? [] : (readNestedArray(prevValue, key) ?? []);\n const patches = diffArray(prevNested, resolvedNext);\n const templateChanged = liveSlot !== null && previousTemplate !== nextTemplate;\n if (patches.length > 0 || templateChanged) {\n children =\n prepareStructuralPlan(\n liveSlot ?? newSlot,\n nextTemplate,\n patches,\n resolvedNext,\n templateChanged,\n store,\n ) ?? undefined;\n if (children === undefined) return null;\n }\n }\n }\n plans.push([liveSlot, newSlot, children]);\n }\n return plans;\n}\n\n/** Only the outermost nested slots: a transplanted slot owns the recursion below it. */\nfunction findDirectNestedSlots(item: Element): readonly Element[] {\n return Array.from(item.querySelectorAll(`[${NESTED_KEY_ATTRIBUTE}]`)).filter((slot) => {\n let ancestor = slot.parentElement;\n while (ancestor !== null && ancestor !== item) {\n if (ancestor.hasAttribute(NESTED_KEY_ATTRIBUTE)) return false;\n ancestor = ancestor.parentElement;\n }\n return ancestor === item;\n });\n}\n\nfunction synchronizeAttributes(target: Element, source: Element): void {\n for (const attribute of Array.from(target.attributes)) {\n if (!source.hasAttribute(attribute.name)) target.removeAttribute(attribute.name);\n }\n for (const attribute of Array.from(source.attributes)) {\n if (target.getAttribute(attribute.name) !== attribute.value) {\n target.setAttribute(attribute.name, attribute.value);\n }\n }\n}\n\nfunction readNestedArray(value: unknown, key: string): readonly unknown[] | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const nested = (value as Record<string, unknown>)[key];\n return Array.isArray(nested) ? (nested as readonly unknown[]) : undefined;\n}\n\nfunction getMemory(container: Element, store: StructuralStore): Map<string, unknown> {\n let map = store.get(container);\n if (!map) {\n map = new Map();\n store.set(container, map);\n }\n return map;\n}\n\nfunction rememberItem(memory: Map<string, unknown>, value: unknown): void {\n const key = readKey(value);\n if (key !== undefined) memory.set(key, value);\n}\n\nfunction readKey(value: unknown): string | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const id = (value as Record<string, unknown>)['id'];\n return typeof id === 'string' || typeof id === 'number' ? String(id) : undefined;\n}\n\nfunction indexByAttribute(elements: readonly Element[], attribute: string): Map<string, Element[]> {\n const indexed = new Map<string, Element[]>();\n // Reverse order so pop() yields duplicates in DOM order.\n for (let index = elements.length - 1; index >= 0; index -= 1) {\n const element = elements[index];\n if (element === undefined) continue;\n const key = element.getAttribute(attribute);\n if (key === null) continue;\n const bucket = indexed.get(key);\n if (bucket === undefined) indexed.set(key, [element]);\n else bucket.push(element);\n }\n return indexed;\n}\n\nfunction takeIndexedElement(indexed: Map<string, Element[]>, key: string): Element | undefined {\n return indexed.get(key)?.pop();\n}\n\n/** Render one item; its `id` is stamped as `data-payload-key` so later diffs find it. */\nfunction renderItem(\n ownerDocument: Document,\n template: string,\n value: unknown,\n index: number,\n): Element | null {\n const filled = interpolateArrayTemplate(template, value, index, safeStringify);\n const safe = sanitizeHtml(filled, templateSanitizeOptions(template));\n const host = ownerDocument.createElement('template');\n host.innerHTML = trustedHtml(safe);\n const first = host.content.firstElementChild;\n if (!first) return null;\n const key = readKey(value);\n if (key !== undefined) first.setAttribute(KEY_ATTRIBUTE, key);\n return first;\n}\n","/**\n * Runs the fragment and route strategies for a revision. A strategy that\n * throws or rejects is treated as failed, never left to reject the runtime.\n */\n\nimport type { PayloadLivePreviewData } from '@/types/payload-protocol';\nimport { trustedHtml } from '@security/trusted-types';\nimport { resolveFieldValue } from './field-value';\nimport { morphElement } from './morph';\nimport type { RuntimeDeps, RuntimeState, UpdateTransaction } from './runtime-state';\nimport type { FragmentContext, FragmentStrategy, RouteStrategy } from './strategies';\nimport { KEY_ATTRIBUTE } from './structural-applier';\nimport type { CachedElement } from './types';\n\n/** What the pipeline lends the runner. */\nexport interface StrategyHost {\n readonly reapply: (transaction: UpdateTransaction, data: PayloadLivePreviewData) => void;\n readonly transform: (\n target: CachedElement,\n value: unknown,\n allFields: Record<string, unknown>,\n isCurrent: () => boolean,\n ) => unknown;\n readonly rebuildCache: () => void;\n /** Scroll to the binding this revision marked, if it has not been revealed yet. */\n readonly revealPending: (transaction: UpdateTransaction) => void;\n}\n\nexport interface FragmentPlan {\n readonly boundaries: readonly Element[];\n readonly strategy: FragmentStrategy;\n /** Whether a binding sits inside a boundary the strategy renders this revision. */\n readonly covers: (target: CachedElement) => boolean;\n}\n\nexport class StrategyRunner {\n constructor(\n private readonly deps: RuntimeDeps,\n private readonly state: RuntimeState,\n private readonly host: StrategyHost,\n ) {}\n\n planFragments(touched: ReadonlySet<string>): FragmentPlan | null {\n const strategy = this.deps.strategies.fragment;\n if (strategy === undefined) return null;\n const boundaries = strategy.plan(this.deps.root, touched);\n const covered = new Set(boundaries);\n return {\n boundaries,\n strategy,\n covers: (target) =>\n target.fragmentBoundary !== undefined && covered.has(target.fragmentBoundary),\n };\n }\n\n /** Whether a touched field is bound to an element the route owns. */\n hasRouteBinding(touched: ReadonlySet<string>): boolean {\n for (const [fieldName, bindings] of this.deps.cache.entries()) {\n if (!touched.has(fieldName)) continue;\n if (bindings.some((target) => target.strategyKind === 'route')) return true;\n }\n return false;\n }\n\n async runFragments(\n transaction: UpdateTransaction,\n data: PayloadLivePreviewData,\n plan: FragmentPlan,\n ): Promise<void> {\n const { deps, state } = this;\n const controller = new AbortController();\n state.fragmentController = controller;\n const isCurrent = (): boolean => state.isCurrent(transaction) && !controller.signal.aborted;\n const { emitter } = deps;\n const { message } = transaction;\n const revision = transaction.identity.revision;\n const receivedAt = transaction.receivedAt;\n const context: FragmentContext = {\n root: deps.root,\n revision,\n receivedAt,\n fields: data.fields,\n locale: transaction.locale,\n collectionSlug:\n typeof message.collectionSlug === 'string' ? message.collectionSlug : undefined,\n globalSlug: typeof message.globalSlug === 'string' ? message.globalSlug : undefined,\n signal: controller.signal,\n isCurrent,\n log: (code, detail) => {\n deps.log('fragment', code, detail);\n },\n morph: (boundary, html) => {\n morphFragment(boundary, html);\n },\n patch: (boundary) => {\n this.patchFallback(transaction, data, boundary);\n },\n rendered: (element, id, key) => {\n transaction.pendingFragments -= 1;\n void emitter.emitWhile(\n 'fragmentRender',\n { element, id, key, status: 'rendered', revision, receivedAt },\n isCurrent,\n );\n },\n failed: (element, id, key, code, reason) => {\n transaction.pendingFragments -= 1;\n void emitter.emitWhile(\n 'error',\n {\n error: new Error(`fragment \"${id}\" fell back to patch: ${reason}`),\n context: 'fragment',\n code,\n },\n isCurrent,\n );\n void emitter.emitWhile(\n 'fragmentRender',\n { element, id, key, status: 'failed', code, revision, receivedAt },\n isCurrent,\n );\n },\n };\n let report = { rendered: 0, failed: 0, superseded: 0 };\n try {\n report = await plan.strategy.render(context, plan.boundaries);\n } catch (error) {\n deps.log('fragment', 'LP0801', error);\n if (isCurrent()) {\n for (const boundary of plan.boundaries) this.patchFallback(transaction, data, boundary);\n report = { rendered: 0, failed: plan.boundaries.length, superseded: 0 };\n }\n }\n state.fragmentStats.rendered += report.rendered;\n state.fragmentStats.failed += report.failed;\n state.fragmentStats.superseded += report.superseded;\n if (!isCurrent()) return;\n if (state.fragmentController === controller) state.fragmentController = null;\n transaction.pendingFragments = 0;\n if (deps.scheduler.pendingCount === 0) state.complete(transaction);\n // The edited field may be one the server just rendered: its element is only\n // in place now, so this is the earliest point it can be scrolled to.\n this.host.revealPending(transaction);\n if (!isCurrent()) return;\n if (report.rendered === 0 || emitter.listenerCount('afterUpdate') === 0) return;\n void emitter.emitWhile(\n 'afterUpdate',\n {\n data,\n updatedCount: report.rendered,\n durationMs: Date.now() - receivedAt,\n revision,\n receivedAt,\n source: 'fragment',\n },\n isCurrent,\n );\n }\n\n /** Refresh the route once per revision, then re-apply the revision onto the fresh markup. */\n async refreshRoute(\n transaction: UpdateTransaction,\n data: PayloadLivePreviewData,\n strategy: RouteStrategy,\n ): Promise<void> {\n const { deps, state } = this;\n const stats = state.routeStats;\n if (transaction.routeRefreshed) {\n stats.loopStopped += 1;\n deps.log(\n 'route',\n 'LP0805',\n `revision ${String(transaction.identity.revision)} asked for a second refresh`,\n );\n return;\n }\n transaction.routeRefreshed = true;\n const controller = new AbortController();\n state.routeController = controller;\n const isCurrent = (): boolean => state.isCurrent(transaction) && !controller.signal.aborted;\n let outcome: 'refreshed' | 'failed' | 'superseded';\n try {\n outcome = await strategy.refresh({\n revision: transaction.identity.revision,\n receivedAt: transaction.receivedAt,\n signal: controller.signal,\n isCurrent,\n log: (code, detail) => {\n deps.log('route', code, detail);\n },\n });\n } catch (error) {\n deps.log('route', 'LP0801', error);\n outcome = 'failed';\n }\n if (!isCurrent()) return;\n if (state.routeController === controller) state.routeController = null;\n if (outcome === 'refreshed') {\n stats.refreshes += 1;\n // The route rendered the saved document; nothing on the page is \"last applied\" any more.\n state.lastAppliedIdentity = new WeakMap();\n this.host.rebuildCache();\n if (!isCurrent()) return;\n this.host.reapply(transaction, data);\n if (deps.emitter.listenerCount('afterUpdate') > 0) {\n void deps.emitter.emitWhile(\n 'afterUpdate',\n {\n data,\n // The server re-rendered the whole route, so every binding now on\n // the page carries fresh markup; the unsaved fields scheduled just\n // above report themselves in their own `patch` batch.\n updatedCount: deps.cache.elementCount,\n durationMs: Date.now() - transaction.receivedAt,\n revision: transaction.identity.revision,\n receivedAt: transaction.receivedAt,\n source: 'route',\n },\n isCurrent,\n );\n }\n return;\n }\n if (outcome === 'failed') stats.failed += 1;\n this.host.reapply(transaction, data);\n }\n\n /** LP0806, once: a fragment boundary with no handler is patched instead. */\n warnFragmentFallback(target: CachedElement): void {\n if (this.state.warnedFragmentFallback) return;\n this.state.warnedFragmentFallback = true;\n this.deps.warn(\n `[live-preview] LP0806: \"${target.fieldName}\" asks for the fragment strategy but no handler is configured; patching instead`,\n );\n }\n\n /** LP0407, once per element: an unknown strategy is left alone, not guessed at. */\n warnUnsupportedStrategy(target: CachedElement): void {\n if (this.state.warnedStrategy.has(target.element)) return;\n this.state.warnedStrategy.add(target.element);\n this.deps.warn(\n `[live-preview] LP0407: \"${target.fieldName}\" asks for strategy \"${String(target.strategy)}\"; only patch, fragment and route exist`,\n );\n }\n\n /** The deterministic fallback: patch the boundary's own bindings from the same revision. */\n private patchFallback(\n transaction: UpdateTransaction,\n data: PayloadLivePreviewData,\n boundary: Element,\n ): void {\n for (const [fieldName, bindings] of this.deps.cache.entries()) {\n for (const target of bindings) {\n if (target.fragmentBoundary !== boundary) continue;\n const value = resolveFieldValue(\n data.fields,\n fieldName,\n target.locale ?? transaction.locale,\n target.locale !== undefined,\n );\n if (value === undefined) continue;\n this.deps.scheduler.schedule({\n target,\n value: this.host.transform(target, value, data.fields, () => true),\n allFields: data.fields,\n identity: transaction.identity,\n data,\n });\n }\n }\n }\n}\n\n/** Morph server-rendered HTML into the boundary, keeping focus and visitor state. */\nfunction morphFragment(boundary: Element, html: string): void {\n const template = boundary.ownerDocument.createElement('template');\n template.innerHTML = trustedHtml(html);\n const rendered = boundary.cloneNode(false) as Element;\n rendered.append(template.content);\n morphElement(boundary, rendered, { keyAttributes: [KEY_ATTRIBUTE] });\n}\n","/**\n * From an accepted message to scheduled writes: merge, diff, plan the\n * strategies, schedule each binding, and finish the revision on flush.\n */\n\nimport type { PayloadLivePreviewData, PayloadLivePreviewMessage } from '@/types/payload-protocol';\nimport { buildSchemaIndex } from '@schema/index';\nimport { isBindingInScope, messageOwnerKeys, readDocumentId } from './binding-owner';\nimport { mergeDependencyMaps } from './dependencies';\nimport { resolveFieldValue } from './field-value';\nimport { dispatchIslandUpdate } from './islands';\nimport type { MessageRevision } from './message-bus';\nimport { diagnoseOrphanFields } from './orphan-diagnostics';\nimport { detectProtocolProfile } from './protocol-profile';\nimport { observeCapabilities } from './protocol-version';\nimport type { RevealWindow } from './reveal';\nimport {\n sameRevision,\n type RuntimeDeps,\n type RuntimeState,\n type UpdateTransaction,\n} from './runtime-state';\nimport { resolveStrategy } from './strategies';\nimport { StrategyRunner } from './strategy-runner';\nimport { observeThenableResult } from './thenable';\nimport type { CachedElement } from './types';\nimport type { FlushStats, ScheduledUpdate } from './update-scheduler';\nimport { valueIdentity } from './value-identity';\n\nexport class UpdatePipeline {\n private readonly strategies: StrategyRunner;\n\n constructor(\n private readonly deps: RuntimeDeps,\n private readonly state: RuntimeState,\n rebuildCache: () => void,\n ) {\n this.strategies = new StrategyRunner(deps, state, {\n reapply: (transaction, data) => {\n this.scheduleAllFields(transaction, data);\n },\n transform: (target, value, allFields, isCurrent) =>\n this.transformForBinding(target, value, allFields, isCurrent),\n rebuildCache,\n revealPending: (transaction) => {\n this.revealPending(transaction);\n },\n });\n }\n\n /** Message-bus callback for every shape-valid update. */\n handleUpdate(\n message: PayloadLivePreviewMessage,\n origin: string,\n identity: MessageRevision | undefined,\n ): void {\n const { deps, state } = this;\n deps.heartbeat.kick();\n state.protocol.observe(observeCapabilities(message), deps.log);\n if (message.data === undefined) {\n if (message.protocolVersion !== undefined) {\n state.protocol.applyVersion(message.protocolVersion, deps.log);\n }\n return;\n }\n if (identity === undefined) return;\n const relationship = message.externallyUpdatedRelationship;\n const relationshipEdited = typeof relationship === 'object' && relationship !== null;\n if (relationshipEdited) {\n void deps.emitter.emit('relationshipUpdate', { detail: relationship, timestamp: Date.now() });\n }\n if (typeof message.locale === 'string') state.locale = message.locale;\n if (Array.isArray(message.fieldSchemaJSON)) {\n state.schema = message.fieldSchemaJSON;\n state.schemaIndex = buildSchemaIndex(message.fieldSchemaJSON);\n }\n const transaction: UpdateTransaction = {\n identity,\n message,\n locale: state.locale,\n schema: state.schema,\n schemaIndex: state.schemaIndex,\n receivedAt: Date.now(),\n forceRender: relationshipEdited,\n touched: new Set(),\n invalidated: new Set(),\n revealTarget: undefined,\n revealIdentities: [],\n pendingFragments: 0,\n routeRefreshed: false,\n cancelled: false,\n completed: false,\n };\n // Acceptance is the single supersession point. Only a revision that never\n // reached its terminal state counts as superseded.\n const previous = state.activeUpdate;\n state.abortStrategies();\n if (previous !== null && !previous.completed) state.supersededCount += 1;\n state.activeUpdate = transaction;\n deps.scheduler.acceptRevision(identity);\n state.updateCount += 1;\n if (message.protocolVersion !== undefined) {\n state.protocol.applyVersion(message.protocolVersion, deps.log);\n if (!state.isCurrent(transaction)) return;\n }\n if (deps.connection.markConnected()) {\n deps.a11y?.announceConnected();\n void deps.emitter.emit('connect', { origin, timestamp: Date.now() });\n if (!state.isCurrent(transaction)) return;\n deps.log('connection', 'disconnected', '→', 'connected');\n if (!state.isCurrent(transaction)) return;\n }\n // Nothing awaits this, so an unexpected throw would leave the page as an\n // unhandled rejection — a console error the host cannot attribute, and a\n // process exit under `--unhandled-rejections=strict`.\n void this.processUpdate(transaction).catch((error: unknown) => {\n deps.log('update failed:', error);\n });\n }\n\n private async processUpdate(transaction: UpdateTransaction): Promise<void> {\n const { deps, state } = this;\n const fields = await this.resolveIncomingFields(transaction);\n if (fields === null || !state.isCurrent(transaction)) return;\n const { message } = transaction;\n const data: PayloadLivePreviewData = {\n fields,\n ...(transaction.schema !== undefined ? { schema: transaction.schema } : {}),\n ...(typeof message.globalSlug === 'string' ? { globalSlug: message.globalSlug } : {}),\n ...(typeof message.collectionSlug === 'string'\n ? { collectionSlug: message.collectionSlug }\n : {}),\n ...(transaction.locale !== undefined ? { locale: transaction.locale } : {}),\n };\n if (deps.emitter.listenerCount('beforeUpdate') > 0) {\n const completed = await deps.emitter.emitWhile(\n 'beforeUpdate',\n {\n data,\n revision: transaction.identity.revision,\n receivedAt: transaction.receivedAt,\n source: 'patch',\n cancel: (): void => {\n transaction.cancelled = true;\n deps.scheduler.cancelRevision(transaction.identity);\n },\n },\n () => !transaction.cancelled && state.isCurrent(transaction),\n );\n if (!completed || transaction.cancelled || !state.isCurrent(transaction)) return;\n }\n const dependencies = mergeDependencyMaps(deps.dependencies, deps.cache.dependencyMap());\n const changes = state.changes.diff(fields, dependencies);\n transaction.invalidated = changes.invalidated;\n transaction.touched = new Set([...changes.changed, ...changes.invalidated]);\n this.scheduleAllFields(transaction, data);\n }\n\n /** The merged document when a `DataMerger` is configured, else the raw form values; `null` when superseded. */\n private async resolveIncomingFields(\n transaction: UpdateTransaction,\n ): Promise<Record<string, unknown> | null> {\n const { deps, state } = this;\n const raw = transaction.message.data ?? {};\n if (deps.merger === null) return raw;\n // A Payload 2.x admin posts populated relationships itself.\n if (detectProtocolProfile(state.protocol.observed).populatesRelationships === 'admin') {\n return raw;\n }\n const { message } = transaction;\n const result = await deps.merger.merge({\n collectionSlug: message.collectionSlug,\n globalSlug: message.globalSlug,\n data: raw,\n locale: transaction.locale,\n });\n if (!state.isCurrent(transaction)) return null;\n if (result.status === 'merged') return result.doc;\n if (result.status === 'superseded') return null;\n return raw;\n }\n\n scheduleAllFields(transaction: UpdateTransaction, data: PayloadLivePreviewData): void {\n const { deps, state } = this;\n if (!state.isCurrent(transaction)) return;\n const isCurrent = (): boolean => state.isCurrent(transaction);\n const ownerKeys = this.ownerKeysForUpdate(transaction, data.fields);\n const { touched } = transaction;\n // A revision that touches the route refreshes it first; the re-apply lands on the fresh markup.\n const route = deps.strategies.route;\n if (\n route !== undefined &&\n !transaction.routeRefreshed &&\n (route.plan(deps.root, touched) || this.strategies.hasRouteBinding(touched))\n ) {\n void this.strategies.refreshRoute(transaction, data, route);\n return;\n }\n const plan = this.strategies.planFragments(touched);\n // Only `skipUnchanged` needs it now; the reveal keeps its own ledger.\n const trackIdentity = deps.skipUnchanged;\n let scheduled = 0;\n for (const [fieldName, bindings] of deps.cache.entries()) {\n if (!isCurrent()) return;\n for (const target of bindings) {\n if (ownerKeys !== false && !isBindingInScope(target.owner, ownerKeys)) continue;\n // A binding inside a boundary the server renders is patched only as the\n // fallback — but it can still be the field being edited, so the reveal\n // has to notice it here, before the boundary is re-rendered.\n if (plan?.covers(target) === true) {\n // Resolving the value is only worth it when something reveals.\n if (deps.revealEditedField) {\n this.noteRevealCandidate(transaction, target, this.rawValue(transaction, target, data));\n }\n continue;\n }\n const kind = target.strategyKind ?? resolveStrategy(target.element) ?? 'unknown';\n if (kind === 'unknown') {\n this.strategies.warnUnsupportedStrategy(target);\n continue;\n }\n if (kind === 'fragment' && plan === null) this.strategies.warnFragmentFallback(target);\n const value = resolveFieldValue(\n data.fields,\n fieldName,\n target.locale ?? transaction.locale,\n target.locale !== undefined,\n );\n if (value === undefined) {\n state.absentFields.add(fieldName);\n continue;\n }\n // Noted before `skipUnchanged` can skip the write: the reveal ledger is\n // its own record, and a binding whose write is unchanged since the last\n // one that landed may still be the field whose reveal was superseded.\n this.noteRevealCandidate(transaction, target, value);\n if (!isCurrent()) return;\n const transformed = this.transformForBinding(target, value, data.fields, isCurrent);\n if (!isCurrent()) return;\n // A binding renders its own value *and* the sibling fields bound to\n // href/src/alt, so its identity must cover them: otherwise an edit to\n // the sibling alone looks unchanged and the link or image stays stale.\n const identity = trackIdentity\n ? bindingIdentity(target, transformed, data.fields, transaction.locale)\n : undefined;\n const last = state.lastAppliedIdentity.get(target.element);\n if (\n !transaction.forceRender &&\n deps.skipUnchanged &&\n identity !== undefined &&\n last === identity &&\n !transaction.invalidated.has(fieldName)\n ) {\n state.skippedUnchangedCount += 1;\n continue;\n }\n const update: ScheduledUpdate = {\n target,\n value: transformed,\n allFields: data.fields,\n identity: transaction.identity,\n data,\n valueIdentity: identity,\n };\n deps.scheduler.schedule(update);\n scheduled += 1;\n }\n }\n diagnoseOrphanFields(\n { cache: deps.cache, warned: state.warnedOrphanFields, warn: deps.warn },\n data.fields,\n transaction.locale,\n ownerKeys,\n );\n if (plan !== null && plan.boundaries.length > 0) {\n transaction.pendingFragments = plan.boundaries.length;\n void this.strategies.runFragments(transaction, data, plan);\n }\n // Nothing to flush is still this revision reaching its end — and its reveal\n // point: every write may be unchanged while the reveal is still owed.\n if (scheduled === 0 && transaction.pendingFragments === 0) {\n state.complete(transaction);\n this.revealPending(transaction);\n }\n }\n\n private rawValue(\n transaction: UpdateTransaction,\n target: CachedElement,\n data: PayloadLivePreviewData,\n ): unknown {\n return resolveFieldValue(\n data.fields,\n target.fieldName,\n target.locale ?? transaction.locale,\n target.locale !== undefined,\n );\n }\n\n /**\n * Record what this binding's value looks like now and, for the first binding\n * whose value moved, mark it as the one to reveal.\n *\n * The first message is a baseline and a binding new to the page is not an\n * edit, so an unseen key only records. A value too large or cyclic to compare\n * cannot claim to have changed either, or it would take the reveal from a\n * field that did. The ledger is keyed by document, locale and field rather\n * than by element: the element a fragment renders does not survive its own\n * re-render, but the field it shows is the same field.\n */\n private noteRevealCandidate(\n transaction: UpdateTransaction,\n target: CachedElement,\n value: unknown,\n ): void {\n const { deps, state } = this;\n if (!deps.revealEditedField) return;\n const identity = valueIdentity(value);\n if (identity === undefined) return;\n const key = `${target.owner ?? ''}\\u0000${target.locale ?? ''}\\u0000${target.fieldName}`;\n const seen = state.seenFieldIdentity.get(key);\n if (seen === undefined) {\n // A baseline is recorded at once: nothing is owed for it.\n state.seenFieldIdentity.set(key, identity);\n return;\n }\n if (seen === identity) return;\n transaction.revealIdentities.push([key, identity]);\n transaction.revealTarget ??= target;\n }\n\n /** Owner keys this update may address; `false` when scoping is off, `null` when the message names no document. */\n private ownerKeysForUpdate(\n transaction: UpdateTransaction,\n fields: Record<string, unknown>,\n ): readonly string[] | null | false {\n const { deps, state } = this;\n if (!deps.scopeBindingsByOwner) return false;\n const { message } = transaction;\n const keys = messageOwnerKeys({\n globalSlug: typeof message.globalSlug === 'string' ? message.globalSlug : undefined,\n collectionSlug:\n typeof message.collectionSlug === 'string' ? message.collectionSlug : undefined,\n documentId: readDocumentId(fields),\n });\n if (keys === null && !state.warnedUnattributableMessage) {\n state.warnedUnattributableMessage = true;\n deps.warn(\n '[live-preview] LP0202: scopeBindingsByOwner: update names no document; nothing applied',\n );\n }\n return keys;\n }\n\n /** Transforms are plugin code: frozen into the scheduler entry, errors reported, never awaited. */\n private transformForBinding(\n target: CachedElement,\n originalValue: unknown,\n allFields: Record<string, unknown>,\n isCurrent: () => boolean,\n ): unknown {\n const transform = this.deps.transformValue;\n if (transform === undefined) return originalValue;\n try {\n const transformed = transform(\n target.fieldName,\n originalValue,\n { element: target.element, allFields },\n isCurrent,\n );\n const returnedThenable = observeThenableResult(transformed);\n if (!isCurrent()) return originalValue;\n if (returnedThenable) {\n throw new TypeError(\n `Transform for \"${target.fieldName}\" returned a thenable; transforms must be synchronous`,\n );\n }\n return transformed;\n } catch (err) {\n if (!isCurrent()) return originalValue;\n const error = err instanceof Error ? err : new Error(String(err));\n void this.deps.emitter.emit('error', { error, context: 'transform', code: 'LP0602' });\n return originalValue;\n }\n }\n\n /** Scheduler callback after every flush, including one that applied nothing. */\n onFlush(stats: FlushStats): void {\n const { deps, state } = this;\n state.lastFlush = stats;\n if (stats.deferred > 0 && !state.warnedVisibilityGate) {\n state.warnedVisibilityGate = true;\n deps.warn(\n `[live-preview] LP0301: visibility gate held ${String(stats.deferred)} off-screen update(s) until scrolled into view; see visibilityGateThreshold`,\n );\n }\n const { identity, data } = stats;\n if (identity === undefined) return;\n const transaction = state.activeUpdate;\n if (\n transaction === null ||\n !state.isCurrent(transaction) ||\n !sameRevision(transaction.identity, identity)\n ) {\n return;\n }\n if (transaction.pendingFragments === 0) state.complete(transaction);\n const isCurrent = (): boolean =>\n state.isCurrent(transaction) && sameRevision(transaction.identity, identity);\n // Reveal before the applied check: the edited element may be exactly the\n // off-screen one the visibility gate deferred, and scrolling to it is what replays it.\n this.revealPending(transaction);\n if (!isCurrent()) return;\n if (stats.applied === 0 || data === undefined) return;\n deps.a11y?.announceUpdate(stats.applied);\n if (!isCurrent()) return;\n dispatchIslandUpdate(deps.cache.islands, {\n fields: data.fields,\n revision: identity.revision,\n receivedAt: transaction.receivedAt,\n locale: transaction.locale,\n });\n if (!isCurrent() || deps.emitter.listenerCount('afterUpdate') === 0) return;\n void deps.emitter.emitWhile(\n 'afterUpdate',\n {\n data,\n updatedCount: stats.applied,\n durationMs: stats.durationMs,\n revision: identity.revision,\n receivedAt: transaction.receivedAt,\n source: 'patch',\n },\n isCurrent,\n );\n }\n\n /**\n * Reveal the binding this revision marked, once. Called from the patch flush\n * and again once fragments land, because only one of the two runs for any\n * given field, and a fragment-rendered element is in place only afterwards.\n */\n revealPending(transaction: UpdateTransaction): void {\n // This revision reached its reveal point, so what it saw is now what the\n // ledger shows — whether or not the scroll below has anything to do.\n for (const [key, identity] of transaction.revealIdentities) {\n this.state.seenFieldIdentity.set(key, identity);\n }\n transaction.revealIdentities = [];\n const target = transaction.revealTarget;\n if (target === undefined) return;\n transaction.revealTarget = undefined;\n try {\n this.revealBinding(target);\n } catch (error) {\n this.deps.log('reveal', error);\n }\n }\n\n /**\n * Scroll one field's bound element into view; the admin-focus path (tier 2)\n * names a field, so it takes the first binding — a focus message carries no\n * document identity to choose between several.\n */\n revealField(fieldName: string): 'revealed' | 'already-visible' | 'skipped-same' | 'no-element' {\n const target = this.deps.cache.get(fieldName)?.[0];\n if (target === undefined) return 'no-element';\n return this.revealBinding(target);\n }\n\n private revealBinding(\n target: CachedElement,\n ): 'revealed' | 'already-visible' | 'skipped-same' | 'no-element' {\n const { element } = target;\n const win = element.ownerDocument.defaultView as RevealWindow | null;\n if (win === null) return 'no-element';\n // Keyed by document as well as field: two documents on one page have their\n // own `title`, and revealing one must not count as revealing the other.\n const key = `${target.owner ?? ''} ${target.fieldName}`;\n return this.state.revealer.reveal(key, element, win);\n }\n}\n\n/** Identity of everything a binding renders: its value plus any sibling href/src/alt fields. */\nfunction bindingIdentity(\n target: CachedElement,\n value: unknown,\n fields: Record<string, unknown>,\n locale: string | undefined,\n): string | undefined {\n const own = valueIdentity(value);\n if (own === undefined) return undefined;\n const siblings = [target.hrefField, target.srcField, target.altField];\n let combined = own;\n for (const sibling of siblings) {\n if (sibling === undefined || sibling.length === 0) continue;\n const resolved = resolveFieldValue(\n fields,\n sibling,\n target.locale ?? locale,\n target.locale !== undefined,\n );\n const identity = valueIdentity(resolved);\n if (identity === undefined) return undefined;\n combined += `|${sibling}=${identity}`;\n }\n return combined;\n}\n","/**\n * Debounce, frame batching and off-screen replay for scheduled writes. The\n * scheduler never touches the DOM; the injected `apply` callback does.\n */\n\nimport type { PayloadLivePreviewData } from '@/types/payload-protocol';\nimport { usesNoWriteOutcome } from './internal-outcome';\nimport type { MessageRevision } from './message-bus';\nimport type { CachedElement } from './types';\n\nexport interface ScheduledUpdate {\n readonly target: CachedElement;\n readonly value: unknown;\n readonly allFields: Record<string, unknown>;\n /** Revision identity; runtime-produced entries always carry one. */\n readonly identity?: MessageRevision | undefined;\n readonly data?: PayloadLivePreviewData | undefined;\n /** `valueIdentity(value)`, computed once by the pipeline for skip and reveal. */\n readonly valueIdentity?: string | undefined;\n}\n\nexport type ApplyUpdate = (update: ScheduledUpdate) => void;\n\nexport interface UpdateSchedulerOptions {\n /** Debounce window in ms. Default 50. */\n readonly debounceMs?: number;\n /** Longest a flush may be postponed by continuous scheduling. Default `4 * debounceMs`. */\n readonly maxWaitMs?: number;\n /** Deferred writes replay when the host reports the element visible via `notifyVisible()`. */\n readonly isVisible: (element: Element) => boolean;\n /** Apply every write immediately regardless of visibility. Default `false`. */\n readonly disableVisibilityGate?: boolean;\n /** Cached-element count above which the gate activates. Default 50. */\n readonly visibilityGateThreshold?: number;\n readonly getCacheSize: () => number;\n readonly onFlush?: (stats: FlushStats) => void;\n /** Frame scheduler; defaults to `requestAnimationFrame`. Tests inject a synchronous one. */\n readonly scheduleFrame?: (callback: FrameRequestCallback) => number;\n readonly cancelFrame?: (handle: number) => void;\n}\n\nexport interface FlushStats {\n readonly applied: number;\n /** Field names applied, in order; `applied` alone cannot say which binding stayed stale. */\n readonly appliedFields: readonly string[];\n readonly deferred: number;\n readonly durationMs: number;\n readonly identity?: MessageRevision;\n readonly data?: PayloadLivePreviewData;\n}\n\nconst DEFAULT_DEBOUNCE_MS = 50;\n/** Exported so `pll doctor` can prove its own copy of the number has not drifted. */\nexport const DEFAULT_VISIBILITY_THRESHOLD = 50;\n\ninterface BufferEntry {\n target: CachedElement;\n value: unknown;\n allFields: Record<string, unknown>;\n identity: MessageRevision | undefined;\n data: PayloadLivePreviewData | undefined;\n valueIdentity: string | undefined;\n}\n\nexport class UpdateScheduler {\n private readonly apply: ApplyUpdate;\n private readonly debounceMs: number;\n private readonly maxWaitMs: number;\n private readonly isVisible: (element: Element) => boolean;\n private readonly gateThresholdValue: number;\n private readonly gateDisabled: boolean;\n private readonly getCacheSize: () => number;\n private readonly onFlush: ((stats: FlushStats) => void) | undefined;\n private readonly scheduleFrame: (callback: FrameRequestCallback) => number;\n private readonly cancelFrame: (handle: number) => void;\n private pending = new Map<Element, BufferEntry>();\n private readonly replay = new Map<Element, BufferEntry>();\n private readonly activeFlushes = new Set<Map<Element, BufferEntry>>();\n private debounceTimer: ReturnType<typeof setTimeout> | null = null;\n private debounceToken = 0;\n private deadlineTimer: ReturnType<typeof setTimeout> | null = null;\n private frameHandle: number | null = null;\n private frameToken = 0;\n private activeIdentity: MessageRevision | null = null;\n private activeRevisionCancelled = false;\n\n constructor(apply: ApplyUpdate, options: UpdateSchedulerOptions) {\n this.apply = apply;\n this.debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;\n this.maxWaitMs = options.maxWaitMs ?? this.debounceMs * 4;\n this.isVisible = options.isVisible;\n this.gateThresholdValue = options.visibilityGateThreshold ?? DEFAULT_VISIBILITY_THRESHOLD;\n this.gateDisabled = options.disableVisibilityGate ?? false;\n this.getCacheSize = options.getCacheSize;\n this.onFlush = options.onFlush;\n this.scheduleFrame =\n options.scheduleFrame ??\n (typeof requestAnimationFrame === 'function'\n ? requestAnimationFrame.bind(globalThis)\n : (callback) =>\n setTimeout(() => {\n callback(performance.now());\n }, 0) as unknown as number);\n this.cancelFrame =\n options.cancelFrame ??\n (typeof cancelAnimationFrame === 'function'\n ? cancelAnimationFrame.bind(globalThis)\n : (handle) => {\n clearTimeout(handle as unknown as ReturnType<typeof setTimeout>);\n });\n }\n\n /** Queue a write; a later write for the same element replaces it until the flush. */\n schedule(update: ScheduledUpdate): void {\n if (update.identity !== undefined) {\n if (this.activeRevisionCancelled) return;\n if (!sameIdentity(update.identity, this.activeIdentity)) return;\n }\n const existing = this.pending.get(update.target.element);\n if (existing) {\n existing.value = update.value;\n existing.allFields = update.allFields;\n existing.identity = update.identity;\n existing.data = update.data;\n existing.valueIdentity = update.valueIdentity;\n } else {\n this.pending.set(update.target.element, {\n target: update.target,\n value: update.value,\n allFields: update.allFields,\n identity: update.identity,\n data: update.data,\n valueIdentity: update.valueIdentity,\n });\n }\n this.armDebounce();\n }\n\n /**\n * Make `identity` the sole revision allowed to schedule, flush or replay.\n * Older buffered work is dropped even if the new revision is later cancelled.\n */\n acceptRevision(identity: MessageRevision): void {\n if (sameIdentity(identity, this.activeIdentity)) return;\n if (this.activeIdentity !== null && compareIdentity(identity, this.activeIdentity) < 0) return;\n this.cancelScheduledWork();\n this.clearWork();\n this.activeIdentity = identity;\n this.activeRevisionCancelled = false;\n }\n\n /** Cancel buffered work for exactly one revision without reviving its predecessor. */\n cancelRevision(identity: MessageRevision): void {\n if (!sameIdentity(identity, this.activeIdentity)) return;\n this.cancelScheduledWork();\n this.clearWork();\n this.activeRevisionCancelled = true;\n }\n\n /** Flush immediately, bypassing the debounce. */\n flushNow(): FlushStats {\n this.cancelScheduledWork();\n return this.flush();\n }\n\n /** Apply the buffered value for an element that scrolled into view. */\n notifyVisible(element: Element): void {\n const entry = this.replay.get(element);\n if (!entry) return;\n this.replay.delete(element);\n if (!this.isCurrent(entry)) return;\n const t0 = performance.now();\n const applied = this.didApply(entry) ? 1 : 0;\n this.onFlush?.(\n this.statsFor(\n entry,\n applied,\n 0,\n performance.now() - t0,\n applied === 1 ? [entry.target.fieldName] : [],\n ),\n );\n }\n\n /**\n * Point buffered work at a rebuilt cache entry for the same element and\n * field. A different field or locale is a different binding: drop the work.\n */\n retarget(target: CachedElement): void {\n this.retargetBuffer(this.pending, target);\n this.retargetBuffer(this.replay, target);\n for (const flush of this.activeFlushes) this.retargetBuffer(flush, target);\n }\n\n forget(element: Element): void {\n this.pending.delete(element);\n this.replay.delete(element);\n for (const flush of this.activeFlushes) flush.delete(element);\n }\n\n /** Cancel timers and drop buffered state without draining it. */\n destroy(): void {\n this.cancelScheduledWork();\n this.clearWork();\n this.activeIdentity = null;\n this.activeRevisionCancelled = false;\n }\n\n get pendingCount(): number {\n return this.pending.size;\n }\n\n get replayCount(): number {\n return this.replay.size;\n }\n\n get gateThreshold(): number {\n return this.gateThresholdValue;\n }\n\n get gateActive(): boolean {\n return !this.gateDisabled && this.getCacheSize() > this.gateThresholdValue;\n }\n\n private armDebounce(): void {\n const token = (this.debounceToken += 1);\n const timer = this.debounceTimer;\n this.debounceTimer = null;\n if (timer !== null) clearTimeout(timer);\n // clearTimeout is a host boundary; a reentrant schedule owns a newer token.\n if (this.debounceToken !== token) return;\n const next = setTimeout(() => {\n if (this.debounceToken !== token) return;\n this.debounceTimer = null;\n this.requestFrame();\n }, this.debounceMs);\n if (this.debounceToken === token) this.debounceTimer = next;\n // Continuous scheduling (key repeat) must not postpone the flush forever.\n if (this.deadlineTimer === null && this.maxWaitMs > this.debounceMs) {\n this.deadlineTimer = setTimeout(() => {\n this.deadlineTimer = null;\n if (this.pending.size > 0) this.requestFrame();\n }, this.maxWaitMs);\n }\n }\n\n private requestFrame(): void {\n const token = (this.frameToken += 1);\n const handle = this.frameHandle;\n this.frameHandle = null;\n if (handle !== null) this.cancelFrame(handle);\n if (this.frameToken !== token) return;\n let completed = false;\n const next = this.scheduleFrame(() => {\n if (this.frameToken !== token) return;\n completed = true;\n this.frameHandle = null;\n this.flush();\n });\n // An injected scheduler may run the callback synchronously; never publish a spent handle.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!completed && this.frameToken === token) this.frameHandle = next;\n }\n\n private flush(): FlushStats {\n const t0 = performance.now();\n this.clearDeadline();\n const gateActive = this.gateActive;\n const pending = this.pending;\n this.pending = new Map();\n let applied = 0;\n const appliedFields: string[] = [];\n let deferred = 0;\n let batchEntry: BufferEntry | undefined;\n this.activeFlushes.add(pending);\n try {\n for (const entry of pending.values()) {\n if (!this.isCurrent(entry)) continue;\n const visible = !gateActive || this.isVisible(entry.target.element);\n // The visibility callback is consumer code and may change the revision.\n if (!this.isCurrent(entry)) continue;\n batchEntry ??= entry;\n if (!visible) {\n this.replay.set(entry.target.element, entry);\n deferred += 1;\n continue;\n }\n this.replay.delete(entry.target.element);\n if (this.didApply(entry)) {\n applied += 1;\n appliedFields.push(entry.target.fieldName);\n }\n }\n } finally {\n this.activeFlushes.delete(pending);\n }\n const stats = this.statsFor(\n batchEntry,\n applied,\n deferred,\n performance.now() - t0,\n appliedFields,\n );\n this.onFlush?.(stats);\n return stats;\n }\n\n private isCurrent(entry: BufferEntry): boolean {\n return (\n entry.identity === undefined ||\n (!this.activeRevisionCancelled && sameIdentity(entry.identity, this.activeIdentity))\n );\n }\n\n private didApply(entry: BufferEntry): boolean {\n // Only a runtime-marked callback may report exact `false` as \"no write\".\n // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression\n const outcome: unknown = this.apply(entry);\n return outcome !== false || !usesNoWriteOutcome(this.apply);\n }\n\n private retargetBuffer(buffer: Map<Element, BufferEntry>, target: CachedElement): void {\n const entry = buffer.get(target.element);\n if (entry === undefined) return;\n if (entry.target.fieldName !== target.fieldName || entry.target.locale !== target.locale) {\n buffer.delete(target.element);\n return;\n }\n entry.target = target;\n }\n\n private clearWork(): void {\n this.pending.clear();\n this.replay.clear();\n for (const flush of this.activeFlushes) flush.clear();\n }\n\n private statsFor(\n entry: BufferEntry | undefined,\n applied: number,\n deferred: number,\n durationMs: number,\n appliedFields: readonly string[],\n ): FlushStats {\n return {\n applied,\n appliedFields,\n deferred,\n durationMs,\n ...(entry?.identity !== undefined ? { identity: entry.identity } : {}),\n ...(entry?.data !== undefined ? { data: entry.data } : {}),\n };\n }\n\n private clearDeadline(): void {\n if (this.deadlineTimer === null) return;\n clearTimeout(this.deadlineTimer);\n this.deadlineTimer = null;\n }\n\n private cancelScheduledWork(): void {\n const debounceTimer = this.debounceTimer;\n const frameHandle = this.frameHandle;\n // Revoke tokens before calling host cancellation, so a hook that\n // schedules newer work is not clobbered by this older cleanup.\n this.debounceToken += 1;\n this.frameToken += 1;\n this.debounceTimer = null;\n this.frameHandle = null;\n this.clearDeadline();\n if (debounceTimer !== null) clearTimeout(debounceTimer);\n if (frameHandle !== null) this.cancelFrame(frameHandle);\n }\n}\n\nfunction sameIdentity(a: MessageRevision, b: MessageRevision | null): boolean {\n return b !== null && a.generation === b.generation && a.revision === b.revision;\n}\n\nfunction compareIdentity(a: MessageRevision, b: MessageRevision): number {\n if (a.generation !== b.generation) return a.generation - b.generation;\n return a.revision - b.revision;\n}\n","/**\n * `LivePreviewRuntime` builds the primitives, owns their lifecycle and hands\n * accepted messages to the update pipeline. It never speaks postMessage\n * itself and never walks the DOM during an update. See ADR 0004.\n */\n\nimport { A11yAnnouncer } from './a11y';\nimport { BindingWriter } from './binding-writer';\nimport { ElementCache } from './cache';\nimport { DataMerger } from './data-merger';\nimport type { DiagnosticCode } from './diagnostic-codes';\nimport { isolateDiagnostic, noopDiagnostic, safeConsoleWarn } from './diagnostics';\nimport { buildInspection } from './inspection/snapshot';\nimport type { LivePreviewInspection } from './inspection/types';\nimport { markNoWriteCallback } from './internal-outcome';\nimport { isInsideIsland } from './islands';\nimport { MessageBus } from './message-bus';\nimport { ObserverManager } from './observers';\nimport type { ProtocolNegotiation } from './protocol-version';\nimport type { RuntimeOptions } from './runtime-options';\nimport { RuntimeState, type RuntimeDeps } from './runtime-state';\nimport { ConnectionState, HeartbeatTimer } from './state';\nimport type { CachedElement } from './types';\nimport { UpdatePipeline } from './update-pipeline';\nimport { UpdateScheduler } from './update-scheduler';\n\nexport type { RuntimeOptions } from './runtime-options';\nexport { resolveFieldValue } from './field-value';\n\n/** Re-broadcast `ready` a few times to absorb admin-side init latency. */\nconst READY_RETRY_DELAYS_MS = [0, 500, 1000, 2000] as const;\n\nexport class LivePreviewRuntime {\n private readonly deps: RuntimeDeps;\n private readonly state = new RuntimeState();\n private readonly pipeline: UpdatePipeline;\n private readonly writer: BindingWriter;\n /** Watches `<html>` for a swapped `<body>` so the observers follow it. */\n private rootSentinel: MutationObserver | null = null;\n private observedRoot: Node | null = null;\n\n constructor(options: RuntimeOptions) {\n const { emitter, renderers } = options;\n const log = options.log === undefined ? noopDiagnostic : isolateDiagnostic(options.log);\n const warn = options.warn === undefined ? safeConsoleWarn : isolateDiagnostic(options.warn);\n const root =\n options.root ?? (typeof document !== 'undefined' ? document : (null as unknown as Document));\n // Bindings inside a hydrated island are the island's business (ADR 0008 §4).\n const cache = new ElementCache({ filter: (element) => !isInsideIsland(element) });\n const observers = new ObserverManager(\n {\n onStructuralChange: () => {\n this.rebuildCache();\n },\n onVisibilityChange: (element, visible) => {\n if (visible) scheduler.notifyVisible(element);\n },\n },\n options.intersectionRootMargin !== undefined\n ? { intersectionRootMargin: options.intersectionRootMargin }\n : {},\n );\n const scheduler = new UpdateScheduler(\n markNoWriteCallback((update) => this.writer.apply(update)),\n {\n ...(options.debounceMs !== undefined ? { debounceMs: options.debounceMs } : {}),\n ...(options.disableVisibilityGate !== undefined\n ? { disableVisibilityGate: options.disableVisibilityGate }\n : {}),\n ...(options.visibilityGateThreshold !== undefined\n ? { visibilityGateThreshold: options.visibilityGateThreshold }\n : {}),\n isVisible: (element) => observers.isVisible(element),\n getCacheSize: () => cache.elementCount,\n onFlush: (stats) => {\n this.pipeline.onFlush(stats);\n },\n },\n );\n const bus = new MessageBus(options.originMatcher, {\n onUpdate: (message, origin, identity) => {\n this.pipeline.handleUpdate(message, origin, identity);\n },\n onDocumentEvent: () => {\n this.state.protocol.observe(['document-events'], log);\n void emitter.emit('documentSave', { timestamp: Date.now() });\n },\n onFocusField: (field) => {\n if (this.deps.revealEditedField) this.pipeline.revealField(field);\n },\n onInvalid: (reason, origin) => {\n if (reason === 'token') {\n const error = new Error(`Preview token rejected (origin: ${origin})`);\n void emitter.emit('error', { error, context: 'token', code: 'LP0502' });\n }\n log('LP0501 message rejected:', reason, origin);\n },\n ...(options.validateToken !== undefined ? { validateToken: options.validateToken } : {}),\n ...(options.eventSourcePolicy !== undefined\n ? { sourcePolicy: options.eventSourcePolicy }\n : {}),\n });\n const merge = options.dataMerge;\n this.deps = {\n emitter,\n cache,\n observers,\n scheduler,\n bus,\n connection: new ConnectionState(),\n heartbeat: new HeartbeatTimer({\n ...(options.heartbeatMs !== undefined ? { timeoutMs: options.heartbeatMs } : {}),\n onTimeout: () => {\n this.onHeartbeatTimeout();\n },\n }),\n renderers,\n resolveRenderer: options.resolveRenderer ?? ((fieldType) => renderers[fieldType]),\n transformValue: options.transformValue,\n renderRichText: options.renderRichText,\n root,\n readyTargets:\n typeof options.readyTargets === 'function'\n ? options.readyTargets\n : (\n (targets) => (): readonly string[] =>\n targets\n )(options.readyTargets),\n sendReady: options.sendReady ?? defaultSendReady,\n onHeartbeatTimeout: options.onHeartbeatTimeout,\n log,\n warn,\n a11y: createA11y(options),\n merger:\n merge === undefined\n ? null\n : new DataMerger({\n serverURL: merge.serverURL,\n ...(merge.apiRoute !== undefined ? { apiRoute: merge.apiRoute } : {}),\n ...(merge.depth !== undefined ? { depth: merge.depth } : {}),\n ...(merge.fetchFn !== undefined ? { fetchFn: merge.fetchFn } : {}),\n log,\n }),\n scopeBindingsByOwner: options.scopeBindingsByOwner === true,\n lockedOrigin: options.lockedOrigin ?? ((): undefined => undefined),\n skipUnchanged: options.skipUnchanged === true,\n dependencies: options.dependencies ?? {},\n strategies: options.strategies ?? {},\n revealEditedField: options.revealEditedField === true,\n };\n this.writer = new BindingWriter(this.deps, this.state);\n this.pipeline = new UpdatePipeline(this.deps, this.state, () => {\n this.rebuildCache();\n });\n }\n\n /**\n * Build the cache, attach observers and listeners, broadcast `ready`.\n * Returns `false` when already started. While the document is still\n * parsing the real start waits for `DOMContentLoaded`.\n */\n start(): boolean {\n const { state, deps } = this;\n if (state.isRunning()) return false;\n state.started = true;\n state.suspended = false;\n if (isDocumentRoot(deps.root) && deps.root.readyState === 'loading') {\n const onReady = (): void => {\n if (!state.isRunning()) return;\n state.deferredStart = null;\n try {\n this.startNow();\n } catch (error) {\n // start() already returned; roll back and report through the error event.\n this.rollbackFailedStart();\n this.reportError(error, 'startup', 'LP0605');\n }\n };\n state.deferredStart = onReady;\n try {\n deps.root.addEventListener('DOMContentLoaded', onReady, { once: true });\n } catch (error) {\n this.rollbackFailedStart();\n throw error;\n }\n return true;\n }\n try {\n this.startNow();\n return true;\n } catch (error) {\n this.rollbackFailedStart();\n throw error;\n }\n }\n\n private startNow(): void {\n const { state, deps } = this;\n if (!state.isRunning()) return;\n const observerRoot: Node | null = isDocumentRoot(deps.root)\n ? readDocumentBody(deps.root)\n : deps.root;\n if (observerRoot === null) throw new Error('LivePreviewRuntime: document.body unavailable');\n deps.observers.start(observerRoot);\n this.observedRoot = observerRoot;\n this.watchRootReplacement();\n // Observers first: the cache scan registers its elements with them.\n this.buildCacheAndObserve();\n if (!state.isRunning()) return;\n deps.bus.attach();\n void deps.emitter.emitWhile('init', { timestamp: Date.now() }, () => state.isRunning());\n if (!state.isRunning()) return;\n for (const delay of READY_RETRY_DELAYS_MS) {\n if (!state.isRunning()) return;\n if (delay === 0) {\n deps.sendReady(deps.readyTargets());\n } else {\n state.readyTimers.push(\n setTimeout(() => {\n if (state.isRunning()) this.sendReadyAfterStart();\n }, delay),\n );\n }\n }\n }\n\n /**\n * Release the message ingress and observers but keep the configuration, so\n * `start()` brings the same instance back — what a back/forward-cache\n * restore needs, since it re-runs no scripts.\n */\n suspend(): boolean {\n if (!this.state.isRunning()) return false;\n const wasConnected = this.release();\n this.state.suspended = true;\n if (wasConnected) {\n void this.deps.emitter.emit('disconnect', { reason: 'unload', timestamp: Date.now() });\n }\n return true;\n }\n\n destroy(): void {\n const { state, deps } = this;\n if (!state.isRunning() && !state.suspended) return;\n const wasConnected = state.isRunning() ? this.release() : false;\n state.suspended = false;\n if (wasConnected) {\n void deps.emitter.emit('disconnect', { reason: 'destroy', timestamp: Date.now() });\n }\n deps.a11y?.detach();\n void deps.emitter.emit('destroy', { timestamp: Date.now() });\n }\n\n /** Invalidate first, then release everything startup may have acquired. */\n private release(): boolean {\n const { state, deps } = this;\n state.activeUpdate = null;\n state.started = false;\n const deferredStart = state.deferredStart;\n state.deferredStart = null;\n if (deferredStart !== null && isDocumentRoot(deps.root)) {\n this.runCleanup(() => {\n deps.root.removeEventListener('DOMContentLoaded', deferredStart);\n });\n }\n for (const handle of state.readyTimers) {\n this.runCleanup(() => {\n clearTimeout(handle);\n });\n }\n state.readyTimers.length = 0;\n this.runCleanup(() => {\n deps.heartbeat.stop();\n });\n this.runCleanup(() => {\n deps.bus.detach();\n });\n state.abortStrategies();\n this.runCleanup(() => {\n this.rootSentinel?.disconnect();\n this.rootSentinel = null;\n this.observedRoot = null;\n });\n this.runCleanup(() => {\n deps.observers.stop();\n });\n this.runCleanup(() => {\n deps.scheduler.destroy();\n });\n this.runCleanup(() => {\n deps.merger?.destroy();\n });\n deps.cache.clear();\n return deps.connection.markDisconnected();\n }\n\n private rollbackFailedStart(): void {\n this.release();\n this.runCleanup(() => {\n this.deps.a11y?.detach();\n });\n }\n\n private runCleanup(cleanup: () => void): void {\n try {\n cleanup();\n } catch (error) {\n this.deps.log('cleanup failed:', error);\n }\n }\n\n /** Re-scan the DOM and re-register every binding. */\n refreshCache(): void {\n if (!this.state.isRunning()) return;\n this.state.revealer.reset();\n if (!this.followReplacedRoot()) this.rebuildCache();\n }\n\n /** Some routers swap `document.body` on navigation, leaving observers on a detached node. */\n private watchRootReplacement(): void {\n const { root } = this.deps;\n if (!isDocumentRoot(root) || typeof MutationObserver === 'undefined') return;\n this.rootSentinel?.disconnect();\n this.rootSentinel = new MutationObserver(() => {\n this.followReplacedRoot();\n });\n this.rootSentinel.observe(root.documentElement, { childList: true });\n }\n\n /** Rebind observers and cache to a replaced body; returns whether it did. */\n private followReplacedRoot(): boolean {\n const { root } = this.deps;\n if (!this.state.isRunning() || !isDocumentRoot(root)) return false;\n const body = readDocumentBody(root);\n if (body === null || body === this.observedRoot) return false;\n this.observedRoot = body;\n this.deps.observers.start(body);\n this.rebuildCache();\n return true;\n }\n\n get status(): 'disconnected' | 'connecting' | 'connected' {\n return this.deps.connection.status;\n }\n\n get cache(): ElementCache {\n return this.deps.cache;\n }\n\n get updateCount(): number {\n return this.state.updateCount;\n }\n\n /** Negotiated protocol view, `min(library, remote)`. */\n get protocol(): ProtocolNegotiation {\n return this.state.protocol.negotiation;\n }\n\n /** Point-in-time read of runtime state for diagnosing a preview that is not updating. */\n inspect(): LivePreviewInspection {\n return buildInspection(this.deps, this.state);\n }\n\n private buildCacheAndObserve(): void {\n const { state, deps } = this;\n if (!state.isRunning()) return;\n const stats = deps.cache.buildFromRoot(deps.root);\n deps.log('cache', stats);\n if (!state.isRunning()) return;\n void deps.emitter.emitWhile('cacheRefresh', stats, () => state.isRunning());\n if (!state.isRunning()) return;\n for (const entry of deps.cache.values()) {\n if (!state.isRunning()) return;\n deps.observers.observeElement(entry.element);\n }\n }\n\n private rebuildCache(): void {\n const { state, deps } = this;\n if (!state.isRunning()) return;\n const previous = new Map<Element, CachedElement>();\n for (const entry of deps.cache.values()) {\n previous.set(entry.element, entry);\n deps.observers.unobserveElement(entry.element);\n }\n this.buildCacheAndObserve();\n if (!state.isRunning()) return;\n // Buffered work survives only while the same element is bound to the same field.\n for (const entry of deps.cache.values()) {\n const before = previous.get(entry.element);\n if (before?.fieldName === entry.fieldName) deps.scheduler.retarget(entry);\n else deps.scheduler.forget(entry.element);\n previous.delete(entry.element);\n }\n for (const removed of previous.values()) deps.scheduler.forget(removed.element);\n }\n\n private onHeartbeatTimeout(): void {\n const { state, deps } = this;\n if (!state.isRunning()) return;\n deps.bus.advanceGeneration();\n const active = state.activeUpdate;\n state.activeUpdate = null;\n if (active !== null) deps.scheduler.cancelRevision(active.identity);\n deps.merger?.destroy();\n const wasConnected = deps.connection.markDisconnected();\n // Release the origin lock before the disconnect event: a listener may\n // reconnect from another allow-listed origin synchronously.\n try {\n deps.onHeartbeatTimeout?.();\n } catch (error) {\n deps.log('heartbeat:', error);\n }\n if (!state.isRunning()) return;\n if (wasConnected && this.isIdleDisconnected()) {\n deps.a11y?.announceDisconnected();\n void deps.emitter.emitWhile('disconnect', { reason: 'timeout', timestamp: Date.now() }, () =>\n this.isIdleDisconnected(),\n );\n if (!state.isRunning()) return;\n if (this.isIdleDisconnected()) deps.log('connection', 'connected', '→', 'disconnected');\n if (!state.isRunning()) return;\n }\n this.sendReadyAfterStart();\n }\n\n /** Later handshake retries are best-effort and must not escape timer callbacks. */\n private sendReadyAfterStart(): void {\n try {\n this.deps.sendReady(this.deps.readyTargets());\n } catch (error) {\n this.reportError(error, 'ready', 'LP0606');\n }\n }\n\n private reportError(cause: unknown, context: string, code: DiagnosticCode): void {\n const error = cause instanceof Error ? cause : new Error(String(cause));\n void this.deps.emitter.emit('error', { error, context, code });\n }\n\n private isIdleDisconnected(): boolean {\n return (\n this.state.isRunning() &&\n this.deps.connection.status === 'disconnected' &&\n this.state.activeUpdate === null\n );\n }\n}\n\nfunction createA11y(options: RuntimeOptions): A11yAnnouncer | null {\n if (options.enableA11y === false) return null;\n const root = options.root;\n const targetDocument =\n root === undefined ? undefined : isDocumentRoot(root) ? root : root.ownerDocument;\n return new A11yAnnouncer(options.a11yLocale, targetDocument);\n}\n\n/** Node types are stable across realms; global constructors are not. */\nfunction isDocumentRoot(root: Document | Element): root is Document {\n return root.nodeType === 9;\n}\n\n/** lib.dom types body as present; a head-time document has none yet. */\nfunction readDocumentBody(root: Document): HTMLElement | null {\n return root.body;\n}\n\nfunction defaultSendReady(origins: readonly string[]): void {\n if (typeof window === 'undefined') return;\n const targets: Window[] = [];\n if (window.parent !== window) targets.push(window.parent);\n if (window.opener instanceof Window) targets.push(window.opener);\n MessageBus.sendReady(targets, origins);\n}\n","/** Assembles the `inspect()` snapshot. Reads state only; sends nothing anywhere. */\n\nimport { VERSION } from '../../version';\nimport { detectProtocolProfile } from '../protocol-profile';\nimport type { RuntimeDeps, RuntimeState } from '../runtime-state';\nimport type { LivePreviewInspection } from './types';\n\nexport function buildInspection(deps: RuntimeDeps, state: RuntimeState): LivePreviewInspection {\n const { cache, scheduler } = deps;\n const negotiation = state.protocol.negotiation;\n const active = state.activeUpdate;\n const flush = state.lastFlush;\n const fieldNames: string[] = [];\n const owners = new Set<string>();\n for (const [fieldName, bindings] of cache.entries()) {\n fieldNames.push(fieldName);\n for (const binding of bindings) {\n if (binding.owner !== undefined) owners.add(binding.owner);\n }\n }\n return {\n version: VERSION,\n started: state.started,\n status: deps.connection.status,\n origins: { trusted: [...deps.readyTargets()], locked: deps.lockedOrigin() },\n protocol: {\n ours: negotiation.ours,\n theirs: negotiation.theirs,\n negotiated: negotiation.negotiated,\n capabilities: [...negotiation.capabilities].sort(),\n observed: [...negotiation.observed].sort(),\n profile: detectProtocolProfile(negotiation.observed).name,\n },\n revisions: {\n accepted: state.updateCount,\n superseded: state.supersededCount,\n completed: state.completedCount,\n skippedUnchanged: state.skippedUnchangedCount,\n active: active === null ? undefined : active.identity.revision,\n },\n bindings: {\n elements: cache.elementCount,\n fields: cache.fieldCount,\n fieldNames: fieldNames.sort(),\n absentFields: [...state.absentFields].sort(),\n orphanFields: [...state.warnedOrphanFields].sort(),\n ownerScoped: deps.scopeBindingsByOwner,\n owners: [...owners].sort(),\n },\n route: { handler: deps.strategies.route !== undefined, ...state.routeStats },\n fragments: {\n handler: deps.strategies.fragment !== undefined,\n inFlight: active?.pendingFragments ?? 0,\n ...state.fragmentStats,\n },\n scheduler: {\n pending: scheduler.pendingCount,\n deferred: scheduler.replayCount,\n visibilityGateThreshold: scheduler.gateThreshold,\n visibilityGateActive: scheduler.gateActive,\n lastFlush:\n flush === null\n ? undefined\n : {\n applied: flush.applied,\n appliedFields: flush.appliedFields,\n deferred: flush.deferred,\n durationMs: flush.durationMs,\n },\n },\n plugins: [],\n renderers: Object.keys(deps.renderers).sort(),\n };\n}\n","/**\n * Per-instance typed emitter: handlers run sequentially in registration order,\n * may be async, and a throwing one is logged and isolated. See ADR 0002.\n */\n\nimport type { EventHandler, LivePreviewEventMap, Unsubscribe } from './types';\nimport { safeConsoleError } from '@core/diagnostics';\n\ntype AnyHandler = EventHandler<unknown>;\n\n// `object`, not `Record<string, unknown>`: interfaces with readonly and\n// exact-optional properties must be usable as maps.\nexport class EventEmitter<TMap extends object = LivePreviewEventMap> {\n readonly #regular = new Map<keyof TMap, Set<AnyHandler>>();\n readonly #once = new Map<keyof TMap, Set<AnyHandler>>();\n\n on<E extends keyof TMap>(event: E, handler: EventHandler<TMap[E]>): Unsubscribe {\n return this.#register(this.#regular, event, handler as AnyHandler);\n }\n\n once<E extends keyof TMap>(event: E, handler: EventHandler<TMap[E]>): Unsubscribe {\n return this.#register(this.#once, event, handler as AnyHandler);\n }\n\n off<E extends keyof TMap>(event: E, handler: EventHandler<TMap[E]>): void {\n this.#remove(this.#regular, event, handler as AnyHandler);\n this.#remove(this.#once, event, handler as AnyHandler);\n }\n\n /** Dispatch to every handler: regular ones first, then `once` handlers. */\n async emit<E extends keyof TMap>(event: E, payload: TMap[E]): Promise<void> {\n await this.#emitSequential(event, payload);\n }\n\n /**\n * Dispatch while `shouldContinue()` holds — checked around every handler, so\n * an obsolete transaction cannot resume across an await.\n * @internal\n */\n async emitWhile<E extends keyof TMap>(\n event: E,\n payload: TMap[E],\n shouldContinue: () => boolean,\n ): Promise<boolean> {\n return this.#emitSequential(event, payload, shouldContinue);\n }\n\n async #emitSequential<E extends keyof TMap>(\n event: E,\n payload: TMap[E],\n shouldContinue?: () => boolean,\n ): Promise<boolean> {\n const eligible = (): boolean => shouldContinue?.() ?? true;\n if (!eligible()) return false;\n const regular = this.#regular.get(event);\n if (regular) {\n for (const handler of [...regular]) {\n if (!eligible()) return false;\n await this.#invoke(handler, payload, event);\n if (!eligible()) return false;\n }\n }\n if (!eligible()) return false;\n const once = this.#once.get(event);\n if (once && once.size > 0) {\n const snapshot = [...once];\n this.#once.delete(event);\n for (const handler of snapshot) {\n if (!eligible()) return false;\n await this.#invoke(handler, payload, event);\n if (!eligible()) return false;\n }\n }\n return eligible();\n }\n\n /** Registered handlers for `event`, `on` and `once` together. */\n listenerCount(event: keyof TMap): number {\n return (this.#regular.get(event)?.size ?? 0) + (this.#once.get(event)?.size ?? 0);\n }\n\n /** Remove every handler, or only those of `event`. */\n removeAllListeners(event?: keyof TMap): void {\n if (event === undefined) {\n this.#regular.clear();\n this.#once.clear();\n return;\n }\n this.#regular.delete(event);\n this.#once.delete(event);\n }\n\n /** Event names with at least one handler. */\n eventNames(): (keyof TMap)[] {\n const names = new Set<keyof TMap>();\n for (const key of this.#regular.keys()) names.add(key);\n for (const key of this.#once.keys()) names.add(key);\n return [...names];\n }\n\n #register(\n bucket: Map<keyof TMap, Set<AnyHandler>>,\n event: keyof TMap,\n handler: AnyHandler,\n ): Unsubscribe {\n let set = bucket.get(event);\n if (!set) {\n set = new Set();\n bucket.set(event, set);\n }\n set.add(handler);\n return () => {\n this.#remove(bucket, event, handler);\n };\n }\n\n #remove(bucket: Map<keyof TMap, Set<AnyHandler>>, event: keyof TMap, handler: AnyHandler): void {\n const set = bucket.get(event);\n if (set === undefined) return;\n set.delete(handler);\n if (set.size === 0) bucket.delete(event);\n }\n\n async #invoke(handler: AnyHandler, payload: unknown, event: keyof TMap): Promise<void> {\n try {\n await handler(payload);\n } catch (err) {\n const label =\n typeof event === 'string' || typeof event === 'number' ? String(event) : '<event>';\n safeConsoleError(`[live-preview] LP0601: handler for \"${label}\" threw:`, err);\n }\n }\n}\n","/**\n * Where the runtime is running: framed, opened, or on a developer's machine.\n * Nothing reads bundler-injected variables; a Vite consumer passes\n * `import.meta.env.X` explicitly (docs/astro.md).\n */\n\nexport function isInIframe(): boolean {\n if (typeof window === 'undefined') return false;\n try {\n return window.self !== window.top;\n } catch {\n // A cross-origin parent throws on the comparison; that is an iframe.\n return true;\n }\n}\n\nexport function isInPopup(): boolean {\n if (typeof window === 'undefined') return false;\n return window.opener != null;\n}\n\n/** An iframe or a popup; top-level navigation never starts the preview. */\nexport function isInPreviewContext(): boolean {\n return isInIframe() || isInPopup();\n}\n\n/** Under Node, `NODE_ENV !== 'production'`; in a browser the hostname, which is the only signal a bundle has. */\nexport function isDevMode(): boolean {\n const nodeEnv = readNodeEnv();\n if (nodeEnv !== undefined) return nodeEnv !== 'production';\n if (typeof window !== 'undefined') {\n const host = window.location.hostname;\n return host === 'localhost' || host === '127.0.0.1';\n }\n return false;\n}\n\nfunction readNodeEnv(): string | undefined {\n if (typeof process === 'undefined') return undefined;\n const value = process.env['NODE_ENV'];\n return typeof value === 'string' ? value : undefined;\n}\n","/**\n * Which admin origins the runtime trusts: explicit ones always, the\n * `document.referrer` origin only when none is configured, any localhost port\n * in development. See docs/security.md §1.\n */\n\nimport { isDevMode, isInIframe } from './environment';\n\nconst LOCALHOST_PATTERN = /^https?:\\/\\/(localhost|127\\.0\\.0\\.1)(?::\\d+)?$/i;\nconst VALID_ORIGIN_PATTERN = /^https?:\\/\\/[^/?#\\s]+$/i;\n\n/** Ports the handshake broadcasts to when the localhost pattern is on; matching itself is unrestricted. */\nconst LOCALHOST_HANDSHAKE_PORTS: readonly number[] = [\n 3000, 3001, 3333, 4000, 4321, 5000, 5173, 5174, 8000, 8080, 8888, 9000,\n];\n\nexport interface OriginDetectorOptions {\n /** Explicit origins to trust. Always allowed. */\n readonly additionalOrigins?: readonly string[];\n /** Set to `false` to ignore `document.referrer`. */\n readonly enableReferrerDetection?: boolean;\n /** Set to `false` to ignore the localhost pattern even in development. */\n readonly enableLocalhostMatching?: boolean;\n /** Override dev-mode detection. */\n readonly forceDevMode?: boolean;\n /** Override `document.referrer` for tests. */\n readonly referrer?: string;\n}\n\nconst enum OriginSlot {\n ExplicitOrigins,\n ReferrerOrigin,\n AllowLocalhost,\n ReferrerWasAvailable,\n LockedOrigin,\n}\n\ntype OriginState = [\n explicitOrigins: ReadonlySet<string>,\n referrerOrigin: string | undefined,\n allowLocalhost: boolean,\n referrerWasAvailable: boolean,\n lockedOrigin: string | undefined,\n];\n\n/** The trusted-origin policy: the union of the candidate sources, narrowed to one by `lockOrigin()`. */\nexport class OriginDetector {\n readonly #state: OriginState;\n\n constructor(options: OriginDetectorOptions = {}) {\n const explicit = new Set<string>();\n for (const origin of options.additionalOrigins ?? []) {\n const normalised = normaliseOrigin(origin);\n if (normalised !== undefined) explicit.add(normalised);\n }\n let referrerOrigin: string | undefined;\n if (options.enableReferrerDetection ?? true) {\n const referrer =\n options.referrer ?? (typeof document !== 'undefined' ? document.referrer : '');\n if (referrer.length > 0) {\n try {\n const origin = new URL(referrer).origin;\n if (origin && origin !== 'null') referrerOrigin = origin;\n } catch {\n // opaque referrer\n }\n }\n }\n const allowLocalhost =\n (options.enableLocalhostMatching ?? true) && (options.forceDevMode ?? isDevMode());\n this.#state = [\n explicit,\n referrerOrigin,\n allowLocalhost,\n referrerOrigin !== undefined,\n undefined,\n ];\n }\n\n /** Whether `origin` is trusted: the locked origin alone once locked, otherwise the policy above. */\n matches(origin: string): boolean {\n if (origin.length === 0 || origin === 'null') return false;\n if (this.#state[OriginSlot.LockedOrigin] !== undefined) {\n return origin === this.#state[OriginSlot.LockedOrigin];\n }\n if (this.#state[OriginSlot.ExplicitOrigins].has(origin)) return true;\n // The referrer is a fallback, not a union member: any embedder lands there.\n if (\n this.#state[OriginSlot.ExplicitOrigins].size === 0 &&\n this.#state[OriginSlot.ReferrerOrigin] !== undefined &&\n origin === this.#state[OriginSlot.ReferrerOrigin]\n ) {\n return true;\n }\n if (this.#state[OriginSlot.AllowLocalhost] && LOCALHOST_PATTERN.test(origin)) return true;\n return false;\n }\n\n /** Narrow trust to `origin`; refused (`false`) when it is not currently trusted. */\n lockOrigin(origin: string): boolean {\n if (!this.matches(origin)) return false;\n this.#state[OriginSlot.LockedOrigin] = origin;\n return true;\n }\n\n /** Release the lock (heartbeat timeout) so another allow-listed origin may reconnect. Returns the previous lock. */\n unlockOrigin(): string | undefined {\n const previous = this.#state[OriginSlot.LockedOrigin];\n this.#state[OriginSlot.LockedOrigin] = undefined;\n return previous;\n }\n\n get lockedOrigin(): string | undefined {\n return this.#state[OriginSlot.LockedOrigin];\n }\n\n /** Every origin the `ready` handshake is broadcast to; the localhost pattern expands to the common dev ports. */\n enumerate(): string[] {\n if (this.#state[OriginSlot.LockedOrigin] !== undefined) {\n return [this.#state[OriginSlot.LockedOrigin]];\n }\n const result = new Set<string>(this.#state[OriginSlot.ExplicitOrigins]);\n if (\n this.#state[OriginSlot.ExplicitOrigins].size === 0 &&\n this.#state[OriginSlot.ReferrerOrigin] !== undefined\n ) {\n result.add(this.#state[OriginSlot.ReferrerOrigin]);\n }\n if (this.#state[OriginSlot.AllowLocalhost]) {\n for (const port of LOCALHOST_HANDSHAKE_PORTS) {\n result.add(`http://localhost:${String(port)}`);\n result.add(`http://127.0.0.1:${String(port)}`);\n }\n }\n return [...result];\n }\n\n /** Whether `document.referrer` contributed an origin (absent under `Referrer-Policy: no-referrer`). */\n get referrerWasAvailable(): boolean {\n return this.#state[OriginSlot.ReferrerWasAvailable];\n }\n\n /** Framed, outside development, with no trusted origin at all: the host should warn (LP0101). */\n get isProductionUnconfigured(): boolean {\n if (!isInIframe()) return false;\n if (this.#state[OriginSlot.ExplicitOrigins].size > 0) return false;\n if (this.#state[OriginSlot.AllowLocalhost]) return false;\n if (this.#state[OriginSlot.ReferrerOrigin] !== undefined) return false;\n return true;\n }\n\n /** The referrer is the only trust source, so any framing site may drive the preview (LP0102). */\n get isReferrerOnlyTrust(): boolean {\n if (this.#state[OriginSlot.ExplicitOrigins].size > 0) return false;\n if (this.#state[OriginSlot.AllowLocalhost]) return false;\n return this.#state[OriginSlot.ReferrerOrigin] !== undefined;\n }\n}\n\n/** The canonical `http(s)://host[:port]` form of `value`, or `undefined` when it is not one. */\nexport function normaliseOrigin(value: string): string | undefined {\n const trimmed = value.trim();\n if (trimmed.length === 0) return undefined;\n try {\n const url = new URL(trimmed);\n if (url.protocol !== 'http:' && url.protocol !== 'https:') return undefined;\n if (!VALID_ORIGIN_PATTERN.test(url.origin)) return undefined;\n return url.origin;\n } catch {\n return undefined;\n }\n}\n","/**\n * Registration-local resource scope: every listener, transform, renderer\n * layer and cleanup a plugin registers is staged here until `init` commits\n * and released together, in reverse order, when the plugin goes. See ADR 0005.\n */\n\nimport { observeThenableResult } from '@core/thenable';\nimport type { PluginDisposer } from './types';\n\nexport type ResourceKind = 'transform' | 'renderer' | 'subscription' | 'cleanup';\n\ninterface ScopedResource {\n readonly kind: ResourceKind;\n readonly acquire: (() => PluginDisposer | undefined) | undefined;\n readonly finalize: (() => void) | undefined;\n cleanup: PluginDisposer | undefined;\n disposed: boolean;\n}\n\nexport const noopDisposer: PluginDisposer = () => undefined;\n\nexport class ResourceScope {\n readonly #pluginName: string;\n readonly #log: (...args: unknown[]) => void;\n // Insertion order gives commit/reverse-teardown order; short-lived entries\n // (once listeners) leave immediately instead of accumulating until removal.\n readonly #resources = new Set<ScopedResource>();\n #state: 'staging' | 'committing' | 'active' | 'closed' = 'staging';\n\n constructor(pluginName: string, log: (...args: unknown[]) => void) {\n this.#pluginName = pluginName;\n this.#log = log;\n }\n\n assertOpen(): void {\n if (this.#state === 'closed') {\n throw new Error(`Plugin context for \"${this.#pluginName}\" is no longer active`);\n }\n }\n\n get active(): boolean {\n return this.#state === 'active';\n }\n\n /** Whether a retained context still belongs to this registration. */\n eligible(): boolean {\n return this.#state !== 'closed';\n }\n\n /** Own a resource the plugin itself already acquired. */\n own(cleanup: PluginDisposer): PluginDisposer {\n this.assertOpen();\n return this.#track({\n kind: 'cleanup',\n acquire: undefined,\n finalize: undefined,\n cleanup,\n disposed: false,\n });\n }\n\n /** Stage a manager-owned resource; an active scope acquires it at once. */\n stage(\n kind: ResourceKind,\n acquire: () => PluginDisposer | undefined,\n finalize?: () => void,\n ): PluginDisposer {\n this.assertOpen();\n const resource: ScopedResource = {\n kind,\n acquire,\n finalize,\n cleanup: undefined,\n disposed: false,\n };\n const dispose = this.#track(resource);\n if (this.#state === 'active') {\n try {\n this.#activate(resource);\n } catch (error) {\n this.#dispose(resource);\n throw error;\n }\n }\n return dispose;\n }\n\n /** Live resources by kind, what `inspect().plugins` reports. */\n counts(): Record<ResourceKind, number> {\n const counts: Record<ResourceKind, number> = {\n transform: 0,\n renderer: 0,\n subscription: 0,\n cleanup: 0,\n };\n for (const resource of this.#resources) counts[resource.kind] += 1;\n return counts;\n }\n\n /** Publish every staged resource at once after `init` succeeded. */\n commit(): void {\n if (this.#state !== 'staging') {\n throw new Error(`Plugin context for \"${this.#pluginName}\" cannot be committed`);\n }\n this.#state = 'committing';\n try {\n for (const resource of this.#resources) this.#activate(resource);\n this.#state = 'active';\n } catch (error) {\n this.close();\n throw error;\n }\n }\n\n close(): void {\n if (this.#state === 'closed') return;\n this.#state = 'closed';\n for (const resource of [...this.#resources].reverse()) this.#dispose(resource);\n this.#resources.clear();\n }\n\n #track(resource: ScopedResource): PluginDisposer {\n this.#resources.add(resource);\n return (): void => {\n this.#dispose(resource);\n };\n }\n\n #activate(resource: ScopedResource): void {\n if (resource.disposed || resource.cleanup !== undefined || resource.acquire === undefined) {\n return;\n }\n const cleanup = resource.acquire();\n resource.cleanup = cleanup ?? noopDisposer;\n }\n\n #dispose(resource: ScopedResource): void {\n if (resource.disposed) return;\n resource.disposed = true;\n this.#resources.delete(resource);\n const cleanup = resource.cleanup;\n resource.cleanup = undefined;\n if (cleanup !== undefined) {\n try {\n // A `void` cleanup may still return a thenable; observe it without awaiting.\n const cleanupWithResult: () => unknown = cleanup;\n if (observeThenableResult(cleanupWithResult())) {\n this.#log(\n `plugin \"${this.#pluginName}\" cleanup returned a Promise/thenable; cleanups must be synchronous`,\n );\n }\n } catch (error) {\n this.#log(`plugin \"${this.#pluginName}\" cleanup failed:`, error);\n }\n }\n try {\n resource.finalize?.();\n } catch (error) {\n this.#log(`plugin \"${this.#pluginName}\" cleanup failed:`, error);\n }\n }\n}\n","/**\n * Event facade handed to a plugin: subscriptions are owned by the plugin's\n * scope, emits go to the client's emitter. It implements the emitter surface\n * without extending it, so no unused base emitter is allocated per plugin.\n */\n\nimport type { EventEmitter } from '@events/emitter';\nimport type { EventHandler, LivePreviewEventMap, Unsubscribe } from '@events/types';\nimport { noopDisposer, type ResourceScope } from './resource-scope';\nimport type { PluginEvents } from './types';\n\ninterface OwnedSubscription {\n readonly kind: 'on' | 'once';\n readonly event: keyof LivePreviewEventMap;\n readonly handler: EventHandler<unknown>;\n dispose: Unsubscribe;\n}\n\nexport class ScopedPluginEvents implements PluginEvents {\n readonly #events: EventEmitter;\n readonly #scope: ResourceScope;\n readonly #subscriptions = new Set<OwnedSubscription>();\n\n constructor(events: EventEmitter, scope: ResourceScope) {\n this.#events = events;\n this.#scope = scope;\n }\n\n on<E extends keyof LivePreviewEventMap>(\n event: E,\n handler: EventHandler<LivePreviewEventMap[E]>,\n ): Unsubscribe {\n return this.#subscribe('on', event, handler);\n }\n\n once<E extends keyof LivePreviewEventMap>(\n event: E,\n handler: EventHandler<LivePreviewEventMap[E]>,\n ): Unsubscribe {\n return this.#subscribe('once', event, handler);\n }\n\n off<E extends keyof LivePreviewEventMap>(\n event: E,\n handler: EventHandler<LivePreviewEventMap[E]>,\n ): void {\n const untypedHandler = handler as EventHandler<unknown>;\n for (const subscription of [...this.#subscriptions]) {\n if (subscription.event === event && subscription.handler === untypedHandler) {\n subscription.dispose();\n }\n }\n }\n\n emit<E extends keyof LivePreviewEventMap>(\n event: E,\n payload: LivePreviewEventMap[E],\n ): Promise<void> {\n this.#scope.assertOpen();\n return this.#events.emit(event, payload);\n }\n\n emitWhile<E extends keyof LivePreviewEventMap>(\n event: E,\n payload: LivePreviewEventMap[E],\n shouldContinue: () => boolean,\n ): Promise<boolean> {\n this.#scope.assertOpen();\n return this.#events.emitWhile(event, payload, () => {\n if (!this.#scope.eligible()) return false;\n const callerEligible = shouldContinue();\n // The predicate is plugin code and may close this scope re-entrantly.\n if (!this.#scope.eligible()) return false;\n return callerEligible;\n });\n }\n\n listenerCount(event: keyof LivePreviewEventMap): number {\n let count = 0;\n for (const subscription of this.#subscriptions) {\n if (subscription.event === event) count += 1;\n }\n return count;\n }\n\n removeAllListeners(event?: keyof LivePreviewEventMap): void {\n for (const subscription of [...this.#subscriptions]) {\n if (event === undefined || subscription.event === event) subscription.dispose();\n }\n }\n\n eventNames(): (keyof LivePreviewEventMap)[] {\n const names = new Set<keyof LivePreviewEventMap>();\n for (const subscription of this.#subscriptions) names.add(subscription.event);\n return [...names];\n }\n\n #subscribe<E extends keyof LivePreviewEventMap>(\n kind: 'on' | 'once',\n event: E,\n handler: EventHandler<LivePreviewEventMap[E]>,\n ): Unsubscribe {\n this.#scope.assertOpen();\n\n const untypedHandler = handler as EventHandler<unknown>;\n const existing = [...this.#subscriptions].find(\n (subscription) =>\n subscription.kind === kind &&\n subscription.event === event &&\n subscription.handler === untypedHandler,\n );\n if (existing !== undefined) return existing.dispose;\n\n // A distinct wrapper per scope: two plugins passing the same handler\n // reference must be revocable independently in the Set-based emitter.\n let dispose = noopDisposer;\n let subscriptionActive = true;\n const wrapped: EventHandler<LivePreviewEventMap[E]> = async (payload) => {\n if (!this.#scope.active || !subscriptionActive) return;\n // Mirror the base emitter, which drops a once bucket before dispatch.\n if (kind === 'once') dispose();\n await handler(payload);\n };\n const subscription: OwnedSubscription = {\n kind,\n event,\n handler: untypedHandler,\n dispose: noopDisposer,\n };\n dispose = this.#scope.stage(\n 'subscription',\n () => this.#events[kind](event, wrapped),\n () => {\n subscriptionActive = false;\n this.#subscriptions.delete(subscription);\n },\n );\n subscription.dispose = dispose;\n this.#subscriptions.add(subscription);\n return dispose;\n }\n}\n","/**\n * Per-instance plugin manager. Mutations run through one call-order queue;\n * while a queue-held hook is pending, a requested mutation takes the direct\n * path because that hook may be awaiting it. See ADR 0005.\n */\n\nimport type { FieldRenderer } from '@core/types';\nimport type { PluginInspection } from '@core/inspection/types';\nimport { LIBRARY_PROTOCOL_VERSION } from '@core/protocol-version';\nimport { VERSION } from '@/version';\nimport { incompatibilityOf } from './compat';\nimport { isolateDiagnostic } from '@core/diagnostics';\nimport { observeThenableResult } from '@core/thenable';\nimport type { EventEmitter } from '@events/emitter';\nimport { ResourceScope } from './resource-scope';\nimport { ScopedPluginEvents } from './scoped-events';\nimport type { FieldTransform, LivePreviewPlugin, PluginContext } from './types';\n\nexport interface PluginManagerOptions {\n readonly events: EventEmitter;\n readonly config: Readonly<Record<string, unknown>>;\n /** Add one renderer layer to the host; may return the layer's disposer. */\n readonly registerFieldRenderer: (renderer: FieldRenderer) => void;\n /** Receives transform contract failures for the runtime's `error` event. */\n readonly onTransformError?: (error: Error) => unknown;\n readonly log: (...args: unknown[]) => void;\n}\n\ninterface PluginRegistration {\n readonly plugin: LivePreviewPlugin;\n readonly scope: ResourceScope;\n}\n\ninterface InitializingPluginRegistration {\n readonly scope: ResourceScope;\n cancelled: boolean;\n}\n\ninterface TransformRegistration {\n readonly transform: FieldTransform;\n active: boolean;\n}\n\nfunction isPluginDisposer(value: unknown): value is (() => void) | undefined {\n return typeof value === 'function';\n}\n\nexport class PluginManager {\n readonly #events: EventEmitter;\n readonly #config: Readonly<Record<string, unknown>>;\n // The public callback type is void; the client host returns its layer disposer through it.\n readonly #registerRenderer: (renderer: FieldRenderer) => unknown;\n readonly #onTransformError: ((error: Error) => void) | undefined;\n readonly #log: (...args: unknown[]) => void;\n readonly #plugins = new Map<string, PluginRegistration>();\n readonly #initializing = new Map<string, InitializingPluginRegistration>();\n readonly #teardowns = new Map<string, Promise<void>>();\n readonly #destroying = new Set<string>();\n readonly #transforms = new Map<string, TransformRegistration[]>();\n #mutationQueue: Promise<void> = Promise.resolve();\n // Hooks awaited by the queue entry in flight. Hooks started on the direct\n // path never hold the queue, so they must not open it for others.\n #queuedHooks = 0;\n\n constructor(options: PluginManagerOptions) {\n this.#events = options.events;\n this.#config = options.config;\n this.#registerRenderer = options.registerFieldRenderer;\n this.#log = isolateDiagnostic(options.log);\n const onTransformError = options.onTransformError;\n this.#onTransformError =\n onTransformError === undefined\n ? undefined\n : isolateDiagnostic((...args: unknown[]): unknown => {\n // Private and single-callered: `applyTransforms` normalizes to an\n // Error before it reports one.\n const error = args[0] as Error;\n try {\n return onTransformError(error);\n } catch (reportError) {\n this.#log('transform error reporter failed:', reportError);\n return undefined;\n }\n });\n }\n\n /** Register a plugin transactionally; concurrent mutations run in call order. */\n register(plugin: LivePreviewPlugin): Promise<void> {\n if (this.#queuedHooks > 0) return this.#registerNow(plugin, false);\n return this.#enqueue(() => this.#registerNow(plugin, true));\n }\n\n /** Remove one plugin and every resource its registration created. */\n unregister(name: string): Promise<void> {\n if (this.#queuedHooks > 0) return this.#unregisterNow(name, false);\n return this.#enqueue(async () => {\n await this.#unregisterNow(name, true);\n });\n }\n\n /** Destroy every registration; one failure never strands another. */\n destroyAll(): Promise<void> {\n if (this.#queuedHooks > 0) return this.#destroyAllNow(false);\n return this.#enqueue(async () => {\n await this.#destroyAllNow(true);\n });\n }\n\n /** Apply active transforms in registration order; a failure returns the original value. */\n applyTransforms(\n fieldName: string,\n value: unknown,\n context: { readonly element: Element; readonly allFields: Record<string, unknown> },\n isCurrent?: () => boolean,\n ): unknown {\n const registrations = this.#transforms.get(fieldName);\n if (registrations === undefined || registrations.length === 0) return value;\n\n let result: unknown = value;\n for (const registration of [...registrations]) {\n if (!registration.active) continue;\n const { transform } = registration;\n if (isCurrent?.() === false) return value;\n try {\n result = transform(result, {\n fieldName,\n element: context.element,\n allFields: context.allFields,\n });\n const returnedThenable = observeThenableResult(result);\n // A transform may synchronously let a newer message in; then its\n // result belongs to a superseded revision and is not reported.\n if (isCurrent?.() === false) return value;\n if (returnedThenable) {\n throw new TypeError(\n `Transform for \"${fieldName}\" returned a Promise/thenable; transforms must be synchronous`,\n );\n }\n } catch (error) {\n if (isCurrent?.() === false) return value;\n const normalized = error instanceof Error ? error : new Error(String(error));\n this.#log(`transform for \"${fieldName}\" failed:`, normalized);\n this.#onTransformError?.(normalized);\n return value;\n }\n }\n return result;\n }\n\n list(): readonly string[] {\n return [...this.#plugins.keys()];\n }\n\n /** Every plugin with its state and live registrations (`inspect().plugins`). */\n snapshot(): readonly PluginInspection[] {\n const entries: PluginInspection[] = [];\n const describe = (\n name: string,\n version: string | undefined,\n state: PluginInspection['state'],\n scope: ResourceScope,\n ): PluginInspection => {\n const counts = scope.counts();\n return {\n name,\n version,\n state,\n registrations: {\n transforms: counts.transform,\n renderers: counts.renderer,\n subscriptions: counts.subscription,\n cleanups: counts.cleanup,\n },\n };\n };\n for (const [name, initializing] of this.#initializing) {\n entries.push(describe(name, undefined, 'initializing', initializing.scope));\n }\n for (const [name, registration] of this.#plugins) {\n entries.push(describe(name, registration.plugin.version, 'active', registration.scope));\n }\n // A name with a pending teardown left `#plugins` before the teardown began.\n for (const name of this.#teardowns.keys()) {\n entries.push({\n name,\n version: undefined,\n state: 'tearing-down',\n registrations: { transforms: 0, renderers: 0, subscriptions: 0, cleanups: 0 },\n });\n }\n return entries;\n }\n\n get size(): number {\n return this.#plugins.size;\n }\n\n async #registerNow(plugin: LivePreviewPlugin, queued: boolean): Promise<void> {\n if (\n this.#plugins.has(plugin.name) ||\n this.#initializing.has(plugin.name) ||\n this.#teardowns.has(plugin.name)\n ) {\n this.#log(`plugin \"${plugin.name}\" already registered`);\n return;\n }\n\n const incompatibility = incompatibilityOf(plugin.compat, VERSION, LIBRARY_PROTOCOL_VERSION);\n if (incompatibility !== undefined) {\n this.#refuse(plugin.name, incompatibility);\n return;\n }\n const scope = new ResourceScope(plugin.name, this.#log);\n const context = this.#createContext(plugin.name, scope);\n const initializing: InitializingPluginRegistration = { scope, cancelled: false };\n this.#initializing.set(plugin.name, initializing);\n try {\n await this.#runHook(() => plugin.init(context), queued);\n if (initializing.cancelled) return;\n scope.commit();\n } catch (error) {\n scope.close();\n if (!initializing.cancelled) this.#log(`plugin \"${plugin.name}\" init failed:`, error);\n return;\n } finally {\n if (this.#initializing.get(plugin.name) === initializing) {\n this.#initializing.delete(plugin.name);\n }\n }\n\n this.#plugins.set(plugin.name, { plugin, scope });\n this.#log(`plugin \"${plugin.name}\" registered`);\n }\n\n /** A refused plugin is an integration mistake; it reaches the `error` event, not only the log. */\n #refuse(name: string, reason: string): void {\n const message = `plugin \"${name}\" refused: ${reason}`;\n this.#log(message);\n void this.#events.emit('error', {\n error: new Error(message),\n context: 'plugin',\n code: 'LP0103',\n });\n }\n\n #createContext(pluginName: string, scope: ResourceScope): PluginContext {\n return {\n events: new ScopedPluginEvents(this.#events, scope),\n registerFieldRenderer: (renderer) => {\n scope.stage('renderer', () => {\n const result = this.#registerRenderer(renderer);\n return isPluginDisposer(result) ? result : undefined;\n });\n },\n registerTransform: (fieldName, transform) => {\n const registration: TransformRegistration = { transform, active: false };\n scope.stage('transform', () => {\n registration.active = true;\n const existing = this.#transforms.get(fieldName);\n if (existing === undefined) this.#transforms.set(fieldName, [registration]);\n else existing.push(registration);\n\n return () => {\n registration.active = false;\n const current = this.#transforms.get(fieldName);\n if (current === undefined) return;\n const index = current.indexOf(registration);\n if (index >= 0) current.splice(index, 1);\n if (current.length === 0) this.#transforms.delete(fieldName);\n };\n });\n },\n registerCleanup: (cleanup) => {\n scope.own(cleanup);\n },\n getConfig: () => this.#config,\n log: (...args) => {\n this.#log(`[${pluginName}]`, ...args);\n },\n };\n }\n\n #unregisterNow(name: string, queued: boolean): Promise<void> {\n const initializing = this.#initializing.get(name);\n if (initializing !== undefined) {\n initializing.cancelled = true;\n initializing.scope.close();\n return Promise.resolve();\n }\n\n const existingTeardown = this.#teardowns.get(name);\n if (existingTeardown !== undefined) {\n // A destroy hook removing its own name cannot await the teardown that\n // awaits it; its resources are already revoked, so this is complete.\n if (this.#destroying.has(name)) return Promise.resolve();\n return queued ? this.#holdQueue(existingTeardown) : existingTeardown;\n }\n const registration = this.#plugins.get(name);\n if (registration === undefined) return Promise.resolve();\n\n // Revoke before consumer code runs: a throwing destroy keeps no access,\n // and a same-name registration from inside destroy stays a duplicate.\n this.#plugins.delete(name);\n registration.scope.close();\n const teardown = Promise.resolve().then(() =>\n this.#destroyPlugin(name, registration.plugin, queued),\n );\n this.#teardowns.set(name, teardown);\n void teardown.then(() => {\n if (this.#teardowns.get(name) === teardown) this.#teardowns.delete(name);\n });\n return teardown;\n }\n\n async #destroyPlugin(name: string, plugin: LivePreviewPlugin, queued: boolean): Promise<void> {\n if (plugin.destroy === undefined) return;\n this.#destroying.add(name);\n try {\n await this.#runHook(() => plugin.destroy?.(), queued);\n } catch (error) {\n this.#log(`plugin \"${name}\" destroy failed:`, error);\n } finally {\n this.#destroying.delete(name);\n }\n }\n\n async #destroyAllNow(queued: boolean): Promise<void> {\n for (const initializing of this.#initializing.values()) {\n initializing.cancelled = true;\n initializing.scope.close();\n }\n const names = [...this.#plugins.keys()];\n for (const name of names) await this.#unregisterNow(name, queued);\n }\n\n async #runHook(hook: () => void | Promise<void>, queued: boolean): Promise<void> {\n if (!queued) {\n await hook();\n return;\n }\n await this.#holdQueue(Promise.resolve().then(hook));\n }\n\n async #holdQueue(pending: Promise<void>): Promise<void> {\n this.#queuedHooks += 1;\n try {\n await pending;\n } finally {\n this.#queuedHooks -= 1;\n }\n }\n\n #enqueue(operation: () => void | Promise<void>): Promise<void> {\n const result = this.#mutationQueue.then(operation);\n // Keep the tail usable after an escaped error; the caller still sees it on `result`.\n this.#mutationQueue = result.catch((error: unknown) => {\n this.#log('plugin manager mutation failed:', error);\n });\n return result;\n }\n}\n","/**\n * Plugin compatibility claims. The range grammar is the subset a plugin\n * author writes (`*`, `1.2.3`, `^`, `~`, `>=`, `>`, `<`, `<=`, space-joined\n * conjunctions, `||` alternatives); prerelease tags are ignored.\n */\n\nexport interface PluginCompatibility {\n /** A semver range the runtime's `VERSION` must satisfy, e.g. `>=2.0.0`. */\n readonly runtime?: string;\n /** The highest postMessage protocol version the plugin understands. */\n readonly protocol?: number;\n}\n\ntype Version = readonly [number, number, number];\n\nfunction parseVersion(text: string): Version | undefined {\n const match = /^v?(\\d+)\\.(\\d+)\\.(\\d+)/.exec(text.trim());\n if (match === null) return undefined;\n return [Number(match[1]), Number(match[2]), Number(match[3])];\n}\n\nfunction compare(a: Version, b: Version): number {\n for (let index = 0; index < 3; index += 1) {\n const delta = (a[index] ?? 0) - (b[index] ?? 0);\n if (delta !== 0) return delta;\n }\n return 0;\n}\n\nfunction satisfiesComparator(version: Version, comparator: string): boolean {\n const trimmed = comparator.trim();\n if (trimmed === '' || trimmed === '*') return true;\n const match = /^(\\^|~|>=|<=|>|<|=)?\\s*v?(\\d+)\\.(\\d+)\\.(\\d+)/.exec(trimmed);\n if (match === null) return false;\n const operator = match[1] ?? '=';\n const target: Version = [Number(match[2]), Number(match[3]), Number(match[4])];\n const order = compare(version, target);\n switch (operator) {\n case '=':\n return order === 0;\n case '>':\n return order > 0;\n case '>=':\n return order >= 0;\n case '<':\n return order < 0;\n case '<=':\n return order <= 0;\n case '~':\n return order >= 0 && version[0] === target[0] && version[1] === target[1];\n case '^':\n if (order < 0) return false;\n if (target[0] > 0) return version[0] === target[0];\n if (target[1] > 0) return version[0] === 0 && version[1] === target[1];\n return version[0] === 0 && version[1] === 0 && version[2] === target[2];\n default:\n return false;\n }\n}\n\n/** Whether `version` satisfies `range`; anything unparsable never satisfies. */\nexport function satisfiesRange(version: string, range: string): boolean {\n const parsed = parseVersion(version);\n if (parsed === undefined) return false;\n const alternatives = range.split('||');\n return alternatives.some((alternative) => {\n const comparators = alternative\n .trim()\n .split(/\\s+/)\n .filter((part) => part.length > 0);\n if (comparators.length === 0) return alternative.trim() === '' && range.trim() === '';\n return comparators.every((comparator) => satisfiesComparator(parsed, comparator));\n });\n}\n\n/** Why a plugin was refused, or `undefined` when it fits. */\nexport function incompatibilityOf(\n compat: PluginCompatibility | undefined,\n runtimeVersion: string,\n protocolVersion: number,\n): string | undefined {\n if (compat === undefined) return undefined;\n if (compat.runtime !== undefined && !satisfiesRange(runtimeVersion, compat.runtime)) {\n return `declares runtime ${compat.runtime}, this runtime is ${runtimeVersion}`;\n }\n if (compat.protocol !== undefined) {\n if (!Number.isInteger(compat.protocol) || compat.protocol < 1) {\n return `declares an invalid protocol version ${String(compat.protocol)}`;\n }\n if (compat.protocol < protocolVersion) {\n return `declares protocol ${String(compat.protocol)}, this runtime speaks ${String(protocolVersion)}`;\n }\n }\n return undefined;\n}\n","/**\n * Per-client renderer layers: built-ins are the base, plugin registrations\n * stack above per field type, and removing a layer by identity reveals the\n * one beneath. See ADR 0005.\n */\n\nimport type { FieldRenderer, RendererKey } from '@core/types';\nimport type { PluginDisposer } from './types';\n\ninterface RendererLayer {\n readonly renderer: FieldRenderer;\n}\n\nexport class RendererRegistry {\n readonly #base: Readonly<Record<string, FieldRenderer>>;\n readonly #active: Record<string, FieldRenderer>;\n readonly #layers = new Map<RendererKey, RendererLayer[]>();\n\n constructor(base: Readonly<Record<string, FieldRenderer>>) {\n this.#base = base;\n this.#active = { ...base };\n }\n\n /** Stable live map, retained for the runtime's `renderers` option. */\n get renderers(): Readonly<Record<string, FieldRenderer>> {\n return this.#active;\n }\n\n resolve(fieldType: RendererKey): FieldRenderer | undefined {\n return this.#active[fieldType];\n }\n\n register(renderer: FieldRenderer): PluginDisposer {\n const fieldType = renderer.name;\n const layer: RendererLayer = { renderer };\n const stack = this.#layers.get(fieldType);\n if (stack === undefined) this.#layers.set(fieldType, [layer]);\n else stack.push(layer);\n this.#active[fieldType] = renderer;\n\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n\n const current = this.#layers.get(fieldType);\n if (current === undefined) return;\n const index = current.indexOf(layer);\n if (index < 0) return;\n const wasTop = index === current.length - 1;\n current.splice(index, 1);\n if (current.length === 0) this.#layers.delete(fieldType);\n if (!wasTop) return;\n\n const previousLayer = current.at(-1);\n const previousRenderer = previousLayer?.renderer ?? this.#base[fieldType];\n if (previousRenderer === undefined) Reflect.deleteProperty(this.#active, fieldType);\n else this.#active[fieldType] = previousRenderer;\n };\n }\n}\n","/** Attribute helpers shared by the block-level node renderers. */\n\nimport type { LexicalNode } from './types';\n\nconst ALIGNMENT_NUMERIC: Readonly<Record<number, string>> = {\n 1: 'left',\n 2: 'center',\n 3: 'right',\n 4: 'justify',\n};\n\nconst ALIGNMENT_STRING = new Set(['left', 'center', 'right', 'justify', 'start', 'end']);\n\n/** Alignment of a block node; Payload emits it as a string or as Lexical's numeric format. */\nexport function resolveAlignment(node: LexicalNode): string | undefined {\n const fmt = node.format;\n if (typeof fmt === 'string' && ALIGNMENT_STRING.has(fmt)) return fmt;\n if (typeof fmt === 'number') return ALIGNMENT_NUMERIC[fmt];\n return undefined;\n}\n\nexport function resolveIndent(node: LexicalNode): number {\n const indent = node.indent;\n return typeof indent === 'number' && indent > 0 ? indent : 0;\n}\n\nexport function dirAttribute(node: LexicalNode): string {\n if (node.direction === 'rtl') return ' dir=\"rtl\"';\n if (node.direction === 'ltr') return ' dir=\"ltr\"';\n return '';\n}\n\n/**\n * Alignment and indent as `lp-align-*` / `lp-indent-N` classes. The sanitizer\n * strips `style` under every policy, so inline CSS would never reach the page.\n */\nexport function layoutClassAttribute(node: LexicalNode): string {\n const align = resolveAlignment(node);\n const indent = resolveIndent(node);\n const classes: string[] = [];\n if (align !== undefined) classes.push(`lp-align-${align}`);\n if (indent > 0) classes.push(`lp-indent-${String(indent)}`);\n return classes.length === 0 ? '' : ` class=\"${classes.join(' ')}\"`;\n}\n","import type { NodeRenderer } from '../registry';\nimport { dirAttribute, layoutClassAttribute } from '../utils';\n\nconst paragraphRenderer: NodeRenderer = (node, ctx): string => {\n const children = ctx.renderChildren(node.children ?? []);\n return `<p${dirAttribute(node)}${layoutClassAttribute(node)}>${children}</p>`;\n};\n\nexport { paragraphRenderer };\n","/** `heading` renderer; an unknown `tag` (transient editor states emit them) falls back to `h2`. */\n\nimport type { NodeRenderer } from '../registry';\nimport { dirAttribute, layoutClassAttribute } from '../utils';\n\nconst VALID_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);\n\nconst headingRenderer: NodeRenderer = (node, ctx): string => {\n const tagRaw = typeof node['tag'] === 'string' ? node['tag'].toLowerCase() : 'h2';\n const tag = VALID_TAGS.has(tagRaw) ? tagRaw : 'h2';\n const children = ctx.renderChildren(node.children ?? []);\n return `<${tag}${dirAttribute(node)}${layoutClassAttribute(node)}>${children}</${tag}>`;\n};\n\nexport { headingRenderer };\n","/**\n * Value-shape helpers shared by the Lexical node renderers and the field\n * renderers. They live here because `field-types` may import `lexical`, never\n * the reverse (scripts/architecture-policy.ts).\n */\n\nexport interface MediaShape {\n readonly id?: string | number;\n readonly url?: string;\n readonly alt?: string;\n readonly filename?: string;\n readonly mimeType?: string;\n readonly width?: number;\n readonly height?: number;\n readonly sizes?: Readonly<\n Record<string, { readonly url?: string; readonly width?: number; readonly height?: number }>\n >;\n}\n\nexport interface RelationShape {\n readonly id?: string | number;\n readonly title?: string;\n readonly name?: string;\n readonly slug?: string;\n readonly url?: string;\n}\n\nexport function asRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\nexport function readMedia(value: unknown): MediaShape | undefined {\n return asRecord(value);\n}\n\n/** Reduce `value` to `[a-z0-9_-]` so it can be a class-name fragment without escaping. */\nexport function sanitizeIdent(value: string): string {\n return value.replace(/[^a-zA-Z0-9_-]/g, '-').toLowerCase();\n}\n\nfunction nonEmpty(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\n/** Label precedence for a populated relation: `title`, `name`, `slug`, then `id`. */\nexport function pickRelationLabel(value: RelationShape): string | undefined {\n const label = nonEmpty(value.title) ?? nonEmpty(value.name) ?? nonEmpty(value.slug);\n if (label !== undefined) return label;\n return value.id === undefined ? undefined : String(value.id);\n}\n","/**\n * `link` / `autolink` renderer. Payload 3.x serialises links as\n * `{ fields: { linkType, url, newTab, doc } }`; vanilla Lexical puts `url`\n * and `target` on the node itself. Both shapes are read, Payload's first.\n */\n\nimport { escapeHtml, escapeHtmlAttribute } from '@security/escape';\nimport { isExternalHttpUrl, isSafeUrl } from '@security/url-validator';\nimport type { NodeRenderer } from '../registry';\nimport type { LexicalNode } from '../types';\nimport { asRecord } from '../value-shapes';\n\nconst BLANK_TARGET = ' target=\"_blank\" rel=\"noopener noreferrer\"';\n\nconst linkRenderer: NodeRenderer = (node, ctx): string => {\n const children = ctx.renderChildren(node.children ?? []);\n const fields = asRecord(node['fields']);\n const url = resolveUrl(node, fields);\n if (url === undefined || !isSafeUrl(url)) return children;\n const titleAttr =\n typeof node['title'] === 'string' ? ` title=\"${escapeHtml(node['title'])}\"` : '';\n return `<a href=\"${escapeHtmlAttribute(url)}\"${targetAttribute(node, fields, url)}${titleAttr}>${children}</a>`;\n};\n\nfunction resolveUrl(\n node: LexicalNode,\n fields: Record<string, unknown> | undefined,\n): string | undefined {\n if (fields?.['linkType'] === 'internal') return internalUrl(fields['doc']);\n const url = fields?.['url'] ?? node['url'];\n return typeof url === 'string' && url.length > 0 ? url : undefined;\n}\n\n/** An internal link needs the populated document; a bare id has no route to offer. */\nfunction internalUrl(doc: unknown): string | undefined {\n const value = asRecord(asRecord(doc)?.['value']);\n const url = value?.['url'];\n if (typeof url === 'string' && url.length > 0) return url;\n const slug = value?.['slug'];\n return typeof slug === 'string' && slug.length > 0 ? `/${slug}` : undefined;\n}\n\n/** `_blank` always carries `noopener noreferrer`, whichever side asked for it. */\nfunction targetAttribute(\n node: LexicalNode,\n fields: Record<string, unknown> | undefined,\n url: string,\n): string {\n if (fields?.['newTab'] === true || isExternalHttpUrl(url)) return BLANK_TARGET;\n const target = typeof node['target'] === 'string' ? node['target'] : '';\n if (target === '') return '';\n if (target === '_blank') return BLANK_TARGET;\n return ` target=\"${escapeHtml(target)}\"`;\n}\n\nexport { linkRenderer };\n","/** `code` (fenced block) and `code-highlight` (token span) renderers. */\n\nimport { escapeHtml } from '@security/escape';\nimport type { NodeRenderer } from '../registry';\nimport type { LexicalNode } from '../types';\nimport { sanitizeIdent } from '../value-shapes';\n\nconst codeRenderer: NodeRenderer = (node): string => {\n const language = sanitizeIdent(typeof node['language'] === 'string' ? node['language'] : '');\n const langClass = language === '' ? '' : ` class=\"language-${language}\"`;\n return `<pre><code${langClass}>${escapeHtml(extractText(node))}</code></pre>`;\n};\n\nconst codeHighlightRenderer: NodeRenderer = (node): string => {\n const text = typeof node.text === 'string' ? node.text : '';\n const highlight =\n typeof node['highlightType'] === 'string'\n ? ` class=\"token-${sanitizeIdent(node['highlightType'])}\"`\n : '';\n return `<span${highlight}>${escapeHtml(text)}</span>`;\n};\n\nexport { codeRenderer, codeHighlightRenderer };\n\nfunction extractText(node: LexicalNode): string {\n if (typeof node.text === 'string') return node.text;\n if (!node.children) return '';\n let out = '';\n for (const child of node.children) out += extractText(child);\n return out;\n}\n","/**\n * `upload` renderer: `<img>` for image (or unknown) MIME types, `<video>` /\n * `<audio>` for media, a download link otherwise. An unsafe URL renders nothing.\n */\n\nimport { escapeHtml, escapeHtmlAttribute } from '@security/escape';\nimport { isSafeUrl } from '@security/url-validator';\nimport type { NodeRenderer } from '../registry';\nimport { readMedia, type MediaShape } from '../value-shapes';\n\nconst uploadRenderer: NodeRenderer = (node): string => {\n const value = readMedia(node['value']);\n if (value === undefined) return '';\n const url = value.url;\n if (typeof url !== 'string' || !isSafeUrl(url)) return '';\n\n const mime = typeof value.mimeType === 'string' ? value.mimeType : '';\n if (mime.startsWith('video/')) return renderVideo(value, url);\n if (mime.startsWith('audio/')) return renderAudio(value, url);\n if (mime === '' || mime.startsWith('image/')) return renderImage(value, url);\n return renderFallbackLink(value, url);\n};\n\nexport { uploadRenderer };\n\nfunction dimensionAttributes(value: MediaShape): string {\n const width = typeof value.width === 'number' ? ` width=\"${String(value.width)}\"` : '';\n const height = typeof value.height === 'number' ? ` height=\"${String(value.height)}\"` : '';\n return `${width}${height}`;\n}\n\nfunction typeAttribute(value: MediaShape): string {\n return typeof value.mimeType === 'string' ? ` type=\"${escapeHtmlAttribute(value.mimeType)}\"` : '';\n}\n\nfunction renderImage(value: MediaShape, url: string): string {\n const alt = typeof value.alt === 'string' ? escapeHtml(value.alt) : '';\n return `<img src=\"${escapeHtmlAttribute(url)}\" alt=\"${alt}\"${dimensionAttributes(value)} loading=\"lazy\" decoding=\"async\">`;\n}\n\nfunction renderVideo(value: MediaShape, url: string): string {\n return `<video controls${dimensionAttributes(value)}><source src=\"${escapeHtmlAttribute(url)}\"${typeAttribute(value)}></video>`;\n}\n\nfunction renderAudio(value: MediaShape, url: string): string {\n return `<audio controls><source src=\"${escapeHtmlAttribute(url)}\"${typeAttribute(value)}></audio>`;\n}\n\nfunction renderFallbackLink(value: MediaShape, url: string): string {\n const label = typeof value.filename === 'string' ? escapeHtml(value.filename) : escapeHtml(url);\n return `<a href=\"${escapeHtmlAttribute(url)}\" target=\"_blank\" rel=\"noopener noreferrer\">${label}</a>`;\n}\n","/** `relationship` renderer: a link when the populated document carries a URL, a span otherwise. */\n\nimport { escapeHtml, escapeHtmlAttribute } from '@security/escape';\nimport { isSafeUrl } from '@security/url-validator';\nimport type { NodeRenderer } from '../registry';\nimport { asRecord, pickRelationLabel, sanitizeIdent, type RelationShape } from '../value-shapes';\n\nconst relationshipRenderer: NodeRenderer = (node): string => {\n const relationTo = typeof node['relationTo'] === 'string' ? node['relationTo'] : '';\n const value = asRecord(node['value']) as RelationShape | undefined;\n const label = escapeHtml((value && pickRelationLabel(value)) ?? `#${relationTo}`);\n const slug = sanitizeIdent(relationTo);\n const classAttr =\n slug === '' ? ' class=\"lp-relation\"' : ` class=\"lp-relation lp-relation--${slug}\"`;\n const url = value?.url;\n if (typeof url === 'string' && isSafeUrl(url)) {\n return `<a href=\"${escapeHtmlAttribute(url)}\"${classAttr}>${label}</a>`;\n }\n return `<span${classAttr}>${label}</span>`;\n};\n\nexport { relationshipRenderer };\n","/** Block-renderer registry keyed by Payload block slug; consulted by the `block` and `inlineBlock` nodes. */\n\nimport type { LexicalNode } from '../types';\n\nexport interface BlockRenderContext {\n /** Render nested Lexical content through the node registry. */\n readonly renderChildren: (children: readonly LexicalNode[]) => string;\n}\n\n/** Receives the block's `fields` (with `blockType`) and returns HTML. */\nexport type BlockRenderer = (\n fields: Record<string, unknown>,\n context: BlockRenderContext,\n) => string;\n\nconst registry = new Map<string, BlockRenderer>();\n\n/** Register or replace the renderer for `blockType`. */\nexport function registerBlockRenderer(blockType: string, renderer: BlockRenderer): void {\n registry.set(blockType, renderer);\n}\n\nexport function lookupBlockRenderer(blockType: string): BlockRenderer | undefined {\n return registry.get(blockType);\n}\n\nexport function registeredBlockTypes(): readonly string[] {\n return [...registry.keys()];\n}\n\n/** Test-only: clear the registry. */\nexport function __resetBlockRegistryForTests(): void {\n registry.clear();\n}\n","/**\n * `block` and `inlineBlock` renderers for Payload's BlocksFeature. The block\n * registry is consulted first; without a renderer for the slug the node\n * becomes an empty, class-tagged element a consumer can style or replace.\n */\n\nimport { lookupBlockRenderer } from '../blocks/registry';\nimport type { NodeRenderer, RenderNodeContext } from '../registry';\nimport type { LexicalNode } from '../types';\nimport { asRecord, sanitizeIdent } from '../value-shapes';\n\nfunction renderBlockNode(\n node: LexicalNode,\n ctx: RenderNodeContext,\n tag: 'div' | 'span',\n baseClass: string,\n): string {\n const fields = asRecord(node['fields']) ?? {};\n const blockType = typeof fields['blockType'] === 'string' ? fields['blockType'] : '';\n const slug = sanitizeIdent(blockType);\n if (blockType !== '') {\n const custom = lookupBlockRenderer(blockType) ?? lookupBlockRenderer(slug);\n if (custom) return custom(fields, { renderChildren: ctx.renderChildren });\n }\n const classes = slug === '' ? baseClass : `${baseClass} ${baseClass}--${slug}`;\n return `<${tag} class=\"${classes}\"></${tag}>`;\n}\n\nconst blockRenderer: NodeRenderer = (node, ctx) => renderBlockNode(node, ctx, 'div', 'lp-block');\n\nconst inlineBlockRenderer: NodeRenderer = (node, ctx) =>\n renderBlockNode(node, ctx, 'span', 'lp-inline-block');\n\nexport { blockRenderer, inlineBlockRenderer };\n","/** `table` / `tablerow` / `tablecell` renderers for the `@lexical/table` shapes Payload's table feature emits. */\n\nimport type { NodeRenderer } from '../registry';\nimport { dirAttribute } from '../utils';\n\n// `@lexical/table` TableCellHeaderStates: ROW marks a cell in a header row, COLUMN one in a header column.\nconst HEADER_ROW = 1;\nconst HEADER_COLUMN = 2;\n\nconst tableRenderer: NodeRenderer = (node, ctx) =>\n `<table${dirAttribute(node)}><tbody>${ctx.renderChildren(node.children ?? [])}</tbody></table>`;\n\nconst tableRowRenderer: NodeRenderer = (node, ctx) =>\n `<tr>${ctx.renderChildren(node.children ?? [])}</tr>`;\n\nconst tableCellRenderer: NodeRenderer = (node, ctx): string => {\n const header = typeof node['headerState'] === 'number' ? node['headerState'] : 0;\n const tag = (header & (HEADER_ROW | HEADER_COLUMN)) === 0 ? 'td' : 'th';\n const scope =\n header === HEADER_ROW ? ' scope=\"col\"' : header === HEADER_COLUMN ? ' scope=\"row\"' : '';\n return `<${tag}${scope}${spanAttribute('colspan', node['colSpan'])}${spanAttribute('rowspan', node['rowSpan'])}>${ctx.renderChildren(node.children ?? [])}</${tag}>`;\n};\n\nfunction spanAttribute(name: string, value: unknown): string {\n return typeof value === 'number' && value > 1 ? ` ${name}=\"${String(value)}\"` : '';\n}\n\nexport { tableRenderer, tableRowRenderer, tableCellRenderer };\n","import type { NodeRenderer } from '../registry';\nimport { textRenderer } from './text';\nimport { paragraphRenderer } from './paragraph';\nimport { headingRenderer } from './heading';\nimport { listRenderer, listItemRenderer } from './list';\nimport { linkRenderer } from './link';\nimport { quoteRenderer } from './quote';\nimport { codeRenderer, codeHighlightRenderer } from './code';\nimport { linebreakRenderer, horizontalRuleRenderer, tabRenderer } from './linebreak';\nimport { uploadRenderer } from './upload';\nimport { relationshipRenderer } from './relationship';\nimport { blockRenderer, inlineBlockRenderer } from './block';\nimport { tableCellRenderer, tableRenderer, tableRowRenderer } from './table';\n\n// A value table instead of `register()` calls at import time: a consumer that\n// never renders Lexical content must not carry these under `sideEffects: false`.\nexport const BUILTIN_NODE_RENDERERS: Readonly<Record<string, NodeRenderer>> = {\n text: textRenderer,\n paragraph: paragraphRenderer,\n heading: headingRenderer,\n list: listRenderer,\n listitem: listItemRenderer,\n link: linkRenderer,\n autolink: linkRenderer,\n quote: quoteRenderer,\n code: codeRenderer,\n 'code-highlight': codeHighlightRenderer,\n linebreak: linebreakRenderer,\n horizontalrule: horizontalRuleRenderer,\n tab: tabRenderer,\n upload: uploadRenderer,\n relationship: relationshipRenderer,\n block: blockRenderer,\n inlineBlock: inlineBlockRenderer,\n table: tableRenderer,\n tablerow: tableRowRenderer,\n tablecell: tableCellRenderer,\n};\n","/** `text` renderer. Format flags wrap in a fixed order so equal input gives byte-equal output. */\n\nimport { escapeHtml } from '@security/escape';\nimport type { LexicalNode } from '../types';\nimport { TextFormat } from '../types';\nimport type { NodeRenderer } from '../registry';\n\nconst textRenderer: NodeRenderer = (node: LexicalNode): string => {\n const raw = typeof node.text === 'string' ? node.text : '';\n let out = escapeHtml(raw);\n const format = typeof node.format === 'number' ? node.format : 0;\n if ((format & TextFormat.CODE) !== 0) out = `<code>${out}</code>`;\n if ((format & TextFormat.BOLD) !== 0) out = `<strong>${out}</strong>`;\n if ((format & TextFormat.ITALIC) !== 0) out = `<em>${out}</em>`;\n if ((format & TextFormat.UNDERLINE) !== 0) out = `<u>${out}</u>`;\n if ((format & TextFormat.STRIKETHROUGH) !== 0) out = `<s>${out}</s>`;\n if ((format & TextFormat.SUBSCRIPT) !== 0) out = `<sub>${out}</sub>`;\n if ((format & TextFormat.SUPERSCRIPT) !== 0) out = `<sup>${out}</sup>`;\n if ((format & TextFormat.HIGHLIGHT) !== 0) out = `<mark>${out}</mark>`;\n return out;\n};\n\nexport { textRenderer };\n","/**\n * Lexical document types. Only `type` and `children` are required; every\n * other property is forwarded opaquely to the renderer for that node type.\n */\n\n/** Lexical text-format bitmask; flags combine (`BOLD | ITALIC === 3`). */\nexport const TextFormat = {\n BOLD: 1,\n ITALIC: 2,\n STRIKETHROUGH: 4,\n UNDERLINE: 8,\n CODE: 16,\n SUBSCRIPT: 32,\n SUPERSCRIPT: 64,\n HIGHLIGHT: 128,\n} as const;\n\nexport interface LexicalNode {\n readonly type: string;\n readonly version?: number;\n readonly format?: number | string;\n readonly indent?: number;\n readonly direction?: 'ltr' | 'rtl' | null;\n readonly children?: readonly LexicalNode[];\n readonly text?: string;\n readonly [extra: string]: unknown;\n}\n\nexport interface LexicalRoot {\n readonly root: {\n readonly type?: string;\n readonly children: readonly LexicalNode[];\n readonly direction?: 'ltr' | 'rtl' | null;\n readonly format?: number | string;\n readonly indent?: number;\n readonly [extra: string]: unknown;\n };\n}\n","/** `list` / `listitem` renderers: `bullet` → `<ul>`, `number` → `<ol>`, `check` → `<ul role=\"list\">` with `aria-checked` items. */\n\nimport { escapeHtml } from '@security/escape';\nimport type { NodeRenderer } from '../registry';\nimport { dirAttribute, layoutClassAttribute } from '../utils';\n\nconst listRenderer: NodeRenderer = (node, ctx): string => {\n const listType = typeof node['listType'] === 'string' ? node['listType'] : 'bullet';\n const tag = listType === 'number' ? 'ol' : 'ul';\n const startAttr =\n listType === 'number' && typeof node['start'] === 'number' && node['start'] > 1\n ? ` start=\"${String(node['start'])}\"`\n : '';\n const checkAttr = listType === 'check' ? ' role=\"list\"' : '';\n const children = ctx.renderChildren(node.children ?? []);\n return `<${tag}${dirAttribute(node)}${layoutClassAttribute(node)}${startAttr}${checkAttr}>${children}</${tag}>`;\n};\n\nconst listItemRenderer: NodeRenderer = (node, ctx): string => {\n const children = ctx.renderChildren(node.children ?? []);\n if (typeof node['checked'] === 'boolean') {\n const state = node['checked'] ? 'true' : 'false';\n return `<li role=\"checkbox\" aria-checked=\"${state}\"${layoutClassAttribute(node)}>${children}</li>`;\n }\n const valueAttr =\n typeof node['value'] === 'number' ? ` value=\"${escapeHtml(String(node['value']))}\"` : '';\n return `<li${dirAttribute(node)}${layoutClassAttribute(node)}${valueAttr}>${children}</li>`;\n};\n\nexport { listRenderer, listItemRenderer };\n","import type { NodeRenderer } from '../registry';\nimport { dirAttribute, layoutClassAttribute } from '../utils';\n\nconst quoteRenderer: NodeRenderer = (node, ctx): string => {\n const children = ctx.renderChildren(node.children ?? []);\n return `<blockquote${dirAttribute(node)}${layoutClassAttribute(node)}>${children}</blockquote>`;\n};\n\nexport { quoteRenderer };\n","import type { NodeRenderer } from '../registry';\n\nconst linebreakRenderer: NodeRenderer = () => '<br>';\nconst horizontalRuleRenderer: NodeRenderer = () => '<hr>';\nconst tabRenderer: NodeRenderer = () => '\\t';\n\nexport { linebreakRenderer, horizontalRuleRenderer, tabRenderer };\n","/** Node-renderer registry: consumer registrations layered over the built-in table. */\n\nimport type { LexicalNode } from './types';\nimport { BUILTIN_NODE_RENDERERS } from './nodes/builtin';\n\nexport interface RenderNodeContext {\n /** Render child nodes through the registry. */\n readonly renderChildren: (children: readonly LexicalNode[]) => string;\n /** Text alignment of a block node, or `undefined`. */\n readonly resolveAlignment: (node: LexicalNode) => string | undefined;\n /** Indent level of a node, `0` when none. */\n readonly resolveIndent: (node: LexicalNode) => number;\n}\n\nexport type NodeRenderer = (node: LexicalNode, context: RenderNodeContext) => string;\n\nconst registry = new Map<string, NodeRenderer>();\n\n/** Register or replace the renderer for `type`. */\nexport function register(type: string, renderer: NodeRenderer): void {\n registry.set(type, renderer);\n}\n\nexport function lookup(type: string): NodeRenderer | undefined {\n return registry.get(type) ?? BUILTIN_NODE_RENDERERS[type];\n}\n\nexport function registeredTypes(): readonly string[] {\n return [...new Set([...Object.keys(BUILTIN_NODE_RENDERERS), ...registry.keys()])];\n}\n\n/** Test-only: drop consumer registrations. */\nexport function __resetForTests(): void {\n registry.clear();\n}\n","/**\n * Lexical → HTML. Each node dispatches to the renderer registered for its\n * `type`; an unknown node renders its children so content is never lost.\n */\n\nimport { sanitizeHtml, hasSanitizerDocument } from '@security/sanitizer';\nimport { lookup, type RenderNodeContext } from './registry';\nimport type { LexicalNode, LexicalRoot } from './types';\nimport { resolveAlignment, resolveIndent } from './utils';\n\nconst RENDER_CONTEXT: RenderNodeContext = {\n renderChildren,\n resolveAlignment,\n resolveIndent,\n};\n\nexport interface LexicalRenderOptions {\n /** Pass the result through `sanitizeHtml()` (default `true`). */\n readonly sanitize?: boolean;\n}\n\nlet warnedNoSanitizer = false;\n\nexport function isLexicalContent(value: unknown): value is LexicalRoot {\n if (typeof value !== 'object' || value === null) return false;\n if (!('root' in value)) return false;\n const root = value.root;\n if (typeof root !== 'object' || root === null) return false;\n if (!('children' in root)) return false;\n return Array.isArray(root.children);\n}\n\n/** Render a Lexical document to HTML; without `setSanitizerDocument()` the result is unsanitised and warns once. */\nexport function lexicalToHtml(content: LexicalRoot, options: LexicalRenderOptions = {}): string {\n if (!isLexicalContent(content)) return '';\n const html = renderChildren(content.root.children);\n if (options.sanitize === false) return html;\n if (hasSanitizerDocument()) return sanitizeHtml(html);\n warnNoSanitizerOnce();\n return html;\n}\n\n/** Plain text of a document, paragraphs separated by `\\n`. */\nexport function lexicalToPlainText(content: LexicalRoot): string {\n if (!isLexicalContent(content)) return '';\n return content.root.children.map(extractPlainText).join('\\n').trim();\n}\n\n/** Test-only: allow the SSR warning to fire again. */\nexport function __resetSanitizerWarningForTests(): void {\n warnedNoSanitizer = false;\n}\n\nfunction renderChildren(children: readonly LexicalNode[]): string {\n let out = '';\n for (const child of children) out += renderNode(child);\n return out;\n}\n\nfunction renderNode(node: LexicalNode): string {\n const renderer = lookup(node.type);\n if (renderer) return renderer(node, RENDER_CONTEXT);\n return node.children !== undefined ? renderChildren(node.children) : '';\n}\n\nfunction extractPlainText(node: LexicalNode): string {\n if (typeof node.text === 'string') return node.text;\n if (node.type === 'linebreak') return '\\n';\n if (node.children === undefined) return '';\n let out = '';\n for (const child of node.children) out += extractPlainText(child);\n return out;\n}\n\n// This layer may not import `@core/diagnostics` (architecture policy), so the\n// warn-once lives here; a hostile or absent console must not break rendering.\nfunction warnNoSanitizerOnce(): void {\n if (warnedNoSanitizer) return;\n warnedNoSanitizer = true;\n try {\n console.warn(\n '[live-preview] lexicalToHtml() has no sanitizer document and returned unsanitised HTML; ' +\n 'call setSanitizerDocument() (linkedom/jsdom) for server rendering, see docs/security.md §3.',\n );\n } catch {\n // Diagnostics never become a second failure.\n }\n}\n","/**\n * `text` / `textarea` renderer. An element with structured children is left\n * alone (warned once) unless it opts in with `data-payload-text`, so a styled\n * wrapper is not destroyed by a value meant for its text node.\n */\n\nimport { isLexicalContent, lexicalToPlainText } from '@lexical/render';\nimport { trustedHtml } from '@security/trusted-types';\nimport { escapeAndLinebreak } from '@security/escape';\nimport { safeConsoleWarn } from '@core/diagnostics';\nimport { markNoWriteCallback } from '@core/internal-outcome';\nimport type { FieldRenderer, RendererKey } from '@core/types';\n\nconst TEXT_OPT_IN_ATTRIBUTE = 'data-payload-text';\n\n/** Build the renderer with its own warn-once state; one per client (ADR 0002). */\nexport function createTextRenderer(name: RendererKey = 'text'): FieldRenderer {\n const warnedElements = new WeakSet<Element>();\n\n return {\n name,\n render: /* @__PURE__ */ markNoWriteCallback((target, value) => {\n const element = target.element;\n const text = toPlainString(value);\n if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {\n (element as HTMLInputElement | HTMLTextAreaElement).value = text;\n return;\n }\n if (hasForeignChildren(element) && !element.hasAttribute(TEXT_OPT_IN_ATTRIBUTE)) {\n warnOnce(warnedElements, element, target.fieldName);\n return false;\n }\n if (text.includes('\\n') || text.includes('\\r')) {\n element.innerHTML = trustedHtml(escapeAndLinebreak(text));\n return;\n }\n element.textContent = text;\n return;\n }),\n };\n}\n\n// `<br>` is this renderer's own multiline output, not a consumer wrapper;\n// counting it froze every multiline binding after its first write.\nfunction hasForeignChildren(element: Element): boolean {\n return element.querySelector(':scope > :not(br)') !== null;\n}\n\nfunction warnOnce(warnedElements: WeakSet<Element>, element: Element, fieldName: string): void {\n if (warnedElements.has(element)) return;\n warnedElements.add(element);\n safeConsoleWarn(\n `[live-preview] LP0402: Skipping text update for \"${fieldName}\": ` +\n `<${element.tagName.toLowerCase()}> has structured children. Move ` +\n `data-payload-field to the value element, or add data-payload-text to replace them.`,\n );\n}\n\nfunction toPlainString(value: unknown): string {\n if (value === null || value === undefined) return '';\n if (isLexicalContent(value)) return lexicalToPlainText(value);\n if (typeof value === 'string') return value;\n if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n return JSON.stringify(value);\n}\n","/**\n * `richText` renderer: a Lexical root or an HTML string. A project\n * `renderRichText` takes precedence; its output is sanitised like every\n * other HTML write.\n */\n\nimport { isLexicalContent, lexicalToHtml } from '@lexical/render';\nimport { trustedHtml } from '@security/trusted-types';\nimport { sanitizeHtml } from '@security/sanitizer';\nimport { markNoWriteCallback } from '@core/internal-outcome';\nimport type { FieldRenderer } from '@core/types';\nimport { isEmptyValue } from './utils';\n\nconst richTextRenderer: FieldRenderer = {\n name: 'richText',\n render: /* @__PURE__ */ markNoWriteCallback((target, value, context) => {\n const element = target.element;\n if (isEmptyValue(value)) {\n element.textContent = '';\n return;\n }\n if (context.renderRichText !== undefined) {\n const html = context.renderRichText(value, {\n fieldName: target.fieldName,\n element,\n locale: context.locale,\n });\n element.innerHTML = trustedHtml(sanitizeHtml(html));\n return;\n }\n if (isLexicalContent(value)) {\n element.innerHTML = trustedHtml(lexicalToHtml(value));\n return;\n }\n if (typeof value === 'string') {\n element.innerHTML = trustedHtml(sanitizeHtml(value));\n return;\n }\n return false;\n }),\n};\n\nexport { richTextRenderer };\n","/** `html` renderer (`data-payload-type=\"html\"`): the value is sanitised, then injected. */\n\nimport { sanitizeHtml } from '@security/sanitizer';\nimport { trustedHtml } from '@security/trusted-types';\nimport type { FieldRenderer } from '@core/types';\nimport { isEmptyValue, safeStringify } from './utils';\n\nconst htmlRenderer: FieldRenderer = {\n name: 'html',\n render(target, value) {\n if (isEmptyValue(value)) {\n target.element.textContent = '';\n return;\n }\n const html = typeof value === 'string' ? value : safeStringify(value);\n target.element.innerHTML = trustedHtml(sanitizeHtml(html));\n },\n};\n\nexport { htmlRenderer };\n","/** URL acceptance shared by the renderers that write `href` / `src`: one LP0401 warning per element. */\n\nimport { safeConsoleWarn } from '@core/diagnostics';\nimport { isSafeUrl } from '@security/url-validator';\n\n// Keyed by element so a second client on the same page does not repeat the warning.\nconst warned = new WeakSet<Element>();\n\nexport type UrlOutcome =\n | { readonly kind: 'none' }\n | { readonly kind: 'unsafe' }\n | { readonly kind: 'safe'; readonly url: string };\n\n/** `none` when there is no URL to write, `unsafe` (warned once) when it fails `isSafeUrl`. */\nexport function acceptUrl(element: Element, fieldName: string, candidate: unknown): UrlOutcome {\n if (typeof candidate !== 'string' || candidate.length === 0) return { kind: 'none' };\n if (isSafeUrl(candidate)) return { kind: 'safe', url: candidate };\n if (!warned.has(element)) {\n warned.add(element);\n safeConsoleWarn(\n `[live-preview] LP0401: refused an unsafe URL for \"${fieldName}\" on ` +\n `<${element.tagName.toLowerCase()}>; the attribute was cleared.`,\n );\n }\n return { kind: 'unsafe' };\n}\n","/**\n * `url` renderer and the factory the `email` renderer shares. On an `<a>` the\n * value (or the `data-payload-href` sibling) becomes `href`; the value is\n * always the visible text.\n */\n\nimport { resolveFieldValue } from '@core/field-value';\nimport type { FieldRenderer, RendererKey } from '@core/types';\nimport { acceptUrl } from './unsafe-url';\nimport { isEmptyValue, safeStringify } from './utils';\n\n/** Build the link renderer named `name`; `toHref` derives the URL from the field value. */\nexport function createLinkRenderer(\n name: RendererKey,\n toHref: (value: string) => string = (value) => value,\n): FieldRenderer {\n return {\n name,\n render(target, value, context) {\n const element = target.element;\n if (isEmptyValue(value)) {\n clear(element);\n return;\n }\n const text = safeStringify(value);\n if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {\n (element as HTMLInputElement | HTMLTextAreaElement).value = text;\n return;\n }\n if (element.tagName === 'A') {\n const hrefField = target.hrefField;\n const candidate =\n hrefField === undefined || hrefField.length === 0\n ? toHref(text)\n : resolveFieldValue(\n context.allFields,\n hrefField,\n context.locale,\n target.locale !== undefined,\n );\n const outcome = acceptUrl(element, target.fieldName, candidate);\n if (outcome.kind === 'safe') element.setAttribute('href', outcome.url);\n else if (outcome.kind === 'unsafe') element.removeAttribute('href');\n }\n element.textContent = text;\n },\n };\n}\n\nfunction clear(element: Element): void {\n if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {\n (element as HTMLInputElement | HTMLTextAreaElement).value = '';\n return;\n }\n element.removeAttribute('href');\n element.textContent = '';\n}\n\nexport const urlRenderer: FieldRenderer = createLinkRenderer('url');\n","/** `email` renderer: a bare address becomes a `mailto:` link, a value with a scheme is used as written. */\n\nimport type { FieldRenderer } from '@core/types';\nimport { createLinkRenderer } from './url';\n\nconst HAS_SCHEME = /^[a-zA-Z][a-zA-Z0-9+.-]*:/;\n\nfunction mailtoHref(value: string): string {\n const trimmed = value.trim();\n if (HAS_SCHEME.test(trimmed) || !trimmed.includes('@')) return trimmed;\n return `mailto:${trimmed}`;\n}\n\nexport const emailRenderer: FieldRenderer = createLinkRenderer('email', mailtoHref);\n","/** `<img>` writes shared by the image and upload renderers. */\n\nimport { isSafeUrl } from '@security/url-validator';\nimport type { MediaShape } from '@lexical/value-shapes';\n\nconst IMAGE_SOURCE_ATTRIBUTES = ['src', 'srcset', 'sizes'] as const;\n\nexport function clearImage(img: HTMLImageElement): void {\n for (const name of IMAGE_SOURCE_ATTRIBUTES) img.removeAttribute(name);\n}\n\n/**\n * A server-rendered `srcset` would keep winning over a new `src`, so it is\n * rebuilt from the media's `sizes` or removed together with `sizes`.\n */\nexport function writeImage(\n img: HTMLImageElement,\n url: string,\n media: MediaShape | undefined,\n): void {\n img.src = url;\n const srcset = buildSrcset(media);\n if (srcset === undefined) {\n img.removeAttribute('srcset');\n img.removeAttribute('sizes');\n return;\n }\n img.setAttribute('srcset', srcset);\n}\n\nfunction buildSrcset(media: MediaShape | undefined): string | undefined {\n if (media?.sizes === undefined) return undefined;\n const candidates: string[] = [];\n for (const size of Object.values(media.sizes)) {\n if (typeof size.url !== 'string' || typeof size.width !== 'number' || !isSafeUrl(size.url)) {\n continue;\n }\n candidates.push(`${srcsetUrl(size.url)} ${String(size.width)}w`);\n }\n if (candidates.length === 0) return undefined;\n if (typeof media.width === 'number' && typeof media.url === 'string' && isSafeUrl(media.url)) {\n candidates.push(`${srcsetUrl(media.url)} ${String(media.width)}w`);\n }\n return candidates.join(', ');\n}\n\n// Commas and whitespace delimit srcset candidates and cannot appear raw in a URL there.\nfunction srcsetUrl(url: string): string {\n return url.replace(/[\\s,]/g, encodeURIComponent);\n}\n","/**\n * `image` renderer: `src`/`alt`/`srcset` on an `<img>`, a CSS background on\n * anything else. The value is a media object, a URL string, or resolved from\n * the `data-payload-src` / `data-payload-alt` sibling fields.\n */\n\nimport { escapeCssUrl } from '@security/escape';\nimport { resolveFieldValue } from '@core/field-value';\nimport { markNoWriteCallback } from '@core/internal-outcome';\nimport type { CachedElement, FieldRenderer, RenderContext } from '@core/types';\nimport { readMedia, type MediaShape } from '@lexical/value-shapes';\nimport { clearImage, writeImage } from './media';\nimport { acceptUrl } from './unsafe-url';\nimport { isEmptyValue } from './utils';\n\nconst imageRenderer: FieldRenderer = {\n name: 'image',\n render: /* @__PURE__ */ markNoWriteCallback((target, value, context) => {\n const element = target.element;\n if (isEmptyValue(value)) {\n clear(element);\n return;\n }\n const preferLocale = target.locale !== undefined;\n const { media, candidate } = pickSource(target, value, context, preferLocale);\n const outcome = acceptUrl(element, target.fieldName, candidate);\n if (outcome.kind === 'none') return false;\n if (outcome.kind === 'unsafe') {\n clear(element);\n return;\n }\n if (element.tagName === 'IMG') {\n const img = element as HTMLImageElement;\n writeImage(img, outcome.url, media);\n const alt = pickAlt(media, target.altField, context.allFields, context.locale, preferLocale);\n if (alt !== undefined) img.alt = alt;\n return;\n }\n (element as HTMLElement).style.backgroundImage = `url('${escapeCssUrl(outcome.url)}')`;\n return;\n }),\n};\n\nfunction clear(element: Element): void {\n if (element.tagName === 'IMG') clearImage(element as HTMLImageElement);\n else (element as HTMLElement).style.backgroundImage = '';\n}\n\nfunction pickSource(\n target: CachedElement,\n value: unknown,\n context: RenderContext,\n preferLocale: boolean,\n): { readonly media: MediaShape | undefined; readonly candidate: unknown } {\n const source =\n target.srcField !== undefined && target.srcField.length > 0\n ? resolveFieldValue(context.allFields, target.srcField, context.locale, preferLocale)\n : value;\n const media = readMedia(source);\n return { media, candidate: media === undefined ? source : media.url };\n}\n\nfunction pickAlt(\n media: MediaShape | undefined,\n altField: string | undefined,\n allFields: Record<string, unknown>,\n locale: string | undefined,\n preferLocale: boolean,\n): string | undefined {\n if (altField !== undefined && altField.length > 0) {\n const sibling = resolveFieldValue(allFields, altField, locale, preferLocale);\n return typeof sibling === 'string' ? sibling : undefined;\n }\n return media?.alt;\n}\n\nexport { imageRenderer };\n","/** `upload` renderer: an image on `<img>`, a download link on `<a>`, an injected link elsewhere. */\n\nimport { escapeHtml, escapeHtmlAttribute } from '@security/escape';\nimport { trustedHtml } from '@security/trusted-types';\nimport { markNoWriteCallback } from '@core/internal-outcome';\nimport type { FieldRenderer } from '@core/types';\nimport { readMedia } from '@lexical/value-shapes';\nimport { clearImage, writeImage } from './media';\nimport { acceptUrl } from './unsafe-url';\nimport { isEmptyValue } from './utils';\n\nconst uploadRenderer: FieldRenderer = {\n name: 'upload',\n render: /* @__PURE__ */ markNoWriteCallback((target, value) => {\n const element = target.element;\n if (isEmptyValue(value)) {\n clear(element);\n return;\n }\n const media = readMedia(value);\n if (media === undefined) return false;\n const outcome = acceptUrl(element, target.fieldName, media.url);\n if (outcome.kind === 'none') return false;\n if (outcome.kind === 'unsafe') {\n clear(element);\n return;\n }\n const url = outcome.url;\n if (element.tagName === 'IMG') {\n const img = element as HTMLImageElement;\n writeImage(img, url, media);\n if (media.alt !== undefined) img.alt = media.alt;\n return;\n }\n if (element.tagName === 'A') {\n element.setAttribute('href', url);\n element.textContent = media.filename ?? url;\n return;\n }\n const label = escapeHtml(media.filename ?? url);\n element.innerHTML = trustedHtml(`<a href=\"${escapeHtmlAttribute(url)}\">${label}</a>`);\n return;\n }),\n};\n\nfunction clear(element: Element): void {\n if (element.tagName === 'IMG') {\n clearImage(element as HTMLImageElement);\n return;\n }\n element.removeAttribute('href');\n element.textContent = '';\n}\n\nexport { uploadRenderer };\n","/** `relationship` renderer: the relation's label as text; on an `<a>` a populated `url` becomes `href`. */\n\nimport type { FieldRenderer } from '@core/types';\nimport { asRecord, pickRelationLabel, type RelationShape } from '@lexical/value-shapes';\nimport { acceptUrl } from './unsafe-url';\nimport { isEmptyValue, safeStringify } from './utils';\n\nconst relationshipRenderer: FieldRenderer = {\n name: 'relationship',\n render(target, value) {\n const element = target.element;\n if (isEmptyValue(value)) {\n element.removeAttribute('href');\n element.textContent = '';\n return;\n }\n if (element.tagName === 'A' && !Array.isArray(value)) {\n const outcome = acceptUrl(element, target.fieldName, asRecord(value)?.['url']);\n if (outcome.kind === 'safe') element.setAttribute('href', outcome.url);\n else if (outcome.kind === 'unsafe') element.removeAttribute('href');\n }\n element.textContent = Array.isArray(value) ? value.map(label).join(', ') : label(value);\n },\n};\n\nfunction label(value: unknown): string {\n const record = asRecord(value) as RelationShape | undefined;\n if (record === undefined) return safeStringify(value);\n return pickRelationLabel(record) ?? '';\n}\n\nexport { relationshipRenderer };\n","/**\n * `select` / `radio` renderer. Form controls receive option values; other\n * elements show the option labels from the field schema when the admin sent\n * one, else the values.\n */\n\nimport type { FieldRenderer, RenderContext } from '@core/types';\nimport { asRecord } from '@lexical/value-shapes';\nimport { isEmptyValue, safeStringify } from './utils';\n\nconst selectRenderer: FieldRenderer = {\n name: 'select',\n render(target, value, context) {\n const element = target.element;\n const values = isEmptyValue(value) ? [] : toValues(value);\n if (element.tagName === 'SELECT') {\n writeSelect(element as HTMLSelectElement, values);\n return;\n }\n if (element.tagName === 'INPUT' && (element as HTMLInputElement).type === 'radio') {\n const radio = element as HTMLInputElement;\n radio.checked = values.includes(radio.value);\n return;\n }\n element.textContent = values.map((item) => labelFor(item, context)).join(', ');\n },\n};\n\nfunction toValues(value: unknown): readonly string[] {\n if (Array.isArray(value)) return value.map(safeStringify);\n return [safeStringify(value)];\n}\n\n// `.value = 'a, b'` on a multiple select selects nothing; options are set one by one.\nfunction writeSelect(select: HTMLSelectElement, values: readonly string[]): void {\n if (select.multiple) {\n for (const option of Array.from(select.options)) {\n option.selected = values.includes(option.value);\n }\n return;\n }\n select.value = values[0] ?? '';\n}\n\nfunction labelFor(value: string, context: RenderContext): string {\n const options = context.schema?.['options'];\n if (!Array.isArray(options)) return value;\n for (const option of options) {\n const record = asRecord(option);\n if (record === undefined || safeStringify(record['value']) !== value) continue;\n return typeof record['label'] === 'string' ? record['label'] : value;\n }\n return value;\n}\n\nexport { selectRenderer };\n","/** `checkbox` renderer: `checked` on an input, `aria-checked` where present, `true`/`false` text otherwise. */\n\nimport type { FieldRenderer } from '@core/types';\n\nconst FALSE_STRINGS = new Set(['', 'false', '0', 'off', 'no']);\n\nconst checkboxRenderer: FieldRenderer = {\n name: 'checkbox',\n render(target, value) {\n const element = target.element;\n const checked = toBoolean(value);\n if (element.tagName === 'INPUT' && (element as HTMLInputElement).type === 'checkbox') {\n (element as HTMLInputElement).checked = checked;\n return;\n }\n if (element.hasAttribute('aria-checked')) {\n element.setAttribute('aria-checked', checked ? 'true' : 'false');\n return;\n }\n element.textContent = checked ? 'true' : 'false';\n },\n};\n\n// Form state and query parameters arrive as strings; `Boolean('false')` is not an answer.\nfunction toBoolean(value: unknown): boolean {\n if (typeof value === 'boolean') return value;\n if (typeof value === 'string') return !FALSE_STRINGS.has(value.trim().toLowerCase());\n if (typeof value === 'number') return value !== 0;\n return value !== null && value !== undefined;\n}\n\nexport { checkboxRenderer };\n","/**\n * Memoised `Intl` formatters, keyed by locale and options. Constructing them\n * per call dominates render time for arrays of many numeric or date fields,\n * and a formatter is a pure function of its key, so one instance is safe to\n * share across the page. Bounded so a language switcher cannot grow it without\n * limit.\n */\n\nconst NUMBER_CACHE = new Map<string, Intl.NumberFormat>();\nconst DATE_CACHE = new Map<string, Intl.DateTimeFormat>();\n\nconst DEFAULT_MAX_ENTRIES = 64;\n\nlet maxEntries = DEFAULT_MAX_ENTRIES;\n\n/** Internal test helper — purges every cached formatter. */\nexport function __resetIntlCache(): void {\n NUMBER_CACHE.clear();\n DATE_CACHE.clear();\n maxEntries = DEFAULT_MAX_ENTRIES;\n}\n\n/** Adjust the LRU bound. Returns the previous value. */\nexport function setIntlCacheLimit(limit: number): number {\n if (!Number.isFinite(limit) || limit < 1) return maxEntries;\n const previous = maxEntries;\n maxEntries = Math.floor(limit);\n trimToLimit(NUMBER_CACHE);\n trimToLimit(DATE_CACHE);\n return previous;\n}\n\n/** Cache occupancy, for tests and dev observability. */\nexport function intlCacheSize(): { readonly numbers: number; readonly dates: number } {\n return { numbers: NUMBER_CACHE.size, dates: DATE_CACHE.size };\n}\n\nexport function getNumberFormat(\n locale: string | undefined,\n options?: Intl.NumberFormatOptions,\n): Intl.NumberFormat {\n const key = buildKey(locale, options);\n const cached = NUMBER_CACHE.get(key);\n if (cached !== undefined) {\n NUMBER_CACHE.delete(key);\n NUMBER_CACHE.set(key, cached);\n return cached;\n }\n const formatter = new Intl.NumberFormat(locale, options);\n NUMBER_CACHE.set(key, formatter);\n trimToLimit(NUMBER_CACHE);\n return formatter;\n}\n\nexport function getDateTimeFormat(\n locale: string | undefined,\n options?: Intl.DateTimeFormatOptions,\n): Intl.DateTimeFormat {\n const key = buildKey(locale, options);\n const cached = DATE_CACHE.get(key);\n if (cached !== undefined) {\n DATE_CACHE.delete(key);\n DATE_CACHE.set(key, cached);\n return cached;\n }\n const formatter = new Intl.DateTimeFormat(locale, options);\n DATE_CACHE.set(key, formatter);\n trimToLimit(DATE_CACHE);\n return formatter;\n}\n\nfunction buildKey(locale: string | undefined, options: unknown): string {\n // Stable key order so equivalent option objects share a slot, and an empty\n // one collapses to the bare-locale key.\n const localePart = locale ?? '';\n if (options === undefined || options === null) return localePart;\n const serialised = stableStringify(options);\n if (serialised === '{}') return localePart;\n return `${localePart}|${serialised}`;\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value);\n if (Array.isArray(value)) {\n return `[${value.map((v) => stableStringify(v)).join(',')}]`;\n }\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record).sort();\n const parts: string[] = [];\n for (const key of keys) {\n const inner = record[key];\n if (inner === undefined) continue;\n parts.push(`${JSON.stringify(key)}:${stableStringify(inner)}`);\n }\n return `{${parts.join(',')}}`;\n}\n\nfunction trimToLimit(map: Map<string, unknown>): void {\n while (map.size > maxEntries) {\n const oldest = map.keys().next().value;\n if (oldest === undefined) break;\n map.delete(oldest);\n }\n}\n","/**\n * `date` renderer. `<time>` gets an ISO `datetime` plus a localised label;\n * date inputs get the value in the visitor's local time zone, because that is\n * what the control displays.\n */\n\nimport { detectInitialLocale } from '@detection/locale';\nimport { getDateTimeFormat } from '@core/intl-cache';\nimport type { FieldRenderer, RenderContext } from '@core/types';\nimport { isEmptyValue, safeStringify } from './utils';\n\nconst dateRenderer: FieldRenderer = {\n name: 'date',\n render(target, value, context) {\n const element = target.element;\n if (isEmptyValue(value)) {\n if (element.tagName === 'INPUT') (element as HTMLInputElement).value = '';\n else {\n element.removeAttribute('datetime');\n element.textContent = '';\n }\n return;\n }\n const raw = typeof value === 'number' ? value : safeStringify(value);\n const date = new Date(raw);\n const valid = !Number.isNaN(date.getTime());\n const fallback = String(raw);\n if (element.tagName === 'INPUT') {\n (element as HTMLInputElement).value = valid\n ? formatForInput((element as HTMLInputElement).type, date)\n : fallback;\n return;\n }\n if (element.tagName === 'TIME') {\n element.setAttribute('datetime', valid ? date.toISOString() : fallback);\n }\n element.textContent = valid ? formatDate(date, context) : fallback;\n },\n};\n\nfunction formatDate(date: Date, context: RenderContext): string {\n const locale = context.locale ?? detectInitialLocale();\n try {\n return getDateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'short' }).format(date);\n } catch {\n return date.toISOString();\n }\n}\n\n/** Value for `<input type=\"date|datetime-local|time\">` in local time; other inputs get the ISO instant. */\nexport function formatForInput(type: string, date: Date): string {\n const day = `${String(date.getFullYear()).padStart(4, '0')}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;\n const clock = `${pad(date.getHours())}:${pad(date.getMinutes())}`;\n if (type === 'date') return day;\n if (type === 'datetime-local') return `${day}T${clock}`;\n if (type === 'time') return clock;\n return date.toISOString();\n}\n\nfunction pad(value: number): string {\n return String(value).padStart(2, '0');\n}\n\nexport { dateRenderer };\n","/** `number` renderer: raw value on inputs, `Intl.NumberFormat` elsewhere. */\n\nimport { detectInitialLocale } from '@detection/locale';\nimport { getNumberFormat } from '@core/intl-cache';\nimport type { FieldRenderer, RenderContext } from '@core/types';\nimport { isEmptyValue, safeStringify } from './utils';\n\nconst numberRenderer: FieldRenderer = {\n name: 'number',\n render(target, value, context) {\n const element = target.element;\n if (isEmptyValue(value)) {\n if (element.tagName === 'INPUT') (element as HTMLInputElement).value = '';\n else element.textContent = '';\n return;\n }\n const num = typeof value === 'number' ? value : Number(safeStringify(value));\n if (Number.isNaN(num)) {\n element.textContent = safeStringify(value);\n return;\n }\n if (element.tagName === 'INPUT') {\n (element as HTMLInputElement).value = String(num);\n return;\n }\n element.textContent = format(num, context);\n },\n};\n\nfunction format(num: number, context: RenderContext): string {\n const locale = context.locale ?? detectInitialLocale();\n try {\n return getNumberFormat(locale).format(num);\n } catch {\n return String(num);\n }\n}\n\nexport { numberRenderer };\n","/**\n * `array` / `blocks` renderer. With `data-payload-array-template` each item\n * is interpolated into the template (`{{key}}`, `{{value}}`, `{{index}}`);\n * without one, items are joined by `data-payload-array-separator`.\n */\n\nimport { sanitizeHtml } from '@security/sanitizer';\nimport { trustedHtml } from '@security/trusted-types';\nimport { interpolateArrayTemplate } from '@core/array-template';\nimport { markNoWriteCallback } from '@core/internal-outcome';\nimport { templateSanitizeOptions } from '@core/template-sanitize';\nimport type { FieldRenderer } from '@core/types';\nimport { isEmptyValue, safeStringify } from './utils';\n\nconst arrayRenderer: FieldRenderer = {\n name: 'array',\n render: /* @__PURE__ */ markNoWriteCallback((target, value) => {\n const element = target.element;\n if (isEmptyValue(value)) {\n element.textContent = '';\n return;\n }\n if (!Array.isArray(value)) return false;\n const template = target.arrayTemplate;\n if (template !== undefined && template.length > 0) {\n const html = renderTemplate(template, value);\n element.innerHTML = trustedHtml(sanitizeHtml(html, templateSanitizeOptions(template)));\n return;\n }\n element.textContent = value.map(safeStringify).join(target.arraySeparator ?? ', ');\n return;\n }),\n};\n\nfunction renderTemplate(template: string, items: readonly unknown[]): string {\n let out = '';\n for (let i = 0; i < items.length; i += 1) {\n out += interpolateArrayTemplate(template, items[i], i, safeStringify);\n }\n return out;\n}\n\nexport { arrayRenderer };\n","/**\n * `structural-array` renderer (`data-payload-structural`): diffs the previous\n * and next item lists and patches the container through the keyed morph\n * (ADR 0008). All diff memory lives in the closure, one per client.\n */\n\nimport { safeConsoleWarn } from '@core/diagnostics';\nimport { markNoWriteCallback } from '@core/internal-outcome';\nimport {\n applyStructuralPatches,\n createStructuralStore,\n KEY_ATTRIBUTE,\n type StructuralStore,\n} from '@core/structural-applier';\nimport { diffArray } from '@schema/diff';\nimport type { FieldRenderer } from '@core/types';\nimport { isEmptyValue } from './utils';\n\ninterface StructuralRenderState {\n readonly values: readonly unknown[];\n readonly template: string;\n readonly domSnapshot: readonly (string | null)[];\n}\n\ntype WarnedCodes = WeakMap<Element, Set<string>>;\n\nexport function createStructuralArrayRenderer(): FieldRenderer {\n const states = new WeakMap<Element, StructuralRenderState>();\n const warnedContainers = new WeakSet<Element>();\n const warnedKeys: WarnedCodes = new WeakMap();\n const store: StructuralStore = createStructuralStore();\n\n return {\n name: 'structural-array',\n render: /* @__PURE__ */ markNoWriteCallback((target, rawValue) => {\n const value = isEmptyValue(rawValue) ? [] : rawValue;\n if (!Array.isArray(value)) return false;\n const container = target.element;\n const template = target.arrayTemplate;\n if (template === undefined || template.length === 0) {\n warnMissingTemplate(warnedContainers, container, target.fieldName);\n return false;\n }\n const previousState = states.get(container);\n const domSnapshot = readDomKeySnapshot(container);\n const previous = previousState?.values ?? valuesFromDomSnapshot(domSnapshot);\n const patches = diffArray(previous, value);\n const forceRender = needsForcedRender(previousState, template, domSnapshot);\n if (patches.length === 0 && !forceRender) {\n states.set(container, { values: value.slice(), template, domSnapshot });\n return false;\n }\n warnAboutKeys(warnedKeys, container, target.fieldName, previousState?.values, value);\n const applied = applyStructuralPatches({\n template,\n container,\n patches,\n nextItems: value,\n store,\n forceRender,\n onDuplicateKey: (owner, key) => {\n warnDuplicateKey(warnedKeys, owner, target.fieldName, key);\n },\n });\n if (applied === null) return false;\n states.set(container, {\n values: value.slice(),\n template,\n domSnapshot: readDomKeySnapshot(container),\n });\n return applied ? undefined : false;\n }),\n };\n}\n\nfunction needsForcedRender(\n previous: StructuralRenderState | undefined,\n template: string,\n domSnapshot: readonly (string | null)[],\n): boolean {\n if (previous === undefined) return true;\n return previous.template !== template || !sameDomKeySnapshot(previous.domSnapshot, domSnapshot);\n}\n\n// SSR markup exists before any in-memory snapshot; its direct-child keys let\n// the first update reconcile instead of appending a second copy.\nfunction readDomKeySnapshot(container: Element): readonly (string | null)[] {\n return Array.from(container.children, (child) => child.getAttribute(KEY_ATTRIBUTE));\n}\n\nfunction valuesFromDomSnapshot(snapshot: readonly (string | null)[]): readonly unknown[] {\n return snapshot.map((key, position) =>\n key === null ? { __payloadDomPosition: position } : { id: key },\n );\n}\n\nfunction sameDomKeySnapshot(\n previous: readonly (string | null)[],\n current: readonly (string | null)[],\n): boolean {\n if (previous.length !== current.length) return false;\n return previous.every((key, index) => key === current[index]);\n}\n\nfunction warnMissingTemplate(\n warnedContainers: WeakSet<Element>,\n container: Element,\n fieldName: string,\n): void {\n if (warnedContainers.has(container)) return;\n warnedContainers.add(container);\n safeConsoleWarn(\n `[live-preview] LP0403: Skipping structural update for \"${fieldName}\": ` +\n `<${container.tagName.toLowerCase()} data-payload-structural> needs ` +\n `data-payload-array-template (for example \"<li>{{label}}</li>\").`,\n );\n}\n\nfunction itemKey(value: unknown): string | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const id = (value as Record<string, unknown>)['id'];\n return typeof id === 'string' || typeof id === 'number' ? String(id) : undefined;\n}\n\n/** Key problems degrade the morph, they do not break it; each is announced once per container (ADR 0008 §5). */\nfunction warnAboutKeys(\n warned: WarnedCodes,\n container: Element,\n fieldName: string,\n previous: readonly unknown[] | undefined,\n next: readonly unknown[],\n): void {\n const nextKeys = next.map(itemKey);\n const seen = new Set<string>();\n const duplicate = nextKeys.find((key) => {\n if (key === undefined) return false;\n if (seen.has(key)) return true;\n seen.add(key);\n return false;\n });\n if (duplicate !== undefined) warnDuplicateKey(warned, container, fieldName, duplicate);\n if (nextKeys.some((key) => key === undefined)) {\n warnOnce(\n warned,\n container,\n 'LP0404',\n `LP0404: an item of \"${fieldName}\" has no id and pairs by ` +\n 'position, so an insert re-renders every row after it. Give items a stable id.',\n );\n }\n if (previous?.length === next.length && next.length > 1) {\n const previousKeys = new Set(previous.map(itemKey).filter((key) => key !== undefined));\n const stable = nextKeys.some((key) => key !== undefined && previousKeys.has(key));\n if (previousKeys.size > 0 && !stable) {\n warnOnce(\n warned,\n container,\n 'LP0406',\n `LP0406: every key of \"${fieldName}\" changed at once; the ` +\n 'source generates ids per message, so no item can be retained across updates.',\n );\n }\n }\n}\n\n// Reached from the pre-diff check and from the morph's nested-slot check; one site, one message.\nfunction warnDuplicateKey(\n warned: WarnedCodes,\n owner: Element,\n fieldName: string,\n key: string,\n): void {\n warnOnce(\n warned,\n owner,\n 'LP0405',\n `LP0405: two items of \"${fieldName}\" share the key \"${key}\"; later ones pair by ` +\n 'position. Make `id` unique per item.',\n );\n}\n\nfunction warnOnce(warned: WarnedCodes, container: Element, code: string, message: string): void {\n let codes = warned.get(container);\n if (codes === undefined) {\n codes = new Set();\n warned.set(container, codes);\n }\n if (codes.has(code)) return;\n codes.add(code);\n safeConsoleWarn(`[live-preview] ${message}`);\n}\n","/**\n * Explicit renderer overrides, layered above the defaults each time a map is\n * built. The registry never retains the defaults, so stateful ones can be\n * recreated per client.\n */\n\nimport type { FieldRenderer, RendererKey } from '@core/types';\n\nconst builtinRenderers = new Map<RendererKey, FieldRenderer>();\n\nexport function buildBuiltinRenderers(\n defaults: readonly FieldRenderer[] = [],\n): Readonly<Record<string, FieldRenderer>> {\n const out: Record<string, FieldRenderer> = {};\n for (const renderer of defaults) out[renderer.name] = renderer;\n for (const [type, renderer] of builtinRenderers) out[type] = renderer;\n return Object.freeze(out);\n}\n\n/** Register or replace an override for maps built afterwards. */\nexport function registerBuiltinRenderer(renderer: FieldRenderer): void {\n builtinRenderers.set(renderer.name, renderer);\n}\n\n/** Test-only: clear the overrides. */\nexport function __resetBuiltinRenderersForTests(): void {\n builtinRenderers.clear();\n}\n","/** Built-in field renderers, assembled as values so `sideEffects: false` bundlers keep them all. */\n\nimport type { FieldRenderer } from '@core/types';\nimport { createTextRenderer } from './text';\nimport { richTextRenderer } from './rich-text';\nimport { htmlRenderer } from './html';\nimport { urlRenderer } from './url';\nimport { emailRenderer } from './email';\nimport { imageRenderer } from './image';\nimport { uploadRenderer } from './upload';\nimport { relationshipRenderer } from './relationship';\nimport { selectRenderer } from './select';\nimport { checkboxRenderer } from './checkbox';\nimport { dateRenderer } from './date';\nimport { numberRenderer } from './number';\nimport { arrayRenderer } from './array';\nimport { createStructuralArrayRenderer } from './structural-array';\nimport {\n buildBuiltinRenderers as buildRegistry,\n registerBuiltinRenderer,\n __resetBuiltinRenderersForTests,\n} from './registry';\n\n/** One renderer map per client; the stateful text and structural renderers are created fresh each call. */\nexport function buildBuiltinRenderers(): Readonly<Record<string, FieldRenderer>> {\n // Built per call: a module-level table would pin every renderer into any\n // consumer importing an unrelated symbol from the root barrel.\n const stateless: readonly FieldRenderer[] = [\n richTextRenderer,\n htmlRenderer,\n urlRenderer,\n emailRenderer,\n imageRenderer,\n uploadRenderer,\n relationshipRenderer,\n selectRenderer,\n { ...selectRenderer, name: 'radio' },\n checkboxRenderer,\n dateRenderer,\n numberRenderer,\n arrayRenderer,\n { ...arrayRenderer, name: 'blocks' },\n ];\n\n return buildRegistry([\n createTextRenderer('text'),\n createTextRenderer('textarea'),\n ...stateless,\n createStructuralArrayRenderer(),\n ]);\n}\n\nexport { registerBuiltinRenderer, __resetBuiltinRenderersForTests };\nexport type { PayloadMedia, PayloadRelationship } from './types';\n","/** Drops `undefined`-valued keys, so a literal built from optional inputs satisfies `exactOptionalPropertyTypes`. */\n\nexport type DefinedOnly<T> = { readonly [K in keyof T]-?: Exclude<T[K], undefined> };\n\nexport function definedOnly<T extends object>(source: T): DefinedOnly<T> {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(source)) {\n if (value !== undefined) result[key] = value;\n }\n return result as DefinedOnly<T>;\n}\n","/**\n * The two defaults profiles, row by row. 2.0 ships `v2`; `defaults: 'v1'` opts\n * back into the 1.x table for a staged migration. Each row belongs to exactly\n * one side — the adapter's request decision or the browser runtime — and a\n * test asserts the profile assigns every readiness row that has an option, so\n * a row added later cannot be forgotten. See ADR 0007.\n */\n\n/** `'v2'` is the 2.0 default; `'v1'` is the 1.x table. */\nexport type DefaultsProfile = 'v1' | 'v2';\n\n/** How the runtime decides which windows may post updates. */\nexport type EventSourcePolicy = 'any' | 'parent-or-opener';\n\n/** Readiness rows that are options, keyed by the option they set. */\nexport const READINESS_ROWS = Object.freeze({\n strict: 'production response changes require an authorized context',\n previewSignals: 'query-only intent signal',\n disableReferrerDetection: 'referrer trust off outside local dev',\n eventSourcePolicy: 'messages must come from parent/opener',\n skipUnchanged: 'skip unchanged bindings by default',\n sanitizerPolicy: 'hardened sanitizer id/data-* policy',\n} as const);\n\n/** Options an adapter's request decision reads from the profile. */\nexport interface AdapterProfileDefaults {\n readonly strict: boolean;\n readonly previewSignals: readonly ('query' | 'fetch-dest' | 'referer')[];\n}\n\n/** Options the browser runtime reads from the profile (through the inline configuration). */\nexport interface RuntimeProfileDefaults {\n readonly disableReferrerDetection: boolean;\n readonly eventSourcePolicy: EventSourcePolicy;\n readonly skipUnchanged: boolean;\n readonly sanitizerPolicy: 'compat' | 'strict';\n}\n\nexport const V2_ADAPTER_DEFAULTS: AdapterProfileDefaults = Object.freeze({\n strict: true,\n previewSignals: Object.freeze(['query'] as const),\n});\n\nexport const V2_RUNTIME_DEFAULTS: RuntimeProfileDefaults = Object.freeze({\n disableReferrerDetection: true,\n eventSourcePolicy: 'parent-or-opener',\n skipUnchanged: true,\n sanitizerPolicy: 'strict',\n});\n\n/** The 1.x table, spelled out so the profiles compare row by row. */\nexport const V1_ADAPTER_DEFAULTS: AdapterProfileDefaults = Object.freeze({\n strict: false,\n previewSignals: Object.freeze(['query', 'fetch-dest', 'referer'] as const),\n});\n\nexport const V1_RUNTIME_DEFAULTS: RuntimeProfileDefaults = Object.freeze({\n disableReferrerDetection: false,\n eventSourcePolicy: 'any',\n skipUnchanged: false,\n sanitizerPolicy: 'compat',\n});\n\n/** Only an explicit `'v1'` opts out; everything else gets the hardened rows. */\nexport function adapterDefaultsFor(profile: DefaultsProfile | undefined): AdapterProfileDefaults {\n return profile === 'v1' ? V1_ADAPTER_DEFAULTS : V2_ADAPTER_DEFAULTS;\n}\n\nexport function runtimeDefaultsFor(profile: DefaultsProfile | undefined): RuntimeProfileDefaults {\n return profile === 'v1' ? V1_RUNTIME_DEFAULTS : V2_RUNTIME_DEFAULTS;\n}\n","/**\n * `LivePreviewClient`: a `LivePreviewRuntime` with its own emitter, plugin\n * manager and renderer registry. A page that only needs a working preview uses\n * `generateInlineScript()` instead.\n */\n\nimport { LivePreviewRuntime, type RuntimeOptions } from '@core/lifecycle';\nimport type { LivePreviewInspection } from '@core/inspection/types';\nimport type { CachedElement, RendererKey } from '@core/types';\nimport { EventEmitter } from '@events/emitter';\nimport { OriginDetector } from '@detection/origin';\nimport { setSanitizerPolicy } from '@security/sanitizer';\nimport { PluginManager } from '@plugins/manager';\nimport { RendererRegistry } from '@plugins/renderer-registry';\nimport type { LivePreviewPlugin } from '@plugins/types';\nimport { isDevMode, isInPreviewContext } from '@detection/environment';\nimport { buildBuiltinRenderers } from '@field-types/index';\nimport { definedOnly } from '@/types/defined-only';\nimport { withProfileDefaults, type LivePreviewClientConfig } from './config';\nimport { noopDiagnostic, safeConsoleDebug } from '@core/diagnostics';\n\n/** `T` with every property optional and `undefined`-able, for literals built from optional inputs. */\ntype Loose<T> = { readonly [K in keyof T]?: T[K] | undefined };\n\nfunction invert(value: boolean | undefined): boolean | undefined {\n return value === undefined ? undefined : !value;\n}\n\nexport class LivePreviewClient {\n readonly #emitter = new EventEmitter();\n readonly #detector: OriginDetector;\n readonly #rendererRegistry: RendererRegistry;\n readonly #runtime: LivePreviewRuntime;\n readonly #plugins: PluginManager;\n readonly #log: (...args: unknown[]) => void;\n #started = false;\n #destroyed = false;\n #tornDown = false;\n #destroyPromise: Promise<void> | null = null;\n\n constructor(rawConfig: LivePreviewClientConfig = {}) {\n const config = withProfileDefaults(rawConfig);\n const serverURL = config.serverURL ?? '';\n if (rawConfig.defaults !== 'v1' && serverURL !== '' && config.mergeDepth === undefined) {\n throw new Error(\n 'payload-live-preview: `serverURL` needs an explicit `mergeDepth` under the 2.0 defaults — ' +\n \"choose the population depth deliberately (0 for none), or pass `defaults: 'v1'` to keep \" +\n 'the 1.x default of 1 while migrating (ADR 0007, entry 10).',\n );\n }\n if (config.sanitizerPolicy !== undefined) setSanitizerPolicy(config.sanitizerPolicy);\n const debug = config.debug ?? isDevMode();\n this.#log = debug\n ? (...args): void => {\n safeConsoleDebug('[live-preview]', ...args);\n }\n : noopDiagnostic;\n\n this.#detector = new OriginDetector(\n definedOnly({\n additionalOrigins: config.allowedOrigins,\n enableReferrerDetection: invert(config.disableReferrerDetection),\n enableLocalhostMatching: invert(config.disableLocalhostMatching),\n }),\n );\n\n if (this.#detector.isProductionUnconfigured) {\n this.#log('no trusted origin could be detected — set allowedOrigins');\n }\n\n this.#rendererRegistry = new RendererRegistry(buildBuiltinRenderers());\n\n this.#plugins = new PluginManager({\n events: this.#emitter,\n config: Object.freeze({ ...config }),\n registerFieldRenderer: (renderer) => this.#rendererRegistry.register(renderer),\n onTransformError: (error) => {\n void this.#emitter.emit('error', { error, context: 'transform', code: 'LP0602' });\n },\n log: this.#log,\n });\n\n this.#runtime = new LivePreviewRuntime(\n definedOnly({\n root: config.root,\n renderers: this.#rendererRegistry.renderers,\n resolveRenderer: (fieldType: RendererKey, target: CachedElement) =>\n config.resolveRenderer?.(fieldType, target) ?? this.#rendererRegistry.resolve(fieldType),\n renderRichText: config.renderRichText,\n transformValue: (\n fieldName: string,\n value: unknown,\n context: { readonly element: Element; readonly allFields: Record<string, unknown> },\n isCurrent?: () => boolean,\n ) => this.#plugins.applyTransforms(fieldName, value, context, isCurrent),\n originMatcher: (origin: string) => this.#detector.matches(origin),\n // Read per handshake, not once: after a lock, a bfcache restore must\n // re-broadcast to the locked origin alone, not every pre-lock candidate.\n readyTargets: () => this.#detector.enumerate(),\n emitter: this.#emitter,\n dataMerge:\n serverURL === ''\n ? undefined\n : definedOnly({\n serverURL,\n apiRoute: config.apiRoute,\n depth: config.mergeDepth,\n fetchFn: config.mergeFetch,\n }),\n debounceMs: config.debounceMs,\n heartbeatMs: config.heartbeatMs,\n intersectionRootMargin: config.intersectionRootMargin,\n scopeBindingsByOwner: config.scopeBindingsByOwner,\n skipUnchanged: config.skipUnchanged,\n revealEditedField: config.revealEditedField,\n eventSourcePolicy: config.eventSourcePolicy,\n dependencies: config.dependencies,\n strategies: config.strategies,\n disableVisibilityGate: config.disableVisibilityGate,\n visibilityGateThreshold: config.visibilityGateThreshold,\n enableA11y: config.enableA11y,\n a11yLocale: config.a11yLocale,\n onHeartbeatTimeout: () => {\n this.#detector.unlockOrigin();\n },\n lockedOrigin: () => this.#detector.lockedOrigin,\n validateToken: config.validateToken,\n log: this.#log,\n } satisfies Loose<RuntimeOptions>),\n );\n\n this.#emitter.on('connect', (e) => {\n this.#detector.lockOrigin(e.origin);\n });\n\n if (config.autoStart !== false) {\n this.start();\n }\n }\n\n /**\n * Start the runtime: `true` while eligible and started or scheduled for DOM\n * readiness, `false` once destroyed or outside a preview context.\n */\n start(): boolean {\n if (this.#destroyed) return false;\n if (this.#started) {\n // A deferred DOM-ready startup can fail after this returned and roll\n // itself back; this call retries it.\n this.#runtime.start();\n return true;\n }\n if (!isInPreviewContext()) return false;\n const started = this.#runtime.start();\n if (started) this.#started = true;\n return started;\n }\n\n /**\n * Release the message ingress, keeping plugins and renderers, for `pagehide`:\n * a bfcache restore re-runs no script, so an attached client would return\n * bound to a frozen page. `false` when nothing was running.\n */\n suspend(): boolean {\n if (this.#destroyed || !this.#started) return false;\n return this.#runtime.suspend();\n }\n\n /** Reacquire after `suspend()`: the same path as `start()`, because a restored document needs the same rebuild. */\n resume(): boolean {\n if (this.#destroyed || !this.#started) return false;\n return this.#runtime.start();\n }\n\n /** Stop the runtime and tear down every plugin. Idempotent; concurrent callers share one promise. */\n destroy(): Promise<void> {\n if (this.#destroyPromise !== null) return this.#destroyPromise;\n this.#destroyed = true;\n let resolveDestroy!: () => void;\n let rejectDestroy!: (reason: unknown) => void;\n const inFlight = new Promise<void>((resolve, reject) => {\n resolveDestroy = resolve;\n rejectDestroy = reject;\n });\n // Published before the teardown: a `destroy` handler calling destroy()\n // re-entrantly must get this same promise.\n this.#destroyPromise = inFlight;\n const finish = (): void => {\n this.#emitter.removeAllListeners();\n this.#tornDown = true;\n };\n try {\n this.#runtime.destroy();\n void this.#plugins.destroyAll().finally(finish).then(resolveDestroy, rejectDestroy);\n } catch (error) {\n finish();\n rejectDestroy(error);\n }\n return inFlight;\n }\n\n async use(plugin: LivePreviewPlugin): Promise<void> {\n if (this.#destroyed) throw new Error('LivePreviewClient: already destroyed');\n await this.#plugins.register(plugin);\n }\n\n /** Unregister a plugin and release everything its registration owned. Still allowed from a destroy hook during teardown. */\n async unuse(name: string): Promise<void> {\n if (this.#tornDown) throw new Error('LivePreviewClient: already destroyed');\n await this.#plugins.unregister(name);\n }\n\n refreshCache(): void {\n this.#runtime.refreshCache();\n }\n\n get events(): EventEmitter {\n return this.#emitter;\n }\n\n /** Names of the registered plugins. */\n get plugins(): readonly string[] {\n return this.#plugins.list();\n }\n\n get status(): 'disconnected' | 'connecting' | 'connected' {\n return this.#runtime.status;\n }\n\n /**\n * Point-in-time read of runtime state, no I/O: `bindings.orphanFields` when a\n * field refuses to update, `scheduler.deferred` when updates stop below the fold.\n */\n inspect(): LivePreviewInspection {\n return { ...this.#runtime.inspect(), plugins: this.#plugins.snapshot() };\n }\n\n /** Number of accepted updates so far. */\n get updateCount(): number {\n return this.#runtime.updateCount;\n }\n\n /** `true` once `destroy()` has been called. */\n get destroyed(): boolean {\n return this.#destroyed;\n }\n}\n\n/** A started client, or `null` when the page is not a preview context. */\nexport function initLivePreview(config: LivePreviewClientConfig = {}): LivePreviewClient | null {\n const client = new LivePreviewClient({ ...config, autoStart: false });\n return client.start() ? client : null;\n}\n\nexport type { LivePreviewClientConfig } from './config';\n","/**\n * `LivePreviewClient` configuration. Defaults are the 2.0 rows; `defaults: 'v1'`\n * restores the 1.x values named per option (ADR 0007).\n */\n\nimport type { CachedElement, FieldRenderer, RendererKey, RichTextRenderer } from '@core/types';\nimport type { StrategyHandlers } from '@core/strategies';\nimport {\n runtimeDefaultsFor,\n type DefaultsProfile,\n type EventSourcePolicy,\n} from '@core/defaults-profile';\n\nexport interface LivePreviewClientConfig {\n /** Explicit trusted admin origins. */\n readonly allowedOrigins?: readonly string[];\n /** Payload origin; every update is then re-fetched through the REST API so relations arrive populated. Requires `mergeDepth`. */\n readonly serverURL?: string;\n /** REST route prefix used with `serverURL`. Default `/api`. */\n readonly apiRoute?: string;\n /** Population depth used with `serverURL`. Required with it; `defaults: 'v1'` falls back to `1`. */\n readonly mergeDepth?: number;\n /** Custom fetch for the `serverURL` merge request: attach auth headers or route through a proxy. */\n readonly mergeFetch?: typeof fetch;\n /** Verbose console output. Defaults to dev-mode detection. */\n readonly debug?: boolean;\n /** Debounce window for incoming updates. Default 50 ms. */\n readonly debounceMs?: number;\n /** Heartbeat timeout in ms; `0` disables it (default), because the admin posts only on edits. */\n readonly heartbeatMs?: number;\n /** IntersectionObserver `rootMargin`. Default `200px`. */\n readonly intersectionRootMargin?: string;\n /** Update only bindings under a matching `data-payload-owner`; an unowned binding is then never updated. Default `false`. */\n readonly scopeBindingsByOwner?: boolean;\n /** Skip a binding whose value did not change. Default `true`; `defaults: 'v1'` sets `false`. */\n readonly skipUnchanged?: boolean;\n /** Scroll the preview to the field being edited when its value changes. Default `false`. */\n readonly revealEditedField?: boolean;\n /** Fields whose change re-applies other bindings regardless of their own value: `{ price: ['priceLabel'] }`. Used with `skipUnchanged`. */\n readonly dependencies?: Readonly<Record<string, readonly string[]>>;\n /** Strategy handlers beyond patching; `createFragmentStrategy()` from `payload-live-preview/fragment` builds one. */\n readonly strategies?: StrategyHandlers;\n /** Apply every update regardless of visibility. Default `false`. */\n readonly disableVisibilityGate?: boolean;\n /** Cache size above which off-screen updates wait for intersection. Default `50`. */\n readonly visibilityGateThreshold?: number;\n /** Mount an `aria-live` region for connections, applied updates and heartbeat disconnects. Default `true`. */\n readonly enableA11y?: boolean;\n /** Locale of the announcement strings. Defaults to the detected locale. */\n readonly a11yLocale?: string;\n /** Document root. Default `document`. */\n readonly root?: Document | Element;\n /** Renderer resolution ahead of the registry; return `undefined` to fall through. */\n readonly resolveRenderer?: (\n fieldType: RendererKey,\n target: CachedElement,\n ) => FieldRenderer | undefined;\n /** The project's rich-text renderer, shared with SSR. Its output is sanitized. */\n readonly renderRichText?: RichTextRenderer;\n /** Ignore `document.referrer` as an origin source. Default `true`; `defaults: 'v1'` sets `false`. */\n readonly disableReferrerDetection?: boolean;\n /** Disable the dev-mode localhost matcher. Default `false`. */\n readonly disableLocalhostMatching?: boolean;\n /** Which windows may post updates. Default `'parent-or-opener'`; `defaults: 'v1'` sets `'any'`. */\n readonly eventSourcePolicy?: EventSourcePolicy;\n /** Sanitizer policy for rich text and HTML writes. Default `'strict'`; `defaults: 'v1'` sets `'compat'`. */\n readonly sanitizerPolicy?: 'compat' | 'strict';\n /** `'v2'` (default) is the 2.0 table; `'v1'` restores every 1.x row at once. Explicit options win. */\n readonly defaults?: DefaultsProfile;\n /** Start the runtime in the constructor. Default `true`. */\n readonly autoStart?: boolean;\n /** Preview-token validator; every update must then carry a `previewToken` it approves. Stock Payload sends none. */\n readonly validateToken?: (\n token: string | undefined,\n origin: string,\n ) => boolean | Promise<boolean>;\n}\n\n/** The configuration with the `defaults` profile applied: explicit options win, `'v1'` changes nothing. */\nexport function withProfileDefaults(config: LivePreviewClientConfig): LivePreviewClientConfig {\n if (config.defaults === 'v1') return config;\n const rows = runtimeDefaultsFor(config.defaults);\n return {\n ...config,\n skipUnchanged: config.skipUnchanged ?? rows.skipUnchanged,\n disableReferrerDetection: config.disableReferrerDetection ?? rows.disableReferrerDetection,\n eventSourcePolicy: config.eventSourcePolicy ?? rows.eventSourcePolicy,\n sanitizerPolicy: config.sanitizerPolicy ?? rows.sanitizerPolicy,\n };\n}\n","/**\n * Admin-side reporter for \"reveal the edited section\": it names the field the\n * editor's cursor is in so the preview scrolls there without a keystroke.\n */\n\n/** The preview window (usually `iframe.contentWindow`) messages are posted to. */\nexport interface FocusReportTarget {\n postMessage: (message: unknown, targetOrigin: string) => void;\n}\n\nexport interface PreviewFocusMessage {\n readonly type: 'payload-live-preview-focus';\n readonly field: string;\n}\n\n/** Post one focus report. `targetOrigin` must be the preview's exact origin, never `'*'`. */\nexport function reportPreviewFocus(\n target: FocusReportTarget,\n field: string,\n targetOrigin: string,\n): void {\n if (field.length === 0) return;\n const message: PreviewFocusMessage = { type: 'payload-live-preview-focus', field };\n target.postMessage(message, targetOrigin);\n}\n\n/** A reporter bound to a preview window and origin; `resolveTarget` runs per report, so a re-created iframe is addressed freshly. */\nexport function createPreviewFocusReporter(\n resolveTarget: () => FocusReportTarget | null | undefined,\n targetOrigin: string,\n): (field: string) => void {\n return (field: string): void => {\n const target = resolveTarget();\n if (target === null || target === undefined) return;\n reportPreviewFocus(target, field, targetOrigin);\n };\n}\n","/**\n * Binds the document lifecycle the runtime cannot see: a back/forward-cache\n * restore re-runs no scripts, so a client that stayed attached comes back\n * bound to a frozen document and quietly stops updating; a soft navigation\n * replaces the content the binding cache describes. Both are silent failures.\n */\n\n/** The part of the client this owner drives. */\nexport interface NavigationLifecycleTarget {\n suspend(): boolean;\n resume(): boolean;\n refreshCache(): void;\n}\n\nexport interface NavigationLifecycleOptions {\n /** Where `pagehide`/`pageshow` fire; they exist only on the window. Defaults to `window`. */\n readonly windowTarget?: EventTarget;\n /** Event target for soft-navigation events. Defaults to `document`. */\n readonly documentTarget?: EventTarget;\n /**\n * Events after which the DOM was replaced and the cache must be rebuilt, e.g.\n * `astro:page-load`. Empty by default: only the host knows which its router fires.\n */\n readonly softNavigationEvents?: readonly string[];\n}\n\n/** Returns an unbind function; calling it twice is harmless. */\nexport function bindNavigationLifecycle(\n target: NavigationLifecycleTarget,\n options: NavigationLifecycleOptions = {},\n): () => void {\n const windowTarget = options.windowTarget ?? (globalThis as { window?: EventTarget }).window;\n const documentTarget =\n options.documentTarget ?? (globalThis as { document?: EventTarget }).document;\n const softEvents = options.softNavigationEvents ?? [];\n\n const onPageHide = (): void => {\n target.suspend();\n };\n const onPageShow = (event: Event): void => {\n // Only a persisted restore needs reacquiring; an ordinary load already started.\n if ((event as Event & { readonly persisted?: boolean }).persisted === true) {\n target.resume();\n }\n };\n const onSoftNavigation = (): void => {\n target.refreshCache();\n };\n\n windowTarget?.addEventListener('pagehide', onPageHide);\n windowTarget?.addEventListener('pageshow', onPageShow);\n for (const name of softEvents) documentTarget?.addEventListener(name, onSoftNavigation);\n\n let unbound = false;\n return (): void => {\n if (unbound) return;\n unbound = true;\n windowTarget?.removeEventListener('pagehide', onPageHide);\n windowTarget?.removeEventListener('pageshow', onPageShow);\n for (const name of softEvents) documentTarget?.removeEventListener(name, onSoftNavigation);\n };\n}\n","/**\n * Every diagnostic code the runtime and tools emit, so a consumer can branch\n * on `e.code` instead of matching message text. A code is never reused for a\n * different meaning; a retired one stays reserved.\n *\n * Browser-side reporting sites write the literal (`code: 'LP0603'`) rather than\n * reading it from this record: the frozen table would then ship in the inline\n * runtime for the sake of six characters. Server-side tools may import it.\n */\n\n/**\n * Every diagnostic code the runtime can report, by name.\n *\n * ```ts\n * client.events.on('error', (e) => {\n * if (e.code === DIAGNOSTIC_CODES.TransformThrew) reportToSentry(e.error);\n * });\n * ```\n */\nexport const DIAGNOSTIC_CODES = Object.freeze({\n /** No trusted origin configured in production; nothing will be accepted. */\n NoTrustedOrigin: 'LP0101',\n /** Origin trust rests on `document.referrer`, so any framing site is trusted. */\n ReferrerOnlyTrust: 'LP0102',\n /** A plugin declares a runtime range this runtime does not satisfy; it was refused. */\n PluginIncompatible: 'LP0103',\n\n /** An update named a field with no binding anchor on the page. */\n OrphanField: 'LP0201',\n /** Owner scoping is on and the update names no document it could belong to. */\n UnattributableUpdate: 'LP0202',\n\n /** The visibility gate held offscreen writes back until they scroll into view. */\n VisibilityGateDeferred: 'LP0301',\n\n /** A value was refused because the attribute or the value itself is unsafe. */\n UnsafeAttributeWrite: 'LP0401',\n /** A text element has structured children, so replacing its text was skipped. */\n TextTargetHasChildren: 'LP0402',\n /** A structural container has no array template, so the update was skipped. */\n MissingArrayTemplate: 'LP0403',\n /** A structural item has no `id`; it pairs positionally, so an insert re-renders every row after it. */\n StructuralItemUnkeyed: 'LP0404',\n /** Two structural items share a key; later ones pair positionally. */\n StructuralDuplicateKey: 'LP0405',\n /** Every structural key changed while the length did not; the source generates keys per message. */\n StructuralUnstableKeys: 'LP0406',\n /** A binding asks for a delivery strategy this release does not have; it is left unchanged. */\n UnsupportedStrategy: 'LP0407',\n\n /** A message was rejected before it reached the update pipeline. */\n MessageRejected: 'LP0501',\n /** A preview token was rejected. */\n TokenRejected: 'LP0502',\n\n /** A consumer event handler threw. */\n HandlerThrew: 'LP0601',\n /** A consumer transform threw; the original value was kept. */\n TransformThrew: 'LP0602',\n /** A renderer threw while writing a value. */\n RendererThrew: 'LP0603',\n // LP0604 is reserved and unassigned; codes are never reused or renumbered.\n /** Runtime startup failed. */\n StartupFailed: 'LP0605',\n /** Sending the ready handshake failed. */\n ReadyFailed: 'LP0606',\n\n /** The audit found no runtime in a response that carried preview intent. */\n AuditRuntimeMissing: 'LP0701',\n /** The preview response declares no `frame-ancestors`. */\n AuditNoFrameAncestors: 'LP0702',\n /** `X-Frame-Options` forbids framing, which no CSP can undo. */\n AuditFrameOptionsBlocks: 'LP0703',\n /** Binding attributes are served to anonymous visitors. */\n AuditBindingsExposed: 'LP0704',\n /** More bindings than the default visibility gate will write eagerly. */\n AuditGateThresholdExceeded: 'LP0705',\n /** Owner markers exist, but some bindings are outside all of them. */\n AuditUnownedBindings: 'LP0706',\n /** The preview response carries no bindings at all. */\n AuditNoBindings: 'LP0707',\n /** The URL did not return an HTML page, so nothing else can be judged. */\n AuditNotAPage: 'LP0708',\n /** A fragment request failed (network, timeout, server error); the boundary was patched instead. */\n FragmentRequestFailed: 'LP0801',\n /** The fragment response had the wrong content type or shape; the boundary was patched instead. */\n FragmentResponseInvalid: 'LP0802',\n /** The fragment endpoint refused the preview (not authorized); the boundary was patched instead. */\n FragmentUnauthorized: 'LP0803',\n /** A fragment response arrived for a revision that was already superseded and was discarded. */\n FragmentSuperseded: 'LP0804',\n /** A route refresh was requested again for the same revision; the loop guard stopped it. */\n RouteRefreshLoop: 'LP0805',\n /** A boundary asks for the fragment strategy but no fragment handler is configured; it is patched. */\n FragmentStrategyUnavailable: 'LP0806',\n /** A readiness row is not yet at its 2.0 value; `pll doctor --v2` reports it. */\n V2ReadinessGap: 'LP0709',\n /** The preview runtime is served to anonymous visitors, not only inside the admin frame. */\n RuntimeOnPublicPage: 'LP0710',\n} as const);\n\n/** A diagnostic code, as it appears in log output and on the `error` event. */\nexport type DiagnosticCode = (typeof DIAGNOSTIC_CODES)[keyof typeof DIAGNOSTIC_CODES];\n","// Auto-generated by scripts/build-runtime.ts — do not edit.\nexport interface RuntimeBuildInfo { readonly generatedAt: string; readonly size: number }\nexport const RUNTIME_SOURCE: string = \"(()=>{function e(e){return(\\\"object\\\"==typeof e&&null!==e||\\\"function\\\"==typeof e)&&\\\"function\\\"==typeof e.then&&(Promise.resolve(e).catch(()=>{}),!0)}function t(t){return(...n)=>{try{e(t(...n))}catch{}}}function n(){}function i(){return function(){if(typeof document>\\\"u\\\")return;let e=document.documentElement.getAttribute(\\\"lang\\\");return null===e||0===e.length?void 0:e}()??function(){if(typeof navigator>\\\"u\\\")return;let e=navigator.language;return\\\"string\\\"==typeof e&&e.length>0?e:void 0}()??\\\"en\\\"}function r(e){null!==e.timer&&(clearTimeout(e.timer),e.timer=null),e.messageNode?.remove(),e.messageNode=null}function l(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=o(n);e&&t.push(e)}return t}function o(e){if(\\\"object\\\"!=typeof e||null===e)return;let t=e,n=t.name,i=t.type;if(\\\"string\\\"!=typeof n||0===n.length||\\\"string\\\"!=typeof i||0===i.length)return;let r=l(t.fields),o=function(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(\\\"object\\\"!=typeof n||null===n)continue;let e=n,i=e.slug;if(\\\"string\\\"!=typeof i||0===i.length)continue;let r=l(e.fields);t.push({...e,slug:i,fields:r})}return t}(t.blocks),a={...t,name:n,type:i};return r.length>0?a.fields=r:delete a.fields,o.length>0?a.blocks=o:delete a.blocks,a}function a(e,t=\\\"\\\"){let n=new Map;return s(e,t,n),n}function s(e,t,n){for(let i of e){if(Dt.has(i.type)){i.fields&&s(i.fields,t,n);continue}let e=\\\"\\\"===t?i.name:`${t}.${i.name}`;if(n.set(e,i),\\\"group\\\"===i.type)i.fields&&s(i.fields,e,n);else if(\\\"array\\\"===i.type&&i.fields)s(i.fields,`${e}.*`,n);else if(\\\"blocks\\\"===i.type&&i.blocks)for(let t of i.blocks)s(t.fields,`${e}.*.${t.slug}`,n)}}function u(e){if(\\\"object\\\"!=typeof e||null===e)return;let t=e.id;return\\\"string\\\"==typeof t||\\\"number\\\"==typeof t?t:void 0}function d(e){if(\\\"object\\\"!=typeof e||null===e)return;let t=e.blockType;return\\\"string\\\"==typeof t?t:void 0}function c(e,t){return t.every(e=>void 0!==u(e))?function(e,t){let n=[],i=new Map;for(let t=0;t<e.length;t+=1){let n=u(e[t]);void 0!==n&&i.set(n,t)}let r=new Set;for(let l=0;l<t.length;l+=1){let o=t[l],a=u(o);if(void 0===a){n.push({kind:\\\"insert\\\",index:l,value:o});continue}let s=i.get(a);if(void 0===s){n.push({kind:\\\"insert\\\",index:l,value:o});continue}r.add(s);let c=e[s];d(c)===d(o)?(s!==l&&n.push({kind:\\\"move\\\",from:s,to:l,value:o}),h(c,o)||n.push({kind:\\\"update\\\",index:l,value:o})):n.push({kind:\\\"replace\\\",index:l,oldValue:c,value:o})}for(let t=0;t<e.length;t+=1)r.has(t)||n.push({kind:\\\"remove\\\",index:t,value:e[t]});return n}(e,t):function(e,t){let n=[],i=Math.min(e.length,t.length);for(let r=0;r<i;r+=1)h(e[r],t[r])||n.push({kind:\\\"update\\\",index:r,value:t[r]});if(t.length>e.length)for(let i=e.length;i<t.length;i+=1)n.push({kind:\\\"insert\\\",index:i,value:t[i]});if(e.length>t.length)for(let i=t.length;i<e.length;i+=1)n.push({kind:\\\"remove\\\",index:i,value:e[i]});return n}(e,t)}function h(e,t){if(Object.is(e,t))return!0;if(\\\"object\\\"!=typeof e||\\\"object\\\"!=typeof t||null===e||null===t)return!1;let n=e,i=t,r=Object.keys(n),l=Object.keys(i);if(r.length!==l.length)return!1;for(let e of r)if(!Object.is(n[e],i[e]))return!1;return!0}function f(e){if(\\\"string\\\"!=typeof e||0===e.length)return!1;let t=e.trim().replace(Gt,\\\"\\\");if(0===t.length||_t.test(t))return!1;if(t.startsWith(\\\"#\\\")||t.startsWith(\\\"?\\\")||zt.test(t)||t.startsWith(\\\"/\\\"))return!0;try{let e=new URL(t);return Bt.has(e.protocol)}catch{return Ht.test(t)}}function p(e){if(!f(e))return!1;let t=e.trim().replace(Gt,\\\"\\\");return/^https?:\\\\/\\\\//i.test(t)||zt.test(t)}function g(e){return Kt.add(e),e}function m(e){switch(typeof e){case\\\"string\\\":return e.length>65536?void 0:`s:${e}`;case\\\"number\\\":return`n:${Object.is(e,-0)?\\\"-0\\\":String(e)}`;case\\\"boolean\\\":return\\\"b:\\\"+(e?\\\"1\\\":\\\"0\\\");case\\\"bigint\\\":return`i:${String(e)}`;case\\\"undefined\\\":return\\\"u\\\";case\\\"object\\\":{if(null===e)return\\\"z\\\";let t;try{t=JSON.stringify(e)}catch{return}return t.length>65536?void 0:`o:${t}`}case\\\"symbol\\\":case\\\"function\\\":return}}function v(e,t=[]){let n=\\\"number\\\"==typeof e&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0,i=Math.min(4,n??1),r=new Set(t),l=new Set;for(let e of Zt)(i>=Xt[e].since||r.has(e))&&l.add(e);return{ours:4,...void 0!==n?{theirs:n}:{theirs:void 0},negotiated:i,capabilities:l,observed:r}}function y(e){try{return!0===e.matchMedia?.(\\\"(prefers-reduced-motion: reduce)\\\").matches}catch{return!1}}function b(e,t){return e.generation===t.generation&&e.revision===t.revision}function w(...e){let t=new Map;for(let n of e)for(let[e,i]of Object.entries(n)){let n=t.get(e);void 0===n&&(n=new Set,t.set(e,n));for(let e of i)n.add(e)}let n={};for(let[e,i]of t)n[e]=[...i];return n}function S(e,t){let n={};for(let i of t)i!==e&&(n[i]=[e]);return n}function k(e){return\\\"astro-island\\\"===e.tagName.toLowerCase()||e.hasAttribute(ln)}function T(e){return\\\"patch\\\"===e.getAttribute(ln)}function A(e){return e.closest(`[${an}]`)}function C(e){let t=e.getAttribute(sn);return null!==t&&t.length>0?\\\"patch\\\"===t||\\\"fragment\\\"===t||\\\"route\\\"===t?t:void 0:null!==A(e)?\\\"fragment\\\":null!==e.closest(\\\"head\\\")?\\\"route\\\":\\\"patch\\\"}function $(e){return Mn.has(e)||Nn.test(e)}function F(e){let t=e.getAttribute(dn);if(null!==t&&$(t))return t;if(e.hasAttribute(yn))return\\\"richText\\\";if(e.hasAttribute(bn))return\\\"html\\\";if(e.hasAttribute(Sn))return\\\"structural-array\\\";if(e.hasAttribute(wn))return\\\"array\\\";if(\\\"IMG\\\"===e.tagName)return\\\"image\\\";if(\\\"A\\\"===e.tagName)return\\\"url\\\";if(\\\"TIME\\\"===e.tagName)return\\\"date\\\";if(\\\"INPUT\\\"===e.tagName){let t=e.type;if(\\\"checkbox\\\"===t)return\\\"checkbox\\\";if(\\\"number\\\"===t)return\\\"number\\\";if(\\\"date\\\"===t||\\\"datetime-local\\\"===t)return\\\"date\\\"}return\\\"text\\\"}function R(){return!0}function N(e){for(let t of e){let e=t.codePointAt(0);if(void 0!==e&&(e<=31||127===e))return!0}return!1}function M(e){if(void 0===e||0===e.length||e.length>128||\\\".\\\"===e||\\\"..\\\"===e||e.includes(\\\"/\\\")||e.includes(\\\"\\\\\\\\\\\")||e.includes(\\\"?\\\")||e.includes(\\\"#\\\")||N(e))return!1;try{return encodeURIComponent(e),!0}catch{return!1}}function x(e){return e.aborted}function E(e){return e.has(\\\"schema-json\\\")?Ln:e.has(\\\"document-events\\\")||e.has(\\\"relationship-events\\\")?On:Un}function I(e,t){return void 0===e||t(e)}function L(e,t){return null==e||t(e)}function O(e){if(\\\"object\\\"!=typeof e||null===e)return!1;let t=Object.getPrototypeOf(e);return null===t||null===Object.getPrototypeOf(t)}function U(e){if(e.nodeType!==Wn)return!1;let t=e;return t.hasAttribute(un)||null!==t.querySelector(`[${un}]`)}function P(e){return`global:${e}`}function j(e,t){return void 0===t||\\\"\\\"===t?`collection:${e}`:`collection:${e}:${t}`}function W(e){return\\\"string\\\"==typeof e&&e.length>0}function D(e,t){return null!==t&&void 0!==e&&t.includes(e)}function V(e){let t=e.id;return\\\"string\\\"==typeof t&&t.length>0?t:\\\"number\\\"==typeof t&&Number.isFinite(t)?String(t):void 0}function B(e,t,n,i=!1){if(i&&void 0!==n){let i=_(e,`${t}_${n}`);if(void 0!==i)return i}let r=_(e,t);if(void 0!==r)return r;if(t.includes(\\\".\\\")){let n=e,i=!0;for(let e of t.split(\\\".\\\")){if(_n.has(e)||null===n||\\\"object\\\"!=typeof n){i=!1;break}if(n=_(n,e),void 0===n){i=!1;break}}if(i)return n}return void 0===n?void 0:_(e,`${t}_${n}`)}function _(e,t){if(!_n.has(t)&&Object.prototype.hasOwnProperty.call(e,t))return e[t]}function H(e,t,n){let i=e.get(t);return void 0!==i&&(!1===n||i.some(e=>D(e.owner,n)))}function z(e,t){let n=new Set;for(let[i,r]of e.entries())for(let e of r)!1!==t&&!D(e.owner,t)||void 0!==e.locale&&n.add(`${i}_${e.locale}`);return n}function G(e){let t=typeof e;return\\\"string\\\"===t||\\\"number\\\"===t||\\\"boolean\\\"===t||\\\"bigint\\\"===t}function q(e,t){if(void 0===t||0===t.length)return e;let n=`_${t}`;return e.endsWith(n)?e.slice(0,-n.length):e}function J(e){let t=function(){if(void 0!==vt)return vt;let e=function(){let e=globalThis.trustedTypes;return\\\"object\\\"!=typeof e||null===e?void 0:\\\"function\\\"==typeof e.createPolicy?e:void 0}();if(void 0===e)return vt=null,null;try{vt=e.createPolicy(zn,{createHTML:e=>e})}catch{vt=null}return vt}();return null===t?e:t.createHTML(e)}function K(e,t){for(let n of t.keyAttributes){let t=e.getAttribute(n);if(null!==t&&t.length>0)return`${n}=${t}`}}function Q(e){if(e.tagName.toLowerCase().includes(\\\"-\\\")||e.hasAttribute(ln)||e.hasAttribute(Gn))return!0;let t=e.getAttribute(\\\"contenteditable\\\");return null!==t&&\\\"false\\\"!==t}function X(e,t,n){if(!function(e,t){return e.tagName===t.tagName&&e.namespaceURI===t.namespaceURI&&!Q(e)&&!Q(t)}(e,t))return t;let i=function(e){let t=e.ownerDocument.activeElement;return t instanceof HTMLElement&&e.contains(t)?{element:t,selection:t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement?[t.selectionStart,t.selectionEnd]:null}:null}(e);return function(e,t){for(let n of Array.from(e.attributes))t.hasAttribute(n.name)||qn.has(n.name.toLowerCase())||e.removeAttribute(n.name);for(let n of Array.from(t.attributes))e.getAttribute(n.name)!==n.value&&e.setAttribute(n.name,n.value)}(e,t),!0!==n.retainChildrenOf?.(e,t)&&function(e,t,n){let i=function(e,t){let n,i=new Map;for(let r of Array.from(e.children)){let e=K(r,t);if(void 0!==e){if(i.has(e)){n??(n=e.slice(e.indexOf(\\\"=\\\")+1));continue}i.set(e,r)}}return void 0!==n&&t.onDuplicateKey?.(e,n),i}(e,n),r=new Set(i.values()),l=Array.from(e.childNodes).filter(e=>!r.has(e)),o=new Set,a=new Set,s=Array.from(t.childNodes),u=e.firstChild,d=0;for(let t=0;t<s.length;t+=1){let r=s[t],c=null,h=r instanceof Element?K(r,n):void 0;if(void 0!==h&&a.has(h)&&(h=void 0),void 0!==h){a.add(h);let e=i.get(h);if(void 0!==e&&!o.has(e)&&(c=Z(e,r,n)===e?e:null,null===c)){e.replaceWith(r),o.add(r),u=r.nextSibling;continue}}else{for(;d<l.length;){let i=l[d];if(d+=1,!o.has(i)){if(ee(i,r)){c=Z(i,r,n)===i?i:null,null===c&&(e.replaceChild(r,i),o.add(r),u=r.nextSibling);break}if(i instanceof Element){let n=s[t+1];if(!(r instanceof Element)||void 0!==n&&ee(i,n)){d-=1;break}e.replaceChild(r,i),o.add(r),u=r.nextSibling;break}if(!(r instanceof Element)){e.replaceChild(r,i),o.add(r),u=r.nextSibling;break}}}if(null===c&&o.has(r))continue}let f=c??r;for(o.add(f);null!==u&&u!==f&&!o.has(u)&&Y(u);)u=u.nextSibling;f!==u&&e.insertBefore(f,u),u=f.nextSibling}for(let t of Array.from(e.childNodes))o.has(t)||t.remove()}(e,t,n),function(e){if(null===e)return;let{element:t,selection:n}=e;if(t.ownerDocument.activeElement!==t&&t.isConnected)try{t.focus({preventScroll:!0});let[e,i]=n??[null,null];null!==e&&null!==i&&t.setSelectionRange(e,i)}catch{}}(i),e}function Z(e,t,n){return e instanceof Element&&t instanceof Element?Q(e)&&Q(t)?e:X(e,t,n):(e.nodeValue!==t.nodeValue&&(e.nodeValue=t.nodeValue),e)}function Y(e){return e.nodeType===Node.TEXT_NODE&&0===(e.nodeValue??\\\"\\\").trim().length}function ee(e,t){return e.nodeType===t.nodeType&&(!(e instanceof Element&&t instanceof Element)||e.tagName===t.tagName&&e.namespaceURI===t.namespaceURI)}function te(e,t){let n=ne();if(!n)throw new Error(\\\"sanitizeHtml needs a DOM\\\");if(\\\"\\\"===e)return\\\"\\\";let i=function(e){if(!e){let e=new Map;for(let[t,n]of Object.entries(ti))e.set(t,n);return{allowedTags:Jn,attrByTag:e,allowFormControls:!1,templateMode:!1,mode:oi,allowedData:new Set}}let t=new Set(Jn);for(let n of e.additionalAllowedTags??[])t.add(n);if(!0===e.allowFormControls)for(let e of Kn)t.add(e);let n=new Map;for(let[e,t]of Object.entries(ti))n.set(e,t);for(let[t,i]of Object.entries(e.additionalAllowedAttributes??{})){let e=n.get(t),r=new Set(e??[]);for(let e of i)r.add(e);n.set(t,r)}return{allowedTags:t,attrByTag:n,allowFormControls:!0===e.allowFormControls,templateMode:!0===e.templateMode,mode:e.policy??oi,allowedData:new Set((e.allowedDataAttributes??[]).map(e=>e.toLowerCase()))}}(t),r=n.createElement(\\\"template\\\");return r.innerHTML=J(e),ie(r.content,i),r.innerHTML}function ne(){if(!(typeof document>\\\"u\\\"))return document}function ie(e,t){for(let n of Array.from(e.childNodes))n.nodeType===ii?re(n,t):n.nodeType===ri&&n.remove()}function re(e,t){let n=e.tagName.toLowerCase();if(!Qn.has(n)||t.allowFormControls&&Kn.has(n)){if(!t.allowedTags.has(n)){ie(e,t);let n=e.parentNode;if(n){for(;e.firstChild;)n.insertBefore(e.firstChild,e);e.remove()}return}(function(e,t,n){let i=n.attrByTag.get(t);for(let t of Array.from(e.attributes)){let r=t.name.toLowerCase();if(r.startsWith(\\\"on\\\")||\\\"style\\\"===r)e.removeAttribute(t.name);else{if(\\\"strict\\\"===n.mode){if(n.templateMode&&li.has(r))continue;if(\\\"id\\\"===r||\\\"name\\\"===r||r.startsWith(ei)){e.removeAttribute(t.name);continue}if(r.startsWith(Yn)){n.allowedData.has(r)||e.removeAttribute(t.name);continue}if(Xn.has(r)||r.startsWith(Zn))continue}else if(Xn.has(r)||r.startsWith(Zn)||r.startsWith(Yn))continue;i?.has(r)?(ni.has(r)&&!f(t.value)||\\\"srcset\\\"===r&&!le(t.value))&&e.removeAttribute(t.name):e.removeAttribute(t.name)}}})(e,n,t),\\\"a\\\"===n&&function(e){let t=e.getAttribute(\\\"href\\\");null===t||!p(t)||(e.setAttribute(\\\"rel\\\",\\\"noopener noreferrer\\\"),e.hasAttribute(\\\"target\\\")||e.setAttribute(\\\"target\\\",\\\"_blank\\\"))}(e),ie(e,t)}else e.remove()}function le(e){for(let t of e.split(\\\",\\\")){let e=t.trim();if(0===e.length)continue;let n=e.search(/\\\\s/);if(!f(-1===n?e:e.slice(0,n)))return!1}return!0}function oe(e){return\\\"\\\"===e?\\\"\\\":e.replace(si,e=>ai[e])}function ae(e){return\\\"\\\"===e?\\\"\\\":e.replace(di,e=>ui[e])}function se(e,t,n,i){let r=\\\"object\\\"==typeof t&&null!==t?t:null;return e.replace(ci,(e,l)=>null!==r&&function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(r,l)?oe(i(Reflect.get(r,l))):null===r&&\\\"value\\\"===l?oe(i(t)):\\\"index\\\"===l?String(n):e)}function ue(e){if(null==e)return\\\"\\\";if(\\\"string\\\"==typeof e)return e;if(\\\"number\\\"==typeof e||\\\"boolean\\\"==typeof e||\\\"bigint\\\"==typeof e)return String(e);try{return JSON.stringify(e)}catch{return\\\"\\\"}}function de(e){return null==e||\\\"\\\"===e}function ce(e){let t=gi.get(e);if(void 0!==t)return t;let n=new Set(hi);for(let t of e.matchAll(pi)){let e=t[1]?.toLowerCase();void 0!==e&&n.add(e)}let i={};for(let e of n)i[e]=fi;let r={additionalAllowedTags:[...n],additionalAllowedAttributes:i,allowFormControls:!0,templateMode:!0};return gi.set(e,r),r}function he(e){let{template:t,container:n,patches:i,nextItems:r,store:l,forceRender:o=!1}=e,a=pe(n,t,i,r,o,l);return null===a?null:ge(a,l,{morph:e.morph??!0,onDuplicateKey:e.onDuplicateKey})}function fe(e,t){return t.hasAttribute(vi)&&t.hasAttribute(yi)}function pe(e,t,n,i,r,l){let o=function(e,t,n,i,r,l,o){let a=Array.from(e.children),s=ke(a,mi),u=new Set,d=[];for(let c=0;c<n.length;c+=1){let h=n[c],f=Se(h),p=void 0===f?a[c]??null:Te(s,f)??null;null!==p&&u.has(p)&&(p=null),null!==p&&u.add(p);let g=i.replaces.has(c),m=r||i.renders.has(c)||null===p?Ae(e.ownerDocument,t,h,c):void 0;if(null===m)return null;let v=void 0===m?[]:me(g?null:p,m,h,l,o);if(null===v)return null;d.push([c,p,m??void 0,v,g])}return d}(e,t,i,function(e){let t=new Set,n=new Set;for(let i of e)\\\"insert\\\"===i.kind||\\\"update\\\"===i.kind?t.add(i.index):\\\"replace\\\"===i.kind&&(t.add(i.index),n.add(i.index));return{renders:t,replaces:n}}(n),r,l.get(e),l);return null===o?null:[e,o,i]}function ge(e,t,n){let[i,r,l]=e,o=new Set,a=!1;for(let[e,l,s,u,d]of r){let r=l;if(void 0!==s){let e=!(!n.morph||d||null===l)&&X(l,s,{keyAttributes:[mi,vi],retainChildrenOf:fe,...void 0!==n.onDuplicateKey?{onDuplicateKey:n.onDuplicateKey}:{}})===l;if(!e)for(let[e,t]of u)null!==e&&(ye(e,t),t.replaceWith(e));for(let[,,e]of u)void 0!==e&&ge(e,t,n);e?a=!0:(null!==l&&(l.replaceWith(s),a=!0),r=s)}if(null===r)continue;let c=i.children[e]??null;r!==c&&(i.insertBefore(r,c),a=!0),o.add(r)}for(let e of Array.from(i.children))o.has(e)||(e.remove(),a=!0);let s=function(e,t){let n=t.get(e);return n||(n=new Map,t.set(e,n)),n}(i,t);s.clear();for(let e of l)we(s,e);return a}function me(e,t,n,i,r){let l=ke(null===e?[]:ve(e),vi),o=Se(n),a=void 0!==o?i?.get(o):void 0,s=[];for(let e of ve(t)){let t=e.getAttribute(vi);if(null===t)continue;let i,o=Te(l,t)??null,u=e.getAttribute(yi),d=u?o:null,h=d?.getAttribute(yi)??null;if(u){let l=be(n,t);if(void 0!==l||null!==d){let n=l??[],o=c(null===d?[]:be(a,t)??[],n),s=null!==d&&h!==u;if((o.length>0||s)&&(i=pe(d??e,u,o,n,s,r)??void 0,void 0===i))return null}}s.push([d,e,i])}return s}function ve(e){return Array.from(e.querySelectorAll(`[${vi}]`)).filter(t=>{let n=t.parentElement;for(;null!==n&&n!==e;){if(n.hasAttribute(vi))return!1;n=n.parentElement}return n===e})}function ye(e,t){for(let n of Array.from(e.attributes))t.hasAttribute(n.name)||e.removeAttribute(n.name);for(let n of Array.from(t.attributes))e.getAttribute(n.name)!==n.value&&e.setAttribute(n.name,n.value)}function be(e,t){if(\\\"object\\\"!=typeof e||null===e)return;let n=e[t];return Array.isArray(n)?n:void 0}function we(e,t){let n=Se(t);void 0!==n&&e.set(n,t)}function Se(e){if(\\\"object\\\"!=typeof e||null===e)return;let t=e.id;return\\\"string\\\"==typeof t||\\\"number\\\"==typeof t?String(t):void 0}function ke(e,t){let n=new Map;for(let i=e.length-1;i>=0;i-=1){let r=e[i];if(void 0===r)continue;let l=r.getAttribute(t);if(null===l)continue;let o=n.get(l);void 0===o?n.set(l,[r]):o.push(r)}return n}function Te(e,t){return e.get(t)?.pop()}function Ae(e,t,n,i){let r=te(se(t,n,i,ue),ce(t)),l=e.createElement(\\\"template\\\");l.innerHTML=J(r);let o=l.content.firstElementChild;if(!o)return null;let a=Se(n);return void 0!==a&&o.setAttribute(mi,a),o}function Ce(e,t,n,i){let r=m(t);if(void 0===r)return;let l=[e.hrefField,e.srcField,e.altField],o=r;for(let t of l){if(void 0===t||0===t.length)continue;let r=m(B(n,t,e.locale??i,void 0!==e.locale));if(void 0===r)return;o+=`|${t}=${r}`}return o}function $e(e,t){return null!==t&&e.generation===t.generation&&e.revision===t.revision}function Fe(e){if(!1===e.enableA11y)return null;let t=e.root,n=void 0===t?void 0:Re(t)?t:t.ownerDocument;return new Wt(e.a11yLocale,n)}function Re(e){return 9===e.nodeType}function Ne(e){return e.body}function Me(e){if(typeof window>\\\"u\\\")return;let t=[];window.parent!==window&&t.push(window.parent),window.opener instanceof Window&&t.push(window.opener),jn.sendReady(t,e)}function xe(){if(typeof window>\\\"u\\\")return!1;try{return window.self!==window.top}catch{return!0}}function Ee(e){let t=e.trim();if(0!==t.length)try{let e=new URL(t);return\\\"http:\\\"!==e.protocol&&\\\"https:\\\"!==e.protocol||!Ci.test(e.origin)?void 0:e.origin}catch{return}}function Ie(e){let t=e.format;return\\\"string\\\"==typeof t&&Mi.has(t)?t:\\\"number\\\"==typeof t?Ni[t]:void 0}function Le(e){let t=e.indent;return\\\"number\\\"==typeof t&&t>0?t:0}function Oe(e){return\\\"rtl\\\"===e.direction?' dir=\\\"rtl\\\"':\\\"ltr\\\"===e.direction?' dir=\\\"ltr\\\"':\\\"\\\"}function Ue(e){let t=Ie(e),n=Le(e),i=[];return void 0!==t&&i.push(`lp-align-${t}`),n>0&&i.push(`lp-indent-${String(n)}`),0===i.length?\\\"\\\":` class=\\\"${i.join(\\\" \\\")}\\\"`}function Pe(e){return\\\"object\\\"==typeof e&&null!==e?e:void 0}function je(e){return Pe(e)}function We(e){return e.replace(/[^a-zA-Z0-9_-]/g,\\\"-\\\").toLowerCase()}function De(e){return\\\"string\\\"==typeof e&&e.length>0?e:void 0}function Ve(e){let t=De(e.title)??De(e.name)??De(e.slug);return void 0!==t?t:void 0===e.id?void 0:String(e.id)}function Be(e){if(\\\"string\\\"==typeof e.text)return e.text;if(!e.children)return\\\"\\\";let t=\\\"\\\";for(let n of e.children)t+=Be(n);return t}function _e(e){return`${\\\"number\\\"==typeof e.width?` width=\\\"${String(e.width)}\\\"`:\\\"\\\"}${\\\"number\\\"==typeof e.height?` height=\\\"${String(e.height)}\\\"`:\\\"\\\"}`}function He(e){return\\\"string\\\"==typeof e.mimeType?` type=\\\"${ae(e.mimeType)}\\\"`:\\\"\\\"}function ze(e){return Li.get(e)}function Ge(e,t,n,i){let r=Pe(e.fields)??{},l=\\\"string\\\"==typeof r.blockType?r.blockType:\\\"\\\",o=We(l);if(\\\"\\\"!==l){let e=ze(l)??ze(o);if(e)return e(r,{renderChildren:t.renderChildren})}return`<${n} class=\\\"${\\\"\\\"===o?i:`${i} ${i}--${o}`}\\\"></${n}>`}function qe(e,t){return\\\"number\\\"==typeof t&&t>1?` ${e}=\\\"${String(t)}\\\"`:\\\"\\\"}function Je(e){if(\\\"object\\\"!=typeof e||null===e||!(\\\"root\\\"in e))return!1;let t=e.root;return\\\"object\\\"==typeof t&&null!==t&&\\\"children\\\"in t&&Array.isArray(t.children)}function Ke(e){let t=\\\"\\\";for(let n of e)t+=Qe(n);return t}function Qe(e){let t=function(e){return Ui.get(e)??Oi[e]}(e.type);return t?t(e,Pi):void 0!==e.children?Ke(e.children):\\\"\\\"}function Xe(e){if(\\\"string\\\"==typeof e.text)return e.text;if(\\\"linebreak\\\"===e.type)return\\\"\\\\n\\\";if(void 0===e.children)return\\\"\\\";let t=\\\"\\\";for(let n of e.children)t+=Xe(n);return t}function Ze(e=\\\"text\\\"){let t=new WeakSet;return{name:e,render:g((e,n)=>{let i=e.element,r=function(e){return null==e?\\\"\\\":Je(e)?function(e){return Je(e)?e.root.children.map(Xe).join(\\\"\\\\n\\\").trim():\\\"\\\"}(e):\\\"string\\\"==typeof e?e:\\\"number\\\"==typeof e||\\\"boolean\\\"==typeof e?String(e):JSON.stringify(e)}(n);if(\\\"INPUT\\\"!==i.tagName&&\\\"TEXTAREA\\\"!==i.tagName){if(function(e){return null!==e.querySelector(\\\":scope > :not(br)\\\")}(i)&&!i.hasAttribute(Wi))return function(e,t,n){e.has(t)||(e.add(t),Ft(`[live-preview] LP0402: Skipping text update for \\\"${n}\\\": <${t.tagName.toLowerCase()}> has structured children. Move data-payload-field to the value element, or add data-payload-text to replace them.`))}(t,i,e.fieldName),!1;r.includes(\\\"\\\\n\\\")||r.includes(\\\"\\\\r\\\")?i.innerHTML=J(function(e){return oe(e).replace(/\\\\r\\\\n|\\\\r|\\\\n/g,\\\"<br>\\\")}(r)):i.textContent=r}else i.value=r})}}function Ye(e,t,n){return\\\"string\\\"!=typeof n||0===n.length?{kind:\\\"none\\\"}:f(n)?{kind:\\\"safe\\\",url:n}:(Bi.has(e)||(Bi.add(e),Ft(`[live-preview] LP0401: refused an unsafe URL for \\\"${t}\\\" on <${e.tagName.toLowerCase()}>; the attribute was cleared.`)),{kind:\\\"unsafe\\\"})}function et(e,t=e=>e){return{name:e,render(e,n,i){let r=e.element;if(de(n)){!function(e){\\\"INPUT\\\"!==e.tagName&&\\\"TEXTAREA\\\"!==e.tagName?(e.removeAttribute(\\\"href\\\"),e.textContent=\\\"\\\"):e.value=\\\"\\\"}(r);return}let l=ue(n);if(\\\"INPUT\\\"!==r.tagName&&\\\"TEXTAREA\\\"!==r.tagName){if(\\\"A\\\"===r.tagName){let n=e.hrefField,o=void 0===n||0===n.length?t(l):B(i.allFields,n,i.locale,void 0!==e.locale),a=Ye(r,e.fieldName,o);\\\"safe\\\"===a.kind?r.setAttribute(\\\"href\\\",a.url):\\\"unsafe\\\"===a.kind&&r.removeAttribute(\\\"href\\\")}r.textContent=l}else r.value=l}}}function tt(e){for(let t of Gi)e.removeAttribute(t)}function nt(e,t,n){e.src=t;let i=function(e){if(void 0===e?.sizes)return;let t=[];for(let n of Object.values(e.sizes))\\\"string\\\"!=typeof n.url||\\\"number\\\"!=typeof n.width||!f(n.url)||t.push(`${it(n.url)} ${String(n.width)}w`);return 0!==t.length?(\\\"number\\\"==typeof e.width&&\\\"string\\\"==typeof e.url&&f(e.url)&&t.push(`${it(e.url)} ${String(e.width)}w`),t.join(\\\", \\\")):void 0}(n);void 0!==i?e.setAttribute(\\\"srcset\\\",i):(e.removeAttribute(\\\"srcset\\\"),e.removeAttribute(\\\"sizes\\\"))}function it(e){return e.replace(/[\\\\s,]/g,encodeURIComponent)}function rt(e){\\\"IMG\\\"===e.tagName?tt(e):e.style.backgroundImage=\\\"\\\"}function lt(e){\\\"IMG\\\"!==e.tagName?(e.removeAttribute(\\\"href\\\"),e.textContent=\\\"\\\"):tt(e)}function ot(e){let t=Pe(e);return void 0===t?ue(e):Ve(t)??\\\"\\\"}function at(e,t){let n=e??\\\"\\\";if(null==t)return n;let i=st(t);return\\\"{}\\\"===i?n:`${n}|${i}`}function st(e){if(null===e||\\\"object\\\"!=typeof e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(e=>st(e)).join(\\\",\\\")}]`;let t=e,n=Object.keys(t).sort(),i=[];for(let e of n){let n=t[e];void 0!==n&&i.push(`${JSON.stringify(e)}:${st(n)}`)}return`{${i.join(\\\",\\\")}}`}function ut(e){for(;e.size>tr;){let t=e.keys().next().value;if(void 0===t)break;e.delete(t)}}function dt(e){return String(e).padStart(2,\\\"0\\\")}function ct(){let e=new WeakMap,t=new WeakSet,n=new WeakMap,i=new WeakMap;return{name:\\\"structural-array\\\",render:g((r,l)=>{let o=de(l)?[]:l;if(!Array.isArray(o))return!1;let a=r.element,s=r.arrayTemplate;if(void 0===s||0===s.length)return function(e,t,n){e.has(t)||(e.add(t),Ft(`[live-preview] LP0403: Skipping structural update for \\\"${n}\\\": <${t.tagName.toLowerCase()} data-payload-structural> needs data-payload-array-template (for example \\\"<li>{{label}}</li>\\\").`))}(t,a,r.fieldName),!1;let u=e.get(a),d=ht(a),h=u?.values??function(e){return e.map((e,t)=>null===e?{__payloadDomPosition:t}:{id:e})}(d),f=c(h,o),p=function(e,t,n){return void 0===e||e.template!==t||!function(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}(e.domSnapshot,n)}(u,s,d);if(0===f.length&&!p)return e.set(a,{values:o.slice(),template:s,domSnapshot:d}),!1;!function(e,t,n,i,r){let l=r.map(ft),o=new Set,a=l.find(e=>!(void 0===e||!o.has(e)&&(o.add(e),1)));if(void 0!==a&&pt(e,t,n,a),l.some(e=>void 0===e)&&gt(e,t,\\\"LP0404\\\",`LP0404: an item of \\\"${n}\\\" has no id and pairs by position, so an insert re-renders every row after it. Give items a stable id.`),i?.length===r.length&&r.length>1){let r=new Set(i.map(ft).filter(e=>void 0!==e)),o=l.some(e=>void 0!==e&&r.has(e));r.size>0&&!o&&gt(e,t,\\\"LP0406\\\",`LP0406: every key of \\\"${n}\\\" changed at once; the source generates ids per message, so no item can be retained across updates.`)}}(n,a,r.fieldName,u?.values,o);let g=he({template:s,container:a,patches:f,nextItems:o,store:i,forceRender:p,onDuplicateKey:(e,t)=>{pt(n,e,r.fieldName,t)}});return null!==g&&(e.set(a,{values:o.slice(),template:s,domSnapshot:ht(a)}),!!g&&void 0)})}}function ht(e){return Array.from(e.children,e=>e.getAttribute(mi))}function ft(e){if(\\\"object\\\"!=typeof e||null===e)return;let t=e.id;return\\\"string\\\"==typeof t||\\\"number\\\"==typeof t?String(t):void 0}function pt(e,t,n,i){gt(e,t,\\\"LP0405\\\",`LP0405: two items of \\\"${n}\\\" share the key \\\"${i}\\\"; later ones pair by position. Make \\\\`id\\\\` unique per item.`)}function gt(e,t,n,i){let r=e.get(t);void 0===r&&(r=new Set,e.set(t,r)),!r.has(n)&&(r.add(n),Ft(`[live-preview] ${i}`))}function mt(){return typeof __LIVE_PREVIEW_CONFIG__>\\\"u\\\"?[]:__LIVE_PREVIEW_CONFIG__}var vt,yt=Object.defineProperty,bt=e=>{throw TypeError(e)},wt=(e,t,n)=>((e,t,n)=>t in e?yt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,\\\"symbol\\\"!=typeof t?t+\\\"\\\":t,n),St=(e,t,n)=>t.has(e)||bt(\\\"Cannot \\\"+n),kt=(e,t,n)=>(St(e,t,\\\"read from private field\\\"),n?n.call(e):t.get(e)),Tt=(e,t,n)=>t.has(e)?bt(\\\"Cannot add the same private member more than once\\\"):t instanceof WeakSet?t.add(e):t.set(e,n),At=(e,t,n,i)=>(St(e,t,\\\"write to private field\\\"),i?i.call(e,n):t.set(e,n),n),Ct=(e,t,n)=>(St(e,t,\\\"access private method\\\"),n),$t=t((...e)=>console.error(...e)),Ft=t((...e)=>console.warn(...e)),Rt=t((...e)=>console.debug(...e)),Nt=class{constructor(){Tt(this,Et);Tt(this,Mt,new Map);Tt(this,xt,new Map)}on(e,t){return Ct(this,Et,Lt).call(this,kt(this,Mt),e,t)}once(e,t){return Ct(this,Et,Lt).call(this,kt(this,xt),e,t)}off(e,t){Ct(this,Et,Ot).call(this,kt(this,Mt),e,t),Ct(this,Et,Ot).call(this,kt(this,xt),e,t)}async emit(e,t){await Ct(this,Et,It).call(this,e,t)}async emitWhile(e,t,n){return Ct(this,Et,It).call(this,e,t,n)}listenerCount(e){return(kt(this,Mt).get(e)?.size??0)+(kt(this,xt).get(e)?.size??0)}removeAllListeners(e){void 0!==e?(kt(this,Mt).delete(e),kt(this,xt).delete(e)):(kt(this,Mt).clear(),kt(this,xt).clear())}eventNames(){let e=new Set;for(let t of kt(this,Mt).keys())e.add(t);for(let t of kt(this,xt).keys())e.add(t);return[...e]}},Mt=new WeakMap,xt=new WeakMap,Et=new WeakSet,It=async function(e,t,n){let i=()=>n?.()??!0;if(!i())return!1;let r=kt(this,Mt).get(e);if(r)for(let n of[...r])if(!i()||(await Ct(this,Et,Ut).call(this,n,t,e),!i()))return!1;if(!i())return!1;let l=kt(this,xt).get(e);if(l&&l.size>0){let n=[...l];kt(this,xt).delete(e);for(let r of n)if(!i()||(await Ct(this,Et,Ut).call(this,r,t,e),!i()))return!1}return i()},Lt=function(e,t,n){let i=e.get(t);return i||(i=new Set,e.set(t,i)),i.add(n),()=>{Ct(this,Et,Ot).call(this,e,t,n)}},Ot=function(e,t,n){let i=e.get(t);void 0!==i&&(i.delete(n),0===i.size&&e.delete(t))},Ut=async function(e,t,n){try{await e(t)}catch(e){let t=\\\"string\\\"==typeof n||\\\"number\\\"==typeof n?String(n):\\\"<event>\\\";$t(`[live-preview] LP0601: handler for \\\"${t}\\\" threw:`,e)}},Pt=\\\"payload-live-preview-a11y\\\",jt=new WeakMap,Wt=class{constructor(e,t){wt(this,\\\"german\\\");wt(this,\\\"document\\\");wt(this,\\\"lease\\\",null);let n=t??(typeof document>\\\"u\\\"?null:document),r=n?.documentElement.getAttribute(\\\"lang\\\")??\\\"\\\";this.german=function(e){return/^de(?:[-_]|$)/i.test(e)}(e??(r.length>0?r:i())),this.document=n}mount(){let e=this.document;if(null==e?.body)return null;this.lease??(this.lease=function(e){let t=jt.get(e);return void 0===t&&(t={element:null,owned:!1,messageNode:null,refs:0,timer:null},jt.set(e,t)),t.refs+=1,t}(e));let t=this.lease,n=t.element;if(n?.isConnected&&n.ownerDocument===e)return n;if(null!==n){let e=t.owned;r(t),e&&n.remove()}let i=e.getElementById(Pt);return t.owned=null===i,null===i&&(i=e.createElement(\\\"div\\\"),i.id=Pt,i.setAttribute(\\\"role\\\",\\\"status\\\"),i.setAttribute(\\\"aria-live\\\",\\\"polite\\\"),i.setAttribute(\\\"aria-atomic\\\",\\\"true\\\"),i.setAttribute(\\\"style\\\",\\\"position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap;border:0\\\"),e.body.appendChild(i)),t.element=i,i}announceConnected(){this.say(this.german?\\\"Vorschau verbunden\\\":\\\"Live preview connected\\\")}announceDisconnected(){this.say(this.german?\\\"Vorschau getrennt\\\":\\\"Live preview disconnected\\\")}announceUpdate(e){e<=0||this.say(this.german?`${String(e)} ${1===e?\\\"\\\\xc4nderung\\\":\\\"\\\\xc4nderungen\\\"} angewendet`:`${String(e)} ${1===e?\\\"change\\\":\\\"changes\\\"} applied`)}detach(){let e=this.lease,t=this.document;if(null===e||null===t||(this.lease=null,e.refs-=1,e.refs>0))return;let n=e.element;null!==n&&r(e),e.owned&&n?.remove(),e.element=null,jt.delete(t)}say(e){let t=this.mount(),n=this.lease;if(null===t||null===n)return;let i=n.messageNode;i?.parentNode!==t?(i?.remove(),i=t.ownerDocument.createTextNode(t.hasChildNodes()?` ${e}`:e),n.messageNode=i,t.appendChild(i)):i.data=null===i.previousSibling?e:` ${e}`,null!==n.timer&&clearTimeout(n.timer);let l=setTimeout(()=>{n.timer===l&&n.element===t&&r(n)},1500);n.timer=l}},Dt=new Set([\\\"tabs\\\",\\\"row\\\",\\\"collapsible\\\"]),Vt={text:\\\"text\\\",textarea:\\\"textarea\\\",richText:\\\"richText\\\",email:\\\"email\\\",number:\\\"number\\\",checkbox:\\\"checkbox\\\",date:\\\"date\\\",select:\\\"select\\\",radio:\\\"radio\\\",array:\\\"array\\\",blocks:\\\"blocks\\\",group:\\\"text\\\",tabs:\\\"text\\\",row:\\\"text\\\",collapsible:\\\"text\\\",relationship:\\\"relationship\\\",upload:\\\"upload\\\",point:\\\"text\\\",json:\\\"text\\\",code:\\\"text\\\",ui:\\\"text\\\"},Bt=new Set([\\\"http:\\\",\\\"https:\\\",\\\"mailto:\\\",\\\"tel:\\\"]),_t=/^\\\\s*(?:javascript|data|vbscript|file|blob|about)\\\\s*:/i,Ht=/^(?:\\\\.{1,2}\\\\/|[a-zA-Z0-9_-]+\\\\/?)/,zt=/^[\\\\\\\\/]{2}/,Gt=/[\\\\t\\\\n\\\\r]/g,qt=new Set([\\\"style\\\",\\\"srcdoc\\\",\\\"formaction\\\",\\\"form\\\",\\\"id\\\",\\\"name\\\",\\\"is\\\",\\\"srcset\\\",\\\"imagesrcset\\\"]),Jt=new Set([\\\"href\\\",\\\"src\\\",\\\"poster\\\",\\\"cite\\\",\\\"action\\\",\\\"xlink:href\\\",\\\"data\\\"]),Kt=new WeakSet,Qt=class{constructor(){wt(this,\\\"previous\\\",null)}diff(e,t){let n=this.previous,i=new Map,r=new Set;for(let[t,l]of Object.entries(e)){let e=m(l);i.set(t,e),(null===n||void 0===e||n.get(t)!==e)&&r.add(t)}if(null!==n)for(let e of n.keys())i.has(e)||r.add(e);this.previous=i;let l=new Set;for(let[e,n]of Object.entries(t))if(r.has(e))for(let e of n)l.add(e);return{changed:r,invalidated:l}}reset(){this.previous=null}},Xt={basic:{since:1},\\\"schema-json\\\":{since:2,observed:\\\"schema\\\"},locale:{since:2,observed:\\\"locale\\\"},\\\"preview-token\\\":{since:3,observed:\\\"preview-token\\\"},\\\"nested-arrays\\\":{since:4},\\\"recursive-diffs\\\":{since:4},\\\"document-events\\\":{since:4,observed:\\\"document-event\\\"},\\\"relationship-events\\\":{since:4,observed:\\\"relationship-event\\\"}},Zt=Object.keys(Xt),Yt=class{constructor(){wt(this,\\\"negotiation\\\",v(void 0));wt(this,\\\"observed\\\",new Set)}observe(e,t){let n=e.filter(e=>!this.observed.has(e));if(0!==n.length){for(let e of n)this.observed.add(e);this.negotiation=v(this.negotiation.theirs,this.observed),t(\\\"protocol\\\",`observed=${n.join(\\\",\\\")}`)}}applyVersion(e,t){let n=this.negotiation;if(n.theirs===e)return;let i=v(e,this.observed);this.negotiation=i,i.negotiated!==n.negotiated&&t(\\\"protocol\\\",\\\"ours=4\\\",`theirs=${e}`,`negotiated=${i.negotiated}`)}},en=class{constructor(){Tt(this,tn)}reveal(e,t,n){return e===kt(this,tn)?\\\"skipped-same\\\":(At(this,tn,e),function(e,t){return function(e,t){let n=e.getBoundingClientRect(),i=n.bottom>0&&n.top<t.innerHeight,r=n.right>0&&n.left<t.innerWidth;return i&&r}(e,t)?\\\"already-visible\\\":(e.scrollIntoView({behavior:y(t)?\\\"auto\\\":\\\"smooth\\\",block:\\\"center\\\"}),\\\"revealed\\\")}(t,n))}reset(){At(this,tn,void 0)}},tn=new WeakMap,nn=class{constructor(){wt(this,\\\"started\\\",!1);wt(this,\\\"suspended\\\",!1);wt(this,\\\"deferredStart\\\",null);wt(this,\\\"activeUpdate\\\",null);wt(this,\\\"locale\\\");wt(this,\\\"schema\\\");wt(this,\\\"schemaIndex\\\");wt(this,\\\"updateCount\\\",0);wt(this,\\\"supersededCount\\\",0);wt(this,\\\"completedCount\\\",0);wt(this,\\\"skippedUnchangedCount\\\",0);wt(this,\\\"lastFlush\\\",null);wt(this,\\\"absentFields\\\",new Set);wt(this,\\\"warnedOrphanFields\\\",new Set);wt(this,\\\"warnedStrategy\\\",new WeakSet);wt(this,\\\"warnedUnattributableMessage\\\",!1);wt(this,\\\"warnedVisibilityGate\\\",!1);wt(this,\\\"warnedFragmentFallback\\\",!1);wt(this,\\\"lastAppliedIdentity\\\",new WeakMap);wt(this,\\\"seenFieldIdentity\\\",new Map);wt(this,\\\"fragmentStats\\\",{rendered:0,failed:0,superseded:0});wt(this,\\\"routeStats\\\",{refreshes:0,failed:0,loopStopped:0});wt(this,\\\"fragmentController\\\",null);wt(this,\\\"routeController\\\",null);wt(this,\\\"readyTimers\\\",[]);wt(this,\\\"revealer\\\",new en);wt(this,\\\"changes\\\",new Qt);wt(this,\\\"protocol\\\",new Yt)}isRunning(){return this.started}isCurrent(e){return this.started&&this.activeUpdate===e}complete(e){e.completed||(e.completed=!0,this.completedCount+=1)}abortStrategies(){for(let e of[\\\"fragmentController\\\",\\\"routeController\\\"]){let t=this[e];null!==t&&(this[e]=null,t.abort())}}},rn=class{constructor(e,t){wt(this,\\\"deps\\\",e);wt(this,\\\"state\\\",t)}apply(e){let{deps:t,state:n}=this,i=n.activeUpdate;if(null===i||void 0===e.identity||!b(i.identity,e.identity)||!n.isCurrent(i))return!1;let{target:r,value:l}=e,o=void 0!==i.schemaIndex?function(e,t){if(e.has(t))return e.get(t);let n=t.replace(/\\\\.\\\\d+(?=\\\\.|$)/g,\\\".*\\\");return e.has(n)?e.get(n):void 0}(i.schemaIndex,r.fieldName):void 0,a=function(e,t){if(e.explicitFieldType)return e.fieldType;if(void 0!==t){let e=function(e){if(Object.prototype.hasOwnProperty.call(Vt,e))return Vt[e]}(t);if(void 0!==e)return e}return e.fieldType}(r,o?.type);\\\"text\\\"===a&&!0!==r.explicitFieldType&&function(e){if(\\\"object\\\"!=typeof e||null===e||!(\\\"root\\\"in e))return!1;let t=e.root;return\\\"object\\\"==typeof t&&null!==t&&Array.isArray(t.children)}(l)&&(a=\\\"richText\\\");let s;try{s=t.resolveRenderer(a,r)}catch(e){return this.fail(i,e)}if(!n.isCurrent(i))return!1;let u=t.emitter.listenerCount(\\\"elementUpdate\\\")>0,d=u?function(e){return\\\"INPUT\\\"===e.tagName||\\\"TEXTAREA\\\"===e.tagName?e.value:\\\"IMG\\\"===e.tagName?e.src:e.textContent}(r.element):void 0;if(!n.isCurrent(i))return!1;let c={allFields:e.allFields,locale:r.locale??i.locale,schema:o,...void 0!==t.renderRichText?{renderRichText:t.renderRichText}:{}};!0===r.boundary&&r.element.toggleAttribute(\\\"hidden\\\",function(e){return null==e||(\\\"string\\\"==typeof e?0===e.trim().length:Array.isArray(e)&&0===e.length)}(l));try{if(void 0!==r.targetAttribute){if(\\\"blocked\\\"===function(e,t,n){let i=t.toLowerCase().trim();if(0===i.length||i.startsWith(\\\"on\\\")||qt.has(i))return\\\"blocked\\\";if(null==n)return e.removeAttribute(i),\\\"applied\\\";if(\\\"string\\\"!=typeof n&&\\\"number\\\"!=typeof n&&\\\"boolean\\\"!=typeof n)return\\\"blocked\\\";let r=String(n);return Jt.has(i)&&!f(r)?\\\"blocked\\\":(e.setAttribute(i,r),\\\"applied\\\")}(r.element,r.targetAttribute,l))return t.warn(`[live-preview] LP0401: refused to write \\\"${r.fieldName}\\\" into attribute \\\"${r.targetAttribute}\\\"`),!1}else{if(void 0===s)return t.log(\\\"no renderer for\\\",a),!1;if(!1===function(e,t,n,i){return e.render(t,n,i)}(s,r,l,c)&&function(e){return Kt.has(e.render)}(s))return!1}}catch(e){return this.fail(i,e)}if(!n.isCurrent(i))return!1;u&&t.emitter.emitWhile(\\\"elementUpdate\\\",{element:r.element,fieldName:r.fieldName,previousValue:d,nextValue:l,revision:i.identity.revision,receivedAt:i.receivedAt,source:\\\"patch\\\"},()=>n.isCurrent(i));let h=n.isCurrent(i);return h&&(void 0!==e.valueIdentity?n.lastAppliedIdentity.set(r.element,e.valueIdentity):n.lastAppliedIdentity.delete(r.element)),h}fail(e,t){if(!this.state.isCurrent(e))return!1;let n=t instanceof Error?t:new Error(String(t));return this.deps.emitter.emitWhile(\\\"error\\\",{error:n,context:\\\"renderer\\\",code:\\\"LP0603\\\"},()=>this.state.isCurrent(e)),!1}},ln=\\\"data-payload-island\\\",on=`astro-island, [${ln}]`,an=\\\"data-payload-fragment\\\",sn=\\\"data-payload-strategy\\\",un=\\\"data-payload-field\\\",dn=\\\"data-payload-type\\\",cn=\\\"data-payload-attribute\\\",hn=\\\"data-payload-href\\\",fn=\\\"data-payload-src\\\",pn=\\\"data-payload-alt\\\",gn=\\\"data-payload-array-template\\\",mn=\\\"data-payload-array-separator\\\",vn=\\\"data-payload-locale\\\",yn=\\\"data-payload-richtext\\\",bn=\\\"data-payload-html\\\",wn=\\\"data-payload-array\\\",Sn=\\\"data-payload-structural\\\",kn=\\\"data-payload-owner\\\",Tn=\\\"data-payload-depends\\\",An=\\\"data-payload-strategy\\\",Cn=\\\"data-payload-boundary\\\",$n=[un,dn,cn,hn,fn,pn,gn,mn,vn,yn,bn,wn,Sn,kn,Tn,An,Cn,\\\"type\\\"],Fn=`[${un}]`,Rn=`[${kn}]`,Nn=/^[a-z][a-z0-9-]*:[a-z][a-z0-9-]*$/i,Mn=new Set([\\\"text\\\",\\\"textarea\\\",\\\"richText\\\",\\\"email\\\",\\\"number\\\",\\\"checkbox\\\",\\\"date\\\",\\\"select\\\",\\\"radio\\\",\\\"array\\\",\\\"blocks\\\",\\\"group\\\",\\\"tabs\\\",\\\"row\\\",\\\"collapsible\\\",\\\"relationship\\\",\\\"upload\\\",\\\"point\\\",\\\"json\\\",\\\"code\\\",\\\"ui\\\",\\\"html\\\",\\\"url\\\",\\\"image\\\",\\\"structural-array\\\"]),xn=class{constructor(e={}){wt(this,\\\"entriesByField\\\",new Map);wt(this,\\\"entryByElement\\\",new WeakMap);wt(this,\\\"filter\\\");wt(this,\\\"count\\\",0);wt(this,\\\"dependencies\\\",null);wt(this,\\\"islandRoots\\\",[]);this.filter=e.filter??R}dependencyMap(){if(null!==this.dependencies)return this.dependencies;let e=[];for(let t of this.values())void 0!==t.dependsOn&&e.push(S(t.fieldName,t.dependsOn));return this.dependencies=w(...e),this.dependencies}get islands(){return this.islandRoots}buildFromRoot(e){let t=performance.now();this.clear();let n=0;for(let t of e.querySelectorAll(Fn))void 0!==this.add(t)&&(n+=1);return this.islandRoots=function(e){let t=[];for(let n of e.querySelectorAll(on))T(n)||t.push(n);return t}(e),{elementCount:n,fieldCount:this.entriesByField.size,durationMs:performance.now()-t}}add(e){let t=this.filter(e)?this.resolveBinding(e):void 0,n=this.entryByElement.get(e);if(this.dependencies=null,void 0!==t)return void 0!==n&&this.replaceEntry(n,t)?(this.entryByElement.set(e,t),t):(void 0!==n&&this.removeEntry(e,n),this.append(t),this.entryByElement.set(e,t),t);void 0!==n&&this.removeEntry(e,n)}remove(e){let t=this.entryByElement.get(e);return!!t&&(this.dependencies=null,this.removeEntry(e,t))}get(e){return this.entriesByField.get(e)}getByElement(e){return this.entryByElement.get(e)}get fieldCount(){return this.entriesByField.size}get elementCount(){return this.count}entries(){return this.entriesByField.entries()}*values(){for(let e of this.entriesByField.values())yield*e}has(e){return this.entryByElement.has(e)}clear(){this.entriesByField.clear(),this.entryByElement=new WeakMap,this.count=0,this.dependencies=null,this.islandRoots=[]}replaceEntry(e,t){if(e.fieldName!==t.fieldName)return!1;let n=this.entriesByField.get(e.fieldName),i=void 0===n?-1:n.indexOf(e);return!(void 0===n||i<0||(n[i]=t,0))}removeEntry(e,t){this.entryByElement.delete(e);let n=this.entriesByField.get(t.fieldName),i=void 0===n?-1:n.indexOf(t);return!(void 0===n||i<0||(n.splice(i,1),0===n.length&&this.entriesByField.delete(t.fieldName),this.count-=1,0))}append(e){let t=this.entriesByField.get(e.fieldName);t?t.push(e):this.entriesByField.set(e.fieldName,[e]),this.count+=1}resolveBinding(e){let t=e.getAttribute(un);if(null===t||0===t.length)return;let n=e.getAttribute(dn),i=e.getAttribute(cn),r=e.getAttribute(hn),l=e.getAttribute(fn),o=e.getAttribute(pn),a=e.getAttribute(gn),s=e.getAttribute(mn),u=e.getAttribute(vn),d=function(e){let t=e.closest(Rn)?.getAttribute(kn);return null==t||0===t.length?void 0:t}(e),c=function(e){if(null==e)return[];let t=new Set,n=[];for(let i of e.split(/[\\\\s,]+/)){let e=i.trim();0===e.length||t.has(e)||(t.add(e),n.push(e))}return n}(e.getAttribute(Tn)),h=e.getAttribute(An),f=A(e);return{element:e,fieldName:t,fieldType:F(e),explicitFieldType:null!==n&&$(n),strategyKind:C(e)??\\\"unknown\\\",...null!==f?{fragmentBoundary:f}:{},...null!==i&&i.length>0?{targetAttribute:i}:{},...null!==r&&r.length>0?{hrefField:r}:{},...null!==l&&l.length>0?{srcField:l}:{},...null!==o&&o.length>0?{altField:o}:{},...null!==a?{arrayTemplate:a}:{},...null!==s?{arraySeparator:s}:{},...null!==u&&u.length>0?{locale:u}:{},...void 0!==d?{owner:d}:{},...c.length>0?{dependsOn:c}:{},...null!==h&&h.length>0?{strategy:h}:{},...e.hasAttribute(Cn)?{boundary:!0}:{}}}},En=class{constructor(e){wt(this,\\\"serverURL\\\");wt(this,\\\"apiRoute\\\");wt(this,\\\"depth\\\");wt(this,\\\"fetchFn\\\");wt(this,\\\"log\\\");wt(this,\\\"inflight\\\",null);wt(this,\\\"attempt\\\",0);wt(this,\\\"destroyDepth\\\",0);this.serverURL=e.serverURL.replace(/\\\\/+$/,\\\"\\\");let i=e.apiRoute??\\\"/api\\\";this.apiRoute=i.startsWith(\\\"/\\\")?i:`/${i}`,this.depth=e.depth??1,this.fetchFn=e.fetchFn,this.log=void 0===e.log?n:t(e.log)}canMerge(e){try{return e.globalSlug?M(e.globalSlug):!!M(e.collectionSlug)&&function(e){if(\\\"number\\\"==typeof e)return Number.isFinite(e);if(\\\"string\\\"!=typeof e||0===e.length||e.length>512||\\\".\\\"===e||\\\"..\\\"===e||e.includes(\\\"/\\\")||e.includes(\\\"\\\\\\\\\\\")||N(e))return!1;try{return encodeURIComponent(e),!0}catch{return!1}}(e.data.id)}catch{return!1}}async merge(e){if(this.destroyDepth>0)return{status:\\\"superseded\\\"};let t=this.attempt+=1,n=this.inflight;this.inflight=null;let i=null,r=()=>this.attempt!==t;try{if(n?.abort(),r())return{status:\\\"superseded\\\"};if(!this.canMerge(e))return r()?{status:\\\"superseded\\\"}:{status:\\\"unavailable\\\"};let t=this.fetchFn??(\\\"function\\\"==typeof fetch?fetch:void 0);if(void 0===t)return{status:\\\"unavailable\\\"};i=new AbortController,this.inflight=i;let l=e.globalSlug?`globals/${encodeURIComponent(e.globalSlug)}`:`${encodeURIComponent(e.collectionSlug??\\\"\\\")}/${encodeURIComponent(String(e.data.id))}`,o=`${this.serverURL}${this.apiRoute}/${l}`,a=await t(o,{method:\\\"POST\\\",credentials:\\\"include\\\",headers:{\\\"Content-Type\\\":\\\"application/json\\\",\\\"X-Payload-HTTP-Method-Override\\\":\\\"GET\\\"},body:JSON.stringify({data:e.data,depth:this.depth,flattenLocales:!1,...void 0!==e.locale?{locale:e.locale}:{}}),signal:i.signal});if(r()||x(i.signal))return{status:\\\"superseded\\\"};if(!a.ok)return this.log(\\\"merge HTTP\\\",a.status,o),{status:\\\"unavailable\\\"};let s=await a.json();return r()||x(i.signal)?{status:\\\"superseded\\\"}:null===s||\\\"object\\\"!=typeof s||Array.isArray(s)?(this.log(\\\"merge invalid\\\",o),{status:\\\"unavailable\\\"}):{status:\\\"merged\\\",doc:s}}catch(e){return r()||null!==i&&x(i.signal)?{status:\\\"superseded\\\"}:(this.log(\\\"merge exception\\\",e),{status:\\\"unavailable\\\"})}finally{null!==i&&!r()&&this.inflight===i&&(this.inflight=null)}}destroy(){this.attempt+=1;let e=this.inflight;this.inflight=null,this.destroyDepth+=1;try{e?.abort()}finally{this.destroyDepth-=1}}},In=\\\"2.0.0-beta.0\\\",Ln={name:\\\"payload-2\\\",fieldTyping:\\\"schema\\\",populatesRelationships:\\\"admin\\\",documentEvents:!1},On={name:\\\"payload-3\\\",fieldTyping:\\\"heuristic\\\",populatesRelationships:\\\"server\\\",documentEvents:!0},Un={name:\\\"unknown\\\",fieldTyping:\\\"heuristic\\\",populatesRelationships:\\\"server\\\",documentEvents:!1},Pn=[\\\"data\\\",\\\"fieldSchemaJSON\\\",\\\"globalSlug\\\",\\\"collectionSlug\\\",\\\"locale\\\",\\\"ready\\\",\\\"previewToken\\\",\\\"protocolVersion\\\"],jn=class{constructor(e,t){wt(this,\\\"matcher\\\");wt(this,\\\"handlers\\\");wt(this,\\\"boundListener\\\");wt(this,\\\"attachedTarget\\\");wt(this,\\\"generation\\\",0);wt(this,\\\"revision\\\",0);wt(this,\\\"queue\\\",[]);wt(this,\\\"queueHead\\\",0);this.matcher=e,this.handlers=t}attach(e=window){if(void 0!==this.attachedTarget)return;let t=!1,n=e=>{if(!t||this.boundListener!==n)return;let i=this.generation;try{this.receive(e,i)}catch{let t;try{t=e.origin}catch{t=\\\"\\\"}this.reportInvalid(\\\"shape\\\",t,i)}};this.generation+=1,this.resetQueue(),this.attachedTarget=e,this.boundListener=n;try{e.addEventListener(\\\"message\\\",n)}catch(t){this.boundListener===n&&(this.attachedTarget=void 0,this.boundListener=void 0,this.resetQueue());try{e.removeEventListener(\\\"message\\\",n)}catch{}throw t}if(this.boundListener===n)t=!0;else try{e.removeEventListener(\\\"message\\\",n)}catch{}}detach(){let e=this.attachedTarget,t=this.boundListener;void 0===e||void 0===t||(this.attachedTarget=void 0,this.boundListener=void 0,this.resetQueue(),e.removeEventListener(\\\"message\\\",t))}advanceGeneration(){return void 0!==this.attachedTarget&&(this.generation+=1,this.resetQueue(),!0)}static sendReady(e,t){if(0===e.length||0===t.length)return;let n={type:\\\"payload-live-preview\\\",ready:!0,protocolVersion:4};for(let i of e)for(let e of t)try{i.postMessage(n,e)}catch{}}receive(e,t){if(!this.isCurrentGeneration(t))return;let n=e.origin;if(!this.matchesOrigin(n,t)){this.reportInvalid(\\\"origin\\\",n,t);return}if(!this.matchesSource(e)){this.reportInvalid(\\\"source\\\",n,t);return}let i=e.data;if(function(e){return\\\"object\\\"==typeof e&&null!==e&&\\\"type\\\"in e&&\\\"string\\\"==typeof e.type}(i))switch(i.type){case\\\"payload-live-preview\\\":if(!function(e){let t=e;return!(void 0!==t.data&&null!==t.data&&!O(t.data))&&L(t.fieldSchemaJSON,e=>Array.isArray(e))&&L(t.globalSlug,e=>\\\"string\\\"==typeof e)&&L(t.collectionSlug,e=>\\\"string\\\"==typeof e)&&L(t.locale,e=>\\\"string\\\"==typeof e)&&L(t.ready,e=>\\\"boolean\\\"==typeof e)&&L(t.previewToken,e=>\\\"string\\\"==typeof e)&&L(t.protocolVersion,e=>\\\"number\\\"==typeof e)}(i)){this.reportInvalid(\\\"shape\\\",n,t);return}this.dispatchUpdate(function(e){let t={...e};for(let e of Pn)null===Reflect.get(t,e)&&Reflect.deleteProperty(t,e);if(!Array.isArray(t.fieldSchemaJSON))return t;let n;try{n=l(t.fieldSchemaJSON)}catch{n=[]}return{...t,fieldSchemaJSON:n}}(i),n,t);return;case\\\"payload-document-event\\\":if(!function(e){let t=e;return I(t.action,e=>\\\"updated\\\"===e||\\\"created\\\"===e||\\\"deleted\\\"===e)&&I(t.slug,e=>\\\"string\\\"==typeof e)&&I(t.id,e=>\\\"string\\\"==typeof e||\\\"number\\\"==typeof e&&Number.isFinite(e))}(i)){this.reportInvalid(\\\"shape\\\",n,t);return}this.invokeHandler(t,this.handlers.onDocumentEvent,i,n);return;case\\\"payload-live-preview-focus\\\":{let e=function(e){let t=e.field;return\\\"string\\\"==typeof t&&t.length>0?t:void 0}(i);if(void 0===e){this.reportInvalid(\\\"shape\\\",n,t);return}let r=this.handlers.onFocusField;void 0!==r&&this.invokeHandler(t,r,e,n);return}default:this.reportInvalid(\\\"type\\\",n,t)}else this.reportInvalid(\\\"shape\\\",n,t)}dispatchUpdate(e,t,n){let i=O(e.data);if(!this.isCurrentGeneration(n))return;let r=i?{generation:n,revision:this.revision+=1}:void 0,l=this.handlers.validateToken;if(!this.isCurrentGeneration(n))return;if(void 0===l){this.commitUpdate(e,t,n,r);return}if(!0===e.ready&&void 0===e.data){this.commitUpdate(e,t,n,void 0);return}let o={generation:n,message:e,origin:t,messageRevision:r,settled:!1,approved:!1};this.queue.push(o);let a;try{a=l(e.previewToken,t)}catch{this.settleValidation(o,!1);return}\\\"boolean\\\"!=typeof a?Promise.resolve(a).then(e=>{this.settleValidation(o,!0===e)},()=>{this.settleValidation(o,!1)}):this.settleValidation(o,a)}settleValidation(e,t){this.isCurrentGeneration(e.generation)&&(e.approved=t,e.settled=!0,this.drainQueue(e.generation))}drainQueue(e){for(;this.isCurrentGeneration(e);){let t=this.queue[this.queueHead];if(void 0===t)return;if(this.matchesOrigin(t.origin,e)){if(!t.settled)return;this.dequeue(t)&&(t.approved?this.commitUpdate(t.message,t.origin,t.generation,t.messageRevision):this.reportInvalid(\\\"token\\\",t.origin,t.generation))}else{if(!this.dequeue(t))continue;this.reportInvalid(\\\"origin\\\",t.origin,t.generation)}}}commitUpdate(e,t,n,i){this.isCurrentGeneration(n)&&(void 0===i?this.invokeHandler(n,this.handlers.onUpdate,e,t):this.invokeHandler(n,this.handlers.onUpdate,e,t,i))}reportInvalid(e,t,n){if(!this.isCurrentGeneration(n))return;let i=this.handlers.onInvalid;void 0!==i&&this.invokeHandler(n,i,e,t)}matchesSource(e){if(\\\"parent-or-opener\\\"!==this.handlers.sourcePolicy)return!0;let t=this.attachedTarget;if(void 0===t)return!1;try{let n=e.source;if(null===n)return!1;let i=t.parent;if(i!==t&&n===i)return!0;let r=t.opener;return null!=r&&n===r}catch{return!1}}matchesOrigin(e,t){if(!this.isCurrentGeneration(t))return!1;try{return!0===this.matcher(e)&&this.isCurrentGeneration(t)}catch{return!1}}invokeHandler(t,n,...i){if(this.isCurrentGeneration(t))try{e(n(...i))}catch{}}isCurrentGeneration(e){return void 0!==this.attachedTarget&&this.generation===e}dequeue(e){return this.queue[this.queueHead]===e&&(this.queueHead+=1,this.queueHead===this.queue.length?(this.resetQueue(),!0):(this.queueHead>=1024&&2*this.queueHead>=this.queue.length&&(this.queue=this.queue.slice(this.queueHead),this.queueHead=0),!0))}resetQueue(){this.queue=[],this.queueHead=0}},Wn=1,Dn=class{constructor(e,t={}){wt(this,\\\"callbacks\\\");wt(this,\\\"debounceMs\\\");wt(this,\\\"rootMargin\\\");wt(this,\\\"visible\\\",new Set);wt(this,\\\"mutation\\\",null);wt(this,\\\"intersection\\\",null);wt(this,\\\"debounceTimer\\\",null);wt(this,\\\"generation\\\",0);this.callbacks=e,this.debounceMs=t.mutationDebounceMs??100,this.rootMargin=t.intersectionRootMargin??\\\"200px\\\"}start(e){let t=this.generation;this.stop();let n=t+1;if(this.generation!==n)return;let i=null,r=null;try{i=new MutationObserver(e=>{this.handleMutations(e,n)}),r=new IntersectionObserver(e=>{this.handleIntersection(e,n)},{rootMargin:this.rootMargin,threshold:0}),i.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[...$n]})}catch(e){throw i?.disconnect(),r?.disconnect(),e}this.generation===n?(this.mutation=i,this.intersection=r):(i.disconnect(),r.disconnect())}observeElement(e){this.intersection?.observe(e)}unobserveElement(e){this.intersection?.unobserve(e),this.visible.delete(e)}markVisible(e,t){t?this.visible.add(e):this.visible.delete(e)}isVisible(e){return this.visible.has(e)}stop(){this.generation+=1;let e=this.debounceTimer,t=this.mutation,n=this.intersection;this.debounceTimer=null,this.mutation=null,this.intersection=null,this.visible.clear(),null!==e&&clearTimeout(e);try{t?.disconnect()}finally{n?.disconnect()}}handleMutations(e,t){if(!this.isCurrentGeneration(t)||!function(e){for(let t of e){if(\\\"attributes\\\"===t.type&&null!==t.attributeName&&$n.includes(t.attributeName)&&(t.attributeName===un||t.attributeName===kn||t.target.nodeType===Wn&&t.target.hasAttribute(un)))return!0;for(let e of t.addedNodes)if(U(e))return!0;for(let e of t.removedNodes)if(U(e))return!0}return!1}(e))return;null!==this.debounceTimer&&clearTimeout(this.debounceTimer);let n=setTimeout(()=>{!this.isCurrentGeneration(t)||this.debounceTimer!==n||(this.debounceTimer=null,this.callbacks.onStructuralChange())},this.debounceMs);this.debounceTimer=n}handleIntersection(e,t){for(let n of e){if(!this.isCurrentGeneration(t))return;let{target:e}=n;if(n.isIntersecting){if(this.visible.has(e))continue;this.visible.add(e),this.callbacks.onVisibilityChange(e,!0)}else this.visible.has(e)&&(this.visible.delete(e),this.callbacks.onVisibilityChange(e,!1))}}isCurrentGeneration(e){return this.generation===e&&null!==this.intersection}},Vn=class{constructor(e){wt(this,\\\"timeoutMs\\\");wt(this,\\\"onTimeout\\\");wt(this,\\\"handle\\\",null);wt(this,\\\"lastKick\\\",0);this.timeoutMs=e.timeoutMs??0,this.onTimeout=e.onTimeout}kick(){if(this.lastKick=Date.now(),this.timeoutMs<=0)return;null!==this.handle&&clearTimeout(this.handle);let e=setTimeout(()=>{this.handle===e&&(this.handle=null,this.onTimeout())},this.timeoutMs);this.handle=e}stop(){null!==this.handle&&(clearTimeout(this.handle),this.handle=null)}get lastKickAt(){return this.lastKick}get pending(){return null!==this.handle}},Bn=class{constructor(){wt(this,\\\"current\\\",\\\"disconnected\\\")}get status(){return this.current}markConnected(){return this.transition(\\\"connected\\\")}markDisconnected(){return this.transition(\\\"disconnected\\\")}transition(e){return this.current!==e&&(this.current=e,!0)}},_n=new Set([\\\"__proto__\\\",\\\"prototype\\\",\\\"constructor\\\"]),Hn=new Set([\\\"id\\\",\\\"_id\\\",\\\"createdAt\\\",\\\"updatedAt\\\",\\\"createdBy\\\",\\\"updatedBy\\\",\\\"_status\\\",\\\"globalType\\\",\\\"collection\\\",\\\"locale\\\",\\\"localized\\\"]),zn=\\\"payload-live-preview\\\",Gn=\\\"data-payload-owned\\\",qn=new Set([\\\"open\\\",\\\"value\\\",\\\"checked\\\",\\\"selected\\\"]),Jn=new Set([\\\"p\\\",\\\"br\\\",\\\"strong\\\",\\\"b\\\",\\\"em\\\",\\\"i\\\",\\\"u\\\",\\\"s\\\",\\\"strike\\\",\\\"mark\\\",\\\"small\\\",\\\"h1\\\",\\\"h2\\\",\\\"h3\\\",\\\"h4\\\",\\\"h5\\\",\\\"h6\\\",\\\"ul\\\",\\\"ol\\\",\\\"li\\\",\\\"dl\\\",\\\"dt\\\",\\\"dd\\\",\\\"blockquote\\\",\\\"code\\\",\\\"pre\\\",\\\"kbd\\\",\\\"samp\\\",\\\"var\\\",\\\"a\\\",\\\"span\\\",\\\"div\\\",\\\"section\\\",\\\"article\\\",\\\"aside\\\",\\\"header\\\",\\\"footer\\\",\\\"nav\\\",\\\"figure\\\",\\\"figcaption\\\",\\\"img\\\",\\\"picture\\\",\\\"source\\\",\\\"audio\\\",\\\"video\\\",\\\"sub\\\",\\\"sup\\\",\\\"hr\\\",\\\"time\\\",\\\"abbr\\\",\\\"cite\\\",\\\"q\\\",\\\"table\\\",\\\"thead\\\",\\\"tbody\\\",\\\"tfoot\\\",\\\"tr\\\",\\\"th\\\",\\\"td\\\",\\\"caption\\\",\\\"colgroup\\\",\\\"col\\\"]),Kn=new Set([\\\"input\\\",\\\"button\\\",\\\"textarea\\\",\\\"select\\\",\\\"option\\\",\\\"label\\\"]),Qn=new Set([\\\"script\\\",\\\"style\\\",\\\"iframe\\\",\\\"object\\\",\\\"embed\\\",\\\"link\\\",\\\"meta\\\",\\\"base\\\",\\\"form\\\",\\\"input\\\",\\\"button\\\",\\\"select\\\",\\\"textarea\\\",\\\"svg\\\",\\\"math\\\",\\\"template\\\",\\\"frame\\\",\\\"frameset\\\",\\\"noframes\\\",\\\"noscript\\\"]),Xn=new Set([\\\"id\\\",\\\"class\\\",\\\"lang\\\",\\\"dir\\\",\\\"title\\\",\\\"role\\\",\\\"tabindex\\\"]),Zn=\\\"aria-\\\",Yn=\\\"data-\\\",ei=\\\"data-payload-\\\",ti={a:new Set([\\\"href\\\",\\\"target\\\",\\\"rel\\\",\\\"download\\\",\\\"hreflang\\\",\\\"type\\\"]),img:new Set([\\\"src\\\",\\\"srcset\\\",\\\"sizes\\\",\\\"alt\\\",\\\"width\\\",\\\"height\\\",\\\"loading\\\",\\\"decoding\\\"]),picture:new Set([]),source:new Set([\\\"src\\\",\\\"srcset\\\",\\\"sizes\\\",\\\"type\\\",\\\"media\\\"]),audio:new Set([\\\"src\\\",\\\"controls\\\",\\\"autoplay\\\",\\\"loop\\\",\\\"muted\\\",\\\"preload\\\"]),video:new Set([\\\"src\\\",\\\"poster\\\",\\\"controls\\\",\\\"autoplay\\\",\\\"loop\\\",\\\"muted\\\",\\\"preload\\\",\\\"width\\\",\\\"height\\\",\\\"playsinline\\\"]),time:new Set([\\\"datetime\\\"]),abbr:new Set([\\\"title\\\"]),q:new Set([\\\"cite\\\"]),blockquote:new Set([\\\"cite\\\"]),table:new Set([\\\"summary\\\"]),th:new Set([\\\"colspan\\\",\\\"rowspan\\\",\\\"scope\\\",\\\"headers\\\",\\\"abbr\\\"]),td:new Set([\\\"colspan\\\",\\\"rowspan\\\",\\\"headers\\\"]),col:new Set([\\\"span\\\"]),colgroup:new Set([\\\"span\\\"]),ol:new Set([\\\"start\\\",\\\"reversed\\\",\\\"type\\\"]),li:new Set([\\\"value\\\"]),code:new Set([\\\"class\\\"]),pre:new Set([\\\"class\\\"])},ni=new Set([\\\"href\\\",\\\"src\\\",\\\"cite\\\",\\\"poster\\\"]),ii=1,ri=8,li=(Error,new Set([\\\"id\\\",\\\"name\\\",\\\"data-payload-key\\\",\\\"data-payload-nested-key\\\",\\\"data-payload-nested-template\\\"])),oi=\\\"strict\\\",ai=(Object.freeze({allowedTags:Jn,removeCompletely:Qn,globalAttributes:Xn,attributesByTag:ti,urlAttributes:ni}),Object.freeze({\\\"&\\\":\\\"&amp;\\\",\\\"<\\\":\\\"&lt;\\\",\\\">\\\":\\\"&gt;\\\",'\\\"':\\\"&quot;\\\",\\\"'\\\":\\\"&#x27;\\\",\\\"/\\\":\\\"&#x2F;\\\",\\\"`\\\":\\\"&#x60;\\\",\\\"=\\\":\\\"&#x3D;\\\"})),si=/[&<>\\\"'/`=]/g,ui=Object.freeze({\\\"&\\\":\\\"&amp;\\\",\\\"<\\\":\\\"&lt;\\\",\\\">\\\":\\\"&gt;\\\",'\\\"':\\\"&quot;\\\",\\\"'\\\":\\\"&#x27;\\\"}),di=/[&<>\\\"']/g,ci=/\\\\{\\\\{([\\\\s\\\\S]*?)\\\\}\\\\}/g,hi=[\\\"input\\\",\\\"textarea\\\",\\\"select\\\",\\\"option\\\",\\\"button\\\",\\\"label\\\",\\\"details\\\",\\\"summary\\\",\\\"dialog\\\",\\\"video\\\",\\\"audio\\\",\\\"progress\\\",\\\"meter\\\"],fi=[\\\"type\\\",\\\"name\\\",\\\"placeholder\\\",\\\"open\\\",\\\"disabled\\\",\\\"readonly\\\",\\\"required\\\",\\\"checked\\\",\\\"selected\\\",\\\"value\\\",\\\"min\\\",\\\"max\\\",\\\"step\\\",\\\"rows\\\",\\\"cols\\\",\\\"for\\\",\\\"controls\\\",\\\"muted\\\",\\\"loop\\\",\\\"poster\\\",\\\"src\\\"],pi=/<([a-z][a-z0-9]*(?:-[a-z0-9]+)+)\\\\b/gi,gi=new Map,mi=\\\"data-payload-key\\\",vi=\\\"data-payload-nested-key\\\",yi=\\\"data-payload-nested-template\\\",bi=class{constructor(e,t,n){wt(this,\\\"deps\\\",e);wt(this,\\\"state\\\",t);wt(this,\\\"host\\\",n)}planFragments(e){let t=this.deps.strategies.fragment;if(void 0===t)return null;let n=t.plan(this.deps.root,e),i=new Set(n);return{boundaries:n,strategy:t,covers:e=>void 0!==e.fragmentBoundary&&i.has(e.fragmentBoundary)}}hasRouteBinding(e){for(let[t,n]of this.deps.cache.entries())if(e.has(t)&&n.some(e=>\\\"route\\\"===e.strategyKind))return!0;return!1}async runFragments(e,t,n){let{deps:i,state:r}=this,l=new AbortController;r.fragmentController=l;let o=()=>r.isCurrent(e)&&!l.signal.aborted,{emitter:a}=i,{message:s}=e,u=e.identity.revision,d=e.receivedAt,c={root:i.root,revision:u,receivedAt:d,fields:t.fields,locale:e.locale,collectionSlug:\\\"string\\\"==typeof s.collectionSlug?s.collectionSlug:void 0,globalSlug:\\\"string\\\"==typeof s.globalSlug?s.globalSlug:void 0,signal:l.signal,isCurrent:o,log:(e,t)=>{i.log(\\\"fragment\\\",e,t)},morph:(e,t)=>{!function(e,t){let n=e.ownerDocument.createElement(\\\"template\\\");n.innerHTML=J(t);let i=e.cloneNode(!1);i.append(n.content),X(e,i,{keyAttributes:[mi]})}(e,t)},patch:n=>{this.patchFallback(e,t,n)},rendered:(t,n,i)=>{e.pendingFragments-=1,a.emitWhile(\\\"fragmentRender\\\",{element:t,id:n,key:i,status:\\\"rendered\\\",revision:u,receivedAt:d},o)},failed:(t,n,i,r,l)=>{e.pendingFragments-=1,a.emitWhile(\\\"error\\\",{error:new Error(`fragment \\\"${n}\\\" fell back to patch: ${l}`),context:\\\"fragment\\\",code:r},o),a.emitWhile(\\\"fragmentRender\\\",{element:t,id:n,key:i,status:\\\"failed\\\",code:r,revision:u,receivedAt:d},o)}},h={rendered:0,failed:0,superseded:0};try{h=await n.strategy.render(c,n.boundaries)}catch(r){if(i.log(\\\"fragment\\\",\\\"LP0801\\\",r),o()){for(let i of n.boundaries)this.patchFallback(e,t,i);h={rendered:0,failed:n.boundaries.length,superseded:0}}}r.fragmentStats.rendered+=h.rendered,r.fragmentStats.failed+=h.failed,r.fragmentStats.superseded+=h.superseded,o()&&(r.fragmentController===l&&(r.fragmentController=null),e.pendingFragments=0,0===i.scheduler.pendingCount&&r.complete(e),this.host.revealPending(e),o()&&(0===h.rendered||0===a.listenerCount(\\\"afterUpdate\\\")||a.emitWhile(\\\"afterUpdate\\\",{data:t,updatedCount:h.rendered,durationMs:Date.now()-d,revision:u,receivedAt:d,source:\\\"fragment\\\"},o)))}async refreshRoute(e,t,n){let{deps:i,state:r}=this,l=r.routeStats;if(e.routeRefreshed){l.loopStopped+=1,i.log(\\\"route\\\",\\\"LP0805\\\",`revision ${String(e.identity.revision)} asked for a second refresh`);return}e.routeRefreshed=!0;let o=new AbortController;r.routeController=o;let a,s=()=>r.isCurrent(e)&&!o.signal.aborted;try{a=await n.refresh({revision:e.identity.revision,receivedAt:e.receivedAt,signal:o.signal,isCurrent:s,log:(e,t)=>{i.log(\\\"route\\\",e,t)}})}catch(e){i.log(\\\"route\\\",\\\"LP0801\\\",e),a=\\\"failed\\\"}if(s()){if(r.routeController===o&&(r.routeController=null),\\\"refreshed\\\"===a){if(l.refreshes+=1,r.lastAppliedIdentity=new WeakMap,this.host.rebuildCache(),!s())return;this.host.reapply(e,t),i.emitter.listenerCount(\\\"afterUpdate\\\")>0&&i.emitter.emitWhile(\\\"afterUpdate\\\",{data:t,updatedCount:i.cache.elementCount,durationMs:Date.now()-e.receivedAt,revision:e.identity.revision,receivedAt:e.receivedAt,source:\\\"route\\\"},s);return}\\\"failed\\\"===a&&(l.failed+=1),this.host.reapply(e,t)}}warnFragmentFallback(e){this.state.warnedFragmentFallback||(this.state.warnedFragmentFallback=!0,this.deps.warn(`[live-preview] LP0806: \\\"${e.fieldName}\\\" asks for the fragment strategy but no handler is configured; patching instead`))}warnUnsupportedStrategy(e){this.state.warnedStrategy.has(e.element)||(this.state.warnedStrategy.add(e.element),this.deps.warn(`[live-preview] LP0407: \\\"${e.fieldName}\\\" asks for strategy \\\"${String(e.strategy)}\\\"; only patch, fragment and route exist`))}patchFallback(e,t,n){for(let[i,r]of this.deps.cache.entries())for(let l of r){if(l.fragmentBoundary!==n)continue;let r=B(t.fields,i,l.locale??e.locale,void 0!==l.locale);void 0!==r&&this.deps.scheduler.schedule({target:l,value:this.host.transform(l,r,t.fields,()=>!0),allFields:t.fields,identity:e.identity,data:t})}}},wi=class{constructor(e,t,n){wt(this,\\\"deps\\\",e);wt(this,\\\"state\\\",t);wt(this,\\\"strategies\\\");this.strategies=new bi(e,t,{reapply:(e,t)=>{this.scheduleAllFields(e,t)},transform:(e,t,n,i)=>this.transformForBinding(e,t,n,i),rebuildCache:n,revealPending:e=>{this.revealPending(e)}})}handleUpdate(e,t,n){let{deps:i,state:r}=this;if(i.heartbeat.kick(),r.protocol.observe(function(e){let t=[];return Array.isArray(e.fieldSchemaJSON)&&t.push(\\\"schema-json\\\"),\\\"string\\\"==typeof e.locale&&t.push(\\\"locale\\\"),\\\"string\\\"==typeof e.previewToken&&t.push(\\\"preview-token\\\"),\\\"object\\\"==typeof e.externallyUpdatedRelationship&&null!==e.externallyUpdatedRelationship&&t.push(\\\"relationship-events\\\"),t}(e),i.log),void 0===e.data){void 0!==e.protocolVersion&&r.protocol.applyVersion(e.protocolVersion,i.log);return}if(void 0===n)return;let l=e.externallyUpdatedRelationship,o=\\\"object\\\"==typeof l&&null!==l;o&&i.emitter.emit(\\\"relationshipUpdate\\\",{detail:l,timestamp:Date.now()}),\\\"string\\\"==typeof e.locale&&(r.locale=e.locale),Array.isArray(e.fieldSchemaJSON)&&(r.schema=e.fieldSchemaJSON,r.schemaIndex=a(e.fieldSchemaJSON));let s={identity:n,message:e,locale:r.locale,schema:r.schema,schemaIndex:r.schemaIndex,receivedAt:Date.now(),forceRender:o,touched:new Set,invalidated:new Set,revealTarget:void 0,revealIdentities:[],pendingFragments:0,routeRefreshed:!1,cancelled:!1,completed:!1},u=r.activeUpdate;r.abortStrategies(),null!==u&&!u.completed&&(r.supersededCount+=1),r.activeUpdate=s,i.scheduler.acceptRevision(n),r.updateCount+=1,(void 0===e.protocolVersion||(r.protocol.applyVersion(e.protocolVersion,i.log),r.isCurrent(s)))&&(i.connection.markConnected()&&(i.a11y?.announceConnected(),i.emitter.emit(\\\"connect\\\",{origin:t,timestamp:Date.now()}),!r.isCurrent(s)||(i.log(\\\"connection\\\",\\\"disconnected\\\",\\\"\\\\u2192\\\",\\\"connected\\\"),!r.isCurrent(s)))||this.processUpdate(s).catch(e=>{i.log(\\\"update failed:\\\",e)}))}async processUpdate(e){let{deps:t,state:n}=this,i=await this.resolveIncomingFields(e);if(null===i||!n.isCurrent(e))return;let{message:r}=e,l={fields:i,...void 0!==e.schema?{schema:e.schema}:{},...\\\"string\\\"==typeof r.globalSlug?{globalSlug:r.globalSlug}:{},...\\\"string\\\"==typeof r.collectionSlug?{collectionSlug:r.collectionSlug}:{},...void 0!==e.locale?{locale:e.locale}:{}};if(t.emitter.listenerCount(\\\"beforeUpdate\\\")>0&&(!await t.emitter.emitWhile(\\\"beforeUpdate\\\",{data:l,revision:e.identity.revision,receivedAt:e.receivedAt,source:\\\"patch\\\",cancel:()=>{e.cancelled=!0,t.scheduler.cancelRevision(e.identity)}},()=>!e.cancelled&&n.isCurrent(e))||e.cancelled||!n.isCurrent(e)))return;let o=w(t.dependencies,t.cache.dependencyMap()),a=n.changes.diff(i,o);e.invalidated=a.invalidated,e.touched=new Set([...a.changed,...a.invalidated]),this.scheduleAllFields(e,l)}async resolveIncomingFields(e){let{deps:t,state:n}=this,i=e.message.data??{};if(null===t.merger||\\\"admin\\\"===E(n.protocol.observed).populatesRelationships)return i;let{message:r}=e,l=await t.merger.merge({collectionSlug:r.collectionSlug,globalSlug:r.globalSlug,data:i,locale:e.locale});return n.isCurrent(e)?\\\"merged\\\"===l.status?l.doc:\\\"superseded\\\"===l.status?null:i:null}scheduleAllFields(e,t){let{deps:n,state:i}=this;if(!i.isCurrent(e))return;let r=()=>i.isCurrent(e),l=this.ownerKeysForUpdate(e,t.fields),{touched:o}=e,a=n.strategies.route;if(void 0!==a&&!e.routeRefreshed&&(a.plan(n.root,o)||this.strategies.hasRouteBinding(o))){this.strategies.refreshRoute(e,t,a);return}let s=this.strategies.planFragments(o),u=n.skipUnchanged,d=0;for(let[o,a]of n.cache.entries()){if(!r())return;for(let c of a){if(!1!==l&&!D(c.owner,l))continue;if(!0===s?.covers(c)){n.revealEditedField&&this.noteRevealCandidate(e,c,this.rawValue(e,c,t));continue}let a=c.strategyKind??C(c.element)??\\\"unknown\\\";if(\\\"unknown\\\"===a){this.strategies.warnUnsupportedStrategy(c);continue}\\\"fragment\\\"===a&&null===s&&this.strategies.warnFragmentFallback(c);let h=B(t.fields,o,c.locale??e.locale,void 0!==c.locale);if(void 0===h){i.absentFields.add(o);continue}if(this.noteRevealCandidate(e,c,h),!r())return;let f=this.transformForBinding(c,h,t.fields,r);if(!r())return;let p=u?Ce(c,f,t.fields,e.locale):void 0,g=i.lastAppliedIdentity.get(c.element);if(!e.forceRender&&n.skipUnchanged&&void 0!==p&&g===p&&!e.invalidated.has(o)){i.skippedUnchangedCount+=1;continue}let m={target:c,value:f,allFields:t.fields,identity:e.identity,data:t,valueIdentity:p};n.scheduler.schedule(m),d+=1}}(function(e,t,n,i){let{cache:r,warned:l,warn:o}=e;if(0===r.fieldCount||!1!==i&&!function(e,t){for(let n of e.values())if(D(n.owner,t))return!0;return!1}(r,i))return;let a;for(let[e,s]of Object.entries(t)){if(l.has(e)||Hn.has(e)||!G(s))continue;let t=q(e,n);H(r,e,i)||t!==e&&H(r,t,i)||(a??(a=z(r,i)),!a.has(e)&&(l.add(e),o(`[live-preview] LP0201: no <\\\\u2026 data-payload-field=\\\"${t}\\\"> for field \\\"${e}\\\"; render the anchor unconditionally so edits to an empty field have somewhere to land.`)))}})({cache:n.cache,warned:i.warnedOrphanFields,warn:n.warn},t.fields,e.locale,l),null!==s&&s.boundaries.length>0&&(e.pendingFragments=s.boundaries.length,this.strategies.runFragments(e,t,s)),0===d&&0===e.pendingFragments&&(i.complete(e),this.revealPending(e))}rawValue(e,t,n){return B(n.fields,t.fieldName,t.locale??e.locale,void 0!==t.locale)}noteRevealCandidate(e,t,n){let{deps:i,state:r}=this;if(!i.revealEditedField)return;let l=m(n);if(void 0===l)return;let o=`${t.owner??\\\"\\\"}\\\\0${t.locale??\\\"\\\"}\\\\0${t.fieldName}`,a=r.seenFieldIdentity.get(o);void 0!==a?a!==l&&(e.revealIdentities.push([o,l]),e.revealTarget??(e.revealTarget=t)):r.seenFieldIdentity.set(o,l)}ownerKeysForUpdate(e,t){let{deps:n,state:i}=this;if(!n.scopeBindingsByOwner)return!1;let{message:r}=e,l=function(e){if(W(e.globalSlug))return[P(e.globalSlug)];if(!W(e.collectionSlug))return null;let t=j(e.collectionSlug);return W(e.documentId)?[t,j(e.collectionSlug,e.documentId)]:[t]}({globalSlug:\\\"string\\\"==typeof r.globalSlug?r.globalSlug:void 0,collectionSlug:\\\"string\\\"==typeof r.collectionSlug?r.collectionSlug:void 0,documentId:V(t)});return null===l&&!i.warnedUnattributableMessage&&(i.warnedUnattributableMessage=!0,n.warn(\\\"[live-preview] LP0202: scopeBindingsByOwner: update names no document; nothing applied\\\")),l}transformForBinding(t,n,i,r){let l=this.deps.transformValue;if(void 0===l)return n;try{let o=l(t.fieldName,n,{element:t.element,allFields:i},r),a=e(o);if(!r())return n;if(a)throw new TypeError(`Transform for \\\"${t.fieldName}\\\" returned a thenable; transforms must be synchronous`);return o}catch(e){if(!r())return n;let t=e instanceof Error?e:new Error(String(e));return this.deps.emitter.emit(\\\"error\\\",{error:t,context:\\\"transform\\\",code:\\\"LP0602\\\"}),n}}onFlush(e){let{deps:t,state:n}=this;n.lastFlush=e,e.deferred>0&&!n.warnedVisibilityGate&&(n.warnedVisibilityGate=!0,t.warn(`[live-preview] LP0301: visibility gate held ${String(e.deferred)} off-screen update(s) until scrolled into view; see visibilityGateThreshold`));let{identity:i,data:r}=e;if(void 0===i)return;let l=n.activeUpdate;if(null===l||!n.isCurrent(l)||!b(l.identity,i))return;0===l.pendingFragments&&n.complete(l);let o=()=>n.isCurrent(l)&&b(l.identity,i);this.revealPending(l),o()&&(0===e.applied||void 0===r||(t.a11y?.announceUpdate(e.applied),o()&&(function(e,t){for(let n of e)n.dispatchEvent(new CustomEvent(\\\"payload-live-preview:update\\\",{detail:t,bubbles:!1}));e.length}(t.cache.islands,{fields:r.fields,revision:i.revision,receivedAt:l.receivedAt,locale:l.locale}),o()&&0!==t.emitter.listenerCount(\\\"afterUpdate\\\")&&t.emitter.emitWhile(\\\"afterUpdate\\\",{data:r,updatedCount:e.applied,durationMs:e.durationMs,revision:i.revision,receivedAt:l.receivedAt,source:\\\"patch\\\"},o))))}revealPending(e){for(let[t,n]of e.revealIdentities)this.state.seenFieldIdentity.set(t,n);e.revealIdentities=[];let t=e.revealTarget;if(void 0!==t){e.revealTarget=void 0;try{this.revealBinding(t)}catch(e){this.deps.log(\\\"reveal\\\",e)}}}revealField(e){let t=this.deps.cache.get(e)?.[0];return void 0===t?\\\"no-element\\\":this.revealBinding(t)}revealBinding(e){let{element:t}=e,n=t.ownerDocument.defaultView;if(null===n)return\\\"no-element\\\";let i=`${e.owner??\\\"\\\"} ${e.fieldName}`;return this.state.revealer.reveal(i,t,n)}},Si=class{constructor(e,t){wt(this,\\\"apply\\\");wt(this,\\\"debounceMs\\\");wt(this,\\\"maxWaitMs\\\");wt(this,\\\"isVisible\\\");wt(this,\\\"gateThresholdValue\\\");wt(this,\\\"gateDisabled\\\");wt(this,\\\"getCacheSize\\\");wt(this,\\\"onFlush\\\");wt(this,\\\"scheduleFrame\\\");wt(this,\\\"cancelFrame\\\");wt(this,\\\"pending\\\",new Map);wt(this,\\\"replay\\\",new Map);wt(this,\\\"activeFlushes\\\",new Set);wt(this,\\\"debounceTimer\\\",null);wt(this,\\\"debounceToken\\\",0);wt(this,\\\"deadlineTimer\\\",null);wt(this,\\\"frameHandle\\\",null);wt(this,\\\"frameToken\\\",0);wt(this,\\\"activeIdentity\\\",null);wt(this,\\\"activeRevisionCancelled\\\",!1);this.apply=e,this.debounceMs=t.debounceMs??50,this.maxWaitMs=t.maxWaitMs??4*this.debounceMs,this.isVisible=t.isVisible,this.gateThresholdValue=t.visibilityGateThreshold??50,this.gateDisabled=t.disableVisibilityGate??!1,this.getCacheSize=t.getCacheSize,this.onFlush=t.onFlush,this.scheduleFrame=t.scheduleFrame??(\\\"function\\\"==typeof requestAnimationFrame?requestAnimationFrame.bind(globalThis):e=>setTimeout(()=>{e(performance.now())},0)),this.cancelFrame=t.cancelFrame??(\\\"function\\\"==typeof cancelAnimationFrame?cancelAnimationFrame.bind(globalThis):e=>{clearTimeout(e)})}schedule(e){if(void 0!==e.identity&&(this.activeRevisionCancelled||!$e(e.identity,this.activeIdentity)))return;let t=this.pending.get(e.target.element);t?(t.value=e.value,t.allFields=e.allFields,t.identity=e.identity,t.data=e.data,t.valueIdentity=e.valueIdentity):this.pending.set(e.target.element,{target:e.target,value:e.value,allFields:e.allFields,identity:e.identity,data:e.data,valueIdentity:e.valueIdentity}),this.armDebounce()}acceptRevision(e){$e(e,this.activeIdentity)||null!==this.activeIdentity&&function(e,t){return e.generation!==t.generation?e.generation-t.generation:e.revision-t.revision}(e,this.activeIdentity)<0||(this.cancelScheduledWork(),this.clearWork(),this.activeIdentity=e,this.activeRevisionCancelled=!1)}cancelRevision(e){$e(e,this.activeIdentity)&&(this.cancelScheduledWork(),this.clearWork(),this.activeRevisionCancelled=!0)}flushNow(){return this.cancelScheduledWork(),this.flush()}notifyVisible(e){let t=this.replay.get(e);if(!t||(this.replay.delete(e),!this.isCurrent(t)))return;let n=performance.now(),i=this.didApply(t)?1:0;this.onFlush?.(this.statsFor(t,i,0,performance.now()-n,1===i?[t.target.fieldName]:[]))}retarget(e){this.retargetBuffer(this.pending,e),this.retargetBuffer(this.replay,e);for(let t of this.activeFlushes)this.retargetBuffer(t,e)}forget(e){this.pending.delete(e),this.replay.delete(e);for(let t of this.activeFlushes)t.delete(e)}destroy(){this.cancelScheduledWork(),this.clearWork(),this.activeIdentity=null,this.activeRevisionCancelled=!1}get pendingCount(){return this.pending.size}get replayCount(){return this.replay.size}get gateThreshold(){return this.gateThresholdValue}get gateActive(){return!this.gateDisabled&&this.getCacheSize()>this.gateThresholdValue}armDebounce(){let e=this.debounceToken+=1,t=this.debounceTimer;if(this.debounceTimer=null,null!==t&&clearTimeout(t),this.debounceToken!==e)return;let n=setTimeout(()=>{this.debounceToken===e&&(this.debounceTimer=null,this.requestFrame())},this.debounceMs);this.debounceToken===e&&(this.debounceTimer=n),null===this.deadlineTimer&&this.maxWaitMs>this.debounceMs&&(this.deadlineTimer=setTimeout(()=>{this.deadlineTimer=null,this.pending.size>0&&this.requestFrame()},this.maxWaitMs))}requestFrame(){let e=this.frameToken+=1,t=this.frameHandle;if(this.frameHandle=null,null!==t&&this.cancelFrame(t),this.frameToken!==e)return;let n=!1,i=this.scheduleFrame(()=>{this.frameToken===e&&(n=!0,this.frameHandle=null,this.flush())});!n&&this.frameToken===e&&(this.frameHandle=i)}flush(){let e=performance.now();this.clearDeadline();let t=this.gateActive,n=this.pending;this.pending=new Map;let i,r=0,l=[],o=0;this.activeFlushes.add(n);try{for(let e of n.values()){if(!this.isCurrent(e))continue;let n=!t||this.isVisible(e.target.element);if(this.isCurrent(e)){if(i??(i=e),!n){this.replay.set(e.target.element,e),o+=1;continue}this.replay.delete(e.target.element),this.didApply(e)&&(r+=1,l.push(e.target.fieldName))}}}finally{this.activeFlushes.delete(n)}let a=this.statsFor(i,r,o,performance.now()-e,l);return this.onFlush?.(a),a}isCurrent(e){return void 0===e.identity||!this.activeRevisionCancelled&&$e(e.identity,this.activeIdentity)}didApply(e){return!1!==this.apply(e)||!function(e){return Kt.has(e)}(this.apply)}retargetBuffer(e,t){let n=e.get(t.element);if(void 0!==n){if(n.target.fieldName!==t.fieldName||n.target.locale!==t.locale){e.delete(t.element);return}n.target=t}}clearWork(){this.pending.clear(),this.replay.clear();for(let e of this.activeFlushes)e.clear()}statsFor(e,t,n,i,r){return{applied:t,appliedFields:r,deferred:n,durationMs:i,...void 0!==e?.identity?{identity:e.identity}:{},...void 0!==e?.data?{data:e.data}:{}}}clearDeadline(){null!==this.deadlineTimer&&(clearTimeout(this.deadlineTimer),this.deadlineTimer=null)}cancelScheduledWork(){let e=this.debounceTimer,t=this.frameHandle;this.debounceToken+=1,this.frameToken+=1,this.debounceTimer=null,this.frameHandle=null,this.clearDeadline(),null!==e&&clearTimeout(e),null!==t&&this.cancelFrame(t)}},ki=[0,500,1e3,2e3],Ti=class{constructor(e){wt(this,\\\"deps\\\");wt(this,\\\"state\\\",new nn);wt(this,\\\"pipeline\\\");wt(this,\\\"writer\\\");wt(this,\\\"rootSentinel\\\",null);wt(this,\\\"observedRoot\\\",null);let{emitter:i,renderers:r}=e,l=void 0===e.log?n:t(e.log),o=void 0===e.warn?Ft:t(e.warn),a=e.root??(typeof document<\\\"u\\\"?document:null),s=new xn({filter:e=>!function(e){let t=e;for(;null!==t;){if(k(t)&&!T(t))return!0;t=t.parentElement}return!1}(e)}),u=new Dn({onStructuralChange:()=>{this.rebuildCache()},onVisibilityChange:(e,t)=>{t&&d.notifyVisible(e)}},void 0!==e.intersectionRootMargin?{intersectionRootMargin:e.intersectionRootMargin}:{}),d=new Si(g(e=>this.writer.apply(e)),{...void 0!==e.debounceMs?{debounceMs:e.debounceMs}:{},...void 0!==e.disableVisibilityGate?{disableVisibilityGate:e.disableVisibilityGate}:{},...void 0!==e.visibilityGateThreshold?{visibilityGateThreshold:e.visibilityGateThreshold}:{},isVisible:e=>u.isVisible(e),getCacheSize:()=>s.elementCount,onFlush:e=>{this.pipeline.onFlush(e)}}),c=new jn(e.originMatcher,{onUpdate:(e,t,n)=>{this.pipeline.handleUpdate(e,t,n)},onDocumentEvent:()=>{this.state.protocol.observe([\\\"document-events\\\"],l),i.emit(\\\"documentSave\\\",{timestamp:Date.now()})},onFocusField:e=>{this.deps.revealEditedField&&this.pipeline.revealField(e)},onInvalid:(e,t)=>{if(\\\"token\\\"===e){let e=new Error(`Preview token rejected (origin: ${t})`);i.emit(\\\"error\\\",{error:e,context:\\\"token\\\",code:\\\"LP0502\\\"})}l(\\\"LP0501 message rejected:\\\",e,t)},...void 0!==e.validateToken?{validateToken:e.validateToken}:{},...void 0!==e.eventSourcePolicy?{sourcePolicy:e.eventSourcePolicy}:{}}),h=e.dataMerge;this.deps={emitter:i,cache:s,observers:u,scheduler:d,bus:c,connection:new Bn,heartbeat:new Vn({...void 0!==e.heartbeatMs?{timeoutMs:e.heartbeatMs}:{},onTimeout:()=>{this.onHeartbeatTimeout()}}),renderers:r,resolveRenderer:e.resolveRenderer??(e=>r[e]),transformValue:e.transformValue,renderRichText:e.renderRichText,root:a,readyTargets:\\\"function\\\"==typeof e.readyTargets?e.readyTargets:(e=>()=>e)(e.readyTargets),sendReady:e.sendReady??Me,onHeartbeatTimeout:e.onHeartbeatTimeout,log:l,warn:o,a11y:Fe(e),merger:void 0===h?null:new En({serverURL:h.serverURL,...void 0!==h.apiRoute?{apiRoute:h.apiRoute}:{},...void 0!==h.depth?{depth:h.depth}:{},...void 0!==h.fetchFn?{fetchFn:h.fetchFn}:{},log:l}),scopeBindingsByOwner:!0===e.scopeBindingsByOwner,lockedOrigin:e.lockedOrigin??(()=>{}),skipUnchanged:!0===e.skipUnchanged,dependencies:e.dependencies??{},strategies:e.strategies??{},revealEditedField:!0===e.revealEditedField},this.writer=new rn(this.deps,this.state),this.pipeline=new wi(this.deps,this.state,()=>{this.rebuildCache()})}start(){let{state:e,deps:t}=this;if(e.isRunning())return!1;if(e.started=!0,e.suspended=!1,Re(t.root)&&\\\"loading\\\"===t.root.readyState){let n=()=>{if(e.isRunning()){e.deferredStart=null;try{this.startNow()}catch(e){this.rollbackFailedStart(),this.reportError(e,\\\"startup\\\",\\\"LP0605\\\")}}};e.deferredStart=n;try{t.root.addEventListener(\\\"DOMContentLoaded\\\",n,{once:!0})}catch(e){throw this.rollbackFailedStart(),e}return!0}try{return this.startNow(),!0}catch(e){throw this.rollbackFailedStart(),e}}startNow(){let{state:e,deps:t}=this;if(!e.isRunning())return;let n=Re(t.root)?Ne(t.root):t.root;if(null===n)throw new Error(\\\"LivePreviewRuntime: document.body unavailable\\\");if(t.observers.start(n),this.observedRoot=n,this.watchRootReplacement(),this.buildCacheAndObserve(),e.isRunning()&&(t.bus.attach(),t.emitter.emitWhile(\\\"init\\\",{timestamp:Date.now()},()=>e.isRunning()),e.isRunning()))for(let n of ki){if(!e.isRunning())return;0===n?t.sendReady(t.readyTargets()):e.readyTimers.push(setTimeout(()=>{e.isRunning()&&this.sendReadyAfterStart()},n))}}suspend(){if(!this.state.isRunning())return!1;let e=this.release();return this.state.suspended=!0,e&&this.deps.emitter.emit(\\\"disconnect\\\",{reason:\\\"unload\\\",timestamp:Date.now()}),!0}destroy(){let{state:e,deps:t}=this;if(!e.isRunning()&&!e.suspended)return;let n=!!e.isRunning()&&this.release();e.suspended=!1,n&&t.emitter.emit(\\\"disconnect\\\",{reason:\\\"destroy\\\",timestamp:Date.now()}),t.a11y?.detach(),t.emitter.emit(\\\"destroy\\\",{timestamp:Date.now()})}release(){let{state:e,deps:t}=this;e.activeUpdate=null,e.started=!1;let n=e.deferredStart;e.deferredStart=null,null!==n&&Re(t.root)&&this.runCleanup(()=>{t.root.removeEventListener(\\\"DOMContentLoaded\\\",n)});for(let t of e.readyTimers)this.runCleanup(()=>{clearTimeout(t)});return e.readyTimers.length=0,this.runCleanup(()=>{t.heartbeat.stop()}),this.runCleanup(()=>{t.bus.detach()}),e.abortStrategies(),this.runCleanup(()=>{this.rootSentinel?.disconnect(),this.rootSentinel=null,this.observedRoot=null}),this.runCleanup(()=>{t.observers.stop()}),this.runCleanup(()=>{t.scheduler.destroy()}),this.runCleanup(()=>{t.merger?.destroy()}),t.cache.clear(),t.connection.markDisconnected()}rollbackFailedStart(){this.release(),this.runCleanup(()=>{this.deps.a11y?.detach()})}runCleanup(e){try{e()}catch(e){this.deps.log(\\\"cleanup failed:\\\",e)}}refreshCache(){this.state.isRunning()&&(this.state.revealer.reset(),this.followReplacedRoot()||this.rebuildCache())}watchRootReplacement(){let{root:e}=this.deps;!Re(e)||typeof MutationObserver>\\\"u\\\"||(this.rootSentinel?.disconnect(),this.rootSentinel=new MutationObserver(()=>{this.followReplacedRoot()}),this.rootSentinel.observe(e.documentElement,{childList:!0}))}followReplacedRoot(){let{root:e}=this.deps;if(!this.state.isRunning()||!Re(e))return!1;let t=Ne(e);return null!==t&&t!==this.observedRoot&&(this.observedRoot=t,this.deps.observers.start(t),this.rebuildCache(),!0)}get status(){return this.deps.connection.status}get cache(){return this.deps.cache}get updateCount(){return this.state.updateCount}get protocol(){return this.state.protocol.negotiation}inspect(){return function(e,t){let{cache:n,scheduler:i}=e,r=t.protocol.negotiation,l=t.activeUpdate,o=t.lastFlush,a=[],s=new Set;for(let[e,t]of n.entries()){a.push(e);for(let e of t)void 0!==e.owner&&s.add(e.owner)}return{version:In,started:t.started,status:e.connection.status,origins:{trusted:[...e.readyTargets()],locked:e.lockedOrigin()},protocol:{ours:r.ours,theirs:r.theirs,negotiated:r.negotiated,capabilities:[...r.capabilities].sort(),observed:[...r.observed].sort(),profile:E(r.observed).name},revisions:{accepted:t.updateCount,superseded:t.supersededCount,completed:t.completedCount,skippedUnchanged:t.skippedUnchangedCount,active:null===l?void 0:l.identity.revision},bindings:{elements:n.elementCount,fields:n.fieldCount,fieldNames:a.sort(),absentFields:[...t.absentFields].sort(),orphanFields:[...t.warnedOrphanFields].sort(),ownerScoped:e.scopeBindingsByOwner,owners:[...s].sort()},route:{handler:void 0!==e.strategies.route,...t.routeStats},fragments:{handler:void 0!==e.strategies.fragment,inFlight:l?.pendingFragments??0,...t.fragmentStats},scheduler:{pending:i.pendingCount,deferred:i.replayCount,visibilityGateThreshold:i.gateThreshold,visibilityGateActive:i.gateActive,lastFlush:null===o?void 0:{applied:o.applied,appliedFields:o.appliedFields,deferred:o.deferred,durationMs:o.durationMs}},plugins:[],renderers:Object.keys(e.renderers).sort()}}(this.deps,this.state)}buildCacheAndObserve(){let{state:e,deps:t}=this;if(!e.isRunning())return;let n=t.cache.buildFromRoot(t.root);if(t.log(\\\"cache\\\",n),e.isRunning()&&(t.emitter.emitWhile(\\\"cacheRefresh\\\",n,()=>e.isRunning()),e.isRunning()))for(let n of t.cache.values()){if(!e.isRunning())return;t.observers.observeElement(n.element)}}rebuildCache(){let{state:e,deps:t}=this;if(!e.isRunning())return;let n=new Map;for(let e of t.cache.values())n.set(e.element,e),t.observers.unobserveElement(e.element);if(this.buildCacheAndObserve(),e.isRunning()){for(let e of t.cache.values())n.get(e.element)?.fieldName===e.fieldName?t.scheduler.retarget(e):t.scheduler.forget(e.element),n.delete(e.element);for(let e of n.values())t.scheduler.forget(e.element)}}onHeartbeatTimeout(){let{state:e,deps:t}=this;if(!e.isRunning())return;t.bus.advanceGeneration();let n=e.activeUpdate;e.activeUpdate=null,null!==n&&t.scheduler.cancelRevision(n.identity),t.merger?.destroy();let i=t.connection.markDisconnected();try{t.onHeartbeatTimeout?.()}catch(e){t.log(\\\"heartbeat:\\\",e)}e.isRunning()&&(i&&this.isIdleDisconnected()&&(t.a11y?.announceDisconnected(),t.emitter.emitWhile(\\\"disconnect\\\",{reason:\\\"timeout\\\",timestamp:Date.now()},()=>this.isIdleDisconnected()),!e.isRunning()||(this.isIdleDisconnected()&&t.log(\\\"connection\\\",\\\"connected\\\",\\\"\\\\u2192\\\",\\\"disconnected\\\"),!e.isRunning()))||this.sendReadyAfterStart())}sendReadyAfterStart(){try{this.deps.sendReady(this.deps.readyTargets())}catch(e){this.reportError(e,\\\"ready\\\",\\\"LP0606\\\")}}reportError(e,t,n){let i=e instanceof Error?e:new Error(String(e));this.deps.emitter.emit(\\\"error\\\",{error:i,context:t,code:n})}isIdleDisconnected(){return this.state.isRunning()&&\\\"disconnected\\\"===this.deps.connection.status&&null===this.state.activeUpdate}},Ai=/^https?:\\\\/\\\\/(localhost|127\\\\.0\\\\.0\\\\.1)(?::\\\\d+)?$/i,Ci=/^https?:\\\\/\\\\/[^/?#\\\\s]+$/i,$i=[3e3,3001,3333,4e3,4321,5e3,5173,5174,8e3,8080,8888,9e3],Fi=class{constructor(e={}){Tt(this,Ri);let t=new Set;for(let n of e.additionalOrigins??[]){let e=Ee(n);void 0!==e&&t.add(e)}let n;if(e.enableReferrerDetection??1){let t=e.referrer??(typeof document<\\\"u\\\"?document.referrer:\\\"\\\");if(t.length>0)try{let e=new URL(t).origin;e&&\\\"null\\\"!==e&&(n=e)}catch{}}let i=(e.enableLocalhostMatching??!0)&&(e.forceDevMode??function(){let e=function(){if(!(typeof process>\\\"u\\\"))return\\\"production\\\"}();if(void 0!==e)return\\\"production\\\"!==e;if(typeof window<\\\"u\\\"){let e=window.location.hostname;return\\\"localhost\\\"===e||\\\"127.0.0.1\\\"===e}return!1}());At(this,Ri,[t,n,i,void 0!==n,void 0])}matches(e){return 0!==e.length&&\\\"null\\\"!==e&&(void 0!==kt(this,Ri)[4]?e===kt(this,Ri)[4]:!!(kt(this,Ri)[0].has(e)||0===kt(this,Ri)[0].size&&void 0!==kt(this,Ri)[1]&&e===kt(this,Ri)[1]||kt(this,Ri)[2]&&Ai.test(e)))}lockOrigin(e){return!!this.matches(e)&&(kt(this,Ri)[4]=e,!0)}unlockOrigin(){let e=kt(this,Ri)[4];return kt(this,Ri)[4]=void 0,e}get lockedOrigin(){return kt(this,Ri)[4]}enumerate(){if(void 0!==kt(this,Ri)[4])return[kt(this,Ri)[4]];let e=new Set(kt(this,Ri)[0]);if(0===kt(this,Ri)[0].size&&void 0!==kt(this,Ri)[1]&&e.add(kt(this,Ri)[1]),kt(this,Ri)[2])for(let t of $i)e.add(`http://localhost:${String(t)}`),e.add(`http://127.0.0.1:${String(t)}`);return[...e]}get referrerWasAvailable(){return kt(this,Ri)[3]}get isProductionUnconfigured(){return!(!xe()||kt(this,Ri)[0].size>0||kt(this,Ri)[2]||void 0!==kt(this,Ri)[1])}get isReferrerOnlyTrust(){return!(kt(this,Ri)[0].size>0||kt(this,Ri)[2])&&void 0!==kt(this,Ri)[1]}},Ri=new WeakMap,Ni={1:\\\"left\\\",2:\\\"center\\\",3:\\\"right\\\",4:\\\"justify\\\"},Mi=new Set([\\\"left\\\",\\\"center\\\",\\\"right\\\",\\\"justify\\\",\\\"start\\\",\\\"end\\\"]),xi=new Set([\\\"h1\\\",\\\"h2\\\",\\\"h3\\\",\\\"h4\\\",\\\"h5\\\",\\\"h6\\\"]),Ei=' target=\\\"_blank\\\" rel=\\\"noopener noreferrer\\\"',Ii=(e,t)=>{let n=t.renderChildren(e.children??[]),i=Pe(e.fields),r=function(e,t){if(\\\"internal\\\"===t?.linkType)return function(e){let t=Pe(Pe(e)?.value),n=t?.url;if(\\\"string\\\"==typeof n&&n.length>0)return n;let i=t?.slug;return\\\"string\\\"==typeof i&&i.length>0?`/${i}`:void 0}(t.doc);let n=t?.url??e.url;return\\\"string\\\"==typeof n&&n.length>0?n:void 0}(e,i);if(void 0===r||!f(r))return n;let l=\\\"string\\\"==typeof e.title?` title=\\\"${oe(e.title)}\\\"`:\\\"\\\";return`<a href=\\\"${ae(r)}\\\"${function(e,t,n){if(!0===t?.newTab||p(n))return Ei;let i=\\\"string\\\"==typeof e.target?e.target:\\\"\\\";return\\\"\\\"===i?\\\"\\\":\\\"_blank\\\"===i?Ei:` target=\\\"${oe(i)}\\\"`}(e,i,r)}${l}>${n}</a>`},Li=new Map,Oi={text:e=>{let t=oe(\\\"string\\\"==typeof e.text?e.text:\\\"\\\"),n=\\\"number\\\"==typeof e.format?e.format:0;return!!(16&n)&&(t=`<code>${t}</code>`),!!(1&n)&&(t=`<strong>${t}</strong>`),!!(2&n)&&(t=`<em>${t}</em>`),!!(8&n)&&(t=`<u>${t}</u>`),!!(4&n)&&(t=`<s>${t}</s>`),!!(32&n)&&(t=`<sub>${t}</sub>`),!!(64&n)&&(t=`<sup>${t}</sup>`),!!(128&n)&&(t=`<mark>${t}</mark>`),t},paragraph:(e,t)=>{let n=t.renderChildren(e.children??[]);return`<p${Oe(e)}${Ue(e)}>${n}</p>`},heading:(e,t)=>{let n=\\\"string\\\"==typeof e.tag?e.tag.toLowerCase():\\\"h2\\\",i=xi.has(n)?n:\\\"h2\\\",r=t.renderChildren(e.children??[]);return`<${i}${Oe(e)}${Ue(e)}>${r}</${i}>`},list:(e,t)=>{let n=\\\"string\\\"==typeof e.listType?e.listType:\\\"bullet\\\",i=\\\"number\\\"===n?\\\"ol\\\":\\\"ul\\\",r=\\\"number\\\"===n&&\\\"number\\\"==typeof e.start&&e.start>1?` start=\\\"${String(e.start)}\\\"`:\\\"\\\",l=\\\"check\\\"===n?' role=\\\"list\\\"':\\\"\\\",o=t.renderChildren(e.children??[]);return`<${i}${Oe(e)}${Ue(e)}${r}${l}>${o}</${i}>`},listitem:(e,t)=>{let n=t.renderChildren(e.children??[]);if(\\\"boolean\\\"==typeof e.checked)return`<li role=\\\"checkbox\\\" aria-checked=\\\"${e.checked?\\\"true\\\":\\\"false\\\"}\\\"${Ue(e)}>${n}</li>`;let i=\\\"number\\\"==typeof e.value?` value=\\\"${oe(String(e.value))}\\\"`:\\\"\\\";return`<li${Oe(e)}${Ue(e)}${i}>${n}</li>`},link:Ii,autolink:Ii,quote:(e,t)=>{let n=t.renderChildren(e.children??[]);return`<blockquote${Oe(e)}${Ue(e)}>${n}</blockquote>`},code:e=>{let t=We(\\\"string\\\"==typeof e.language?e.language:\\\"\\\");return`<pre><code${\\\"\\\"===t?\\\"\\\":` class=\\\"language-${t}\\\"`}>${oe(Be(e))}</code></pre>`},\\\"code-highlight\\\":e=>{let t=\\\"string\\\"==typeof e.text?e.text:\\\"\\\";return`<span${\\\"string\\\"==typeof e.highlightType?` class=\\\"token-${We(e.highlightType)}\\\"`:\\\"\\\"}>${oe(t)}</span>`},linebreak:()=>\\\"<br>\\\",horizontalrule:()=>\\\"<hr>\\\",tab:()=>\\\"\\\\t\\\",upload:e=>{let t=je(e.value);if(void 0===t)return\\\"\\\";let n=t.url;if(\\\"string\\\"!=typeof n||!f(n))return\\\"\\\";let i=\\\"string\\\"==typeof t.mimeType?t.mimeType:\\\"\\\";return i.startsWith(\\\"video/\\\")?function(e,t){return`<video controls${_e(e)}><source src=\\\"${ae(t)}\\\"${He(e)}></video>`}(t,n):i.startsWith(\\\"audio/\\\")?function(e,t){return`<audio controls><source src=\\\"${ae(t)}\\\"${He(e)}></audio>`}(t,n):\\\"\\\"===i||i.startsWith(\\\"image/\\\")?function(e,t){let n=\\\"string\\\"==typeof e.alt?oe(e.alt):\\\"\\\";return`<img src=\\\"${ae(t)}\\\" alt=\\\"${n}\\\"${_e(e)} loading=\\\"lazy\\\" decoding=\\\"async\\\">`}(t,n):function(e,t){let n=\\\"string\\\"==typeof e.filename?oe(e.filename):oe(t);return`<a href=\\\"${ae(t)}\\\" target=\\\"_blank\\\" rel=\\\"noopener noreferrer\\\">${n}</a>`}(t,n)},relationship:e=>{let t=\\\"string\\\"==typeof e.relationTo?e.relationTo:\\\"\\\",n=Pe(e.value),i=oe((n&&Ve(n))??`#${t}`),r=We(t),l=\\\"\\\"===r?' class=\\\"lp-relation\\\"':` class=\\\"lp-relation lp-relation--${r}\\\"`,o=n?.url;return\\\"string\\\"==typeof o&&f(o)?`<a href=\\\"${ae(o)}\\\"${l}>${i}</a>`:`<span${l}>${i}</span>`},block:(e,t)=>Ge(e,t,\\\"div\\\",\\\"lp-block\\\"),inlineBlock:(e,t)=>Ge(e,t,\\\"span\\\",\\\"lp-inline-block\\\"),table:(e,t)=>`<table${Oe(e)}><tbody>${t.renderChildren(e.children??[])}</tbody></table>`,tablerow:(e,t)=>`<tr>${t.renderChildren(e.children??[])}</tr>`,tablecell:(e,t)=>{let n=\\\"number\\\"==typeof e.headerState?e.headerState:0,i=3&n?\\\"th\\\":\\\"td\\\";return`<${i}${1===n?' scope=\\\"col\\\"':2===n?' scope=\\\"row\\\"':\\\"\\\"}${qe(\\\"colspan\\\",e.colSpan)}${qe(\\\"rowspan\\\",e.rowSpan)}>${t.renderChildren(e.children??[])}</${i}>`}},Ui=new Map,Pi={renderChildren:Ke,resolveAlignment:Ie,resolveIndent:Le},ji=!1,Wi=\\\"data-payload-text\\\",Di={name:\\\"richText\\\",render:g((e,t,n)=>{let i=e.element;if(de(t))i.textContent=\\\"\\\";else{if(void 0!==n.renderRichText){let r=n.renderRichText(t,{fieldName:e.fieldName,element:i,locale:n.locale});i.innerHTML=J(te(r));return}if(Je(t))i.innerHTML=J(function(e,t={}){if(!Je(e))return\\\"\\\";let n=Ke(e.root.children);return!1===t.sanitize?n:void 0!==ne()?te(n):(function(){if(!ji){ji=!0;try{console.warn(\\\"[live-preview] lexicalToHtml() has no sanitizer document and returned unsanitised HTML; call setSanitizerDocument() (linkedom/jsdom) for server rendering, see docs/security.md \\\\xa73.\\\")}catch{}}}(),n)}(t));else{if(\\\"string\\\"!=typeof t)return!1;i.innerHTML=J(te(t))}}})},Vi={name:\\\"html\\\",render(e,t){if(de(t)){e.element.textContent=\\\"\\\";return}let n=\\\"string\\\"==typeof t?t:ue(t);e.element.innerHTML=J(te(n))}},Bi=new WeakSet,_i=et(\\\"url\\\"),Hi=/^[a-zA-Z][a-zA-Z0-9+.-]*:/,zi=et(\\\"email\\\",function(e){let t=e.trim();return Hi.test(t)||!t.includes(\\\"@\\\")?t:`mailto:${t}`}),Gi=[\\\"src\\\",\\\"srcset\\\",\\\"sizes\\\"],qi={name:\\\"image\\\",render:g((e,t,n)=>{let i=e.element;if(de(t)){rt(i);return}let r=void 0!==e.locale,{media:l,candidate:o}=function(e,t,n,i){let r=void 0!==e.srcField&&e.srcField.length>0?B(n.allFields,e.srcField,n.locale,i):t,l=je(r);return{media:l,candidate:void 0===l?r:l.url}}(e,t,n,r),a=Ye(i,e.fieldName,o);if(\\\"none\\\"===a.kind)return!1;if(\\\"unsafe\\\"!==a.kind){if(\\\"IMG\\\"===i.tagName){let t=i;nt(t,a.url,l);let o=function(e,t,n,i,r){if(void 0!==t&&t.length>0){let e=B(n,t,i,r);return\\\"string\\\"==typeof e?e:void 0}return e?.alt}(l,e.altField,n.allFields,n.locale,r);void 0!==o&&(t.alt=o);return}i.style.backgroundImage=`url('${function(e){return e.replace(/['\\\"()\\\\\\\\]/g,\\\"\\\\\\\\$&\\\")}(a.url)}')`}else rt(i)})},Ji={name:\\\"upload\\\",render:g((e,t)=>{let n=e.element;if(de(t)){lt(n);return}let i=je(t);if(void 0===i)return!1;let r=Ye(n,e.fieldName,i.url);if(\\\"none\\\"===r.kind)return!1;if(\\\"unsafe\\\"===r.kind){lt(n);return}let l=r.url;if(\\\"IMG\\\"===n.tagName){let e=n;nt(e,l,i),void 0!==i.alt&&(e.alt=i.alt);return}if(\\\"A\\\"===n.tagName){n.setAttribute(\\\"href\\\",l),n.textContent=i.filename??l;return}let o=oe(i.filename??l);n.innerHTML=J(`<a href=\\\"${ae(l)}\\\">${o}</a>`)})},Ki={name:\\\"relationship\\\",render(e,t){let n=e.element;if(de(t))n.removeAttribute(\\\"href\\\"),n.textContent=\\\"\\\";else{if(\\\"A\\\"===n.tagName&&!Array.isArray(t)){let i=Ye(n,e.fieldName,Pe(t)?.url);\\\"safe\\\"===i.kind?n.setAttribute(\\\"href\\\",i.url):\\\"unsafe\\\"===i.kind&&n.removeAttribute(\\\"href\\\")}n.textContent=Array.isArray(t)?t.map(ot).join(\\\", \\\"):ot(t)}}},Qi={name:\\\"select\\\",render(e,t,n){let i=e.element,r=de(t)?[]:function(e){return Array.isArray(e)?e.map(ue):[ue(e)]}(t);if(\\\"SELECT\\\"!==i.tagName){if(\\\"INPUT\\\"===i.tagName&&\\\"radio\\\"===i.type){let e=i;e.checked=r.includes(e.value);return}i.textContent=r.map(e=>function(e,t){let n=t.schema?.options;if(!Array.isArray(n))return e;for(let t of n){let n=Pe(t);if(void 0!==n&&ue(n.value)===e)return\\\"string\\\"==typeof n.label?n.label:e}return e}(e,n)).join(\\\", \\\")}else!function(e,t){if(e.multiple)for(let n of Array.from(e.options))n.selected=t.includes(n.value);else e.value=t[0]??\\\"\\\"}(i,r)}},Xi=new Set([\\\"\\\",\\\"false\\\",\\\"0\\\",\\\"off\\\",\\\"no\\\"]),Zi={name:\\\"checkbox\\\",render(e,t){let n=e.element,i=function(e){return\\\"boolean\\\"==typeof e?e:\\\"string\\\"==typeof e?!Xi.has(e.trim().toLowerCase()):\\\"number\\\"==typeof e?0!==e:null!=e}(t);\\\"INPUT\\\"!==n.tagName||\\\"checkbox\\\"!==n.type?n.hasAttribute(\\\"aria-checked\\\")?n.setAttribute(\\\"aria-checked\\\",i?\\\"true\\\":\\\"false\\\"):n.textContent=i?\\\"true\\\":\\\"false\\\":n.checked=i}},Yi=new Map,er=new Map,tr=64,nr={name:\\\"date\\\",render(e,t,n){let r=e.element;if(de(t)){\\\"INPUT\\\"===r.tagName?r.value=\\\"\\\":(r.removeAttribute(\\\"datetime\\\"),r.textContent=\\\"\\\");return}let l=\\\"number\\\"==typeof t?t:ue(t),o=new Date(l),a=!Number.isNaN(o.getTime()),s=String(l);\\\"INPUT\\\"!==r.tagName?(\\\"TIME\\\"===r.tagName&&r.setAttribute(\\\"datetime\\\",a?o.toISOString():s),r.textContent=a?function(e,t){let n=t.locale??i();try{return function(e,t){let n=at(e,t),i=er.get(n);if(void 0!==i)return er.delete(n),er.set(n,i),i;let r=new Intl.DateTimeFormat(e,t);return er.set(n,r),ut(er),r}(n,{dateStyle:\\\"medium\\\",timeStyle:\\\"short\\\"}).format(e)}catch{return e.toISOString()}}(o,n):s):r.value=a?function(e,t){let n=`${String(t.getFullYear()).padStart(4,\\\"0\\\")}-${dt(t.getMonth()+1)}-${dt(t.getDate())}`,i=`${dt(t.getHours())}:${dt(t.getMinutes())}`;return\\\"date\\\"===e?n:\\\"datetime-local\\\"===e?`${n}T${i}`:\\\"time\\\"===e?i:t.toISOString()}(r.type,o):s}},ir={name:\\\"number\\\",render(e,t,n){let r=e.element;if(de(t)){\\\"INPUT\\\"===r.tagName?r.value=\\\"\\\":r.textContent=\\\"\\\";return}let l=\\\"number\\\"==typeof t?t:Number(ue(t));Number.isNaN(l)?r.textContent=ue(t):\\\"INPUT\\\"!==r.tagName?r.textContent=function(e,t){let n=t.locale??i();try{return function(e,t){let n=at(e,t),i=Yi.get(n);if(void 0!==i)return Yi.delete(n),Yi.set(n,i),i;let r=new Intl.NumberFormat(e,t);return Yi.set(n,r),ut(Yi),r}(n).format(e)}catch{return String(e)}}(l,n):r.value=String(l)}},rr={name:\\\"array\\\",render:g((e,t)=>{let n=e.element;if(de(t)){n.textContent=\\\"\\\";return}if(!Array.isArray(t))return!1;let i=e.arrayTemplate;if(void 0!==i&&i.length>0){let e=function(e,t){let n=\\\"\\\";for(let i=0;i<t.length;i+=1)n+=se(e,t[i],i,ue);return n}(i,t);n.innerHTML=J(te(e,ce(i)));return}n.textContent=t.map(ue).join(e.arraySeparator??\\\", \\\")})},lr=new Map;!function(){if(typeof window>\\\"u\\\"||!xe()&&(typeof window>\\\"u\\\"||null==window.opener))return;let e=window.__livePreview,t=JSON.stringify(mt());if(void 0!==e&&(void 0===e.configSignature||e.configSignature===t))return e.refresh(),e;let[n=[],i=\\\"\\\",r=\\\"/api\\\",l=1,o=!1,a=50,s=!0,u=0,d=!1,c=50,h=\\\"200px\\\",f=!0,p=!1,g=!1,m=!0,v=\\\"parent-or-opener\\\",y=\\\"strict\\\",b,w=!1]=mt(),S=typeof __LIVE_PREVIEW_FRAGMENT__<\\\"u\\\"&&\\\"string\\\"==typeof b&&b.length>0?{fragment:__LIVE_PREVIEW_FRAGMENT__.createFragmentStrategy({endpoint:b}),route:__LIVE_PREVIEW_FRAGMENT__.createRouteStrategy()}:void 0;!function(e){oi=e}(y);let k=new Fi({additionalOrigins:n,enableReferrerDetection:!f,enableLocalhostMatching:!p});k.isProductionUnconfigured?Ft(\\\"[live-preview] LP0101: No trusted origin. Pass allowedOrigins to generateInlineScript() (or to the adapter) \\\\u2014 the runtime reads no environment variable in the browser.\\\"):k.isReferrerOnlyTrust&&Ft(\\\"[live-preview] LP0102: document.referrer fallback trusts any framing site. Set allowedOrigins and a frame-ancestors CSP in production.\\\");let T=new Nt,A=function(){let e=[Di,Vi,_i,zi,qi,Ji,Ki,Qi,{...Qi,name:\\\"radio\\\"},Zi,nr,ir,rr,{...rr,name:\\\"blocks\\\"}];return function(e=[]){let t={};for(let n of e)t[n.name]=n;for(let[e,n]of lr)t[e]=n;return Object.freeze(t)}([Ze(\\\"text\\\"),Ze(\\\"textarea\\\"),...e,ct()])}(),C=new Ti({renderers:A,originMatcher:e=>k.matches(e),lockedOrigin:()=>k.lockedOrigin,readyTargets:()=>k.enumerate(),emitter:T,eventSourcePolicy:v,...\\\"\\\"!==i?{dataMerge:{serverURL:i,apiRoute:r,depth:l}}:{},debounceMs:a,heartbeatMs:u,intersectionRootMargin:h,disableVisibilityGate:d,visibilityGateThreshold:c,enableA11y:s,scopeBindingsByOwner:g,skipUnchanged:m,revealEditedField:w,...void 0!==S?{strategies:S}:{},onHeartbeatTimeout:()=>{k.unlockOrigin()},...o?{log:(...e)=>{Rt(\\\"[live-preview]\\\",...e)}}:{}});T.on(\\\"connect\\\",e=>{k.lockOrigin(e.origin)}),C.start(),e?.destroy();let $=function(e,t={}){let n=t.windowTarget??globalThis.window,i=t.documentTarget??globalThis.document,r=t.softNavigationEvents??[],l=()=>{e.suspend()},o=t=>{!0===t.persisted&&e.resume()},a=()=>{e.refreshCache()};n?.addEventListener(\\\"pagehide\\\",l),n?.addEventListener(\\\"pageshow\\\",o);for(let e of r)i?.addEventListener(e,a);let s=!1;return()=>{if(!s){s=!0,n?.removeEventListener(\\\"pagehide\\\",l),n?.removeEventListener(\\\"pageshow\\\",o);for(let e of r)i?.removeEventListener(e,a)}}}({suspend:()=>C.suspend(),resume:()=>C.start(),refreshCache:()=>{C.refreshCache()}}),F=Object.freeze({version:In,configSignature:t,destroy:()=>{$(),C.destroy();let e=window;e.__livePreview===F&&delete e.__livePreview},refresh:()=>{C.refreshCache()},enumerateOrigins:()=>k.enumerate(),inspect:()=>C.inspect()});try{Object.defineProperty(window,\\\"__livePreview\\\",{value:F,writable:!1,configurable:!0})}catch(e){throw $(),C.destroy(),e}}()})();\";\nexport const RUNTIME_CONTENT_HASH = \"1185dfbfe640ed73\";\nexport const RUNTIME_INTEGRITY = \"sha384-I9LyG2ZEhry95cbM0dFAWbkM9q9GaWoapFEJ00ko1Xzv+rrGIl0X/yUSu1QLDOI+\";\nexport const RUNTIME_BUILD_INFO: RuntimeBuildInfo = { generatedAt: \"2026-09-04T21:17:52.000Z\", size: 93041 };\n","// Auto-generated by scripts/build-runtime.ts — do not edit.\nexport const FRAGMENT_SOURCE = \"\\\"use strict\\\";var __LIVE_PREVIEW_FRAGMENT__=(()=>{var N=Object.defineProperty;var J=Object.getOwnPropertyDescriptor;var Q=Object.getOwnPropertyNames;var Z=Object.prototype.hasOwnProperty;var ee=(e,n)=>{for(var t in n)N(e,t,{get:n[t],enumerable:!0})},ne=(e,n,t,o)=>{if(n&&typeof n==\\\"object\\\"||typeof n==\\\"function\\\")for(let r of Q(n))!Z.call(e,r)&&r!==t&&N(e,r,{get:()=>n[r],enumerable:!(o=J(n,r))||o.enumerable});return e};var te=e=>ne(N({},\\\"__esModule\\\",{value:!0}),e);var De={};ee(De,{createFragmentStrategy:()=>z,createRouteStrategy:()=>X});var R=\\\"data-payload-island\\\",Pe=`astro-island, [${R}]`;function re(e){return e.tagName.toLowerCase()===\\\"astro-island\\\"||e.hasAttribute(R)}function oe(e){return e.getAttribute(R)===\\\"patch\\\"}function _(e){let n=e;for(;n!==null;){if(re(n)&&!oe(n))return!0;n=n.parentElement}return!1}function w(e){if(e==null)return[];let n=new Set,t=[];for(let o of e.split(/[\\\\s,]+/)){let r=o.trim();r.length===0||n.has(r)||(n.add(r),t.push(r))}return t}var b=\\\"data-payload-fragment\\\";var D=\\\"data-payload-fragment-key\\\",ae=\\\"data-payload-depends\\\";function M(e){let n=e.getAttribute(b);if(n===null||n.length===0)return null;let t=e.getAttribute(D);return{element:e,id:n,key:t===null||t.length===0?void 0:t,dependsOn:w(e.getAttribute(ae))}}function L(e,n){let t=[];for(let o of e.querySelectorAll(`[${b}]`)){let r=M(o);r===null||_(o)||r.dependsOn.length>0&&!r.dependsOn.some(a=>n.has(a))||t.push(r)}return t}var B=\\\"x-payload-fragment-version\\\";function v(e){return typeof e==\\\"object\\\"&&e!==null&&!Array.isArray(e)}function C(e){if(!v(e))return null;let{html:n,boundary:t,revision:o,metadata:r}=e;return typeof n!=\\\"string\\\"||!v(t)||typeof t.id!=\\\"string\\\"||t.key!==void 0&&typeof t.key!=\\\"string\\\"||typeof o!=\\\"number\\\"||!v(r)||typeof r.renderedAt!=\\\"string\\\"||typeof r.renderer!=\\\"string\\\"?null:e}function U(e){let n={};for(let[t,o]of Object.entries(e))o!==void 0&&(n[t]=o);return n}function H(e){let n=0,t=[],o=()=>{let r=t.shift();r===void 0?n-=1:r()};return async r=>{n<e?n+=1:await new Promise(a=>{t.push(a)});try{return await r()}finally{o()}}}var le=5e3,se=4,de=512*1024,A={status:\\\"superseded\\\"};function h(e,n){return{status:\\\"failed\\\",code:e,reason:n}}function ue(e){return e instanceof Error?e.message:String(e)}function ce(e){let n=()=>{throw new TypeError('createFragmentStrategy: endpoint must be a same-origin path starting with \\\"/\\\"')};if((typeof e!=\\\"string\\\"||!e.startsWith(\\\"/\\\")||e.startsWith(\\\"//\\\")||e.includes(\\\"\\\\\\\\\\\"))&&n(),typeof location<\\\"u\\\"){let t;try{t=new URL(e,location.href)}catch{t=void 0}t?.origin!==location.origin&&n()}return e}function fe(e){return typeof e==\\\"object\\\"&&e!==null&&typeof e.getReader==\\\"function\\\"}async function me(e,n,t){let o=e.body;if(!fe(o)){let s=await e.text();return new TextEncoder().encode(s).byteLength>n?null:s}let r=o.getReader(),a=()=>{r.cancel().catch(()=>{})};t.addEventListener(\\\"abort\\\",a,{once:!0});let l=new TextDecoder,i=\\\"\\\",u=0;try{for(;;){let{done:s,value:y}=await r.read();if(s)break;if(u+=y.byteLength,u>n)return a(),null;i+=l.decode(y,{stream:!0})}}finally{t.removeEventListener(\\\"abort\\\",a)}return i+l.decode()}function K(e){let n=ce(e.endpoint),t=e.timeoutMs??le,o=e.maxResponseBytes??de,r=H(Math.max(1,e.maxConcurrent??se)),a=new Map;async function l(i,u){let s=()=>i.signal.aborted;if(s())return A;let y=e.location??location,m=U({fragment:u.id,key:u.key,route:y.pathname,search:y.search,revision:i.revision,locale:i.locale,collectionSlug:i.collectionSlug,globalSlug:i.globalSlug,fields:i.fields}),d=new AbortController,f=()=>{d.abort()};i.signal.addEventListener(\\\"abort\\\",f,{once:!0});let g={timedOut:!1},E=setTimeout(()=>{g.timedOut=!0,d.abort()},t),c=p=>s()?A:g.timedOut?h(\\\"LP0801\\\",`timeout after ${String(t)} ms`):h(\\\"LP0801\\\",ue(p));try{let p;try{p=await(e.fetch??fetch)(n,{method:\\\"POST\\\",credentials:\\\"same-origin\\\",headers:{...e.headers,accept:\\\"application/json\\\",\\\"content-type\\\":\\\"application/json\\\",[B]:String(1)},body:JSON.stringify(m),signal:d.signal})}catch(O){return c(O)}if(s())return A;if(p.status===401||p.status===403)return h(\\\"LP0803\\\",`endpoint refused the preview (${String(p.status)})`);if(!p.ok)return h(\\\"LP0801\\\",`endpoint answered ${String(p.status)}`);let T=p.headers.get(\\\"content-type\\\")??\\\"\\\";if(!T.toLowerCase().startsWith(\\\"application/json\\\"))return h(\\\"LP0802\\\",`unexpected content type \\\"${T}\\\"`);if(Number(p.headers.get(\\\"content-length\\\")??\\\"0\\\")>o)return h(\\\"LP0802\\\",\\\"response exceeds the size limit\\\");let k;try{k=await me(p,o,d.signal)}catch(O){return c(O)}if(s())return A;if(g.timedOut)return h(\\\"LP0801\\\",`timeout after ${String(t)} ms`);if(k===null)return h(\\\"LP0802\\\",\\\"response exceeds the size limit\\\");let I;try{I=JSON.parse(k)}catch{return h(\\\"LP0802\\\",\\\"response is not JSON\\\")}let S=C(I);return S===null?h(\\\"LP0802\\\",\\\"response has the wrong shape\\\"):S.boundary.id!==u.id?h(\\\"LP0802\\\",\\\"response is for another boundary\\\"):S.revision!==i.revision?A:{status:\\\"rendered\\\",html:S.html,metadata:S.metadata}}finally{clearTimeout(E),i.signal.removeEventListener(\\\"abort\\\",f)}}return(i,u)=>{let s=`${u.id} ${u.key??\\\"\\\"} ${String(i.revision)}`,y=a.get(s);if(y!==void 0)return y;let m=r(()=>l(i,u));a.set(s,m);let d=()=>{a.get(s)===m&&a.delete(s)};return m.then(d,d),m}}var F=\\\"data-payload-owned\\\",ye=new Set([\\\"open\\\",\\\"value\\\",\\\"checked\\\",\\\"selected\\\"]);function q(e,n){for(let t of n.keyAttributes){let o=e.getAttribute(t);if(o!==null&&o.length>0)return`${t}=${o}`}}function x(e){if(e.tagName.toLowerCase().includes(\\\"-\\\")||e.hasAttribute(R)||e.hasAttribute(F))return!0;let n=e.getAttribute(\\\"contenteditable\\\");return n!==null&&n!==\\\"false\\\"}function ge(e,n){return e.tagName===n.tagName&&e.namespaceURI===n.namespaceURI&&!x(e)&&!x(n)}function P(e,n,t){if(!ge(e,n))return n;let o=Se(e);return pe(e,n),t.retainChildrenOf?.(e,n)!==!0&&he(e,n,t),Re(o),e}function pe(e,n){for(let t of Array.from(e.attributes))n.hasAttribute(t.name)||ye.has(t.name.toLowerCase())||e.removeAttribute(t.name);for(let t of Array.from(n.attributes))e.getAttribute(t.name)!==t.value&&e.setAttribute(t.name,t.value)}function he(e,n,t){let o=be(e,t),r=new Set(o.values()),a=Array.from(e.childNodes).filter(m=>!r.has(m)),l=new Set,i=new Set,u=Array.from(n.childNodes),s=e.firstChild,y=0;for(let m=0;m<u.length;m+=1){let d=u[m],f=null,g=d instanceof Element?q(d,t):void 0;if(g!==void 0&&i.has(g)&&(g=void 0),g!==void 0){i.add(g);let c=o.get(g);if(c!==void 0&&!l.has(c)&&(f=$(c,d,t)===c?c:null,f===null)){c.replaceWith(d),l.add(d),s=d.nextSibling;continue}}else{for(;y<a.length;){let c=a[y];if(y+=1,!l.has(c)){if(G(c,d)){f=$(c,d,t)===c?c:null,f===null&&(e.replaceChild(d,c),l.add(d),s=d.nextSibling);break}if(c instanceof Element){let p=u[m+1];if(!(d instanceof Element)||p!==void 0&&G(c,p)){y-=1;break}e.replaceChild(d,c),l.add(d),s=d.nextSibling;break}if(!(d instanceof Element)){e.replaceChild(d,c),l.add(d),s=d.nextSibling;break}}}if(f===null&&l.has(d))continue}let E=f??d;for(l.add(E);s!==null&&s!==E&&!l.has(s)&&Ee(s);)s=s.nextSibling;E!==s&&e.insertBefore(E,s),s=E.nextSibling}for(let m of Array.from(e.childNodes))l.has(m)||m.remove()}function $(e,n,t){return e instanceof Element&&n instanceof Element?x(e)&&x(n)?e:P(e,n,t):(e.nodeValue!==n.nodeValue&&(e.nodeValue=n.nodeValue),e)}function Ee(e){return e.nodeType===Node.TEXT_NODE&&(e.nodeValue??\\\"\\\").trim().length===0}function G(e,n){return e.nodeType!==n.nodeType?!1:e instanceof Element&&n instanceof Element?e.tagName===n.tagName&&e.namespaceURI===n.namespaceURI:!0}function be(e,n){let t=new Map,o;for(let r of Array.from(e.children)){let a=q(r,n);if(a!==void 0){if(t.has(a)){o??(o=a.slice(a.indexOf(\\\"=\\\")+1));continue}t.set(a,r)}}return o!==void 0&&n.onDuplicateKey?.(e,o),t}function Se(e){let n=e.ownerDocument.activeElement;if(!(n instanceof HTMLElement)||!e.contains(n))return null;let t=n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement?[n.selectionStart,n.selectionEnd]:null;return{element:n,selection:t}}function Re(e){if(e===null)return;let{element:n,selection:t}=e;if(!(n.ownerDocument.activeElement===n||!n.isConnected))try{n.focus({preventScroll:!0});let[o,r]=t??[null,null];o!==null&&r!==null&&n.setSelectionRange(o,r)}catch{}}var V=\\\"data-payload-key\\\";var W=\\\"data-payload-strategy\\\",Y=\\\"data-payload-field\\\",Ae=\\\"data-payload-depends\\\",Te=\\\"x-payload-live-preview\\\",we=8e3,xe=1e3;function Fe(e){let n=e.getAttribute(W);return n!==null?n===\\\"route\\\":e.closest(\\\"head\\\")!==null}function ke(e){let n=e.getAttribute(Y),t=w(e.getAttribute(Ae));return n===null||n.length===0?t:[n,...t]}function j(e){if(e.tagName===\\\"META\\\"){let n=e.getAttribute(\\\"name\\\")??e.getAttribute(\\\"property\\\");return n===null?null:`meta:${n}`}return e.tagName===\\\"LINK\\\"&&e.getAttribute(\\\"rel\\\")===\\\"canonical\\\"?\\\"link:canonical\\\":null}function Oe(e,n){n.title!==e.title&&(e.title=n.title);let t=new Map;for(let r of e.head.querySelectorAll(\\\"meta, link\\\")){let a=j(r);a!==null&&!t.has(a)&&t.set(a,r)}let o=new Set;for(let r of n.head.querySelectorAll(\\\"meta, link\\\")){let a=j(r);if(a===null)continue;o.add(a);let l=t.get(a);if(l===void 0){e.head.append(e.importNode(r,!0));continue}if(!l.hasAttribute(F))for(let i of Array.from(r.attributes))l.getAttribute(i.name)!==i.value&&l.setAttribute(i.name,i.value)}for(let[r,a]of t)!o.has(r)&&!a.hasAttribute(F)&&a.remove()}function X(e={}){let n=e.timeoutMs??we,t=e.minIntervalMs??xe,o=-1/0;return{plan(r,a){for(let l of r.querySelectorAll(`[${Y}], [${W}=\\\"route\\\"]`)){if(!Fe(l))continue;let i=ke(l);if(i.length===0||i.some(u=>a.has(u)))return!0}return!1},async refresh(r){let a=Date.now();if(a-o<t)return r.log(\\\"LP0805\\\",`route refresh for revision ${String(r.revision)} refused: the previous one was ${String(a-o)} ms ago`),\\\"failed\\\";o=a;let l=e.document??document,i=e.location??location,u=e.window??window,s=new AbortController,y=()=>{s.abort()};r.signal.addEventListener(\\\"abort\\\",y,{once:!0});let m=setTimeout(()=>{s.abort()},n),d=f=>r.signal.aborted?\\\"superseded\\\":(r.log(\\\"LP0801\\\",f instanceof Error?f.message:String(f)),\\\"failed\\\");try{let f;try{f=await(e.fetch??fetch)(i.href,{method:\\\"GET\\\",credentials:\\\"same-origin\\\",cache:\\\"no-store\\\",headers:{accept:\\\"text/html\\\",[Te]:\\\"route\\\"},signal:s.signal})}catch(g){return d(g)}if(r.signal.aborted)return\\\"superseded\\\";if(!f.ok||!(f.headers.get(\\\"content-type\\\")??\\\"\\\").includes(\\\"text/html\\\"))return r.log(\\\"LP0802\\\",`route answered ${String(f.status)} ${f.headers.get(\\\"content-type\\\")??\\\"\\\"}`),\\\"failed\\\";try{let g=await f.text();if(!r.isCurrent())return\\\"superseded\\\";let E=new DOMParser().parseFromString(g,\\\"text/html\\\"),c=u.scrollX,p=u.scrollY;return Oe(l,E),P(l.body,E.body,{keyAttributes:[V,D,b],retainChildrenOf:T=>T.hasAttribute(b)}),u.scrollTo(c,p),\\\"refreshed\\\"}catch(g){return d(g)}}finally{clearTimeout(m),r.signal.removeEventListener(\\\"abort\\\",y)}}}}function Ne(e){return{plan:(n,t)=>L(n,t).map(o=>o.element),async render(n,t){let o={rendered:0,failed:0,superseded:0},r={revision:n.revision,receivedAt:n.receivedAt,fields:n.fields,locale:n.locale,collectionSlug:n.collectionSlug,globalSlug:n.globalSlug,signal:n.signal};return await Promise.all(t.map(async a=>{let l=M(a);if(l===null)return;let i;try{i=await e(r,l)}catch(u){i={status:\\\"failed\\\",code:\\\"LP0801\\\",reason:u instanceof Error?u.message:String(u)}}if(!n.isCurrent()||i.status===\\\"superseded\\\"){o.superseded+=1,n.log(\\\"LP0804\\\",`fragment \\\"${l.id}\\\" for revision ${String(r.revision)} discarded as superseded`);return}if(i.status===\\\"rendered\\\"){n.morph(a,i.html),n.rendered(a,l.id,l.key),o.rendered+=1;return}n.failed(a,l.id,l.key,i.code,i.reason),n.isCurrent()&&n.patch(a),o.failed+=1})),o}}}function z(e){return Ne(K(e))}return te(De);})();\";\n","/**\n * The inline script's configuration and its positional wire order: the\n * generator writes the tuple, `src/core/runtime.ts` destructures it, and\n * `INLINE_CONFIG_KEYS` is where they agree. Append only, never reorder.\n */\n\nimport type { DefaultsProfile } from '@core/defaults-profile';\n\nexport interface InlineScriptConfig {\n /** Trusted admin origins, merged with the detected ones. */\n readonly allowedOrigins?: readonly string[];\n /** Payload origin; every update is then re-fetched through the REST API with credentials. Requires `mergeDepth`. */\n readonly serverURL?: string;\n /** REST route prefix used with `serverURL`. Default `/api`. */\n readonly apiRoute?: string;\n /** Population depth used with `serverURL`. Required with `serverURL` unless `defaults: 'v1'`. */\n readonly mergeDepth?: number;\n /** Verbose console logging. Default `false`. */\n readonly debug?: boolean;\n /** Debounce window for incoming updates in ms. Default `50`. */\n readonly debounceMs?: number;\n /** Mount the screen-reader live region. Default `true`. */\n readonly enableA11y?: boolean;\n /** Heartbeat timeout in ms; `0` disables it (default), because the admin posts only on edits. */\n readonly heartbeatMs?: number;\n /** Apply every update regardless of viewport position. Default `false`. */\n readonly disableVisibilityGate?: boolean;\n /** Cache size above which off-screen updates wait for intersection. Default `50`. */\n readonly visibilityGateThreshold?: number;\n /** `rootMargin` of the IntersectionObserver. Default `'200px'`. */\n readonly intersectionRootMargin?: string;\n /** Ignore `document.referrer` as an origin source. Default `true`; `defaults: 'v1'` sets `false`. */\n readonly disableReferrerDetection?: boolean;\n /** Disable the dev-mode localhost matcher (any port on `localhost`/`127.0.0.1`). Default `false`. */\n readonly disableLocalhostMatching?: boolean;\n /** Update only bindings under a matching `data-payload-owner`. Default `false`. */\n readonly scopeBindingsByOwner?: boolean;\n /** Skip bindings whose value did not change. Default `true`; `defaults: 'v1'` sets `false`. */\n readonly skipUnchanged?: boolean;\n /** Scroll the preview to the field being edited. Default `false`. */\n readonly revealEditedField?: boolean;\n /** Which windows may post updates. Default `'parent-or-opener'`; `defaults: 'v1'` sets `'any'`. */\n readonly eventSourcePolicy?: 'any' | 'parent-or-opener';\n /** Sanitizer policy for rich text and HTML writes. Default `'strict'`; `defaults: 'v1'` sets `'compat'`. */\n readonly sanitizerPolicy?: 'compat' | 'strict';\n /** Same-origin path of a fragment endpoint; the script then carries the fragment client ahead of the runtime (ADR 0011). */\n readonly fragmentEndpoint?: string;\n /** Which defaults the omitted options fall back to. Not serialized: `'v1'` only relaxes the generator's `mergeDepth` check. */\n readonly defaults?: DefaultsProfile;\n}\n\n/** Keys that travel in the wire tuple, in slot order. */\nexport const INLINE_CONFIG_KEYS = [\n 'allowedOrigins',\n 'serverURL',\n 'apiRoute',\n 'mergeDepth',\n 'debug',\n 'debounceMs',\n 'enableA11y',\n 'heartbeatMs',\n 'disableVisibilityGate',\n 'visibilityGateThreshold',\n 'intersectionRootMargin',\n 'disableReferrerDetection',\n 'disableLocalhostMatching',\n 'scopeBindingsByOwner',\n 'skipUnchanged',\n 'eventSourcePolicy',\n 'sanitizerPolicy',\n 'fragmentEndpoint',\n 'revealEditedField',\n] as const satisfies readonly Exclude<keyof InlineScriptConfig, 'defaults'>[];\n","/**\n * Wraps the build-time runtime IIFE with the consumer's configuration; a page\n * with a fragment endpoint gets the fragment prelude ahead of it.\n */\n\nimport { RUNTIME_SOURCE, RUNTIME_BUILD_INFO, type RuntimeBuildInfo } from './runtime.generated';\nimport { FRAGMENT_SOURCE } from './fragment.generated';\nimport { LOADER_SOURCE } from './loader.generated';\nimport { INLINE_CONFIG_KEYS, type InlineScriptConfig } from '@/types/inline-config';\n\nexport type { InlineScriptConfig } from '@/types/inline-config';\n\nfunction assertBuilt(source: string, artifact: string): void {\n if (source.length === 0) {\n throw new Error(\n `[live-preview] ${artifact} is empty. Run \\`npm run build:runtime\\` before bundling.`,\n );\n }\n}\n\n/** The inline script body without `<script>` tags; see `wrapWithScriptTag()`. */\nexport function generateInlineScript(config: InlineScriptConfig = {}): string {\n assertBuilt(RUNTIME_SOURCE, 'runtime.generated.ts');\n return [configStatement(config), ...fragmentPrelude(config), RUNTIME_SOURCE].join('\\n');\n}\n\nfunction fragmentPrelude(config: InlineScriptConfig): readonly string[] {\n if (config.fragmentEndpoint == null) return [];\n assertBuilt(FRAGMENT_SOURCE, 'fragment.generated.ts');\n return [FRAGMENT_SOURCE];\n}\n\n// `__LIVE_PREVIEW_CONFIG__` is a public presence signal: consumers' integration\n// tests grep for it, so the name outlives any refactor.\nfunction configStatement(config: InlineScriptConfig): string {\n return `var __LIVE_PREVIEW_CONFIG__=${buildConfigLiteral(config)};`;\n}\n\n/** The positional wire literal the runtime destructures; shared by the inline script and the loader. */\nfunction buildConfigLiteral(config: InlineScriptConfig): string {\n if (config.defaults !== 'v1' && (config.serverURL ?? '') !== '' && config.mergeDepth == null) {\n throw new Error(\n 'payload-live-preview: `serverURL` needs an explicit `mergeDepth` under the 2.0 defaults — ' +\n \"choose the population depth deliberately (0 for none), or pass `defaults: 'v1'` to keep \" +\n 'the 1.x default of 1 while migrating (ADR 0007, entry 10).',\n );\n }\n // `null` counts as omitted, and omitted slots stay empty (`[,,1]`): a JSON\n // `null` would bypass the runtime's destructuring defaults.\n const values: unknown[] = INLINE_CONFIG_KEYS.map((key) => config[key] ?? undefined);\n while (values.length > 0 && values.at(-1) === undefined) values.pop();\n // `<` is escaped so a value containing `</script>` cannot end the tag.\n return `[${values\n .map((value) => (value === undefined ? '' : JSON.stringify(value)))\n .join(',')}]`.replace(/</g, '\\\\u003C');\n}\n\n/** Where the runtime asset lives, and how the browser should verify it. */\nexport interface LoaderScriptTarget {\n /** URL the bootstrap appends. Same-origin or absolute; hashed by the caller. */\n readonly runtimeSrc: string;\n /** Subresource-integrity value, e.g. `sha384-…`; empty drops the check and the `crossorigin` it requires. */\n readonly integrity?: string;\n}\n\n/**\n * The static-delivery bootstrap: the configuration plus a few hundred bytes\n * appending the runtime inside a preview. The asset stays configuration-free.\n */\nexport function generateLoaderScript(\n config: InlineScriptConfig = {},\n target: LoaderScriptTarget,\n): string {\n assertBuilt(LOADER_SOURCE, 'loader.generated.ts');\n if (target.runtimeSrc === '') {\n throw new Error('[live-preview] generateLoaderScript needs a runtimeSrc.');\n }\n const encode = (value: string): string => JSON.stringify(value).replace(/</gu, '\\\\u003C');\n return [\n configStatement(config),\n `var __LP_RUNTIME_SRC__=${encode(target.runtimeSrc)};`,\n `var __LP_RUNTIME_INTEGRITY__=${encode(target.integrity ?? '')};`,\n ...fragmentPrelude(config),\n LOADER_SOURCE,\n ].join('\\n');\n}\n\n/** Wrap a script body in `<script>`, with the CSP nonce attribute when given. */\nexport function wrapWithScriptTag(body: string, options: { nonce?: string } = {}): string {\n const nonceAttr = options.nonce !== undefined ? ` nonce=\"${escapeNonce(options.nonce)}\"` : '';\n return `<script${nonceAttr}>${body}</script>`;\n}\n\nexport function runtimeBuildInfo(): RuntimeBuildInfo {\n return RUNTIME_BUILD_INFO;\n}\n\nfunction escapeNonce(nonce: string): string {\n if (!/^[A-Za-z0-9+/=_-]+$/.test(nonce)) {\n throw new RangeError('wrapWithScriptTag: nonce contains invalid characters');\n }\n return nonce;\n}\n","/**\n * Content-Security-Policy helpers: nonce generation, directive builders and\n * the header merge every adapter uses. Isomorphic; needs only Web Crypto.\n */\n\nconst DEFAULT_NONCE_BYTES = 16;\n\n/** CSP3's exact whitespace set: HTAB, LF, FF, CR, and SPACE. */\nconst CSP_ASCII_WHITESPACE = /[\\t\\n\\f\\r ]+/;\n\n/** Reads one code unit; an index past the end yields NaN, which matches nothing. */\nfunction isCspWhitespace(value: string, index: number): boolean {\n const code = value.charCodeAt(index);\n return code === 9 || code === 10 || code === 12 || code === 13 || code === 32;\n}\n\n/**\n * Trim CSP whitespace by scanning from both ends.\n *\n * The obvious `/^\\s+|\\s+$/` is superlinear by construction: for a long run the\n * trailing alternative is retried at every position. V8 happens to optimise the\n * shape away, but this header can come from a consumer's own response and this\n * module runs in every engine, so the guarantee has to come from the algorithm\n * rather than from one engine's optimiser.\n */\nfunction trimCspWhitespace(value: string): string {\n let start = 0;\n let end = value.length;\n while (start < end && isCspWhitespace(value, start)) start += 1;\n while (end > start && isCspWhitespace(value, end - 1)) end -= 1;\n return start === 0 && end === value.length ? value : value.slice(start, end);\n}\n\n/** CSP names are ASCII; Unicode case folding must not create directives. */\nfunction asciiLowercase(value: string): string {\n return value.replace(/[A-Z]/g, (character) => character.toLowerCase());\n}\n\n/** The one Web Crypto method this module calls; accepts Node's `webcrypto` without a cast. */\ninterface WebCryptoLike {\n getRandomValues: <T extends ArrayBufferView | null>(array: T) => T;\n}\n\nlet cryptoOverride: WebCryptoLike | undefined;\n\n/** Supply a Web Crypto implementation for runtimes without `globalThis.crypto`; `null` clears it. */\nexport function setCspCrypto(crypto: WebCryptoLike | null): void {\n cryptoOverride = crypto ?? undefined;\n}\n\n/** A base64url nonce of `bytes` random bytes (default 16); throws without Web Crypto, since a predictable nonce silently defeats the CSP. */\nexport function generateCspNonce(bytes: number = DEFAULT_NONCE_BYTES): string {\n if (!Number.isInteger(bytes) || bytes < 8) {\n throw new RangeError(`generateCspNonce: bytes must be an integer >= 8, got ${String(bytes)}`);\n }\n const crypto = resolveCrypto();\n if (!crypto) {\n throw new Error(\n 'generateCspNonce: Web Crypto is unavailable. On Node 18 call setCspCrypto(webcrypto) ' +\n \"once at startup, or run with --experimental-global-webcrypto. We won't fabricate \" +\n 'a predictable nonce — that would silently defeat the entire CSP.',\n );\n }\n const buffer = new Uint8Array(bytes);\n crypto.getRandomValues(buffer);\n return base64UrlEncode(buffer);\n}\n\nfunction resolveCrypto(): WebCryptoLike | undefined {\n if (cryptoOverride?.getRandomValues) return cryptoOverride;\n const fromGlobal = (globalThis as { crypto?: WebCryptoLike }).crypto;\n if (fromGlobal?.getRandomValues) return fromGlobal;\n return undefined;\n}\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n const base64 = typeof btoa === 'function' ? btoa(binary) : Buffer.from(bytes).toString('base64');\n return base64.replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');\n}\n\n/** A `frame-ancestors` source: `'self'`, `'none'`, or an origin. */\nexport type FrameAncestorSource = string;\n\nexport interface FrameAncestorsOptions {\n readonly self?: boolean;\n readonly origins?: readonly string[];\n readonly allowNone?: boolean;\n}\n\n/** The `frame-ancestors` value: `'self'` and the origins, deduplicated; `'none'` when empty. */\nexport function buildFrameAncestors(options: FrameAncestorsOptions = {}): string {\n const { self = true, origins = [], allowNone = false } = options;\n const seen = new Set<string>();\n const out: FrameAncestorSource[] = [];\n if (allowNone && !self && origins.length === 0) return \"'none'\";\n if (self) {\n out.push(\"'self'\");\n seen.add(\"'self'\");\n }\n for (const origin of origins) {\n const trimmed = origin.trim();\n if (trimmed.length === 0 || seen.has(trimmed)) continue;\n seen.add(trimmed);\n out.push(trimmed);\n }\n return out.length > 0 ? out.join(' ') : \"'none'\";\n}\n\n/**\n * A `script-src` value permitting one nonce plus optional extra sources.\n * `'strict-dynamic'` is opt-in: it makes CSP 3 browsers ignore `'self'` and\n * host sources, so every script on the page must then carry the nonce.\n */\nexport function buildScriptSrcWithNonce(\n nonce: string,\n options: {\n readonly self?: boolean;\n readonly extra?: readonly string[];\n readonly strictDynamic?: boolean;\n } = {},\n): string {\n if (nonce.length === 0) throw new RangeError('buildScriptSrcWithNonce: nonce is empty');\n const { self = true, extra = [], strictDynamic = false } = options;\n const parts: string[] = [];\n if (self) parts.push(\"'self'\");\n parts.push(`'nonce-${nonce}'`);\n if (strictDynamic) parts.push(\"'strict-dynamic'\");\n for (const e of extra) {\n const trimmed = e.trim();\n if (trimmed.length > 0) parts.push(trimmed);\n }\n return parts.join(' ');\n}\n\n/** `union` (default) adds sources to an existing directive; `replace` overwrites it. */\nexport interface CspDirectiveMerge {\n readonly value: string;\n readonly mode?: 'union' | 'replace';\n}\n\n/**\n * Merge directives into an existing `Content-Security-Policy` header value.\n * Commas separate policies (that is how `Headers.get()` joins repeated\n * headers); each is merged, because a browser enforces every policy and\n * widening only the last would leave the others blocking.\n */\nexport function mergeCspHeader(\n existing: string,\n additions: Readonly<Record<string, string | CspDirectiveMerge>>,\n): string {\n const policies = existing.split(',').filter((policy) => policy.trim().length > 0);\n if (policies.length === 0) return mergeCspPolicy('', additions);\n return policies.map((policy) => mergeCspPolicy(policy, additions)).join(', ');\n}\n\nfunction mergeCspPolicy(\n existing: string,\n additions: Readonly<Record<string, string | CspDirectiveMerge>>,\n): string {\n const directives = new Map<string, string>();\n for (const part of existing.split(';')) {\n const trimmed = trimCspWhitespace(part);\n if (trimmed.length === 0) continue;\n const whitespaceIndex = trimmed.search(CSP_ASCII_WHITESPACE);\n const name = asciiLowercase(whitespaceIndex < 0 ? trimmed : trimmed.slice(0, whitespaceIndex));\n // CSP3 §2.2.1: a user agent ignores later duplicates, so a looser\n // duplicate must not become the policy that is serialized.\n if (directives.has(name)) continue;\n const value = whitespaceIndex < 0 ? '' : trimCspWhitespace(trimmed.slice(whitespaceIndex));\n directives.set(name, value);\n }\n\n for (const [rawName, rawAddition] of Object.entries(additions)) {\n const name = asciiLowercase(rawName);\n const addition: CspDirectiveMerge =\n typeof rawAddition === 'string' ? { value: rawAddition } : rawAddition;\n const mode = addition.mode ?? 'union';\n const current = directives.get(name);\n if (mode === 'replace' || current === undefined || current.length === 0) {\n directives.set(name, addition.value);\n continue;\n }\n const seen = new Set<string>();\n const merged: string[] = [];\n for (const token of [\n ...current.split(CSP_ASCII_WHITESPACE),\n ...addition.value.split(CSP_ASCII_WHITESPACE),\n ]) {\n if (token.length === 0 || seen.has(token)) continue;\n seen.add(token);\n merged.push(token);\n }\n // `'none'` cannot coexist with other sources.\n const withoutNone = merged.filter((token) => token !== \"'none'\");\n directives.set(name, (withoutNone.length > 0 ? withoutNone : merged).join(' '));\n }\n\n const out: string[] = [];\n for (const [name, value] of directives) {\n out.push(value.length === 0 ? name : `${name} ${value}`);\n }\n return out.join('; ');\n}\n","/**\n * The authorized preview context's shape and brand, in the leaf `types` domain\n * so producer and consumers recognise the same context. See ADR 0006.\n */\n\n/**\n * The brand key, in the type and on the object.\n *\n * This was a `unique symbol` until 2026-08-30. A `unique symbol` is nominal per\n * *declaration*, and the published entries each carry their own declaration\n * file — so `AuthorizedPreviewContext` from the root barrel was a different\n * type from the one in `./server` or in an adapter, and the documented flow\n * (authorize once, hand the context to the adapter hook and to the draft read)\n * did not type-check in any combination a consumer can write.\n *\n * That is the same trap the runtime brand below already avoids by using\n * `Symbol.for` rather than `Symbol()`; the lesson simply had not reached the\n * type. A shared string literal is identical in every bundle for the same\n * reason a registry symbol is.\n *\n * It is not what makes a context trustworthy. `isAuthorizedPreviewContext`\n * decides that, on the registry symbol and on `Object.isFrozen`, and every\n * consumption point calls it — the adapter policy, the draft read and the\n * binding emitter. Writing this key by hand buys nothing.\n */\nexport const AUTHORIZED_PREVIEW_BRAND_KEY = 'payload-live-preview.authorized-preview-context';\n\nexport type PreviewAuthorizationStrategyName = 'payload-session' | 'signed-token' | 'verifier';\n\n/** What a context is bound to; every field is optional because every strategy binds differently. */\nexport interface AuthorizedPreviewScope {\n /** The site origin the credential was issued for. */\n readonly audience?: string;\n /** The request pathname the credential is valid for. */\n readonly path?: string;\n readonly locale?: string;\n}\n\n/** The verdict of a successful `authorizePreviewRequest()`: frozen, branded, produced only there. Carry it, do not rebuild it. */\nexport interface AuthorizedPreviewContext {\n readonly [AUTHORIZED_PREVIEW_BRAND_KEY]: true;\n readonly strategy: PreviewAuthorizationStrategyName;\n /** The user id, token subject, or whatever the verifier named. */\n readonly subject: string | undefined;\n /** Unix milliseconds. */\n readonly authorizedAt: number;\n /** Unix milliseconds, or `undefined` when the strategy does not know. */\n readonly expiresAt: number | undefined;\n readonly scope: AuthorizedPreviewScope;\n /** The minimal request material a draft read forwards to Payload — one verified cookie, never the whole `Cookie` header. */\n readonly payloadHeaders: Readonly<Record<string, string>>;\n}\n\n// A registry symbol: entries are separate bundles, and a per-bundle `Symbol()`\n// would refuse the other's contexts in the package while unit tests passed.\nconst BRAND = Symbol.for(AUTHORIZED_PREVIEW_BRAND_KEY);\n\n/** Whether `value` was produced by `authorizePreviewRequest()`; a copy or JSON round trip is not. */\nexport function isAuthorizedPreviewContext(value: unknown): value is AuthorizedPreviewContext {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<PropertyKey, unknown>)[BRAND] === true &&\n Object.isFrozen(value)\n );\n}\n\n/** Internal: the one place a context is made. */\nexport function createAuthorizedPreviewContext(\n fields: Omit<AuthorizedPreviewContext, typeof AUTHORIZED_PREVIEW_BRAND_KEY>,\n): AuthorizedPreviewContext {\n const context = Object.freeze({\n ...fields,\n scope: Object.freeze({ ...fields.scope }),\n payloadHeaders: Object.freeze({ ...fields.payloadHeaders }),\n [BRAND]: true,\n [AUTHORIZED_PREVIEW_BRAND_KEY]: true,\n });\n // No cast: the frozen object carries the brand key the interface declares.\n return context;\n}\n","/**\n * The verdict shape every authorization strategy produces, and the one error\n * class that is allowed to escape it. Kept apart from the strategies so the\n * adapters can import the error without pulling in HMAC or session code.\n */\n\nimport type { AuthorizedPreviewContext } from '@/types/authorized-preview';\n\n/** Why a request was refused. `'authorized'` is the one non-refusal. */\nexport type PreviewAuthorizationOutcome =\n | 'authorized'\n | 'missing-credential'\n | 'invalid'\n | 'expired'\n | 'wrong-audience'\n | 'wrong-path'\n | 'wrong-locale'\n | 'wrong-purpose'\n | 'replayed'\n | 'unavailable';\n\n/** The result of `authorizePreviewRequest()`: a verdict, never an exception. */\nexport type PreviewAuthorization =\n | {\n readonly authorized: true;\n readonly outcome: 'authorized';\n readonly context: AuthorizedPreviewContext;\n }\n | {\n readonly authorized: false;\n readonly outcome: Exclude<PreviewAuthorizationOutcome, 'authorized'>;\n readonly context: null;\n };\n\n/** The request shape every strategy reads: a URL and a header getter. */\nexport interface PreviewAuthorizationRequest {\n readonly url: string;\n readonly headers: { get(name: string): string | null };\n}\n\n/**\n * A strategy was misconfigured — raised on first use and re-thrown by the\n * adapters rather than reported as `'unavailable'`, so it fails loudly.\n */\nexport class PreviewConfigurationError extends Error {\n override readonly name = 'PreviewConfigurationError';\n}\n\n/** Recognises the error across bundles, where `instanceof` sees a different class copy. */\nexport function isPreviewConfigurationError(error: unknown): error is PreviewConfigurationError {\n return (\n error instanceof PreviewConfigurationError ||\n (error instanceof Error && error.name === 'PreviewConfigurationError')\n );\n}\n\nexport function refused(\n outcome: Exclude<PreviewAuthorizationOutcome, 'authorized'>,\n): PreviewAuthorization {\n return { authorized: false, outcome, context: null };\n}\n","/**\n * The `payload-session` strategy: forward exactly one named cookie to\n * `GET <serverURL>/api/<usersSlug>/me` and authorize when a user comes back.\n */\n\nimport { createAuthorizedPreviewContext } from '@/types/authorized-preview';\nimport {\n PreviewConfigurationError,\n refused,\n type PreviewAuthorization,\n type PreviewAuthorizationRequest,\n} from './preview-verdict';\n\n/** A `fetch`-compatible function, injectable for tests. */\nexport type FetchLike = (\n input: string,\n init: { readonly headers: Record<string, string>; readonly signal: AbortSignal },\n) => Promise<{ readonly ok: boolean; readonly status: number; json(): Promise<unknown> }>;\n\nexport interface PayloadSessionStrategy {\n readonly type: 'payload-session';\n /** Payload server origin, e.g. `https://cms.example.com`. */\n readonly serverURL: string;\n /** Auth collection slug; `users` unless the project renamed it. */\n readonly usersSlug?: string;\n /** Cookie name; Payload's default is `payload-token`. */\n readonly cookieName?: string;\n /** Upper bound for the `/me` round trip. Below 250 ms is raised to 250 ms; default 3000. */\n readonly timeoutMs?: number;\n /** Longest cookie value accepted; longer ones are refused as `invalid`. Default 4096. */\n readonly maxCookieLength?: number;\n readonly fetch?: FetchLike;\n /** Clock, Unix milliseconds. Injectable for tests. */\n readonly now?: () => number;\n}\n\nconst DEFAULT_USERS_SLUG = 'users';\nconst DEFAULT_COOKIE_NAME = 'payload-token';\nconst DEFAULT_TIMEOUT_MS = 3_000;\nconst MIN_TIMEOUT_MS = 250;\nconst DEFAULT_MAX_COOKIE_LENGTH = 4_096;\nconst COOKIE_NAME_PATTERN = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\nconst COOKIE_VALUE_PATTERN = /^[A-Za-z0-9._~-]+$/;\n/** Below this an `exp` is Unix seconds; a millisecond timestamp passed it in 1973. */\nconst SECONDS_CEILING = 1e11;\n\n/**\n * Exactly one value for `name`, or `null` when absent, empty, over `maxLength`\n * or repeated — a repeated cookie is ambiguous and is refused, not guessed.\n */\nexport function extractCookie(\n header: string | null,\n name: string,\n maxLength: number = DEFAULT_MAX_COOKIE_LENGTH,\n): string | null {\n if (header === null || header.length === 0) return null;\n const prefix = `${name}=`;\n const values: string[] = [];\n for (const part of header.split(';')) {\n const trimmed = part.trim();\n if (trimmed.startsWith(prefix)) values.push(trimmed.slice(prefix.length));\n }\n if (values.length !== 1) return null;\n const value = values[0] ?? '';\n // A JWT is `[A-Za-z0-9._~-]`; anything else must not be forwarded in a header.\n if (value.length === 0 || value.length > maxLength || !COOKIE_VALUE_PATTERN.test(value)) {\n return null;\n }\n return value;\n}\n\nfunction cookieNameFor(configured: string | undefined): string {\n const name = configured ?? DEFAULT_COOKIE_NAME;\n if (!COOKIE_NAME_PATTERN.test(name)) {\n throw new PreviewConfigurationError(\n `payload-live-preview: cookie name \"${name}\" is not a valid cookie-name token`,\n );\n }\n return name;\n}\n\nfunction serverOriginFor(serverURL: string): string {\n let url: URL;\n try {\n url = new URL(serverURL);\n } catch {\n throw new PreviewConfigurationError(\n `payload-live-preview: serverURL \"${serverURL}\" is not an absolute URL`,\n );\n }\n if (url.protocol !== 'https:' && url.protocol !== 'http:') {\n throw new PreviewConfigurationError(\n `payload-live-preview: serverURL must be http(s), got \"${url.protocol}\"`,\n );\n }\n return url.origin;\n}\n\nexport async function authorizeSession(\n request: PreviewAuthorizationRequest,\n strategy: PayloadSessionStrategy,\n): Promise<PreviewAuthorization> {\n const cookieName = cookieNameFor(strategy.cookieName);\n const origin = serverOriginFor(strategy.serverURL);\n const value = extractCookie(\n request.headers.get('cookie'),\n cookieName,\n strategy.maxCookieLength ?? DEFAULT_MAX_COOKIE_LENGTH,\n );\n if (value === null) return refused('missing-credential');\n const now = strategy.now ?? Date.now;\n const timeoutMs = Math.max(MIN_TIMEOUT_MS, strategy.timeoutMs ?? DEFAULT_TIMEOUT_MS);\n const fetchImpl: FetchLike = strategy.fetch ?? globalThis.fetch;\n const usersSlug = encodeURIComponent(strategy.usersSlug ?? DEFAULT_USERS_SLUG);\n const forwarded = `${cookieName}=${value}`;\n let body: unknown;\n try {\n // `depth=0`: the verdict needs the user's id, not its populated relations.\n const response = await fetchImpl(`${origin}/api/${usersSlug}/me?depth=0`, {\n headers: { cookie: forwarded, accept: 'application/json' },\n signal: AbortSignal.timeout(timeoutMs),\n });\n if (!response.ok) return refused(response.status === 401 ? 'invalid' : 'unavailable');\n body = await response.json();\n } catch {\n return refused('unavailable');\n }\n const user = readUser(body, strategy.usersSlug ?? DEFAULT_USERS_SLUG);\n if (user === null) return refused('invalid');\n const expiresAt = readExpiry(body);\n if (expiresAt !== undefined && expiresAt <= now()) return refused('expired');\n return {\n authorized: true,\n outcome: 'authorized',\n context: createAuthorizedPreviewContext({\n strategy: 'payload-session',\n subject: user,\n authorizedAt: now(),\n expiresAt,\n scope: {},\n payloadHeaders: { cookie: forwarded },\n }),\n };\n}\n\n/** The user id from a `/me` body, or `null` when absent or from another auth collection — Payload answers `/me` for every one of them. */\nfunction readUser(body: unknown, usersSlug: string): string | null {\n if (typeof body !== 'object' || body === null || Array.isArray(body)) return null;\n const user = (body as { user?: unknown }).user;\n if (typeof user !== 'object' || user === null || Array.isArray(user)) return null;\n const collection =\n (body as { collection?: unknown }).collection ?? (user as { collection?: unknown }).collection;\n if (collection !== undefined && collection !== usersSlug) return null;\n const id = (user as { id?: unknown }).id;\n if (typeof id === 'string' && id.length > 0) return id;\n if (typeof id === 'number' && Number.isFinite(id)) return String(id);\n return null;\n}\n\n/** `/me` reports `exp` in Unix seconds; units are decided by magnitude so an expired millisecond value stays expired. */\nfunction readExpiry(body: unknown): number | undefined {\n const exp = (body as { exp?: unknown }).exp;\n if (typeof exp !== 'number' || !Number.isFinite(exp) || exp <= 0) return undefined;\n return exp < SECONDS_CEILING ? exp * 1000 : exp;\n}\n","/**\n * The `signed-token` strategy: a short-lived HMAC-SHA256 token minted by the\n * Payload side and verified by the site. Format and bindings: ADR 0006 §3.\n */\n\nimport { createAuthorizedPreviewContext } from '@/types/authorized-preview';\nimport {\n PreviewConfigurationError,\n refused,\n type PreviewAuthorization,\n type PreviewAuthorizationRequest,\n} from './preview-verdict';\n\n/** The subset of Web Crypto the token strategy needs, injectable for environments that expose it elsewhere. */\nexport interface SubtleCryptoLike {\n readonly subtle: {\n importKey(\n format: 'raw',\n keyData: Uint8Array,\n algorithm: { readonly name: 'HMAC'; readonly hash: 'SHA-256' },\n extractable: false,\n keyUsages: readonly ('sign' | 'verify')[],\n ): Promise<CryptoKey>;\n sign(algorithm: 'HMAC', key: CryptoKey, data: Uint8Array): Promise<ArrayBuffer>;\n verify(\n algorithm: 'HMAC',\n key: CryptoKey,\n signature: Uint8Array,\n data: Uint8Array,\n ): Promise<boolean>;\n };\n getRandomValues<T extends Uint8Array>(array: T): T;\n}\n\n/** Where a signed token is read from on the request. */\nexport type PreviewTokenTransport =\n | { readonly kind: 'query'; readonly param?: string }\n | { readonly kind: 'header'; readonly name?: string };\n\n/**\n * Optional replay store. Not shipped: a per-process memory is useless behind\n * a load balancer, so the store is a deployment decision.\n */\nexport interface PreviewTokenReplayStore {\n isUsed(id: string): Promise<boolean> | boolean;\n markUsed(id: string, expiresAt: number): Promise<void> | void;\n}\n\nexport interface SignedTokenStrategy {\n readonly type: 'signed-token';\n /** Shared secret, at least 32 bytes; shorter ones are refused on first use. */\n readonly secret: string | Uint8Array;\n /** The site origin tokens must name, e.g. `https://www.example.com`. */\n readonly audience: string;\n /** Purpose string tokens must carry. Default `live-preview`. */\n readonly purpose?: string;\n /** Default: query parameter `previewToken`. */\n readonly transport?: PreviewTokenTransport;\n /** Resolve the request's locale for the `loc` binding. Unset: tokens with `loc` are refused as `wrong-locale`. */\n readonly locale?: (request: PreviewAuthorizationRequest) => string | undefined;\n readonly replay?: PreviewTokenReplayStore;\n readonly crypto?: SubtleCryptoLike;\n readonly now?: () => number;\n}\n\n/** What `issuePreviewToken()` binds a token to. */\nexport interface PreviewTokenClaims {\n /** The site origin the token is for. */\n readonly audience: string;\n /** Request pathname the token opens. Recommended; omit only for a single-page preview. */\n readonly path?: string;\n readonly locale?: string;\n readonly subject?: string;\n readonly purpose?: string;\n /** Lifetime in milliseconds. Default ten minutes; capped at one hour. */\n readonly ttlMs?: number;\n}\n\nexport interface IssuePreviewTokenOptions {\n readonly secret: string | Uint8Array;\n readonly crypto?: SubtleCryptoLike;\n readonly now?: () => number;\n}\n\ninterface WireClaims {\n readonly v: 1;\n readonly aud: string;\n readonly pth?: string;\n readonly loc?: string;\n readonly sub?: string;\n readonly pur: string;\n readonly iat: number;\n readonly exp: number;\n readonly jti: string;\n}\n\nconst DEFAULT_PURPOSE = 'live-preview';\nconst DEFAULT_QUERY_PARAM = 'previewToken';\nconst DEFAULT_HEADER_NAME = 'x-preview-token';\nconst DEFAULT_TTL_MS = 10 * 60_000;\nconst MAX_TTL_MS = 60 * 60_000;\nconst MIN_SECRET_BYTES = 32;\nconst TOKEN_VERSION = 'v1';\n/** A real token is a few hundred bytes. */\nconst MAX_TOKEN_LENGTH = 4_096;\n\n// Lazy: a module-scope `new TextEncoder()` is a side effect a bundler must keep.\nlet cachedEncoder: TextEncoder | undefined;\nfunction encoder(): TextEncoder {\n cachedEncoder ??= new TextEncoder();\n return cachedEncoder;\n}\n\nfunction secretBytes(secret: string | Uint8Array): Uint8Array {\n const bytes = typeof secret === 'string' ? encoder().encode(secret) : secret;\n if (bytes.byteLength < MIN_SECRET_BYTES) {\n throw new PreviewConfigurationError(\n `payload-live-preview: the preview token secret must be at least ${String(MIN_SECRET_BYTES)} bytes`,\n );\n }\n return bytes;\n}\n\nfunction cryptoFor(configured: SubtleCryptoLike | undefined): SubtleCryptoLike | undefined {\n if (configured !== undefined) return configured;\n const candidate = (globalThis as { crypto?: unknown }).crypto;\n if (typeof (candidate as { subtle?: unknown } | undefined)?.subtle === 'object') {\n return candidate as SubtleCryptoLike;\n }\n return undefined;\n}\n\nasync function hmacKey(crypto: SubtleCryptoLike, secret: Uint8Array): Promise<CryptoKey> {\n return crypto.subtle.importKey('raw', secret, { name: 'HMAC', hash: 'SHA-256' }, false, [\n 'sign',\n 'verify',\n ]);\n}\n\nfunction toBase64Url(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nfunction fromBase64Url(text: string): Uint8Array | undefined {\n if (!/^[A-Za-z0-9_-]*$/.test(text)) return undefined;\n const padded =\n text.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (text.length % 4)) % 4);\n try {\n const binary = atob(padded);\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);\n return bytes;\n } catch {\n return undefined;\n }\n}\n\n/** Mint a preview token on the Payload side; pair with `buildLivePreviewUrl`. */\nexport async function issuePreviewToken(\n claims: PreviewTokenClaims,\n options: IssuePreviewTokenOptions,\n): Promise<string> {\n const crypto = cryptoFor(options.crypto);\n if (crypto === undefined) {\n throw new Error('payload-live-preview: no Web Crypto implementation available to sign tokens');\n }\n const secret = secretBytes(options.secret);\n const now = (options.now ?? Date.now)();\n const ttl = Math.min(MAX_TTL_MS, Math.max(1, claims.ttlMs ?? DEFAULT_TTL_MS));\n const id = new Uint8Array(16);\n crypto.getRandomValues(id);\n const wire: WireClaims = {\n v: 1,\n aud: claims.audience,\n ...(claims.path !== undefined ? { pth: claims.path } : {}),\n ...(claims.locale !== undefined ? { loc: claims.locale } : {}),\n ...(claims.subject !== undefined ? { sub: claims.subject } : {}),\n pur: claims.purpose ?? DEFAULT_PURPOSE,\n iat: now,\n exp: now + ttl,\n jti: toBase64Url(id),\n };\n const payload = toBase64Url(encoder().encode(JSON.stringify(wire)));\n const signed = `${TOKEN_VERSION}.${payload}`;\n const key = await hmacKey(crypto, secret);\n const signature = new Uint8Array(await crypto.subtle.sign('HMAC', key, encoder().encode(signed)));\n return `${signed}.${toBase64Url(signature)}`;\n}\n\nfunction readToken(\n request: PreviewAuthorizationRequest,\n transport: PreviewTokenTransport | undefined,\n): string | null {\n if (transport?.kind === 'header') {\n return request.headers.get(transport.name ?? DEFAULT_HEADER_NAME);\n }\n let url: URL;\n try {\n url = new URL(request.url);\n } catch {\n return null;\n }\n const values = url.searchParams.getAll(transport?.param ?? DEFAULT_QUERY_PARAM);\n return values.length === 1 ? (values[0] ?? null) : null;\n}\n\nfunction parseClaims(bytes: Uint8Array): WireClaims | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(new TextDecoder().decode(bytes));\n } catch {\n return undefined;\n }\n if (typeof parsed !== 'object' || parsed === null) return undefined;\n const c = parsed as Record<string, unknown>;\n const optionalString = (key: string): boolean =>\n c[key] === undefined || typeof c[key] === 'string';\n if (\n c['v'] !== 1 ||\n typeof c['aud'] !== 'string' ||\n typeof c['pur'] !== 'string' ||\n typeof c['iat'] !== 'number' ||\n typeof c['exp'] !== 'number' ||\n typeof c['jti'] !== 'string' ||\n !optionalString('pth') ||\n !optionalString('loc') ||\n !optionalString('sub')\n ) {\n return undefined;\n }\n return c as unknown as WireClaims;\n}\n\nexport async function authorizeToken(\n request: PreviewAuthorizationRequest,\n strategy: SignedTokenStrategy,\n): Promise<PreviewAuthorization> {\n const secret = secretBytes(strategy.secret);\n const crypto = cryptoFor(strategy.crypto);\n if (crypto === undefined) return refused('unavailable');\n const token = readToken(request, strategy.transport);\n if (token === null || token.length === 0) return refused('missing-credential');\n if (token.length > MAX_TOKEN_LENGTH) return refused('invalid');\n const parts = token.split('.');\n if (parts.length !== 3 || parts[0] !== TOKEN_VERSION) return refused('invalid');\n const payloadText = parts[1] ?? '';\n const payloadBytes = fromBase64Url(payloadText);\n const signature = fromBase64Url(parts[2] ?? '');\n if (payloadBytes === undefined || signature?.byteLength !== 32) return refused('invalid');\n let verified: boolean;\n try {\n const key = await hmacKey(crypto, secret);\n verified = await crypto.subtle.verify(\n 'HMAC',\n key,\n signature,\n encoder().encode(`${TOKEN_VERSION}.${payloadText}`),\n );\n } catch {\n return refused('unavailable');\n }\n if (!verified) return refused('invalid');\n const claims = parseClaims(payloadBytes);\n if (claims === undefined) return refused('invalid');\n const now = (strategy.now ?? Date.now)();\n if (claims.exp <= now || claims.iat > claims.exp) return refused('expired');\n if (claims.aud !== strategy.audience) return refused('wrong-audience');\n if (claims.pur !== (strategy.purpose ?? DEFAULT_PURPOSE)) return refused('wrong-purpose');\n if (claims.pth !== undefined) {\n let pathname: string;\n try {\n pathname = new URL(request.url).pathname;\n } catch {\n return refused('invalid');\n }\n if (claims.pth !== pathname) return refused('wrong-path');\n }\n if (claims.loc !== undefined) {\n const locale = strategy.locale?.(request);\n if (locale !== claims.loc) return refused('wrong-locale');\n }\n if (strategy.replay !== undefined) {\n try {\n if (await strategy.replay.isUsed(claims.jti)) return refused('replayed');\n await strategy.replay.markUsed(claims.jti, claims.exp);\n } catch {\n return refused('unavailable');\n }\n }\n return {\n authorized: true,\n outcome: 'authorized',\n context: createAuthorizedPreviewContext({\n strategy: 'signed-token',\n subject: claims.sub,\n authorizedAt: now,\n expiresAt: claims.exp,\n scope: {\n audience: claims.aud,\n ...(claims.pth !== undefined ? { path: claims.pth } : {}),\n ...(claims.loc !== undefined ? { locale: claims.loc } : {}),\n },\n payloadHeaders: {},\n }),\n };\n}\n","/**\n * Authorized preview context: the one verdict every privileged preview\n * decision is keyed on. Intent (`?preview=true`, an iframe destination, a\n * referer) is client-chosen; this turns a session, a signed token or the\n * application's own verifier into a branded context. Threat model: ADR 0006.\n */\n\nimport {\n AUTHORIZED_PREVIEW_BRAND_KEY,\n createAuthorizedPreviewContext,\n isAuthorizedPreviewContext,\n type AuthorizedPreviewContext,\n type AuthorizedPreviewScope,\n type PreviewAuthorizationStrategyName,\n} from '@/types/authorized-preview';\nimport {\n refused,\n type PreviewAuthorization,\n type PreviewAuthorizationRequest,\n} from './preview-verdict';\nimport { authorizeSession, type PayloadSessionStrategy } from './preview-session';\nimport { authorizeToken, type SignedTokenStrategy } from './preview-token';\n\nexport {\n AUTHORIZED_PREVIEW_BRAND_KEY,\n isAuthorizedPreviewContext,\n type AuthorizedPreviewContext,\n type AuthorizedPreviewScope,\n type PreviewAuthorizationStrategyName,\n};\nexport {\n PreviewConfigurationError,\n type PreviewAuthorization,\n type PreviewAuthorizationOutcome,\n type PreviewAuthorizationRequest,\n} from './preview-verdict';\nexport { extractCookie, type FetchLike, type PayloadSessionStrategy } from './preview-session';\nexport {\n issuePreviewToken,\n type IssuePreviewTokenOptions,\n type PreviewTokenClaims,\n type PreviewTokenReplayStore,\n type PreviewTokenTransport,\n type SignedTokenStrategy,\n type SubtleCryptoLike,\n} from './preview-token';\n\n/** Claims a consumer verifier returns for a request it accepts. */\nexport interface PreviewVerifierClaims {\n readonly subject?: string;\n readonly expiresAt?: number;\n readonly scope?: AuthorizedPreviewScope;\n readonly payloadHeaders?: Readonly<Record<string, string>>;\n}\n\n/** The application's own verification: claims authorize, `null` refuses, a throw is `unavailable`. */\nexport interface VerifierStrategy {\n readonly type: 'verifier';\n readonly verify: (\n request: PreviewAuthorizationRequest,\n ) => Promise<PreviewVerifierClaims | null> | PreviewVerifierClaims | null;\n readonly now?: () => number;\n}\n\nexport type PreviewAuthorizationStrategy =\n PayloadSessionStrategy | SignedTokenStrategy | VerifierStrategy;\n\n/** Decide whether `request` is an authorized preview; refusals resolve to `{ authorized: false }` and only a `PreviewConfigurationError` throws. */\nexport async function authorizePreviewRequest(\n request: PreviewAuthorizationRequest,\n strategy: PreviewAuthorizationStrategy,\n): Promise<PreviewAuthorization> {\n switch (strategy.type) {\n case 'payload-session':\n return authorizeSession(request, strategy);\n case 'signed-token':\n return authorizeToken(request, strategy);\n case 'verifier':\n return authorizeVerifier(request, strategy);\n }\n}\n\nasync function authorizeVerifier(\n request: PreviewAuthorizationRequest,\n strategy: VerifierStrategy,\n): Promise<PreviewAuthorization> {\n let claims: PreviewVerifierClaims | null;\n try {\n claims = await strategy.verify(request);\n } catch {\n return refused('unavailable');\n }\n if (claims === null) return refused('invalid');\n const now = (strategy.now ?? Date.now)();\n if (claims.expiresAt !== undefined && claims.expiresAt <= now) return refused('expired');\n return {\n authorized: true,\n outcome: 'authorized',\n context: createAuthorizedPreviewContext({\n strategy: 'verifier',\n subject: claims.subject,\n authorizedAt: now,\n expiresAt: claims.expiresAt,\n scope: claims.scope ?? {},\n payloadHeaders: claims.payloadHeaders ?? {},\n }),\n };\n}\n","/**\n * Server-side preview-intent detection. Every signal here is client-controlled:\n * a positive result is a delivery hint, never proof of identity or permission.\n * Verify with `authorizePreviewRequest()` before anything privileged.\n */\n\n/** `query`: `?preview=true`; `fetch-dest`: `Sec-Fetch-Dest: iframe`; `referer`: an admin-origin Referer. */\nexport type PreviewSignal = 'query' | 'fetch-dest' | 'referer';\n\nexport interface PreviewRequestOptions {\n /** Which signals count. Default: all three. `['query']` is the adapters' 2.0 default. */\n readonly signals?: readonly PreviewSignal[];\n /** Query parameters (value `true` or `1`) that signal intent. Default `['preview', 'draft', 'livePreview']`. */\n readonly queryParams?: readonly string[];\n /** Admin origins whose Referer signals intent, e.g. `['https://cms.example.com']`. */\n readonly adminOrigins?: readonly string[];\n}\n\nconst DEFAULT_QUERY_PARAMS = ['preview', 'draft', 'livePreview'] as const;\n\n/** The request surface the predicate reads; `Request` satisfies it, Nitro/H3 events need a shim. */\nexport interface PreviewRequestLike {\n readonly url: string;\n readonly headers: { get(name: string): string | null };\n}\n\n/** Whether `request` carries live-preview intent. Intent, not authorization. */\nexport function hasPreviewIntent(\n request: PreviewRequestLike,\n options: PreviewRequestOptions = {},\n): boolean {\n const signals = new Set<PreviewSignal>(options.signals ?? ['query', 'fetch-dest', 'referer']);\n const queryParams = options.queryParams ?? DEFAULT_QUERY_PARAMS;\n\n if (signals.has('query')) {\n let url: URL | undefined;\n try {\n url = new URL(request.url);\n } catch {\n url = undefined;\n }\n if (url !== undefined) {\n for (const param of queryParams) {\n const value = url.searchParams.get(param);\n if (value === 'true' || value === '1') return true;\n }\n }\n }\n\n if (signals.has('fetch-dest') && request.headers.get('sec-fetch-dest') === 'iframe') {\n return true;\n }\n\n const adminOrigins = signals.has('referer') ? (options.adminOrigins ?? []) : [];\n if (adminOrigins.length > 0) {\n const referer = request.headers.get('referer');\n if (referer !== null) {\n try {\n const refererOrigin = new URL(referer).origin;\n for (const adminOrigin of adminOrigins) {\n try {\n if (new URL(adminOrigin).origin === refererOrigin) return true;\n } catch {\n // A malformed configured origin matches nothing.\n }\n }\n } catch {\n // A malformed referer is not a signal.\n }\n }\n }\n\n return false;\n}\n","/**\n * `highlight` plugin: flashes an outline on updated elements. Respects\n * `prefers-reduced-motion`; the stylesheet is shared per document across\n * clients through a lease (ADR 0002).\n */\n\nimport type { LivePreviewPlugin, PluginDisposer } from '../types';\n\nconst STYLE_ID = 'payload-live-preview-highlight';\nconst REDUCED_MOTION_CSS =\n '.lp-highlight{outline:2px solid rgba(0,102,204,0.85);outline-offset:2px;}';\nconst ANIMATED_CSS =\n '@keyframes lp-highlight{0%{outline:2px solid rgba(0,102,204,0.85);outline-offset:2px}100%{outline:2px solid transparent;outline-offset:2px}}.lp-highlight{animation:lp-highlight 0.6s ease-out;}';\n\ninterface StyleLease {\n readonly pluginOwned: boolean;\n readonly connected: () => boolean;\n readonly remove: () => void;\n owners: number;\n}\n\ninterface HighlightLease {\n owners: number;\n readonly pluginAdded: boolean;\n}\n\nconst styleLeases = new WeakMap<Document, StyleLease>();\nconst highlightLeases = new WeakMap<Element, HighlightLease>();\n\nexport const highlightPlugin: LivePreviewPlugin = {\n name: 'highlight',\n version: '1.0.0',\n init: (ctx) => {\n if (typeof document === 'undefined' || typeof window === 'undefined') return;\n const prefersReducedMotion =\n typeof window.matchMedia === 'function' &&\n window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n const releaseStyle = acquireStyle(document, prefersReducedMotion);\n const duration = prefersReducedMotion ? 1000 : 600;\n const activeTimers = new WeakMap<Element, PluginDisposer>();\n // Only armed timers are retained; one registration-owned cleanup drains them.\n const timerCleanups = new Set<PluginDisposer>();\n ctx.registerCleanup?.(() => {\n for (const cleanup of [...timerCleanups]) cleanup();\n releaseStyle();\n });\n ctx.events.on('elementUpdate', (e) => {\n const element = e.element;\n activeTimers.get(element)?.();\n const releaseHighlight = acquireHighlight(element);\n let disposed = false;\n const disposeTimer: PluginDisposer = () => {\n if (disposed) return;\n disposed = true;\n window.clearTimeout(handle);\n if (activeTimers.get(element) === disposeTimer) activeTimers.delete(element);\n timerCleanups.delete(disposeTimer);\n releaseHighlight();\n };\n const handle = window.setTimeout(disposeTimer, duration);\n timerCleanups.add(disposeTimer);\n activeTimers.set(element, disposeTimer);\n });\n },\n};\n\nfunction acquireStyle(document: Document, prefersReducedMotion: boolean): PluginDisposer {\n let lease = styleLeases.get(document);\n // HMR or a host DOM swap may drop the sheet without plugin teardown.\n if (lease !== undefined && !lease.connected()) {\n styleLeases.delete(document);\n lease = undefined;\n }\n if (lease === undefined) {\n lease = installStyle(document, prefersReducedMotion ? REDUCED_MOTION_CSS : ANIMATED_CSS);\n styleLeases.set(document, lease);\n }\n const acquiredLease = lease;\n acquiredLease.owners += 1;\n\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n acquiredLease.owners -= 1;\n if (acquiredLease.owners > 0) return;\n if (styleLeases.get(document) === acquiredLease) styleLeases.delete(document);\n if (acquiredLease.pluginOwned) acquiredLease.remove();\n };\n}\n\nfunction installStyle(document: Document, css: string): StyleLease {\n const existing = document.getElementById(STYLE_ID);\n if (existing instanceof HTMLStyleElement) {\n return {\n pluginOwned: false,\n connected: () => existing.isConnected,\n remove: () => undefined,\n owners: 0,\n };\n }\n const sheet = adoptSheet(document, css);\n if (sheet !== undefined) {\n return {\n pluginOwned: true,\n connected: () => document.adoptedStyleSheets.includes(sheet),\n remove: () => {\n document.adoptedStyleSheets = document.adoptedStyleSheets.filter((s) => s !== sheet);\n },\n owners: 0,\n };\n }\n const style = document.createElement('style');\n style.id = STYLE_ID;\n style.textContent = css;\n document.head.appendChild(style);\n return {\n pluginOwned: true,\n connected: () => style.isConnected,\n remove: () => {\n style.remove();\n },\n owners: 0,\n };\n}\n\n// A constructed sheet needs no nonce under `style-src`; `<style>` is only the fallback.\nfunction adoptSheet(document: Document, css: string): CSSStyleSheet | undefined {\n try {\n if (!Array.isArray(document.adoptedStyleSheets) || typeof CSSStyleSheet !== 'function') {\n return undefined;\n }\n const sheet = new CSSStyleSheet();\n if (typeof sheet.replaceSync !== 'function') return undefined;\n sheet.replaceSync(css);\n document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];\n return sheet;\n } catch {\n return undefined;\n }\n}\n\nfunction acquireHighlight(element: Element): PluginDisposer {\n let lease = highlightLeases.get(element);\n if (lease === undefined) {\n lease = { owners: 0, pluginAdded: !element.classList.contains('lp-highlight') };\n highlightLeases.set(element, lease);\n }\n const acquiredLease = lease;\n acquiredLease.owners += 1;\n element.classList.add('lp-highlight');\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n acquiredLease.owners -= 1;\n if (acquiredLease.owners > 0) return;\n highlightLeases.delete(element);\n if (acquiredLease.pluginAdded) element.classList.remove('lp-highlight');\n };\n}\n","/** `debug` plugin: logs every lifecycle event through the plugin context. */\n\nimport type { LivePreviewPlugin } from '../types';\n\nexport const debugPlugin: LivePreviewPlugin = {\n name: 'debug',\n version: '1.0.0',\n init: (ctx) => {\n ctx.events.on('init', () => {\n ctx.log('init');\n });\n ctx.events.on('connect', (e) => {\n ctx.log('connect ←', e.origin);\n });\n ctx.events.on('disconnect', (e) => {\n ctx.log('disconnect (', e.reason, ')');\n });\n ctx.events.on('cacheRefresh', (e) => {\n ctx.log('cacheRefresh', e.elementCount, 'elements,', e.fieldCount, 'fields');\n });\n ctx.events.on('beforeUpdate', (e) => {\n ctx.log('beforeUpdate', Object.keys(e.data.fields).length, 'fields');\n });\n ctx.events.on('afterUpdate', (e) => {\n ctx.log('afterUpdate', e.updatedCount, 'in', e.durationMs.toFixed(2), 'ms');\n });\n ctx.events.on('error', (e) => {\n ctx.log('error in', e.context, ':', e.error.message);\n });\n },\n};\n","/** `analytics` plugin: running totals over the update stream, read through `getStats()`. */\n\nimport type { LivePreviewPlugin } from '../types';\n\nexport interface AnalyticsSnapshot {\n readonly updateCount: number;\n readonly totalElements: number;\n readonly totalDurationMs: number;\n readonly averageDurationMs: number;\n}\n\nexport function createAnalyticsPlugin(): LivePreviewPlugin & {\n readonly getStats: () => AnalyticsSnapshot;\n} {\n let updateCount = 0;\n let totalElements = 0;\n let totalDurationMs = 0;\n\n return {\n name: 'analytics',\n version: '1.0.0',\n init: (ctx) => {\n ctx.events.on('afterUpdate', (e) => {\n updateCount += 1;\n totalElements += e.updatedCount;\n totalDurationMs += e.durationMs;\n });\n },\n getStats: (): AnalyticsSnapshot => ({\n updateCount,\n totalElements,\n totalDurationMs,\n averageDurationMs: updateCount === 0 ? 0 : totalDurationMs / updateCount,\n }),\n };\n}\n","/**\n * `documentSave` plugin: what to do when Payload saves the document.\n * `'silent'` (default) emits only; `'reload'` reloads and restores the scroll\n * position; `'revalidate'` POSTs to a revalidation endpoint; `'fetch'` runs\n * a custom handler.\n */\n\nimport type { LivePreviewPlugin } from '../types';\n\nconst SCROLL_KEY = 'payload-live-preview:scroll';\n\nfunction saveScrollPosition(): void {\n if (typeof window === 'undefined') return;\n try {\n sessionStorage.setItem(\n SCROLL_KEY,\n JSON.stringify({ href: window.location.href, x: window.scrollX, y: window.scrollY }),\n );\n } catch {\n // sessionStorage is unavailable in a sandboxed iframe without allow-same-origin.\n }\n}\n\nfunction restoreScrollPosition(): void {\n if (typeof window === 'undefined') return;\n try {\n const raw = sessionStorage.getItem(SCROLL_KEY);\n if (raw === null) return;\n sessionStorage.removeItem(SCROLL_KEY);\n const saved = JSON.parse(raw) as { href?: string; x?: number; y?: number };\n if (saved.href !== window.location.href) return;\n window.scrollTo(saved.x ?? 0, saved.y ?? 0);\n } catch {\n // A corrupt entry or unavailable storage: nothing to restore.\n }\n}\n\nfunction reloadPreservingScroll(): void {\n if (typeof window === 'undefined') return;\n saveScrollPosition();\n window.location.reload();\n}\n\nexport type DocumentSaveStrategy = 'silent' | 'reload' | 'revalidate' | 'fetch';\n\n/** Handler for the `fetch` strategy; the signal aborts when the plugin is removed. */\nexport type DocumentSaveHandler = {\n bivarianceHack(signal?: AbortSignal): void | Promise<void>;\n}['bivarianceHack'];\n\nexport interface DocumentSavePluginOptions {\n /** Default `'silent'`. */\n readonly strategy?: DocumentSaveStrategy;\n /**\n * `'revalidate'` endpoint, default `/api/revalidate`; the body is\n * `{ source: 'payload-live-preview' }`. The request is a plain `fetch` from\n * the preview page: cookies travel with it, there is no CSRF token, and a\n * bearer secret in `revalidateHeaders` would sit in page JavaScript. The\n * endpoint must authorise on its own (session cookie, same-origin check).\n */\n readonly revalidateUrl?: string;\n /** Extra request headers for `'revalidate'`; `Content-Type` is set already. */\n readonly revalidateHeaders?: Readonly<Record<string, string>>;\n /** `'fetch'` handler; rejections are logged, never thrown. */\n readonly handler?: DocumentSaveHandler;\n /** `'reload'` hard-refreshes when the revalidate request fails or returns non-2xx. */\n readonly onRevalidateFailure?: 'silent' | 'reload';\n}\n\nconst DEFAULT_REVALIDATE_URL = '/api/revalidate';\n\nexport function documentSavePlugin(options: DocumentSavePluginOptions = {}): LivePreviewPlugin {\n const strategy = options.strategy ?? 'silent';\n return {\n name: 'document-save',\n version: '1.1.0',\n init: (ctx) => {\n let active = true;\n const controllers = new Set<AbortController>();\n ctx.registerCleanup?.(() => {\n active = false;\n for (const controller of controllers) controller.abort();\n controllers.clear();\n });\n restoreScrollPosition();\n ctx.events.on('documentSave', () => {\n if (!active) return;\n if (strategy === 'silent') return;\n if (strategy === 'reload') {\n reloadPreservingScroll();\n return;\n }\n const controller = new AbortController();\n controllers.add(controller);\n const operation =\n strategy === 'fetch'\n ? runFetch(options, ctx.log, controller.signal, () => active)\n : runRevalidate(options, ctx.log, controller.signal, () => active);\n void operation.finally(() => {\n controllers.delete(controller);\n });\n });\n },\n };\n}\n\nasync function runFetch(\n options: DocumentSavePluginOptions,\n log: (...args: unknown[]) => void,\n signal: AbortSignal,\n isActive: () => boolean,\n): Promise<void> {\n if (!options.handler) {\n log('document-save: fetch strategy selected but no handler supplied');\n return;\n }\n try {\n await options.handler(signal);\n } catch (err) {\n if (!isActive() || signal.aborted) return;\n log('document-save handler threw:', err);\n }\n}\n\nasync function runRevalidate(\n options: DocumentSavePluginOptions,\n log: (...args: unknown[]) => void,\n signal: AbortSignal,\n isActive: () => boolean,\n): Promise<void> {\n if (typeof fetch === 'undefined') {\n log('document-save: revalidate strategy needs fetch — not available');\n return;\n }\n const url = options.revalidateUrl ?? DEFAULT_REVALIDATE_URL;\n let ok = false;\n try {\n const response = await fetch(url, {\n method: 'POST',\n signal,\n headers: {\n 'Content-Type': 'application/json',\n ...(options.revalidateHeaders ?? {}),\n },\n body: JSON.stringify({ source: 'payload-live-preview' }),\n });\n if (!isActive() || signal.aborted) return;\n ok = response.ok;\n if (!ok) log('document-save revalidate non-2xx:', response.status);\n } catch (err) {\n if (!isActive() || signal.aborted) return;\n log('document-save revalidate failed:', err);\n }\n if (!ok && options.onRevalidateFailure === 'reload') {\n reloadPreservingScroll();\n }\n}\n","/**\n * What each capability tells the runtime, for `inspect()` and consumer\n * diagnostics. Kept out of the runtime module so the inline bundle ships the\n * rules and not this prose. See ADR 0010.\n */\nimport type { ProtocolCapability } from './protocol-version';\n\nexport interface CapabilityDocumentation {\n /** The runtime behaviour that depends on the capability. */\n readonly gates: string;\n /** What the runtime does without it. */\n readonly fallback: string;\n}\n\nexport const CAPABILITY_DOCUMENTATION: Readonly<\n Record<ProtocolCapability, CapabilityDocumentation>\n> = {\n basic: {\n gates: 'data updates are applied to bound elements',\n fallback: 'none — every peer has it',\n },\n 'schema-json': {\n gates: 'field typing from fieldSchemaJSON (Payload 2.x) and the payload-2 profile',\n fallback: 'field types come from DOM heuristics and Lexical auto-detection',\n },\n locale: {\n gates:\n 'locale-aware field resolution (`title_de` before `title`) and the locale on island events',\n fallback: 'bindings resolve the unsuffixed field value',\n },\n 'preview-token': {\n gates: 'per-message token validation (library extension)',\n fallback: 'messages carry no token; validateToken cannot be satisfied',\n },\n 'nested-arrays': {\n gates: 'keyed array diffs below the top level',\n fallback: 'array updates replace the whole array',\n },\n 'recursive-diffs': {\n gates: 'recursive object diffs',\n fallback: 'nested objects re-render as a unit',\n },\n 'document-events': {\n gates: 'the `documentSave` runtime event, the document-save plugin and the payload-3 profile',\n fallback: 'no documentSave event; a save is not distinguishable from an edit',\n },\n 'relationship-events': {\n gates:\n 'the `relationshipUpdate` runtime event and an unconditional re-render of the update that carries it',\n fallback: 'a related document edited in a drawer shows up on the next data update only',\n },\n};\n","/**\n * Typed helpers emitting the `data-payload-*` attributes the runtime reads.\n * `bindByPath` records the path through a Proxy, so a rename follows.\n */\n\nimport type { FieldName } from './paths';\n\n/** A spreadable attribute record: `<h1 {...bind<Homepage>('heroTitle')}>`. */\nexport interface FieldBindingAttributes {\n readonly 'data-payload-field': string;\n readonly 'data-payload-attribute'?: string;\n readonly 'data-payload-type'?: string;\n readonly 'data-payload-richtext'?: string;\n readonly 'data-payload-html'?: string;\n readonly 'data-payload-locale'?: string;\n readonly 'data-payload-alt'?: string;\n readonly 'data-payload-href'?: string;\n readonly 'data-payload-array-template'?: string;\n}\n\nexport interface BindOptions {\n /** Attribute to write instead of the text content, e.g. `'src'` for `<img>`. */\n readonly attribute?: string;\n /** Explicit field type, bypassing schema detection. */\n readonly type?: string;\n /** Mark the binding as Lexical rich text; needed only when the initial render is empty. */\n readonly richtext?: boolean;\n /** Render the value as sanitised HTML rather than text. */\n readonly html?: boolean;\n /** Lock this element to one locale, overriding the message locale. */\n readonly locale?: string;\n /** Field whose value becomes the image `alt`. */\n readonly alt?: string;\n /** Field whose value becomes the link `href`. */\n readonly href?: string;\n /** Markup per array item with `{{value}}` placeholders. */\n readonly arrayTemplate?: string;\n}\n\n/** `bind<Homepage>('heroTitle')`; without `T` any string is accepted. */\nexport function bind<T = Record<string, unknown>>(\n field: FieldName<T>,\n options?: BindOptions,\n): FieldBindingAttributes {\n return buildAttributes(field, options);\n}\n\n/** `bindByPath<Homepage>(d => d.slides[0].title)` → `slides.title`; array indices are dropped because bindings resolve against the schema. */\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters\nexport function bindByPath<T = Record<string, unknown>>(\n picker: (data: T) => unknown,\n options?: BindOptions,\n): FieldBindingAttributes {\n const path = recordPath(picker);\n if (path.length === 0) {\n throw new Error(\n 'bindByPath: the picker did not read any field — return data.<field> instead of a constant',\n );\n }\n return buildAttributes(path.join('.'), options);\n}\n\nfunction buildAttributes(field: string, options: BindOptions | undefined): FieldBindingAttributes {\n if (field.length === 0) {\n throw new Error('bind: field name must be a non-empty string');\n }\n const attrs: {\n 'data-payload-field': string;\n 'data-payload-attribute'?: string;\n 'data-payload-type'?: string;\n 'data-payload-richtext'?: string;\n 'data-payload-html'?: string;\n 'data-payload-locale'?: string;\n 'data-payload-alt'?: string;\n 'data-payload-href'?: string;\n 'data-payload-array-template'?: string;\n } = { 'data-payload-field': field };\n if (options?.attribute !== undefined) attrs['data-payload-attribute'] = options.attribute;\n if (options?.type !== undefined) attrs['data-payload-type'] = options.type;\n // Presence attributes: the runtime tests for the attribute, not its value.\n if (options?.richtext === true) attrs['data-payload-richtext'] = '';\n if (options?.html === true) attrs['data-payload-html'] = '';\n if (options?.locale !== undefined) attrs['data-payload-locale'] = options.locale;\n if (options?.alt !== undefined) attrs['data-payload-alt'] = options.alt;\n if (options?.href !== undefined) attrs['data-payload-href'] = options.href;\n if (options?.arrayTemplate !== undefined) {\n attrs['data-payload-array-template'] = options.arrayTemplate;\n }\n return attrs;\n}\n\nfunction recordPath(picker: (data: never) => unknown): string[] {\n const path: string[] = [];\n const proxy: unknown = new Proxy(\n {},\n {\n get(_target, prop: string | symbol): unknown {\n if (typeof prop === 'symbol') return undefined;\n if (/^\\d+$/.test(prop)) return proxy;\n path.push(prop);\n return proxy;\n },\n },\n );\n try {\n picker(proxy as never);\n } catch {\n // A picker doing math or JSX on the proxy throws after recording the path it meant.\n }\n return path;\n}\n","/**\n * Binding helpers gated on one authorization verdict per request: the\n * attributes publish the content model, so an unauthorized response carries\n * none and a binding is suppressed whole, never in part. See ADR 0006.\n */\n\nimport {\n isAuthorizedPreviewContext,\n type AuthorizedPreviewContext,\n} from '@/types/authorized-preview';\nimport { bind, bindByPath, type BindOptions, type FieldBindingAttributes } from './bind';\nimport type { FieldName } from './paths';\n\nexport interface OwnerBindingAttributes {\n readonly 'data-payload-owner': string;\n}\n\n/** No attributes at all: an unauthorized response is byte-identical to one that never knew about live preview. */\nexport type SuppressedBinding = Readonly<Record<string, never>>;\n\nconst SUPPRESSED: SuppressedBinding = Object.freeze({});\n\nexport interface PreviewBindingsCommonOptions {\n /** Document this subtree belongs to, emitted as `data-payload-owner`; needed with `scopeBindingsByOwner`. */\n readonly owner?: string;\n}\n\n/** The verdict from `authorizePreviewRequest()`, or `null` for a public response. Only a branded context authorizes emission. */\nexport interface PreviewBindingsOptions extends PreviewBindingsCommonOptions {\n readonly authorization: AuthorizedPreviewContext | null;\n}\n\n/** Request-scoped binding helpers carrying one authorization decision. */\nexport interface PreviewBindings {\n readonly authorized: boolean;\n /** Typed field binding, or nothing while unauthorized. */\n bind: <T = Record<string, unknown>>(\n field: FieldName<T>,\n options?: BindOptions,\n ) => FieldBindingAttributes | SuppressedBinding;\n /** Rename-safe field binding, or nothing while unauthorized. */\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters\n bindByPath: <T = Record<string, unknown>>(\n picker: (data: T) => unknown,\n options?: BindOptions,\n ) => FieldBindingAttributes | SuppressedBinding;\n /** Owner marker for this subtree, or nothing while unauthorized or without an owner. */\n owner: () => OwnerBindingAttributes | SuppressedBinding;\n}\n\n/** Request-scoped `bind`, `bindByPath` and `owner`, all suppressed unless `authorization` is a real context. */\nexport function createPreviewBindings(options: PreviewBindingsOptions): PreviewBindings {\n // A copied or hand-written context is a public response.\n const authorized = isAuthorizedPreviewContext(options.authorization);\n const owner = options.owner !== undefined && options.owner.length > 0 ? options.owner : undefined;\n\n return Object.freeze({\n authorized,\n bind: <T = Record<string, unknown>>(\n field: FieldName<T>,\n bindOptions?: BindOptions,\n ): FieldBindingAttributes | SuppressedBinding =>\n authorized ? bind<T>(field, bindOptions) : SUPPRESSED,\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters\n bindByPath: <T = Record<string, unknown>>(\n picker: (data: T) => unknown,\n bindOptions?: BindOptions,\n ): FieldBindingAttributes | SuppressedBinding =>\n authorized ? bindByPath<T>(picker, bindOptions) : SUPPRESSED,\n owner: (): OwnerBindingAttributes | SuppressedBinding =>\n authorized && owner !== undefined ? { 'data-payload-owner': owner } : SUPPRESSED,\n });\n}\n"],"mappings":"AAAA,ICIaA,EDFA,eEEN,SAASC,sBACd,OAGF,WACE,GAAwB,oBAAbC,SAA0B,OACrC,MAAMC,EAAOD,SAASE,gBAAgBC,aAAa,QACnD,OAAgB,OAATF,GAAiC,IAAhBA,EAAKG,YAAe,EAAYH,CAC1D,CAPSI,IAST,WACE,GAAyB,oBAAdC,UAA2B,OACtC,MAAML,EAAOK,UAAUC,SACvB,MAAuB,iBAATN,GAAqBA,EAAKG,OAAS,EAAIH,OAAO,CAC9D,CAb2BO,IAHH,IAIxB,CCEA,IAAMC,EAAa,4BAoBbC,iBAAA,IAAqBC,QAa3B,SAASC,EAAkBC,GACL,OAAhBA,EAAMC,QACRC,aAAaF,EAAMC,OACnBD,EAAMC,MAAQ,MAEhBD,EAAMG,aAAaC,SACnBJ,EAAMG,YAAc,IACtB,CAEO,IAAME,EAAN,MACYC,OACAnB,SACTa,MAA8B,KAEtC,WAAAO,CAAYC,EAAiBC,GAC3B,MAAMC,EAAiBD,IAAuC,oBAAbtB,SAA2B,KAAOA,UAC7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,IAEnC8P,EAAU6D,YAAcnlB,EAAKmlB,YAAW7D,EAAU6D,UAAYnlB,EAAKmlB,WAChE7D,EACT,CAEA,SAASqD,GAAY3G,GACnB,OAAOA,EAAKD,WAAaqH,KAAKC,WAAsD,KAAxCrH,EAAKmH,WAAa,IAAI1hB,OAAOnJ,MAC3E,CAEA,SAASkqB,GAAStjB,EAASC,GACzB,OAAID,EAAE6c,WAAa5c,EAAE4c,aACjB7c,aAAakjB,SAAWjjB,aAAaijB,UAChCljB,EAAE4L,UAAY3L,EAAE2L,SAAW5L,EAAEmhB,eAAiBlhB,EAAEkhB,aAG3D,CC/KA,IAkQIiD,GAlQEC,kBAAA,IAAwCvmB,IAAI,CAChD,IACA,KACA,SACA,IACA,KACA,IACA,IACA,IACA,SACA,OACA,QACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,aACA,OACA,MACA,MACA,OACA,MACA,IACA,OACA,MACA,UACA,UACA,QACA,SACA,SACA,MACA,SACA,aACA,MACA,UACA,SACA,QACA,QACA,MACA,MACA,KACA,OACA,OACA,OACA,IACA,QACA,QACA,QACA,QACA,KACA,KACA,KACA,UACA,WACA,QAIIwmB,kBAAA,IAAyCxmB,IAAI,CACjD,QACA,SACA,WACA,SACA,SACA,UAIIymB,kBAAA,IAA6CzmB,IAAI,CACrD,SACA,QACA,SACA,SACA,QACA,OACA,OACA,OACA,OACA,QACA,SACA,SACA,WACA,MACA,OACA,WACA,QACA,WACA,WACA,aAGI0mB,kBAAA,IAAuC1mB,IAAI,CAC/C,KACA,QACA,OACA,MACA,QACA,OACA,aAGI2mB,GAAmB,QACnBC,GAAmB,QAGnBC,GAA6D,CACjE3kB,iBAAG,IAAIlC,IAAI,CAAC,OAAQ,SAAU,MAAO,WAAY,WAAY,SAC7D8mB,mBAAK,IAAI9mB,IAAI,CAAC,MAAO,SAAU,QAAS,MAAO,QAAS,SAAU,UAAW,aAC7E+mB,uBAAS,IAAI/mB,IAAI,IACjB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