payload-live-preview 1.2.2 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/astro/index.js +1 -1
- package/dist/adapters/astro/index.js.map +1 -1
- package/dist/adapters/astro/middleware-entry.js +1 -1
- package/dist/adapters/astro/middleware-entry.js.map +1 -1
- package/dist/adapters/nextjs/index.js +1 -1
- package/dist/adapters/nextjs/index.js.map +1 -1
- package/dist/adapters/nuxt/index.js +1 -1
- package/dist/adapters/nuxt/index.js.map +1 -1
- package/dist/adapters/sveltekit/index.js +1 -1
- package/dist/adapters/sveltekit/index.js.map +1 -1
- package/dist/core.cjs +1 -1
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +19 -0
- package/dist/core.d.ts +19 -0
- package/dist/core.js +1 -1
- package/dist/core.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +72 -1
- package/dist/index.d.ts +72 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
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","token","nextTimer","#requestFrame","completed","nextHandle","gateActive","batchEntry","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","isDocumentRoot","readyState","onReady","#startNow","#rollbackFailedStart","#reportError","once","observerRoot","readDocumentBody","#buildCacheAndObserve","#isRunning","emitWhile","delay","#sendReadyAfterStart","#releaseRuntimeResources","deferredStart","#runCleanup","cleanup","refreshCache","updateCount","previousBindings","removed","#applyNegotiation","remoteVersion","transaction","schemaIndex","cancelled","#processUpdate","#resolveIncomingFields","listenerCount","cancel","#scheduleAllFields","isCurrent","ownerKeys","#ownerKeysForUpdate","bindings","transformedValue","#transformForBinding","#diagnoseOrphanFields","#ownsAnyBinding","binding","#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","active","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","lockedOrigin","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","sort","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","started","resolveDestroy","rejectDestroy","inFlight","reject","finally","use","unuse","plugins","destroyed","initLivePreview","client","RUNTIME_SOURCE","RUNTIME_BUILD_INFO","generatedAt","generateInlineScript","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","version","prefersReducedMotion","matchMedia","releaseStyle","acquireStyle","duration","activeTimers","timerCleanups","releaseHighlight","acquireHighlight","disposeTimer","HTMLStyleElement","pluginOwned","head","owners","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","F","se","Ee","z","xi","Le","Pe","ct","ci","bi","Ri","yi","D","Si","h","R","jo","Vo","di","Io","Hi","gi","No","W","V","X","Ge","ye","L","_o","p","Re","G","fi","le","Tn","ri","Fo","ai","tn","Do"],"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/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.2.2\",\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 \"./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 },\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 readonly deferred: number;\n readonly durationMs: number;\n readonly identity?: MessageRevision;\n readonly data?: PayloadLivePreviewData;\n}\n\nconst DEFAULT_DEBOUNCE_MS = 50;\nconst 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]?.(this.#statsFor(entry, applied, 0, performance.now() - t0));\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 #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 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)) applied += 1;\n }\n } finally {\n this.s[SchedulerSlot.ActiveFlushes].delete(pending);\n }\n const stats = this.#statsFor(batchEntry, applied, deferred, performance.now() - t0);\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 ): FlushStats {\n return {\n applied,\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 { 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 /** 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}\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];\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}\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];\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' });\n }\n log('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 ];\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 ];\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');\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 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 // 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 next = negotiateProtocol(remoteVersion);\n if (next.negotiated === this.l[RuntimeLifecycleSlot.ProtocolNegotiation].negotiated) {\n return;\n }\n this.l[RuntimeLifecycleSlot.ProtocolNegotiation] = next;\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 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) continue;\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] 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] 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 });\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] 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' },\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] 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' },\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 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');\n }\n }\n\n #reportError(cause: unknown, context: string): 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 });\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] 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 '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n '/': '/',\n '`': '`',\n '=': '=',\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 '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\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] 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] 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 { 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' });\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 ...(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 * 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 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","// 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?0:(Promise.resolve(t).catch(()=>{}),1)}function e(e){return(...i)=>{try{t(e(...i))}catch{}}}function i(){}function n(){return 1}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?0: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 0;let e=t;return e.hasAttribute(ke)?1:null!==e.querySelector(`[${ke}]`)}function h(t){if(!Array.isArray(t))return[];let e=[];for(let i of t){let t=c(i);t&&e.push(t)}return e}function c(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 d(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?1:e(t)}function g(t){if(\\\"object\\\"!=typeof t||null===t)return 0;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 1}return 0}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 0;try{return encodeURIComponent(t),1}catch{return 0}}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 0;let e=t.trim();if(0===e.length||$i.test(e))return 0;if(e.startsWith(\\\"#\\\")||e.startsWith(\\\"?\\\")||e.startsWith(\\\"//\\\")||e.startsWith(\\\"/\\\"))return 1;try{let t=new URL(e);return Si.has(t.protocol)}catch{return Ai.test(e)}}function S(t){if(!w(t))return 0;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=0){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=1;for(let t of e.split(\\\".\\\")){if(Pi.has(t)||null===i||\\\"object\\\"!=typeof i){n=0;break}if(i=T(i,t),void 0===i){n=0;break}}if(n)return i}return void 0===i?void 0:T(t,`${e}_${i}`)}function T(t,e){if(!Pi.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(zi.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 j(t){if(\\\"object\\\"!=typeof t||null===t)return;let e=t.id;return\\\"string\\\"==typeof e||\\\"number\\\"==typeof e?e:void 0}function I(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!==j(t))?function(t,e){let i=[],n=new Map;for(let e=0;e<t.length;e+=1){let i=j(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=j(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];I(u)===I(s)?(a!==l&&i.push({kind:\\\"move\\\",from:a,to:l,value:s}),R(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)R(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 R(t,e){if(Object.is(t,e))return 1;if(\\\"object\\\"!=typeof t||\\\"object\\\"!=typeof e||null===t||null===e)return 0;let i=t,n=e,r=Object.keys(i),l=Object.keys(n);if(r.length!==l.length)return 0;for(let t of r)if(!Object.is(i[t],n[t]))return 0;return 1}function _(t){return 9===t.nodeType}function L(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 W(t,e){return t.generation===e.generation&&t.revision===e.revision}function P(t){return null==t?0:\\\"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 0;try{return window.self!==window.top}catch{return 1}}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||!wn.test(t.origin)?void 0:t.origin}catch{return}}function V(t,e){let i=G();if(!i)throw new Rn(\\\"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(On))t.set(e,i);return{allowedTags:Tn,attrByTag:t}}let e=new Set(Tn);for(let i of t.additionalAllowedTags??[])e.add(i);let i=new Map;for(let[t,e]of Object.entries(On))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===In?H(i,e):i.nodeType===En&&i.remove()}function H(t,e){let i=t.tagName.toLowerCase();if(Nn.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(!(xn.has(i)||i.startsWith(Mn)||i.startsWith(Cn))){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 0}return 1}function J(t,e){_n.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=Ln[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(Fn,t=>Pn[t])}function tt(t){return\\\"\\\"===t?\\\"\\\":t.replace(Un,t=>Dn[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 Gn.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 0;let e=t.root;return\\\"object\\\"==typeof e&&null!==e&&\\\"children\\\"in e?Array.isArray(e.children):0}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 _n.get(t)}(t.type);return e?e(t,Lt):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 ct(){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(Wt))return function(t,e,i){t.has(e)||(t.add(e),pe(`[live-preview] 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),0;r.includes(\\\"\\\\n\\\")||r.includes(\\\"\\\\r\\\")?n.innerHTML=et(r):n.textContent=r}else n.value=r})}}function dt(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 dt(t)}function gt(t){return Array.isArray(t)?t.map(t=>gt(t)).join(\\\", \\\"):dt(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,dt)}function St(t){return dt(t)}function $t(t){let{template:e,container:i,patches:n,nextItems:r,store:l,forceRender:s=0}=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=jt(o,te),u=new Set,h=[];for(let c=0;c<i.length;c+=1){let d=i[c],f=Ot(d),p=void 0===f?o[c]??null:It(a,f)??null;null!==p&&u.has(p)&&(p=null),null!==p&&u.add(p);let g=n.replaces.has(c),m=r||n.renders.has(c)||null===p?Et(t.ownerDocument,e,d,c):void 0;if(null===m)return null;let y=void 0===m?[]:Tt(g?null:p,m,d,l,s);if(null===y)return null;h.push([c,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=0;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=1),u=o}if(null===u)continue;let h=i.children[n]??null;u!==h&&(i.insertBefore(u,h),s=1),l.add(u)}for(let t of Array.from(i.children))l.has(t)||(t.remove(),s=1);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=jt(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=It(l,e)??null,u=t.getAttribute(ie),h=u?s:null,c=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&&c!==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 0;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 jt(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 It(t,e){return t.get(e)?.pop()}function Et(t,e,i,n){let r=function(t,e,i){return bt(t,e,i,dt)}(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 Rt(){let t=new WeakMap,e=new WeakSet,i=new WeakMap;return{name:\\\"structural-array\\\",render:$((n,r)=>{if(!Array.isArray(r))return 0;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] 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),0;let o=t.get(l),a=_t(l),u=o?.values??function(t){return t.map((t,e)=>null===t?{__payloadDomPosition:e}:{id:t})}(a),h=E(u,r),c=function(t,e,i){return void 0===t?1:t.template!==e||!function(t,e){return t.length!==e.length?0:t.every((t,i)=>t===e[i])}(t.domSnapshot,i)}(o,s,a);if(0===h.length&&!c)return t.set(l,{values:r.slice(),template:s,domSnapshot:a}),0;let d=$t({template:s,container:l,patches:h,nextItems:r,store:i,forceRender:c});return null===d?0:(t.set(l,{values:r.slice(),template:s,domSnapshot:_t(l)}),d?void 0:0)})}}function _t(t){return Array.from(t.children,t=>t.getAttribute(te))}var Lt,Wt,Pt,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:1,configurable:1,writable:1,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),ce=(t,e,i,n)=>(ae(t,e,\\\"write to private field\\\"),n?n.call(t,i):e.set(t,i),i),de=(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 de(this,be,Se).call(this,ue(this,ye),t,e)}once(t,e){return de(this,be,Se).call(this,ue(this,ve),t,e)}off(t,e){de(this,be,$e).call(this,ue(this,ye),t,e),de(this,be,$e).call(this,ue(this,ve),t,e)}async emit(t,e){await de(this,be,we).call(this,t,e)}async emitWhile(t,e,i){return de(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?.()??1;if(!n())return 0;let r=ue(this,ye).get(t);if(r)for(let i of[...r])if(!n()||(await de(this,be,Ae).call(this,i,e,t),!n()))return 0;if(!n())return 0;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 de(this,be,Ae).call(this,r,e,t),!n()))return 0}return n()},Se=function(t,e,i){let n=t.get(e);return n||(n=new Set,t.set(e,n)),n.add(i),()=>{de(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] 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\\\",je=\\\"data-payload-array-separator\\\",Ie=\\\"data-payload-locale\\\",Ee=\\\"data-payload-richtext\\\",Re=\\\"data-payload-html\\\",_e=\\\"data-payload-array\\\",Le=\\\"data-payload-structural\\\",We=\\\"data-payload-owner\\\",Pe=[ke,Te,Ne,xe,Me,Ce,Oe,je,Ie,Ee,Re,_e,Le,We,\\\"type\\\"],Fe=`[${ke}]`,De=`[${We}]`,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);ce(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)?de(this,He,Ye).call(this,t):void 0,i=ue(this,Ge).get(t);if(void 0!==e)return void 0!==i&&de(this,He,qe).call(this,i,e)?(ue(this,Ge).set(t,e),e):(void 0!==i&&de(this,He,Je).call(this,t,i),de(this,He,Xe).call(this,e),ue(this,Ge).set(t,e),e);void 0!==i&&de(this,He,Je).call(this,t,i)}remove(t){let e=ue(this,Ge).get(t);return e?de(this,He,Je).call(this,t,e):0}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(),ce(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 0;let i=ue(this,Ve).get(t.fieldName);if(!i)return 0;let n=i.indexOf(t);return n<0?0:(i[n]=e,1)},Je=function(t,e){let i=ue(this,Ve).get(e.fieldName);if(!i)return ue(this,Ge).delete(t),0;let n=i.indexOf(e);return n<0?(ue(this,Ge).delete(t),0):(i.splice(n,1),0===i.length&&ue(this,Ve).delete(e.fieldName),ue(this,Ge).delete(t),1)},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(Re))return\\\"html\\\";if(t.hasAttribute(Le))return\\\"structural-array\\\";if(t.hasAttribute(_e))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(je),h=t.getAttribute(Ie),c=function(t){let e=t.closest(De)?.getAttribute(We);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!==c?{owner:c}:{}}},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=>{de(this,Qe,ti).call(this,t,i)}),r=new IntersectionObserver(t=>{de(this,Qe,ei).call(this,t,i)},{rootMargin:this.s[2],threshold:0}),n.observe(t,{childList:1,subtree:1,attributes:1,attributeFilter:[...Pe]})}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(!de(this,Qe,ii).call(this,e)||!function(t){for(let e of t){if(\\\"attributes\\\"===e.type&&null!==e.attributeName&&Pe.includes(e.attributeName)&&(e.attributeName===ke||e.attributeName===We||e.target.nodeType===Ze&&e.target.hasAttribute(ke)))return 1;for(let t of e.addedNodes)if(u(t))return 1;for(let t of e.removedNodes)if(u(t))return 1}return 0}(t)||!de(this,Qe,ii).call(this,e))return;null!==this.s[6]&&clearTimeout(this.s[6]);let i=setTimeout(()=>{!de(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(!de(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,1),!de(this,Qe,ii).call(this,e)))return}else if(this.s[3].has(t)&&(this.s[3].delete(t),this.s[0].onVisibilityChange(t,0),!de(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=0,i=t=>{if(!e||this.s[2]!==i)return;let n=this.s[4];try{de(this,li,si).call(this,t,n)}catch{let e=\\\"\\\";try{e=t.origin}catch{}de(this,li,ci).call(this,\\\"shape\\\",e,n)}};this.s[4]+=1,de(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,de(this,li,mi).call(this));try{t.removeEventListener(\\\"message\\\",i)}catch{}throw e}if(this.s[2]===i)e=1;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,de(this,li,mi).call(this),e.removeEventListener(\\\"message\\\",i))}advanceGeneration(){return void 0===this.s[3]?0:(this.s[4]+=1,de(this,li,mi).call(this),1)}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(!de(this,li,pi).call(this,e))return;let i=t.origin;if(!de(this,li,pi).call(this,e))return;if(!de(this,li,di).call(this,i,e)){de(this,li,ci).call(this,\\\"origin\\\",i,e);return}let n=t.data;if(!de(this,li,pi).call(this,e))return;let r=function(t){return\\\"object\\\"==typeof t&&null!==t&&\\\"type\\\"in t?\\\"string\\\"==typeof t.type:0}(n);if(!de(this,li,pi).call(this,e))return;if(!r){de(this,li,ci).call(this,\\\"shape\\\",i,e);return}let l=n.type;if(de(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(!de(this,li,pi).call(this,e))return;if(!t){de(this,li,ci).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(!de(this,li,pi).call(this,e))return;de(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(!de(this,li,pi).call(this,e))return;if(!t){de(this,li,ci).call(this,\\\"shape\\\",i,e);return}let r;try{r=this.s[1].onDocumentEvent}catch{return}if(!de(this,li,pi).call(this,e))return;de(this,li,fi).call(this,r,n,i);return}default:de(this,li,ci).call(this,\\\"type\\\",i,e)}},oi=function(t,e,i){if(!de(this,li,pi).call(this,i))return;let n=t.data;if(!de(this,li,pi).call(this,i))return;let r=g(n);if(!de(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(!de(this,li,pi).call(this,i))return;if(void 0===l){de(this,li,hi).call(this,t,e,i,s);return}if(1==t.ready&&void 0===n){de(this,li,hi).call(this,t,e,i,void 0);return}let o={generation:i,message:t,origin:e,messageRevision:s,settled:0,approved:0};this.s[6].push(o);let a;try{a=l(t.previewToken,e)}catch{de(this,li,ai).call(this,o,0);return}\\\"boolean\\\"!=typeof a?Promise.resolve(a).then(t=>{de(this,li,ai).call(this,o,1==t)},()=>{de(this,li,ai).call(this,o,0)}):de(this,li,ai).call(this,o,a)},ai=function(t,e){de(this,li,pi).call(this,t.generation)&&(t.approved=e,t.settled=1,de(this,li,ui).call(this,t.generation))},ui=function(t){for(;de(this,li,pi).call(this,t);){let e=this.s[6][this.s[7]];if(void 0===e)return;if(de(this,li,di).call(this,e.origin,t)){if(!e.settled)return;de(this,li,gi).call(this,e)&&(e.approved?de(this,li,hi).call(this,e.message,e.origin,e.generation,e.messageRevision):de(this,li,ci).call(this,\\\"token\\\",e.origin,e.generation))}else{if(!de(this,li,gi).call(this,e))continue;de(this,li,ci).call(this,\\\"origin\\\",e.origin,e.generation)}}},hi=function(t,e,i,n){if(!de(this,li,pi).call(this,i))return;let r;try{r=this.s[1].onUpdate}catch{return}de(this,li,pi).call(this,i)&&(void 0===n?de(this,li,fi).call(this,r,t,e):de(this,li,fi).call(this,r,t,e,n))},ci=function(t,e,i){if(!de(this,li,pi).call(this,i))return;let n;try{n=this.s[1].onInvalid}catch{return}de(this,li,pi).call(this,i)&&void 0!==n&&de(this,li,fi).call(this,n,t,e)},di=function(t,e){if(!de(this,li,pi).call(this,e))return 0;try{return 1==this.s[0](t)&&de(this,li,pi).call(this,e)}catch{return 0}},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?0:(e[7]+=1,e[7]===e[6].length?(de(this,li,mi).call(this),1):(e[7]>=1024&&2*e[7]>=e[6].length&&(e[6]=e[6].slice(e[7]),e[7]=0),1))},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 0;let e=this.s[0];return this.s[0]=t,this.s[1](t,e),1}},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 0;try{return encodeURIComponent(t),1}catch{return 0}}(t.data.id):0}catch{return 0}}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:0,...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??0,e.getCacheSize,e.onFlush,i,n,new Map,new Map,new Set,null,0,null,0,null,0]}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}),de(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||(de(this,Mi,Wi).call(this),de(this,Mi,_i).call(this),this.s[16]=t,this.s[17]=0)}cancelRevision(t){A(t,this.s[16])&&(de(this,Mi,Wi).call(this),de(this,Mi,_i).call(this),this.s[17]=1)}flushNow(){return de(this,Mi,Wi).call(this),de(this,Mi,ji).call(this)}notifyVisible(t){let e=this.s[10],i=e.get(t);if(!i||(e.delete(t),!de(this,Mi,Ii).call(this,i)))return;let n=performance.now(),r=de(this,Mi,Ei).call(this,i)?1:0;this.s[6]?.(de(this,Mi,Li).call(this,i,r,0,performance.now()-n))}retarget(t){de(this,Mi,Ri).call(this,this.s[9],t),de(this,Mi,Ri).call(this,this.s[10],t);for(let e of this.s[11])de(this,Mi,Ri).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(){de(this,Mi,Wi).call(this),de(this,Mi,_i).call(this),this.s[16]=null,this.s[17]=0}get pendingCount(){return this.s[9].size}get replayCount(){return this.s[10].size}},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,de(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=0,n=this.s[7](()=>{this.s[15]===t&&(i=1,this.s[14]=null,de(this,Mi,ji).call(this))});!i&&this.s[15]===t&&(this.s[14]=n)},ji=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=0;this.s[11].add(i);try{for(let t of i.values()){if(!de(this,Mi,Ii).call(this,t))continue;let i=!e||this.s[2](t.target.element);if(de(this,Mi,Ii).call(this,t)){if(n??(n=t),!i){this.s[10].set(t.target.element,t),l+=1;continue}this.s[10].delete(t.target.element),de(this,Mi,Ei).call(this,t)&&(r+=1)}}}finally{this.s[11].delete(i)}let s=de(this,Mi,Li).call(this,n,r,l,performance.now()-t);return this.s[6]?.(s),s},Ii=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 0!=e(t)||!function(t){return Ni.has(t)}(e)},Ri=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}},_i=function(){this.s[9].clear(),this.s[10].clear();for(let t of this.s[11])t.clear()},Li=function(t,e,i,n){return{applied:e,deferred:i,durationMs:n,...void 0!==t?.identity?{identity:t.identity}:{},...void 0!==t?.data?{data:t.data}:{}}},Wi=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)},Pi=new Set([\\\"__proto__\\\",\\\"prototype\\\",\\\"constructor\\\"]),Fi=\\\"payload-live-preview-a11y\\\",Di=new WeakMap,Ui=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=Di.get(t);return e??(e=[null,0,null,0,null]),Di.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(Fi);return e[1]=null===n,n||(n=t.createElement(\\\"div\\\"),n.id=Fi,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,Di.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}},zi=new Set([\\\"tabs\\\",\\\"row\\\",\\\"collapsible\\\"]),Vi={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\\\"},Gi=[0,500,1e3,2e3],Bi=class{constructor(t){he(this,Hi);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??L,h=t.onHeartbeatTimeout,c=void 0===t.log?i:e(t.log),f=void 0===t.warn?pe:e(t.warn),p=function(t){if(0==t.enableA11y)return null;let e=void 0===t.root?void 0:9===t.root.nodeType?t.root:t.root.ownerDocument;return new Ui(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)=>{c(...t)}}):null,m=new ze,y=new Ke({onStructuralChange:()=>{de(this,Hi,Ki).call(this)},onVisibilityChange:(t,e)=>{e&&this.d[3].notifyVisible(t)}},{...void 0!==t.intersectionRootMargin?{intersectionRootMargin:t.intersectionRootMargin}:{}}),v=new xi($(t=>de(this,Hi,dn).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=>{de(this,Hi,fn).call(this,t)}}),b=new ri(t.originMatcher,{onUpdate:(t,e,i)=>{de(this,Hi,tn).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\\\"})}c(\\\"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:()=>{de(this,Hi,pn).call(this)}});this.d=[n,m,y,v,b,w,S,r,l,s,o,a,u,h,c,f,[],p,g,1==t.scopeBindingsByOwner],this.l=[void 0,void 0,void 0,d(void 0),0,null,0,null,new Set,0,0]}start(){if(this.l[4])return 0;this.l[4]=1;let t=this.d[10];if(_(t)&&\\\"loading\\\"===t.readyState){let e=()=>{if(this.l[4]){this.l[5]=null;try{de(this,Hi,qi).call(this)}catch(t){de(this,Hi,Xi).call(this),de(this,Hi,mn).call(this,t,\\\"startup\\\")}}};this.l[5]=e;try{t.addEventListener(\\\"DOMContentLoaded\\\",e,{once:1})}catch(t){throw de(this,Hi,Xi).call(this),t}return 1}try{return de(this,Hi,qi).call(this),1}catch(t){throw de(this,Hi,Xi).call(this),t}}destroy(){this.l[4]&&(de(this,Hi,Ji).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]&&de(this,Hi,Ki).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]}},Hi=new WeakSet,qi=function(){if(!this.l[4])return;let t=_(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),de(this,Hi,Zi).call(this),de(this,Hi,hn).call(this)&&(this.d[4].attach(),this.d[0].emitWhile(\\\"init\\\",{timestamp:Date.now()},()=>this.l[4]),de(this,Hi,hn).call(this)))for(let t of Gi){if(!de(this,Hi,hn).call(this))return;if(0===t){if(this.d[12](this.d[11]),!de(this,Hi,hn).call(this))return}else{let e=setTimeout(()=>{this.l[4]&&de(this,Hi,gn).call(this)},t);this.d[16].push(e)}}},Ji=function(){this.l[7]=null,this.l[4]=0;let t=this.l[5];this.l[5]=null,null!==t&&_(this.d[10])&&de(this,Hi,Yi).call(this,()=>{this.d[10].removeEventListener(\\\"DOMContentLoaded\\\",t)});for(let t of this.d[16])de(this,Hi,Yi).call(this,()=>{clearTimeout(t)});return this.d[16].length=0,de(this,Hi,Yi).call(this,()=>{this.d[6].stop()}),de(this,Hi,Yi).call(this,()=>{this.d[4].detach()}),de(this,Hi,Yi).call(this,()=>{this.d[2].stop()}),de(this,Hi,Yi).call(this,()=>{this.d[3].destroy()}),de(this,Hi,Yi).call(this,()=>{this.d[18]?.destroy()}),this.d[1].clear(),this.d[5].markDisconnected()},Xi=function(){de(this,Hi,Ji).call(this),de(this,Hi,Yi).call(this,()=>{this.d[17]?.detach()})},Yi=function(t){try{t()}catch(t){this.d[14](\\\"cleanup failed:\\\",t)}},Zi=function(){if(!this.l[4])return;let t=this.d[1].buildFromRoot(this.d[10]);if(this.d[14](\\\"cache\\\",t),de(this,Hi,hn).call(this)&&(this.d[0].emitWhile(\\\"cacheRefresh\\\",t,()=>this.l[4]),de(this,Hi,hn).call(this)))for(let t of this.d[1].values()){if(!de(this,Hi,hn).call(this))return;this.d[2].observeElement(t.element)}},Ki=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(de(this,Hi,Zi).call(this),de(this,Hi,hn).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)}},Qi=function(t){let e=d(t);e.negotiated!==this.l[3].negotiated&&(this.l[3]=e,this.d[14](\\\"protocol\\\",\\\"ours=4\\\",`theirs=${t}`,`negotiated=${e.negotiated}`))},tn=function(t,e,i){if(this.d[6].kick(),void 0===t.data){void 0!==t.protocolVersion&&de(this,Hi,Qi).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:0};this.l[7]=n,this.d[3].acceptRevision(i),this.l[6]+=1,(void 0===t.protocolVersion||(de(this,Hi,Qi).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))||de(this,Hi,en).call(this,n))},en=async function(t){let e=await de(this,Hi,nn).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=1,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&&de(this,Hi,rn).call(this,t,n)},nn=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},rn=function(t,e){if(!this.l[4]||this.l[7]!==t)return;let i=()=>this.l[4]&&this.l[7]===t,n=de(this,Hi,ln).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(0!=n&&!o(s.owner,n))continue;let l=k(e.fields,r,s.locale??t.locale,void 0!==s.locale);if(void 0===l)continue;if(!this.l[4]||this.l[7]!==t)return;let a=de(this,Hi,un).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)}}de(this,Hi,an).call(this,e.fields,t.locale,n)},ln=function(t,e){if(!this.d[19])return 0;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]=1,this.d[15](\\\"[live-preview] scopeBindingsByOwner: update names no document; nothing applied\\\")),n},sn=function(t){for(let e of this.d[1].values())if(o(e.owner,t))return 1;return 0},on=function(t,e){let i=this.d[1].get(t);return void 0===i?0:0==e?1:i.some(t=>o(t.owner,e))},an=function(t,e,i){if(0===this.d[1].fieldCount||0!=i&&!de(this,Hi,sn).call(this,i))return;let n;for(let[r,l]of Object.entries(t)){if(this.l[8].has(r)||vn.has(r)||!P(l))continue;let t=F(r,e);if(!(de(this,Hi,on).call(this,r,i)||t!==r&&de(this,Hi,on).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)0!=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] 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.`))}}},un=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\\\"}),i}},hn=function(){return this.l[4]},cn=function(t){0!==t.deferred&&(this.l[10]||(this.l[10]=1,this.d[15](`[live-preview] visibility gate held ${String(t.deferred)} offscreen update(s) until scrolled into view; see visibilityGateThreshold.`)))},dn=function(t){let e=this.l[7];if(null===e||void 0===t.identity||!W(e.identity,t.identity)||!this.l[4]||this.l[7]!==e)return 0;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(Vi,t))return Vi[t]}(e);if(void 0!==t)return t}return t.fieldType}(t.target,i?.type);\\\"text\\\"===r&&1!=t.target.explicitFieldType&&function(t){if(\\\"object\\\"!=typeof t||null===t||!(\\\"root\\\"in t))return 0;let e=t.root;return\\\"object\\\"!=typeof e||null===e?0: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 0;let i=t instanceof Error?t:new Error(String(t));return this.d[0].emitWhile(\\\"error\\\",{error:i,context:\\\"renderer\\\"},()=>this.l[4]&&this.l[7]===e),0}if(!this.l[4]||this.l[7]!==e)return 0;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 0;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] refused to write field \\\"${t.target.fieldName}\\\" into attribute \\\"${t.target.targetAttribute}\\\" (unsafe attribute or value)`),0}else{if(!l)return this.d[14](\\\"no renderer for\\\",r),0;if(0==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 0}}catch(t){if(!this.l[4]||this.l[7]!==e)return 0;let i=t instanceof Error?t:new Error(String(t));return this.d[0].emitWhile(\\\"error\\\",{error:i,context:\\\"renderer\\\"},()=>this.l[4]&&this.l[7]===e),0}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):0},fn=function(t){de(this,Hi,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||!W(n.identity,e))return;let r=()=>this.l[4]&&this.l[7]===n&&W(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)},pn=function(){if(!de(this,Hi,hn).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)}de(this,Hi,hn).call(this)&&(e&&de(this,Hi,yn).call(this)&&(this.d[17]?.announceDisconnected(),this.d[0].emitWhile(\\\"disconnect\\\",{reason:\\\"timeout\\\",timestamp:Date.now()},()=>de(this,Hi,yn).call(this)),!de(this,Hi,hn).call(this)||de(this,Hi,yn).call(this)&&(this.d[14](\\\"connection\\\",\\\"connected\\\",\\\"\\\\u2192\\\",\\\"disconnected\\\"),!de(this,Hi,hn).call(this)))||de(this,Hi,hn).call(this)&&de(this,Hi,gn).call(this))},gn=function(){try{this.d[12](this.d[11])}catch(t){de(this,Hi,mn).call(this,t,\\\"ready\\\")}},mn=function(t,e){let i=t instanceof Error?t:new Error(String(t));this.d[0].emit(\\\"error\\\",{error:i,context:e})},yn=function(){return this.l[4]&&\\\"disconnected\\\"===this.d[5].status&&null===this.l[7]},vn=new Set([\\\"id\\\",\\\"_id\\\",\\\"createdAt\\\",\\\"updatedAt\\\",\\\"createdBy\\\",\\\"updatedBy\\\",\\\"_status\\\",\\\"globalType\\\",\\\"collection\\\",\\\"locale\\\",\\\"localized\\\"]),bn=/^https?:\\\\/\\\\/(localhost|127\\\\.0\\\\.0\\\\.1)(?::\\\\d+)?$/i,wn=/^https?:\\\\/\\\\/[^/?#\\\\s]+$/i,Sn=[\\\"PAYLOAD_ADMIN_ORIGIN\\\",\\\"PUBLIC_PAYLOAD_ADMIN_ORIGIN\\\",\\\"NEXT_PUBLIC_PAYLOAD_ADMIN_ORIGIN\\\"],$n=class{constructor(t={}){he(this,An);let e=new Set;for(let i of t.additionalOrigins??[]){let t=z(i);void 0!==t&&e.add(t)}for(let t of Sn){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??1)&&(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 1}return 0}());ce(this,An,[e,i,n,void 0!==i,void 0])}matches(t){return 0===t.length||\\\"null\\\"===t?0:void 0!==ue(this,An)[4]?t===ue(this,An)[4]:!!(ue(this,An)[0].has(t)||0===ue(this,An)[0].size&&void 0!==ue(this,An)[1]&&t===ue(this,An)[1]||ue(this,An)[2]&&bn.test(t))}lockOrigin(t){return this.matches(t)?(ue(this,An)[4]=t,1):0}unlockOrigin(){let t=ue(this,An)[4];return ue(this,An)[4]=void 0,t}get lockedOrigin(){return ue(this,An)[4]}enumerate(){if(void 0!==ue(this,An)[4])return[ue(this,An)[4]];let t=new Set(ue(this,An)[0]);if(0===ue(this,An)[0].size&&void 0!==ue(this,An)[1]&&t.add(ue(this,An)[1]),ue(this,An)[2])for(let e of kn)t.add(`http://localhost:${String(e)}`),t.add(`http://127.0.0.1:${String(e)}`);return[...t]}get referrerWasAvailable(){return ue(this,An)[3]}get isProductionUnconfigured(){return!(!D()||ue(this,An)[0].size>0||ue(this,An)[2]||void 0!==ue(this,An)[1])}get isReferrerOnlyTrust(){return ue(this,An)[0].size>0||ue(this,An)[2]?0:void 0!==ue(this,An)[1]}},An=new WeakMap,kn=[3e3,3001,3333,4e3,4321,5e3,5173,5174,8e3,8080,8888,9e3],Tn=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\\\"]),Nn=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\\\"]),Mn=\\\"aria-\\\",Cn=\\\"data-\\\",On={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\\\"]),In=1,En=8,Rn=class extends Error{constructor(){super(...arguments);oe(this,\\\"name\\\",\\\"SanitizerEnvironmentError\\\")}},_n=(Object.freeze({allowedTags:Tn,removeCompletely:Nn,globalAttributes:xn,attributesByTag:On,urlAttributes:jn}),new Map),Ln={1:\\\"left\\\",2:\\\"center\\\",3:\\\"right\\\",4:\\\"justify\\\"},Wn=new Set([\\\"left\\\",\\\"center\\\",\\\"right\\\",\\\"justify\\\",\\\"start\\\",\\\"end\\\"]),Pn=Object.freeze({\\\"&\\\":\\\"&\\\",\\\"<\\\":\\\"<\\\",\\\">\\\":\\\">\\\",'\\\"':\\\""\\\",\\\"'\\\":\\\"'\\\",\\\"/\\\":\\\"/\\\",\\\"`\\\":\\\"`\\\",\\\"=\\\":\\\"=\\\"}),Fn=/[&<>\\\"'/`=]/g,Dn=Object.freeze({\\\"&\\\":\\\"&\\\",\\\"<\\\":\\\"<\\\",\\\">\\\":\\\">\\\",'\\\"':\\\""\\\",\\\"'\\\":\\\"'\\\"}),Un=/[&<>\\\"']/g,zn=new Set([\\\"h1\\\",\\\"h2\\\",\\\"h3\\\",\\\"h4\\\",\\\"h5\\\",\\\"h6\\\"]),Vn=(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>`},Gn=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=zn.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\\\",Vn);J(\\\"autolink\\\",Vn);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>`});Lt={renderChildren:at,resolveAlignment:X,resolveIndent:Y};Wt=\\\"data-payload-text\\\";Pt={name:\\\"textarea\\\",render(t,e){let i=t.element,n=st(e)?ot(e):dt(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 0==e.sanitize||void 0===G()?i:V(i)}(e);else{if(\\\"string\\\"!=typeof e)return 0;t.element.innerHTML=V(e)}})};Dt={name:\\\"html\\\",render(t,e){if(null==e){t.element.textContent=\\\"\\\";return}let i=\\\"string\\\"==typeof e?e:dt(e);t.element.innerHTML=V(i)}};Ut={name:\\\"url\\\",render(t,e,i){let n=t.element,r=dt(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 0;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 0;let r=n.url;if(\\\"string\\\"!=typeof r||!w(r))return 0;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:dt(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(dt(e));Number.isNaN(r)?n.textContent=dt(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 0;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=[Pt,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=0,s=50,o=1,a=0,u=0,h=50,c=\\\"200px\\\",d=0,f=0,p=0]=typeof __LIVE_PREVIEW_CONFIG__>\\\"u\\\"?[]:__LIVE_PREVIEW_CONFIG__,g=new $n({additionalOrigins:e,enableReferrerDetection:!d,enableLocalhostMatching:!f});g.isProductionUnconfigured?pe(\\\"[live-preview] No trusted origin. Set PAYLOAD_ADMIN_ORIGIN or pass allowedOrigins to generateInlineScript().\\\"):g.isReferrerOnlyTrust&&pe(\\\"[live-preview] 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)}([ct(),...re,Rt()]),v=new Bi({renderers:y,originMatcher:t=>g.matches(t),readyTargets:g.enumerate(),emitter:m,...\\\"\\\"!==i?{dataMerge:{serverURL:i,apiRoute:n,depth:r}}:{},debounceMs:s,heartbeatMs:a,intersectionRootMargin:c,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=Object.freeze({version:\\\"1.2.2\\\",destroy:()=>{v.destroy();let t=window;t.__livePreview===b&&delete t.__livePreview},refresh:()=>{v.refreshCache()},enumerateOrigins:()=>g.enumerate()});try{Object.defineProperty(window,\\\"__livePreview\\\",{value:b,writable:0,configurable:1})}catch(t){throw v.destroy(),t}}()})();\";\nexport const RUNTIME_BUILD_INFO: RuntimeBuildInfo = { generatedAt: \"2026-08-20T15:53:37.000Z\", size: 65661 };\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';\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 // 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 // The IIFE declares its own scope. We inject the config via a global\n // assignment 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__=${configLiteral};`, RUNTIME_SOURCE].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,uBAK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LATE_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","token","nextTimer","#requestFrame","completed","nextHandle","gateActive","batchEntry","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","isDocumentRoot","readyState","onReady","#startNow","#rollbackFailedStart","#reportError","once","observerRoot","readDocumentBody","#buildCacheAndObserve","#isRunning","emitWhile","delay","#sendReadyAfterStart","suspend","#releaseRuntimeResources","deferredStart","#runCleanup","cleanup","refreshCache","updateCount","previousBindings","removed","#applyNegotiation","remoteVersion","transaction","schemaIndex","cancelled","#processUpdate","#resolveIncomingFields","listenerCount","cancel","#scheduleAllFields","isCurrent","ownerKeys","#ownerKeysForUpdate","bindings","transformedValue","#transformForBinding","#diagnoseOrphanFields","#ownsAnyBinding","binding","#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","active","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","lockedOrigin","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","sort","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","started","resume","resolveDestroy","rejectDestroy","inFlight","reject","finally","use","unuse","plugins","destroyed","initLivePreview","client","bindNavigationLifecycle","windowTarget","documentTarget","softEvents","softNavigationEvents","onPageHide","onPageShow","persisted","onSoftNavigation","unbound","RUNTIME_SOURCE","RUNTIME_BUILD_INFO","generatedAt","generateInlineScript","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","version","prefersReducedMotion","matchMedia","releaseStyle","acquireStyle","duration","activeTimers","timerCleanups","releaseHighlight","acquireHighlight","disposeTimer","HTMLStyleElement","pluginOwned","head","owners","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","F","se","Ee","z","xi","Le","Pe","Io","ct","ci","bi","Ri","yi","D","Si","h","R","Vo","Wo","di","Do","Hi","gi","No","W","V","X","Ge","ye","L","jo","p","Re","G","fi","le","Tn","ri","$o","ai","tn","Fo"],"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/client/navigation-lifecycle.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.3.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 \"./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 },\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 readonly deferred: number;\n readonly durationMs: number;\n readonly identity?: MessageRevision;\n readonly data?: PayloadLivePreviewData;\n}\n\nconst DEFAULT_DEBOUNCE_MS = 50;\nconst 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]?.(this.#statsFor(entry, applied, 0, performance.now() - t0));\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 #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 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)) applied += 1;\n }\n } finally {\n this.s[SchedulerSlot.ActiveFlushes].delete(pending);\n }\n const stats = this.#statsFor(batchEntry, applied, deferred, performance.now() - t0);\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 ): FlushStats {\n return {\n applied,\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 { 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 /** 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}\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];\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}\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];\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' });\n }\n log('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 ];\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 ];\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');\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 // 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 next = negotiateProtocol(remoteVersion);\n if (next.negotiated === this.l[RuntimeLifecycleSlot.ProtocolNegotiation].negotiated) {\n return;\n }\n this.l[RuntimeLifecycleSlot.ProtocolNegotiation] = next;\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 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) continue;\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] 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] 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 });\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] 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' },\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] 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' },\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 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');\n }\n }\n\n #reportError(cause: unknown, context: string): 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 });\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] 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 '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n '/': '/',\n '`': '`',\n '=': '=',\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 '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\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] 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] 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 { 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' });\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 ...(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 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 @client/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","// 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?0:(Promise.resolve(t).catch(()=>{}),1)}function e(e){return(...i)=>{try{t(e(...i))}catch{}}}function i(){}function n(){return 1}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?0: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 0;let e=t;return e.hasAttribute(ke)?1:null!==e.querySelector(`[${ke}]`)}function h(t){if(!Array.isArray(t))return[];let e=[];for(let i of t){let t=c(i);t&&e.push(t)}return e}function c(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 d(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?1:e(t)}function g(t){if(\\\"object\\\"!=typeof t||null===t)return 0;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 1}return 0}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 0;try{return encodeURIComponent(t),1}catch{return 0}}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 0;let e=t.trim();if(0===e.length||$i.test(e))return 0;if(e.startsWith(\\\"#\\\")||e.startsWith(\\\"?\\\")||e.startsWith(\\\"//\\\")||e.startsWith(\\\"/\\\"))return 1;try{let t=new URL(e);return Si.has(t.protocol)}catch{return Ai.test(e)}}function S(t){if(!w(t))return 0;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=0){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=1;for(let t of e.split(\\\".\\\")){if(Pi.has(t)||null===i||\\\"object\\\"!=typeof i){n=0;break}if(i=T(i,t),void 0===i){n=0;break}}if(n)return i}return void 0===i?void 0:T(t,`${e}_${i}`)}function T(t,e){if(!Pi.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(zi.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 j(t){if(\\\"object\\\"!=typeof t||null===t)return;let e=t.id;return\\\"string\\\"==typeof e||\\\"number\\\"==typeof e?e:void 0}function I(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!==j(t))?function(t,e){let i=[],n=new Map;for(let e=0;e<t.length;e+=1){let i=j(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=j(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];I(u)===I(s)?(a!==l&&i.push({kind:\\\"move\\\",from:a,to:l,value:s}),R(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)R(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 R(t,e){if(Object.is(t,e))return 1;if(\\\"object\\\"!=typeof t||\\\"object\\\"!=typeof e||null===t||null===e)return 0;let i=t,n=e,r=Object.keys(i),l=Object.keys(n);if(r.length!==l.length)return 0;for(let t of r)if(!Object.is(i[t],n[t]))return 0;return 1}function _(t){return 9===t.nodeType}function L(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 W(t,e){return t.generation===e.generation&&t.revision===e.revision}function P(t){return null==t?0:\\\"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 0;try{return window.self!==window.top}catch{return 1}}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||!wn.test(t.origin)?void 0:t.origin}catch{return}}function V(t,e){let i=G();if(!i)throw new Rn(\\\"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(On))t.set(e,i);return{allowedTags:Tn,attrByTag:t}}let e=new Set(Tn);for(let i of t.additionalAllowedTags??[])e.add(i);let i=new Map;for(let[t,e]of Object.entries(On))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===In?H(i,e):i.nodeType===En&&i.remove()}function H(t,e){let i=t.tagName.toLowerCase();if(Nn.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(!(xn.has(i)||i.startsWith(Mn)||i.startsWith(Cn))){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 0}return 1}function J(t,e){_n.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=Ln[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(Fn,t=>Pn[t])}function tt(t){return\\\"\\\"===t?\\\"\\\":t.replace(Un,t=>Dn[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 Gn.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 0;let e=t.root;return\\\"object\\\"==typeof e&&null!==e&&\\\"children\\\"in e?Array.isArray(e.children):0}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 _n.get(t)}(t.type);return e?e(t,Lt):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 ct(){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(Wt))return function(t,e,i){t.has(e)||(t.add(e),pe(`[live-preview] 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),0;r.includes(\\\"\\\\n\\\")||r.includes(\\\"\\\\r\\\")?n.innerHTML=et(r):n.textContent=r}else n.value=r})}}function dt(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 dt(t)}function gt(t){return Array.isArray(t)?t.map(t=>gt(t)).join(\\\", \\\"):dt(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,dt)}function St(t){return dt(t)}function $t(t){let{template:e,container:i,patches:n,nextItems:r,store:l,forceRender:s=0}=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=jt(o,te),u=new Set,h=[];for(let c=0;c<i.length;c+=1){let d=i[c],f=Ot(d),p=void 0===f?o[c]??null:It(a,f)??null;null!==p&&u.has(p)&&(p=null),null!==p&&u.add(p);let g=n.replaces.has(c),m=r||n.renders.has(c)||null===p?Et(t.ownerDocument,e,d,c):void 0;if(null===m)return null;let y=void 0===m?[]:Tt(g?null:p,m,d,l,s);if(null===y)return null;h.push([c,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=0;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=1),u=o}if(null===u)continue;let h=i.children[n]??null;u!==h&&(i.insertBefore(u,h),s=1),l.add(u)}for(let t of Array.from(i.children))l.has(t)||(t.remove(),s=1);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=jt(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=It(l,e)??null,u=t.getAttribute(ie),h=u?s:null,c=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&&c!==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 0;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 jt(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 It(t,e){return t.get(e)?.pop()}function Et(t,e,i,n){let r=function(t,e,i){return bt(t,e,i,dt)}(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 Rt(){let t=new WeakMap,e=new WeakSet,i=new WeakMap;return{name:\\\"structural-array\\\",render:$((n,r)=>{if(!Array.isArray(r))return 0;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] 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),0;let o=t.get(l),a=_t(l),u=o?.values??function(t){return t.map((t,e)=>null===t?{__payloadDomPosition:e}:{id:t})}(a),h=E(u,r),c=function(t,e,i){return void 0===t?1:t.template!==e||!function(t,e){return t.length!==e.length?0:t.every((t,i)=>t===e[i])}(t.domSnapshot,i)}(o,s,a);if(0===h.length&&!c)return t.set(l,{values:r.slice(),template:s,domSnapshot:a}),0;let d=$t({template:s,container:l,patches:h,nextItems:r,store:i,forceRender:c});return null===d?0:(t.set(l,{values:r.slice(),template:s,domSnapshot:_t(l)}),d?void 0:0)})}}function _t(t){return Array.from(t.children,t=>t.getAttribute(te))}var Lt,Wt,Pt,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:1,configurable:1,writable:1,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),ce=(t,e,i,n)=>(ae(t,e,\\\"write to private field\\\"),n?n.call(t,i):e.set(t,i),i),de=(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 de(this,be,Se).call(this,ue(this,ye),t,e)}once(t,e){return de(this,be,Se).call(this,ue(this,ve),t,e)}off(t,e){de(this,be,$e).call(this,ue(this,ye),t,e),de(this,be,$e).call(this,ue(this,ve),t,e)}async emit(t,e){await de(this,be,we).call(this,t,e)}async emitWhile(t,e,i){return de(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?.()??1;if(!n())return 0;let r=ue(this,ye).get(t);if(r)for(let i of[...r])if(!n()||(await de(this,be,Ae).call(this,i,e,t),!n()))return 0;if(!n())return 0;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 de(this,be,Ae).call(this,r,e,t),!n()))return 0}return n()},Se=function(t,e,i){let n=t.get(e);return n||(n=new Set,t.set(e,n)),n.add(i),()=>{de(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] 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\\\",je=\\\"data-payload-array-separator\\\",Ie=\\\"data-payload-locale\\\",Ee=\\\"data-payload-richtext\\\",Re=\\\"data-payload-html\\\",_e=\\\"data-payload-array\\\",Le=\\\"data-payload-structural\\\",We=\\\"data-payload-owner\\\",Pe=[ke,Te,Ne,xe,Me,Ce,Oe,je,Ie,Ee,Re,_e,Le,We,\\\"type\\\"],Fe=`[${ke}]`,De=`[${We}]`,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);ce(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)?de(this,He,Ye).call(this,t):void 0,i=ue(this,Ge).get(t);if(void 0!==e)return void 0!==i&&de(this,He,qe).call(this,i,e)?(ue(this,Ge).set(t,e),e):(void 0!==i&&de(this,He,Je).call(this,t,i),de(this,He,Xe).call(this,e),ue(this,Ge).set(t,e),e);void 0!==i&&de(this,He,Je).call(this,t,i)}remove(t){let e=ue(this,Ge).get(t);return e?de(this,He,Je).call(this,t,e):0}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(),ce(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 0;let i=ue(this,Ve).get(t.fieldName);if(!i)return 0;let n=i.indexOf(t);return n<0?0:(i[n]=e,1)},Je=function(t,e){let i=ue(this,Ve).get(e.fieldName);if(!i)return ue(this,Ge).delete(t),0;let n=i.indexOf(e);return n<0?(ue(this,Ge).delete(t),0):(i.splice(n,1),0===i.length&&ue(this,Ve).delete(e.fieldName),ue(this,Ge).delete(t),1)},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(Re))return\\\"html\\\";if(t.hasAttribute(Le))return\\\"structural-array\\\";if(t.hasAttribute(_e))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(je),h=t.getAttribute(Ie),c=function(t){let e=t.closest(De)?.getAttribute(We);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!==c?{owner:c}:{}}},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=>{de(this,Qe,ti).call(this,t,i)}),r=new IntersectionObserver(t=>{de(this,Qe,ei).call(this,t,i)},{rootMargin:this.s[2],threshold:0}),n.observe(t,{childList:1,subtree:1,attributes:1,attributeFilter:[...Pe]})}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(!de(this,Qe,ii).call(this,e)||!function(t){for(let e of t){if(\\\"attributes\\\"===e.type&&null!==e.attributeName&&Pe.includes(e.attributeName)&&(e.attributeName===ke||e.attributeName===We||e.target.nodeType===Ze&&e.target.hasAttribute(ke)))return 1;for(let t of e.addedNodes)if(u(t))return 1;for(let t of e.removedNodes)if(u(t))return 1}return 0}(t)||!de(this,Qe,ii).call(this,e))return;null!==this.s[6]&&clearTimeout(this.s[6]);let i=setTimeout(()=>{!de(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(!de(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,1),!de(this,Qe,ii).call(this,e)))return}else if(this.s[3].has(t)&&(this.s[3].delete(t),this.s[0].onVisibilityChange(t,0),!de(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=0,i=t=>{if(!e||this.s[2]!==i)return;let n=this.s[4];try{de(this,li,si).call(this,t,n)}catch{let e=\\\"\\\";try{e=t.origin}catch{}de(this,li,ci).call(this,\\\"shape\\\",e,n)}};this.s[4]+=1,de(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,de(this,li,mi).call(this));try{t.removeEventListener(\\\"message\\\",i)}catch{}throw e}if(this.s[2]===i)e=1;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,de(this,li,mi).call(this),e.removeEventListener(\\\"message\\\",i))}advanceGeneration(){return void 0===this.s[3]?0:(this.s[4]+=1,de(this,li,mi).call(this),1)}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(!de(this,li,pi).call(this,e))return;let i=t.origin;if(!de(this,li,pi).call(this,e))return;if(!de(this,li,di).call(this,i,e)){de(this,li,ci).call(this,\\\"origin\\\",i,e);return}let n=t.data;if(!de(this,li,pi).call(this,e))return;let r=function(t){return\\\"object\\\"==typeof t&&null!==t&&\\\"type\\\"in t?\\\"string\\\"==typeof t.type:0}(n);if(!de(this,li,pi).call(this,e))return;if(!r){de(this,li,ci).call(this,\\\"shape\\\",i,e);return}let l=n.type;if(de(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(!de(this,li,pi).call(this,e))return;if(!t){de(this,li,ci).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(!de(this,li,pi).call(this,e))return;de(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(!de(this,li,pi).call(this,e))return;if(!t){de(this,li,ci).call(this,\\\"shape\\\",i,e);return}let r;try{r=this.s[1].onDocumentEvent}catch{return}if(!de(this,li,pi).call(this,e))return;de(this,li,fi).call(this,r,n,i);return}default:de(this,li,ci).call(this,\\\"type\\\",i,e)}},oi=function(t,e,i){if(!de(this,li,pi).call(this,i))return;let n=t.data;if(!de(this,li,pi).call(this,i))return;let r=g(n);if(!de(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(!de(this,li,pi).call(this,i))return;if(void 0===l){de(this,li,hi).call(this,t,e,i,s);return}if(1==t.ready&&void 0===n){de(this,li,hi).call(this,t,e,i,void 0);return}let o={generation:i,message:t,origin:e,messageRevision:s,settled:0,approved:0};this.s[6].push(o);let a;try{a=l(t.previewToken,e)}catch{de(this,li,ai).call(this,o,0);return}\\\"boolean\\\"!=typeof a?Promise.resolve(a).then(t=>{de(this,li,ai).call(this,o,1==t)},()=>{de(this,li,ai).call(this,o,0)}):de(this,li,ai).call(this,o,a)},ai=function(t,e){de(this,li,pi).call(this,t.generation)&&(t.approved=e,t.settled=1,de(this,li,ui).call(this,t.generation))},ui=function(t){for(;de(this,li,pi).call(this,t);){let e=this.s[6][this.s[7]];if(void 0===e)return;if(de(this,li,di).call(this,e.origin,t)){if(!e.settled)return;de(this,li,gi).call(this,e)&&(e.approved?de(this,li,hi).call(this,e.message,e.origin,e.generation,e.messageRevision):de(this,li,ci).call(this,\\\"token\\\",e.origin,e.generation))}else{if(!de(this,li,gi).call(this,e))continue;de(this,li,ci).call(this,\\\"origin\\\",e.origin,e.generation)}}},hi=function(t,e,i,n){if(!de(this,li,pi).call(this,i))return;let r;try{r=this.s[1].onUpdate}catch{return}de(this,li,pi).call(this,i)&&(void 0===n?de(this,li,fi).call(this,r,t,e):de(this,li,fi).call(this,r,t,e,n))},ci=function(t,e,i){if(!de(this,li,pi).call(this,i))return;let n;try{n=this.s[1].onInvalid}catch{return}de(this,li,pi).call(this,i)&&void 0!==n&&de(this,li,fi).call(this,n,t,e)},di=function(t,e){if(!de(this,li,pi).call(this,e))return 0;try{return 1==this.s[0](t)&&de(this,li,pi).call(this,e)}catch{return 0}},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?0:(e[7]+=1,e[7]===e[6].length?(de(this,li,mi).call(this),1):(e[7]>=1024&&2*e[7]>=e[6].length&&(e[6]=e[6].slice(e[7]),e[7]=0),1))},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 0;let e=this.s[0];return this.s[0]=t,this.s[1](t,e),1}},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 0;try{return encodeURIComponent(t),1}catch{return 0}}(t.data.id):0}catch{return 0}}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:0,...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??0,e.getCacheSize,e.onFlush,i,n,new Map,new Map,new Set,null,0,null,0,null,0]}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}),de(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||(de(this,Mi,Wi).call(this),de(this,Mi,_i).call(this),this.s[16]=t,this.s[17]=0)}cancelRevision(t){A(t,this.s[16])&&(de(this,Mi,Wi).call(this),de(this,Mi,_i).call(this),this.s[17]=1)}flushNow(){return de(this,Mi,Wi).call(this),de(this,Mi,ji).call(this)}notifyVisible(t){let e=this.s[10],i=e.get(t);if(!i||(e.delete(t),!de(this,Mi,Ii).call(this,i)))return;let n=performance.now(),r=de(this,Mi,Ei).call(this,i)?1:0;this.s[6]?.(de(this,Mi,Li).call(this,i,r,0,performance.now()-n))}retarget(t){de(this,Mi,Ri).call(this,this.s[9],t),de(this,Mi,Ri).call(this,this.s[10],t);for(let e of this.s[11])de(this,Mi,Ri).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(){de(this,Mi,Wi).call(this),de(this,Mi,_i).call(this),this.s[16]=null,this.s[17]=0}get pendingCount(){return this.s[9].size}get replayCount(){return this.s[10].size}},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,de(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=0,n=this.s[7](()=>{this.s[15]===t&&(i=1,this.s[14]=null,de(this,Mi,ji).call(this))});!i&&this.s[15]===t&&(this.s[14]=n)},ji=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=0;this.s[11].add(i);try{for(let t of i.values()){if(!de(this,Mi,Ii).call(this,t))continue;let i=!e||this.s[2](t.target.element);if(de(this,Mi,Ii).call(this,t)){if(n??(n=t),!i){this.s[10].set(t.target.element,t),l+=1;continue}this.s[10].delete(t.target.element),de(this,Mi,Ei).call(this,t)&&(r+=1)}}}finally{this.s[11].delete(i)}let s=de(this,Mi,Li).call(this,n,r,l,performance.now()-t);return this.s[6]?.(s),s},Ii=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 0!=e(t)||!function(t){return Ni.has(t)}(e)},Ri=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}},_i=function(){this.s[9].clear(),this.s[10].clear();for(let t of this.s[11])t.clear()},Li=function(t,e,i,n){return{applied:e,deferred:i,durationMs:n,...void 0!==t?.identity?{identity:t.identity}:{},...void 0!==t?.data?{data:t.data}:{}}},Wi=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)},Pi=new Set([\\\"__proto__\\\",\\\"prototype\\\",\\\"constructor\\\"]),Fi=\\\"payload-live-preview-a11y\\\",Di=new WeakMap,Ui=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=Di.get(t);return e??(e=[null,0,null,0,null]),Di.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(Fi);return e[1]=null===n,n||(n=t.createElement(\\\"div\\\"),n.id=Fi,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,Di.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}},zi=new Set([\\\"tabs\\\",\\\"row\\\",\\\"collapsible\\\"]),Vi={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\\\"},Gi=[0,500,1e3,2e3],Bi=class{constructor(t){he(this,Hi);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??L,h=t.onHeartbeatTimeout,c=void 0===t.log?i:e(t.log),f=void 0===t.warn?pe:e(t.warn),p=function(t){if(0==t.enableA11y)return null;let e=void 0===t.root?void 0:9===t.root.nodeType?t.root:t.root.ownerDocument;return new Ui(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)=>{c(...t)}}):null,m=new ze,y=new Ke({onStructuralChange:()=>{de(this,Hi,Ki).call(this)},onVisibilityChange:(t,e)=>{e&&this.d[3].notifyVisible(t)}},{...void 0!==t.intersectionRootMargin?{intersectionRootMargin:t.intersectionRootMargin}:{}}),v=new xi($(t=>de(this,Hi,dn).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=>{de(this,Hi,fn).call(this,t)}}),b=new ri(t.originMatcher,{onUpdate:(t,e,i)=>{de(this,Hi,tn).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\\\"})}c(\\\"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:()=>{de(this,Hi,pn).call(this)}});this.d=[n,m,y,v,b,w,S,r,l,s,o,a,u,h,c,f,[],p,g,1==t.scopeBindingsByOwner],this.l=[void 0,void 0,void 0,d(void 0),0,null,0,null,new Set,0,0]}start(){if(this.l[4])return 0;this.l[4]=1;let t=this.d[10];if(_(t)&&\\\"loading\\\"===t.readyState){let e=()=>{if(this.l[4]){this.l[5]=null;try{de(this,Hi,qi).call(this)}catch(t){de(this,Hi,Xi).call(this),de(this,Hi,mn).call(this,t,\\\"startup\\\")}}};this.l[5]=e;try{t.addEventListener(\\\"DOMContentLoaded\\\",e,{once:1})}catch(t){throw de(this,Hi,Xi).call(this),t}return 1}try{return de(this,Hi,qi).call(this),1}catch(t){throw de(this,Hi,Xi).call(this),t}}suspend(){return this.l[4]?(de(this,Hi,Ji).call(this)&&this.d[0].emit(\\\"disconnect\\\",{reason:\\\"unload\\\",timestamp:Date.now()}),1):0}destroy(){this.l[4]&&(de(this,Hi,Ji).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]&&de(this,Hi,Ki).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]}},Hi=new WeakSet,qi=function(){if(!this.l[4])return;let t=_(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),de(this,Hi,Zi).call(this),de(this,Hi,hn).call(this)&&(this.d[4].attach(),this.d[0].emitWhile(\\\"init\\\",{timestamp:Date.now()},()=>this.l[4]),de(this,Hi,hn).call(this)))for(let t of Gi){if(!de(this,Hi,hn).call(this))return;if(0===t){if(this.d[12](this.d[11]),!de(this,Hi,hn).call(this))return}else{let e=setTimeout(()=>{this.l[4]&&de(this,Hi,gn).call(this)},t);this.d[16].push(e)}}},Ji=function(){this.l[7]=null,this.l[4]=0;let t=this.l[5];this.l[5]=null,null!==t&&_(this.d[10])&&de(this,Hi,Yi).call(this,()=>{this.d[10].removeEventListener(\\\"DOMContentLoaded\\\",t)});for(let t of this.d[16])de(this,Hi,Yi).call(this,()=>{clearTimeout(t)});return this.d[16].length=0,de(this,Hi,Yi).call(this,()=>{this.d[6].stop()}),de(this,Hi,Yi).call(this,()=>{this.d[4].detach()}),de(this,Hi,Yi).call(this,()=>{this.d[2].stop()}),de(this,Hi,Yi).call(this,()=>{this.d[3].destroy()}),de(this,Hi,Yi).call(this,()=>{this.d[18]?.destroy()}),this.d[1].clear(),this.d[5].markDisconnected()},Xi=function(){de(this,Hi,Ji).call(this),de(this,Hi,Yi).call(this,()=>{this.d[17]?.detach()})},Yi=function(t){try{t()}catch(t){this.d[14](\\\"cleanup failed:\\\",t)}},Zi=function(){if(!this.l[4])return;let t=this.d[1].buildFromRoot(this.d[10]);if(this.d[14](\\\"cache\\\",t),de(this,Hi,hn).call(this)&&(this.d[0].emitWhile(\\\"cacheRefresh\\\",t,()=>this.l[4]),de(this,Hi,hn).call(this)))for(let t of this.d[1].values()){if(!de(this,Hi,hn).call(this))return;this.d[2].observeElement(t.element)}},Ki=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(de(this,Hi,Zi).call(this),de(this,Hi,hn).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)}},Qi=function(t){let e=d(t);e.negotiated!==this.l[3].negotiated&&(this.l[3]=e,this.d[14](\\\"protocol\\\",\\\"ours=4\\\",`theirs=${t}`,`negotiated=${e.negotiated}`))},tn=function(t,e,i){if(this.d[6].kick(),void 0===t.data){void 0!==t.protocolVersion&&de(this,Hi,Qi).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:0};this.l[7]=n,this.d[3].acceptRevision(i),this.l[6]+=1,(void 0===t.protocolVersion||(de(this,Hi,Qi).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))||de(this,Hi,en).call(this,n))},en=async function(t){let e=await de(this,Hi,nn).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=1,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&&de(this,Hi,rn).call(this,t,n)},nn=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},rn=function(t,e){if(!this.l[4]||this.l[7]!==t)return;let i=()=>this.l[4]&&this.l[7]===t,n=de(this,Hi,ln).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(0!=n&&!o(s.owner,n))continue;let l=k(e.fields,r,s.locale??t.locale,void 0!==s.locale);if(void 0===l)continue;if(!this.l[4]||this.l[7]!==t)return;let a=de(this,Hi,un).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)}}de(this,Hi,an).call(this,e.fields,t.locale,n)},ln=function(t,e){if(!this.d[19])return 0;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]=1,this.d[15](\\\"[live-preview] scopeBindingsByOwner: update names no document; nothing applied\\\")),n},sn=function(t){for(let e of this.d[1].values())if(o(e.owner,t))return 1;return 0},on=function(t,e){let i=this.d[1].get(t);return void 0===i?0:0==e?1:i.some(t=>o(t.owner,e))},an=function(t,e,i){if(0===this.d[1].fieldCount||0!=i&&!de(this,Hi,sn).call(this,i))return;let n;for(let[r,l]of Object.entries(t)){if(this.l[8].has(r)||vn.has(r)||!P(l))continue;let t=F(r,e);if(!(de(this,Hi,on).call(this,r,i)||t!==r&&de(this,Hi,on).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)0!=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] 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.`))}}},un=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\\\"}),i}},hn=function(){return this.l[4]},cn=function(t){0!==t.deferred&&(this.l[10]||(this.l[10]=1,this.d[15](`[live-preview] visibility gate held ${String(t.deferred)} offscreen update(s) until scrolled into view; see visibilityGateThreshold.`)))},dn=function(t){let e=this.l[7];if(null===e||void 0===t.identity||!W(e.identity,t.identity)||!this.l[4]||this.l[7]!==e)return 0;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(Vi,t))return Vi[t]}(e);if(void 0!==t)return t}return t.fieldType}(t.target,i?.type);\\\"text\\\"===r&&1!=t.target.explicitFieldType&&function(t){if(\\\"object\\\"!=typeof t||null===t||!(\\\"root\\\"in t))return 0;let e=t.root;return\\\"object\\\"!=typeof e||null===e?0: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 0;let i=t instanceof Error?t:new Error(String(t));return this.d[0].emitWhile(\\\"error\\\",{error:i,context:\\\"renderer\\\"},()=>this.l[4]&&this.l[7]===e),0}if(!this.l[4]||this.l[7]!==e)return 0;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 0;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] refused to write field \\\"${t.target.fieldName}\\\" into attribute \\\"${t.target.targetAttribute}\\\" (unsafe attribute or value)`),0}else{if(!l)return this.d[14](\\\"no renderer for\\\",r),0;if(0==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 0}}catch(t){if(!this.l[4]||this.l[7]!==e)return 0;let i=t instanceof Error?t:new Error(String(t));return this.d[0].emitWhile(\\\"error\\\",{error:i,context:\\\"renderer\\\"},()=>this.l[4]&&this.l[7]===e),0}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):0},fn=function(t){de(this,Hi,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||!W(n.identity,e))return;let r=()=>this.l[4]&&this.l[7]===n&&W(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)},pn=function(){if(!de(this,Hi,hn).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)}de(this,Hi,hn).call(this)&&(e&&de(this,Hi,yn).call(this)&&(this.d[17]?.announceDisconnected(),this.d[0].emitWhile(\\\"disconnect\\\",{reason:\\\"timeout\\\",timestamp:Date.now()},()=>de(this,Hi,yn).call(this)),!de(this,Hi,hn).call(this)||de(this,Hi,yn).call(this)&&(this.d[14](\\\"connection\\\",\\\"connected\\\",\\\"\\\\u2192\\\",\\\"disconnected\\\"),!de(this,Hi,hn).call(this)))||de(this,Hi,hn).call(this)&&de(this,Hi,gn).call(this))},gn=function(){try{this.d[12](this.d[11])}catch(t){de(this,Hi,mn).call(this,t,\\\"ready\\\")}},mn=function(t,e){let i=t instanceof Error?t:new Error(String(t));this.d[0].emit(\\\"error\\\",{error:i,context:e})},yn=function(){return this.l[4]&&\\\"disconnected\\\"===this.d[5].status&&null===this.l[7]},vn=new Set([\\\"id\\\",\\\"_id\\\",\\\"createdAt\\\",\\\"updatedAt\\\",\\\"createdBy\\\",\\\"updatedBy\\\",\\\"_status\\\",\\\"globalType\\\",\\\"collection\\\",\\\"locale\\\",\\\"localized\\\"]),bn=/^https?:\\\\/\\\\/(localhost|127\\\\.0\\\\.0\\\\.1)(?::\\\\d+)?$/i,wn=/^https?:\\\\/\\\\/[^/?#\\\\s]+$/i,Sn=[\\\"PAYLOAD_ADMIN_ORIGIN\\\",\\\"PUBLIC_PAYLOAD_ADMIN_ORIGIN\\\",\\\"NEXT_PUBLIC_PAYLOAD_ADMIN_ORIGIN\\\"],$n=class{constructor(t={}){he(this,An);let e=new Set;for(let i of t.additionalOrigins??[]){let t=z(i);void 0!==t&&e.add(t)}for(let t of Sn){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??1)&&(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 1}return 0}());ce(this,An,[e,i,n,void 0!==i,void 0])}matches(t){return 0===t.length||\\\"null\\\"===t?0:void 0!==ue(this,An)[4]?t===ue(this,An)[4]:!!(ue(this,An)[0].has(t)||0===ue(this,An)[0].size&&void 0!==ue(this,An)[1]&&t===ue(this,An)[1]||ue(this,An)[2]&&bn.test(t))}lockOrigin(t){return this.matches(t)?(ue(this,An)[4]=t,1):0}unlockOrigin(){let t=ue(this,An)[4];return ue(this,An)[4]=void 0,t}get lockedOrigin(){return ue(this,An)[4]}enumerate(){if(void 0!==ue(this,An)[4])return[ue(this,An)[4]];let t=new Set(ue(this,An)[0]);if(0===ue(this,An)[0].size&&void 0!==ue(this,An)[1]&&t.add(ue(this,An)[1]),ue(this,An)[2])for(let e of kn)t.add(`http://localhost:${String(e)}`),t.add(`http://127.0.0.1:${String(e)}`);return[...t]}get referrerWasAvailable(){return ue(this,An)[3]}get isProductionUnconfigured(){return!(!D()||ue(this,An)[0].size>0||ue(this,An)[2]||void 0!==ue(this,An)[1])}get isReferrerOnlyTrust(){return ue(this,An)[0].size>0||ue(this,An)[2]?0:void 0!==ue(this,An)[1]}},An=new WeakMap,kn=[3e3,3001,3333,4e3,4321,5e3,5173,5174,8e3,8080,8888,9e3],Tn=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\\\"]),Nn=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\\\"]),Mn=\\\"aria-\\\",Cn=\\\"data-\\\",On={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\\\"]),In=1,En=8,Rn=class extends Error{constructor(){super(...arguments);oe(this,\\\"name\\\",\\\"SanitizerEnvironmentError\\\")}},_n=(Object.freeze({allowedTags:Tn,removeCompletely:Nn,globalAttributes:xn,attributesByTag:On,urlAttributes:jn}),new Map),Ln={1:\\\"left\\\",2:\\\"center\\\",3:\\\"right\\\",4:\\\"justify\\\"},Wn=new Set([\\\"left\\\",\\\"center\\\",\\\"right\\\",\\\"justify\\\",\\\"start\\\",\\\"end\\\"]),Pn=Object.freeze({\\\"&\\\":\\\"&\\\",\\\"<\\\":\\\"<\\\",\\\">\\\":\\\">\\\",'\\\"':\\\""\\\",\\\"'\\\":\\\"'\\\",\\\"/\\\":\\\"/\\\",\\\"`\\\":\\\"`\\\",\\\"=\\\":\\\"=\\\"}),Fn=/[&<>\\\"'/`=]/g,Dn=Object.freeze({\\\"&\\\":\\\"&\\\",\\\"<\\\":\\\"<\\\",\\\">\\\":\\\">\\\",'\\\"':\\\""\\\",\\\"'\\\":\\\"'\\\"}),Un=/[&<>\\\"']/g,zn=new Set([\\\"h1\\\",\\\"h2\\\",\\\"h3\\\",\\\"h4\\\",\\\"h5\\\",\\\"h6\\\"]),Vn=(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>`},Gn=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=zn.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\\\",Vn);J(\\\"autolink\\\",Vn);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>`});Lt={renderChildren:at,resolveAlignment:X,resolveIndent:Y};Wt=\\\"data-payload-text\\\";Pt={name:\\\"textarea\\\",render(t,e){let i=t.element,n=st(e)?ot(e):dt(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 0==e.sanitize||void 0===G()?i:V(i)}(e);else{if(\\\"string\\\"!=typeof e)return 0;t.element.innerHTML=V(e)}})};Dt={name:\\\"html\\\",render(t,e){if(null==e){t.element.textContent=\\\"\\\";return}let i=\\\"string\\\"==typeof e?e:dt(e);t.element.innerHTML=V(i)}};Ut={name:\\\"url\\\",render(t,e,i){let n=t.element,r=dt(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 0;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 0;let r=n.url;if(\\\"string\\\"!=typeof r||!w(r))return 0;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:dt(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(dt(e));Number.isNaN(r)?n.textContent=dt(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 0;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=[Pt,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=0,s=50,o=1,a=0,u=0,h=50,c=\\\"200px\\\",d=0,f=0,p=0]=typeof __LIVE_PREVIEW_CONFIG__>\\\"u\\\"?[]:__LIVE_PREVIEW_CONFIG__,g=new $n({additionalOrigins:e,enableReferrerDetection:!d,enableLocalhostMatching:!f});g.isProductionUnconfigured?pe(\\\"[live-preview] No trusted origin. Set PAYLOAD_ADMIN_ORIGIN or pass allowedOrigins to generateInlineScript().\\\"):g.isReferrerOnlyTrust&&pe(\\\"[live-preview] 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)}([ct(),...re,Rt()]),v=new Bi({renderers:y,originMatcher:t=>g.matches(t),readyTargets:g.enumerate(),emitter:m,...\\\"\\\"!==i?{dataMerge:{serverURL:i,apiRoute:n,depth:r}}:{},debounceMs:s,heartbeatMs:a,intersectionRootMargin:c,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=Object.freeze({version:\\\"1.3.0\\\",destroy:()=>{v.destroy();let t=window;t.__livePreview===b&&delete t.__livePreview},refresh:()=>{v.refreshCache()},enumerateOrigins:()=>g.enumerate()});try{Object.defineProperty(window,\\\"__livePreview\\\",{value:b,writable:0,configurable:1})}catch(t){throw v.destroy(),t}}()})();\";\nexport const RUNTIME_BUILD_INFO: RuntimeBuildInfo = { generatedAt: \"2026-08-21T15:41:02.000Z\", size: 65789 };\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';\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 // 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 // The IIFE declares its own scope. We inject the config via a global\n // assignment 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__=${configLiteral};`, RUNTIME_SOURCE].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,WAA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