payload-live-preview 2.1.0 → 2.1.2
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/README.md +18 -11
- 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/client.cjs +1 -1
- package/dist/client.cjs.map +1 -1
- package/dist/client.js +1 -1
- package/dist/client.js.map +1 -1
- package/dist/core.cjs +1 -1
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +5 -1
- package/dist/core.d.ts +5 -1
- 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 +5 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/lean.cjs +1 -1
- package/dist/lean.cjs.map +1 -1
- package/dist/lean.js +1 -1
- package/dist/lean.js.map +1 -1
- package/dist/plugins.cjs +1 -1
- package/dist/plugins.cjs.map +1 -1
- package/dist/plugins.js +1 -1
- package/dist/plugins.js.map +1 -1
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +8 -3
- package/dist/server.d.ts +8 -3
- package/dist/server.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["CSP_ASCII_WHITESPACE","isCspWhitespace","value","index","code","charCodeAt","trimCspWhitespace","start","end","length","slice","asciiLowercase","replace","character","toLowerCase","buildFrameAncestors","options","self","origins","allowNone","seen","Set","out","push","add","origin","trimmed","trim","has","join","mergeCspPolicy","existing","additions","directives","Map","part","split","whitespaceIndex","search","name","set","rawName","rawAddition","Object","entries","addition","mode","current","get","merged","token","withoutNone","filter","assertMergeDepthExplicit","defaults","serverURL","mergeDepth","Error","isDevelopmentProcess","env","globalThis","process","warnOnce","key","message","holder","warned","console","warn","warnDeprecatedOptions","onUnboundChange","V2_ADAPTER_DEFAULTS","freeze","strict","previewSignals","V2_RUNTIME_DEFAULTS","disableReferrerDetection","eventSourcePolicy","skipUnchanged","sanitizerPolicy","V1_ADAPTER_DEFAULTS","V1_RUNTIME_DEFAULTS","RUNTIME_SOURCE","FRAGMENT_SOURCE","ROUTE_SOURCE","LOADER_SOURCE","LOADER_REACT_SOURCE","INLINE_CONFIG_KEYS","assertBuilt","source","artifact","strategyPrelude","config","fragmentEndpoint","routeStrategy","configStatement","profile","profileSlots","values","map","at","pop","JSON","stringify","buildConfigLiteral","wrapWithScriptTag","body","nonce","assertNonce","test","RangeError","normalizePath","path","runtimeAsset","runtime","fileName","contentHash","urlPath","assetPath","integrity","HEAD_INSERT","HTML_CONTENT_TYPE","META_CHARSET","resolvePolicyOptions","adapter","runtimeRow","disableLocalhostMatching","bindDecisionHooks","policy","request","shouldInject","authorizes","authorize","authorizePreview","renderScriptBody","facts","resolved","allowedOrigins","apiRoute","revealEditedField","debug","debounceMs","heartbeatMs","scopeBindingsByOwner","fragments","endpoint","onUnfaithfulPatch","autoBind","subfieldCoverage","hydration","softNavigationEvents","inlineScriptConfig","delivery","generateInlineScript","runtimeFor","asset","target","bootstrap","loaderFor","runtimeSrc","encode","generateLoaderScript","DEFAULT_QUERY_PARAMS","PreviewConfigurationError","refused","outcome","authorized","context","AUTHORIZED_PREVIEW_BRAND_KEY","BRAND","Symbol","for","isAuthorizedPreviewContext","isFrozen","createAuthorizedPreviewContext","fields","scope","payload","document","payloadHeaders","async","runAuthorizeHook","hook","result","error","isPreviewConfigurationError","verdictFrom","STAGED","NONE","isPreview","authorization","inject","cspMode","exposeNonce","createPreviewPolicy","protocol","URL","includes","assertStrictConfiguration","manageCsp","autoInject","decide","hooks","signals","queryParams","url","param","searchParams","getAll","headers","alias","adminOrigins","configured","referer","refererOrigin","adminOrigin","hasPreviewIntent","previewQueryParams","previewIntentFor","verdict","scriptTag","csp","frameAncestorsExtra","buildScriptSrcWithNonce","extra","strictDynamic","parts","e","scriptSrcExtra","policies","mergeCspHeader","buildPreviewCsp","generateCspNonce","bytes","Number","isInteger","String","crypto","fromGlobal","getRandomValues","resolveCrypto","buffer","Uint8Array","binary","byte","fromCharCode","btoa","Buffer","from","toString","replaceAll","base64UrlEncode","REACT_PAGE","createLivePreviewMiddleware","response","decision","apply","Headers","Response","status","statusText","withHeaders","cacheControl","vary","listed","markUncacheable","applyCspHeaders","withCspHeader","injected","html","head","exec","headEnd","headClose","indexOf","meta","injectIntoHead","clone","text","delete","injectIntoResponse","applyDecision","livePreviewScriptProps","dangerouslySetInnerHTML","__html","renderLivePreviewScript","renderScriptTag","lazyPeer","load","pending","started","catch","cachedEncoder","DEFAULT_USERS_SLUG","COOKIE_NAME_PATTERN","COOKIE_VALUE_PATTERN","httpOriginFor","option","encoder","TextEncoder","fromBase64Url","padded","repeat","atob","pathSegment","isPreviewDocumentID","isSafeInteger","isPayloadScopeCurrent","expiresAt","isFinite","Date","now","matchesPreviewDocument","expected","actual","kind","slug","id","authorizePreviewRequest","strategy","type","cookieName","cookieNameFor","sentOrigin","header","maxLength","prefix","startsWith","extractCookie","maxCookieLength","timeoutMs","Math","max","fetchImpl","fetch","usersSlug","encodeURIComponent","forwarded","cookie","controller","AbortController","abort","signal","reason","isAborted","aborted","timer","addEventListener","once","setTimeout","DOMException","attempt","accept","ok","json","user","clearTimeout","removeEventListener","Array","isArray","collection","readUser","exp","readExpiry","subject","authorizedAt","authorizeSession","secret","byteLength","secretBytes","candidate","subtle","cryptoFor","transport","readToken","payloadText","payloadBytes","signature","verified","importKey","hash","hmacKey","verify","claims","parsed","parse","TextDecoder","decode","c","optionalString","parseClaims","iat","aud","audience","pur","purpose","pth","pathname","loc","locale","replay","first","store","consume","isUsed","markUsed","consumeTokenId","jti","sub","authorizeToken","username","password","rawPath","route","every","payloadAPIBase","isValidPayloadScope","authorizeVerifier","positiveIntegerLimit","fallback","maximum","FRAGMENT_VERSION_HEADER","MAX_FIELD_DEPTH","depthOf","depth","maxDepth","deepest","child","isRecord","parseFragmentRequestResult","maxFieldDepth","fragment","revision","slugs","collectionSlug","globalSlug","MAX_TIMER_MS","NO_STORE_HEADERS","refuse","EndpointStopped","cancelStream","stream","locked","Promise","resolve","cancel","signalIsAborted","createFragmentEndpointHandler","binding","pageRequest","authorizerFor","render","rendererName","allowed","bodyLimit","limits","bodyBytes","MAX_SAFE_INTEGER","totalTimeoutMs","fieldDepth","TypeError","registry","locals","method","site","sameOrigin","requestSignal","deadline","performance","stopped","resolveStopped","stoppedPromise","stop","totalTimer","check","run","work","phaseTimeoutMs","phaseTimer","race","then","dispose","createEndpointRequestScope","bodyState","read","raw","limit","overLimitBody","bodyUsed","declared","normalized","boundary","declaredLengthExceeds","reader","getReader","decoder","total","overLimit","next","done","releaseLock","readBody","Request","page","data","hasOwn","matchesPreviewDocumentData","scopeAllows","entry","prototype","hasOwnProperty","call","input","props","record","component","metadata","renderedAt","toISOString","renderer","durationMs","loadReact","react","server","all","createElement","renderToString","cause","packages","names","one","missingPeerError","renderWithReact","defineFragment","createFragmentEndpoint","handler","hostOf","host","previewHeaderRules","withLivePreview","nextConfig","rules","existingHeaders","devOrigins","allowDevOrigins","allowedDevOrigins","createRuntimeAssetRoute","GET","lastIndexOf","runtimeAssetResponse","loadCreateElement","LivePreviewScript"],"sources":["../../../src/security/csp.ts","../../../src/types/merge-depth.ts","../../../src/types/dev-warning.ts","../../../src/types/defaults-profile.ts","../../../src/inline/runtime.generated.ts","../../../src/inline/fragment.generated.ts","../../../src/inline/route.generated.ts","../../../src/inline/loader.generated.ts","../../../src/inline/loader-react.generated.ts","../../../src/types/inline-config.ts","../../../src/inline/generator.ts","../../../src/adapters/shared/runtime-asset.ts","../../../src/adapters/shared/html-inject.ts","../../../src/adapters/shared/policy-options.ts","../../../src/adapters/shared/response.ts","../../../src/adapters/shared/preview-request.ts","../../../src/security/preview-verdict.ts","../../../src/types/authorized-preview.ts","../../../src/adapters/shared/authorize-hook.ts","../../../src/adapters/shared/strict.ts","../../../src/adapters/shared/policy.ts","../../../src/core/navigation-lifecycle.ts","../../../src/adapters/nextjs/adapter.ts","../../../src/adapters/shared/optional-peer.ts","../../../src/security/preview-session.ts","../../../src/security/preview-token.ts","../../../src/security/preview-scope.ts","../../../src/security/preview-authorization.ts","../../../src/adapters/shared/fragment-limits.ts","../../../src/types/fragment-protocol.ts","../../../src/adapters/shared/fragment-endpoint.ts","../../../src/adapters/nextjs/fragments.ts","../../../src/adapters/nextjs/config.ts","../../../src/adapters/nextjs/asset-route.ts","../../../src/adapters/nextjs/script-component.ts"],"sourcesContent":["/**\n * Content-Security-Policy helpers: nonce generation, directive builders and\n * the header merge every adapter uses. Isomorphic; needs only Web Crypto.\n */\n\nconst DEFAULT_NONCE_BYTES = 16;\n\n/** CSP3's exact whitespace set: HTAB, LF, FF, CR, and SPACE. */\nconst CSP_ASCII_WHITESPACE = /[\\t\\n\\f\\r ]+/;\n\n/** Reads one code unit; an index past the end yields NaN, which matches nothing. */\nfunction isCspWhitespace(value: string, index: number): boolean {\n const code = value.charCodeAt(index);\n return code === 9 || code === 10 || code === 12 || code === 13 || code === 32;\n}\n\n/**\n * Trim CSP whitespace by scanning from both ends.\n *\n * The obvious `/^\\s+|\\s+$/` is superlinear by construction: for a long run the\n * trailing alternative is retried at every position. V8 happens to optimise the\n * shape away, but this header can come from a consumer's own response and this\n * module runs in every engine, so the guarantee has to come from the algorithm\n * rather than from one engine's optimiser.\n */\nfunction trimCspWhitespace(value: string): string {\n let start = 0;\n let end = value.length;\n while (start < end && isCspWhitespace(value, start)) start += 1;\n while (end > start && isCspWhitespace(value, end - 1)) end -= 1;\n return start === 0 && end === value.length ? value : value.slice(start, end);\n}\n\n/** CSP names are ASCII; Unicode case folding must not create directives. */\nfunction asciiLowercase(value: string): string {\n return value.replace(/[A-Z]/g, (character) => character.toLowerCase());\n}\n\n/** The one Web Crypto method this module calls; accepts Node's `webcrypto` without a cast. */\ninterface WebCryptoLike {\n getRandomValues: <T extends ArrayBufferView | null>(array: T) => T;\n}\n\nlet cryptoOverride: WebCryptoLike | undefined;\n\n/** Supply a Web Crypto implementation for runtimes without `globalThis.crypto`; `null` clears it. @internal */\nexport function setCspCrypto(crypto: WebCryptoLike | null): void {\n cryptoOverride = crypto ?? undefined;\n}\n\n/** A base64url nonce of `bytes` random bytes (default 16); throws without Web Crypto, since a predictable nonce silently defeats the CSP. @internal */\nexport function generateCspNonce(bytes: number = DEFAULT_NONCE_BYTES): string {\n if (!Number.isInteger(bytes) || bytes < 8) {\n throw new RangeError(`generateCspNonce: bytes must be an integer >= 8, got ${String(bytes)}`);\n }\n const crypto = resolveCrypto();\n if (!crypto) {\n throw new Error(\n 'generateCspNonce: Web Crypto is unavailable. On Node 18 call setCspCrypto(webcrypto) ' +\n \"once at startup, or run with --experimental-global-webcrypto. We won't fabricate \" +\n 'a predictable nonce — that would silently defeat the entire CSP.',\n );\n }\n const buffer = new Uint8Array(bytes);\n crypto.getRandomValues(buffer);\n return base64UrlEncode(buffer);\n}\n\nfunction resolveCrypto(): WebCryptoLike | undefined {\n if (cryptoOverride?.getRandomValues) return cryptoOverride;\n const fromGlobal = (globalThis as { crypto?: WebCryptoLike }).crypto;\n if (fromGlobal?.getRandomValues) return fromGlobal;\n return undefined;\n}\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n const base64 = typeof btoa === 'function' ? btoa(binary) : Buffer.from(bytes).toString('base64');\n return base64.replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');\n}\n\n/** A `frame-ancestors` source: `'self'`, `'none'`, or an origin. */\nexport type FrameAncestorSource = string;\n\nexport interface FrameAncestorsOptions {\n readonly self?: boolean;\n readonly origins?: readonly string[];\n readonly allowNone?: boolean;\n}\n\n/** The `frame-ancestors` value: `'self'` and the origins, deduplicated; `'none'` when empty. */\nexport function buildFrameAncestors(options: FrameAncestorsOptions = {}): string {\n const { self = true, origins = [], allowNone = false } = options;\n const seen = new Set<string>();\n const out: FrameAncestorSource[] = [];\n if (allowNone && !self && origins.length === 0) return \"'none'\";\n if (self) {\n out.push(\"'self'\");\n seen.add(\"'self'\");\n }\n for (const origin of origins) {\n const trimmed = origin.trim();\n if (trimmed.length === 0 || seen.has(trimmed)) continue;\n seen.add(trimmed);\n out.push(trimmed);\n }\n return out.length > 0 ? out.join(' ') : \"'none'\";\n}\n\n/**\n * A `script-src` value permitting one nonce plus optional extra sources.\n * `'strict-dynamic'` is opt-in: it makes CSP 3 browsers ignore `'self'` and\n * host sources, so every script on the page must then carry the nonce.\n * @internal\n */\nexport function buildScriptSrcWithNonce(\n nonce: string,\n options: {\n readonly self?: boolean;\n readonly extra?: readonly string[];\n readonly strictDynamic?: boolean;\n } = {},\n): string {\n if (nonce.length === 0) throw new RangeError('buildScriptSrcWithNonce: nonce is empty');\n const { self = true, extra = [], strictDynamic = false } = options;\n const parts: string[] = [];\n if (self) parts.push(\"'self'\");\n parts.push(`'nonce-${nonce}'`);\n if (strictDynamic) parts.push(\"'strict-dynamic'\");\n for (const e of extra) {\n const trimmed = e.trim();\n if (trimmed.length > 0) parts.push(trimmed);\n }\n return parts.join(' ');\n}\n\n/** `union` (default) adds sources to an existing directive; `replace` overwrites it. */\nexport interface CspDirectiveMerge {\n readonly value: string;\n readonly mode?: 'union' | 'replace';\n}\n\n/**\n * Merge directives into an existing `Content-Security-Policy` header value.\n * Commas separate policies (that is how `Headers.get()` joins repeated\n * headers); each is merged, because a browser enforces every policy and\n * widening only the last would leave the others blocking.\n */\nexport function mergeCspHeader(\n existing: string,\n additions: Readonly<Record<string, string | CspDirectiveMerge>>,\n): string {\n const policies = existing.split(',').filter((policy) => policy.trim().length > 0);\n if (policies.length === 0) return mergeCspPolicy('', additions);\n return policies.map((policy) => mergeCspPolicy(policy, additions)).join(', ');\n}\n\nfunction mergeCspPolicy(\n existing: string,\n additions: Readonly<Record<string, string | CspDirectiveMerge>>,\n): string {\n const directives = new Map<string, string>();\n for (const part of existing.split(';')) {\n const trimmed = trimCspWhitespace(part);\n if (trimmed.length === 0) continue;\n const whitespaceIndex = trimmed.search(CSP_ASCII_WHITESPACE);\n const name = asciiLowercase(whitespaceIndex < 0 ? trimmed : trimmed.slice(0, whitespaceIndex));\n // CSP3 §2.2.1: a user agent ignores later duplicates, so a looser\n // duplicate must not become the policy that is serialized.\n if (directives.has(name)) continue;\n const value = whitespaceIndex < 0 ? '' : trimCspWhitespace(trimmed.slice(whitespaceIndex));\n directives.set(name, value);\n }\n\n for (const [rawName, rawAddition] of Object.entries(additions)) {\n const name = asciiLowercase(rawName);\n const addition: CspDirectiveMerge =\n typeof rawAddition === 'string' ? { value: rawAddition } : rawAddition;\n const mode = addition.mode ?? 'union';\n const current = directives.get(name);\n if (mode === 'replace' || current === undefined || current.length === 0) {\n directives.set(name, addition.value);\n continue;\n }\n const seen = new Set<string>();\n const merged: string[] = [];\n for (const token of [\n ...current.split(CSP_ASCII_WHITESPACE),\n ...addition.value.split(CSP_ASCII_WHITESPACE),\n ]) {\n if (token.length === 0 || seen.has(token)) continue;\n seen.add(token);\n merged.push(token);\n }\n // `'none'` cannot coexist with other sources.\n const withoutNone = merged.filter((token) => token !== \"'none'\");\n directives.set(name, (withoutNone.length > 0 ? withoutNone : merged).join(' '));\n }\n\n const out: string[] = [];\n for (const [name, value] of directives) {\n out.push(value.length === 0 ? name : `${name} ${value}`);\n }\n return out.join('; ');\n}\n","/**\n * The one rule shared by the adapters, the client and the inline generator:\n * `serverURL` needs an explicit `mergeDepth` under the 2.0 defaults (ADR 0007,\n * entry 10). It lives in the leaf `types` domain because the inline generator\n * is server-side code that may not reach the browser runtime in `core`, and\n * three copies of the check had already drifted in what they treated as\n * \"no server\" and \"no depth\".\n */\n\nimport type { DefaultsProfile } from '@/types/defaults-profile';\n\n/**\n * The population depth is a deliberate choice; the 1.x default of 1 stays only\n * behind `defaults: 'v1'`. An empty `serverURL` fetches nothing and owes no\n * depth; `null` counts as omitted because the inline wire config carries it.\n */\nexport function assertMergeDepthExplicit(options: {\n readonly defaults?: DefaultsProfile | undefined;\n readonly serverURL?: string | undefined;\n readonly mergeDepth?: number | null | undefined;\n}): void {\n if (options.defaults === 'v1') return;\n if ((options.serverURL ?? '') === '' || options.mergeDepth != null) return;\n throw new Error(\n 'payload-live-preview: `serverURL` needs an explicit `mergeDepth` under the 2.0 defaults — ' +\n \"choose the population depth deliberately (0 for none), or pass `defaults: 'v1'` to keep \" +\n 'the 1.x default of 1 while migrating (ADR 0007, entry 10).',\n );\n}\n","/**\n * One development warning per process. The set of issued keys lives on\n * `globalThis` so two package copies in one process still warn once.\n */\n\nconst WARNED_KEY = '__payloadLivePreviewDeprecationsWarned';\n\n/** `true` outside a production build; `false` when `NODE_ENV` is production or unknown. */\nexport function isDevelopmentProcess(): boolean {\n try {\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process\n ?.env;\n if (env === undefined) return false;\n return env['NODE_ENV'] !== 'production';\n } catch {\n return false;\n }\n}\n\n/** Warn once per process for `key`, outside production only. */\nexport function warnOnce(key: string, message: string): void {\n if (!isDevelopmentProcess()) return;\n const holder = globalThis as unknown as Record<string, Set<string> | undefined>;\n const warned = (holder[WARNED_KEY] ??= new Set<string>());\n if (warned.has(key)) return;\n warned.add(key);\n try {\n console.warn(`[payload-live-preview] ${message}`);\n } catch {\n // A console that throws must not break a request.\n }\n}\n\n/**\n * The deprecated options the adapters and the inline generator both accept;\n * an adapter hands them on to the generator, and the shared keys keep that to\n * one warning each (ADR 0026).\n */\nexport function warnDeprecatedOptions(options: {\n readonly defaults?: string | undefined;\n readonly onUnboundChange?: string | undefined;\n}): void {\n if (options.defaults === 'v1') {\n warnOnce(\n 'defaults-v1',\n \"`defaults: 'v1'` is removed in 3.0: `pll migrate` writes the 1.x rows it stands for \" +\n 'into your options, where they keep working (ADR 0026).',\n );\n }\n if (options.onUnboundChange !== undefined) {\n warnOnce(\n 'on-unbound-change',\n \"`onUnboundChange` is removed in 3.0: name it `onUnfaithfulPatch`, where 'route' is \" +\n \"'escalate'; `pll migrate` renames it (ADR 0026).\",\n );\n }\n}\n\n/** Test hook: forget every warning issued so far. */\nexport function resetDevWarnings(): void {\n const holder = globalThis as unknown as Record<string, Set<string> | undefined>;\n holder[WARNED_KEY] = undefined;\n}\n","/**\n * The two defaults profiles, row by row. 2.0 ships `v2`; `defaults: 'v1'` opts\n * back into the 1.x table for a staged migration. Each row belongs to exactly\n * one side — the adapter's request decision or the browser runtime — and a\n * test asserts the profile assigns every readiness row that has an option, so\n * a row added later cannot be forgotten. See ADR 0007.\n *\n * It lives in the leaf `types` domain, like `merge-depth.ts`, because the\n * inline generator resolves the profile too, and the generator is server-side\n * code that may not reach the browser runtime in `core`.\n */\n\n/** `'v2'` is the 2.0 default; `'v1'` is the 1.x table. */\nexport type DefaultsProfile = 'v1' | 'v2';\n\n/** How the runtime decides which windows may post updates. */\nexport type EventSourcePolicy = 'any' | 'parent-or-opener';\n\n/** Readiness rows that are options, keyed by the option they set. */\nexport const READINESS_ROWS = Object.freeze({\n strict: 'production response changes require an authorized context',\n previewSignals: 'query-only intent signal',\n disableReferrerDetection: 'referrer trust off',\n eventSourcePolicy: 'messages must come from parent/opener',\n skipUnchanged: 'skip unchanged bindings by default',\n sanitizerPolicy: 'hardened sanitizer id/data-* policy',\n} as const);\n\n/** Options an adapter's request decision reads from the profile. */\nexport interface AdapterProfileDefaults {\n readonly strict: boolean;\n readonly previewSignals: readonly ('query' | 'fetch-dest' | 'referer')[];\n}\n\n/** Options the browser runtime reads from the profile (through the inline configuration). */\nexport interface RuntimeProfileDefaults {\n readonly disableReferrerDetection: boolean;\n readonly eventSourcePolicy: EventSourcePolicy;\n readonly skipUnchanged: boolean;\n readonly sanitizerPolicy: 'compat' | 'strict';\n}\n\nexport const V2_ADAPTER_DEFAULTS: AdapterProfileDefaults = Object.freeze({\n strict: true,\n previewSignals: Object.freeze(['query'] as const),\n});\n\nexport const V2_RUNTIME_DEFAULTS: RuntimeProfileDefaults = Object.freeze({\n disableReferrerDetection: true,\n eventSourcePolicy: 'parent-or-opener',\n skipUnchanged: true,\n sanitizerPolicy: 'strict',\n});\n\n/** The 1.x table, spelled out so the profiles compare row by row. */\nexport const V1_ADAPTER_DEFAULTS: AdapterProfileDefaults = Object.freeze({\n strict: false,\n previewSignals: Object.freeze(['query', 'fetch-dest', 'referer'] as const),\n});\n\nexport const V1_RUNTIME_DEFAULTS: RuntimeProfileDefaults = Object.freeze({\n disableReferrerDetection: false,\n eventSourcePolicy: 'any',\n skipUnchanged: false,\n sanitizerPolicy: 'compat',\n});\n\n/** Only an explicit `'v1'` opts out; everything else gets the hardened rows. */\nexport function adapterDefaultsFor(profile: DefaultsProfile | undefined): AdapterProfileDefaults {\n return profile === 'v1' ? V1_ADAPTER_DEFAULTS : V2_ADAPTER_DEFAULTS;\n}\n\nexport function runtimeDefaultsFor(profile: DefaultsProfile | undefined): RuntimeProfileDefaults {\n return profile === 'v1' ? V1_RUNTIME_DEFAULTS : V2_RUNTIME_DEFAULTS;\n}\n","// Auto-generated by scripts/build-runtime.ts — do not edit.\nexport interface RuntimeBuildInfo { readonly generatedAt: string; readonly size: number }\nexport const RUNTIME_SOURCE: string = /* @__PURE__ */ [\"(()=>{function e(e){return(\\\"object\\\"==typeof e&&null!==e||\\\"function\\\"==typeof e)&&\\\"function\\\"==typeof e.then&&(Promise.resolve(e).catch(()=>{}),!0)}function t(t){return(...n)=>{try{e(t(...n))}catch{}}}function n(){}function i(e){return e.onUnfaithfulPatch??(\\\"ignore\\\"===e.onUnboundChange?\\\"ignore\\\":\\\"escalate\\\")}function r(e,t,n,i){let r=e.onUnfaithfulPatch,l=t.reportedUnfaithful.has(n.element);if((l||\\\"escalate\\\"!==r)&&t.display.shortfall(t.activeUpdate,{kind:\\\"unfaithful\\\",field:n.fieldName}),!l&&(t.reportedUnfaithful.add(n.element),t.unfaithfulCount+=1,t.unfaithfulFields.add(n.fieldName),\\\"ignore\\\"!==r)){if(\\\"warn\\\"===r){e.warn(`[live-preview] LP0411: \\\"${n.fieldName}\\\" ${i}`);return}e.log(\\\"LP0411\\\",n.fieldName,i),t.unfaithfulPatches.push(n)}}function l(e,t){return!e.unfaithfulFields.has(t)&&(e.unfaithfulFields.add(t),e.unfaithfulCount+=1,!0)}function a(e){return\\\"INPUT\\\"===e.tagName||\\\"TEXTAREA\\\"===e.tagName?e.value:e.textContent}function s(e){let t=e.trim();return JSON.stringify(t.length>yi?`${t.slice(0,yi)}\\\\u2026`:t)}function o(){return function(){if(typ\",\"eof document>\\\"u\\\")return;let e=document.documentElement.getAttribute(\\\"lang\\\");return null===e||0===e.length?void 0:e}()??function(){if(typeof navigator>\\\"u\\\")return;let e=navigator.language;return\\\"string\\\"==typeof e&&e.length>0?e:void 0}()??\\\"en\\\"}function u(e){null!==e.timer&&(clearTimeout(e.timer),e.timer=null),e.messageNode?.remove(),e.messageNode=null}function d(e){if(++e.nodes>1e4)throw new Error(\\\"invalid or oversized field schema\\\")}function c(e,t,n){if(d(t),n>64||t.active.has(e))throw new Error(\\\"invalid or oversized field schema\\\");t.active.add(e)}function h(e){try{return f(e,{nodes:0,active:new WeakSet},0)}catch{return[]}}function f(e,t,n){if(!Array.isArray(e))return[];c(e,t,n);let i=[];for(let r of e){let e=p(r,t,n);e&&i.push(e)}return t.active.delete(e),i}function p(e,t,n){if(d(t),\\\"object\\\"!=typeof e||null===e)return;let i=e,r=i.name,l=i.type;if(\\\"string\\\"!=typeof r||0===r.length||\\\"string\\\"!=typeof l||0===l.length)return;let a=f(i.fields,t,n+1),s=function(e,t,n){if(\\\"object\\\"==typeof e&&null!==e&&!Array.isArray(e)){c(e,t,n);let i=[];for(let r in e){if(!Object.hasOwn(e,r))continue;d(t);let l=Reflect.get(e,r);\\\"object\\\"!=typeof l||null===l||[\\\"__proto__\\\",\\\"constructor\\\",\\\"prototype\\\"].includes(r)||i.push({...l,slug:r,fields:f(l.fields,t,n+1)})}return t.active.delete(e),i}if(!Array.isArray(e))return[];c(e,t,n);let i=[];for(let r of e){if(d(t),\\\"object\\\"!=typeof r||null===r)continue;let e=r,l=e.slug;if(\\\"string\\\"!=typeof l||0===l.length)continue;let a=f(e.fields,t,n+1);i.push({...e,slug:l,fields:a})}return t.active.delete(e),i}(i.blocks,t,n+1),o={...i,name:r,type:l},u=i.relationTo;if(Array.isArray(u)){let e=[];for(let n of u)d(t),e.push(n);o.relationTo=e}return a.length>0?o.fields=a:delete o.fields,s.length>0?o.blocks=s:delete o.blocks,o}function g(e,t){return void 0===e||t(e)}function m(e,t){return null==e||t(e)}function v(e){if(\\\"object\\\"!=typeof e||null===e)return!1;let t=Object.getPrototypeOf(e);return null===t||null===Object.getPrototypeOf(t)}function y(e,t=[]){let n=\\\"number\\\"==typeof e&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0,i=Math.min(4,n??1),r=new Set(t),l=new Set;for(let e of Ti)(i>=ki[e].since||r.has(e))&&l.add(e);return{ours:4,...void 0!==n?{theirs:n}:{theirs:void 0},negotiated:i,capabilities:l,observed:r}}function b(e,t){return e.generation===t.generation&&e.revision===t.revision}function w(e){return function(e){if(!1===e.enableA11y)return null;let t=e.root,n=void 0===t?void 0:function(e){return 9===e.nodeType}(t)?t:t.ownerDocument;return new Si(e.a11yLocale,n)}(e)}function S(e){if(typ\",\"eof window>\\\"u\\\")return;let t=[];window.parent!==window&&t.push(window.parent),window.opener instanceof Window&&t.push(window.opener),Ci.sendReady(t,e)}function A(e,t,n,i){for(let r of e){if(Ri.has(r.type)){let e=r.fields;e&&A(e,i&&\\\"tabs\\\"===r.type?\\\"\\\"===t?r.name:`${t}.${r.name}`:t,n,i);continue}let e=\\\"\\\"===t?r.name:`${t}.${r.name}`;if(n.set(e,r),\\\"group\\\"===r.type)r.fields&&A(r.fields,e,n,i);else if(\\\"array\\\"===r.type&&r.fields)A(r.fields,`${e}.*`,n,i);else if(\\\"blocks\\\"===r.type&&r.blocks)for(let t of r.blocks)A(t.fields,`${e}.*.${t.slug}`,n,i)}}function k(e,t){if(e.has(t))return e.get(t);let n=t.replace(/\\\\.\\\\d+(?=\\\\.|$)/g,\\\".*\\\");return e.has(n)?e.get(n):void 0}function T(e){if(\\\"object\\\"!=typeof e||null===e)return;let t=e.id;return\\\"string\\\"==typeof t||\\\"number\\\"==typeof t?t:void 0}function C(e){if(\\\"object\\\"!=typeof e||null===e)return;let t=e.blockType;return\\\"string\\\"==typeof t?t:void 0}function R(e,t){return t.every(e=>void 0!==T(e))?function(e,t){let n=[],i=new Map;for(let t=0;t<e.length;t+=1){let n=T(e[t]);void 0!==n&&i.set(n,t)}let r=new Set;for(let l=0;l<t.length;l+=1){let a=t[l],s=T(a);if(void 0===s){n.push({kind:\\\"insert\\\",index:l,value:a});continue}let o=i.get(s);if(void 0===o){n.push({kind:\\\"insert\\\",index:l,value:a});continue}r.add(o);let u=e[o];C(u)===C(a)?(o!==l&&n.push({kind:\\\"move\\\",from:o,to:l,value:a}),$(u,a)||n.push({kind:\\\"update\\\",index:l,value:a})):n.push({kind:\\\"replace\\\",index:l,oldValue:u,value:a})}for(let t=0;t<e.length;t+=1)r.has(t)||n.push({kind:\\\"remove\\\",index:t,value:e[t]});return n}(e,t):function(e,t){let n=[],i=Math.min(e.length,t.length);for(let r=0;r<i;r+=1)$(e[r],t[r])||n.push({kind:\\\"update\\\",index:r,value:t[r]});if(t.length>e.length)for(let i=e.length;i<t.length;i+=1)n.push({kind:\\\"insert\\\",index:i,value:t[i]});if(e.length>t.length)for(let i=t.length;i<e.length;i+=1)n.push({kind:\\\"remove\\\",index:i,value:e[i]});return n}(e,t)}function $(e,t){if(Object.is(e,t))return!0;if(\\\"object\\\"!=typeof e||\\\"object\\\"!=typeof t||null===e||null===t)return!1;let n=e,i=t,r=Object.keys(n),l=Object.keys(i);if(r.length!==l.length)return!1;for(let e of r)if(!Object.is(n[e],i[e]))return!1;return!0}function F(e){if(\\\"string\\\"!=typeof e)return!1;let t=e.trim().replace(Ei,\\\"\\\");if(0===t.length)return!1;if(t.startsWith(\\\"#\\\")||t.startsWith(\\\"?\\\")||Mi.test(t)||t.startsWith(\\\"/\\\"))return!0;try{let e=new URL(t);return Fi.has(e.protocol)}catch{return Ni.test(t)&&!function(e){let t=Li.exec(e.replace(Oi,\\\"\\\"))?.[1];return void 0!==t&&!Fi.has(`${t.toLowerCase()}:`)}(t)}}function N(e){let t=e.trim().replace(Ei,\\\"\\\");return/^https?:\\\\/\\\\//i.test(t)||Mi.test(t)}function M(e){return!e.startsWith(\\\"on\\\")&&!xi.has(e)}function E(e){return Ui.add(e),e}function O(e){switch(typeof e){case\\\"string\\\":return e.length>65536?void 0:`s:${e}`;case\\\"number\\\":return`n:${Object.is(e,-0)?\\\"-0\\\":String(e)}`;case\\\"boolean\\\":return\\\"b:\\\"+(e?\\\"1\\\":\\\"0\\\");case\\\"bigint\\\":return`i:${String(e)}`;case\\\"undefined\\\":return\\\"u\\\";case\\\"object\\\":{if(null===e)return\\\"z\\\";let t;try{t=JSON.stringify(e)}catch{return}return t.length>65536?void 0:`o:${t}`}case\\\"symbol\\\":case\\\"function\\\":return}}function L(){return!0}function x(e){return e.closest(`[${ji}]`)}function P(e){let t=e.getAttribute(Bi);return null!==t&&t.length>0?\\\"patch\\\"===t||\\\"fragment\\\"===t||\\\"route\\\"===t?t:void 0:null!==x(e)?\\\"fragment\\\":null!==e.closest(\\\"head\\\")?\\\"route\\\":\\\"patch\\\"}function U(e){return`global:${e}`}function I(e,t){return void 0===t||\\\"\\\"===t?`collection:${e}`:`collection:${e}:${t}`}function j(e){return\\\"string\\\"==typeof e&&e.length>0}function W(e,t){return null!==t&&void 0!==e&&t.includes(e)}function B(e){let t=e.id;return\\\"string\\\"==typeof t&&t.length>0?t:\\\"number\\\"==typeof t&&Number.isFinite(t)?String(t):void 0}function D(e){return\\\"object\\\"==typeof e&&null!==e}function _(e){return Array.isArray(e)?\\\"array\\\":D(e)?\\\"object\\\":\\\"scalar\\\"}function z(e,t){return D(e)?e[t]:void 0}function V(e,t,n,i){let r=[],l=0,a=(e,t,n,s)=>{if(l+=1,i.covers(e))return;let o=O(n);if(void 0!==o&&o===O(t))return;if(!((void 0===t||_(t)===_(n))&&D(n)&&i.reachesBelow(e)&&s<Di)){r.push({path:e,value:n});return}let u=function(e,t){let n=new Set(Object.keys(t));if(D(e))for(let t of Object.keys(e))n.add(t);return[...n]}(t,n);0===u.length&&r.push({path:e,value:n});for(let i of u){if(l>=_i){r.push({path:e,value:n});return}a(`${e}.${i}`,z(t,i),z(n,i),s+1)}};return a(e,t,n,0),r}function q(e,t,n={}){let i=e=>!1===t||W(e,t),r=[];for(let[t,n]of e.entries())n.some(e=>i(e.owner))&&r.push(t);let l=e.rendered.filter(e=>void 0!==n[e.strategy]);return function(e,t){let n=new Set(e),i=[...t],r=(e,t)=>{let n=`${t}.`;for(let t of e)if(t.startsWith(n))return!0;return!1};return{covers:e=>n.has(e)||i.some(t=>t===e||e.startsWith(`${t}.`)),reachesBelow:e=>r(n,e)||r(i,e)}}(r,[...e.covers,...l].filter(e=>i(e.owner)).flatMap(e=>e.paths))}function H(e,t){if(void 0===t||0===t.length)return e;let n=`_${t}`;return e.endsWith(n)?e.slice(0,-n.length):e}function G(e,t,n,i=q(e,n)){let r,l=i.covers,a=i.reachesBelow;return i=>{let s=H(i,t);return l(i)||s!==i&&l(s)||(r??(r=function(e,t){let n=new Set;for(let[i,r]of e.entries())for(let e of r)!1!==t&&!W(e.owner,t)||void 0!==e.locale&&n.add(`${i}_${e.locale}`);return n}(e,n)),r.has(i))?\\\"whole\\\":a(i)||s!==i&&a(s)?\\\"below\\\":\\\"none\\\"}}function K(e,t,n,i,r){return X(n)?!X(t)||function(e,t,n){let i=void 0===n?void 0:k(n,e);return void 0!==i&&!Vi.has(i.type)||!0===t.get(e)?.some(J)||function(e,t){let n=`${t}.`;for(let[t,i]of e.entries())if(t.startsWith(n))return!0;return!1}(t,e)}(e,i,r)?\\\"keep\\\":null==t?\\\"ask\\\":\\\"own\\\":\\\"ask\\\"}function J(e){return!Vi.has(e.fieldType)}function X(e){return null===e||\\\"object\\\"!=typeof e&&\\\"function\\\"!=typeof e}function Q(e){return!0===e?.includes(\\\".\\\")}function Z(e,t){let n=t.globalSlug??t.collectionSlug;if(\\\"string\\\"!=typeof n||e.entitySlug!==n)return!0;let i=B(e),r=B(t.data??{});return void 0!==i&&void 0!==r&&i!==r}function Y(e){return null!==e&&e.forceRender&&!e.completed}function ee(e){try{return!0===e.matchMedia?.(\\\"(prefers-reduced-motion: reduce)\\\").matches}catch{return!1}}function te(e,t){let n=t.element.ownerDocument.defaultView;return null===n?\\\"no-element\\\":e.reveal(`${t.owner??\\\"\\\"} ${t.fieldName}`,t.element,n)}function ne(e){let t=e.getAttribute(Wi);return{kind:\\\"fragment\\\",id:e.getAttribute(ji)??\\\"\\\",key:null===t||0===t.length?void 0:t,code:\\\"LP0801\\\"}}function ie(e){if(null==e)return[];let t=new Set,n=[];for(let i of e.split(/[\\\\s,]+/)){let e=i.trim();0===e.length||t.has(e)||(t.add(e),n.push(e))}return n}function re(...e){let t=new Map;for(let n of e)for(let[e,i]of Object.entries(n)){let n=t.get(e);void 0===n&&(n=new Set,t.set(e,n));for(let e of i)n.add(e)}let n={};for(let[e,i]of t)n[e]=[...i];return n}function le(e,t){let n={};for(let i of t)i!==e&&(n[i]=[e]);return n}function ae(e){if(e.tagName.toLowerCase().includes(\\\"-\\\")&&!e.hasAttribute(ar)||oe(e)||e.hasAttribute(lr))return!0;let t=e.getAttribute(\\\"contenteditable\\\");return null!==t&&\\\"false\\\"!==t}function se(e){return\\\"patch\\\"===e.getAttribute(ir)}function oe(e){return function(e){return\\\"astro-island\\\"===e.tagName.toLowerCase()||e.hasAttribute(ir)}(e)&&!se(e)}function ue(e){return\\\"astro-island\\\"===e.tagName.toLowerCase()&&e.hasAttribute(\\\"ssr\\\")}function de(e){return\\\"astro-island\\\"===e.tagName.toLowerCase()}function ce(e){let t=\\\"\\\";for(let n of e.querySelectorAll(\\\"astro-slot, template[data-astro-template]\\\"))n.parentElement?.closest(\\\"astro-island\\\")===e&&(t+=`${n.getAttribute(\\\"name\\\")??n.getAttribute(\\\"data-astro-template\\\")??\\\"\\\"}\\\\0${n.innerHTML}\\\\0`);return t}function he(e,t){if(!de(e)||!de(t))return!0;let n=ce(t);if(!sr.every(n=>e.getAttribute(n)===t.getAttribute(n))||(or.get(e)??ce(e))!==n||e.getAttribute(\\\"props\\\")!==t.getAttribute(\\\"props\\\")&&!function(e){let t=e.ownerDocument.defaultView?.customElements.get(\\\"astro-island\\\");return void 0!==t&&e instanceof t&&Array.isArray(t.observedAttributes)&&t.observedAttributes.includes(\\\"props\\\")}(e))return or.set(t,n),!1;or.set(e,n);let i=t.getAttribute(\\\"props\\\");return i!==e.getAttribute(\\\"props\\\")&&(e.setAttribute(\\\"ssr\\\",\\\"\\\"),null===i?e.removeAttribute(\\\"props\\\"):e.setAttribute(\\\"props\\\",i)),!0}function fe(e){return Array.from(e.querySelectorAll(\\\"astro-island\\\"))}function pe(e){let t=e.ownerDocument.defaultView;if(void 0===t?.customElements.get(\\\"astro-island\\\"))return\\\"element\\\";let n=e.getAttribute(\\\"client\\\"),i=Reflect.get(t,\\\"Astro\\\");return null===n||\\\"object\\\"!=typeof i||null===i||void 0===Reflect.get(i,n)?\\\"directive\\\":void 0}function ge(e){let t=e.closest(Er)?.getAttribute(kr);return null==t||0===t.length?void 0:t}function me(e){return xr.has(e)||Lr.test(e)}function ve(e,t){return e.fieldName===t.fieldName&&e.locale===t.locale&&e.owner===t.owner&&e.strategyKind===t.strategyKind&&e.fragmentBoundary===t.fragmentBoundary}function ye(e){let t=e.getAttribute(cr);if(null!==t&&me(t))return t;if(e.hasAttribute(br))return\\\"richText\\\";if(e.hasAttribute(wr))return\\\"html\\\";if(e.hasAttribute(Ar))return\\\"structural-array\\\";if(e.hasAttribute(Sr))return\\\"array\\\";if(\\\"IMG\\\"===e.tagName)return\\\"image\\\";if(\\\"A\\\"===e.tagName)return\\\"url\\\";if(\\\"TIME\\\"===e.tagName)return\\\"date\\\";if(\\\"INPUT\\\"===e.tagName){let t=e.type;if(\\\"checkbox\\\"===t)return\\\"checkbox\\\";if(\\\"number\\\"===t)return\\\"number\\\";if(\\\"date\\\"===t||\\\"datetime-local\\\"===t)return\\\"date\\\"}return\\\"text\\\"}function be(){return!0}function we(){throw new Error(\\\"invalid or oversized legacy population\\\")}function Se(e){for(let t=0;t<e.length;t+=1){let n=e.charCodeAt(t);if(n<=31||127===n)return!0}return!1}function Ae(e,t){if(\\\"string\\\"!=typeof e||0===e.length||e.length>t||\\\".\\\"===e||\\\"..\\\"===e||e.includes(\\\"/\\\")||e.includes(\\\"\\\\\\\\\\\")||Se(e))return!1;try{return encodeURIComponent(e),!0}catch{return!1}}function ke(e){return Ae(e,128)&&!/[?#%]/u.test(e)&&!Vr.has(e)}function Te(e){return Number.isFinite(e)?String(e):Ae(e,512)?e:we()}function Ce(e,t){return Object.hasOwn(e,t)?Reflect.get(e,t):void 0}function Re(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,configurable:!0,enumerable:!0})}function $e(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t-=1;return e.slice(0,t)}function Fe(e){let t=new WeakSet,n=0,i=0;return function e(r,l){if(++n>Ir||l>Ur)return we();if(\\\"string\\\"==typeof r)return i+=r.length,i>Dr&&we(),r;if(null==r||\\\"boolean\\\"==typeof r)return r;if(\\\"number\\\"==typeof r)return Number.isFinite(r)?r:we();if(!Array.isArray(r)&&!v(r))return we();if(Array.isArray(r)){r.length>Ir&&we();for(let e=0;e<r.length;e+=1)Object.hasOwn(r,e)||we()}if(t.has(r))return we();t.add(r);let a=Array.isArray(r)?[]:{};for(let t of Object.keys(r))Re(a,t,e(Reflect.get(r,t),l+1));return t.delete(r),a}(e,0)}function Ne(e,t,n,i,r,l){function a(e,t,n,i){if(null==i||\\\"\\\"===i)return;let l=v(i)?Ce(i,\\\"id\\\"):i,a=Te(l);if(0===r){Re(e,t,l);return}let s=JSON.stringify([n,a]);c.add(s),c.size>jr&&we();let o=d.get(n)??[];o.push({owner:e,key:t,id:a}),d.set(n,o)}function s(e,t,n){void 0!==n.hasMany&&\\\"boolean\\\"!=typeof n.hasMany&&we();let i=n.relationTo,r=Ce(e,t);if(Array.isArray(i)){0===i.length&&we();let e,t=v(r)?Ce(r,\\\"relationTo\\\"):void 0;for(let n of i)p(0),ke(n)||we(),n===t&&(e=n);if(null==r||\\\"\\\"===r)return;(!v(r)||void 0===e)&&we(),a(r,\\\"value\\\",e,Ce(r,\\\"value\\\"))}else ke(i)||we(),a(e,t,i,r)}function o(e,t){if(p(t),Array.isArray(e)||v(e)){if(v(e)&&Object.hasOwn(e,\\\"relationTo\\\")&&Object.hasOwn(e,\\\"value\\\")){let t=Ce(e,\\\"relationTo\\\");ke(t)||we(),a(e,\\\"value\\\",t,Ce(e,\\\"value\\\"));return}for(let n of Object.keys(e))o(Reflect.get(e,n),t+1)}}if(!Number.isSafeInteger(r)||r<0||r>Ur)return we();void 0!==l&&(\\\"string\\\"!=typeof l||l.length>128||Se(l))&&we();let u=Fe(e);if(!v(u))return we();let d=new Map,c=new Set,h=0,f=new WeakSet,p=e=>{(++h>Ir||e>Ur)&&we()};(function e(t,n,i){p(i),f.has(t)&&we(),f.add(t);for(let r of t){p(i),(!v(r)||!Ae(r.name,512)||Vr.has(r.name))&&we();let t=Ce(n,r.name);if(\\\"relationship\\\"===r.type||\\\"upload\\\"===r.type)if(r.hasMany)if(null!=t&&!Array.isArray(t)&&we(),Array.isArray(t))for(let e=0;e<t.length;e+=1)s(t,e,r);else s(n,r.name,r);else s(n,r.name,r);else if(\\\"group\\\"===r.type||\\\"tabs\\\"===r.type)null!=t&&!v(t)&&we(),v(t)&&r.fields&&e(r.fields,t,i+1);else if(\\\"row\\\"===r.type||\\\"collapsible\\\"===r.type)r.fields&&e(r.fields,n,i+1);else if(\\\"array\\\"===r.type||\\\"blocks\\\"===r.type){if(0===t?Re(n,r.name,[]):null!=t&&!Array.isArray(t)&&we(),Array.isArray(t))for(let n of t)if(v(n)||we(),\\\"array\\\"===r.type&&r.fields)e(r.fields,n,i+1);else if(\\\"blocks\\\"===r.type){let t=Ce(n,\\\"blockType\\\"),l=r.blocks?.find(e=>(p(i),e.slug===t));void 0===l&&we(),e(l.fields,n,i+1)}}else\\\"richText\\\"===r.type&&o(t,i+1)}f.delete(t)})(t,u,0),d.size>25&&we();let g=[];if(0===d.size)return{doc:u,requests:g};let m=new URL(n);(![\\\"http:\\\",\\\"https:\\\"].includes(m.protocol)||m.username||m.password||m.search||m.hash)&&we(),(!i.startsWith(\\\"/\\\")||i.includes(\\\"\\\\\\\\\\\")||/[%?#]/u.test(i)||Se(i))&&we(),i.split(\\\"/\\\").some(e=>\\\".\\\"===e||\\\"..\\\"===e)&&we();let y=`${$e(n)}${$e(i)}/`;for(let[e,t]of d){let n=[...new Set(t.map(e=>e.id))],i=0;for(;i<n.length;){let a=n[i];void 0===a&&we();let s=a.includes(\\\",\\\"),o=[],u=\\\"\\\";for(;i<n.length&&o.length<zr;){let t=n[i];if(void 0===t||o.length>0&&(s||t.includes(\\\",\\\")))break;let a=[...o,t],d=new URLSearchParams({depth:String(r),limit:String(a.length)});void 0!==l&&d.set(\\\"locale\\\",l),d.set(s?\\\"where[id][equals]\\\":\\\"where[id][in]\\\",s?t:a.join(\\\",\\\"));let c=`${y}${encodeURIComponent(e)}?${d}`;if(c.length>Br){0===o.length&&we();break}new URL(c).origin!==m.origin&&we(),o.push(t),i+=1,u=c}(0===o.length||g.length>=Wr)&&we();let d=new Set(o);g.push({url:u,ids:d,slots:t.filter(e=>d.has(e.id))})}}return{doc:u,requests:g}}async function Me(e,t,n){let i,r,l=!1,a=!1,s=Symbol(),o=new Promise(e=>{r=()=>{e(s)}}),u=()=>{(!n()||t.aborted)&&we()},d=()=>{if(void 0!==i&&!l){l=!0;try{Promise.resolve(i.cancel()).catch(()=>{})}catch{}}},c=()=>{r?.(),d()};t.addEventListener(\\\"abort\\\",c,{once:!0});try{u();let t=e.body??null;if(u(),null===t){let t=e.json.bind(e);u();let n=await Promise.race([Promise.resolve().then(()=>(u(),t())),o]);return u(),n===s&&we(),n}let n=t.getReader.bind(t);u();let r=n();i=r,u();let l=[],d=0,c=0;for(;;){let e=Promise.resolve().then(()=>{u();let e=r.read.bind(r);return u(),e()}),t=await Promise.race([e,o]);if(u(),t===s&&we(),t.done)break;d+=t.value.byteLength,(++c>_r||d>Dr)&&we(),l.push(t.value)}a=!0;let h=new Uint8Array(d),f=0;for(let e of l)h.set(e,f),f+=e.byteLength;try{return JSON.parse((new TextDecoder).decode(h))}catch{return we()}}finally{t.removeEventListener(\\\"abort\\\",c),a||d();try{i?.releaseLock()}catch{}}}function Ee(e,t){let n=Fe(t);v(n)||we();let i=Ce(n,\\\"docs\\\");(!Array.isArray(i)||i.length>zr)&&we();let r=new Map;for(let t of i){v(t)||we();let n=Te(Ce(t,\\\"id\\\"));(!e.ids.has(n)||r.has(n))&&we(),r.set(n,t)}r.size!==e.ids.size&&we();for(let t of e.slots)Re(t.owner,t.key,r.get(t.id))}function Oe(e,t){return e.length>0&&e.length<=t&&\\\".\\\"!==e&&\\\"..\\\"!==e&&!e.includes(\\\"/\\\")&&!e.includes(\\\"\\\\\\\\\\\")&&!function(e){for(let t of e){let e=t.codePointAt(0)??0;if(e<=31||127===e)return!0}return!1}(e)}function Le(e){return Oe(e,128)&&!e.includes(\\\"?\\\")&&!e.includes(\\\"#\\\")}function xe(e){return\\\"number\\\"==typeof e?Number.isFinite(e):\\\"string\\\"==typeof e&&Oe(e,512)}function Pe(e){return e.has(\\\"schema-json\\\")?Gr:e.has(\\\"document-events\\\")||e.has(\\\"relationship-events\\\")?Kr:Jr}function Ue(e){if(\\\"attributes\\\"!==e.type||e.attributeName!==Xr||e.target.nodeType!==Qr)return null;let t=e.target;return\\\"astro-island\\\"!==t.tagName.toLowerCase()||t.hasAttribute(Xr)?null:t}function Ie(e){if(e.nodeType!==Qr)return!1;let t=e;return t.hasAttribute(dr)||t.matches(rr)||t.matches(Or)||null!==t.querySelector(`[${dr}], ${rr}, ${Or}`)}function je(){if(typ\",\"eof window>\\\"u\\\")return;let e=window;return e[ll]??(e[ll]={armed:!1,committed:!1,commits:[],onCommit:void 0,waiters:[]})}function We(){let e=je();if(void 0===e||e.armed)return;e.armed=!0;let t=window,n=t.__REACT_DEVTOOLS_GLOBAL_HOOK__??(t.__REACT_DEVTOOLS_GLOBAL_HOOK__=function(){let e=new Map;return{supportsFiber:!0,renderers:e,inject:t=>{let n=e.size+1;return e.set(n,t),n}}}()),i=n.onCommitFiberRoot;n.onCommitFiberRoot=function(t,n,...r){try{i?.call(this,t,n,...r)}catch{}void 0===e.onCommit?e.commits.push(n):e.onCommit(n)}}function Be(e){e.committed=!0;let t=e.waiters;e.waiters=[];for(let e of t)e()}function De(e,t){let n=e.waiters.indexOf(t);n>=0&&e.waiters.splice(n,1)}function _e(e,t,n){if(e.committed)return null;let i=null,r=()=>{null!==i&&clearTimeout(i),i=null,t(\\\"committed\\\")};return e.waiters.push(r),i=setTimeout(()=>{i=null,De(e,r),t(\\\"timed-out\\\")},n),()=>{null!==i&&clearTimeout(i),i=null,De(e,r)}}function ze(){if(typ\",\"eof window>\\\"u\\\")return;let e=window;return e[ol]??(e[ol]={armed:!1,committed:!1,waiters:[]})}function Ve(e){return Object.prototype.hasOwnProperty.call(e,sl)?e[sl]:void 0}function qe(){let e=ze();if(void 0===e||e.armed)return;e.armed=!0;let t=Element.prototype;void 0===Object.getOwnPropertyDescriptor(t,sl)&&Object.defineProperty(t,sl,{configurable:!0,get:()=>{},set(e){Object.defineProperty(this,sl,{value:e,writable:!0,configurable:!0,enumerable:!0});let t=ze();void 0===t||t.committed||null===this.querySelector(al)||function(e,t){let n=t?.$nuxt;!0!==n?.isHydrating||\\\"function\\\"!=typeof n.hook?Be(e):n.hook(ul,()=>{e.committed||Be(e)})}(t,e)}})}function He(e){let t=e.hydration;if(void 0===t){e.startNow();return}let n=dl[t](e.root,n=>{e.later(()=>{Ge(e,t,n)})});null!==n?(e.defer(n),e.hydrated(\\\"waiting\\\")):Ge(e,t,\\\"committed\\\")}function Ge(e,t,n){e.hydrated(n),\\\"timed-out\\\"===n&&e.warn(`[live-preview] LP0607: no ${cl[t]} in ${String(5e3)} ms; started without waiting for hydration.`),e.startNow()}function Ke(e){return 9===e.nodeType}function Je(e){return e.body}function Xe(e,t=gl){if(\\\"string\\\"!=typeof e)return!1;let n=e.trim();return!(n.length<t||vl.test(n)||ml.has(n.toLowerCase())||yl.test(n)||bl.test(n))}function Qe(e){return\\\"object\\\"==typeof e&&null!==e&&!Array.isArray(e)}function Ze(e,t,n=gl){let i=new Map,r=(e,t,n)=>{i.set(e,i.has(e)?null:{field:t,media:n})};for(let[i,l]of Object.entries(e)){if(zi.has(i))continue;let e=H(i,t);if(Xe(l,n))r(l.trim(),e,!1);else if(Qe(l))if(\\\"string\\\"==typeof l.url)r(l.url,e,!0);else if(!(\\\"id\\\"in l)&&!(\\\"_id\\\"in l))for(let[t,i]of Object.entries(l))zi.has(t)||!Xe(i,n)||r(i.trim(),`${e}.${t}`,!1)}return i}function Ye(e){if(e.namespaceURI!==Sl||wl.has(e.tagName)||e.hasAttribute(dr)||e.hasAttribute(pl)||e.hasAttribute(lr)||oe(e))return!0;let t=e.getAttribute(\\\"contenteditable\\\");return null!==t&&\\\"false\\\"!==t}function et(e){let t;for(let n=e.firstChild;null!==n;n=n.nextSibling){if(1===n.nodeType)return;if(3!==n.nodeType)continue;let e=n.data.trim();if(0!==e.length){if(void 0!==t)return;t=e}}return t}function tt(e){return M(e)&&!e.startsWith(\\\"data-payload-\\\")&&\\\"value\\\"!==e}function nt(e,t,n){let i=e.byElement.get(t);void 0===i&&(i={attributes:new Map},e.byElement.set(t,i));let r=e.byField.get(n.field);return void 0===r&&(r=new Set,e.byField.set(n.field,r)),r.add(t),i}function it(e,t){for(let n=e.firstElementChild;null!==n;n=n.nextElementSibling){if(Ye(n))continue;let e=et(n),i=void 0===e?void 0:t.values.get(e);null!=i&&!i.media&&(nt(t,n,i).text=i.field);for(let e of n.getAttributeNames()){if(!tt(e))continue;let i=t.values.get(n.getAttribute(e)??\\\"\\\");null!=i&&(i.media&&(\\\"IMG\\\"!==n.tagName||\\\"src\\\"!==e)||nt(t,n,i).attributes.set(e,i))}it(n,t)}}function rt(e,t,n){let i=e.tagName;if(void 0!==t){let r={[dr]:t};if(\\\"A\\\"===i){let e=n.get(\\\"href\\\");void 0===e?r[cr]=\\\"text\\\":e!==t&&(r[fr]=e)}return{element:e,fieldName:t,matched:et(e)??\\\"\\\",stamps:r}}if(\\\"IMG\\\"===i){let t=n.get(\\\"src\\\");if(void 0!==t){let i=n.get(\\\"alt\\\");return{element:e,fieldName:t,matched:e.getAttribute(\\\"src\\\")??\\\"\\\",attribute:\\\"src\\\",stamps:{[dr]:t,...void 0!==i&&i!==t?{[gr]:i}:{}}}}}let r=n.entries().next();if(r.done)return;let[l,a]=r.value;return{element:e,fieldName:a,matched:e.getAttribute(l)??\\\"\\\",attribute:l,stamps:{[dr]:a,[hr]:l}}}function lt(e,t){let n={values:t,byElement:new Map,byField:new Map};t.size>0&&!Ye(e)&&it(e,n);let i=e=>1===n.byField.get(e)?.size,r=[];for(let[e,t]of n.byElement){let n=void 0!==t.text&&i(t.text)?t.text:void 0,l=new Map;for(let[e,n]of t.attributes)i(n.field)&&l.set(e,n.field);let a=rt(e,n,l);void 0!==a&&r.push(a)}return r}function at(e){return 9===e.nodeType?e.body:e}function st(e,t){for(let n=t.length-1;n>=0;n-=1){let i=t[n];if(void 0!==i){i.observed&&e.observers.unobserveElement(i.element);for(let e=i.attributes.length-1;e>=0;e-=1){let t=i.attributes[e];if(void 0===t)continue;let{name:n,before:r,written:l}=t;r===l||i.element.getAttribute(n)!==l||(null===r?i.element.removeAttribute(n):i.element.setAttribute(n,r))}i.cacheTouched&&(i.element.hasAttribute(dr)?e.cache.add(i.element):e.cache.remove(i.element))}}}function ot(e,t,n,i,r){let l=[],a=[],s=()=>(st(e,a),[]);for(let o of t){if(!r())return s();let{element:t}=o;if(t.hasAttribute(dr))continue;if(!r())return s();if(!1!==n&&!W(ge(t),n))continue;if(!r())return s();let u={element:t,attributes:[],cacheTouched:!1,observed:!1};a.push(u);for(let[e,n]of[...Object.entries(o.stamps),[$r,o.matched]]){let i=t.getAttribute(e);if(!r()||(u.attributes.push({name:e,before:i,written:n}),t.setAttribute(e,n),!r()))return s()}if(u.cacheTouched=!0,void 0!==e.cache.add(t)){if(!r()||(e.observers.observeElement(t),u.observed=!0,!r())||(e.log(\\\"autoBind\\\",o.fieldName,\\\"\\\\u2192\\\",`<${t.tagName.toLowerCase()}>`,o.attribute??\\\"text\\\",JSON.stringify(o.matched),i),!r()))return s();l.push(o)}else st(e,[u]),a.pop()}return l}function ut(e,t,n,i=!1){if(i&&void 0!==n){let i=dt(e,`${t}_${n}`);if(void 0!==i)return i}let r=dt(e,t);if(void 0!==r)return r;if(t.includes(\\\".\\\")){let n=e,i=!0;for(let e of t.split(\\\".\\\")){if(Al.has(e)||null===n||\\\"object\\\"!=typeof n){i=!1;break}if(n=dt(n,e),void 0===n){i=!1;break}}if(i)return n}return void 0===n?void 0:dt(e,`${t}_${n}`)}function dt(e,t){if(!Al.has(t)&&Object.prototype.hasOwnProperty.call(e,t))return e[t]}function ct(e,t,n,i){return ut(e,n,t.locale??i,void 0!==t.locale)}function ht(e,t,n,i){let r=O(t);if(void 0===r)return;let l=[e.hrefField,e.srcField,e.altField],a=r;for(let t of l){if(void 0===t||0===t.length)continue;let r=O(ct(n,e,t,i));if(void 0===r)return;a+=`|${t}=${r}`}return a}function ft(e,t,n,i){if(!e.scopeBindingsByOwner)return!1;let{message:r}=n,l=function(e){if(j(e.globalSlug))return[U(e.globalSlug)];if(!j(e.collectionSlug))return null;let t=I(e.collectionSlug);return j(e.documentId)?[t,I(e.collectionSlug,e.documentId)]:[t]}({globalSlug:\\\"string\\\"==typeof r.globalSlug?r.globalSlug:void 0,collectionSlug:\\\"string\\\"==typeof r.collectionSlug?r.collectionSlug:void 0,documentId:B(i)});return null===l&&!t.warnedUnattributableMessage&&(t.warnedUnattributableMessage=!0,e.warn(\\\"[live-preview] LP0202: scopeBindingsByOwner: update names no document; nothing applied\\\")),l}function pt(e,t,n,i,r){!function(e,t,n){let i=0;for(let r of e)if(!n()||(r.dispatchEvent(new CustomEvent(nr,{detail:t,bubbles:!1})),i+=1,!n()))break}(n,{fields:t.fields,revision:e.revision.revision,receivedAt:e.receivedAt,locale:e.locale,displayed:r},i)}function gt(e,t,n,i,r){let{warned:l,warn:a}=e;if(l.has(n)||t(n))return;l.add(n);let s=`data-payload-field=\\\"${H(n,i)}\\\"`;a(\\\"\\\"!==r?`[live-preview] LP0203: field \\\"${n}\\\" has a value and no <\\\\u2026 ${s}> on this page; editing it changes nothing here. Expected where the page shows part of the document: inspect().fidelity.fields lists these, onUnfaithfulPatch decides whether a server render is asked for.`:`[live-preview] LP0201: no <\\\\u2026 ${s}> for the empty field \\\"${n}\\\"; render the anchor unconditionally so edits to an empty field have somewhere to land.`)}function mt(e){let t=typeof e;return\\\"string\\\"===t||\\\"number\\\"===t||\\\"boolean\\\"===t||\\\"bigint\\\"===t}function vt(e){return\\\"object\\\"==typeof e&&null!==e&&!Array.isArray(e)}function yt(e){let t=function(){let e=function(){let e=globalThis,t=e[Cl];if(void 0!==t)return t;let n={};return e[Cl]=n,n}();if(void 0!==e.override)return e.override;if(void 0!==e.auto)return e.auto;let t=function(){let e=globalThis.trustedTypes;return\\\"object\\\"!=typeof e||null===e?void 0:\\\"function\\\"==typeof e.createPolicy?e:void 0}();try{e.auto=void 0===t?null:t.createPolicy(Tl,{createHTML:e=>e})}catch{e.auto=null}return e.auto}();return null===t?e:t.createHTML(e)}function bt(e,t){for(let n of t.keyAttributes){let t=e.getAttribute(n);if(null!==t&&t.length>0)return`${n}=${t}`}}function wt(e,t,n){if(!kt(e,t))return t;let i=n.boundary??ae,r=i(e),l=i(t);if(r||l)return r&&l&&(n.retainBoundary?.(e,t)??1)?e:t;let a=Tt(e);return function(e,t){for(let n of Array.from(e.attributes))t.hasAttribute(n.name)||Rl.has(n.name.toLowerCase())||e.removeAttribute(n.name);for(let n of Array.from(t.attributes))e.getAttribute(n.name)!==n.value&&e.setAttribute(n.name,n.value)}(e,t),!0!==n.retainChildrenOf?.(e,t)&&function(e,t,n){let i=function(e,t){let n,i=new Map;for(let r of Array.from(e.children)){let e=bt(r,t);if(void 0!==e){if(i.has(e)){n??(n=e.slice(e.indexOf(\\\"=\\\")+1));continue}i.set(e,r)}}return void 0!==n&&t.onDuplicateKey?.(e,n),i}(e,n),r=new Set(i.values()),l=Array.from(e.childNodes).filter(e=>!r.has(e)),a=new Set,s=new Set,o=Array.from(t.childNodes),u=e.firstChild,d=0;for(let t=0;t<o.length;t+=1){let r=o[t],c=null,h=r instanceof Element?bt(r,n):void 0;if(void 0!==h&&s.has(h)&&(h=void 0),void 0!==h){s.add(h);let e=i.get(h);if(void 0!==e&&!a.has(e)&&(c=St(e,r,n)===e?e:null,null===c)){e.replaceWith(r),a.add(r),u=r.nextSibling;continue}}else{for(;d<l.length;){let i=l[d];if(d+=1,!a.has(i)){if(kt(i,r)){c=St(i,r,n)===i?i:null,null===c&&(e.replaceChild(r,i),a.add(r),u=r.nextSibling);break}if(i instanceof Element){let n=o[t+1];if(!(r instanceof Element)||void 0!==n&&kt(i,n)){d-=1;break}e.replaceChild(r,i),a.add(r),u=r.nextSibling;break}if(!(r instanceof Element)){e.replaceChild(r,i),a.add(r),u=r.nextSibling;break}}}if(null===c&&a.has(r))continue}let f=c??r;for(a.add(f);null!==u&&u!==f&&!a.has(u)&&At(u);)u=u.nextSibling;f!==u&&e.insertBefore(f,u),u=f.nextSibling}for(let t of Array.from(e.childNodes))a.has(t)||t.remove()}(e,t,n),Ct(a),e}function St(e,t,n){return e instanceof Element&&t instanceof Element?wt(e,t,n):(e.nodeValue!==t.nodeValue&&(e.nodeValue=t.nodeValue),e)}function At(e){return e.nodeType===Node.TEXT_NODE&&0===(e.nodeValue??\\\"\\\").trim().length}function kt(e,t){return e.nodeType===t.nodeType&&(!(e instanceof Element&&t instanceof Element)||e.tagName===t.tagName&&e.namespaceURI===t.namespaceURI)}function Tt(e){let t=e.ownerDocument.activeElement;return t instanceof HTMLElement&&e.contains(t)?{element:t,selection:t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement?[t.selectionStart,t.selectionEnd]:null}:null}function Ct(e){if(null===e)return;let{element:t,selection:n}=e;if(t.ownerDocument.activeElement!==t&&t.isConnected)try{t.focus({preventScroll:!0});let[e,i]=n??[null,null];null!==e&&null!==i&&t.setSelectionRange(e,i)}catch{}}function Rt(e){Fl.has(e)||(Fl.add(e),function(e){try{console.warn(e)}catch{}}(`[live-preview] LP0409: the strict sanitizer removed \\\\`${e}\\\\` from written markup; the 1.x default (\\\\`sanitizerPolicy: 'compat'\\\\`) kept it. ${function(e){return e.startsWith(Nl)?\\\"A binding inside CMS content is refused by design \\\\u2014 an editor could otherwise aim a write at any element on the page (docs/security.md)\\\":\\\"id\\\"===e||\\\"name\\\"===e?\\\"CMS content that can name an element can shadow a global of that name \\\\u2014 DOM clobbering, refused by design (docs/security.md)\\\":\\\"Put it on an element the template owns, or set `sanitizerPolicy: 'compat'` to keep every `data-*` as 1.x did\\\"}(e)}.`))}function $t(e,t){return Ft(e,void 0,t)}function Ft(e,t,n){let i=n?.document??Nt();if(!i)throw new Error(\\\"sanitizeHtml needs a DOM\\\");if(\\\"\\\"===e)return\\\"\\\";let r=function(e,t){let n=e?.policy??t??zl;if(!e){let e=new Map;for(let[t,n]of Object.entries(Il))e.set(t,n);return{allowedTags:Ml,attrByTag:e,allowFormControls:!1,templateMode:!1,mode:n,allowedData:new Set}}let i=new Set(Ml);if(e.additionalAllowedTags?.forEach(e=>i.add(e)),!0===e.allowFormControls)for(let e of El)i.add(e);let r=new Map;for(let[e,t]of Object.entries(Il))r.set(e,t);for(let[t,n]of Object.entries(e.additionalAllowedAttributes??{})){let e=new Set(r.get(t));for(let t of n)e.add(t);r.set(t,e)}return{allowedTags:i,attrByTag:r,allowFormControls:!0===e.allowFormControls,templateMode:!0===e.templateMode,mode:n,allowedData:new Set(e.allowedDataAttributes?.map(e=>e.toLowerCase()))}}(n,t),l=e;for(let e=0;e<Wl;e+=1){let e=i.createElement(\\\"template\\\");e.innerHTML=yt(l),Mt(e.content,r);let t=e.innerHTML;if(t===l)return t;l=t}return function(e,t){if(!function(){try{let e=glo\",\"balThis.process?.env;return void 0!==e&&\\\"production\\\"!==e.NODE_ENV}catch{return!1}}())return;let n=globalThis,i=n[$l]??(n[$l]=new Set);if(!i.has(e)){i.add(e);try{console.warn(`[payload-live-preview] ${t}`)}catch{}}}(\\\"sanitizer-unsettled\\\",`sanitizeHtml: the output did not settle after ${String(Wl)} passes, so it returned an empty string (ADR 0016).`),\\\"\\\"}function Nt(){if(!(typ\",\"eof document>\\\"u\\\"))return document}function Mt(e,t){for(let n of Array.from(e.childNodes))n.nodeType===Bl?Et(n,t):n.nodeType===Dl&&n.remove()}function Et(e,t){let n=e.tagName.toLowerCase();!Ol.has(n)||t.allowFormControls&&El.has(n)?t.allowedTags.has(n)?(function(e,t,n){let i=n.attrByTag.get(t);for(let t of Array.from(e.attributes)){let r=t.name.toLowerCase();if(r.startsWith(\\\"on\\\")||\\\"style\\\"===r)e.removeAttribute(t.name);else if(\\\"is\\\"!==r){if(\\\"strict\\\"===n.mode){if(n.templateMode&&_l.has(r))continue;if(\\\"id\\\"===r||\\\"name\\\"===r||r.startsWith(Ul)){e.removeAttribute(t.name),(\\\"name\\\"!==r||!0===i?.has(r))&&Rt(r);continue}if(r.startsWith(Pl)){n.allowedData.has(r)||(e.removeAttribute(t.name),Rt(r));continue}if(Ll.has(r)||r.startsWith(xl))continue}else if(Ll.has(r)||r.startsWith(xl)||r.startsWith(Pl))continue;i?.has(r)?(jl.has(r)&&!F(t.value)||\\\"srcset\\\"===r&&!Ot(t.value))&&e.removeAttribute(t.name):e.removeAttribute(t.name)}else e.setAttribute(\\\"is\\\",\\\"\\\")}}(e,n,t),\\\"a\\\"===n&&function(e){let t=e.getAttribute(\\\"href\\\");null===t||!N(t)||(e.setAttribute(\\\"rel\\\",\\\"noopener noreferrer\\\"),e.hasAttribute(\\\"target\\\")||e.setAttribute(\\\"target\\\",\\\"_blank\\\"))}(e),Mt(e,t)):(Mt(e,t),e.replaceWith(...e.childNodes)):e.remove()}function Ot(e){for(let t of e.split(\\\",\\\")){let e=t.trim();if(0===e.length)continue;let[n=e]=e.split(/\\\\s/,1);if(!F(n)||!F(e))return!1}return!0}function Lt(e){return e.replace(ql,e=>Vl[e])}function xt(e){return e.replace(Gl,e=>Hl[e])}function Pt(e){let t=new Set;for(let n of e)if(\\\"object\\\"==typeof n&&null!==n)for(let e of Object.keys(n))t.add(e);return t}function Ut(e,t,n,i,r){let l=\\\"object\\\"==typeof t&&null!==t?t:null;return e.replace(Kl,(e,a)=>null!==l&&function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(l,a)?Lt(i(Reflect.get(l,a))):null===l&&\\\"value\\\"===a?Lt(i(t)):\\\"index\\\"===a?String(n):null!==l&&!0===r?.has(a)?\\\"\\\":e)}function It(e){let t=e.children,n=t[0];if(void 0===n)return[];let i=[];for(let{name:e,value:r}of Array.from(n.attributes)){if(!M(e)||e.startsWith(Jl))continue;let n=!0;for(let i=1;i<t.length&&n;i+=1)n=t[i]?.getAttribute(e)===r;n&&i.push([e,r])}return i}function jt(e,t){for(let[n,i]of t)e.hasAttribute(n)||e.setAttribute(n,i)}function Wt(e){if(null==e)return\\\"\\\";if(\\\"string\\\"==typeof e)return e;if(\\\"number\\\"==typeof e||\\\"boolean\\\"==typeof e||\\\"bigint\\\"==typeof e)return String(e);try{return JSON.stringify(e)}catch{return\\\"\\\"}}function Bt(e){return null==e||\\\"\\\"===e}function Dt(e,t){let n=e.get(t);return void 0!==n&&(e.delete(t),e.set(t,n)),n}function _t(e,t,n,i){return e.set(t,n),function(e,t){for(let n of e.keys()){if(e.size<=t)break;e.delete(n)}}(e,i),n}function zt(e){let t=Dt(ea,e);if(void 0!==t)return t;let n=new Set(Xl);for(let t of e.matchAll(Zl)){let e=t[1]?.toLowerCase();void 0!==e&&n.add(e)}let i={};for(let e of n)i[e]=Ql;let r={additionalAllowedTags:[...n],additionalAllowedAttributes:i,allowFormControls:!0,templateMode:!0};return _t(ea,e,r,Yl)}function Vt(e){let t=Ht(e.container,e.patches,e);return null===t?null:Gt(t,e.store,{morph:e.morph??!0,onDuplicateKey:e.onDuplicateKey})}function qt(e,t){return t.hasAttribute(na)&&t.hasAttribute(ia)}function Ht(e,t,n){let i=function(e,t,n){let{template:i,nextItems:r,forceRender:l=!1,store:a,sanitizerPolicy:s}=n,o=a.get(e),u=It(e),d=Pt(r),c=Array.from(e.children),h=en(c,ta),f=new Set,p=[];for(let a=0;a<r.length;a+=1){let g=r[a],m=Yt(g),v=void 0===m?c[a]??null:tn(h,m)??null;null!==v&&f.has(v)&&(v=null),null!==v&&f.add(v);let y=t.replaces.has(a),b=l||t.renders.has(a)||null===v?nn(e.ownerDocument,i,g,a,s,u,d):void 0;if(null===b)return null;let w=void 0===b?[]:Kt(y?null:v,b,g,void 0===m?void 0:o?.get(m),n);if(null===w)return null;p.push([a,v,b,w,y])}return p}(e,function(e){let t=new Set,n=new Set;for(let i of e)\\\"insert\\\"===i.kind||\\\"update\\\"===i.kind?t.add(i.index):\\\"replace\\\"===i.kind&&(t.add(i.index),n.add(i.index));return{renders:t,replaces:n}}(t),n);return null===i?null:[e,i,n.nextItems]}function Gt(e,t,n){let[i,r,l]=e,a=new Set,s=!1,o=Tt(i);for(let[e,l,o,u,d]of r){let r=l;if(void 0!==o){let e=!(!n.morph||d||null===l)&&wt(l,o,{keyAttributes:[ta,na],boundary:ae,retainBoundary:he,retainChildrenOf:qt,...void 0!==n.onDuplicateKey?{onDuplicateKey:n.onDuplicateKey}:{}})===l;if(!e)for(let[e,t]of u)null!==e&&(Xt(e,t),t.replaceWith(e));for(let[,,e]of u)void 0!==e&&Gt(e,t,n);e?s=!0:(null!==l&&(l.replaceWith(o),s=!0),r=o)}if(null===r)continue;let c=i.children[e]??null;r!==c&&(i.insertBefore(r,c),s=!0),a.add(r)}for(let e of Array.from(i.children))a.has(e)||(e.remove(),s=!0);Ct(o);let u=function(e,t){let n=t.get(e);return n||(n=new Map,t.set(e,n)),n}(i,t);u.clear();for(let e of l)Zt(u,e);return s}function Kt(e,t,n,i,r){let l=en(null===e?[]:Jt(e),na),a=[];for(let e of Jt(t)){let t=e.getAttribute(na);if(null===t)continue;let s,o=tn(l,t)??null,u=e.getAttribute(ia),d=u?o:null,c=d?.getAttribute(ia)??null;if(u){let l=Qt(n,t);if(void 0!==l||null!==d){let n=l??[],a=R(null===d?[]:Qt(i,t)??[],n),o=null!==d&&c!==u;if((a.length>0||o)&&(s=Ht(d??e,a,{template:u,nextItems:n,forceRender:o,store:r.store,sanitizerPolicy:r.sanitizerPolicy})??void 0,void 0===s))return null}}a.push([d,e,s])}return a}function Jt(e){return Array.from(e.querySelectorAll(`[${na}]`)).filter(t=>{let n=t.parentElement;for(;null!==n&&n!==e;){if(n.hasAttribute(na))return!1;n=n.parentElement}return n===e})}function Xt(e,t){for(let n of Array.from(e.attributes))t.hasAttribute(n.name)||e.removeAttribute(n.name);for(let n of Array.from(t.attributes))e.getAttribute(n.name)!==n.value&&e.setAttribute(n.name,n.value)}function Qt(e,t){if(\\\"object\\\"!=typeof e||null===e)return;let n=e[t];return Array.isArray(n)?n:void 0}function Zt(e,t){let n=Yt(t);void 0!==n&&e.set(n,t)}function Yt(e){if(\\\"object\\\"!=typeof e||null===e)return;let t=e.id;return\\\"string\\\"==typeof t||\\\"number\\\"==typeof t?String(t):void 0}function en(e,t){let n=new Map;for(let i=e.length-1;i>=0;i-=1){let r=e[i];if(void 0===r)continue;let l=r.getAttribute(t);if(null===l)continue;let a=n.get(l);void 0===a?n.set(l,[r]):a.push(r)}return n}function tn(e,t){return e.get(t)?.pop()}function nn(e,t,n,i,r,l,a){let s=Ft(Ut(t,n,i,Wt,a),r,zt(t)),o=e.createElement(\\\"template\\\");o.innerHTML=yt(s);let u=o.content.firstElementChild;if(!u)return null;jt(u,l);let d=Yt(n);return void 0!==d&&u.setAttribute(ta,d),u}function rn(e,t,n){let i=new Set(t);return{boundaries:t,strategy:e,ownerKeys:n,covers:e=>void 0!==e.fragmentBoundary&&i.has(e.fragmentBoundary)}}function ln(e,t){return!1===t||W(ge(e),t)}function an(t,n,i,r,l){let a=t.transformValue;if(void 0===a)return i;try{let t=a(n.fieldName,i,{element:n.element,allFields:r},l),s=e(t);if(!l())return i;if(s)throw new TypeError(`Transform for \\\"${n.fieldName}\\\" returned a thenable; transforms must be synchronous`);return t}catch(e){if(!l())return i;let n=e instanceof Error?e:new Error(String(e));return t.emitter.emit(\\\"error\\\",{error:n,context:\\\"transform\\\",code:\\\"LP0602\\\"}),i}}function sn(){if(typ\",\"eof window>\\\"u\\\")return!1;try{return window.self!==window.top}catch{return!0}}function on(e){let t=e.trim();if(0!==t.length)try{let e=new URL(t);return\\\"http:\\\"!==e.protocol&&\\\"https:\\\"!==e.protocol||!ha.test(e.origin)?void 0:e.origin}catch{return}}function un(e){let t=e.format;return\\\"string\\\"==typeof t&&ba.has(t)?t:\\\"number\\\"==typeof t?ya[t]:void 0}function dn(e){let t=e.indent;return\\\"number\\\"==typeof t&&t>0?t:0}function cn(e){return\\\"rtl\\\"===e.direction?' dir=\\\"rtl\\\"':\\\"ltr\\\"===e.direction?' dir=\\\"ltr\\\"':\\\"\\\"}function hn(e){let t=un(e),n=dn(e),i=[];return void 0!==t&&i.push(`lp-align-${t}`),n>0&&i.push(`lp-indent-${String(n)}`),0===i.length?\\\"\\\":` class=\\\"${i.join(\\\" \\\")}\\\"`}function fn(e){return\\\"object\\\"==typeof e&&null!==e?e:void 0}function pn(e){return fn(e)}function gn(e,t){if(void 0===t||\\\"\\\"===t||!e.startsWith(\\\"/\\\"))return e;try{let n=new URL(t),i=new URL(e,n);return i.origin===n.origin?i.href:e}catch{return e}}function mn(e){return e.replace(/[^a-zA-Z0-9_-]/g,\\\"-\\\").toLowerCase()}function vn(e){return\\\"string\\\"==typeof e&&e.length>0?e:void 0}function yn(e){let t=vn(e.title)??vn(e.name)??vn(e.slug);return void 0!==t?t:void 0===e.id?void 0:String(e.id)}function bn(e){if(\\\"string\\\"==typeof e.text)return e.text;if(!e.children)return\\\"\\\";let t=\\\"\\\";for(let n of e.children)t+=bn(n);return t}function wn(e){return`${\\\"number\\\"==typeof e.width?` width=\\\"${String(e.width)}\\\"`:\\\"\\\"}${\\\"number\\\"==typeof e.height?` height=\\\"${String(e.height)}\\\"`:\\\"\\\"}`}function Sn(e){return\\\"string\\\"==typeof e.mimeType?` type=\\\"${xt(e.mimeType)}\\\"`:\\\"\\\"}function An(e){return ka.get(e)}function kn(e,t,n,i){let r=fn(e.fields)??{},l=\\\"string\\\"==typeof r.blockType?r.blockType:\\\"\\\",a=mn(l),s=\\\"\\\"===a?i:`${i} ${i}--${a}`;if(\\\"\\\"!==l){let e=An(l)??An(a);if(e)return e(r,{renderChildren:t.renderChildren});t.onUnrenderedBlock?.(l,s)}return`<${n} class=\\\"${s}\\\"></${n}>`}function Tn(e,t){return\\\"number\\\"==typeof t&&t>1?` ${e}=\\\"${String(t)}\\\"`:\\\"\\\"}function Cn(e){if(\\\"object\\\"!=typeof e||null===e||!(\\\"root\\\"in e))return!1;let t=e.root;return\\\"object\\\"==typeof t&&null!==t&&\\\"children\\\"in t&&Array.isArray(t.children)}function Rn(e,t){let n=function(e){return Ra.get(e)??Ca[e]}(e.type);return n?n(e,t):void 0!==e.children?t.renderChildren(e.children):\\\"\\\"}function $n(e){if(\\\"string\\\"==typeof e.text)return e.text;if(\\\"linebreak\\\"===e.type)return\\\"\\\\n\\\";if(void 0===e.children)return\\\"\\\";let t=\\\"\\\";for(let n of e.children)t+=$n(n);return t}function Fn(e=\\\"text\\\"){let t=new WeakSet;return{name:e,render:E((e,n)=>{let i=e.element,r=function(e){return null==e?\\\"\\\":Cn(e)?function(e){return Cn(e)?e.root.children.map($n).join(\\\"\\\\n\\\").trim():\\\"\\\"}(e):\\\"string\\\"==typeof e?e:\\\"number\\\"==typeof e||\\\"boolean\\\"==typeof e?String(e):JSON.stringify(e)}(n);if(\\\"INPUT\\\"!==i.tagName&&\\\"TEXTAREA\\\"!==i.tagName){if(function(e){return null!==e.querySelector(\\\":scope > :not(br)\\\")}(i)&&!i.hasAttribute(Fa))return function(e,t,n){e.has(t)||(e.add(t),si(`[live-preview] LP0402: Skipping text update for \\\"${n}\\\": <${t.tagName.toLowerCase()}> has structured children. Move data-payload-field to the value element, or add data-payload-text to replace them.`))}(t,i,e.fieldName),!1;r.includes(\\\"\\\\n\\\")||r.includes(\\\"\\\\r\\\")?i.innerHTML=yt(function(e){return Lt(e).replace(/\\\\r\\\\n|\\\\r|\\\\n/g,\\\"<br>\\\")}(r)):i.textContent=r}else i.value=r})}}function Nn(e,t){let n=e.cloneNode(!1);n.innerHTML=yt(t);let i=function(e,t){let n=e.firstElementChild;if(null!==n?.nextElementSibling||t.children.length<2||!Ea.has(n.tagName)||n.hasAttribute(dr))return null;for(let e of t.children)if(e.tagName===n.tagName&&e.className===n.className)return null;return n}(e,n)??e,r=new Map,l=n.querySelectorAll(Ta);if(l.length>0&&null!==i.firstElementChild){let e=[];Mn(i,n,e);for(let[t,n]of e)t.replaceWith(n),n.matches(Ta)||r.set(t.className,!1);for(let e of l)null!==e.parentNode&&r.set(e.className,!0)}return i.replaceChildren(...n.childNodes),r}function Mn(e,t,n){if(e.children.length!==t.children.length)return;let i=e.firstElementChild,r=t.firstElementChild;for(;null!==i&&null!==r;)r.matches(Ta)?n.push([r,i]):Mn(i,r,n),i=i.nextElementSibling,r=r.nextElementSibling}function En(e,t,n,i){i&&t.reportUnfaithful?.(e,`lost the markup the server drew for block \\\"${n}\\\"`);let r=i?Ma:Na;r.has(n)||(r.add(n),si(`[live-preview] ${i?`LP0413: no renderer for block \\\"${n}\\\", and the markup the server rendered for it is lost.`:`LP0410: no renderer for block \\\"${n}\\\"; keeping what the server rendered for it.`} Register one with registerBlockRenderer().`))}function On(e,t,n,i){if(\\\"string\\\"!=typeof n||0===n.length)return{kind:\\\"none\\\"};let r=gn(n,i);return F(r)?{kind:\\\"safe\\\",url:r}:(xa.has(e)||(xa.add(e),si(`[live-preview] LP0401: refused an unsafe URL for \\\"${t}\\\" on <${e.tagName.toLowerCase()}>; the attribute was cleared.`)),{kind:\\\"unsafe\\\"})}function Ln(e,t=e=>e){return{name:e,render(e,n,i){let r=e.element;if(Bt(n)){!function(e){\\\"INPUT\\\"!==e.tagName&&\\\"TEXTAREA\\\"!==e.tagName?(e.removeAttribute(\\\"href\\\"),e.textContent=\\\"\\\"):e.value=\\\"\\\"}(r);return}let l=Wt(n);if(\\\"INPUT\\\"!==r.tagName&&\\\"TEXTAREA\\\"!==r.tagName){if(\\\"A\\\"===r.tagName){let n=e.hrefField,a=void 0===n||0===n.length?t(l):ut(i.allFields,n,i.locale,void 0!==e.locale),s=On(r,e.fieldName,a);\\\"safe\\\"===s.kind?r.setAttribute(\\\"href\\\",s.url):\\\"unsafe\\\"===s.kind&&r.removeAttribute(\\\"href\\\")}r.textContent=l}else r.value=l}}}function xn(e){for(let t of ja)e.removeAttribute(t)}function Pn(e,t,n,i){e.src=t;let r=function(e,t){if(void 0===e?.sizes)return;let n=[];for(let i of Object.values(e.sizes)){if(\\\"string\\\"!=typeof i.url||\\\"number\\\"!=typeof i.width)continue;let e=gn(i.url,t);F(e)&&n.push(`${Un(e)} ${String(i.width)}w`)}if(0!==n.length){if(\\\"number\\\"==typeof e.width&&\\\"string\\\"==typeof e.url){let i=gn(e.url,t);F(i)&&n.push(`${Un(i)} ${String(e.width)}w`)}return n.join(\\\", \\\")}}(n,i);void 0!==r?e.setAttribute(\\\"srcset\\\",r):(e.removeAttribute(\\\"srcset\\\"),e.removeAttribute(\\\"sizes\\\"))}function Un(e){return e.replace(/[\\\\s,]/g,encodeURIComponent)}function In(e){\\\"IMG\\\"===e.tagName?xn(e):e.style.backgroundImage=\\\"\\\"}function jn(e){\\\"IMG\\\"!==e.tagName?(e.removeAttribute(\\\"href\\\"),e.textContent=\\\"\\\"):xn(e)}function Wn(e){let t=fn(e);return void 0===t?Wt(e):yn(t)??\\\"\\\"}function Bn(e,t){let n=e??\\\"\\\";if(null==t)return n;let i=Dn(t);return\\\"{}\\\"===i?n:`${n}|${i}`}function Dn(e){if(null===e||\\\"object\\\"!=typeof e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(e=>Dn(e)).join(\\\",\\\")}]`;let t=e,n=Object.keys(t).sort(),i=[];for(let e of n){let n=t[e];void 0!==n&&i.push(`${JSON.stringify(e)}:${Dn(n)}`)}return`{${i.join(\\\",\\\")}}`}function _n(e){return{kind:\\\"date\\\",options:e}}function zn(e){return{kind:\\\"number\\\",options:e}}function Vn(e,t,n,i){if(void 0===t||\\\"\\\"===t)return;let r=function(e){let t=e.indexOf(\\\":\\\"),n=-1===t?e:e.slice(0,t),i=-1===t?void 0:e.slice(t+1);switch(n){case\\\"date\\\":return void 0===i?_n({dateStyle:\\\"medium\\\"}):Ga.has(i)?_n({dateStyle:i}):void 0;case\\\"time\\\":return void 0===i?_n({timeStyle:\\\"short\\\"}):Ka.has(i)?_n({timeStyle:i}):void 0;case\\\"datetime\\\":return void 0===i?_n({dateStyle:\\\"medium\\\",timeStyle:\\\"short\\\"}):Ga.has(i)?_n({dateStyle:i,timeStyle:\\\"short\\\"===i?\\\"short\\\":\\\"medium\\\"}):void 0;case\\\"number\\\":return void 0===i?zn({}):Xa.test(i)?zn({minimumFractionDigits:Number(i),maximumFractionDigits:Number(i)}):void 0;case\\\"currency\\\":return void 0!==i&&Ja.test(i)?zn({style:\\\"currency\\\",currency:i.toUpperCase()}):void 0;case\\\"percent\\\":return void 0===i?zn({style:\\\"percent\\\"}):void 0;default:return}}(t);if(void 0!==r)return r.kind===e?r.options:void 0;!function(e,t,n){Qa.has(e)||(Qa.add(e),si(`[live-preview] LP0408: data-payload-format=\\\"${n}\\\" on \\\"${t}\\\" is not a known format; the default formatting was used. Known: date, time, datetime (each also :short|medium|long|full), number, number:0-4, currency:XXX, percent.`))}(n,i,t)}function qn(e){return String(e).padStart(2,\\\"0\\\")}function Hn(){let e=new WeakMap,t=new WeakSet,n=new WeakMap,i=new WeakMap;return{name:\\\"structural-array\\\",render:E((r,l,a)=>{let s=Bt(l)?[]:l;if(!Array.isArray(s))return!1;let o=r.element,u=r.arrayTemplate;if(void 0===u||0===u.length)return function(e,t,n){e.has(t)||(e.add(t),si(`[live-preview] LP0403: Skipping structural update for \\\"${n}\\\": <${t.tagName.toLowerCase()} data-payload-structural> needs data-payload-array-template (for example \\\"<li>{{label}}</li>\\\").`))}(t,o,r.fieldName),!1;let d=e.get(o),c=Gn(o),h=d?.values??function(e){return e.map((e,t)=>null===e?{__payloadDomPosition:t}:{id:e})}(c),f=R(h,s),p=function(e,t,n){return void 0===e||e.template!==t||!function(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}(e.domSnapshot,n)}(d,u,c);if(0===f.length&&!p)return e.set(o,{values:s.slice(),template:u,domSnapshot:c}),!1;!function(e,t,n,i,r){let l=r.map(Kn),a=new Set,s=l.find(e=>!(void 0===e||!a.has(e)&&(a.add(e),1)));if(void 0!==s&&Jn(e,t,n,s),l.some(e=>void 0===e)&&Xn(e,t,\\\"LP0404\\\",`LP0404: an item of \\\"${n}\\\" has no id and pairs by position, so an insert re-renders every row after it. Give items a stable id.`),i?.length===r.length&&r.length>1){let r=new Set(i.map(Kn).filter(e=>void 0!==e)),a=l.some(e=>void 0!==e&&r.has(e));r.size>0&&!a&&Xn(e,t,\\\"LP0406\\\",`LP0406: every key of \\\"${n}\\\" changed at once; the source generates ids per message, so no item can be retained across updates.`)}}(n,o,r.fieldName,d?.values,s);let g=Vt({template:u,container:o,patches:f,nextItems:s,store:i,forceRender:p,sanitizerPolicy:a.sanitizerPolicy,onDuplicateKey:(e,t)=>{Jn(n,e,r.fieldName,t)}});return null!==g&&(e.set(o,{values:s.slice(),template:u,domSnapshot:Gn(o)}),!!g&&void 0)})}}function Gn(e){return Array.from(e.children,e=>e.getAttribute(ta))}function Kn(e){if(\\\"object\\\"!=typeof e||null===e)return;let t=e.id;return\\\"string\\\"==typeof t||\\\"number\\\"==typeof t?String(t):void 0}function Jn(e,t,n,i){Xn(e,t,\\\"LP0405\\\",`LP0405: two items of \\\"${n}\\\" share the key \\\"${i}\\\"; later ones pair by position. Make \\\\`id\\\\` unique per item.`)}function Xn(e,t,n,i){let r=e.get(t);void 0===r&&(r=new Set,e.set(t,r)),!r.has(n)&&(r.add(n),si(`[live-preview] ${i}`))}function Qn(){return typeof __LIVE_PREVIEW_CONFIG__>\\\"u\\\"?[]:__LIVE_PREVIEW_CONFIG__}var Zn=Object.defineProperty,Yn=e=>{throw TypeError(e)},ei=(e,t,n)=>((e,t,n)=>t in e?Zn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,\\\"symbol\\\"!=typeof t?t+\\\"\\\":t,n),ti=(e,t,n)=>t.has(e)||Yn(\\\"Cannot \\\"+n),ni=(e,t,n)=>(ti(e,t,\\\"read from private field\\\"),n?n.call(e):t.get(e)),ii=(e,t,n)=>t.has(e)?Yn(\\\"Cannot add the same private member more than once\\\"):t instanceof WeakSet?t.add(e):t.set(e,n),ri=(e,t,n,i)=>(ti(e,t,\\\"write to private field\\\"),i?i.call(e,n):t.set(e,n),n),li=(e,t,n)=>(ti(e,t,\\\"access private method\\\"),n),ai=t((...e)=>console.error(...e)),si=t((...e)=>console.warn(...e)),oi=t((...e)=>console.debug(...e)),ui=class{constructor(){ii(this,hi);ii(this,di,new Map);ii(this,ci,new Map)}on(e,t){return li(this,hi,pi).call(this,ni(this,di),e,t)}once(e,t){return li(this,hi,pi).call(this,ni(this,ci),e,t)}off(e,t){li(this,hi,gi).call(this,ni(this,di),e,t),li(this,hi,gi).call(this,ni(this,ci),e,t)}async emit(e,t){await li(this,hi,fi).call(this,e,t)}async emitWhile(e,t,n){return li(this,hi,fi).call(this,e,t,n)}listenerCount(e){return(ni(this,di).get(e)?.size??0)+(ni(this,ci).get(e)?.size??0)}removeAllListeners(e){void 0!==e?(ni(this,di).delete(e),ni(this,ci).delete(e)):(ni(this,di).clear(),ni(this,ci).clear())}eventNames(){let e=new Set;for(let t of ni(this,di).keys())e.add(t);for(let t of ni(this,ci).keys())e.add(t);return[...e]}},di=new WeakMap,ci=new WeakMap,hi=new WeakSet,fi=async function(e,t,n){let i=()=>n?.()??!0;if(!i())return!1;let r=ni(this,di).get(e);if(r)for(let n of[...r])if(!i()||(await li(this,hi,mi).call(this,n,t,e),!i()))return!1;if(!i())return!1;let l=ni(this,ci).get(e);if(l&&l.size>0){let n=[...l];ni(this,ci).delete(e);for(let r of n)if(!i()||(await li(this,hi,mi).call(this,r,t,e),!i()))return!1}return i()},pi=function(e,t,n){let i=e.get(t);return i||(i=new Set,e.set(t,i)),i.add(n),()=>{li(this,hi,gi).call(this,e,t,n)}},gi=function(e,t,n){let i=e.get(t);void 0!==i&&(i.delete(n),0===i.size&&e.delete(t))},mi=async function(e,t,n){try{await e(t)}catch(e){let t=\\\"string\\\"==typeof n||\\\"number\\\"==typeof n?String(n):\\\"<event>\\\";ai(`[live-preview] LP0601: handler for \\\"${t}\\\" threw:`,e)}},vi=new Set([\\\"date\\\",\\\"number\\\",\\\"checkbox\\\"]),yi=40,bi=\\\"payload-live-preview-a11y\\\",wi=new WeakMap,Si=class{constructor(e,t){ei(this,\\\"german\\\");ei(this,\\\"document\\\");ei(this,\\\"lease\\\",null);let n=t??(typ\",\"eof document>\\\"u\\\"?null:document),i=n?.documentElement.getAttribute(\\\"lang\\\")??\\\"\\\";this.german=function(e){return/^de(?:[-_]|$)/i.test(e)}(e??(i.length>0?i:o())),this.document=n}mount(){let e=this.document;if(null==e?.body)return null;this.lease??(this.lease=function(e){let t=wi.get(e);return void 0===t&&(t={element:null,owned:!1,messageNode:null,refs:0,timer:null},wi.set(e,t)),t.refs+=1,t}(e));let t=this.lease,n=t.element;if(n?.isConnected&&n.ownerDocument===e)return n;if(null!==n){let e=t.owned;u(t),e&&n.remove()}let i=e.getElementById(bi);return t.owned=null===i,null===i&&(i=e.createElement(\\\"div\\\"),i.id=bi,i.setAttribute(\\\"role\\\",\\\"status\\\"),i.setAttribute(\\\"aria-live\\\",\\\"polite\\\"),i.setAttribute(\\\"aria-atomic\\\",\\\"true\\\"),i.style.cssText=\\\"position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap;border:0\\\",e.body.appendChild(i)),t.element=i,i}announceConnected(){this.say(this.german?\\\"Vorschau verbunden\\\":\\\"Live preview connected\\\")}announceDisconnected(){this.say(this.german?\\\"Vorschau getrennt\\\":\\\"Live preview disconnected\\\")}announceUpdate(e){e<=0||this.say(this.german?`${String(e)} ${1===e?\\\"\\\\xc4nderung\\\":\\\"\\\\xc4nderungen\\\"} angewendet`:`${String(e)} ${1===e?\\\"change\\\":\\\"changes\\\"} applied`)}announcePartial(){this.say(this.german?\\\"Vorschau teilweise aktualisiert\\\":\\\"Preview partly updated\\\")}detach(){let e=this.lease,t=this.document;if(null===e||null===t||(this.lease=null,e.refs-=1,e.refs>0))return;let n=e.element;null!==n&&u(e),e.owned&&n?.remove(),e.element=null,wi.delete(t)}say(e){let t=this.mount(),n=this.lease;if(null===t||null===n)return;let i=n.messageNode;i?.parentNode!==t?(i?.remove(),i=t.ownerDocument.createTextNode(t.hasChildNodes()?` ${e}`:e),n.messageNode=i,t.appendChild(i)):i.data=null===i.previousSibling?e:` ${e}`,null!==n.timer&&clearTimeout(n.timer);let r=setTimeout(()=>{n.timer===r&&n.element===t&&u(n)},1500);n.timer=r}},Ai=[\\\"data\\\",\\\"fieldSchemaJSON\\\",\\\"globalSlug\\\",\\\"collectionSlug\\\",\\\"locale\\\",\\\"ready\\\",\\\"previewToken\\\",\\\"protocolVersion\\\"],ki={basic:{since:1},\\\"schema-json\\\":{since:2,observed:\\\"schema\\\"},locale:{since:2,observed:\\\"locale\\\"},\\\"preview-token\\\":{since:3,observed:\\\"preview-token\\\"},\\\"nested-arrays\\\":{since:4},\\\"recursive-diffs\\\":{since:4},\\\"document-events\\\":{since:4,observed:\\\"document-event\\\"},\\\"relationship-events\\\":{since:4,observed:\\\"relationship-event\\\"}},Ti=Object.keys(ki),Ci=class{constructor(e,t){ei(this,\\\"matcher\\\");ei(this,\\\"handlers\\\");ei(this,\\\"boundListener\\\");ei(this,\\\"attachedTarget\\\");ei(this,\\\"generation\\\",0);ei(this,\\\"revision\\\",0);ei(this,\\\"queueHead\\\");ei(this,\\\"queueTail\\\");ei(this,\\\"lastAccepted\\\");ei(this,\\\"replayedGeneration\\\",0);ei(this,\\\"latestAcceptedAttempt\\\");this.matcher=e,this.handlers=t}attach(e=window){if(void 0!==this.attachedTarget)return;let t=!1,n=i=>{if(!t||this.boundListener!==n)return;let r=this.generation;try{this.receive(i,r,e)}catch{let e;try{e=i.origin}catch{e=\\\"\\\"}this.reportInvalid(\\\"shape\\\",e,r)}};this.generation+=1,this.resetQueue(),this.attachedTarget=e,this.boundListener=n;try{e.addEventListener(\\\"message\\\",n)}catch(t){this.boundListener===n&&(this.attachedTarget=void 0,this.boundListener=void 0,this.resetQueue());try{e.removeEventListener(\\\"message\\\",n)}catch{}throw t}if(this.boundListener===n)t=!0;else try{e.removeEventListener(\\\"message\\\",n)}catch{}}detach(){let e=this.attachedTarget,t=this.boundListener;void 0===e||void 0===t||(this.attachedTarget=void 0,this.boundListener=void 0,this.resetQueue(),e.removeEventListener(\\\"message\\\",t))}advanceGeneration(){return void 0!==this.attachedTarget&&(this.generation+=1,this.resetQueue(),!0)}replayLastAccepted(){let e=this.lastAccepted,t=this.generation,n=this.handlers.onReplay;if(void 0===n||void 0===e||e.generation>=t||this.replayedGeneration===t||!this.matchesOrigin(e.origin,t)||this.lastAccepted!==e)return!1;this.replayedGeneration=t;let i={generation:t,revision:this.revision+=1};return this.invokeHandler(t,n,structuredClone(e.message),e.origin,i),!0}forgetLastAccepted(){this.lastAccepted=void 0,this.replayedGeneration=0,this.latestAcceptedAttempt=void 0}static sendReady(e,t){let n={type:\\\"payload-live-preview\\\",ready:!0,protocolVersion:4};for(let i of e)for(let e of t)try{i.postMessage(n,e)}catch{}}receive(e,t,n){let i=e.origin;if(!this.matchesOrigin(i,t)){this.reportInvalid(\\\"origin\\\",i,t);return}if(!this.matchesSource(e,n)){this.reportInvalid(\\\"source\\\",i,t);return}let r=e.data;if(function(e){return\\\"object\\\"==typeof e&&null!==e&&\\\"type\\\"in e&&\\\"string\\\"==typeof e.type}(r))switch(r.type){case\\\"payload-live-preview\\\":if(!function(e){let t=e;return!(void 0!==t.data&&null!==t.data&&!v(t.data))&&m(t.fieldSchemaJSON,e=>Array.isArray(e))&&m(t.globalSlug,e=>\\\"string\\\"==typeof e)&&m(t.collectionSlug,e=>\\\"string\\\"==typeof e)&&m(t.locale,e=>\\\"string\\\"==typeof e)&&m(t.ready,e=>\\\"boolean\\\"==typeof e)&&m(t.previewToken,e=>\\\"string\\\"==typeof e)&&m(t.protocolVersion,e=>\\\"number\\\"==typeof e)}(r)){this.reportInvalid(\\\"shape\\\",i,t);return}this.dispatchUpdate(function(e){let t={...e};for(let e of Ai)null===Reflect.get(t,e)&&Reflect.deleteProperty(t,e);return Array.isArray(t.fieldSchemaJSON)?{...t,fieldSchemaJSON:h(t.fieldSchemaJSON)}:t}(r),i,t);return;case\\\"payload-document-event\\\":if(!function(e){let t=e;return g(t.action,e=>\\\"updated\\\"===e||\\\"created\\\"===e||\\\"deleted\\\"===e)&&g(t.slug,e=>\\\"string\\\"==typeof e)&&g(t.id,e=>\\\"string\\\"==typeof e||Number.isFinite(e))}(r)){this.reportInvalid(\\\"shape\\\",i,t);return}this.invokeHandler(t,this.handlers.onDocumentEvent,r,i);return;case\\\"payload-live-preview-focus\\\":{let e=function(e){let t=e.field;return\\\"string\\\"==typeof t&&t.length>0?t:void 0}(r);if(void 0===e){this.reportInvalid(\\\"shape\\\",i,t);return}this.invokeHandler(t,this.handlers.onFocusField,e,i);return}default:this.reportInvalid(\\\"type\\\",i,t)}else this.reportInvalid(\\\"shape\\\",i,t)}dispatchUpdate(e,t,n){let i=v(e.data);if(!this.isCurrentGeneration(n))return;let r=i?{generation:n,revision:this.revision+=1}:void 0,l=this.handlers.validateToken;if(!this.isCurrentGeneration(n))return;if(void 0===l){this.commitUpdate(e,t,n,r);return}if(!0===e.ready&&void 0===e.data){this.commitUpdate(e,t,n,void 0);return}let a={generation:n,message:e,origin:t,messageRevision:r,verdict:void 0,next:void 0};this.enqueue(a);let s;try{s=l(e.previewToken,t)}catch{this.settleValidation(a,!1);return}\\\"boolean\\\"!=typeof s?Promise.resolve(s).then(e=>{this.settleValidation(a,!0===e)},()=>{this.settleValidation(a,!1)}):this.settleValidation(a,s)}settleValidation(e,t){e.verdict=t,this.drainQueue(e.generation)}drainQueue(e){for(;this.isCurrentGeneration(e);){let t=this.queueHead;if(void 0===t)return;if(this.matchesOrigin(t.origin,e)){if(void 0===t.verdict)return;this.dequeue(t)&&(t.verdict?this.commitUpdate(t.message,t.origin,t.generation,t.messageRevision):this.reportInvalid(\\\"token\\\",t.origin,t.generation))}else{if(!this.dequeue(t))continue;this.reportInvalid(\\\"origin\\\",t.origin,t.generation)}}}commitUpdate(e,t,n,i){if(void 0===i)this.invokeHandler(n,this.handlers.onUpdate,e,t);else{let r={};this.latestAcceptedAttempt=r;let l=function(e){let t={...e};delete t.previewToken;try{return structuredClone(t)}catch{return null}}(e);if(this.latestAcceptedAttempt!==r||!this.isCurrentGeneration(n))return;this.lastAccepted=null===l?void 0:{generation:n,message:l,origin:t},this.invokeHandler(n,this.handlers.onUpdate,e,t,i)}}reportInvalid(e,t,n){this.invokeHandler(n,this.handlers.onInvalid,e,t)}matchesSource(e,t){if(\\\"parent-or-opener\\\"!==this.handlers.sourcePolicy)return!0;try{let n=e.source;if(\\\"object\\\"!=typeof n||null===n)return!1;let i=t.parent;return i!==t&&n===i||n===t.opener}catch{return!1}}matchesOrigin(e,t){try{return!0===(this.isCurrentGeneration(t)&&this.matcher(e))&&this.isCurrentGeneration(t)}catch{return!1}}invokeHandler(t,n,...i){if(void 0!==n&&this.isCurrentGeneration(t))try{e(n(...i))}catch{}}isCurrentGeneration(e){return void 0!==this.attachedTarget&&this.generation===e}enqueue(e){void 0===this.queueTail?this.queueHead=e:this.queueTail.next=e,this.queueTail=e}dequeue(e){return this.queueHead===e&&(this.queueHead=e.next,void 0===this.queueHead&&(this.queueTail=void 0),!0)}resetQueue(){this.queueHead=void 0,this.queueTail=void 0}},Ri=new Set([\\\"tabs\\\",\\\"row\\\",\\\"collapsible\\\"]),$i={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\\\"},Fi=new Set([\\\"http:\\\",\\\"https:\\\",\\\"mailto:\\\",\\\"tel:\\\"]),Ni=/^(?:\\\\.{1,2}\\\\/|[a-zA-Z0-9_-]+\\\\/?)/,Mi=/^[\\\\\\\\/]{2}/,Ei=/[\\\\t\\\\n\\\\r]/g,Oi=/[\\\\s\\\\u0000-\\\\u001f\\\\u180e\\\\u2000-\\\\u2029]/g,Li=/^([a-z][a-z0-9+.-]*):/i,xi=new Set([\\\"style\\\",\\\"srcdoc\\\",\\\"formaction\\\",\\\"form\\\",\\\"id\\\",\\\"name\\\",\\\"is\\\",\\\"srcset\\\",\\\"imagesrcset\\\"]),Pi=new Set([\\\"href\\\",\\\"src\\\",\\\"poster\\\",\\\"cite\\\",\\\"action\\\",\\\"xlink:href\\\",\\\"data\\\"]),Ui=new WeakSet,Ii=class{constructor(){ei(this,\\\"previous\\\",null);ei(this,\\\"lastFields\\\");ei(this,\\\"priorFields\\\");ei(this,\\\"keepValues\\\",!1)}get previousFields(){return this.priorFields}get isBaseline(){return null===this.previous}diff(e,t,n=L){let i=this.previous,r=null===i,l=new Map,a=new Set,s=Object.entries(e);if(!n())return null;for(let[e,t]of s){let r=O(t);if(!n())return null;l.set(e,r),(null===i||void 0===r||i.get(e)!==r)&&a.add(e)}if(null!==i)for(let e of i.keys())l.has(e)||a.add(e);let o=new Set,u=Object.entries(t);if(!n())return null;for(let[e,t]of u)if(a.has(e))for(let e of t)if(o.add(e),!n())return null;return n()?(this.previous=l,this.priorFields=this.keepValues?this.lastFields:void 0,this.lastFields=this.keepValues?e:void 0,{changed:a,invalidated:o,baseline:r}):null}reset(){this.previous=null,this.lastFields=void 0,this.priorFields=void 0}},ji=\\\"data-payload-fragment\\\",Wi=\\\"data-payload-fragment-key\\\",Bi=\\\"data-payload-strategy\\\",Di=8,_i=1024,zi=new Set([\\\"id\\\",\\\"_id\\\",\\\"createdAt\\\",\\\"updatedAt\\\",\\\"createdBy\\\",\\\"updatedBy\\\",\\\"_status\\\",\\\"globalType\\\",\\\"collection\\\",\\\"locale\\\",\\\"localized\\\"]),Vi=new Set([\\\"text\\\",\\\"textarea\\\",\\\"email\\\",\\\"number\\\",\\\"checkbox\\\",\\\"date\\\",\\\"select\\\",\\\"radio\\\",\\\"point\\\",\\\"code\\\",\\\"json\\\",\\\"ui\\\",\\\"html\\\"]),qi={},Hi=class{constructor(){ei(this,\\\"rawChanges\\\",new Ii);ei(this,\\\"resolved\\\",null);ei(this,\\\"resolvedLocale\\\",null);ei(this,\\\"trailing\\\",null);ei(this,\\\"openUntil\\\",0);ei(this,\\\"requestAttempt\\\",0)}decide(e,t){let n=t.rawData;if(!function(e){let{cache:t,emitter:n}=e;if(t.islands.length>0||n.listenerCount(\\\"beforeUpdate\\\")>0||n.listenerCount(\\\"afterUpdate\\\")>0)return!0;for(let e of t.values())if(J(e)||e.fieldName.includes(\\\".\\\")||Q(e.hrefField)||Q(e.srcField)||Q(e.altField))return!0;return void 0!==e.strategies.fragment&&null!==e.root.querySelector(`[${ji}]`)}(e))return t.forceRender&&(this.resolvedLocale=null),{merge:!1,fields:n};let{changed:i}=this.rawChanges.diff(n,qi),r=this.resolvedLocale!==t.locale,l=this.resolved;if(null===l)return this.resolved=n,{merge:!0,fields:n};let a={...l};t.forceRender&&(this.resolvedLocale=null);let s=t.forceRender||r;for(let r of i){let i=n[r];if(zi.has(r)){a[r]=i;continue}let o=K(r,l[r],i,e.cache,t.schemaIndex);\\\"own\\\"!==o&&(s=!0,this.resolvedLocale=null),\\\"keep\\\"!==o&&(a[r]=i)}return this.resolved=a,{merge:s,fields:a}}request(e,t,n){let i=++this.requestAttempt,r=Date.now();if(r>=this.openUntil)return this.openUntil=r+t,this.dropQueued(),this.requestAttempt!==i?{leading:!0,result:Promise.resolve({status:\\\"superseded\\\"})}:{leading:!0,result:e.merge(n)};let l=this.trailing,a=l?.pending??function(){let e;return{promise:new Promise(t=>{e=t}),settle:e}}(),s={request:n,pending:a,timer:null};if(this.trailing=s,this.openUntil=r+t,null!==l&&null!==l.timer&&clearTimeout(l.timer),this.trailing!==s)return{leading:!1,result:a.promise};let o=setTimeout(()=>{this.flush(e,s)},t);return this.trailing===s?s.timer=o:clearTimeout(o),{leading:!1,result:a.promise}}recordMerged(e,t){this.resolved=e,this.resolvedLocale=t}resetRawChanges(){this.rawChanges.reset()}destroy(){this.requestAttempt+=1,this.openUntil=0,this.dropQueued()}dropQueued(){let e=this.trailing;this.trailing=null,null!==e&&(null!==e.timer&&clearTimeout(e.timer),e.pending.settle({status:\\\"superseded\\\"}))}flush(e,t){this.trailing===t&&(this.trailing=null,t.timer=null,e.merge(t.request).then(t.pending.settle))}},Gi=class{constructor(){ei(this,\\\"negotiation\\\",y(void 0));ei(this,\\\"observed\\\",new Set)}observe(e,t){let n=e.filter(e=>!this.observed.has(e));if(0!==n.length){for(let e of n)this.observed.add(e);this.negotiation=y(this.negotiation.theirs,this.observed),t(\\\"protocol\\\",`observed=${n.join(\\\",\\\")}`)}}applyVersion(e,t){let n=this.negotiation;if(n.theirs===e)return;let i=y(e,this.observed);this.negotiation=i,i.negotiated!==n.negotiated&&t(\\\"protocol\\\",\\\"ours=4\\\",`theirs=${e}`,`negotiated=${i.negotiated}`)}},Ki=class{constructor(){ei(this,\\\"lastIdentity\\\")}inspect(e){let t=e.externallyUpdatedRelationship;if(\\\"object\\\"!=typeof t||null===t)return null;let n=JSON.stringify([t.entitySlug,B(t),t.updatedAt]);return{identity:n,edit:n!==this.lastIdentity&&Z(t,e)?t:null}}commit(e){let t=e.identity!==this.lastIdentity;return this.lastIdentity=e.identity,t?e.edit:null}},Ji=class{constructor(){ii(this,Xi)}reveal(e,t,n){return e===ni(this,Xi)?\\\"skipped-same\\\":(ri(this,Xi,e),function(e,t){return function(e,t){let n=e.getBoundingClientRect(),i=n.bottom>0&&n.top<t.innerHeight,r=n.right>0&&n.left<t.innerWidth;return i&&r}(e,t)?\\\"already-visible\\\":(e.scrollIntoView({behavior:ee(t)?\\\"auto\\\":\\\"smooth\\\",block:\\\"center\\\"}),\\\"revealed\\\")}(t,n))}reset(){ri(this,Xi,void 0)}},Xi=new WeakMap,Qi=class{constructor(){ei(this,\\\"seen\\\",new Map)}note(e,t,n){let i=O(n);if(void 0===i)return;let r=`${t.owner??\\\"\\\"}\\\\0${t.locale??\\\"\\\"}\\\\0${t.fieldName}`,l=this.seen.get(r);void 0!==l?l!==i&&(e.revealIdentities.push([r,i]),e.revealTarget??(e.revealTarget=t)):this.seen.set(r,i)}commit(e){for(let[t,n]of e.revealIdentities)this.seen.set(t,n);e.revealIdentities=[];let t=e.revealTarget;return e.revealTarget=void 0,t}},Zi=()=>{},Yi=class{constructor(){ei(this,\\\"host\\\",{outstanding:()=>!1,report:Zi,failed:Zi});ei(this,\\\"entry\\\",null);ei(this,\\\"ended\\\")}begin(e,t){let n=this.entry,i=null===n?void 0:this.view(n);null!==n&&(n.key=void 0),this.ended=void 0,this.entry={key:e,revision:t,shortfalls:[],seen:new Set,deferred:0,awaiting:0,reported:void 0,queued:!1},null!==n&&void 0!==i&&this.publish(n,\\\"pending\\\"===i.state?{...i,state:\\\"superseded\\\"}:i)}end(){let e=this.entry;if(null!==e){this.entry=null;try{this.ended=this.view(e)}finally{e.key=void 0}}}snapshot(){return null!==this.entry?this.view(this.entry):void 0===this.ended?void 0:{...this.ended,shortfalls:[...this.ended.shortfalls]}}shortfall(e,t){let n=this.entry;if(n?.key!==e)return;let i=JSON.stringify(t);n.seen.has(i)||(n.seen.add(i),n.shortfalls.push(t),this.requestSettle(n.key))}deferred(e,t){this.entry?.key===e&&(this.entry.deferred=t)}handIsland(e){let t=this.entry;if(t?.key!==e)return Zi;t.awaiting+=1;let n=!1;return()=>{n||this.entry!==t||(n=!0,t.awaiting-=1,this.settle(t))}}requestSettle(e){let t=this.entry;t?.key!==e||t.queued||(t.queued=!0,queueMicrotask(()=>{t.queued=!1;try{this.entry===t&&this.settle(t)}catch(e){this.host.failed(e)}}))}settle(e){let t=this.view(e);\\\"pending\\\"!==t.state&&this.publish(e,t)}publish(e,t){e.reported!==t.state&&(e.reported=t.state,this.host.report(t))}view(e){let t=void 0!==e.key&&this.host.outstanding(e.key)?\\\"pending\\\":e.shortfalls.length>0?\\\"partial\\\":e.awaiting>0?\\\"unconfirmed\\\":\\\"current\\\";return{revision:e.revision,state:t,shortfalls:[...e.shortfalls],deferred:e.deferred,awaitingIslands:e.awaiting}}},er=class{constructor(){ei(this,\\\"started\\\",!1);ei(this,\\\"suspended\\\",!1);ei(this,\\\"deferredStart\\\",null);ei(this,\\\"hydration\\\",\\\"idle\\\");ei(this,\\\"activeUpdate\\\",null);ei(this,\\\"locale\\\");ei(this,\\\"schema\\\");ei(this,\\\"schemaIndex\\\");ei(this,\\\"updateCount\\\",0);ei(this,\\\"supersededCount\\\",0);ei(this,\\\"completedCount\\\",0);ei(this,\\\"skippedUnchangedCount\\\",0);ei(this,\\\"lastFlush\\\",null);ei(this,\\\"absentFields\\\",new Set);ei(this,\\\"warnedOrphanFields\\\",new Set);ei(this,\\\"warnedStrategy\\\",new WeakSet);ei(this,\\\"warnedUnattributableMessage\\\",!1);ei(this,\\\"warnedVisibilityGate\\\",!1);ei(this,\\\"warnedFragmentFallback\\\",!1);ei(this,\\\"warnedIslandStart\\\",!1);ei(this,\\\"warnedEscalationUnavailable\\\",!1);ei(this,\\\"warnedProtocolShape\\\",!1);ei(this,\\\"reportedUnfaithful\\\",new WeakSet);ei(this,\\\"checkedServerFormat\\\",new WeakSet);ei(this,\\\"unfaithfulPatches\\\",[]);ei(this,\\\"unfaithfulCount\\\",0);ei(this,\\\"escalatedCount\\\",0);ei(this,\\\"unfaithfulFields\\\",new Set);ei(this,\\\"autoBindSearchMs\\\");ei(this,\\\"autoBindGuesses\\\",null);ei(this,\\\"warnedForeignSource\\\",!1);ei(this,\\\"lastAppliedIdentity\\\",new WeakMap);ei(this,\\\"navigationReplayPending\\\",!1);ei(this,\\\"navigationBindingReplay\\\",!1);ei(this,\\\"revealLedger\\\",new Qi);ei(this,\\\"display\\\",new Yi);ei(this,\\\"fragmentStats\\\",{rendered:0,failed:0,superseded:0});ei(this,\\\"routeStats\\\",{refreshes:0,partial:0,failed:0,refused:0,loopStopped:0});ei(this,\\\"fragmentControllers\\\",new Map);ei(this,\\\"routeController\\\",null);ei(this,\\\"routeRetry\\\",null);ei(this,\\\"routeRefreshOwed\\\",!1);ei(this,\\\"fragmentsOwed\\\",new Set);ei(this,\\\"readyTimers\\\",[]);ei(this,\\\"revealer\\\",new Ji);ei(this,\\\"changes\\\",new Ii);ei(this,\\\"merges\\\",new Hi);ei(this,\\\"protocol\\\",new Gi);ei(this,\\\"relationships\\\",new Ki)}isRunning(){return this.started}isCurrent(e){return this.started&&this.activeUpdate===e}complete(e){this.display.requestSettle(e),!e.completed&&(e.completed=!0,e.countsAsUpdate&&(this.completedCount+=1))}forgetOwedWork(){this.routeRefreshOwed=!1,this.fragmentsOwed.clear()}supersedeStrategies(){null!==this.routeRetry&&(clearTimeout(this.routeRetry),this.routeRetry=null,this.routeRefreshOwed=!0);for(let[e,t]of this.fragmentControllers){for(let e of t)this.fragmentsOwed.add(e);e.abort()}this.fragmentControllers.clear()}abortStrategies(){this.supersedeStrategies();let e=this.routeController;this.routeController=null,e?.abort()}},tr=class{constructor(e,t){ei(this,\\\"deps\\\",e);ei(this,\\\"state\\\",t);ei(this,\\\"instanceContext\\\");this.instanceContext=function(e){let t={};for(let[n,i]of Object.entries(e))void 0!==i&&(t[n]=i);return t}({renderRichText:e.renderRichText,sanitizerPolicy:e.sanitizerPolicy,serverURL:e.serverURL,reportUnfaithful:(n,i)=>{r(e,t,n,i)}})}apply(e){let{deps:t,state:n}=this,i=n.activeUpdate;if(null===i||void 0===e.revision||!b(i.revision,e.revision)||!n.isCurrent(i))return!1;let{target:l,value:o}=e,u=void 0!==i.schemaIndex?k(i.schemaIndex,l.fieldName):void 0,d=function(e,t){if(e.explicitFieldType)return e.fieldType;if(void 0!==t){let e=function(e){if(Object.prototype.hasOwnProperty.call($i,e))return $i[e]}(t);if(void 0!==e)return e}return e.fieldType}(l,u?.type);\\\"text\\\"===d&&!0!==l.explicitFieldType&&function(e){if(\\\"object\\\"!=typeof e||null===e||!(\\\"root\\\"in e))return!1;let t=e.root;return\\\"object\\\"==typeof t&&null!==t&&Array.isArray(t.children)}(o)&&(d=\\\"richText\\\");let c;try{c=t.resolveRenderer(d,l)}catch(e){return this.fail(i,l.fieldName,e)}if(!n.isCurrent(i))return!1;let h=t.emitter.listenerCount(\\\"elementUpdate\\\")>0,f=h?function(e){return\\\"INPUT\\\"===e.tagName||\\\"TEXTAREA\\\"===e.tagName?e.value:\\\"IMG\\\"===e.tagName?e.src:e.textContent}(l.element):void 0;if(!n.isCurrent(i))return!1;let p={allFields:e.allFields,locale:l.locale??i.locale,schema:u,...this.instanceContext};!0===l.hidesWhenEmpty&&l.element.toggleAttribute(\\\"hidden\\\",function(e){return null==e||(\\\"string\\\"==typeof e?0===e.trim().length:Array.isArray(e)&&0===e.length)}(o));try{if(void 0!==l.targetAttribute){if(\\\"blocked\\\"===function(e,t,n){let i=t.toLowerCase().trim();if(0===i.length||!M(i))return\\\"blocked\\\";if(null==n)return e.removeAttribute(i),\\\"applied\\\";if(\\\"string\\\"!=typeof n&&\\\"number\\\"!=typeof n&&\\\"boolean\\\"!=typeof n)return\\\"blocked\\\";let r=String(n);return Pi.has(i)&&!F(r)?\\\"blocked\\\":(e.setAttribute(i,r),\\\"applied\\\")}(l.element,l.targetAttribute,o))return t.warn(`[live-preview] LP0401: refused to write \\\"${l.fieldName}\\\" into attribute \\\"${l.targetAttribute}\\\"`),n.display.shortfall(i,{kind:\\\"write\\\",field:l.fieldName,code:\\\"LP0401\\\"}),!1}else{if(void 0===c)return t.log(\\\"no renderer for\\\",d),r(t,n,l,`has no renderer for \\\"${d}\\\"`),!1;{let e=function(e,t,n,i){if(\\\"ignore\\\"===e.onUnfaithfulPatch||void 0!==n.format||!vi.has(i)||t.checkedServerFormat.has(n.element))return;t.checkedServerFormat.add(n.element);let r=a(n.element);return r.trim().length>0?r:void 0}(t,n,l,d);if(!1===function(e,t,n,i){return e.render(t,n,i)}(c,l,o,p)&&function(e){return Ui.has(e.render)}(c))return r(t,n,l,`is a value ${c.name} cannot render`),!1;void 0!==e&&function(e,t,n){let i=a(t.element);i!==n&&e.warn(`[live-preview] LP0412: \\\"${t.fieldName}\\\" showed ${s(n)}, the patch wrote ${s(i)} \\\\u2014 either an edit that arrived before the preview connected, or a template that formats this value differently. Set data-payload-format to match it.`)}(t,l,e)}}}catch(e){return this.fail(i,l.fieldName,e)}if(!n.isCurrent(i))return!1;h&&t.emitter.emitWhile(\\\"elementUpdate\\\",{element:l.element,fieldName:l.fieldName,previousValue:f,nextValue:o,revision:i.revision.revision,receivedAt:i.receivedAt,source:\\\"patch\\\"},()=>n.isCurrent(i));let g=n.isCurrent(i);return g&&(void 0!==e.valueIdentity?n.lastAppliedIdentity.set(l.element,e.valueIdentity):n.lastAppliedIdentity.delete(l.element)),g}fail(e,t,n){if(!this.state.isCurrent(e))return!1;this.state.display.shortfall(e,{kind:\\\"write\\\",field:t,code:\\\"LP0603\\\"});let i=n instanceof Error?n:new Error(String(n));return this.deps.emitter.emitWhile(\\\"error\\\",{error:i,context:\\\"renderer\\\",code:\\\"LP0603\\\"},()=>this.state.isCurrent(e)),!1}},nr=\\\"payload-live-preview:update\\\",ir=\\\"data-payload-island\\\",rr=`astro-island, [${ir}]`,lr=\\\"data-payload-owned\\\",ar=\\\"data-payload-morph\\\",sr=[\\\"component-url\\\",\\\"component-export\\\",\\\"renderer-url\\\",\\\"client\\\",\\\"opts\\\",\\\"before-hydration-url\\\"],or=new WeakMap,ur=new WeakSet,dr=\\\"data-payload-field\\\",cr=\\\"data-payload-type\\\",hr=\\\"data-payload-attribute\\\",fr=\\\"data-payload-href\\\",pr=\\\"data-payload-src\\\",gr=\\\"data-payload-alt\\\",mr=\\\"data-payload-array-template\\\",vr=\\\"data-payload-array-separator\\\",yr=\\\"data-payload-locale\\\",br=\\\"data-payload-richtext\\\",wr=\\\"data-payload-html\\\",Sr=\\\"data-payload-array\\\",Ar=\\\"data-payload-structural\\\",kr=\\\"data-payload-owner\\\",Tr=\\\"data-payload-depends\\\",Cr=\\\"data-payload-strategy\\\",Rr=\\\"data-payload-boundary\\\",$r=\\\"data-payload-guessed\\\",Fr=\\\"data-payload-covers\\\",Nr=[dr,cr,hr,fr,pr,gr,mr,vr,yr,br,wr,Sr,Ar,kr,Tr,Cr,Rr,\\\"type\\\"],Mr=`[${dr}]`,Er=`[${kr}]`,Or=`[${ji}], [${Cr}=\\\"route\\\"]`,Lr=/^[a-z][a-z0-9-]*:[a-z][a-z0-9-]*$/i,xr=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\\\"]),Pr=class{constructor(e={}){ei(this,\\\"entriesByField\\\",new Map);ei(this,\\\"entryByElement\\\",new WeakMap);ei(this,\\\"filter\\\");ei(this,\\\"count\\\",0);ei(this,\\\"dependencies\\\",null);ei(this,\\\"islandRoots\\\",[]);ei(this,\\\"ownersByIsland\\\",new Map);ei(this,\\\"navigationRoots\\\",[]);ei(this,\\\"coverDeclarations\\\",[]);ei(this,\\\"renderedDeclarations\\\",[]);this.filter=e.filter??be}dependencyMap(){if(null!==this.dependencies)return this.dependencies;let e=[];for(let t of this.values())void 0!==t.dependsOn&&e.push(le(t.fieldName,t.dependsOn));return this.dependencies=re(...e),this.dependencies}get islands(){return this.islandRoots}get islandOwners(){return this.ownersByIsland}get covers(){return this.coverDeclarations}get rendered(){return this.renderedDeclarations}get navigationReplayRoots(){return this.navigationRoots}buildFromRoot(e){let t=performance.now();this.clear();let n=0;for(let t of e.querySelectorAll(Mr))void 0!==this.add(t)&&(n+=1);return this.islandRoots=function(e){let t=[];for(let n of e.querySelectorAll(rr))se(n)||t.push(n);return t}(e),this.ownersByIsland=new Map(this.islandRoots.map(e=>[e,ge(e)])),this.navigationRoots=[...e.querySelectorAll(Or)].filter(e=>this.filter(e)&&(e.hasAttribute(ji)||0===(e.getAttribute(dr)??\\\"\\\").length)),this.coverDeclarations=[...e.querySelectorAll(`[${Fr}]`)].filter(e=>this.filter(e)).map(e=>({paths:ie(e.getAttribute(Fr)),owner:ge(e)})),this.renderedDeclarations=[...e.querySelectorAll(`[${Tr}]`)].filter(e=>this.filter(e)).flatMap(e=>{let t=function(e){if((e.getAttribute(ji)??\\\"\\\").length>0)return\\\"fragment\\\";let t=e.getAttribute(Cr);return null!==t?\\\"route\\\"===t?\\\"route\\\":void 0:e.hasAttribute(dr)&&null!==e.closest(\\\"head\\\")?\\\"route\\\":void 0}(e);return void 0===t?[]:[{strategy:t,paths:ie(e.getAttribute(Tr)),owner:ge(e)}]}),{elementCount:n,fieldCount:this.entriesByField.size,durationMs:performance.now()-t}}add(e){let t=this.filter(e)?this.resolveBinding(e):void 0,n=this.entryByElement.get(e);if(this.dependencies=null,void 0!==t)return void 0!==n&&this.replaceEntry(n,t)?(this.entryByElement.set(e,t),t):(void 0!==n&&this.removeEntry(e,n),this.append(t),this.entryByElement.set(e,t),t);void 0!==n&&this.removeEntry(e,n)}remove(e){let t=this.entryByElement.get(e);return!!t&&(this.dependencies=null,this.removeEntry(e,t))}get(e){return this.entriesByField.get(e)}getByElement(e){return this.entryByElement.get(e)}get fieldCount(){return this.entriesByField.size}get elementCount(){return this.count}entries(){return this.entriesByField.entries()}*values(){for(let e of this.entriesByField.values())yield*e}has(e){return this.entryByElement.has(e)}clear(){this.entriesByField.clear(),this.entryByElement=new WeakMap,this.count=0,this.dependencies=null,this.islandRoots=[],this.ownersByIsland=new Map,this.navigationRoots=[],this.coverDeclarations=[],this.renderedDeclarations=[]}replaceEntry(e,t){if(e.fieldName!==t.fieldName)return!1;let n=this.entriesByField.get(e.fieldName),i=void 0===n?-1:n.indexOf(e);return!(void 0===n||i<0||(n[i]=t,0))}removeEntry(e,t){this.entryByElement.delete(e);let n=this.entriesByField.get(t.fieldName),i=void 0===n?-1:n.indexOf(t);return!(void 0===n||i<0||(n.splice(i,1),0===n.length&&this.entriesByField.delete(t.fieldName),this.count-=1,0))}append(e){let t=this.entriesByField.get(e.fieldName);t?t.push(e):this.entriesByField.set(e.fieldName,[e]),this.count+=1}resolveBinding(e){let t=e.getAttribute(dr);if(null===t||0===t.length)return;let n=e.getAttribute(cr),i=e.getAttribute(hr),r=e.getAttribute(fr),l=e.getAttribute(pr),a=e.getAttribute(gr),s=e.getAttribute(mr),o=e.getAttribute(vr),u=e.getAttribute(yr),d=e.getAttribute(\\\"data-payload-format\\\"),c=ge(e),h=ie(e.getAttribute(Tr)),f=e.getAttribute(Cr),p=e.getAttribute($r),g=x(e);return{element:e,fieldName:t,fieldType:ye(e),explicitFieldType:null!==n&&me(n),strategyKind:P(e)??\\\"unknown\\\",...null!==g?{fragmentBoundary:g}:{},...null!==i&&i.length>0?{targetAttribute:i}:{},...null!==r&&r.length>0?{hrefField:r}:{},...null!==l&&l.length>0?{srcField:l}:{},...null!==a&&a.length>0?{altField:a}:{},...null!==s?{arrayTemplate:s}:{},...null!==o?{arraySeparator:o}:{},...null!==u&&u.length>0?{locale:u}:{},...null!==d&&d.length>0?{format:d}:{},...void 0!==c?{owner:c}:{},...h.length>0?{dependsOn:h}:{},...null!==f&&f.length>0?{strategy:f}:{},...e.hasAttribute(Rr)?{hidesWhenEmpty:!0}:{},...null!==p?{guessed:p}:{}}}},Ur=64,Ir=1e4,jr=1e3,Wr=64,Br=8192,Dr=1048576,_r=1e4,zr=20,Vr=new Set([\\\"__proto__\\\",\\\"constructor\\\",\\\"prototype\\\"]),qr=class{constructor(e){ei(this,\\\"serverURL\\\");ei(this,\\\"apiRoute\\\");ei(this,\\\"depth\\\");ei(this,\\\"fetchFn\\\");ei(this,\\\"log\\\");ei(this,\\\"inflight\\\",null);ei(this,\\\"attempt\\\",0);ei(this,\\\"destroyDepth\\\",0);this.serverURL=function(e){let t=e.length;for(;e.endsWith(\\\"/\\\",t);)t-=1;return e.slice(0,t)}(e.serverURL);let i=e.apiRoute??\\\"/api\\\";this.apiRoute=i.startsWith(\\\"/\\\")?i:`/${i}`,this.depth=e.depth??1,this.fetchFn=e.fetchFn,this.log=t(e.log??n)}canMerge(e){try{let t=e.schema;return void 0!==t?(Ne(e.data,t,this.serverURL,this.apiRoute,this.depth,e.locale),!0):null!==this.endpointOf(e)}catch{return!1}}endpointOf(e){try{let t=e.globalSlug;if(t)return Le(t)?{path:`globals/${encodeURIComponent(t)}`,field:\\\"globalType\\\",value:t}:null;let n=e.collectionSlug??\\\"\\\",i=e.data.id;return Le(n)&&xe(i)?{path:`${encodeURIComponent(n)}/${encodeURIComponent(String(i))}`,field:\\\"id\\\",value:String(i)}:null}catch{return null}}async merge(e){if(this.destroyDepth>0)return{status:\\\"superseded\\\"};let t=this.attempt+=1,n=this.inflight;this.inflight=null;let i=null,r=!1,l=()=>this.attempt!==t;try{if(n?.abort(),l())return{status:\\\"superseded\\\"};let t=e.schema;if(r=void 0!==t,void 0!==t){let n=Ne(e.data,t,this.serverURL,this.apiRoute,this.depth,e.locale);if(l())return{status:\\\"superseded\\\"};if(0===n.requests.length)return{status:\\\"merged\\\",doc:n.doc};let r=this.fetchFn??(\\\"function\\\"==typeof fetch?fetch:void 0);if(l())return{status:\\\"superseded\\\"};if(void 0===r)return{status:\\\"unavailable\\\"};i=new AbortController,this.inflight=i;for(let e of n.requests){let t=await r(e.url,{method:\\\"GET\\\",credentials:\\\"include\\\",redirect:\\\"error\\\",signal:i.signal});if(l())return{status:\\\"superseded\\\"};let n=t.ok;if(l())return{status:\\\"superseded\\\"};if(!n){let e=t.status;return l()?{status:\\\"superseded\\\"}:(i.abort(),l()?{status:\\\"superseded\\\"}:(this.log(\\\"merge HTTP\\\",e),l()?{status:\\\"superseded\\\"}:{status:\\\"unavailable\\\"}))}let a=await Me(t,i.signal,()=>!l());if(l())return{status:\\\"superseded\\\"};if(Ee(e,a),l())return{status:\\\"superseded\\\"}}return{status:\\\"merged\\\",doc:n.doc}}let a=this.endpointOf(e);if(l())return{status:\\\"superseded\\\"};if(null===a)return{status:\\\"unavailable\\\"};let s=this.fetchFn??(\\\"function\\\"==typeof fetch?fetch:void 0);if(l())return{status:\\\"superseded\\\"};if(void 0===s)return{status:\\\"unavailable\\\"};let o=JSON.stringify({data:e.data,depth:this.depth,flattenLocales:!1,locale:e.locale});if(l())return{status:\\\"superseded\\\"};i=new AbortController,this.inflight=i;let u=`${this.serverURL}${this.apiRoute}/${a.path}`,d=await s(u,{method:\\\"POST\\\",credentials:\\\"include\\\",headers:{\\\"Content-Type\\\":\\\"application/json\\\",\\\"X-Payload-HTTP-Method-Override\\\":\\\"GET\\\"},body:o,signal:i.signal});if(l())return{status:\\\"superseded\\\"};let c=d.ok;if(l())return{status:\\\"superseded\\\"};if(!c){let e=d.status;return l()?{status:\\\"superseded\\\"}:(this.log(\\\"merge HTTP\\\",e,u),l()?{status:\\\"superseded\\\"}:{status:\\\"unavailable\\\"})}let h=d.json.bind(d);if(l())return{status:\\\"superseded\\\"};let f=await h();if(l())return{status:\\\"superseded\\\"};if(null===f||\\\"object\\\"!=typeof f||Array.isArray(f))return this.log(\\\"merge invalid\\\",u),l()?{status:\\\"superseded\\\"}:{status:\\\"unavailable\\\"};let p=f,g=p[a.field],m=Object.hasOwn(p,a.field)&&(\\\"id\\\"===a.field?!xe(g)||String(g)!==a.value:g!==a.value);return l()?{status:\\\"superseded\\\"}:m?(this.log(\\\"merge invalid\\\",u),l()?{status:\\\"superseded\\\"}:{status:\\\"unavailable\\\"}):{status:\\\"merged\\\",doc:p}}catch(e){return l()||r&&(i?.abort(),l())?{status:\\\"superseded\\\"}:(this.log(\\\"merge exception\\\",r?new Error(\\\"legacy population could not be resolved\\\"):e),l()?{status:\\\"superseded\\\"}:{status:\\\"unavailable\\\"})}finally{this.inflight===i&&(this.inflight=null)}}destroy(){this.attempt+=1;let e=this.inflight;this.inflight=null,this.destroyDepth+=1;try{e?.abort()}finally{this.destroyDepth-=1}}},Hr=\\\"2.1.0\\\",Gr={name:\\\"payload-2\\\",fieldTyping:\\\"schema\\\",populatesRelationships:\\\"admin\\\",documentEvents:!1},Kr={name:\\\"payload-3\\\",fieldTyping:\\\"heuristic\\\",populatesRelationships:\\\"server\\\",documentEvents:!0},Jr={name:\\\"unknown\\\",fieldTyping:\\\"heuristic\\\",populatesRelationships:\\\"server\\\",documentEvents:!1},Xr=\\\"ssr\\\",Qr=1,Zr=class{constructor(e,t={}){ei(this,\\\"callbacks\\\");ei(this,\\\"debounceMs\\\");ei(this,\\\"rootMargin\\\");ei(this,\\\"visible\\\",new Set);ei(this,\\\"mutation\\\",null);ei(this,\\\"intersection\\\",null);ei(this,\\\"debounceTimer\\\",null);ei(this,\\\"generation\\\",0);this.callbacks=e,this.debounceMs=t.mutationDebounceMs??100,this.rootMargin=t.intersectionRootMargin??\\\"200px\\\"}start(e){let t=this.generation;this.stop();let n=t+1;if(this.generation!==n)return;let i=null,r=null;try{i=new MutationObserver(e=>{this.handleMutations(e,n)}),r=new IntersectionObserver(e=>{this.handleIntersection(e,n)},{rootMargin:this.rootMargin,threshold:0}),i.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[...Nr,ir,Xr]})}catch(e){throw i?.disconnect(),r?.disconnect(),e}this.generation===n?(this.mutation=i,this.intersection=r):(i.disconnect(),r.disconnect())}observeElement(e){this.intersection?.observe(e)}unobserveElement(e){this.intersection?.unobserve(e),this.visible.delete(e)}markVisible(e,t){t?this.visible.add(e):this.visible.delete(e)}isVisible(e){return this.visible.has(e)}stop(){this.generation+=1;let e=this.debounceTimer,t=this.mutation,n=this.intersection;this.debounceTimer=null,this.mutation=null,this.intersection=null,this.visible.clear(),null!==e&&clearTimeout(e);try{t?.disconnect()}finally{n?.disconnect()}}handleMutations(e,t){if(!this.isCurrentGeneration(t))return;for(let n of e){let e=Ue(n);if(null!==e&&(this.callbacks.onIslandHydrated?.(e),!this.isCurrentGeneration(t)))return}if(!function(e){for(let t of e){if(\\\"attributes\\\"===t.type&&t.attributeName===ir||\\\"attributes\\\"===t.type&&null!==t.attributeName&&Nr.includes(t.attributeName)&&(t.attributeName===dr||t.attributeName===kr||t.target.nodeType===Qr&&t.target.hasAttribute(dr)))return!0;for(let e of t.addedNodes)if(Ie(e))return!0;for(let e of t.removedNodes)if(Ie(e))return!0}return!1}(e))return;null!==this.debounceTimer&&clearTimeout(this.debounceTimer);let n=setTimeout(()=>{!this.isCurrentGeneration(t)||this.debounceTimer!==n||(this.debounceTimer=null,this.callbacks.onStructuralChange())},this.debounceMs);this.debounceTimer=n}handleIntersection(e,t){for(let n of e){if(!this.isCurrentGeneration(t))return;let{target:e}=n;if(n.isIntersecting){if(this.visible.has(e))continue;this.visible.add(e),this.callbacks.onVisibilityChange(e,!0)}else this.visible.has(e)&&(this.visible.delete(e),this.callbacks.onVisibilityChange(e,!1))}}isCurrentGeneration(e){return this.generation===e&&null!==this.intersection}},Yr=class{constructor(e){ii(this,il);ii(this,el,[]);ii(this,tl);ii(this,nl,!1);ri(this,tl,e)}get closed(){return ni(this,nl)}own(e){ni(this,nl)?li(this,il,rl).call(this,e):ni(this,el).push(e)}close(){if(ni(this,nl))return;ri(this,nl,!0);let e=ni(this,el).splice(0).reverse();for(let t of e)li(this,il,rl).call(this,t)}},el=new WeakMap,tl=new WeakMap,nl=new WeakMap,il=new WeakSet,rl=function(e){try{e()}catch(e){ni(this,tl).call(this,\\\"runtime cleanup failed:\\\",e)}},ll=\\\"__livePreviewHydration\\\",al=\\\"[data-payload-field]\\\",sl=\\\"__vue_app__\\\",ol=\\\"__livePreviewVueHydration\\\",ul=\\\"app:suspense:resolve\\\",dl={react:(e,t)=>function(e,t=5e3){We();let n=je();if(void 0===n)return null;if(void 0===n.onCommit){let e=e=>{!n.committed&&function(e){let t=e;return null!=t&&function(e){let t=e;return 9===t?.nodeType||null!=t?.querySelector?.(al)}(t.containerInfo)&&!function(e){let t=[];for(null!==e.current&&void 0!==e.current&&t.push(e.current);t.length>0;){let e=t.pop();if(void 0===e)continue;let n=e.memoizedState;if((13===e.tag||31===e.tag)&&\\\"object\\\"==typeof n&&null!==n&&\\\"dehydrated\\\"in n&&\\\"object\\\"==typeof n.dehydrated&&null!==n.dehydrated&&\\\"nodeType\\\"in n.dehydrated&&8===n.dehydrated.nodeType)return!0;null!==e.sibling&&void 0!==e.sibling&&t.push(e.sibling),null!==e.child&&void 0!==e.child&&t.push(e.child)}return!1}(t)}(e)&&Be(n)};n.onCommit=e;for(let t of n.commits.splice(0))e(t)}return _e(n,e,t)}(t),vue:function(e,t,n=5e3){qe();let i=ze();return void 0===i?null:(!i.committed&&function(e){for(let t=e.querySelector(al);null!==t;t=t.parentElement)if(void 0!==Ve(t))return!0;return!1}(e)&&Be(i),_e(i,t,n))},sveltekit:function(e,t,n=5e3){let i=e.ownerDocument??e,r=()=>null!==i.querySelector(\\\"#svelte-announcer\\\");if(r()||!Object.keys(window).some(e=>e.startsWith(\\\"__sveltekit_\\\")))return null;let l={committed:!1,waiters:[]},a=new MutationObserver(()=>{!l.committed&&r()&&Be(l)});a.observe(i,{childList:!0,subtree:!0});let s=_e(l,e=>{a.disconnect(),t(e)},n);return()=>{a.disconnect(),s?.()}}},cl={react:\\\"React commit\\\",vue:\\\"Vue mount\\\",sveltekit:\\\"SvelteKit mount\\\"},hl=class{constructor(e){ei(this,\\\"timeoutMs\\\");ei(this,\\\"onTimeout\\\");ei(this,\\\"handle\\\",null);ei(this,\\\"lastKick\\\",null);this.timeoutMs=e.timeoutMs??0,this.onTimeout=e.onTimeout}kick(){this.lastKick=Date.now(),!(this.timeoutMs<=0)&&(this.stop(),this.arm(this.timeoutMs))}resume(){if(this.timeoutMs<=0||null!==this.handle||null===this.lastKick)return!1;let e=Math.max(0,Date.now()-this.lastKick),t=this.timeoutMs-e;return t<=0?(this.lastKick=null,this.onTimeout(),!0):(this.arm(Math.min(t,this.timeoutMs)),!1)}arm(e){let t=setTimeout(()=>{this.handle===t&&(this.handle=null,this.lastKick=null,this.onTimeout())},e);this.handle=t}stop(){null!==this.handle&&(clearTimeout(this.handle),this.handle=null)}get lastKickAt(){return this.lastKick??0}get pending(){return null!==this.handle}},fl=class{constructor(){ei(this,\\\"current\\\",\\\"disconnected\\\")}get status(){return this.current}markConnected(){return this.transition(\\\"connected\\\")}markDisconnected(){return this.transition(\\\"disconnected\\\")}transition(e){return this.current!==e&&(this.current=e,!0)}},pl=\\\"data-payload-no-bind\\\",gl=13,ml=new Set([\\\"true\\\",\\\"false\\\",\\\"yes\\\",\\\"no\\\",\\\"on\\\",\\\"off\\\"]),vl=/^[\\\\d\\\\s.,:+/-]+$/u,yl=/^[a-z][a-z0-9_-]*$/u,bl=/^[a-z]{2,3}(?:[-_][A-Za-z0-9]{2,8})*$/u,wl=new Set([\\\"SCRIPT\\\",\\\"STYLE\\\",\\\"TEMPLATE\\\",\\\"TITLE\\\",\\\"NOSCRIPT\\\",\\\"TEXTAREA\\\",\\\"SELECT\\\",\\\"OPTION\\\",\\\"INPUT\\\",\\\"IFRAME\\\"]),Sl=\\\"http://www.w3.org/1999/xhtml\\\",Al=new Set([\\\"__proto__\\\",\\\"prototype\\\",\\\"constructor\\\"]),kl=class{constructor(e,t,n){ei(this,\\\"deps\\\",e);ei(this,\\\"state\\\",t);ei(this,\\\"host\\\",n);ei(this,\\\"awaitingHydration\\\",new WeakSet);ei(this,\\\"delivered\\\",new WeakMap);ei(this,\\\"confirmations\\\",new WeakMap)}reapplyBindings(e){let t=this.currentTransaction();void 0!==t?.renderData&&this.host.schedule(t,t.renderData,e)}reapplyIslands(e,t=!1){let n=t?e.filter(e=>this.awaitingHydration.delete(e)):e,i=this.state.activeUpdate,r=t&&null!==i&&this.state.isCurrent(i)?i:this.currentTransaction();void 0!==r?.renderData&&this.dispatchIslands(r,r.renderData,n)}dispatchIslands(e,t,n){let i=ft(this.deps,this.state,e,t.fields),r=()=>!e.cancelled&&this.state.isCurrent(e);if(!r())return;let l=this.delivered.get(t);void 0===l&&(l=new WeakSet,this.delivered.set(t,l));for(let a of n){let n=ge(a);if(!r())return;if(!1!==i&&!W(n,i)){this.awaitingHydration.delete(a);continue}let s=this.confirmation(a,e);if(ue(a))this.awaitingHydration.add(a);else{if(this.awaitingHydration.delete(a),l.has(a))continue;l.add(a),pt(e,t,[a],r,s)}}}hasLateRouteBinding(e,t,n,i){for(let i of e){if((i.getAttribute(dr)??\\\"\\\").length>0||\\\"route\\\"!==i.getAttribute(Cr)||!1!==t&&!W(ge(i),t))continue;let e=ie(i.getAttribute(Tr));if(0===e.length||e.some(e=>n.touched.has(e)))return!0}for(let[r,l]of this.deps.cache.entries())for(let a of l){if(!e.has(a.element)||!1!==t&&!W(a.owner,t)||\\\"route\\\"!==(a.strategyKind??P(a.element)??\\\"unknown\\\"))continue;let l=ct(i.fields,a,r,n.locale);if(!this.state.isCurrent(n))return!1;if(void 0!==l)return!0}return!1}fieldsForElements(e,t){let n=new Set(t);for(let[t,i]of this.deps.cache.entries())i.some(t=>e.has(t.element))&&n.add(t);return n}unrunFragmentPlan(e,t,n){if(null===t)return null;let i=t.boundaries.filter(t=>!e.fragmentBoundariesRun.has(t)&&(void 0===n||[...n].some(e=>e===t||t.contains(e))));if(0===i.length)return null;let r=new Set(i);return{...t,boundaries:i,covers:e=>void 0!==e.fragmentBoundary&&r.has(e.fragmentBoundary)}}confirmation(e,t){let n=this.confirmations.get(e);if(n?.transaction===t)return n.displayed;let i=this.state.display.handIsland(t);return this.confirmations.set(e,{transaction:t,displayed:i}),i}currentTransaction(){let e=this.state.activeUpdate;return this.state.navigationBindingReplay&&null!==e&&this.state.isCurrent(e)?e:null}},Tl=\\\"payload-live-preview\\\",Cl=Symbol.for(\\\"payload-live-preview.trusted-types\\\"),Rl=new Set([\\\"open\\\",\\\"value\\\",\\\"checked\\\",\\\"selected\\\"]),$l=\\\"__payloadLivePreviewDeprecationsWarned\\\",Fl=new Set,Nl=\\\"data-payload-\\\",Ml=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\\\"]),El=new Set([\\\"input\\\",\\\"button\\\",\\\"textarea\\\",\\\"select\\\",\\\"option\\\",\\\"label\\\"]),Ol=new Set([\\\"script\\\",\\\"style\\\",\\\"iframe\\\",\\\"object\\\",\\\"embed\\\",\\\"link\\\",\\\"meta\\\",\\\"base\\\",\\\"form\\\",\\\"input\\\",\\\"button\\\",\\\"select\\\",\\\"textarea\\\",\\\"svg\\\",\\\"math\\\",\\\"template\\\",\\\"frame\\\",\\\"frameset\\\",\\\"noframes\\\",\\\"noscript\\\"]),Ll=new Set([\\\"id\\\",\\\"class\\\",\\\"lang\\\",\\\"dir\\\",\\\"title\\\",\\\"role\\\",\\\"tabindex\\\"]),xl=\\\"aria-\\\",Pl=\\\"data-\\\",Ul=\\\"data-payload-\\\",Il={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\\\"])},jl=new Set([\\\"href\\\",\\\"src\\\",\\\"cite\\\",\\\"poster\\\"]),Wl=6,Bl=1,Dl=8,_l=(Error,new Set([\\\"id\\\",\\\"name\\\",\\\"data-payload-key\\\",\\\"data-payload-morph\\\",\\\"data-payload-nested-key\\\",\\\"data-payload-nested-template\\\"])),zl=\\\"strict\\\",Vl=(Object.freeze({allowedTags:Ml,removeCompletely:Ol,globalAttributes:Ll,attributesByTag:Il,urlAttributes:jl}),Object.freeze({\\\"&\\\":\\\"&\\\",\\\"<\\\":\\\"<\\\",\\\">\\\":\\\">\\\",'\\\"':\\\""\\\",\\\"'\\\":\\\"'\\\",\\\"/\\\":\\\"/\\\",\\\"`\\\":\\\"`\\\",\\\"=\\\":\\\"=\\\"})),ql=/[&<>\\\"'/`=]/g,Hl=Object.freeze({\\\"&\\\":\\\"&\\\",\\\"<\\\":\\\"<\\\",\\\">\\\":\\\">\\\",'\\\"':\\\""\\\",\\\"'\\\":\\\"'\\\"}),Gl=/[&<>\\\"']/g,Kl=/\\\\{\\\\{([\\\\s\\\\S]*?)\\\\}\\\\}/g,Jl=\\\"data-payload-\\\",Xl=[\\\"input\\\",\\\"textarea\\\",\\\"select\\\",\\\"option\\\",\\\"button\\\",\\\"label\\\",\\\"details\\\",\\\"summary\\\",\\\"dialog\\\",\\\"video\\\",\\\"audio\\\",\\\"progress\\\",\\\"meter\\\"],Ql=[\\\"type\\\",\\\"name\\\",\\\"placeholder\\\",\\\"open\\\",\\\"disabled\\\",\\\"readonly\\\",\\\"required\\\",\\\"checked\\\",\\\"selected\\\",\\\"value\\\",\\\"min\\\",\\\"max\\\",\\\"step\\\",\\\"rows\\\",\\\"cols\\\",\\\"for\\\",\\\"controls\\\",\\\"muted\\\",\\\"loop\\\",\\\"poster\\\",\\\"src\\\"],Zl=/<([a-z][a-z0-9]*(?:-[a-z0-9]+)+)\\\\b/gi,Yl=64,ea=new Map,ta=\\\"data-payload-key\\\",na=\\\"data-payload-nested-key\\\",ia=\\\"data-payload-nested-template\\\",ra=class{constructor(e,t,n){ei(this,\\\"deps\\\",e);ei(this,\\\"state\\\",t);ei(this,\\\"host\\\",n)}planFragments(e,t){let{deps:n,state:i}=this,r=n.strategies.fragment;if(void 0===r)return null;let l=new Set(r.plan(n.root,e));for(let e of i.fragmentsOwed)n.root.contains(e)?l.add(e):i.fragmentsOwed.delete(e);return rn(r,[...l].filter(e=>ln(e,t)),t)}escalateUnfaithful(e,t,n,i){if(e.routeRefreshed){this.kept(e,n);return}let{fragment:r,route:l}=this.deps.strategies,a=void 0===r?void 0:function(e){let t=[];for(let n of e){let e=n.fragmentBoundary;if(void 0===e)return;t.includes(e)||t.push(e)}return t}(n),s=void 0===a||a.every(e=>ln(e,i))?a:void 0;void 0===r||void 0===s?void 0!==l?(this.state.escalatedCount+=n.length,this.refreshRoute(e,t,l)):(this.warnEscalationUnavailable(n.length),this.kept(e,n)):(this.state.escalatedCount+=n.length,e.pendingFragments+=s.length,this.runFragments(e,t,rn(r,s,i)))}kept(e,t){for(let n of t)this.state.display.shortfall(e,{kind:\\\"unfaithful\\\",field:n.fieldName})}warnEscalationUnavailable(e){let{deps:t,state:n}=this;n.warnedEscalationUnavailable||(n.warnedEscalationUnavailable=!0,t.warn(`[live-preview] LP0808: onUnfaithfulPatch: 'escalate' has nowhere to go: ${String(e)} field(s) fell short and no route or fragment strategy is configured. Set routeStrategy: true or fragments: { endpoint }, or onUnfaithfulPatch: 'warn' to keep the patch and say so.`))}hasUnboundChange(e,t){let{deps:n,state:i}=this;if(e.baseline||e.routeRefreshed)return!1;let r=function(e,t,n,i,r,l){let a=q(e,i,l),s=G(e,n,i,a),o=[];for(let e of t){if(zi.has(e))continue;let t=s(e);if(\\\"none\\\"===t&&o.push(e),\\\"below\\\"!==t||void 0===r)continue;let i=H(e,n),{previous:l,next:u}=r;for(let{path:t}of V(i,l[e],u[e],a))o.push(t)}return o}(n.cache,e.touched,e.locale,t,function(e,t,n){return\\\"declared\\\"===e&&void 0!==t&&void 0!==n?{previous:t,next:n}:void 0}(n.subfieldCoverage,i.changes.previousFields,e.renderData?.fields),n.strategies),a=0;for(let e of r)l(i,e)&&(a+=1);let[s]=r;if(void 0===s)return!1;if(\\\"escalate\\\"!==n.onUnfaithfulPatch||void 0===n.strategies.route){\\\"escalate\\\"===n.onUnfaithfulPatch&&this.warnEscalationUnavailable(r.length);for(let t of r)i.display.shortfall(e,{kind:\\\"unbound\\\",field:t});return!1}return n.log(\\\"route\\\",\\\"LP0807\\\",`field \\\"${s}\\\" has no binding; refreshing the route`),i.escalatedCount+=a,!0}plansRoute(e,t,n){let i=e=>!1===n||W(e,n);if(e.plan(this.deps.root,t,{inScope:e=>i(ge(e))}))return!0;for(let[e,n]of this.deps.cache.entries())if(t.has(e)&&n.some(e=>\\\"route\\\"===e.strategyKind&&i(e.owner)))return!0;return!1}async runFragments(e,t,n){let{deps:i,state:r}=this,l=new AbortController,a=new Set(n.boundaries);for(let e of a)r.fragmentsOwed.delete(e);r.fragmentControllers.set(l,a);let s=t=>{a.delete(t)&&(e.pendingFragments-=1)},o=()=>r.isCurrent(e)&&!l.signal.aborted,u=e=>function(e,t,n){if(t.isConnected)return t;let i,r=t.getAttribute(ji),l=t.getAttribute(Wi);for(let t of e.querySelectorAll(`[${ji}]`))if(t.getAttribute(ji)===r&&t.getAttribute(Wi)===l&&n(t)){if(void 0!==i)return;i=t}return i}(i.root,e,e=>ln(e,n.ownerKeys)),{emitter:d}=i,{message:c}=e,h=e.revision.revision,f=e.receivedAt,p={root:i.root,revision:h,receivedAt:f,fields:t.fields,locale:e.locale,collectionSlug:\\\"string\\\"==typeof c.collectionSlug?c.collectionSlug:void 0,globalSlug:\\\"string\\\"==typeof c.globalSlug?c.globalSlug:void 0,signal:l.signal,isCurrent:o,log:(e,t)=>{i.log(\\\"fragment\\\",e,t)},morph:(e,t)=>{let n=o()?u(e):void 0;void 0!==n&&function(e,t,n){let i=e.ownerDocument.createElement(\\\"template\\\");i.innerHTML=yt(t);let r=e.cloneNode(!1);r.append(i.content);let l=fe(e);wt(e,r,{keyAttributes:[ta],boundary:ae,retainBoundary:he}),function(e){for(let t of e)t.isConnected||ur.has(t)||(ur.add(t),t.dispatchEvent(new CustomEvent(\\\"astro:unmount\\\")))}(l);let a=new Set(l);for(let t of fe(e)){let e=a.has(t)?void 0:pe(t);void 0!==e&&n(t,e)}}(n,t,(e,t)=>{this.warnIslandStart(e,t)})},patch:i=>{let r=u(i);void 0!==r&&(r!==i&&this.host.rebuildCache(),this.patchFallback(e,t,r,n.ownerKeys,o))},rendered:(e,t,n)=>{s(e);let i=u(e)??e;d.emitWhile(\\\"fragmentRender\\\",{element:i,id:t,key:n,status:\\\"rendered\\\",revision:h,receivedAt:f},o)},failed:(t,n,l,a,c)=>{s(t);let p=u(t)??t;r.display.shortfall(e,{kind:\\\"fragment\\\",id:n,key:l,code:a});let g=`fragment \\\"${n}\\\" fell back to patch: ${c}`;i.log(\\\"fragment\\\",a,g),d.emitWhile(\\\"error\\\",{error:new Error(g),context:\\\"fragment\\\",code:a},o),d.emitWhile(\\\"fragmentRender\\\",{element:p,id:n,key:l,status:\\\"failed\\\",code:a,revision:h,receivedAt:f},o)}},g={rendered:0,failed:0,superseded:0};try{g=await n.strategy.render(p,n.boundaries)}catch(t){if(i.log(\\\"fragment\\\",\\\"LP0801\\\",t),o()){for(let t of n.boundaries)p.patch(t),r.display.shortfall(e,ne(t));g={rendered:0,failed:n.boundaries.length,superseded:0}}}r.fragmentStats.rendered+=g.rendered,r.fragmentStats.failed+=g.failed,r.fragmentStats.superseded+=g.superseded,r.fragmentControllers.delete(l);for(let e of a)s(e);o()&&(g.rendered>0&&this.host.restoreGuesses(e,t),0===e.pendingFragments&&0===i.scheduler.pendingCount&&r.complete(e),this.host.revealPending(e),o()&&(0===g.rendered||0===d.listenerCount(\\\"afterUpdate\\\")||d.emitWhile(\\\"afterUpdate\\\",{data:t,updatedCount:g.rendered,durationMs:Date.now()-f,revision:h,receivedAt:f,source:\\\"fragment\\\"},o)))}async refreshRoute(e,t,n){let{deps:i,state:r}=this;e.routeRefreshed?(r.routeStats.loopStopped+=1,i.log(\\\"route\\\",\\\"LP0805\\\",`revision ${String(e.revision.revision)} asked for a second refresh`)):(e.routeRefreshed=!0,await this.runRoute(e,t,n).catch(e=>{this.routeFailed(e)}))}routeFailed(e){this.deps.log(\\\"route refresh failed:\\\",e)}armRouteRetry(e,t,n,i){let{state:r}=this;null!==r.routeRetry&&clearTimeout(r.routeRetry),r.routeRetry=setTimeout(()=>{r.routeRetry=null,r.isCurrent(e)&&this.runRoute(e,t,n).catch(e=>{this.routeFailed(e)})},i)}async runRoute(e,t,n){let{deps:i,state:r}=this,l=r.routeStats,a=new AbortController;r.routeController?.abort(),r.routeController=a;let s,o=()=>!a.signal.aborted;try{s=await n.refresh({revision:e.revision.revision,receivedAt:e.receivedAt,signal:a.signal,isCurrent:o,log:(e,t)=>{i.log(\\\"route\\\",e,t)},retryAfter:i=>{this.armRouteRetry(e,t,n,i)}})}catch(e){i.log(\\\"route\\\",\\\"LP0801\\\",e),s=\\\"failed\\\"}if(!o())return;r.routeController=null;let u=r.activeUpdate;if(null===u)return;let d=u.renderData,c=()=>r.isCurrent(u);if(\\\"partial\\\"===s?r.display.shortfall(u,{kind:\\\"route-saved\\\"}):(\\\"failed\\\"===s||\\\"superseded\\\"===s||\\\"refused\\\"===s&&null===r.routeRetry)&&r.display.shortfall(u,{kind:\\\"route-failed\\\",outcome:s}),\\\"refreshed\\\"!==s&&\\\"partial\\\"!==s)\\\"failed\\\"===s?l.failed+=1:\\\"refused\\\"===s&&(l.refused+=1),void 0!==d&&this.host.reapply(u,d);else{if(l.refreshes+=1,\\\"partial\\\"===s&&(l.partial+=1),r.lastAppliedIdentity=new WeakMap,void 0!==d&&this.host.restoreGuesses(u,d),this.host.rebuildCache(),void 0===d||!c())return;this.host.reapply(u,d),i.emitter.listenerCount(\\\"afterUpdate\\\")>0&&i.emitter.emitWhile(\\\"afterUpdate\\\",{data:d,updatedCount:i.cache.elementCount,durationMs:Date.now()-u.receivedAt,revision:u.revision.revision,receivedAt:u.receivedAt,source:\\\"route\\\"},c)}}warnIslandStart(e,t){if(this.state.warnedIslandStart)return;this.state.warnedIslandStart=!0;let n=\\\"element\\\"===t?\\\"<astro-island>\\\":`client:${e.getAttribute(\\\"client\\\")??\\\"\\\"}`;this.deps.warn(`[live-preview] LP0809: a fragment island cannot start: this page never loaded ${n}; render one on the page`)}warnFragmentFallback(e){!function(e,t,n){t.warnedFragmentFallback||(t.warnedFragmentFallback=!0,e.warn(`[live-preview] LP0806: \\\"${n.fieldName}\\\" asks for the fragment strategy but no handler is configured; patching instead`))}(this.deps,this.state,e)}warnUnsupportedStrategy(e){!function(e,t,n){t.warnedStrategy.has(n.element)||(t.warnedStrategy.add(n.element),e.warn(`[live-preview] LP0407: \\\"${n.fieldName}\\\" asks for strategy \\\"${String(n.strategy)}\\\"; only patch, fragment and route exist`))}(this.deps,this.state,e)}patchFallback(e,t,n,i,r){if(r())for(let[l,a]of this.deps.cache.entries())for(let s of a){if(s.fragmentBoundary!==n||!1!==i&&!W(s.owner,i))continue;let a=ct(t.fields,s,l,e.locale);void 0===a||!r()||this.deps.scheduler.schedule({target:s,value:this.host.transform(s,a,t.fields,r),allFields:t.fields,revision:e.revision,data:t})}}},la=new Set,aa={kind:\\\"merge\\\"},sa=class{constructor(e,t,n){ei(this,\\\"deps\\\",e);ei(this,\\\"state\\\",t);ei(this,\\\"strategies\\\");ei(this,\\\"navigationReplay\\\");t.changes.keepValues=\\\"declared\\\"===e.subfieldCoverage,t.display.host=function(e,t){return{outstanding:n=>!n.completed||n.pendingFragments>0||null!==t.routeController||null!==t.routeRetry||e.scheduler.pendingCount>0,report:t=>{\\\"partial\\\"===t.state&&e.a11y?.announcePartial(),e.emitter.emit(\\\"revisionDisplay\\\",t)},failed:t=>{e.log(\\\"revision display failed:\\\",t)}}}(e,t),this.strategies=new ra(e,t,{reapply:(e,t)=>{this.scheduleAllFields(e,t)},transform:(t,n,i,r)=>an(e,t,n,i,r),rebuildCache:n,restoreGuesses:(e,t)=>{this.restoreGuesses(e,t)},revealPending:e=>{this.revealPending(e)}}),this.navigationReplay=new kl(e,t,{schedule:(e,t,n)=>{this.scheduleAllFields(e,t,n)}})}handleUpdate(e,t,n){let{deps:i,state:r}=this;i.heartbeat.kick(),r.protocol.observe(function(e){let t=[];return Array.isArray(e.fieldSchemaJSON)&&t.push(\\\"schema-json\\\"),\\\"string\\\"==typeof e.locale&&t.push(\\\"locale\\\"),\\\"string\\\"==typeof e.previewToken&&t.push(\\\"preview-token\\\"),\\\"object\\\"==typeof e.externallyUpdatedRelationship&&null!==e.externallyUpdatedRelationship&&t.push(\\\"relationship-events\\\"),t}(e),i.log);let l=e.data;void 0!==l?void 0!==n&&this.acceptDataUpdate(e,l,t,n,!0):void 0!==e.protocolVersion&&r.protocol.applyVersion(e.protocolVersion,i.log)}handleReplay(e,t,n){let i=e.data;void 0!==i&&this.acceptDataUpdate(e,i,t,n,!1)}reapplyNavigationBindings(e){this.navigationReplay.reapplyBindings(e)}reapplyNavigationIslands(e,t=!1){this.navigationReplay.reapplyIslands(e,t)}acceptDataUpdate(e,t,n,i,r){let{deps:l,state:a}=this,s=r?a.relationships.inspect(e):null,o=\\\"string\\\"==typeof e.locale?e.locale:a.locale,u=a.schema,d=a.schemaIndex;Array.isArray(e.fieldSchemaJSON)&&(u=e.fieldSchemaJSON,d=function(e,t=\\\"\\\"){let n=new Map;return A(e,t,n,!1),A(e,t,n,!0),n}(e.fieldSchemaJSON));let c=a.activeUpdate;if(!a.isRunning()||null!==c&&c.revision.revision>i.revision)return;let h=null===s?null:a.relationships.commit(s),f=c,p={revision:i,message:e,rawData:t,locale:o,schema:u,schemaIndex:d,receivedAt:Date.now(),forceRender:null!==h||Y(f),countsAsUpdate:r,renderData:void 0,fragmentBoundariesRun:new WeakSet,touched:new Set,baseline:!1,invalidated:new Set,revealTarget:void 0,revealIdentities:[],pendingFragments:0,routeRefreshed:!1,cancelled:!1,completed:!1};a.locale=o,a.schema=u,a.schemaIndex=d,null!==f&&!f.completed&&f.countsAsUpdate&&(a.supersededCount+=1),a.activeUpdate=p,r&&(a.updateCount+=1),a.display.begin(p,i.revision),a.isCurrent(p)&&(l.scheduler.acceptRevision(i),a.isCurrent(p)&&(a.supersedeStrategies(),a.isCurrent(p)&&(null!==h&&(l.emitter.emitWhile(\\\"relationshipUpdate\\\",{detail:h,timestamp:Date.now()},()=>a.isCurrent(p)),!a.isCurrent(p))||r&&void 0!==e.protocolVersion&&(a.protocol.applyVersion(e.protocolVersion,l.log),!a.isCurrent(p))||r&&l.connection.markConnected()&&(l.a11y?.announceConnected(),l.emitter.emit(\\\"connect\\\",{origin:n,timestamp:Date.now()}),!a.isCurrent(p)||(l.log(\\\"connection\\\",\\\"disconnected\\\",\\\"\\\\u2192\\\",\\\"connected\\\"),!a.isCurrent(p)))||this.processUpdate(p).catch(e=>{l.log(\\\"update failed:\\\",e)}))))}async processUpdate(e){let{deps:t,state:n}=this,i=await this.resolveIncomingFields(e);if(null===i||!n.isCurrent(e))return;let r=this.dataFor(e,i);t.emitter.listenerCount(\\\"beforeUpdate\\\")>0&&(!await t.emitter.emitWhile(\\\"beforeUpdate\\\",{data:r,revision:e.revision.revision,receivedAt:e.receivedAt,source:\\\"patch\\\",cancel:()=>{e.cancelled=!0,t.scheduler.cancelRevision(e.revision)}},()=>!e.cancelled&&n.isCurrent(e))||e.cancelled||!n.isCurrent(e))||this.applyFields(e,r,!1)}dataFor(e,t){let{message:n}=e;return{fields:t,...void 0!==e.schema?{schema:e.schema}:{},...\\\"string\\\"==typeof n.globalSlug?{globalSlug:n.globalSlug}:{},...\\\"string\\\"==typeof n.collectionSlug?{collectionSlug:n.collectionSlug}:{},...void 0!==e.locale?{locale:e.locale}:{}}}applyFields(e,t,n){let{deps:i,state:r}=this;if(!r.isCurrent(e))return;if(r.changes.isBaseline&&!n&&\\\"off\\\"!==i.autoBind){{let n=ft(i,r,e,t.fields);!function(e,t,n,i,r,l){if(!l())return 0;let a=performance.now(),s=at(e.root),o=Ze(n,i);if(!l())return 0;let u=null===s?[]:lt(s,o);if(!l())return 0;let d=ot(e,u,r,\\\"on the first message\\\",l);if(!l())return 0;let c=function(e,t){let n=new Set;for(let{fieldName:e,stamps:i}of t){n.add(e);for(let e of[fr,gr]){let t=i[e];void 0!==t&&n.add(t)}}let i=new Map;for(let[t,r]of e)null!==r&&n.has(r.field)&&i.set(t,r);return{fields:n,values:i}}(o,d),h=performance.now()-a;l()&&(t.autoBindGuesses=c,t.autoBindSearchMs=h,d.length)}(i,r,t.fields,e.locale,n,()=>r.isCurrent(e))}if(!r.isCurrent(e))return}let l=re(i.dependencies,i.cache.dependencyMap());if(!r.isCurrent(e))return;let a=r.changes.diff(t.fields,l,()=>r.isCurrent(e));if(null===a)return;let s=!n&&r.navigationReplayPending;s&&(r.navigationReplayPending=!1,r.navigationBindingReplay=!0),e.baseline=a.baseline&&!s,e.invalidated=n?la:a.invalidated,e.touched=n?la:new Set([...a.changed,...a.invalidated]),e.renderData=t,this.scheduleAllFields(e,t)}async resolveIncomingFields(e){let{deps:t,state:n}=this,i=e.rawData;if(null===t.merger)return i;let r=n.merges.decide(t,e);if(!r.merge)return r.fields;let{message:l}=e,a=n.merges.request(t.merger,t.mergeWindowMs,{collectionSlug:l.collectionSlug,globalSlug:l.globalSlug,data:i,...void 0===e.schema?{}:{schema:e.schema},locale:e.locale});if(!a.leading)return this.applyMerged(e,a.result).catch(e=>{t.log(\\\"update failed:\\\",e)}),r.fields;let s=await a.result;return n.isCurrent(e)?\\\"merged\\\"===s.status?(n.merges.recordMerged(s.doc,e.locale),s.doc):\\\"superseded\\\"===s.status?null:(n.display.shortfall(e,aa),r.fields):null}async applyMerged(e,t){let{state:n}=this,i=await t;\\\"unavailable\\\"===i.status&&n.display.shortfall(e,aa),\\\"merged\\\"===i.status&&n.isCurrent(e)&&(n.merges.recordMerged(i.doc,e.locale),this.applyFields(e,this.dataFor(e,i.doc),!0))}scheduleAllFields(e,t,n){let{deps:i,state:r}=this;if(!r.isCurrent(e))return;let l=void 0!==n,a=()=>r.isCurrent(e),s=ft(i,r,e,t.fields);if(!a())return;let{touched:o}=e,u=i.strategies.route;if(l&&void 0!==u&&!e.routeRefreshed&&this.navigationReplay.hasLateRouteBinding(n,s,e,t)){a()&&this.strategies.refreshRoute(e,t,u);return}let d=!l&&this.strategies.hasUnboundChange(e,s),c=r.routeRefreshOwed;if(!l&&void 0!==u&&!e.routeRefreshed&&(d||c||this.strategies.plansRoute(u,o,s))&&a()){r.routeRefreshOwed=!1,this.strategies.refreshRoute(e,t,u);return}let h=l?this.navigationReplay.fieldsForElements(n,o):o,f=this.navigationReplay.unrunFragmentPlan(e,this.strategies.planFragments(h,s),n);if(!a())return;let p=i.skipUnchanged,g=0;for(let[o,u]of i.cache.entries()){if(!a())return;for(let d of u){if(void 0!==n&&!n.has(d.element)||!1!==s&&!W(d.owner,s))continue;if(!0===f?.covers(d)){if(i.revealEditedField){let n=ct(t.fields,d,o,e.locale);r.revealLedger.note(e,d,n)}continue}let u=d.strategyKind??P(d.element)??\\\"unknown\\\";if(\\\"unknown\\\"===u){this.strategies.warnUnsupportedStrategy(d);continue}\\\"fragment\\\"===u&&null===f&&this.strategies.warnFragmentFallback(d);let c=ct(t.fields,d,o,e.locale);if(void 0===c){r.absentFields.add(o);continue}if(!l&&i.revealEditedField&&r.revealLedger.note(e,d,c),!a())return;let h=an(i,d,c,t.fields,a);if(!a())return;let m=p?ht(d,h,t.fields,e.locale):void 0,v=r.lastAppliedIdentity.get(d.element);if(!e.forceRender&&i.skipUnchanged&&void 0!==m&&v===m&&!e.invalidated.has(o)){r.skippedUnchangedCount+=1;continue}let y={target:d,value:h,allFields:t.fields,revision:e.revision,...l?{}:{data:t},valueIdentity:m};i.scheduler.schedule(y),g+=1}}if(l||function(e,t,n,i,r){let{cache:l,strategies:a}=e,s={cache:l,warned:t,warn:e.warn};if(0===l.fieldCount||!1!==r&&!function(e,t){for(let n of e.values())if(W(n.owner,t))return!0;return!1}(l,r))return;let o=function(e,t,n,i){let r=G(e,t,n,q(e,n,i));return e=>\\\"none\\\"!==r(e)}(l,i,r,a);for(let[e,t]of Object.entries(n)){if(zi.has(e))continue;if(mt(t)){gt(s,o,e,i,t);continue}if(!vt(t)||o(e))continue;let n=H(e,i);for(let[e,r]of Object.entries(t))!mt(r)||zi.has(e)||gt(s,o,`${n}.${e}`,i,r)}if(\\\"declared\\\"!==e.subfieldCoverage)return;let u=function(e,t,n,i,r){let l=q(e,i,r),a=G(e,n,i,l),s=[];for(let[e,i]of Object.entries(t)){if(zi.has(e)||\\\"below\\\"!==a(e))continue;let t=H(e,n);s.push(...V(t,void 0,i,l))}return s}(l,n,i,r,a);for(let{path:e,value:t}of u)if(mt(t)&>(s,o,e,i,t),vt(t))for(let[n,r]of Object.entries(t))mt(r)&>(s,o,`${e}.${n}`,i,r)}(i,r.warnedOrphanFields,t.fields,e.locale,s),a()){if(null!==f&&f.boundaries.length>0){for(let t of f.boundaries)e.fragmentBoundariesRun.add(t);e.pendingFragments+=f.boundaries.length,this.strategies.runFragments(e,t,f)}l||!a()||0===g&&(0===e.pendingFragments&&0===i.scheduler.pendingCount&&(r.complete(e),this.revealPending(e)),this.notifyIslands(e,t))}}notifyIslands(e,t){0!==e.touched.size&&this.navigationReplay.dispatchIslands(e,t,this.deps.cache.islands)}restoreGuesses(e,t){let{deps:n,state:i}=this;if(\\\"off\\\"!==n.autoBind&&null!==i.autoBindGuesses){let r=ft(n,i,e,t.fields);!function(e,t,n,i,r,l){if(!l())return 0;let a=t.autoBindGuesses,s=at(e.root);if(null===a||0===a.fields.size||null===s)return 0;let o=new Map(a.values);for(let[e,t]of Ze(n,i)){if(null===t||!a.fields.has(t.field))continue;let n=o.get(e);void 0===n?o.set(e,t):n?.field!==t.field&&o.set(e,null)}if(!l())return 0;let u=lt(s,o);l()&&ot(e,u,r,\\\"after a server render\\\",l).length}(n,i,t.fields,e.locale,r,()=>i.isCurrent(e))}}onFlush(e){let{deps:t,state:n}=this;n.lastFlush=e,e.deferred>0&&!n.warnedVisibilityGate&&(n.warnedVisibilityGate=!0,t.warn(`[live-preview] LP0301: visibility gate held ${String(e.deferred)} off-screen update(s) until scrolled into view; see visibilityGateThreshold`));let{revision:i,data:r}=e;if(void 0===i)return;let l=n.activeUpdate;if(null===l||!n.isCurrent(l)||!b(l.revision,i))return;n.display.deferred(l,e.deferred),0===l.pendingFragments&&n.complete(l);let a=()=>n.isCurrent(l)&&b(l.revision,i),s=r??l.renderData;if(this.revealPending(l),!a())return;let o=n.unfaithfulPatches;if(o.length>0){if(n.unfaithfulPatches=[],void 0!==s){let e=ft(t,n,l,s.fields);this.strategies.escalateUnfaithful(l,s,o,e)}if(!a())return}void 0!==r&&(e.applied>0&&t.a11y?.announceUpdate(e.applied),a()&&(this.notifyIslands(l,r),a()&&0!==e.applied&&0!==t.emitter.listenerCount(\\\"afterUpdate\\\")&&t.emitter.emitWhile(\\\"afterUpdate\\\",{data:r,updatedCount:e.applied,durationMs:e.durationMs,revision:i.revision,receivedAt:l.receivedAt,source:\\\"patch\\\"},a)))}revealPending(e){let t=this.state.revealLedger.commit(e);if(void 0!==t)try{te(this.state.revealer,t)}catch(e){this.deps.log(\\\"reveal\\\",e)}}revealField(e){let t=this.deps.cache.get(e)?.[0];return void 0===t?\\\"no-element\\\":te(this.state.revealer,t)}},oa=class{constructor(e,t){ei(this,\\\"apply\\\");ei(this,\\\"debounceMs\\\");ei(this,\\\"maxWaitMs\\\");ei(this,\\\"isVisible\\\");ei(this,\\\"gateThresholdValue\\\");ei(this,\\\"gateDisabled\\\");ei(this,\\\"getCacheSize\\\");ei(this,\\\"onFlush\\\");ei(this,\\\"scheduleFrame\\\");ei(this,\\\"cancelFrame\\\");ei(this,\\\"pending\\\",new Map);ei(this,\\\"replay\\\",new Map);ei(this,\\\"activeFlushes\\\",new Set);ei(this,\\\"debounceTimer\\\",null);ei(this,\\\"debounceToken\\\",0);ei(this,\\\"deadlineTimer\\\",null);ei(this,\\\"frameHandle\\\",null);ei(this,\\\"frameFallback\\\",null);ei(this,\\\"frameToken\\\",0);ei(this,\\\"windowUntil\\\",0);ei(this,\\\"activeRevision\\\",null);ei(this,\\\"activeRevisionCancelled\\\",!1);ei(this,\\\"destroying\\\",!1);this.apply=e,this.debounceMs=t.debounceMs??50,this.maxWaitMs=t.maxWaitMs??4*this.debounceMs,this.isVisible=t.isVisible,this.gateThresholdValue=t.visibilityGateThreshold??50,this.gateDisabled=t.disableVisibilityGate??!1,this.getCacheSize=t.getCacheSize,this.onFlush=t.onFlush,this.scheduleFrame=t.scheduleFrame??(\\\"function\\\"==typeof requestAnimationFrame?requestAnimationFrame.bind(globalThis):e=>setTimeout(()=>{e(performance.now())},0)),this.cancelFrame=t.cancelFrame??(\\\"function\\\"==typeof cancelAnimationFrame?cancelAnimationFrame.bind(globalThis):e=>{clearTimeout(e)})}schedule(e){if(this.destroying||void 0!==e.revision&&(this.activeRevisionCancelled||null===this.activeRevision||!b(e.revision,this.activeRevision)))return;let t=this.pending.get(e.target.element);t?(t.value=e.value,t.allFields=e.allFields,t.revision=e.revision,t.data=e.data,t.valueIdentity=e.valueIdentity):this.pending.set(e.target.element,{target:e.target,value:e.value,allFields:e.allFields,revision:e.revision,data:e.data,valueIdentity:e.valueIdentity}),this.armDebounce()}acceptRevision(e){this.destroying||null!==this.activeRevision&&b(e,this.activeRevision)||null!==this.activeRevision&&function(e,t){return e.generation!==t.generation?e.generation-t.generation:e.revision-t.revision}(e,this.activeRevision)<0||(this.clearWork(),this.activeRevision=e,this.activeRevisionCancelled=!1,this.cancelScheduledWork())}cancelRevision(e){null===this.activeRevision||!b(e,this.activeRevision)||(this.clearWork(),this.activeRevisionCancelled=!0,this.cancelScheduledWork())}flushNow(){return this.cancelScheduledWork(),this.flush()}notifyVisible(e){let t=this.replay.get(e);if(!t||(this.replay.delete(e),!this.isCurrent(t)))return;let n=performance.now(),i=this.didApply(t)?1:0;this.onFlush?.(this.statsFor(t,i,0,performance.now()-n,1===i?[t.target.fieldName]:[]))}retarget(e){this.retargetBuffer(this.pending,e),this.retargetBuffer(this.replay,e);for(let t of this.activeFlushes)this.retargetBuffer(t,e)}forget(e){this.pending.delete(e),this.replay.delete(e);for(let t of this.activeFlushes)t.delete(e)}destroy(){if(!this.destroying){this.destroying=!0;try{this.clearWork(),this.activeRevision=null,this.activeRevisionCancelled=!1,this.windowUntil=0,this.cancelScheduledWork()}finally{this.destroying=!1}}}get pendingCount(){return this.pending.size}get replayCount(){return this.replay.size}get gateThreshold(){return this.gateThresholdValue}get gateActive(){return!this.gateDisabled&&this.getCacheSize()>this.gateThresholdValue}armDebounce(){let e=Date.now(),t=e>=this.windowUntil;if(this.windowUntil=e+this.debounceMs,t){this.requestFrame();return}let n=this.debounceToken+=1,i=this.debounceTimer;if(this.debounceTimer=null,null!==i&&clearTimeout(i),this.debounceToken!==n)return;let r=setTimeout(()=>{this.debounceToken===n&&(this.debounceTimer=null,this.pending.size>0&&this.requestFrame())},this.debounceMs);this.debounceToken===n&&(this.debounceTimer=r),null===this.deadlineTimer&&this.maxWaitMs>this.debounceMs&&(this.deadlineTimer=setTimeout(()=>{this.deadlineTimer=null,this.pending.size>0&&this.requestFrame()},this.maxWaitMs))}requestFrame(){let e=this.frameToken+=1,t=this.frameHandle;if(this.frameHandle=null,this.clearFrameFallback(),null!==t&&this.cancelFrame(t),this.frameToken!==e)return;let n=!1,i=()=>{if(this.frameToken!==e||n)return;n=!0;let t=this.frameHandle;this.frameHandle=null,this.clearFrameFallback(),null!==t&&this.cancelFrame(t),this.flush()},r=this.scheduleFrame(i);n||this.frameToken!==e||(this.frameHandle=r,this.frameFallback=setTimeout(i,100))}clearFrameFallback(){clearTimeout(this.frameFallback??void 0),this.frameFallback=null}flush(){let e=performance.now();this.clearDeadline();let t=this.gateActive,n=this.pending;this.pending=new Map;let i,r=0,l=[],a=0;this.activeFlushes.add(n);try{for(let e of n.values()){if(!this.isCurrent(e))continue;let n=!t||this.isVisible(e.target.element);if(this.isCurrent(e)){if(i??(i=e),!n){this.replay.set(e.target.element,e),a+=1;continue}this.replay.delete(e.target.element),this.didApply(e)&&(r+=1,l.push(e.target.fieldName))}}}finally{this.activeFlushes.delete(n)}let s=this.statsFor(i,r,a,performance.now()-e,l);return this.onFlush?.(s),s}isCurrent(e){return void 0===e.revision||!this.activeRevisionCancelled&&null!==this.activeRevision&&b(e.revision,this.activeRevision)}didApply(e){return!1!==this.apply(e)||!function(e){return Ui.has(e)}(this.apply)}retargetBuffer(e,t){let n=e.get(t.element);if(void 0!==n){if(!ve(n.target,t)){e.delete(t.element);return}n.target=t}}clearWork(){this.pending.clear(),this.replay.clear();for(let e of this.activeFlushes)e.clear()}statsFor(e,t,n,i,r){return{applied:t,appliedFields:r,deferred:n,durationMs:i,...void 0!==e?.revision?{revision:e.revision}:{},...void 0!==e?.data?{data:e.data}:{}}}clearDeadline(){null!==this.deadlineTimer&&(clearTimeout(this.deadlineTimer),this.deadlineTimer=null)}cancelScheduledWork(){let e=this.debounceTimer,t=this.frameHandle;this.debounceToken+=1,this.frameToken+=1,this.debounceTimer=null,this.frameHandle=null,this.clearDeadline(),this.clearFrameFallback(),null!==e&&clearTimeout(e),null!==t&&this.cancelFrame(t)}},ua=[0,500,1e3,2e3],da=class{constructor(e){ei(this,\\\"deps\\\");ei(this,\\\"state\\\",new er);ei(this,\\\"pipeline\\\");ei(this,\\\"writer\\\");ei(this,\\\"rootSentinel\\\",null);ei(this,\\\"scope\\\",null);ei(this,\\\"closingSession\\\",!1);ei(this,\\\"observedRoot\\\",null);ei(this,\\\"replayRetainedOnStart\\\",!1);let{emitter:r,renderers:l}=e,a=void 0===e.log?n:t(e.log),s=void 0===e.warn?si:t(e.warn),o=e.root??(typ\",\"eof document<\\\"u\\\"?document:void 0);if(void 0===o)throw new Error(\\\"LivePreviewRuntime: no document; pass options.root\\\");let u=new Pr({filter:e=>!function(e){let t=e;for(;null!==t;){if(oe(t))return!0;t=t.parentElement}return!1}(e)}),d=new Zr({onStructuralChange:()=>{this.rebuildCache()},onIslandHydrated:e=>{this.pipeline.reapplyNavigationIslands([e],!0)},onVisibilityChange:(e,t)=>{t&&c.notifyVisible(e)}},void 0!==e.intersectionRootMargin?{intersectionRootMargin:e.intersectionRootMargin}:{}),c=new oa(E(e=>this.writer.apply(e)),{...void 0!==e.debounceMs?{debounceMs:e.debounceMs}:{},...void 0!==e.disableVisibilityGate?{disableVisibilityGate:e.disableVisibilityGate}:{},...void 0!==e.visibilityGateThreshold?{visibilityGateThreshold:e.visibilityGateThreshold}:{},isVisible:e=>d.isVisible(e),getCacheSize:()=>u.elementCount,onFlush:e=>{this.pipeline.onFlush(e)}}),h=new Ci(e.originMatcher,{onUpdate:(e,t,n)=>{this.pipeline.handleUpdate(e,t,n)},onReplay:(e,t,n)=>{this.pipeline.handleReplay(e,t,n)},onDocumentEvent:()=>{this.state.protocol.observe([\\\"document-events\\\"],a),r.emit(\\\"documentSave\\\",{timestamp:Date.now()})},onFocusField:e=>{this.deps.revealEditedField&&this.pipeline.revealField(e)},onInvalid:(e,t)=>{if(\\\"token\\\"===e){let e=new Error(`Preview token rejected (origin: ${t})`);r.emit(\\\"error\\\",{error:e,context:\\\"token\\\",code:\\\"LP0502\\\"})}(\\\"shape\\\"===e||\\\"type\\\"===e)&&!this.state.warnedProtocolShape&&(this.state.warnedProtocolShape=!0,s(`[live-preview] LP0503: ${t} posted a message this runtime does not recognise (${\\\"type\\\"===e?\\\"unknown message type\\\":\\\"unexpected shape\\\"}); it was ignored. A newer Payload or a custom sender: check that the versions match.`)),\\\"source\\\"===e&&!this.state.warnedForeignSource&&(this.state.warnedForeignSource=!0,s(`[live-preview] LP0501: a message from ${t} was ignored because it did not come from the window that framed or opened this page. \\\\`eventSourcePolicy\\\\` is 'parent-or-opener' by default since 2.0, where 1.x accepted any window on a trusted origin. Set \\\\`eventSourcePolicy: 'any'\\\\` if the admin posts from elsewhere.`)),a(\\\"LP0501 message rejected:\\\",e,t)},...void 0!==e.validateToken?{validateToken:e.validateToken}:{},...void 0!==e.eventSourcePolicy?{sourcePolicy:e.eventSourcePolicy}:{}}),f=e.dataMerge;this.deps={emitter:r,cache:u,observers:d,scheduler:c,bus:h,connection:new fl,heartbeat:new hl({...void 0!==e.heartbeatMs?{timeoutMs:e.heartbeatMs}:{},onTimeout:()=>{this.onHeartbeatTimeout()}}),renderers:l,resolveRenderer:e.resolveRenderer??(e=>l[e]),transformValue:e.transformValue,renderRichText:e.renderRichText,sanitizerPolicy:e.sanitizerPolicy,root:o,readyTargets:\\\"function\\\"==typeof e.readyTargets?e.readyTargets:(e=>()=>e)(e.readyTargets),sendReady:e.sendReady??S,onHeartbeatTimeout:e.onHeartbeatTimeout,log:a,warn:s,a11y:w(e),serverURL:f?.serverURL,merger:void 0===f?null:new qr({serverURL:f.serverURL,...void 0!==f.apiRoute?{apiRoute:f.apiRoute}:{},...void 0!==f.depth?{depth:f.depth}:{},...void 0!==f.fetchFn?{fetchFn:f.fetchFn}:{},log:a}),mergeWindowMs:e.debounceMs??50,scopeBindingsByOwner:!0===e.scopeBindingsByOwner,subfieldCoverage:e.subfieldCoverage??\\\"descendant\\\",lockedOrigin:e.lockedOrigin??(()=>{}),skipUnchanged:!0===e.skipUnchanged,dependencies:e.dependencies??{},strategies:e.strategies??{},revealEditedField:!0===e.revealEditedField,onUnfaithfulPatch:i(e),autoBind:e.autoBind??\\\"off\\\",hydration:e.hydration},this.writer=new tr(this.deps,this.state),this.pipeline=new sa(this.deps,this.state,()=>{this.rebuildCache()})}start(){let{state:e}=this;if(e.isRunning()||this.closingSession)return!1;e.suspended&&(this.replayRetainedOnStart=!0),e.started=!0,e.suspended=!1,this.openScope();try{return function(e){\\\"react\\\"===e.hydration?We():\\\"vue\\\"===e.hydration&&qe();let{root:t}=e;if(!Ke(t)||\\\"loading\\\"!==t.readyState){He(e);return}let n=()=>{e.isRunning()&&e.later(()=>{He(e)})};t.addEventListener(\\\"DOMContentLoaded\\\",n,{once:!0}),e.defer(()=>{t.removeEventListener(\\\"DOMContentLoaded\\\",n)})}(this.startupHost()),!0}catch(e){throw this.rollbackFailedStart(),e}}startupHost(){let{state:e,deps:t}=this;return{root:t.root,hydration:t.hydration,isRunning:()=>e.isRunning(),defer:t=>{e.deferredStart=t,this.scope?.own(()=>{e.deferredStart===t&&(e.deferredStart=null,t())})},later:t=>{e.deferredStart=null;try{t()}catch(e){this.rollbackFailedStart(),this.reportError(e,\\\"startup\\\",\\\"LP0605\\\")}},hydrated:t=>{e.hydration=t},warn:t.warn,startNow:()=>{this.startNow()}}}startNow(){let{state:e,deps:t}=this;if(!e.isRunning())return;let n=Ke(t.root)?Je(t.root):t.root;if(null===n)throw new Error(\\\"LivePreviewRuntime: document.body unavailable\\\");if(t.observers.start(n),this.observedRoot=n,this.watchRootReplacement(),this.buildCacheAndObserve(),!e.isRunning()||(t.bus.attach(),t.emitter.emitWhile(\\\"init\\\",{timestamp:Date.now()},()=>e.isRunning()),!e.isRunning()))return;let i=this.replayRetainedOnStart;this.replayRetainedOnStart=!1;let r=i&&t.heartbeat.resume();if(e.isRunning()&&(!i||r||(e.forgetOwedWork(),e.merges.resetRawChanges(),e.unfaithfulPatches=[],e.revealer.reset(),e.lastAppliedIdentity=new WeakMap,e.changes.reset(),e.navigationReplayPending=!0,t.bus.replayLastAccepted()||(e.navigationReplayPending=!1),e.isRunning())))for(let n of ua){if(!e.isRunning())return;0===n?t.sendReady(t.readyTargets()):e.readyTimers.push(setTimeout(()=>{e.isRunning()&&this.sendReadyAfterStart()},n))}}suspend(){if(!this.state.isRunning())return!1;let e=this.release();return this.state.suspended=!0,e&&this.deps.emitter.emit(\\\"disconnect\\\",{reason:\\\"unload\\\",timestamp:Date.now()}),!0}destroy(){let{state:e,deps:t}=this;if(!e.isRunning()&&!e.suspended)return;let n=!!e.isRunning()&&this.release();e.suspended=!1,this.replayRetainedOnStart=!1,t.bus.forgetLastAccepted(),n&&t.emitter.emit(\\\"disconnect\\\",{reason:\\\"destroy\\\",timestamp:Date.now()}),t.a11y?.detach(),t.emitter.emit(\\\"destroy\\\",{timestamp:Date.now()})}openScope(){let{state:e,deps:t}=this,n=new Yr(t.log);n.own(()=>{t.merger?.destroy(),e.merges.destroy()}),n.own(()=>{t.scheduler.destroy()}),n.own(()=>{t.observers.stop()}),n.own(()=>{this.rootSentinel?.disconnect(),this.rootSentinel=null,this.observedRoot=null}),n.own(()=>{e.abortStrategies()}),n.own(()=>{t.bus.detach()}),n.own(()=>{t.heartbeat.stop()}),n.own(()=>{for(let t of e.readyTimers)clearTimeout(t);e.readyTimers.length=0}),this.scope=n}release(){let{state:e,deps:t}=this;e.display.end(),e.activeUpdate=null,e.navigationBindingReplay=!1,e.started=!1;let n=this.scope;this.scope=null,this.closingSession=!0;try{n?.close()}finally{this.closingSession=!1}return t.cache.clear(),t.connection.markDisconnected()}rollbackFailedStart(){this.release();try{this.deps.a11y?.detach()}catch(e){this.deps.log(\\\"runtime cleanup failed:\\\",e)}}refreshCache(){this.state.isRunning()&&(this.state.revealer.reset(),this.followReplacedRoot()||this.rebuildCache())}navigationCommit(){let{state:e,deps:t}=this;!e.isRunning()||null!==e.deferredStart||(this.cancelActiveUpdate(!0),t.merger?.destroy(),e.merges.destroy(),e.abortStrategies(),this.cancelActiveUpdate(!0),e.forgetOwedWork(),e.merges.resetRawChanges(),e.unfaithfulPatches=[],e.revealer.reset(),e.lastAppliedIdentity=new WeakMap,e.changes.reset(),e.isRunning()&&(t.bus.advanceGeneration(),e.navigationReplayPending=!0,this.followReplacedRoot()||this.rebuildCache(),e.isRunning()&&(t.bus.replayLastAccepted(),e.isRunning()&&this.sendReadyAfterStart())))}watchRootReplacement(){let{root:e}=this.deps;!Ke(e)||typeof MutationObserver>\\\"u\\\"||(this.rootSentinel?.disconnect(),this.rootSentinel=new MutationObserver(()=>{this.followReplacedRoot()}),this.rootSentinel.observe(e.documentElement,{childList:!0}))}followReplacedRoot(){let{root:e}=this.deps;if(!this.state.isRunning()||!Ke(e))return!1;let t=Je(e);return null!==t&&t!==this.observedRoot&&(this.observedRoot=t,this.deps.observers.start(t),this.rebuildCache(),!0)}get status(){return this.deps.connection.status}get cache(){return this.deps.cache}get updateCount(){return this.state.updateCount}get protocol(){return this.state.protocol.negotiation}inspect(){return function(e,t){let{cache:n,scheduler:i}=e,r=t.protocol.negotiation,l=t.activeUpdate,a=t.lastFlush,s=[],o=new Set,u=[];for(let[e,t]of n.entries()){s.push(e);for(let n of t)void 0!==n.owner&&o.add(n.owner),void 0!==n.guessed&&u.push({field:e,matched:n.guessed,attribute:n.targetAttribute??(\\\"IMG\\\"===n.element.tagName?\\\"src\\\":void 0)})}return{version:Hr,started:t.started,status:e.connection.status,origins:{trusted:[...e.readyTargets()],locked:e.lockedOrigin()},protocol:{ours:r.ours,theirs:r.theirs,negotiated:r.negotiated,capabilities:[...r.capabilities].sort(),observed:[...r.observed].sort(),profile:Pe(r.observed).name},revisions:{accepted:t.updateCount,superseded:t.supersededCount,completed:t.completedCount,skippedUnchanged:t.skippedUnchangedCount,active:null===l?void 0:l.revision.revision,display:t.display.snapshot()},bindings:{elements:n.elementCount,fields:n.fieldCount,fieldNames:s.sort(),absentFields:[...t.absentFields].sort(),orphanFields:[...t.warnedOrphanFields].sort(),ownerScoped:e.scopeBindingsByOwner,owners:[...o].sort(),guessed:u.sort((e,t)=>e.field.localeCompare(t.field)),autoBind:{mode:e.autoBind,searchMs:t.autoBindSearchMs}},route:{handler:void 0!==e.strategies.route,...t.routeStats},fidelity:{mode:e.onUnfaithfulPatch,canEscalate:void 0!==e.strategies.fragment||void 0!==e.strategies.route,unfaithful:t.unfaithfulCount,escalated:t.escalatedCount,fields:[...t.unfaithfulFields].sort()},hydration:{mode:e.hydration??\\\"off\\\",state:t.hydration},fragments:{handler:void 0!==e.strategies.fragment,inFlight:l?.pendingFragments??0,...t.fragmentStats},scheduler:{pending:i.pendingCount,deferred:i.replayCount,visibilityGateThreshold:i.gateThreshold,visibilityGateActive:i.gateActive,lastFlush:null===a?void 0:{applied:a.applied,appliedFields:a.appliedFields,deferred:a.deferred,durationMs:a.durationMs}},plugins:[],renderers:Object.keys(e.renderers).sort()}}(this.deps,this.state)}buildCacheAndObserve(){let{state:e,deps:t}=this;if(!e.isRunning())return;let n=t.cache.buildFromRoot(t.root);if(t.log(\\\"cache\\\",n),e.isRunning()&&(t.emitter.emitWhile(\\\"cacheRefresh\\\",n,()=>e.isRunning()),e.isRunning()))for(let n of t.cache.values()){if(!e.isRunning())return;t.observers.observeElement(n.element)}}rebuildCache(){let{state:e,deps:t}=this;if(!e.isRunning())return;let n=new Map,i=t.cache.islandOwners,r=new Set(t.cache.navigationReplayRoots);for(let e of t.cache.values())n.set(e.element,e),t.observers.unobserveElement(e.element);if(this.buildCacheAndObserve(),!e.isRunning())return;let l=new Set(t.cache.navigationReplayRoots.filter(e=>!r.has(e)));for(let e of t.cache.values()){let i=n.get(e.element);void 0!==i&&ve(i,e)?t.scheduler.retarget(e):(t.scheduler.forget(e.element),l.add(e.element)),n.delete(e.element)}for(let e of n.values())t.scheduler.forget(e.element);l.size>0&&this.pipeline.reapplyNavigationBindings(l);let a=t.cache.islands.filter(e=>!i.has(e)||t.scopeBindingsByOwner&&i.get(e)!==t.cache.islandOwners.get(e));a.length>0&&this.pipeline.reapplyNavigationIslands(a)}onHeartbeatTimeout(){let{state:e,deps:t}=this;if(!e.isRunning()||(this.cancelActiveUpdate(!1),t.merger?.destroy(),e.merges.destroy(),e.abortStrategies(),this.cancelActiveUpdate(!1),!e.isRunning()))return;t.bus.advanceGeneration(),t.bus.forgetLastAccepted(),e.navigationBindingReplay=!1;let n=t.connection.markDisconnected();try{t.onHeartbeatTimeout?.()}catch(e){t.log(\\\"heartbeat:\\\",e)}e.isRunning()&&(n&&this.isIdleDisconnected()&&(t.a11y?.announceDisconnected(),t.emitter.emitWhile(\\\"disconnect\\\",{reason:\\\"timeout\\\",timestamp:Date.now()},()=>this.isIdleDisconnected()),!e.isRunning()||(this.isIdleDisconnected()&&t.log(\\\"connection\\\",\\\"connected\\\",\\\"\\\\u2192\\\",\\\"disconnected\\\"),!e.isRunning()))||this.sendReadyAfterStart())}cancelActiveUpdate(e){let{state:t,deps:n}=this,i=t.activeUpdate;t.display.end(),t.activeUpdate=null,null!==i&&(i.cancelled=!0,n.scheduler.cancelRevision(i.revision),e&&!i.completed&&i.countsAsUpdate&&(t.supersededCount+=1))}sendReadyAfterStart(){try{this.deps.sendReady(this.deps.readyTargets())}catch(e){this.reportError(e,\\\"ready\\\",\\\"LP0606\\\")}}reportError(e,t,n){let i=e instanceof Error?e:new Error(String(e));this.deps.emitter.emit(\\\"error\\\",{error:i,context:t,code:n})}isIdleDisconnected(){return this.state.isRunning()&&\\\"disconnected\\\"===this.deps.connection.status&&null===this.state.activeUpdate}},ca=/^https?:\\\\/\\\\/(localhost|127\\\\.0\\\\.0\\\\.1)(?::\\\\d+)?$/i,ha=/^https?:\\\\/\\\\/[^/?#\\\\s]+$/i,fa=[3e3,3001,3333,4e3,4321,5e3,5173,5174,8e3,8080,8888,9e3],pa=class{constructor(e={}){ii(this,ga);let t=new Set;for(let n of e.additionalOrigins??[]){let e=on(n);void 0!==e&&t.add(e)}let n;if(e.enableReferrerDetection??1){let t=e.referrer??(typ\",\"eof document<\\\"u\\\"?document.referrer:\\\"\\\");if(t.length>0)try{let e=new URL(t).origin;e&&\\\"null\\\"!==e&&(n=e)}catch{}}let i=(e.enableLocalhostMatching??!0)&&(e.forceDevMode??function(){let e=function(){if(!(typ\",\"eof process>\\\"u\\\"))return\\\"production\\\"}();if(void 0!==e)return\\\"production\\\"!==e;if(typ\",\"eof window<\\\"u\\\"){let e=window.location.hostname;return\\\"localhost\\\"===e||\\\"127.0.0.1\\\"===e}return!1}());ri(this,ga,[t,n,i,void 0!==n,void 0])}matches(e){return 0!==e.length&&\\\"null\\\"!==e&&(void 0!==ni(this,ga)[4]?e===ni(this,ga)[4]:!!(ni(this,ga)[0].has(e)||0===ni(this,ga)[0].size&&void 0!==ni(this,ga)[1]&&e===ni(this,ga)[1]||ni(this,ga)[2]&&ca.test(e)))}lockOrigin(e){return!!this.matches(e)&&(ni(this,ga)[4]=e,!0)}unlockOrigin(){let e=ni(this,ga)[4];return ni(this,ga)[4]=void 0,e}get lockedOrigin(){return ni(this,ga)[4]}enumerate(){if(void 0!==ni(this,ga)[4])return[ni(this,ga)[4]];let e=new Set(ni(this,ga)[0]);if(0===ni(this,ga)[0].size&&void 0!==ni(this,ga)[1]&&e.add(ni(this,ga)[1]),ni(this,ga)[2])for(let t of fa)e.add(`http://localhost:${String(t)}`),e.add(`http://127.0.0.1:${String(t)}`);return[...e]}get referrerWasAvailable(){return ni(this,ga)[3]}get isProductionUnconfigured(){return!(!sn()||ni(this,ga)[0].size>0||ni(this,ga)[2]||void 0!==ni(this,ga)[1])}get isReferrerOnlyTrust(){return!(ni(this,ga)[0].size>0||ni(this,ga)[2])&&void 0!==ni(this,ga)[1]}},ga=new WeakMap,ma=\\\"astro:page-load\\\",va=\\\"astro:after-swap\\\",ya={1:\\\"left\\\",2:\\\"center\\\",3:\\\"right\\\",4:\\\"justify\\\"},ba=new Set([\\\"left\\\",\\\"center\\\",\\\"right\\\",\\\"justify\\\",\\\"start\\\",\\\"end\\\"]),wa=new Set([\\\"h1\\\",\\\"h2\\\",\\\"h3\\\",\\\"h4\\\",\\\"h5\\\",\\\"h6\\\"]),Sa=' target=\\\"_blank\\\" rel=\\\"noopener noreferrer\\\"',Aa=(e,t)=>{let n=t.renderChildren(e.children??[]),i=fn(e.fields),r=function(e,t){if(\\\"internal\\\"===t?.linkType)return function(e){let t=fn(fn(e)?.value),n=t?.url;if(\\\"string\\\"==typeof n&&n.length>0)return n;let i=t?.slug;return\\\"string\\\"==typeof i&&i.length>0?`/${i}`:void 0}(t.doc);let n=t?.url??e.url;return\\\"string\\\"==typeof n&&n.length>0?n:void 0}(e,i);if(void 0===r||!F(r))return n;let l=\\\"string\\\"==typeof e.title?` title=\\\"${Lt(e.title)}\\\"`:\\\"\\\";return`<a href=\\\"${xt(r)}\\\"${function(e,t,n){if(!0===t?.newTab||N(n))return Sa;let i=\\\"string\\\"==typeof e.target?e.target:\\\"\\\";return\\\"\\\"===i?\\\"\\\":\\\"_blank\\\"===i?Sa:` target=\\\"${Lt(i)}\\\"`}(e,i,r)}${l}>${n}</a>`},ka=new Map,Ta=\\\".lp-block:empty,.lp-inline-block:empty\\\",Ca={text:e=>{let t=Lt(\\\"string\\\"==typeof e.text?e.text:\\\"\\\"),n=\\\"number\\\"==typeof e.format?e.format:0;return!!(16&n)&&(t=`<code>${t}</code>`),!!(1&n)&&(t=`<strong>${t}</strong>`),!!(2&n)&&(t=`<em>${t}</em>`),!!(8&n)&&(t=`<u>${t}</u>`),!!(4&n)&&(t=`<s>${t}</s>`),!!(32&n)&&(t=`<sub>${t}</sub>`),!!(64&n)&&(t=`<sup>${t}</sup>`),!!(128&n)&&(t=`<mark>${t}</mark>`),t},paragraph:(e,t)=>{let n=t.renderChildren(e.children??[]);return`<p${cn(e)}${hn(e)}>${n}</p>`},heading:(e,t)=>{let n=\\\"string\\\"==typeof e.tag?e.tag.toLowerCase():\\\"h2\\\",i=wa.has(n)?n:\\\"h2\\\",r=t.renderChildren(e.children??[]);return`<${i}${cn(e)}${hn(e)}>${r}</${i}>`},list:(e,t)=>{let n=\\\"string\\\"==typeof e.listType?e.listType:\\\"bullet\\\",i=\\\"number\\\"===n?\\\"ol\\\":\\\"ul\\\",r=\\\"number\\\"===n&&\\\"number\\\"==typeof e.start&&e.start>1?` start=\\\"${String(e.start)}\\\"`:\\\"\\\",l=\\\"check\\\"===n?' role=\\\"list\\\"':\\\"\\\",a=t.renderChildren(e.children??[]);return`<${i}${cn(e)}${hn(e)}${r}${l}>${a}</${i}>`},listitem:(e,t)=>{let n=t.renderChildren(e.children??[]);if(\\\"boolean\\\"==typeof e.checked)return`<li role=\\\"checkbox\\\" aria-checked=\\\"${e.checked?\\\"true\\\":\\\"false\\\"}\\\"${hn(e)}>${n}</li>`;let i=\\\"number\\\"==typeof e.value?` value=\\\"${Lt(String(e.value))}\\\"`:\\\"\\\";return`<li${cn(e)}${hn(e)}${i}>${n}</li>`},link:Aa,autolink:Aa,quote:(e,t)=>{let n=t.renderChildren(e.children??[]);return`<blockquote${cn(e)}${hn(e)}>${n}</blockquote>`},code:e=>{let t=mn(\\\"string\\\"==typeof e.language?e.language:\\\"\\\");return`<pre><code${\\\"\\\"===t?\\\"\\\":` class=\\\"language-${t}\\\"`}>${Lt(bn(e))}</code></pre>`},\\\"code-highlight\\\":e=>{let t=\\\"string\\\"==typeof e.text?e.text:\\\"\\\";return`<span${\\\"string\\\"==typeof e.highlightType?` class=\\\"token-${mn(e.highlightType)}\\\"`:\\\"\\\"}>${Lt(t)}</span>`},linebreak:()=>\\\"<br>\\\",horizontalrule:()=>\\\"<hr>\\\",tab:()=>\\\"\\\\t\\\",upload:e=>{let t=pn(e.value);if(void 0===t)return\\\"\\\";let n=t.url;if(\\\"string\\\"!=typeof n||!F(n))return\\\"\\\";let i=\\\"string\\\"==typeof t.mimeType?t.mimeType:\\\"\\\";return i.startsWith(\\\"video/\\\")?function(e,t){return`<video controls${wn(e)}><source src=\\\"${xt(t)}\\\"${Sn(e)}></video>`}(t,n):i.startsWith(\\\"audio/\\\")?function(e,t){return`<audio controls><source src=\\\"${xt(t)}\\\"${Sn(e)}></audio>`}(t,n):\\\"\\\"===i||i.startsWith(\\\"image/\\\")?function(e,t){let n=\\\"string\\\"==typeof e.alt?Lt(e.alt):\\\"\\\";return`<img src=\\\"${xt(t)}\\\" alt=\\\"${n}\\\"${wn(e)} loading=\\\"lazy\\\" decoding=\\\"async\\\">`}(t,n):function(e,t){let n=\\\"string\\\"==typeof e.filename?Lt(e.filename):Lt(t);return`<a href=\\\"${xt(t)}\\\" target=\\\"_blank\\\" rel=\\\"noopener noreferrer\\\">${n}</a>`}(t,n)},relationship:e=>{let t=\\\"string\\\"==typeof e.relationTo?e.relationTo:\\\"\\\",n=fn(e.value),i=Lt((n&&yn(n))??`#${t}`),r=mn(t),l=\\\"\\\"===r?' class=\\\"lp-relation\\\"':` class=\\\"lp-relation lp-relation--${r}\\\"`,a=n?.url;return\\\"string\\\"==typeof a&&F(a)?`<a href=\\\"${xt(a)}\\\"${l}>${i}</a>`:`<span${l}>${i}</span>`},block:(e,t)=>kn(e,t,\\\"div\\\",\\\"lp-block\\\"),inlineBlock:(e,t)=>kn(e,t,\\\"span\\\",\\\"lp-inline-block\\\"),table:(e,t)=>`<table${cn(e)}><tbody>${t.renderChildren(e.children??[])}</tbody></table>`,tablerow:(e,t)=>`<tr>${t.renderChildren(e.children??[])}</tr>`,tablecell:(e,t)=>{let n=\\\"number\\\"==typeof e.headerState?e.headerState:0,i=3&n?\\\"th\\\":\\\"td\\\";return`<${i}${1===n?' scope=\\\"col\\\"':2===n?' scope=\\\"row\\\"':\\\"\\\"}${Tn(\\\"colspan\\\",e.colSpan)}${Tn(\\\"rowspan\\\",e.rowSpan)}>${t.renderChildren(e.children??[])}</${i}>`}},Ra=new Map,$a=!1,Fa=\\\"data-payload-text\\\",Na=new Set,Ma=new Set,Ea=new Set([\\\"DIV\\\",\\\"SECTION\\\",\\\"ARTICLE\\\"]),Oa={name:\\\"richText\\\",render:E((e,t,n)=>{let i=e.element;if(Bt(t)){i.textContent=\\\"\\\";return}let r=n.sanitizerPolicy;if(void 0!==n.renderRichText){let l=n.renderRichText(t,{fieldName:e.fieldName,element:i,locale:n.locale});i.innerHTML=yt(Ft(l,r));return}if(Cn(t)){let l=new Map,a=Nn(i,Ft(function(e,t={}){if(!Cn(e))return\\\"\\\";let n=function(e){let t={renderChildren:e=>{let n=\\\"\\\";for(let i of e)n+=Rn(i,t);return n},resolveAlignment:un,resolveIndent:dn,onUnrenderedBlock:e};return t}(t.onUnrenderedBlock).renderChildren(e.root.children);return!1===t.sanitize?n:void 0!==t.document?$t(n,{document:t.document}):!0===t.requireDocument||void 0!==Nt()?$t(n):(function(){if(!$a){$a=!0;try{console.warn('[live-preview] lexicalToHtml() has no sanitizer document and returned unsanitised HTML; pass { document } (linkedom, jsdom) per call. 3.0 throws here instead: opt in now with { requireDocument: true }. See \\\"HTML sanitization\\\" in docs/security.md.')}catch{}}}(),n)}(t,{sanitize:!1,onUnrenderedBlock:(e,t)=>{l.set(t,e)}}),r));for(let[t,i]of a){let r=l.get(t);void 0!==r&&En(e,n,r,i)}return}if(\\\"string\\\"!=typeof t)return!1;i.innerHTML=yt(Ft(t,r))})},La={name:\\\"html\\\",render(e,t,n){if(Bt(t)){e.element.textContent=\\\"\\\";return}let i=\\\"string\\\"==typeof t?t:Wt(t);e.element.innerHTML=yt(Ft(i,n.sanitizerPolicy))}},xa=new WeakSet,Pa=Ln(\\\"url\\\"),Ua=/^[a-zA-Z][a-zA-Z0-9+.-]*:/,Ia=Ln(\\\"email\\\",function(e){let t=e.trim();return Ua.test(t)||!t.includes(\\\"@\\\")?t:`mailto:${t}`}),ja=[\\\"src\\\",\\\"srcset\\\",\\\"sizes\\\"],Wa={name:\\\"image\\\",render:E((e,t,n)=>{let i=e.element;if(Bt(t)){In(i);return}let r=void 0!==e.locale,{media:l,candidate:a}=function(e,t,n,i){let r=void 0!==e.srcField&&e.srcField.length>0?ut(n.allFields,e.srcField,n.locale,i):t,l=pn(r);return{media:l,candidate:void 0===l?r:l.url}}(e,t,n,r),s=On(i,e.fieldName,a,void 0===l?void 0:n.serverURL);if(\\\"none\\\"===s.kind)return!1;if(\\\"unsafe\\\"!==s.kind){if(\\\"IMG\\\"===i.tagName){let t=i;Pn(t,s.url,l,n.serverURL);let a=function(e,t,n,i,r){if(void 0!==t&&t.length>0){let e=ut(n,t,i,r);return\\\"string\\\"==typeof e?e:void 0}return e?.alt}(l,e.altField,n.allFields,n.locale,r);void 0!==a&&(t.alt=a);return}i.style.backgroundImage=`url('${function(e){return e.replace(/['\\\"()\\\\\\\\]/g,\\\"\\\\\\\\$&\\\")}(s.url)}')`}else In(i)})},Ba={name:\\\"upload\\\",render:E((e,t,n)=>{let i=e.element;if(Bt(t)){jn(i);return}let r=pn(t);if(void 0===r)return!1;let l=On(i,e.fieldName,r.url,n.serverURL);if(\\\"none\\\"===l.kind)return!1;if(\\\"unsafe\\\"===l.kind){jn(i);return}let a=l.url;if(\\\"IMG\\\"===i.tagName){let e=i;Pn(e,a,r,n.serverURL),void 0!==r.alt&&(e.alt=r.alt);return}if(\\\"A\\\"===i.tagName){i.setAttribute(\\\"href\\\",a),i.textContent=r.filename??a;return}let s=Lt(r.filename??a);i.innerHTML=yt(`<a href=\\\"${xt(a)}\\\">${s}</a>`)})},Da={name:\\\"relationship\\\",render(e,t){let n=e.element;if(Bt(t))n.removeAttribute(\\\"href\\\"),n.textContent=\\\"\\\";else{if(\\\"A\\\"===n.tagName&&!Array.isArray(t)){let i=On(n,e.fieldName,fn(t)?.url);\\\"safe\\\"===i.kind?n.setAttribute(\\\"href\\\",i.url):\\\"unsafe\\\"===i.kind&&n.removeAttribute(\\\"href\\\")}n.textContent=Array.isArray(t)?t.map(Wn).join(\\\", \\\"):Wn(t)}}},_a={name:\\\"select\\\",render(e,t,n){let i=e.element,r=Bt(t)?[]:function(e){return Array.isArray(e)?e.map(Wt):[Wt(e)]}(t);if(\\\"SELECT\\\"!==i.tagName){if(\\\"INPUT\\\"===i.tagName&&\\\"radio\\\"===i.type){let e=i;e.checked=r.includes(e.value);return}i.textContent=r.map(e=>function(e,t){let n=t.schema?.options;if(!Array.isArray(n))return e;for(let t of n){let n=fn(t);if(void 0!==n&&Wt(n.value)===e)return\\\"string\\\"==typeof n.label?n.label:e}return e}(e,n)).join(\\\", \\\")}else!function(e,t){if(e.multiple)for(let n of Array.from(e.options))n.selected=t.includes(n.value);else e.value=t[0]??\\\"\\\"}(i,r)}},za=new Set([\\\"\\\",\\\"false\\\",\\\"0\\\",\\\"off\\\",\\\"no\\\"]),Va={name:\\\"checkbox\\\",render(e,t){let n=e.element,i=function(e){return\\\"boolean\\\"==typeof e?e:\\\"string\\\"==typeof e?!za.has(e.trim().toLowerCase()):\\\"number\\\"==typeof e?0!==e:null!=e}(t);\\\"INPUT\\\"!==n.tagName||\\\"checkbox\\\"!==n.type?n.hasAttribute(\\\"aria-checked\\\")?n.setAttribute(\\\"aria-checked\\\",i?\\\"true\\\":\\\"false\\\"):n.textContent=i?\\\"true\\\":\\\"false\\\":n.checked=i}},qa=new Map,Ha=new Map,Ga=new Set([\\\"short\\\",\\\"medium\\\",\\\"long\\\",\\\"full\\\"]),Ka=new Set([\\\"short\\\",\\\"medium\\\",\\\"long\\\",\\\"full\\\"]),Ja=/^[A-Za-z]{3}$/u,Xa=/^[0-4]$/u,Qa=new WeakSet,Za={name:\\\"date\\\",render(e,t,n){let i=e.element;if(Bt(t)){\\\"INPUT\\\"===i.tagName?i.value=\\\"\\\":(i.removeAttribute(\\\"datetime\\\"),i.textContent=\\\"\\\");return}let r=\\\"number\\\"==typeof t?t:Wt(t),l=new Date(r),a=!Number.isNaN(l.getTime()),s=String(r);\\\"INPUT\\\"!==i.tagName?(\\\"TIME\\\"===i.tagName&&i.setAttribute(\\\"datetime\\\",a?l.toISOString():s),i.textContent=a?function(e,t,n){let i=t.locale??n.locale??o(),r=Vn(\\\"date\\\",t.format,t.element,t.fieldName)??Ya;try{return function(e,t){let n=Bn(e,t);return Dt(Ha,n)??_t(Ha,n,new Intl.DateTimeFormat(e,t),64)}(i,r).format(e)}catch{return e.toISOString()}}(l,e,n):s):i.value=a?function(e,t){let n=`${String(t.getFullYear()).padStart(4,\\\"0\\\")}-${qn(t.getMonth()+1)}-${qn(t.getDate())}`,i=`${qn(t.getHours())}:${qn(t.getMinutes())}`;return\\\"date\\\"===e?n:\\\"datetime-local\\\"===e?`${n}T${i}`:\\\"time\\\"===e?i:t.toISOString()}(i.type,l):s}},Ya={dateStyle:\\\"medium\\\",timeStyle:\\\"short\\\"},es={name:\\\"number\\\",render(e,t,n){let i=e.element;if(Bt(t)){\\\"INPUT\\\"===i.tagName?i.value=\\\"\\\":i.textContent=\\\"\\\";return}let r=\\\"number\\\"==typeof t?t:Number(Wt(t));Number.isNaN(r)?i.textContent=Wt(t):\\\"INPUT\\\"!==i.tagName?i.textContent=function(e,t,n){let i=t.locale??n.locale??o(),r=Vn(\\\"number\\\",t.format,t.element,t.fieldName);try{return function(e,t){let n=Bn(e,t);return Dt(qa,n)??_t(qa,n,new Intl.NumberFormat(e,t),64)}(i,r).format(e)}catch{return String(e)}}(r,e,n):i.value=String(r)}},ts={name:\\\"array\\\",render:E((e,t,n)=>{let i=e.element;if(Bt(t)){i.textContent=\\\"\\\";return}if(!Array.isArray(t))return!1;let r=e.arrayTemplate;if(void 0!==r&&r.length>0){let e=function(e,t){let n=Pt(t),i=\\\"\\\";for(let r=0;r<t.length;r+=1)i+=Ut(e,t[r],r,Wt,n);return i}(r,t),l=n.sanitizerPolicy,a=zt(r),s=It(i);i.innerHTML=yt(Ft(e,l,a));for(let e of Array.from(i.children))jt(e,s);return}i.textContent=t.map(Wt).join(e.arraySeparator??\\\", \\\")})},ns=new Map;!function(){if(typ\",\"eof window>\\\"u\\\"||!sn()&&(typ\",\"eof window>\\\"u\\\"||null==window.opener))return;let e=window.__livePreview,t=JSON.stringify(Qn());if(void 0!==e&&(void 0===e.configSignature||e.configSignature===t))return e.refresh(),e;let[n=[],r=\\\"\\\",l=\\\"/api\\\",a=1,s=!1,o=50,u=!0,d=0,c=!1,h=50,f=\\\"200px\\\",p=!0,g=!1,m=!1,v=!0,y=\\\"parent-or-opener\\\",b=\\\"strict\\\",w,S=!1,A=!1,k,T,C=\\\"off\\\",R,$,F=[],N=\\\"descendant\\\"]=Qn(),M=function(e){let t=typeof __LIVE_PREVIEW_FRAGMENT__<\\\"u\\\"?__LIVE_PREVIEW_FRAGMENT__:void 0,n=t??(typeof __LIVE_PREVIEW_ROUTE__<\\\"u\\\"?__LIVE_PREVIEW_ROUTE__:void 0);if(void 0===n)return;let i=n.createRouteStrategy();return void 0===t||void 0===e||\\\"\\\"===e?{route:i}:{fragment:t.createFragmentStrategy({endpoint:e}),route:i}}(w),E=new pa({additionalOrigins:n,enableReferrerDetection:!p,enableLocalhostMatching:!g});E.isProductionUnconfigured?si(\\\"[live-preview] LP0101: No trusted origin. Pass allowedOrigins to generateInlineScript() (or to the adapter) \\\\u2014 the runtime reads no environment variable in the browser.\\\"):E.isReferrerOnlyTrust&&si(\\\"[live-preview] LP0102: document.referrer fallback trusts any framing site. Set allowedOrigins and a frame-ancestors CSP in production.\\\");let O=new ui,L=function(){let e=[Oa,La,Pa,Ia,Wa,Ba,Da,_a,{..._a,name:\\\"radio\\\"},Va,Za,es,ts,{...ts,name:\\\"blocks\\\"}];return function(e=[]){let t={};for(let n of e)t[n.name]=n;for(let[e,n]of ns)t[e]=n;return Object.freeze(t)}([Fn(\\\"text\\\"),Fn(\\\"textarea\\\"),...e,Hn()])}(),x=new da({renderers:L,originMatcher:e=>E.matches(e),lockedOrigin:()=>E.lockedOrigin,readyTargets:()=>E.enumerate(),emitter:O,eventSourcePolicy:y,...\\\"\\\"!==r?{dataMerge:{serverURL:r,apiRoute:l,depth:a}}:{},debounceMs:o,heartbeatMs:d,intersectionRootMargin:f,disableVisibilityGate:c,visibilityGateThreshold:h,enableA11y:u,scopeBindingsByOwner:m,subfieldCoverage:N,skipUnchanged:v,revealEditedField:S,onUnfaithfulPatch:i({onUnfaithfulPatch:T,onUnboundChange:k}),autoBind:C,...void 0!==R?{hydration:R}:{},sanitizerPolicy:b,...void 0!==M?{strategies:M}:{},onHeartbeatTimeout:()=>{E.unlockOrigin()},...s?{log:(...e)=>{oi(\\\"[live-preview]\\\",...e)}}:{}});O.on(\\\"connect\\\",e=>{E.lockOrigin(e.origin)}),x.start(),e?.destroy();let P=function(e,t={}){let n=t.windowTarget??globalThis.window,i=t.documentTarget??globalThis.document,r=[...new Set(t.softNavigationEvents??[])],l=()=>{e.suspend()},a=t=>{!0===t.persisted&&e.resume()},s=!1,o=()=>{s=!0},u=t=>{if(t.type===ma){if(!s)return;s=!1}void 0===e.refreshAfterNavigation?e.refreshCache():e.refreshAfterNavigation()},d=!1;n?.addEventListener(\\\"pagehide\\\",l),n?.addEventListener(\\\"pageshow\\\",a);for(let e of r)i?.addEventListener(e,u);let c=r.includes(ma);return c&&i?.addEventListener(va,o),()=>{if(!d){d=!0,n?.removeEventListener(\\\"pagehide\\\",l),n?.removeEventListener(\\\"pageshow\\\",a);for(let e of r)i?.removeEventListener(e,u);c&&i?.removeEventListener(va,o)}}}({suspend:()=>x.suspend(),resume:()=>x.start(),refreshCache:()=>{x.refreshCache()},refreshAfterNavigation:()=>{x.navigationCommit()}},{softNavigationEvents:F}),U=Object.freeze({version:Hr,configSignature:t,destroy:()=>{P(),x.destroy();let e=window;e.__livePreview===U&&delete e.__livePreview},refresh:()=>{x.refreshCache()},refreshAfterNavigation:()=>{x.navigationCommit()},enumerateOrigins:()=>E.enumerate(),inspect:()=>x.inspect()});try{Object.defineProperty(window,\\\"__livePreview\\\",{value:U,writable:!1,configurable:!0})}catch(e){throw P(),x.destroy(),e}}()})();\"].join('');\nexport const RUNTIME_CONTENT_HASH = \"36b6b936852f8784\";\nexport const RUNTIME_INTEGRITY = \"sha384-BhMmdzmT60a/bDZtwG08BPr2mB04CPQyneb2GMEwS9qy390XzpU9SvV8FQM6lg+J\";\nexport const RUNTIME_BUILD_INFO: RuntimeBuildInfo = { generatedAt: \"2026-10-23T13:50:38.000Z\", size: 145194 };\n","// Auto-generated by scripts/build-runtime.ts — do not edit.\nexport const FRAGMENT_SOURCE = /* @__PURE__ */ [\"\\\"use strict\\\";var __LIVE_PREVIEW_FRAGMENT__=(()=>{var P=Object.defineProperty;var fe=Object.getOwnPropertyDescriptor;var me=Object.getOwnPropertyNames;var ye=Object.prototype.hasOwnProperty;var pe=(e,t)=>{for(var n in t)P(e,n,{get:t[n],enumerable:!0})},ge=(e,t,n,i)=>{if(t&&typeof t==\\\"object\\\"||typeof t==\\\"function\\\")for(let o of me(t))!ye.call(e,o)&&o!==n&&P(e,o,{get:()=>t[o],enumerable:!(i=fe(t,o))||i.enumerable});return e};var he=e=>ge(P({},\\\"__esModule\\\",{value:!0}),e);var Ye={};pe(Ye,{createFragmentStrategy:()=>ce,createRouteStrategy:()=>ue});function k(e,t){let n=new AbortController,i=!1,o=()=>{n.abort()};e.addEventListener(\\\"abort\\\",o,{once:!0});let r=setTimeout(()=>{i=!0,n.abort()},t);return{signal:n.signal,timedOut:()=>i,dispose:()=>{clearTimeout(r),e.removeEventListener(\\\"abort\\\",o)}}}function R(e){return e instanceof Error?e.message:String(e)}var D=\\\"data-payload-island\\\",Qe=`astro-island, [${D}]`,w=\\\"data-payload-owned\\\",be=\\\"data-payload-morph\\\";function F(e){if(e.tagName.toLowerCase().includes(\\\"-\\\")&&!e.hasAttribute(be)||z(e)||e.hasAttribute(w))return!0;let n=e.getAttribute(\\\"contenteditable\\\");return n!==null&&n!==\\\"false\\\"}function Ee(e){return e.tagName.toLowerCase()===\\\"astro-island\\\"||e.hasAttribute(D)}function Se(e){return e.getAttribute(D)===\\\"patch\\\"}function z(e){return Ee(e)&&!Se(e)}function V(e){let t=e;for(;t!==null;){if(z(t))return!0;t=t.parentElement}return!1}var Re=[\\\"component-url\\\",\\\"component-export\\\",\\\"renderer-url\\\",\\\"client\\\",\\\"opts\\\",\\\"before-hydration-url\\\"],v=new WeakMap,G=new WeakSet;function W(e){return e.tagName.toLowerCase()===\\\"astro-island\\\"}function q(e){let t=\\\"\\\";for(let n of e.querySelectorAll(\\\"astro-slot, template[data-astro-template]\\\")){if(n.parentElement?.closest(\\\"astro-island\\\")!==e)continue;let i=n.getAttribute(\\\"name\\\")??n.getAttribute(\\\"data-astro-template\\\")??\\\"\\\";t+=`${i}\\\\0${n.innerHTML}\\\\0`}return t}function Ae(e){let t=e.ownerDocument.defaultView?.customElements.get(\\\"astro-island\\\");return t!==void 0&&e instanceof t&&Array.isArray(t.observedAttributes)&&t.observedAttributes.includes(\\\"props\\\")}function j(e,t){if(!W(e)||!W(t))return!0;let n=q(t);if(!(Re.every(r=>e.getAttribute(r)===t.getAttribute(r))&&(v.get(e)??q(e))===n&&(e.getAttribute(\\\"props\\\")===t.getAttribute(\\\"props\\\")||Ae(e))))return v.set(t,n),!1;v.set(e,n);let o=t.getAttribute(\\\"props\\\");return o!==e.getAttribute(\\\"props\\\")&&(e.setAttribute(\\\"ssr\\\",\\\"\\\"),o===null?e.removeAttribute(\\\"props\\\"):e.setAttribute(\\\"props\\\",o)),!0}function Y(e){return Array.from(e.querySelectorAll(\\\"astro-island\\\"))}function X(e){for(let t of e)t.isConnected||G.has(t)||(G.add(t),t.dispatchEvent(new CustomEvent(\\\"astro:unmount\\\")))}function O(e){if(e==null)return[];let t=new Set,n=[];for(let i of e.split(/[\\\\s,]+/)){let o=i.trim();o.length===0||t.has(o)||(t.add(o),n.push(o))}return n}var A=\\\"data-payload-fragment\\\",I=\\\"data-payload-fragment-key\\\";var Te=\\\"data-payload-depends\\\";function _(e){let t=e.getAttribute(A);if(t===null||t.length===0)return null;let n=e.getAttribute(I);return{element:e,id:t,key:n===null||n.length===0?void 0:n,dependsOn:O(e.getAttribute(Te))}}function J(e,t){let n=[];for(let i of e.querySelectorAll(`[${A}]`)){let o=_(i);o===null||V(i)||o.dependsOn.length>0&&!o.dependsOn.some(r=>t.has(r))||n.push(o)}return n}var Q=\\\"x-payload-fragment-version\\\";function B(e){return typeof e==\\\"object\\\"&&e!==null&&!Array.isArray(e)}function Z(e){if(!B(e))return null;let{html:t,boundary:n,revision:i,metadata:o}=e;return typeof t!=\\\"string\\\"||!B(n)||typeof n.id!=\\\"string\\\"||n.key!==void 0&&typeof n.key!=\\\"string\\\"||typeof i!=\\\"number\\\"||!B(o)||typeof o.renderedAt!=\\\"string\\\"||typeof o.renderer!=\\\"string\\\"?null:e}function ee(e){let t={};for(let[n,i]of Object.entries(e))i!==void 0&&(t[n]=i);return t}function L(e){return e.reason instanceof Error?e.reason:new DOMException(\\\"The operation was aborted.\\\",\\\"AbortError\\\")}function C(e){return e?.aborted===!0}function te(e){let t=0,n=[],i=()=>{let o=n.shift();o===void 0?t-=1:o.resume()};return async(o,r)=>{if(r!==void 0&&C(r))throw L(r);if(t<e)t+=1;else if(await new Promise((d,m)=>{let l=()=>{},u={resume:()=>{l(),d()}};if(n.push(u),r!==void 0){let s=()=>{let c=n.indexOf(u);c!==-1&&(n.splice(c,1),l(),m(L(r)))};l=()=>{r.removeEventListener(\\\"abort\\\",s)},r.addEventListener(\\\"abort\\\",s,{once:!0}),C(r)&&s()}}),r!==void 0&&C(r))throw i(),L(r);try{return await o()}finally{i()}}}var xe=5e3,ke=4,Fe=512*1024,T={status:\\\"superseded\\\"};function b(e,t){return{status:\\\"failed\\\",code:e,reason:t}}function Oe(e){let t=()=>{throw new TypeError('createFragmentStrategy: endpoint must be a same-origin path starting with \\\"/\\\"')};if((typeof e!=\\\"string\\\"||!e.startsWith(\\\"/\\\")||e.startsWith(\\\"//\\\")||e.includes(\\\"\\\\\\\\\\\"))&&t(),typeof location<\\\"u\\\"){let n;try{n=new URL(e,location.href)}catch{n=void 0}n?.origin!==location.origin&&t()}return e}function Ie(e){return typeof e==\\\"object\\\"&&e!==null&&typeof e.getReader==\\\"function\\\"}async function Ne(e,t,n){let i=e.body;if(!Ie(i)){let u=await e.text();return new TextEncoder().encode(u).byteLength>t?null:u}let o=i.getReader(),r=()=>{o.cancel().catch(()=>{})};n.addEventListener(\\\"abort\\\",r,{once:!0});let d=new TextDecoder,m=\\\"\\\",l=0;try{for(;;){let{done:u,value:s}=await o.read();if(u)break;if(l+=s.byteLength,l>t)return r(),null;m+=d.decode(s,{stream:!0})}}finally{n.removeEventListener(\\\"abort\\\",r),o.releaseLock()}return m+d.decode()}function ne(e){let t=Oe(e.endpoint),n=e.timeoutMs??xe,i=e.maxResponseBytes??Fe,o=te(Math.max(1,e.maxConcurrent??ke)),r=new Map,d=new WeakMap,m=0,l=s=>{let c=d.get(s);return c!==void 0?c:(m+=1,d.set(s,m),m)};async function u(s,c){let a=()=>s.signal.aborted;if(a())return T;let h=e.location??location,p=ee({fragment:c.id,key:c.key,route:h.pathname,search:h.search,revision:s.revision,locale:s.locale,collectionSlug:s.collectionSlug,globalSlug:s.globalSlug,fields:s.fields}),f=k(s.signal,n),y=E=>a()?T:f.timedOut()?b(\\\"LP0801\\\",`timeout after ${String(n)} ms`):b(\\\"LP0801\\\",R(E)),g,x=!1;try{try{g=await(e.fetch??fetch)(t,{method:\\\"POST\\\",credentials:\\\"same-origin\\\",headers:{...e.headers,accept:\\\"application/json\\\",\\\"content-type\\\":\\\"application/json\\\",[Q]:String(1)},body:JSON.stringify(p),signal:f.signal})}catch(M){return y(M)}if(a())return T;if(g.status===401||g.status===403)return b(\\\"LP0803\\\",`endpoint refused the preview (${String(g.status)})`);if(!g.ok)return b(\\\"LP0801\\\",`endpoint answered ${String(g.status)}`);let E=g.headers.get(\\\"content-type\\\")??\\\"\\\";if(!E.toLowerCase().startsWith(\\\"application/json\\\"))return b(\\\"LP0802\\\",`unexpected content type \\\"${E}\\\"`);if(Number(g.headers.get(\\\"content-length\\\")??\\\"0\\\")>i)return b(\\\"LP0802\\\",\\\"response exceeds the size limit\\\");if(f.signal.aborted)return y(f.signal.reason);let N;try{x=!0,N=await Ne(g,i,f.signal)}catch(M){return y(M)}if(a())return T;if(f.timedOut())return b(\\\"LP0801\\\",`timeout after ${String(n)} ms`);if(N===null)return b(\\\"LP0802\\\",\\\"response exceeds the size limit\\\");let $;try{$=JSON.parse(N)}catch{return b(\\\"LP0802\\\",\\\"response is not JSON\\\")}let S=Z($);return S===null?b(\\\"LP0802\\\",\\\"response has the wrong shape\\\"):S.boundary.id!==c.id||S.boundary.key!==c.key?b(\\\"LP0802\\\",\\\"response is for another boundary\\\"):S.revision!==s.revision?T:{status:\\\"rendered\\\",html:S.html,metadata:S.metadata}}finally{if(f.dispose(),g!==void 0&&!x)try{g.body?.cancel().catch(()=>{})}catch{}}}return(s,c)=>{let a=JSON.stringify([l(s.signal),c.id,c.key,s.revision]),h=r.get(a);if(h!==void 0)return h;let p=!1,f=o(()=>(p=!0,u(s,c)),s.signal).catch(g=>{if(!p&&s.signal.aborted)return T;throw g});r.set(a,f);let y=()=>{r.get(a)===f&&r.delete(a)};return f.then(y,y),f}}var Me=new Set([\\\"open\\\",\\\"value\\\",\\\"checked\\\",\\\"selected\\\"]);function oe(e,t){for(let n of t.keyAttributes){let i=e.getAttribute(n);if(i!==null&&i.length>0)return`${n}=${i}`}}function H(e,t,n){if(!U(e,t))return t;let i=n.boundary??F,o=i(e),r=i(t);if(o||r)return!o||!r?t:n.retainBoundary?.(e,t)??!0?e:t;let d=Be(e);return Pe(e,t),n.retainChildrenOf?.(e,t)!==!0&&ve(e,t,n),Le(d),e}function Pe(e,t){for(let n of Array.from(e.attributes))t.hasAttribute(n.name)||Me.has(n.name.toLowerCase())||e.removeAttribute(n.name);for(let n of Array.from(t.attributes))e.getAttribute(n.name)!==n.value&&e.setAttribute(n.name,n.value)}function ve(e,t,n){let i=_e(e,n),o=new Set(i.values()),r=Array.from(e.childNodes).filter(c=>!o.has(c)),d=new Set,m=new Set,l=Array.from(t.childNodes),u=e.firstChild,s=0;for(let c=0;c<l.length;c+=1){let a=l[c],h=null,p=a instanceof Element?oe(a,n):void 0;if(p!==void 0&&m.has(p)&&(p=void 0),p!==void 0){m.add(p);let y=i.get(p);if(y!==void 0&&!d.has(y)&&(h=re(y,a,n)===y?y:null,h===null)){y.replaceWith(a),d.add(a),u=a.nextSibling;continue}}else{for(;s<r.length;){let y=r[s];if(s+=1,!d.has(y)){if(U(y,a)){h=re(y,a,n)===y?y:null,h===null&&(e.replaceChild(a,y),d.add(a),u=a.nextSibling);break}if(y instanceof Element){let g=l[c+1];if(!(a instanceof Element)||g!==void 0&&U(y,g)){s-=1;break}e.replaceChild(a,y),d.add(a),u=a.nextSibling;break}if(!(a instanceof Element)){e.replaceChild(a,y),d.add(a),u=a.nextSibling;break}}}if(h===null&&d.has(a))continue}let f=h??a;for(d.add(f);u!==null&&u!==f&&!d.has(u)&&De(u);)u=u.nextSibling;f!==u&&e.insertBefore(f,u),u=f.nextSibling}for(let c of Array.from(e.childNodes))d.has(c)||c.remove()}function re(e,t,n){return e instanceof Element&&t instanceof Element?H(e,t,n):(e.nodeValue!==t.nodeValue&&(e.nodeValue=t.nodeValue),e)}function De(e){return e.nodeType===Node.TEXT_NODE&&(e.nodeValue??\\\"\\\").trim().length===0}function U(e,t){return e.nodeType!==t.nodeType?!1:e instanceof Element&&t instanceof Element?e.tagName===t.tagName&&e.namespaceURI===t.namespaceURI:!0}function _e(e,t){let n=new Map,i;for(let o of Array.from(e.children)){let r=oe(o,t);if(r!==void 0){if(n.has(r)){i??(i=r.slice(r.indexOf(\\\"=\\\")+1));continue}n.set(r,o)}}return i!==void 0&&t.onDuplicateKey?.(e,i),n}function Be(e){let t=e.ownerDocument.activeElement;if(!(t instanceof HTMLElement)||!e.contains(t))return null;let n=t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement?[t.selectionStart,t.selectionEnd]:null;return{element:t,selection:n}}function Le(e){if(e===null)return;let{element:t,selection:n}=e;if(!(t.ownerDocument.activeElement===t||!t.isConnected))try{t.focus({preventScroll:!0});let[i,o]=n??[null,null];i!==null&&o!==null&&t.setSelectionRange(i,o)}catch{}}var ie=\\\"data-payload-key\\\";var Ce=\\\"__livePreviewRouteRefresh\\\";function Ue(){return typ\",\"eof window>\\\"u\\\"?void 0:window}function ae(){return Ue()?.[Ce]}var le=\\\"data-payload-strategy\\\",de=\\\"data-payload-field\\\",He=\\\"data-payload-depends\\\",Ke=\\\"x-payload-live-preview\\\",$e=8e3,Ge=\\\"route refresh returned no promise; re-applied before the host committed (see LivePreviewRouteRefresh)\\\",We=1e3;function qe(e){let t=e.getAttribute(le);return t!==null?t===\\\"route\\\":e.closest(\\\"head\\\")!==null}function ze(e){let t=e.getAttribute(de),n=O(e.getAttribute(He));return t===null||t.length===0?n:[t,...n]}function se(e){return e.hasAttribute(w)?!1:e.tagName===\\\"META\\\"?e.hasAttribute(\\\"name\\\")||e.hasAttribute(\\\"property\\\"):e.tagName===\\\"LINK\\\"&&e.getAttribute(\\\"rel\\\")===\\\"canonical\\\"}function Ve(e,t){let n=Array.from(e.head.children).find(l=>l.tagName===\\\"TITLE\\\"),i=Array.from(t.head.children).find(l=>l.tagName===\\\"TITLE\\\");!n?.hasAttribute(w)&&!i?.hasAttribute(w)&&t.title!==e.title&&(e.title=t.title);let o=Array.from(e.head.children).filter(se),r=Array.from(t.head.children).filter(se),d=Math.min(o.length,r.length);o.slice(0,d).forEach((l,u)=>{let s=r[u];if(s===void 0)return;if(l.tagName===s.tagName){for(let a of Array.from(l.attributes))s.hasAttribute(a.name)||l.removeAttribute(a.name);for(let a of Array.from(s.attributes))l.getAttribute(a.name)!==a.value&&l.setAttribute(a.name,a.value);return}let c=e.importNode(s,!0);l.replaceWith(c),o[u]=c});let m=o.at(-1);for(let l of r.slice(o.length)){let u=e.importNode(l,!0);m===void 0?e.head.append(u):m.after(u),m=u}for(let l of o.slice(r.length))l.remove()}function ue(e={}){let t=e.timeoutMs??$e,n=e.minIntervalMs??We,i=-1/0,o=!1;return{plan(r,d,m){for(let l of r.querySelectorAll(`[${de}], [${le}=\\\"route\\\"]`)){if(!qe(l)||m?.inScope(l)===!1)continue;let u=ze(l);if(u.length===0||u.some(s=>d.has(s)))return!0}return!1},async refresh(r){let d=Date.now(),m=n-(d-i);if(m>0)return r.retryAfter?.(m),r.log(\\\"LP0805\\\",`route refresh for revision ${String(r.revision)} refused: the previous one was ${String(d-i)} ms ago`),\\\"refused\\\";i=d;let l=e.document??document,u=e.location??location,s=e.window??window,c=k(r.signal,t),a=h=>{if(r.signal.aborted)return\\\"superseded\\\";let p=c.timedOut()?`route refresh timed out after ${String(t)} ms`:R(h);return r.log(\\\"LP0801\\\",p),\\\"failed\\\"};try{let h=ae();if(h!==void 0){try{let f=h();typeof f?.then!=\\\"function\\\"&&!o&&(o=!0,r.log(\\\"LP0810\\\",Ge)),await f}catch(f){return a(f)}return r.isCurrent()?\\\"partial\\\":\\\"superseded\\\"}let p;try{p=await(e.fetch??fetch)(u.href,{method:\\\"GET\\\",credentials:\\\"same-origin\\\",cache:\\\"no-store\\\",headers:{accept:\\\"text/html\\\",[Ke]:\\\"route\\\"},signal:c.signal})}catch(f){return a(f)}if(r.signal.aborted)return\\\"superseded\\\";if(!p.ok||!(p.headers.get(\\\"content-type\\\")??\\\"\\\").includes(\\\"text/html\\\"))return r.log(\\\"LP0802\\\",`route answered ${String(p.status)} ${p.headers.get(\\\"content-type\\\")??\\\"\\\"}`),\\\"failed\\\";try{let f=await p.text();if(!r.isCurrent())return\\\"superseded\\\";let y=new DOMParser().parseFromString(f,\\\"text/html\\\"),g=s.scrollX,x=s.scrollY;Ve(l,y);let E=Y(l.body);return H(l.body,y.body,{boundary:F,retainBoundary:j,keyAttributes:[ie,I,A],retainChildrenOf:K=>K.hasAttribute(A)}),X(E),s.scrollTo(g,x),\\\"partial\\\"}catch(f){return a(f)}}finally{c.dispose()}}}}function je(e){return{plan:(t,n)=>J(t,n).map(i=>i.element),async render(t,n){let i={rendered:0,failed:0,superseded:0},o={revision:t.revision,receivedAt:t.receivedAt,fields:t.fields,locale:t.locale,collectionSlug:t.collectionSlug,globalSlug:t.globalSlug,signal:t.signal};return await Promise.all(n.map(async r=>{let d=_(r);if(d===null)return;let m;try{m=await e(o,d)}catch(l){m={status:\\\"failed\\\",code:\\\"LP0801\\\",reason:R(l)}}if(!t.isCurrent()||m.status===\\\"superseded\\\"){i.superseded+=1,t.log(\\\"LP0804\\\",`fragment \\\"${d.id}\\\" for revision ${String(o.revision)} discarded as superseded`);return}if(m.status===\\\"rendered\\\"){t.morph(r,m.html),t.rendered(r,d.id,d.key),i.rendered+=1;return}t.failed(r,d.id,d.key,m.code,m.reason),t.isCurrent()&&t.patch(r),i.failed+=1})),i}}}function ce(e){return je(ne(e))}return he(Ye);})();\"].join('');\n","// Auto-generated by scripts/build-runtime.ts — do not edit.\nexport const ROUTE_SOURCE = /* @__PURE__ */ [\"\\\"use strict\\\";var __LIVE_PREVIEW_ROUTE__=(()=>{var S=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var V=Object.getOwnPropertyNames;var j=Object.prototype.hasOwnProperty;var X=(e,t)=>{for(var n in t)S(e,n,{get:t[n],enumerable:!0})},J=(e,t,n,i)=>{if(t&&typeof t==\\\"object\\\"||typeof t==\\\"function\\\")for(let r of V(t))!j.call(e,r)&&r!==n&&S(e,r,{get:()=>t[r],enumerable:!(i=G(t,r))||i.enumerable});return e};var Q=e=>J(S({},\\\"__esModule\\\",{value:!0}),e);var Re={};X(Re,{createRouteStrategy:()=>W});var T=\\\"data-payload-island\\\",xe=`astro-island, [${T}]`,E=\\\"data-payload-owned\\\",Z=\\\"data-payload-morph\\\";function h(e){if(e.tagName.toLowerCase().includes(\\\"-\\\")&&!e.hasAttribute(Z)||ne(e)||e.hasAttribute(E))return!0;let n=e.getAttribute(\\\"contenteditable\\\");return n!==null&&n!==\\\"false\\\"}function ee(e){return e.tagName.toLowerCase()===\\\"astro-island\\\"||e.hasAttribute(T)}function te(e){return e.getAttribute(T)===\\\"patch\\\"}function ne(e){return ee(e)&&!te(e)}var re=[\\\"component-url\\\",\\\"component-export\\\",\\\"renderer-url\\\",\\\"client\\\",\\\"opts\\\",\\\"before-hydration-url\\\"],R=new WeakMap,I=new WeakSet;function N(e){return e.tagName.toLowerCase()===\\\"astro-island\\\"}function M(e){let t=\\\"\\\";for(let n of e.querySelectorAll(\\\"astro-slot, template[data-astro-template]\\\")){if(n.parentElement?.closest(\\\"astro-island\\\")!==e)continue;let i=n.getAttribute(\\\"name\\\")??n.getAttribute(\\\"data-astro-template\\\")??\\\"\\\";t+=`${i}\\\\0${n.innerHTML}\\\\0`}return t}function oe(e){let t=e.ownerDocument.defaultView?.customElements.get(\\\"astro-island\\\");return t!==void 0&&e instanceof t&&Array.isArray(t.observedAttributes)&&t.observedAttributes.includes(\\\"props\\\")}function v(e,t){if(!N(e)||!N(t))return!0;let n=M(t);if(!(re.every(o=>e.getAttribute(o)===t.getAttribute(o))&&(R.get(e)??M(e))===n&&(e.getAttribute(\\\"props\\\")===t.getAttribute(\\\"props\\\")||oe(e))))return R.set(t,n),!1;R.set(e,n);let r=t.getAttribute(\\\"props\\\");return r!==e.getAttribute(\\\"props\\\")&&(e.setAttribute(\\\"ssr\\\",\\\"\\\"),r===null?e.removeAttribute(\\\"props\\\"):e.setAttribute(\\\"props\\\",r)),!0}function D(e){return Array.from(e.querySelectorAll(\\\"astro-island\\\"))}function P(e){for(let t of e)t.isConnected||I.has(t)||(I.add(t),t.dispatchEvent(new CustomEvent(\\\"astro:unmount\\\")))}var ie=new Set([\\\"open\\\",\\\"value\\\",\\\"checked\\\",\\\"selected\\\"]);function C(e,t){for(let n of t.keyAttributes){let i=e.getAttribute(n);if(i!==null&&i.length>0)return`${n}=${i}`}}function w(e,t,n){if(!x(e,t))return t;let i=n.boundary??h,r=i(e),o=i(t);if(r||o)return!r||!o?t:n.retainBoundary?.(e,t)??!0?e:t;let d=ue(e);return ae(e,t),n.retainChildrenOf?.(e,t)!==!0&&le(e,t,n),ce(d),e}function ae(e,t){for(let n of Array.from(e.attributes))t.hasAttribute(n.name)||ie.has(n.name.toLowerCase())||e.removeAttribute(n.name);for(let n of Array.from(t.attributes))e.getAttribute(n.name)!==n.value&&e.setAttribute(n.name,n.value)}function le(e,t,n){let i=de(e,n),r=new Set(i.values()),o=Array.from(e.childNodes).filter(f=>!r.has(f)),d=new Set,p=new Set,l=Array.from(t.childNodes),s=e.firstChild,c=0;for(let f=0;f<l.length;f+=1){let a=l[f],g=null,y=a instanceof Element?C(a,n):void 0;if(y!==void 0&&p.has(y)&&(y=void 0),y!==void 0){p.add(y);let u=i.get(y);if(u!==void 0&&!d.has(u)&&(g=B(u,a,n)===u?u:null,g===null)){u.replaceWith(a),d.add(a),s=a.nextSibling;continue}}else{for(;c<o.length;){let u=o[c];if(c+=1,!d.has(u)){if(x(u,a)){g=B(u,a,n)===u?u:null,g===null&&(e.replaceChild(a,u),d.add(a),s=a.nextSibling);break}if(u instanceof Element){let b=l[f+1];if(!(a instanceof Element)||b!==void 0&&x(u,b)){c-=1;break}e.replaceChild(a,u),d.add(a),s=a.nextSibling;break}if(!(a instanceof Element)){e.replaceChild(a,u),d.add(a),s=a.nextSibling;break}}}if(g===null&&d.has(a))continue}let m=g??a;for(d.add(m);s!==null&&s!==m&&!d.has(s)&&se(s);)s=s.nextSibling;m!==s&&e.insertBefore(m,s),s=m.nextSibling}for(let f of Array.from(e.childNodes))d.has(f)||f.remove()}function B(e,t,n){return e instanceof Element&&t instanceof Element?w(e,t,n):(e.nodeValue!==t.nodeValue&&(e.nodeValue=t.nodeValue),e)}function se(e){return e.nodeType===Node.TEXT_NODE&&(e.nodeValue??\\\"\\\").trim().length===0}function x(e,t){return e.nodeType!==t.nodeType?!1:e instanceof Element&&t instanceof Element?e.tagName===t.tagName&&e.namespaceURI===t.namespaceURI:!0}function de(e,t){let n=new Map,i;for(let r of Array.from(e.children)){let o=C(r,t);if(o!==void 0){if(n.has(o)){i??(i=o.slice(o.indexOf(\\\"=\\\")+1));continue}n.set(o,r)}}return i!==void 0&&t.onDuplicateKey?.(e,i),n}function ue(e){let t=e.ownerDocument.activeElement;if(!(t instanceof HTMLElement)||!e.contains(t))return null;let n=t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement?[t.selectionStart,t.selectionEnd]:null;return{element:t,selection:n}}function ce(e){if(e===null)return;let{element:t,selection:n}=e;if(!(t.ownerDocument.activeElement===t||!t.isConnected))try{t.focus({preventScroll:!0});let[i,r]=n??[null,null];i!==null&&r!==null&&t.setSelectionRange(i,r)}catch{}}var O=\\\"data-payload-key\\\";function _(e){if(e==null)return[];let t=new Set,n=[];for(let i of e.split(/[\\\\s,]+/)){let r=i.trim();r.length===0||t.has(r)||(t.add(r),n.push(r))}return n}var fe=\\\"__livePreviewRouteRefresh\\\";function me(){return typ\",\"eof window>\\\"u\\\"?void 0:window}function F(){return me()?.[fe]}var A=\\\"data-payload-fragment\\\",k=\\\"data-payload-fragment-key\\\";function L(e,t){let n=new AbortController,i=!1,r=()=>{n.abort()};e.addEventListener(\\\"abort\\\",r,{once:!0});let o=setTimeout(()=>{i=!0,n.abort()},t);return{signal:n.signal,timedOut:()=>i,dispose:()=>{clearTimeout(o),e.removeEventListener(\\\"abort\\\",r)}}}function U(e){return e instanceof Error?e.message:String(e)}var H=\\\"data-payload-strategy\\\",$=\\\"data-payload-field\\\",ye=\\\"data-payload-depends\\\",pe=\\\"x-payload-live-preview\\\",ge=8e3,Ee=\\\"route refresh returned no promise; re-applied before the host committed (see LivePreviewRouteRefresh)\\\",be=1e3;function he(e){let t=e.getAttribute(H);return t!==null?t===\\\"route\\\":e.closest(\\\"head\\\")!==null}function Ae(e){let t=e.getAttribute($),n=_(e.getAttribute(ye));return t===null||t.length===0?n:[t,...n]}function K(e){return e.hasAttribute(E)?!1:e.tagName===\\\"META\\\"?e.hasAttribute(\\\"name\\\")||e.hasAttribute(\\\"property\\\"):e.tagName===\\\"LINK\\\"&&e.getAttribute(\\\"rel\\\")===\\\"canonical\\\"}function Se(e,t){let n=Array.from(e.head.children).find(l=>l.tagName===\\\"TITLE\\\"),i=Array.from(t.head.children).find(l=>l.tagName===\\\"TITLE\\\");!n?.hasAttribute(E)&&!i?.hasAttribute(E)&&t.title!==e.title&&(e.title=t.title);let r=Array.from(e.head.children).filter(K),o=Array.from(t.head.children).filter(K),d=Math.min(r.length,o.length);r.slice(0,d).forEach((l,s)=>{let c=o[s];if(c===void 0)return;if(l.tagName===c.tagName){for(let a of Array.from(l.attributes))c.hasAttribute(a.name)||l.removeAttribute(a.name);for(let a of Array.from(c.attributes))l.getAttribute(a.name)!==a.value&&l.setAttribute(a.name,a.value);return}let f=e.importNode(c,!0);l.replaceWith(f),r[s]=f});let p=r.at(-1);for(let l of o.slice(r.length)){let s=e.importNode(l,!0);p===void 0?e.head.append(s):p.after(s),p=s}for(let l of r.slice(o.length))l.remove()}function W(e={}){let t=e.timeoutMs??ge,n=e.minIntervalMs??be,i=-1/0,r=!1;return{plan(o,d,p){for(let l of o.querySelectorAll(`[${$}], [${H}=\\\"route\\\"]`)){if(!he(l)||p?.inScope(l)===!1)continue;let s=Ae(l);if(s.length===0||s.some(c=>d.has(c)))return!0}return!1},async refresh(o){let d=Date.now(),p=n-(d-i);if(p>0)return o.retryAfter?.(p),o.log(\\\"LP0805\\\",`route refresh for revision ${String(o.revision)} refused: the previous one was ${String(d-i)} ms ago`),\\\"refused\\\";i=d;let l=e.document??document,s=e.location??location,c=e.window??window,f=L(o.signal,t),a=g=>{if(o.signal.aborted)return\\\"superseded\\\";let y=f.timedOut()?`route refresh timed out after ${String(t)} ms`:U(g);return o.log(\\\"LP0801\\\",y),\\\"failed\\\"};try{let g=F();if(g!==void 0){try{let m=g();typeof m?.then!=\\\"function\\\"&&!r&&(r=!0,o.log(\\\"LP0810\\\",Ee)),await m}catch(m){return a(m)}return o.isCurrent()?\\\"partial\\\":\\\"superseded\\\"}let y;try{y=await(e.fetch??fetch)(s.href,{method:\\\"GET\\\",credentials:\\\"same-origin\\\",cache:\\\"no-store\\\",headers:{accept:\\\"text/html\\\",[pe]:\\\"route\\\"},signal:f.signal})}catch(m){return a(m)}if(o.signal.aborted)return\\\"superseded\\\";if(!y.ok||!(y.headers.get(\\\"content-type\\\")??\\\"\\\").includes(\\\"text/html\\\"))return o.log(\\\"LP0802\\\",`route answered ${String(y.status)} ${y.headers.get(\\\"content-type\\\")??\\\"\\\"}`),\\\"failed\\\";try{let m=await y.text();if(!o.isCurrent())return\\\"superseded\\\";let u=new DOMParser().parseFromString(m,\\\"text/html\\\"),b=c.scrollX,q=c.scrollY;Se(l,u);let z=D(l.body);return w(l.body,u.body,{boundary:h,retainBoundary:v,keyAttributes:[O,k,A],retainChildrenOf:Y=>Y.hasAttribute(A)}),P(z),c.scrollTo(b,q),\\\"partial\\\"}catch(m){return a(m)}}finally{f.dispose()}}}}return Q(Re);})();\"].join('');\n","// Auto-generated by scripts/build-runtime.ts — do not edit.\nexport const LOADER_SOURCE: string = /* @__PURE__ */ [\"\\\"use strict\\\";(()=>{function o(){if(typ\",\"eof window>\\\"u\\\")return!1;try{return window.self!==window.top}catch{return!0}}function t(){return typ\",\"eof window>\\\"u\\\"?!1:window.opener!=null}function e(){return o()||t()}function i(){let n=document.createElement(\\\"script\\\");n.src=__LP_RUNTIME_SRC__,__LP_RUNTIME_INTEGRITY__!==\\\"\\\"&&(n.integrity=__LP_RUNTIME_INTEGRITY__,n.crossOrigin=\\\"anonymous\\\"),n.async=!0,document.head.appendChild(n)}e()&&i();})();\"].join('');\n","// Auto-generated by scripts/build-runtime.ts — do not edit.\nexport const LOADER_REACT_SOURCE: string = /* @__PURE__ */ [\"\\\"use strict\\\";(()=>{function c(){if(typ\",\"eof window>\\\"u\\\")return!1;try{return window.self!==window.top}catch{return!0}}function s(){return typ\",\"eof window>\\\"u\\\"?!1:window.opener!=null}function r(){return c()||s()}var i=\\\"__livePreviewHydration\\\";function f(){if(typ\",\"eof window>\\\"u\\\")return;let e=window;return e[i]??(e[i]={armed:!1,committed:!1,commits:[],onCommit:void 0,waiters:[]})}function d(){let e=f();if(e===void 0||e.armed)return;e.armed=!0;let n=window,o=n.__REACT_DEVTOOLS_GLOBAL_HOOK__??(n.__REACT_DEVTOOLS_GLOBAL_HOOK__=m()),u=o.onCommitFiberRoot;o.onCommitFiberRoot=function(a,t,...l){try{u?.call(this,a,t,...l)}catch{}e.onCommit===void 0?e.commits.push(t):e.onCommit(t)}}function m(){let e=new Map;return{supportsFiber:!0,renderers:e,inject:n=>{let o=e.size+1;return e.set(o,n),o}}}function p(){let e=document.createElement(\\\"script\\\");e.src=__LP_RUNTIME_SRC__,__LP_RUNTIME_INTEGRITY__!==\\\"\\\"&&(e.integrity=__LP_RUNTIME_INTEGRITY__,e.crossOrigin=\\\"anonymous\\\"),e.async=!0,document.head.appendChild(e)}d();r()&&p();})();\"].join('');\n","/**\n * The inline script's configuration and its positional wire order: the\n * generator writes the tuple, `src/core/runtime.ts` destructures it, and\n * `INLINE_CONFIG_KEYS` is where they agree. Append only, never reorder.\n */\n\nimport type { DefaultsProfile } from '@/types/defaults-profile';\n\nexport interface InlineScriptConfig {\n /** Trusted admin origins, merged with the detected ones. */\n readonly allowedOrigins?: readonly string[];\n /** Payload origin; every update is then re-fetched through the REST API with credentials. Requires `mergeDepth`. */\n readonly serverURL?: string;\n /** REST route prefix used with `serverURL`. Default `/api`. */\n readonly apiRoute?: string;\n /** Population depth used with `serverURL`. Required with `serverURL` unless `defaults: 'v1'`. */\n readonly mergeDepth?: number;\n /** Verbose console logging. Default `false`. */\n readonly debug?: boolean;\n /** Debounce window for incoming updates in ms. Default `50`. */\n readonly debounceMs?: number;\n /** Mount the screen-reader live region. Default `true`. */\n readonly enableA11y?: boolean;\n /** Heartbeat timeout in ms; `0` disables it (default), because the admin posts only on edits. */\n readonly heartbeatMs?: number;\n /** Apply every update regardless of viewport position. Default `false`. */\n readonly disableVisibilityGate?: boolean;\n /** Cache size above which off-screen updates wait for intersection. Default `50`. */\n readonly visibilityGateThreshold?: number;\n /** `rootMargin` of the IntersectionObserver. Default `'200px'`. */\n readonly intersectionRootMargin?: string;\n /** Ignore `document.referrer` as an origin source. Default `true`; `defaults: 'v1'` sets `false`. */\n readonly disableReferrerDetection?: boolean;\n /** Disable the dev-mode localhost matcher (any port on `localhost`/`127.0.0.1`). Default `false`. */\n readonly disableLocalhostMatching?: boolean;\n /** Update only bindings under a matching `data-payload-owner`. Default `false`. */\n readonly scopeBindingsByOwner?: boolean;\n /** Skip bindings whose value did not change. Default `true`; `defaults: 'v1'` sets `false`. */\n readonly skipUnchanged?: boolean;\n /** Scroll the preview to the field being edited. Default `false`. */\n readonly revealEditedField?: boolean;\n /** Which windows may post updates. Default `'parent-or-opener'`; `defaults: 'v1'` sets `'any'`. */\n readonly eventSourcePolicy?: 'any' | 'parent-or-opener';\n /** Sanitizer policy for rich text and HTML writes. Default `'strict'`; `defaults: 'v1'` sets `'compat'`. */\n readonly sanitizerPolicy?: 'compat' | 'strict';\n /** Same-origin path of a fragment endpoint; the script then carries the fragment client ahead of the runtime (ADR 0011). */\n readonly fragmentEndpoint?: string;\n /**\n * Carry the route strategy, so a binding in `<head>` or one marked\n * `data-payload-strategy=\"route\"` refreshes the route. `fragmentEndpoint`\n * implies it — the fragment prelude already contains it. Default `false`.\n */\n readonly routeStrategy?: boolean;\n /**\n * The 2.0 name for `onUnfaithfulPatch`, kept until 3.0. `'route'` means\n * `'escalate'`, `'ignore'` means `'ignore'`.\n *\n * @deprecated Renamed to `onUnfaithfulPatch`.\n */\n readonly onUnboundChange?: 'ignore' | 'route';\n /**\n * What to do when the runtime knows a patch cannot reach what the server\n * would have drawn. `'escalate'` (the default) hands the region to the\n * fragment strategy when a boundary covers it and to the route otherwise, so\n * it needs `fragmentEndpoint` or `routeStrategy` to do anything. `'warn'`\n * reports LP0411 and keeps the patch; `'ignore'` keeps it silently.\n */\n readonly onUnfaithfulPatch?: 'ignore' | 'warn' | 'escalate';\n /**\n * Find bindings by value on the connection's first message (ADR 0014): a\n * scalar whose value is the whole content of exactly one element is bound\n * to it as if `data-payload-field` stood there. Default `'off'`.\n */\n readonly autoBind?: 'off' | 'unique';\n /**\n * The framework that hydrates this page (ADR 0015). Under `'react'` the\n * runtime holds its first write until React has committed the tree that\n * holds the bindings — otherwise React finds markup it did not render,\n * throws `Hydration failed` and regenerates the tree, and the write is gone.\n * Under `'vue'` it holds the write until Vue has mounted the app around them\n * — otherwise Vue's hydration repairs the write back to the server's value,\n * quietly. Under `'sveltekit'` it holds the write until SvelteKit's root has\n * mounted, on a page SvelteKit's client runs on — otherwise Svelte's\n * hydration sets its own text back over it, as quietly. The Next.js, Nuxt\n * and SvelteKit adapters set it on every script they emit; a page built by\n * hand with `generateInlineScript()` may. Omitted: the runtime starts on\n * `DOMContentLoaded`, as on a static page.\n */\n readonly hydration?: 'react' | 'vue' | 'sveltekit';\n /**\n * Which defaults the omitted options fall back to, resolved by the generator\n * rather than the runtime, whose own fallbacks are the 2.0 rows: `'v1'`\n * writes its four runtime rows into their slots (an explicit option still\n * wins) and relaxes the `mergeDepth` check. The resolved value always\n * travels in slot 24, so a reader of the served page knows what an\n * empty slot means instead of guessing it — `pll doctor --v2` reads it. The\n * runtime does not use that value: every row the profile decides is already\n * in its slot. Slot 24 stays fixed as later options are appended.\n */\n readonly defaults?: DefaultsProfile;\n /**\n * Document events fired after a client router committed new markup. Each\n * rebuilds the binding cache and locally reapplies the last accepted state.\n * Adapter integrations set this from their framework lifecycle. It is a\n * low-level generator fact, not a `PreviewAdapterOptions` field. Empty by\n * default.\n */\n readonly softNavigationEvents?: readonly string[];\n /**\n * How a group counts as covered (ADR 0022). `'descendant'`, the 2.x default:\n * one bound path inside it covers all of it. `'declared'`: each changed path\n * inside such a group needs its own binding or a `data-payload-covers`\n * declaration; an uncovered one is an unbound change.\n */\n readonly subfieldCoverage?: 'descendant' | 'declared';\n /**\n * A runtime artifact to embed instead of the full one — today only\n * `LEAN_RUNTIME` from `payload-live-preview/lean`, which leaves out the\n * strategies, the keyed morph, the structural arrays, the item templates, the\n * announcer and auto-binding (about 7 KB gzip less on the page) and reports\n * LP0104 when a page needs one of them.\n *\n * It is an imported value rather than a `profile: 'lean'` string on purpose:\n * a second artifact behind a string option would sit in every build that can\n * reach the generator; measured, it grew each adapter entry by the artifact's\n * whole size. This way the bytes follow the import.\n *\n * Not serialized: it decides which bytes are emitted, not how they behave.\n */\n readonly runtime?: RuntimeArtifact;\n}\n\n/**\n * A runtime build this package produces. `source` is the IIFE the page runs;\n * the two digests describe the same bytes as a servable asset, so asset\n * delivery can hash-name and SRI-verify whichever artifact was chosen without\n * hashing anything at request time.\n */\nexport interface RuntimeArtifact {\n readonly profile: 'lean';\n readonly source: string;\n /** Short content hash, for the asset's file name. */\n readonly contentHash: string;\n /** `sha384-…`, for the bootstrap's `integrity` attribute. */\n readonly integrity: string;\n}\n\n/** Keys that travel in the wire tuple, in slot order. */\nexport const INLINE_CONFIG_KEYS = [\n 'allowedOrigins',\n 'serverURL',\n 'apiRoute',\n 'mergeDepth',\n 'debug',\n 'debounceMs',\n 'enableA11y',\n 'heartbeatMs',\n 'disableVisibilityGate',\n 'visibilityGateThreshold',\n 'intersectionRootMargin',\n 'disableReferrerDetection',\n 'disableLocalhostMatching',\n 'scopeBindingsByOwner',\n 'skipUnchanged',\n 'eventSourcePolicy',\n 'sanitizerPolicy',\n 'fragmentEndpoint',\n 'revealEditedField',\n 'routeStrategy',\n 'onUnboundChange',\n 'onUnfaithfulPatch',\n 'autoBind',\n 'hydration',\n 'defaults',\n 'softNavigationEvents',\n 'subfieldCoverage',\n] as const satisfies readonly Exclude<keyof InlineScriptConfig, 'runtime'>[];\n","/**\n * Wraps the build-time runtime IIFE with the consumer's configuration, and\n * places at most one strategy prelude ahead of it.\n */\n\nimport { warnDeprecatedOptions } from '@/types/dev-warning';\nimport { assertMergeDepthExplicit } from '@/types/merge-depth';\nimport { V1_RUNTIME_DEFAULTS } from '@/types/defaults-profile';\nimport { RUNTIME_SOURCE, RUNTIME_BUILD_INFO, type RuntimeBuildInfo } from './runtime.generated';\nimport { FRAGMENT_SOURCE } from './fragment.generated';\nimport { ROUTE_SOURCE } from './route.generated';\nimport { LOADER_SOURCE } from './loader.generated';\nimport { LOADER_REACT_SOURCE } from './loader-react.generated';\nimport { INLINE_CONFIG_KEYS, type InlineScriptConfig } from '@/types/inline-config';\n\nexport type { InlineScriptConfig, RuntimeArtifact } from '@/types/inline-config';\n\nfunction assertBuilt(source: string, artifact: string): void {\n if (source.length === 0) {\n throw new Error(\n `[live-preview] ${artifact} is empty. Run \\`npm run build:runtime\\` before bundling.`,\n );\n }\n}\n\n/** The inline script body without `<script>` tags; see `wrapWithScriptTag()`. */\nexport function generateInlineScript(config: InlineScriptConfig = {}): string {\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- read to warn about it\n warnDeprecatedOptions({ defaults: config.defaults, onUnboundChange: config.onUnboundChange });\n const runtime = runtimeFor(config);\n return [configStatement(config), ...strategyPrelude(config), runtime].join('\\n');\n}\n\n/**\n * The full runtime, or the artifact the consumer imported. The lean one leaves\n * out the strategies (docs/options.md), so the two preludes are refused with it\n * rather than emitted against a runtime that could never answer them.\n */\nfunction runtimeFor(config: InlineScriptConfig): string {\n const artifact = config.runtime;\n if (artifact === undefined) {\n assertBuilt(RUNTIME_SOURCE, 'runtime.generated.ts');\n return RUNTIME_SOURCE;\n }\n assertBuilt(artifact.source, `the ${artifact.profile} runtime`);\n if (config.fragmentEndpoint != null || config.routeStrategy === true) {\n throw new Error(\n `[live-preview] the ${artifact.profile} runtime and the fragment or route strategy exclude ` +\n 'each other: it carries no strategy runner, so the prelude would have nothing to talk to. ' +\n 'Drop the runtime option, or drop `fragmentEndpoint`/`routeStrategy`.',\n );\n }\n return artifact.source;\n}\n\n/**\n * At most one prelude, and the fragment one wins: it already contains the\n * route strategy, so emitting both would ship that code twice and leave two\n * globals where the runtime expects the fragment one to be authoritative.\n */\nfunction strategyPrelude(config: InlineScriptConfig): readonly string[] {\n if (config.fragmentEndpoint != null) {\n assertBuilt(FRAGMENT_SOURCE, 'fragment.generated.ts');\n return [FRAGMENT_SOURCE];\n }\n if (config.routeStrategy === true) {\n assertBuilt(ROUTE_SOURCE, 'route.generated.ts');\n return [ROUTE_SOURCE];\n }\n return [];\n}\n\n// `__LIVE_PREVIEW_CONFIG__` is a public presence signal: consumers' integration\n// tests grep for it, so the name outlives any refactor.\nfunction configStatement(config: InlineScriptConfig): string {\n return `var __LIVE_PREVIEW_CONFIG__=${buildConfigLiteral(config)};`;\n}\n\n/** The positional wire literal the runtime destructures; shared by the inline script and the loader. */\nfunction buildConfigLiteral(config: InlineScriptConfig): string {\n assertMergeDepthExplicit(config);\n const profile = profileSlots(config);\n // `null` counts as omitted, and omitted slots stay empty (`[,,1]`): a JSON\n // `null` would bypass the runtime's destructuring defaults. Defaults remains\n // in its established slot 24; later rows are append-only and may be absent.\n const values: unknown[] = INLINE_CONFIG_KEYS.map((key) => config[key] ?? profile[key]);\n while (values.at(-1) === undefined) values.pop();\n // `<` is escaped so a value containing `</script>` cannot end the tag.\n return `[${values\n .map((value) => (value === undefined ? '' : JSON.stringify(value)))\n .join(',')}]`.replace(/</g, '\\\\u003C');\n}\n\n/**\n * What the `defaults` profile puts on the wire. The runtime's own fallbacks are\n * the 2.0 rows, so `'v2'` fills nothing and `'v1'` has to write its four; the\n * profile itself goes into slot 24 either way, so a reader of the served page\n * learns which generation an empty slot belongs to (ADR 0007).\n */\nfunction profileSlots(config: InlineScriptConfig): Partial<InlineScriptConfig> {\n const defaults = config.defaults ?? 'v2';\n return defaults === 'v1' ? { ...V1_RUNTIME_DEFAULTS, defaults } : { defaults };\n}\n\n/** Where the runtime asset lives, and how the browser should verify it. */\nexport interface LoaderScriptTarget {\n /** URL the bootstrap appends. Same-origin or absolute; hashed by the caller. */\n readonly runtimeSrc: string;\n /** Subresource-integrity value, e.g. `sha384-…`; empty drops the check and the `crossorigin` it requires. */\n readonly integrity?: string;\n}\n\n/**\n * The static-delivery bootstrap: the configuration plus a few hundred bytes\n * appending the runtime inside a preview. The asset stays configuration-free.\n */\nexport function generateLoaderScript(\n config: InlineScriptConfig = {},\n target: LoaderScriptTarget,\n): string {\n const bootstrap = loaderFor(config);\n if (target.runtimeSrc === '') {\n throw new Error('[live-preview] generateLoaderScript needs a runtimeSrc.');\n }\n const encode = (value: string): string => JSON.stringify(value).replace(/</gu, '\\\\u003C');\n return [\n configStatement(config),\n `var __LP_RUNTIME_SRC__=${encode(target.runtimeSrc)};`,\n `var __LP_RUNTIME_INTEGRITY__=${encode(target.integrity ?? '')};`,\n ...strategyPrelude(config),\n bootstrap,\n ].join('\\n');\n}\n\n/**\n * The bootstrap, or the one armed for React's first commit (ADR 0015 F2): the\n * inline runtime is the first script in `<head>` and arms the signal itself,\n * while a fetched asset may evaluate after `react-dom` has, when it is too\n * late — so on a page that declares React the bootstrap arms before it\n * fetches. One script either way, never a prelude ahead of the plain one. A\n * page that declares Vue takes the plain one: Vue's mount leaves state on the\n * container that a late runtime can still read (`core/hydration-vue`).\n */\nfunction loaderFor(config: InlineScriptConfig): string {\n if (config.hydration === 'react') {\n assertBuilt(LOADER_REACT_SOURCE, 'loader-react.generated.ts');\n return LOADER_REACT_SOURCE;\n }\n assertBuilt(LOADER_SOURCE, 'loader.generated.ts');\n return LOADER_SOURCE;\n}\n\n/** Wrap a script body in `<script>`, with the CSP nonce attribute when given. */\nexport function wrapWithScriptTag(body: string, options: { nonce?: string } = {}): string {\n const nonceAttr = options.nonce !== undefined ? ` nonce=\"${assertNonce(options.nonce)}\"` : '';\n return `<script${nonceAttr}>${body}</script>`;\n}\n\n/** @internal */\nexport function runtimeBuildInfo(): RuntimeBuildInfo {\n return RUNTIME_BUILD_INFO;\n}\n\n/**\n * A nonce as CSP defines it: base64url characters only. Returned unchanged so\n * a caller can inline the result. Not re-exported from the package barrel — it\n * is shared with the adapters, not part of the public surface.\n */\nexport function assertNonce(nonce: string): string {\n if (!/^[A-Za-z0-9+/=_-]+$/.test(nonce)) {\n throw new RangeError('nonce contains characters CSP does not allow');\n }\n return nonce;\n}\n","/**\n * The runtime as a servable, cacheable asset — the request-time half of\n * `mode: 'loader'`.\n *\n * Name and integrity are constants of the package build (the artifact carries\n * both), so nothing here hashes anything per request and this module stays\n * reachable from a browser entry: no `node:crypto`, no Node builtins at all.\n *\n * The content hash is in the file name, which is what makes `immutable` honest:\n * different bytes are a different URL, so a year-long cache can never serve the\n * wrong runtime. A request for any other name under the mount path is a 404\n * rather than a redirect to the current one — a client asking for a hash we no\n * longer have is asking for bytes we cannot produce.\n */\n\nimport { RUNTIME_CONTENT_HASH, RUNTIME_INTEGRITY, RUNTIME_SOURCE } from '@inline/runtime.generated';\nimport type { RuntimeArtifact } from '@/types/inline-config';\n\n/** Where the asset route is mounted when nothing says otherwise. */\nexport const DEFAULT_ASSET_PATH = '/payload-live-preview';\n\nexport interface RuntimeAssetOptions {\n /**\n * Path the asset route is mounted at. Must match on both sides — the\n * bootstrap requests it and the route serves it. Default\n * `/payload-live-preview`; give it the framework's own base path as a prefix\n * when the app is not served from the site root.\n */\n readonly assetPath?: string;\n /** The artifact to serve; the default runtime when omitted. */\n readonly runtime?: RuntimeArtifact;\n}\n\nexport interface RuntimeAsset {\n /** The file name alone, `runtime.<hash>.js`. */\n readonly fileName: string;\n /** The absolute path the bootstrap requests, mount path included. */\n readonly urlPath: string;\n /** `sha384-…`, for the bootstrap's `integrity` attribute. */\n readonly integrity: string;\n /** The bytes to serve. */\n readonly source: string;\n}\n\n/**\n * One leading slash, no trailing one, so joining is a single concatenation.\n *\n * Trimmed by index rather than by `/^\\/+|\\/+$/`: that expression backtracks over\n * a long run of slashes and costs quadratic time on a path the consumer\n * configures (CodeQL js/polynomial-redos).\n */\nfunction normalizePath(path: string): string {\n let start = 0;\n let end = path.length;\n while (start < end && path[start] === '/') start += 1;\n while (end > start && path[end - 1] === '/') end -= 1;\n const trimmed = path.slice(start, end);\n return trimmed === '' ? '' : `/${trimmed}`;\n}\n\n/** Describe the asset for these options; deterministic per package version and artifact. */\nexport function runtimeAsset(options: RuntimeAssetOptions = {}): RuntimeAsset {\n const artifact = options.runtime;\n const hash = artifact?.contentHash ?? RUNTIME_CONTENT_HASH;\n const fileName = `runtime.${hash}.js`;\n return {\n fileName,\n urlPath: `${normalizePath(options.assetPath ?? DEFAULT_ASSET_PATH)}/${fileName}`,\n integrity: artifact?.integrity ?? RUNTIME_INTEGRITY,\n source: artifact?.source ?? RUNTIME_SOURCE,\n };\n}\n\n/**\n * A year, the longest `max-age` browsers honour, plus `immutable` so a reload\n * does not revalidate either. Safe only because the hash is in the name.\n */\nexport const ASSET_CACHE_CONTROL = 'public, max-age=31536000, immutable';\n\n/** The headers the asset is served with, on every framework. */\nexport function runtimeAssetHeaders(): Record<string, string> {\n return {\n 'content-type': 'text/javascript; charset=utf-8',\n 'cache-control': ASSET_CACHE_CONTROL,\n // The bootstrap sets `crossorigin=\"anonymous\"` for the integrity check;\n // same-origin needs no CORS header, and a CDN in front of it gets one that\n // says the bytes are public.\n 'access-control-allow-origin': '*',\n // Nothing here is HTML, and a browser that sniffs it as such would be wrong.\n 'x-content-type-options': 'nosniff',\n };\n}\n\n/**\n * The response for one requested URL: the asset when the file name is the one\n * this build produces, 404 otherwise.\n *\n * Only the file name is checked, never the mount path. Where the route sits is\n * the framework's business — the consumer put the file there — while the name\n * is ours, and it is the name that decides whether the bytes a client cached\n * for a year are still the bytes we would send.\n */\nexport function runtimeAssetResponse(url: string, options: RuntimeAssetOptions = {}): Response {\n const asset = runtimeAsset(options);\n // A query string is a cache-buster and must still resolve.\n const path = url.split('?')[0] ?? '';\n const requested = path.slice(path.lastIndexOf('/') + 1);\n if (requested !== asset.fileName) {\n return new Response('Not found', {\n status: 404,\n headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' },\n });\n }\n return new Response(asset.source, { status: 200, headers: runtimeAssetHeaders() });\n}\n","/**\n * Placing the runtime's script tag inside an HTML document, by text: the\n * adapters see a rendered string or a streamed chunk, never a DOM.\n */\n\n/** The opening `<head>` tag the runtime script is inserted into. */\nexport const HEAD_INSERT = /<head(\\s[^>]*)?>/i;\n\n/** `text/html` with or without parameters. */\nexport const HTML_CONTENT_TYPE = /text\\/html/i;\n\n// Browsers prescan only the first 1024 bytes for the encoding; a script\n// inserted ahead of `<meta charset>` would push it out of that window.\nconst META_CHARSET =\n /<meta\\s+(?:[^>]*\\s)?(?:charset\\s*=|http-equiv\\s*=\\s*[\"']?content-type)[^>]*>/i;\n\n/**\n * `html` with the script tag after `<meta charset>`, else right after\n * `<head>`; `undefined` when there is no `<head>` to insert into.\n */\nexport function injectIntoHead(html: string, scriptTag: string): string | undefined {\n const head = HEAD_INSERT.exec(html);\n if (head === null) return undefined;\n const headEnd = head.index + head[0].length;\n const headClose = html.indexOf('</head', headEnd);\n const meta = META_CHARSET.exec(html.slice(headEnd, headClose === -1 ? undefined : headClose));\n const at = meta === null ? headEnd : headEnd + meta.index + meta[0].length;\n return `${html.slice(0, at)}${scriptTag}${html.slice(at)}`;\n}\n","/**\n * The options the policy reads, and what they resolve to: the `defaults`\n * profile fills what an adapter left unset, and the inline-script config\n * carries only what was given so the runtime's own defaults stay the single\n * source of them.\n */\n\nimport type { generateInlineScript } from '@inline/generator';\nimport {\n adapterDefaultsFor,\n runtimeDefaultsFor,\n V2_RUNTIME_DEFAULTS,\n} from '@/types/defaults-profile';\nimport { warnDeprecatedOptions } from '@/types/dev-warning';\nimport { assertMergeDepthExplicit } from '@/types/merge-depth';\nimport type { InlineScriptConfig } from '@/types/inline-config';\nimport type { PreviewSignal } from './preview-request';\nimport type { PreviewAdapterOptions } from './options';\n\n/** The structural subset of any adapter's options the policy reads; hooks are bound per request. */\nexport type PreviewPolicyOptions = PreviewAdapterOptions<never>;\n\n/** The options after the `defaults` profile: explicit options win, the profile fills the rest. */\nexport interface ResolvedPolicyOptions {\n readonly strict: boolean;\n readonly previewSignals: readonly PreviewSignal[] | undefined;\n readonly skipUnchanged: boolean | undefined;\n readonly disableReferrerDetection: boolean | undefined;\n readonly disableLocalhostMatching: boolean | undefined;\n readonly eventSourcePolicy: 'any' | 'parent-or-opener' | undefined;\n readonly sanitizerPolicy: 'compat' | 'strict' | undefined;\n}\n\nexport function resolvePolicyOptions(options: PreviewPolicyOptions): ResolvedPolicyOptions {\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- read to warn about it\n warnDeprecatedOptions({ defaults: options.defaults, onUnboundChange: options.onUnboundChange });\n const adapter = adapterDefaultsFor(options.defaults);\n const runtime = runtimeDefaultsFor(options.defaults);\n // The inline runtime already defaults to the v2 rows, so only a differing\n // profile — an explicit `defaults: 'v1'` — needs a row on the wire.\n const runtimeRow = <K extends keyof typeof V2_RUNTIME_DEFAULTS>(\n key: K,\n ): (typeof V2_RUNTIME_DEFAULTS)[K] | undefined =>\n runtime[key] !== V2_RUNTIME_DEFAULTS[key] ? runtime[key] : undefined;\n return {\n strict: options.strict ?? adapter.strict,\n previewSignals: options.previewSignals ?? adapter.previewSignals,\n skipUnchanged: options.skipUnchanged ?? runtimeRow('skipUnchanged'),\n disableReferrerDetection:\n options.disableReferrerDetection ?? runtimeRow('disableReferrerDetection'),\n disableLocalhostMatching: options.disableLocalhostMatching,\n eventSourcePolicy: options.eventSourcePolicy ?? runtimeRow('eventSourcePolicy'),\n sanitizerPolicy: options.sanitizerPolicy ?? runtimeRow('sanitizerPolicy'),\n };\n}\n\n/**\n * What an adapter knows about the page beyond what a project configured: its\n * hydration owner and the document events its router fires after a commit.\n * These are facts, not project options.\n */\nexport type PageFacts = Pick<InlineScriptConfig, 'hydration' | 'softNavigationEvents'>;\n\n/** The inline-script configuration; only given options travel, so the runtime's own defaults stay the single source of them. */\nexport function inlineScriptConfig(\n options: PreviewPolicyOptions,\n facts: PageFacts = {},\n): Parameters<typeof generateInlineScript>[0] {\n assertMergeDepthExplicit(options);\n const resolved = resolvePolicyOptions(options);\n return {\n // The generator names it in slot 24 and, under `'v1'`, reads an\n // omitted `mergeDepth` as deliberate.\n ...(options.defaults !== undefined ? { defaults: options.defaults } : {}),\n ...(options.allowedOrigins !== undefined ? { allowedOrigins: options.allowedOrigins } : {}),\n ...(options.serverURL !== undefined ? { serverURL: options.serverURL } : {}),\n ...(options.apiRoute !== undefined ? { apiRoute: options.apiRoute } : {}),\n ...(options.mergeDepth !== undefined ? { mergeDepth: options.mergeDepth } : {}),\n ...(options.revealEditedField !== undefined\n ? { revealEditedField: options.revealEditedField }\n : {}),\n ...(options.debug !== undefined ? { debug: options.debug } : {}),\n ...(options.debounceMs !== undefined ? { debounceMs: options.debounceMs } : {}),\n ...(options.heartbeatMs !== undefined ? { heartbeatMs: options.heartbeatMs } : {}),\n ...(resolved.skipUnchanged !== undefined ? { skipUnchanged: resolved.skipUnchanged } : {}),\n ...(options.scopeBindingsByOwner !== undefined\n ? { scopeBindingsByOwner: options.scopeBindingsByOwner }\n : {}),\n ...(resolved.disableReferrerDetection !== undefined\n ? { disableReferrerDetection: resolved.disableReferrerDetection }\n : {}),\n ...(resolved.disableLocalhostMatching !== undefined\n ? { disableLocalhostMatching: resolved.disableLocalhostMatching }\n : {}),\n ...(resolved.eventSourcePolicy !== undefined\n ? { eventSourcePolicy: resolved.eventSourcePolicy }\n : {}),\n ...(resolved.sanitizerPolicy !== undefined\n ? { sanitizerPolicy: resolved.sanitizerPolicy }\n : {}),\n ...(options.runtime !== undefined ? { runtime: options.runtime } : {}),\n ...(options.fragments !== undefined ? { fragmentEndpoint: options.fragments.endpoint } : {}),\n // Only when no endpoint is configured: that prelude carries the route\n // strategy already, and asking for both would emit the larger one twice.\n ...(options.routeStrategy === true && options.fragments === undefined\n ? { routeStrategy: true }\n : {}),\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- the 2.0 name is carried through exactly here\n ...(options.onUnboundChange !== undefined ? { onUnboundChange: options.onUnboundChange } : {}),\n ...(options.onUnfaithfulPatch !== undefined\n ? { onUnfaithfulPatch: options.onUnfaithfulPatch }\n : {}),\n ...(options.autoBind !== undefined ? { autoBind: options.autoBind } : {}),\n ...(options.subfieldCoverage !== undefined\n ? { subfieldCoverage: options.subfieldCoverage }\n : {}),\n ...(facts.hydration !== undefined ? { hydration: facts.hydration } : {}),\n ...(facts.softNavigationEvents !== undefined\n ? { softNavigationEvents: facts.softNavigationEvents }\n : {}),\n };\n}\n","/**\n * Applying a decision to a fetch-style `Response`, and the request-side\n * glue every adapter repeats: hook binding and the manual script tag.\n */\n\nimport { generateInlineScript, generateLoaderScript, wrapWithScriptTag } from '@inline/generator';\nimport { runtimeAsset } from './runtime-asset';\nimport { HTML_CONTENT_TYPE, injectIntoHead } from './html-inject';\nimport { inlineScriptConfig, type PageFacts, type PreviewPolicyOptions } from './policy-options';\nimport type { PreviewDecision, PreviewDecisionHooks, PreviewPolicy } from './policy';\nimport type { PreviewAdapterOptions } from './options';\n\n/** The header surface shared by `Headers` and a Node response. */\nexport interface HeaderSink {\n get(name: string): string | null | undefined;\n set(name: string, value: string): void;\n}\n\n/** Bind an adapter's per-request hooks to `request`. */\nexport function bindDecisionHooks<Req>(\n policy: PreviewPolicy,\n options: Pick<PreviewAdapterOptions<Req>, 'authorizePreview' | 'shouldInject'>,\n request: Req,\n): PreviewDecisionHooks {\n return {\n shouldInject: () => options.shouldInject?.(request) ?? true,\n ...(policy.authorizes ? { authorize: () => options.authorizePreview?.(request) } : {}),\n };\n}\n\n/**\n * The script body alone, for a consumer that builds the element itself — a JSX\n * framework cannot render a tag that arrives as a string.\n *\n * The one place delivery is decided, so every adapter answers `delivery:\n * 'asset'` the same way: the bootstrap plus the URL and integrity of whichever\n * artifact was configured, and never the runtime itself.\n */\nexport function renderScriptBody(options: PreviewPolicyOptions, facts: PageFacts = {}): string {\n const config = inlineScriptConfig(options, facts);\n if (options.delivery !== 'asset') return generateInlineScript(config);\n const asset = runtimeAsset(options);\n return generateLoaderScript(config, { runtimeSrc: asset.urlPath, integrity: asset.integrity });\n}\n\n/** The `<script>` tag for manual embedding, with `nonce` when given. */\nexport function renderScriptTag(\n options: PreviewPolicyOptions & { readonly nonce?: string },\n facts: PageFacts = {},\n): string {\n const body = renderScriptBody(options, facts);\n return wrapWithScriptTag(body, options.nonce !== undefined ? { nonce: options.nonce } : {});\n}\n\n/** A changed response must never be stored as the public page, nor shared across sessions. */\nexport function markUncacheable(headers: HeaderSink): void {\n const cacheControl = headers.get('cache-control') ?? '';\n if (!/\\bno-store\\b/i.test(cacheControl)) headers.set('cache-control', 'private, no-store');\n const vary = (headers.get('vary') ?? '').trim();\n const listed = vary.split(',').map((token) => token.trim().toLowerCase());\n if (listed.includes('*') || listed.includes('cookie')) return;\n headers.set('vary', vary.length === 0 ? 'Cookie' : `${vary}, Cookie`);\n}\n\n/**\n * `response` with the script tag in its `<head>`, untouched when it has no\n * body (204/304/HEAD), is not HTML, or has no `<head>`. Headers describing\n * the old body — length, encoding, ETag — are dropped.\n */\nexport async function injectIntoResponse(response: Response, scriptTag: string): Promise<Response> {\n if (response.body === null) return response;\n if (!HTML_CONTENT_TYPE.test(response.headers.get('content-type') ?? '')) return response;\n const injected = injectIntoHead(await response.clone().text(), scriptTag);\n if (injected === undefined) return response;\n const headers = new Headers(response.headers);\n headers.delete('content-length');\n headers.delete('content-encoding');\n headers.delete('etag');\n return new Response(injected, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n\n/** Run `apply` on the response headers, cloning first when they are immutable (responses passed through from `fetch()`). */\nexport function withHeaders(response: Response, apply: (headers: Headers) => void): Response {\n try {\n apply(response.headers);\n return response;\n } catch {\n const headers = new Headers(response.headers);\n apply(headers);\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n }\n}\n\n/**\n * The header side of a decision on any sink: the merged CSP for its mode,\n * then the cache headers — those also when the mode is off, because an\n * injected body alone already makes the response private.\n */\nexport function applyCspHeaders(\n headers: HeaderSink,\n policy: PreviewPolicy,\n decision: PreviewDecision,\n nonce: string,\n): void {\n const mode = decision.cspMode;\n if (mode !== false) {\n const existing = headers.get('content-security-policy') ?? '';\n headers.set('content-security-policy', policy.csp(existing, nonce, mode));\n }\n markUncacheable(headers);\n}\n\n/** Set the merged CSP header for `mode` and mark the response uncacheable. */\nexport function withCspHeader(\n response: Response,\n policy: PreviewPolicy,\n decision: PreviewDecision,\n nonce: string,\n): Response {\n return withHeaders(response, (headers) => {\n applyCspHeaders(headers, policy, decision, nonce);\n });\n}\n\n/** Apply a decision end to end: inject, then CSP and cache headers. The response is returned as-is when nothing changes. */\nexport async function applyDecision(\n response: Response,\n policy: PreviewPolicy,\n decision: PreviewDecision,\n nonce: string,\n): Promise<Response> {\n if (!decision.inject && decision.cspMode === false) return response;\n const injected = decision.inject\n ? await injectIntoResponse(response, policy.scriptTag(nonce))\n : response;\n return withCspHeader(injected, policy, decision, nonce);\n}\n","/**\n * Server-side preview-intent detection. Every signal here is client-controlled:\n * a positive result is a delivery hint, never proof of identity or permission.\n * Verify with `authorizePreviewRequest()` before anything privileged.\n */\n\nimport { warnOnce } from '@/types/dev-warning';\n\n/** `query`: `?preview=true`; `fetch-dest`: `Sec-Fetch-Dest: iframe`; `referer`: an admin-origin Referer. */\nexport type PreviewSignal = 'query' | 'fetch-dest' | 'referer';\n\nexport interface PreviewRequestOptions {\n /** Which signals count. Default: all three. `['query']` is the adapters' 2.0 default. */\n readonly signals?: readonly PreviewSignal[];\n /** Query parameters (value `true` or `1`) that signal intent. Default `['preview', 'draft', 'livePreview']`. */\n readonly queryParams?: readonly string[];\n /** Admin origins whose Referer signals intent, e.g. `['https://cms.example.com']` — the adapters' option of the same name. */\n readonly allowedOrigins?: readonly string[];\n /** @deprecated Use `allowedOrigins`; removed in 3.0. Ignored when `allowedOrigins` is given. */\n readonly adminOrigins?: readonly string[];\n}\n\nconst DEFAULT_QUERY_PARAMS = ['preview', 'draft', 'livePreview'] as const;\n\n/** The request surface the predicate reads; `Request` satisfies it, Nitro/H3 events need a shim. */\nexport interface PreviewRequestLike {\n readonly url: string;\n readonly headers: { get(name: string): string | null };\n}\n\n/** Whether `request` carries live-preview intent. Intent, not authorization. */\nexport function hasPreviewIntent(\n request: PreviewRequestLike,\n options: PreviewRequestOptions = {},\n): boolean {\n const signals = new Set<PreviewSignal>(options.signals ?? ['query', 'fetch-dest', 'referer']);\n const queryParams = options.queryParams ?? DEFAULT_QUERY_PARAMS;\n\n if (signals.has('query')) {\n let url: URL | undefined;\n try {\n url = new URL(request.url);\n } catch {\n url = undefined;\n }\n if (url !== undefined) {\n for (const param of queryParams) {\n // The last value of a repeated key, as Next.js matches a `has` rule:\n // `withLivePreview()` marks the response by that reading, and the two\n // have to agree on `?preview=true&preview=0`.\n const value = url.searchParams.getAll(param).at(-1);\n if (value === 'true' || value === '1') return true;\n }\n }\n }\n\n if (signals.has('fetch-dest') && request.headers.get('sec-fetch-dest') === 'iframe') {\n return true;\n }\n\n // The 1.x spelling is honoured until 3.0; the canonical name wins when both are given.\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- the alias is read exactly here\n const alias = options.adminOrigins;\n if (alias !== undefined) {\n warnOnce(\n 'admin-origins',\n '`hasPreviewIntent({ adminOrigins })` is removed in 3.0: name the option `allowedOrigins`; ' +\n '`pll migrate` renames it (ADR 0026).',\n );\n }\n const configured = options.allowedOrigins ?? alias ?? [];\n const adminOrigins = signals.has('referer') ? configured : [];\n if (adminOrigins.length > 0) {\n const referer = request.headers.get('referer');\n if (referer !== null) {\n try {\n const refererOrigin = new URL(referer).origin;\n for (const adminOrigin of adminOrigins) {\n try {\n if (new URL(adminOrigin).origin === refererOrigin) return true;\n } catch {\n // A malformed configured origin matches nothing.\n }\n }\n } catch {\n // A malformed referer is not a signal.\n }\n }\n }\n\n return false;\n}\n","/**\n * The verdict shape every authorization strategy produces, and the one error\n * class that is allowed to escape it. Kept apart from the strategies so the\n * adapters can import the error without pulling in HMAC or session code.\n */\n\nimport type { AuthorizedPreviewContext } from '@/types/authorized-preview';\n\n/** Why a request was refused. `'authorized'` is the one non-refusal. */\nexport type PreviewAuthorizationOutcome =\n | 'authorized'\n | 'missing-credential'\n | 'invalid'\n | 'expired'\n | 'wrong-audience'\n | 'wrong-path'\n | 'wrong-locale'\n | 'wrong-purpose'\n | 'replayed'\n | 'unavailable';\n\n/** The result of `authorizePreviewRequest()`: a verdict, never an exception. */\nexport type PreviewAuthorization =\n | {\n readonly authorized: true;\n readonly outcome: 'authorized';\n readonly context: AuthorizedPreviewContext;\n }\n | {\n readonly authorized: false;\n readonly outcome: Exclude<PreviewAuthorizationOutcome, 'authorized'>;\n readonly context: null;\n };\n\n/** The request shape every strategy reads: a URL and a header getter. */\nexport interface PreviewAuthorizationRequest {\n readonly url: string;\n readonly headers: { get(name: string): string | null };\n /** Request lifetime, when supplied by the caller. Session fetches follow it. */\n readonly signal?: AbortSignal;\n}\n\n/**\n * A strategy was misconfigured — raised on first use and re-thrown by the\n * adapters rather than reported as `'unavailable'`, so it fails loudly.\n */\nexport class PreviewConfigurationError extends Error {\n override readonly name = 'PreviewConfigurationError';\n}\n\n/** Recognises the error across bundles, where `instanceof` sees a different class copy. */\nexport function isPreviewConfigurationError(error: unknown): error is PreviewConfigurationError {\n return (\n error instanceof PreviewConfigurationError ||\n (error instanceof Error && error.name === 'PreviewConfigurationError')\n );\n}\n\nexport function refused(\n outcome: Exclude<PreviewAuthorizationOutcome, 'authorized'>,\n): PreviewAuthorization {\n return { authorized: false, outcome, context: null };\n}\n","/**\n * The authorized preview context's shape and brand, in the leaf `types` domain\n * so producer and consumers recognise the same context. See ADR 0006.\n */\n\n/**\n * The brand key, in the type and on the object.\n *\n * This was a `unique symbol` until 2026-08-30. A `unique symbol` is nominal per\n * *declaration*, and the published entries each carry their own declaration\n * file — so `AuthorizedPreviewContext` from the root barrel was a different\n * type from the one in `./server` or in an adapter, and the documented flow\n * (authorize once, hand the context to the adapter hook and to the draft read)\n * did not type-check in any combination a consumer can write.\n *\n * That is the same trap the runtime brand below already avoids by using\n * `Symbol.for` rather than `Symbol()`; the lesson simply had not reached the\n * type. A shared string literal is identical in every bundle for the same\n * reason a registry symbol is.\n *\n * It is not what makes a context trustworthy. `isAuthorizedPreviewContext`\n * decides that, on the registry symbol and on `Object.isFrozen`, and every\n * consumption point calls it — the adapter policy, the draft read and the\n * binding emitter. Writing this key by hand buys nothing.\n */\nexport const AUTHORIZED_PREVIEW_BRAND_KEY = 'payload-live-preview.authorized-preview-context';\n\nexport type PreviewAuthorizationStrategyName = 'payload-session' | 'signed-token' | 'verifier';\n\n/** One server-authorized Payload document, not a query selected by the browser. */\nexport type AuthorizedPreviewDocument =\n | { readonly kind: 'collection'; readonly slug: string; readonly id: string | number }\n | { readonly kind: 'global'; readonly slug: string };\n\n/** Opt-in data capability, enforced by the fragment endpoint and `definePreview`. */\nexport interface AuthorizedPreviewPayloadScope {\n /** Payload base URL, distinct from the preview site's audience. */\n readonly serverURL: string;\n /** REST prefix, default `/api`. */\n readonly apiRoute?: string;\n readonly document: AuthorizedPreviewDocument;\n /** Maximum requested population depth, not a field-level ACL. */\n readonly maxDepth: number;\n}\n\n/** What a context is bound to; every field is optional because every strategy binds differently. */\nexport interface AuthorizedPreviewScope {\n /** The site origin the credential was issued for. */\n readonly audience?: string;\n /** The request pathname the credential is valid for. */\n readonly path?: string;\n readonly locale?: string;\n /** Requires a finite context expiry. Unscoped contexts keep their existing behavior. */\n readonly payload?: AuthorizedPreviewPayloadScope;\n}\n\n/** The verdict of a successful `authorizePreviewRequest()`: frozen, branded, produced only there. Carry it, do not rebuild it. */\nexport interface AuthorizedPreviewContext {\n readonly [AUTHORIZED_PREVIEW_BRAND_KEY]: true;\n readonly strategy: PreviewAuthorizationStrategyName;\n /** The user id, token subject, or whatever the verifier named. */\n readonly subject: string | undefined;\n /** Unix milliseconds. */\n readonly authorizedAt: number;\n /** Unix milliseconds, or `undefined` when the strategy does not know. */\n readonly expiresAt: number | undefined;\n readonly scope: AuthorizedPreviewScope;\n /** The minimal request material a draft read forwards to Payload — one verified cookie, never the whole `Cookie` header. */\n readonly payloadHeaders: Readonly<Record<string, string>>;\n}\n\n// A registry symbol: entries are separate bundles, and a per-bundle `Symbol()`\n// would refuse the other's contexts in the package while unit tests passed.\nconst BRAND = Symbol.for(AUTHORIZED_PREVIEW_BRAND_KEY);\n\n/** Whether `value` was produced by `authorizePreviewRequest()`; a copy or JSON round trip is not. */\nexport function isAuthorizedPreviewContext(value: unknown): value is AuthorizedPreviewContext {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<PropertyKey, unknown>)[BRAND] === true &&\n Object.isFrozen(value)\n );\n}\n\n/** Internal: the one place a context is made. */\nexport function createAuthorizedPreviewContext(\n fields: Omit<AuthorizedPreviewContext, typeof AUTHORIZED_PREVIEW_BRAND_KEY>,\n): AuthorizedPreviewContext {\n const context = Object.freeze({\n ...fields,\n scope: Object.freeze({\n ...fields.scope,\n ...(fields.scope.payload === undefined\n ? {}\n : {\n payload: Object.freeze({\n ...fields.scope.payload,\n document: Object.freeze({ ...fields.scope.payload.document }),\n }),\n }),\n }),\n payloadHeaders: Object.freeze({ ...fields.payloadHeaders }),\n [BRAND]: true,\n [AUTHORIZED_PREVIEW_BRAND_KEY]: true,\n });\n // No cast: the frozen object carries the brand key the interface declares.\n return context;\n}\n","/**\n * Running an `authorizePreview` hook. What the hook may resolve to is\n * normalised here once, so the page policy and the fragment endpoint read the\n * same verdict from the same callback. See ADR 0006.\n */\n\nimport {\n isPreviewConfigurationError,\n refused,\n type PreviewAuthorization,\n} from '@security/preview-verdict';\n// From the leaf `types` domain on purpose: the security module would pull the\n// HMAC and session code into every adapter bundle for a ten-line brand check.\nimport { isAuthorizedPreviewContext } from '@/types/authorized-preview';\nimport type { PreviewAuthorizationHookResult } from './options';\n\n/** A bound hook: the adapter option with the request already applied. */\nexport type BoundAuthorizeHook = () =>\n PreviewAuthorizationHookResult | Promise<PreviewAuthorizationHookResult>;\n\n/**\n * The hook's result as a verdict. Only a context `authorizePreviewRequest()`\n * produced authorizes, bare or inside its verdict; a `{ authorized: true }`\n * literal, a copy, a boolean or nothing refuses as `'invalid'`.\n */\nexport function verdictFrom(result: PreviewAuthorizationHookResult): PreviewAuthorization {\n if (isAuthorizedPreviewContext(result)) {\n return { authorized: true, outcome: 'authorized', context: result };\n }\n if (typeof result === 'object' && result !== null && 'authorized' in result) {\n if (result.authorized && isAuthorizedPreviewContext(result.context)) {\n return { authorized: true, outcome: 'authorized', context: result.context };\n }\n return refused(result.authorized ? 'invalid' : result.outcome);\n }\n // `null`, `undefined`, a boolean, a look-alike literal: refused.\n return refused('invalid');\n}\n\n/**\n * Run a bound hook: a `PreviewConfigurationError` is re-thrown so a\n * misconfigured strategy is loud, any other failure is the `'unavailable'`\n * refusal — an identity provider being down must never authorize.\n */\nexport async function runAuthorizeHook(hook: BoundAuthorizeHook): Promise<PreviewAuthorization> {\n let result: PreviewAuthorizationHookResult;\n try {\n result = await hook();\n } catch (error) {\n if (isPreviewConfigurationError(error)) throw error;\n return refused('unavailable');\n }\n return verdictFrom(result);\n}\n","/**\n * What `strict` refuses at startup, so a misconfiguration fails the process\n * rather than a public response (ADR 0006).\n */\n\nimport { isDevelopmentProcess } from '@/types/dev-warning';\nimport { resolvePolicyOptions, type PreviewPolicyOptions } from './policy-options';\n\n/**\n * The sentence every strict refusal ends with.\n *\n * Each of these rules is new in 2.0, and the process that stops is one that\n * worked yesterday. Saying only the rule leaves an upgrader to find out that\n * there is a staged path at all — so the way out is in the message that stops\n * them, not only in the guide they have not opened yet.\n */\nconst STAGED =\n \" New in 2.0; `defaults: 'v1'` keeps the 1.x table while you migrate (docs/migration.md).\";\n\n/** The configuration errors `strict` exists to raise, at startup rather than on a public response. */\nexport function assertStrictConfiguration(options: PreviewPolicyOptions): void {\n if (typeof options.authorizePreview !== 'function') {\n throw new Error(\n 'payload-live-preview: strict mode requires `authorizePreview` — response changes ' +\n 'must be gated on a verified context, not on intent (ADR 0006).' +\n STAGED,\n );\n }\n const origins = options.allowedOrigins ?? [];\n if (origins.length === 0) {\n throw new Error(\n 'payload-live-preview: strict mode requires explicit, non-empty `allowedOrigins`.' + STAGED,\n );\n }\n if (!isDevelopmentProcess()) {\n for (const origin of origins) {\n let protocol: string | undefined;\n try {\n protocol = new URL(origin).protocol;\n } catch {\n protocol = undefined;\n }\n if (protocol !== 'https:') {\n throw new Error(\n `payload-live-preview: strict mode requires https admin origins in production; got \"${origin}\".` +\n STAGED,\n );\n }\n }\n }\n // The resolved signals, not the option: `defaults: 'v1'` fills in `referer`.\n if (resolvePolicyOptions(options).previewSignals?.includes('referer') === true) {\n throw new Error(\n \"payload-live-preview: strict mode disables referrer trust; remove 'referer' from \" +\n \"`previewSignals` (the 'v1' profile includes it).\",\n );\n }\n}\n","/**\n * The preview policy every framework adapter applies: intent, authorization,\n * injection, CSP. Pure — it reads a `{ url, headers.get }` request shape and\n * never touches a response; the adapter translates both ends. See ADR 0006.\n */\n\nimport {\n buildFrameAncestors,\n buildScriptSrcWithNonce,\n generateCspNonce,\n mergeCspHeader,\n} from '@security/csp';\nimport type { PreviewAuthorizationOutcome } from '@security/preview-verdict';\nimport type { AuthorizedPreviewContext } from '@/types/authorized-preview';\nimport { assertMergeDepthExplicit } from '@/types/merge-depth';\nimport { wrapWithScriptTag } from '@inline/generator';\n// Delivery is decided in one place; the policy caches whatever that produced.\nimport { renderScriptBody } from './response';\nimport { hasPreviewIntent, type PreviewRequestLike } from './preview-request';\nimport { warnOnce } from '@/types/dev-warning';\nimport { runAuthorizeHook, type BoundAuthorizeHook } from './authorize-hook';\nimport { resolvePolicyOptions, type PageFacts, type PreviewPolicyOptions } from './policy-options';\nimport { assertStrictConfiguration } from './strict';\n\nexport type { PreviewAuthorizationHookResult } from './options';\n\n/** How the adapter manages Content-Security-Policy, normalised. */\nexport type CspMode = false | 'frame-ancestors' | 'full';\n\n/** `manageCsp` normalised: unset and `true` both mean frame-ancestors only. */\nexport function normalizeCspMode(value: PreviewPolicyOptions['manageCsp']): CspMode {\n if (value === false) return false;\n if (value === 'full') return 'full';\n return 'frame-ancestors';\n}\n\n/** Whether the request shows preview intent under the options; `inject: 'always'` counts as intent. */\nexport function previewIntentFor(\n request: PreviewRequestLike,\n options: PreviewPolicyOptions,\n): boolean {\n const signals = resolvePolicyOptions(options).previewSignals;\n return (\n (options.inject ?? 'preview-only') === 'always' ||\n hasPreviewIntent(request, {\n ...(options.previewQueryParams !== undefined\n ? { queryParams: options.previewQueryParams }\n : {}),\n ...(signals !== undefined ? { signals } : {}),\n allowedOrigins: options.allowedOrigins ?? [],\n })\n );\n}\n\n/** The CSP header after merging: `frame-ancestors` always, a nonce'd `script-src` only in `'full'` mode. */\nexport function buildPreviewCsp(\n options: PreviewPolicyOptions,\n nonce: string,\n existing: string,\n mode: Exclude<CspMode, false>,\n): string {\n const additions: Record<string, string> = {\n 'frame-ancestors': buildFrameAncestors({\n self: true,\n origins: [...(options.allowedOrigins ?? []), ...(options.frameAncestorsExtra ?? [])],\n }),\n };\n if (mode === 'full') {\n additions['script-src'] = buildScriptSrcWithNonce(nonce, {\n self: true,\n strictDynamic: options.strictDynamic ?? false,\n ...(options.scriptSrcExtra !== undefined ? { extra: options.scriptSrcExtra } : {}),\n });\n }\n return mergeCspHeader(existing, additions);\n}\n\n/** What the policy decided for one request. */\nexport interface PreviewDecision {\n /** The request shows preview intent (or the adapter injects always). */\n readonly isPreview: boolean;\n /** The verified context, or `null` when there was no hook or it refused. */\n readonly authorization: AuthorizedPreviewContext | null;\n /** The hook's verdict, or `undefined` when no hook ran (no intent, or none configured). */\n readonly outcome: PreviewAuthorizationOutcome | undefined;\n /** Intent, authorization, `autoInject` and the adapter's content filter all agreed. */\n readonly inject: boolean;\n /** CSP directives to add, or `false`. Never set without intent, never after a refusal. */\n readonly cspMode: CspMode;\n /** Whether the request-scoped nonce may be handed to templates. */\n readonly exposeNonce: boolean;\n}\n\n/** The per-request hooks an adapter binds to its own request type. */\nexport interface PreviewDecisionHooks {\n /** The adapter's content filter, evaluated lazily once injection is otherwise decided. */\n readonly shouldInject?: () => boolean;\n /** The adapter's `authorizePreview` option, bound to the framework request. Called only on intent. */\n readonly authorize?: BoundAuthorizeHook;\n}\n\n/** A policy bound to one adapter's options. The script body depends on the options only and is built once. */\nexport interface PreviewPolicy {\n /**\n * Decide for a request: `hooks.authorize` runs only on intent, and a\n * `PreviewConfigurationError` from it is re-thrown while any other failure\n * becomes the `'unavailable'` refusal.\n */\n decide(request: PreviewRequestLike, hooks?: PreviewDecisionHooks): Promise<PreviewDecision>;\n /** The `<script>` tag for this policy's runtime, carrying `nonce`. */\n scriptTag(nonce: string): string;\n /** CSP header value for a decision that has a mode. */\n csp(existing: string, nonce: string, mode: Exclude<CspMode, false>): string;\n /** A fresh nonce. */\n nonce(): string;\n /** Whether `authorizePreview` is configured; `decide()` then requires the bound hook. */\n readonly authorizes: boolean;\n}\n\nconst NONE: PreviewDecision = Object.freeze({\n isPreview: false,\n authorization: null,\n outcome: undefined,\n inject: false,\n cspMode: false,\n exposeNonce: false,\n});\n\nexport function createPreviewPolicy(\n options: PreviewPolicyOptions,\n facts: PageFacts = {},\n): PreviewPolicy {\n const resolved = resolvePolicyOptions(options);\n assertMergeDepthExplicit(options);\n const authorizes = typeof options.authorizePreview === 'function';\n if (resolved.strict) {\n assertStrictConfiguration(options);\n } else if (!authorizes) {\n warnOnce(\n 'intent-only-preview',\n 'preview responses are gated on client-controlled intent only. Configure `authorizePreview` ' +\n '(see authorizePreviewRequest) before production; `strict: true` enforces it. ' +\n 'ADR 0006 explains why intent is not authorization.',\n );\n }\n const cspMode = normalizeCspMode(options.manageCsp);\n const autoInject = options.autoInject ?? true;\n let body: string | undefined;\n const scriptBody = (): string => {\n body ??= renderScriptBody(options, facts);\n return body;\n };\n return {\n authorizes,\n async decide(request, hooks = {}) {\n if (authorizes && hooks.authorize === undefined) {\n throw new Error(\n 'payload-live-preview: `authorizePreview` is configured but decide() was called ' +\n 'without an `authorize` hook; bind the hook to the request (bindDecisionHooks).',\n );\n }\n const isPreview = previewIntentFor(request, options);\n if (!isPreview) return NONE;\n let authorization: AuthorizedPreviewContext | null = null;\n let outcome: PreviewAuthorizationOutcome | undefined;\n if (hooks.authorize !== undefined) {\n const verdict = await runAuthorizeHook(hooks.authorize);\n outcome = verdict.outcome;\n if (!verdict.authorized) {\n return {\n isPreview,\n authorization: null,\n outcome,\n inject: false,\n cspMode: false,\n exposeNonce: false,\n };\n }\n authorization = verdict.context;\n }\n return {\n isPreview,\n authorization,\n outcome,\n inject: autoInject && (hooks.shouldInject?.() ?? true),\n cspMode,\n exposeNonce: true,\n };\n },\n scriptTag: (nonce) => wrapWithScriptTag(scriptBody(), { nonce }),\n csp: (existing, nonce, mode) => buildPreviewCsp(options, nonce, existing, mode),\n nonce: () => generateCspNonce(),\n };\n}\n","/**\n * Binds the document lifecycle the runtime cannot see: a back/forward-cache\n * restore re-runs no scripts, so a client that stayed attached comes back\n * bound to a frozen document and quietly stops updating; a soft navigation\n * replaces the content the binding cache describes. Both are silent failures.\n */\n\n/** The part of the client this owner drives. */\nexport interface NavigationLifecycleTarget {\n suspend(): boolean;\n resume(): boolean;\n /** Re-scan bindings after replacing markup without crossing a navigation boundary. */\n refreshCache(): void;\n /** Re-scan and replay the last accepted document after a committed router navigation. */\n refreshAfterNavigation?(): void;\n}\n\n/** Package-owned event dispatched after a framework router commit. @internal */\nexport const NAVIGATION_COMMIT_EVENT = 'payload-live-preview:navigation';\nconst ASTRO_INITIAL_PAGE_LOAD_EVENT = 'astro:page-load';\nconst ASTRO_AFTER_SWAP_EVENT = 'astro:after-swap';\n\nexport interface NavigationLifecycleOptions {\n /** Where `pagehide`/`pageshow` fire; they exist only on the window. Defaults to `window`. */\n readonly windowTarget?: EventTarget;\n /** Event target for soft-navigation events. Defaults to `document`. */\n readonly documentTarget?: EventTarget;\n /**\n * Events after which the DOM was replaced and the current editor state must\n * be replayed, e.g. `astro:page-load`. Empty by default: only the host knows\n * which its router fires.\n */\n readonly softNavigationEvents?: readonly string[];\n}\n\n/** Returns an unbind function; calling it twice is harmless. */\nexport function bindNavigationLifecycle(\n target: NavigationLifecycleTarget,\n options: NavigationLifecycleOptions = {},\n): () => void {\n const windowTarget = options.windowTarget ?? (globalThis as { window?: EventTarget }).window;\n const documentTarget =\n options.documentTarget ?? (globalThis as { document?: EventTarget }).document;\n const softEvents = [...new Set(options.softNavigationEvents ?? [])];\n\n const onPageHide = (): void => {\n target.suspend();\n };\n const onPageShow = (event: Event): void => {\n // Only a persisted restore needs reacquiring; an ordinary load already started.\n if ((event as Event & { readonly persisted?: boolean }).persisted === true) {\n target.resume();\n }\n };\n let astroNavigationArmed = false;\n const onAstroAfterSwap = (): void => {\n astroNavigationArmed = true;\n };\n const onSoftNavigation = (event: Event): void => {\n // Astro emits page-load for the initial document too. A client-router\n // commit is the page-load preceded by after-swap, including before the\n // browser's initial `load` when a subresource is slow.\n if (event.type === ASTRO_INITIAL_PAGE_LOAD_EVENT) {\n if (!astroNavigationArmed) return;\n astroNavigationArmed = false;\n }\n if (target.refreshAfterNavigation === undefined) target.refreshCache();\n else target.refreshAfterNavigation();\n };\n\n let unbound = false;\n\n windowTarget?.addEventListener('pagehide', onPageHide);\n windowTarget?.addEventListener('pageshow', onPageShow);\n for (const name of softEvents) documentTarget?.addEventListener(name, onSoftNavigation);\n const observesAstro = softEvents.includes(ASTRO_INITIAL_PAGE_LOAD_EVENT);\n if (observesAstro) documentTarget?.addEventListener(ASTRO_AFTER_SWAP_EVENT, onAstroAfterSwap);\n\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 if (observesAstro) {\n documentTarget?.removeEventListener(ASTRO_AFTER_SWAP_EVENT, onAstroAfterSwap);\n }\n };\n}\n","/**\n * Next.js adapter. The script goes into the root layout, because\n * `NextResponse.next()` carries no body for the middleware to inject into:\n * `livePreviewScriptProps()` for the App Router's JSX, `renderLivePreviewScript()`\n * for HTML a server assembles as a string.\n */\n\nimport { createPreviewPolicy } from '@adapters/shared/policy';\nimport {\n applyDecision,\n bindDecisionHooks,\n renderScriptBody,\n renderScriptTag,\n} from '@adapters/shared/response';\nimport { assertNonce } from '@inline/generator';\nimport type { PreviewAdapterOptions } from '@adapters/shared/options';\nimport type { PageFacts } from '@adapters/shared/policy-options';\nimport { NAVIGATION_COMMIT_EVENT } from '@core/navigation-lifecycle';\n\nexport type { PreviewAdapterOptions } from '@adapters/shared/options';\n\nexport type LivePreviewNextOptions = PreviewAdapterOptions;\n\n/**\n * A Next page is a React tree, so every script this adapter emits declares\n * that React hydrates it (ADR 0015): the runtime then holds its first write\n * until React has committed the tree that holds the bindings, instead of\n * writing into markup React is about to compare with its own render. Knowledge\n * the adapter has, not an option a project sets.\n */\nconst REACT_PAGE: PageFacts = {\n hydration: 'react',\n softNavigationEvents: [NAVIGATION_COMMIT_EVENT],\n};\n\n/**\n * Middleware over the standard `Request`/`Response` pair: on preview intent it\n * authorizes, injects, merges CSP and marks the response uncacheable. Next.js\n * middleware has no `locals`, so the verdict is not published — call\n * `authorizePreviewRequest()` in the route when a page needs it.\n */\nexport function createLivePreviewMiddleware(\n options: LivePreviewNextOptions = {},\n): (request: Request, response: Response) => Promise<Response> {\n const policy = createPreviewPolicy(options, REACT_PAGE);\n return async (request, response) => {\n const decision = await policy.decide(request, bindDecisionHooks(policy, options, request));\n if (!decision.isPreview) return response;\n return applyDecision(response, policy, decision, policy.nonce());\n };\n}\n\n/** What a `<script>` element needs to carry the runtime; see `livePreviewScriptProps`. */\nexport interface LivePreviewScriptProps {\n readonly dangerouslySetInnerHTML: { readonly __html: string };\n /** Present only when a nonce was passed, so React omits the attribute otherwise. */\n readonly nonce?: string;\n}\n\n/**\n * Props for the `<script>` in `app/layout.tsx`:\n *\n * ```tsx\n * <script {...livePreviewScriptProps({ allowedOrigins: [ADMIN], serverURL: ADMIN, mergeDepth: 1 })} />\n * ```\n *\n * The nonce stays a prop rather than going into the body, because that is where\n * the framework — and any CSP handling built on it — expects the attribute.\n */\nexport function livePreviewScriptProps(\n options: LivePreviewNextOptions & { readonly nonce?: string } = {},\n): LivePreviewScriptProps {\n const html = renderScriptBody(options, REACT_PAGE);\n if (options.nonce === undefined) return { dangerouslySetInnerHTML: { __html: html } };\n return {\n dangerouslySetInnerHTML: { __html: html },\n nonce: assertNonce(options.nonce),\n };\n}\n\n/**\n * The complete `<script>` tag, for HTML a server builds as a string. A JSX\n * framework cannot render it — use `livePreviewScriptProps()` there.\n */\nexport function renderLivePreviewScript(\n options: LivePreviewNextOptions & { readonly nonce?: string } = {},\n): string {\n return renderScriptTag(options, REACT_PAGE);\n}\n","/**\n * An optional peer dependency, imported the first time it is actually needed.\n *\n * Every fragment binding renders with a component system this package does not\n * install: `astro`, `react`/`react-dom`, `svelte`, `vue`. A project that never\n * registers a fragment — most of them — must still be able to install and run\n * this package, so the import happens at the first render rather than at module\n * load. Each caller chooses a specifier its consumer can resolve.\n */\n\n/**\n * `load` runs once per process. Callers arriving while it is in flight share\n * that promise; a rejected one is forgotten rather than kept, so a project that\n * installs the package after the first request is not answered from the first\n * bad start for the rest of the process's life.\n */\nexport function lazyPeer<T>(load: () => Promise<T>): () => Promise<T> {\n let pending: Promise<T> | undefined;\n return () => {\n if (pending === undefined) {\n const started = load();\n pending = started;\n started.catch(() => {\n if (pending === started) pending = undefined;\n });\n }\n return pending;\n };\n}\n\n/**\n * The error a binding throws when its renderer's packages are not installed.\n * The endpoint answers 500 either way; this is what the server log says, and\n * without it the cause reads as \"render failed\".\n */\nexport function missingPeerError(packages: readonly string[], cause: unknown): Error {\n const names = packages.map((name) => `\\`${name}\\``).join(' and ');\n const one = packages.length === 1;\n return new Error(\n `payload-live-preview: this fragment endpoint renders with ${names}, ` +\n `${one ? 'an optional peer' : 'optional peers'} this package does not install. ` +\n `${one ? 'Install it' : 'Install them'}, or pass your own \\`render\\`.`,\n { cause },\n );\n}\n","/**\n * The `payload-session` strategy: forward exactly one named cookie to\n * `GET <serverURL>/api/<usersSlug>/me` and authorize when a user comes back.\n * A cookie-only request preserves working Payload 2 sessions. When `/me`\n * reports no user, one retry adds an `Origin` for Payload 3's CSRF check.\n */\n\nimport { createAuthorizedPreviewContext } from '@/types/authorized-preview';\nimport {\n PreviewConfigurationError,\n refused,\n type PreviewAuthorization,\n type PreviewAuthorizationRequest,\n} from './preview-verdict';\n\n/** A `fetch`-compatible function, injectable for tests. */\nexport type FetchLike = (\n input: string,\n init: { readonly headers: Record<string, string>; readonly signal: AbortSignal },\n) => Promise<{ readonly ok: boolean; readonly status: number; json(): Promise<unknown> }>;\n\nexport interface PayloadSessionStrategy {\n readonly type: 'payload-session';\n /** Payload server origin, e.g. `https://cms.example.com`. */\n readonly serverURL: string;\n /** Auth collection slug; `users` unless the project renamed it. */\n readonly usersSlug?: string;\n /** Cookie name; Payload's default is `payload-token`. */\n readonly cookieName?: string;\n /**\n * Send this listed origin with the cookie from the first request. Without\n * it, try the existing cookie-only request, then the origin of `serverURL`\n * once when `/me` reports a null user. Draft reads keep the accepted headers.\n */\n readonly origin?: string;\n /** Upper bound for the `/me` round trip. Below 250 ms is raised to 250 ms; default 3000. */\n readonly timeoutMs?: number;\n /** Longest cookie value accepted; longer ones are refused as `missing-credential`. Default 4096. */\n readonly maxCookieLength?: number;\n readonly fetch?: FetchLike;\n /** Clock, Unix milliseconds. Injectable for tests. */\n readonly now?: () => number;\n}\n\nconst DEFAULT_USERS_SLUG = 'users';\nconst DEFAULT_COOKIE_NAME = 'payload-token';\nconst DEFAULT_TIMEOUT_MS = 3_000;\nconst MIN_TIMEOUT_MS = 250;\nconst DEFAULT_MAX_COOKIE_LENGTH = 4_096;\nconst COOKIE_NAME_PATTERN = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\nconst COOKIE_VALUE_PATTERN = /^[A-Za-z0-9._~-]+$/;\n/** Below this an `exp` is Unix seconds; a millisecond timestamp passed it in 1973. */\nconst SECONDS_CEILING = 1e11;\n\n/**\n * Exactly one value for `name`, or `null` when absent, empty, over `maxLength`\n * or repeated — a repeated cookie is ambiguous and is refused, not guessed.\n */\nexport function extractCookie(\n header: string | null,\n name: string,\n maxLength: number = DEFAULT_MAX_COOKIE_LENGTH,\n): string | null {\n if (header === null || header.length === 0) return null;\n const prefix = `${name}=`;\n const values: string[] = [];\n for (const part of header.split(';')) {\n const trimmed = part.trim();\n if (trimmed.startsWith(prefix)) values.push(trimmed.slice(prefix.length));\n }\n if (values.length !== 1) return null;\n const value = values[0] ?? '';\n // A JWT is `[A-Za-z0-9._~-]`; anything else must not be forwarded in a header.\n if (value.length === 0 || value.length > maxLength || !COOKIE_VALUE_PATTERN.test(value)) {\n return null;\n }\n return value;\n}\n\nfunction cookieNameFor(configured: string | undefined): string {\n const name = configured ?? DEFAULT_COOKIE_NAME;\n if (!COOKIE_NAME_PATTERN.test(name)) {\n throw new PreviewConfigurationError(\n `payload-live-preview: cookie name \"${name}\" is not a valid cookie-name token`,\n );\n }\n return name;\n}\n\n/** The origin of an absolute http(s) URL; `option` names it in the error. */\nfunction httpOriginFor(value: string, option: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new PreviewConfigurationError(\n `payload-live-preview: ${option} \"${value}\" is not an absolute URL`,\n );\n }\n if (url.protocol !== 'https:' && url.protocol !== 'http:') {\n throw new PreviewConfigurationError(\n `payload-live-preview: ${option} must be http(s), got \"${url.protocol}\"`,\n );\n }\n return url.origin;\n}\n\nexport async function authorizeSession(\n request: PreviewAuthorizationRequest,\n strategy: PayloadSessionStrategy,\n): Promise<PreviewAuthorization> {\n const cookieName = cookieNameFor(strategy.cookieName);\n const origin = httpOriginFor(strategy.serverURL, 'serverURL');\n const sentOrigin =\n strategy.origin === undefined ? undefined : httpOriginFor(strategy.origin, 'origin');\n const value = extractCookie(\n request.headers.get('cookie'),\n cookieName,\n strategy.maxCookieLength ?? DEFAULT_MAX_COOKIE_LENGTH,\n );\n if (value === null) return refused('missing-credential');\n const now = strategy.now ?? Date.now;\n const timeoutMs = Math.max(MIN_TIMEOUT_MS, strategy.timeoutMs ?? DEFAULT_TIMEOUT_MS);\n // Retain AbortSignal.timeout's refusal of non-integral or non-finite values.\n if (!Number.isSafeInteger(timeoutMs)) return refused('unavailable');\n const fetchImpl: FetchLike = strategy.fetch ?? globalThis.fetch;\n const usersSlug = encodeURIComponent(strategy.usersSlug ?? DEFAULT_USERS_SLUG);\n const forwarded = `${cookieName}=${value}`;\n let payloadHeaders: Record<string, string> = { cookie: forwarded };\n if (sentOrigin !== undefined) payloadHeaders['origin'] = sentOrigin;\n const controller = new AbortController();\n const abort = (): void => {\n controller.abort(request.signal?.reason);\n };\n const isAborted = (): boolean => controller.signal.aborted;\n request.signal?.addEventListener('abort', abort, { once: true });\n if (request.signal?.aborted === true) abort();\n let timer: ReturnType<typeof setTimeout> | undefined;\n let body: unknown;\n try {\n if (isAborted()) return refused('unavailable');\n timer = setTimeout(() => {\n controller.abort(new DOMException('The operation timed out', 'TimeoutError'));\n }, timeoutMs);\n for (let attempt = 0; attempt < 2; attempt++) {\n // `depth=0`: the verdict needs the user's id, not its populated relations.\n const response = await fetchImpl(`${origin}/api/${usersSlug}/me?depth=0`, {\n headers: { ...payloadHeaders, accept: 'application/json' },\n signal: controller.signal,\n });\n if (isAborted()) return refused('unavailable');\n if (!response.ok) return refused(response.status === 401 ? 'invalid' : 'unavailable');\n body = await response.json();\n if (isAborted()) return refused('unavailable');\n // Payload 2 accepts an absent Origin; adding one unconditionally can\n // reject its valid session when only the frontend is in the CSRF list.\n if (\n attempt !== 0 ||\n sentOrigin !== undefined ||\n typeof body !== 'object' ||\n body === null ||\n (body as { user?: unknown }).user !== null\n ) {\n break;\n }\n payloadHeaders = { cookie: forwarded, origin };\n }\n } catch {\n return refused('unavailable');\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n request.signal?.removeEventListener('abort', abort);\n }\n const user = readUser(body, strategy.usersSlug ?? DEFAULT_USERS_SLUG);\n if (user === null) return refused('invalid');\n const expiresAt = readExpiry(body);\n if (expiresAt !== undefined && expiresAt <= now()) return refused('expired');\n return {\n authorized: true,\n outcome: 'authorized',\n context: createAuthorizedPreviewContext({\n strategy: 'payload-session',\n subject: user,\n authorizedAt: now(),\n expiresAt,\n scope: {},\n payloadHeaders,\n }),\n };\n}\n\n/** The user id from a `/me` body, or `null` when absent or from another auth collection — Payload answers `/me` for every one of them. */\nfunction readUser(body: unknown, usersSlug: string): string | null {\n if (typeof body !== 'object' || body === null || Array.isArray(body)) return null;\n const user = (body as { user?: unknown }).user;\n if (typeof user !== 'object' || user === null || Array.isArray(user)) return null;\n const collection =\n (body as { collection?: unknown }).collection ?? (user as { collection?: unknown }).collection;\n if (collection !== undefined && collection !== usersSlug) return null;\n const id = (user as { id?: unknown }).id;\n if (typeof id === 'string' && id.length > 0) return id;\n if (typeof id === 'number' && Number.isFinite(id)) return String(id);\n return null;\n}\n\n/** `/me` reports `exp` in Unix seconds; units are decided by magnitude so an expired millisecond value stays expired. */\nfunction readExpiry(body: unknown): number | undefined {\n const exp = (body as { exp?: unknown }).exp;\n if (typeof exp !== 'number' || !Number.isFinite(exp) || exp <= 0) return undefined;\n return exp < SECONDS_CEILING ? exp * 1000 : exp;\n}\n","/**\n * The `signed-token` strategy: a short-lived HMAC-SHA256 token minted by the\n * Payload side and verified by the site. Format and bindings: ADR 0006 §3.\n */\n\nimport { createAuthorizedPreviewContext } from '@/types/authorized-preview';\nimport { warnOnce } from '@/types/dev-warning';\nimport {\n PreviewConfigurationError,\n refused,\n type PreviewAuthorization,\n type PreviewAuthorizationRequest,\n} from './preview-verdict';\n\n/** The subset of Web Crypto the token strategy needs, injectable for environments that expose it elsewhere. */\nexport interface SubtleCryptoLike {\n readonly subtle: {\n importKey(\n format: 'raw',\n keyData: Uint8Array,\n algorithm: { readonly name: 'HMAC'; readonly hash: 'SHA-256' },\n extractable: false,\n keyUsages: readonly ('sign' | 'verify')[],\n ): Promise<CryptoKey>;\n sign(algorithm: 'HMAC', key: CryptoKey, data: Uint8Array): Promise<ArrayBuffer>;\n verify(\n algorithm: 'HMAC',\n key: CryptoKey,\n signature: Uint8Array,\n data: Uint8Array,\n ): Promise<boolean>;\n };\n getRandomValues<T extends Uint8Array>(array: T): T;\n}\n\n/** Where a signed token is read from on the request. */\nexport type PreviewTokenTransport =\n | { readonly kind: 'query'; readonly param?: string }\n | { readonly kind: 'header'; readonly name?: string };\n\n/**\n * Optional replay store. Not shipped: a per-process memory is useless behind\n * a load balancer, so the store is a deployment decision.\n */\nexport interface PreviewTokenReplayStore {\n /**\n * Record `id` as used until `expiresAt` and say whether this call was the\n * first: `true` admits the token, anything else refuses it as `replayed`, a\n * throw refuses it as `unavailable`. Check and record in one step (Redis\n * `SET NX PX`, a unique insert): a read followed by a write lets two requests\n * that carry the same token and arrive together both pass.\n */\n consume(id: string, expiresAt: number): Promise<boolean> | boolean;\n}\n\n/**\n * @deprecated The store shape of the 2.0 beta, removed in 3.0. Its two calls cannot be one\n * step, so two requests with the same token that arrive together both pass\n * `isUsed` before either reaches `markUsed`. Implement\n * {@link PreviewTokenReplayStore.consume} instead.\n */\nexport interface PreviewTokenReplayChecks {\n isUsed(id: string): Promise<boolean> | boolean;\n markUsed(id: string, expiresAt: number): Promise<void> | void;\n}\n\nexport interface SignedTokenStrategy {\n readonly type: 'signed-token';\n /** Shared secret, at least 32 bytes; shorter ones are refused on first use. */\n readonly secret: string | Uint8Array;\n /** The site origin tokens must name, e.g. `https://www.example.com`. */\n readonly audience: string;\n /** Purpose string tokens must carry. Default `live-preview`. */\n readonly purpose?: string;\n /** Default: query parameter `previewToken`. */\n readonly transport?: PreviewTokenTransport;\n /** Resolve the request's locale for the `loc` binding. Unset: tokens with `loc` are refused as `wrong-locale`. */\n readonly locale?: (request: PreviewAuthorizationRequest) => string | undefined;\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- the 2.0 beta shape is accepted until 3.0\n readonly replay?: PreviewTokenReplayStore | PreviewTokenReplayChecks;\n readonly crypto?: SubtleCryptoLike;\n readonly now?: () => number;\n}\n\n/** What `issuePreviewToken()` binds a token to. */\nexport interface PreviewTokenClaims {\n /** The site origin the token is for. */\n readonly audience: string;\n /** Request pathname the token opens. Recommended; omit only for a single-page preview. */\n readonly path?: string;\n readonly locale?: string;\n readonly subject?: string;\n readonly purpose?: string;\n /** Lifetime in milliseconds. Default ten minutes; capped at one hour. */\n readonly ttlMs?: number;\n}\n\nexport interface IssuePreviewTokenOptions {\n readonly secret: string | Uint8Array;\n readonly crypto?: SubtleCryptoLike;\n readonly now?: () => number;\n}\n\ninterface WireClaims {\n readonly v: 1;\n readonly aud: string;\n readonly pth?: string;\n readonly loc?: string;\n readonly sub?: string;\n readonly pur: string;\n readonly iat: number;\n readonly exp: number;\n readonly jti: string;\n}\n\nconst DEFAULT_PURPOSE = 'live-preview';\nconst DEFAULT_QUERY_PARAM = 'previewToken';\nconst DEFAULT_HEADER_NAME = 'x-preview-token';\nconst DEFAULT_TTL_MS = 10 * 60_000;\nconst MAX_TTL_MS = 60 * 60_000;\nconst MIN_SECRET_BYTES = 32;\nconst TOKEN_VERSION = 'v1';\n/** A real token is a few hundred bytes. */\nconst MAX_TOKEN_LENGTH = 4_096;\n\n// Lazy: a module-scope `new TextEncoder()` is a side effect a bundler must keep.\nlet cachedEncoder: TextEncoder | undefined;\nfunction encoder(): TextEncoder {\n cachedEncoder ??= new TextEncoder();\n return cachedEncoder;\n}\n\nfunction secretBytes(secret: string | Uint8Array): Uint8Array {\n const bytes = typeof secret === 'string' ? encoder().encode(secret) : secret;\n if (bytes.byteLength < MIN_SECRET_BYTES) {\n throw new PreviewConfigurationError(\n `payload-live-preview: the preview token secret must be at least ${String(MIN_SECRET_BYTES)} bytes`,\n );\n }\n return bytes;\n}\n\nfunction cryptoFor(configured: SubtleCryptoLike | undefined): SubtleCryptoLike | undefined {\n if (configured !== undefined) return configured;\n const candidate = (globalThis as { crypto?: unknown }).crypto;\n if (typeof (candidate as { subtle?: unknown } | undefined)?.subtle === 'object') {\n return candidate as SubtleCryptoLike;\n }\n return undefined;\n}\n\nasync function hmacKey(crypto: SubtleCryptoLike, secret: Uint8Array): Promise<CryptoKey> {\n return crypto.subtle.importKey('raw', secret, { name: 'HMAC', hash: 'SHA-256' }, false, [\n 'sign',\n 'verify',\n ]);\n}\n\nfunction toBase64Url(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nfunction fromBase64Url(text: string): Uint8Array | undefined {\n if (!/^[A-Za-z0-9_-]*$/.test(text)) return undefined;\n const padded =\n text.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (text.length % 4)) % 4);\n try {\n const binary = atob(padded);\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);\n return bytes;\n } catch {\n return undefined;\n }\n}\n\n/** Mint a preview token on the Payload side; pair with `buildLivePreviewUrl`. */\nexport async function issuePreviewToken(\n claims: PreviewTokenClaims,\n options: IssuePreviewTokenOptions,\n): Promise<string> {\n const crypto = cryptoFor(options.crypto);\n if (crypto === undefined) {\n throw new Error('payload-live-preview: no Web Crypto implementation available to sign tokens');\n }\n const secret = secretBytes(options.secret);\n const now = (options.now ?? Date.now)();\n const ttl = Math.min(MAX_TTL_MS, Math.max(1, claims.ttlMs ?? DEFAULT_TTL_MS));\n const id = new Uint8Array(16);\n crypto.getRandomValues(id);\n const wire: WireClaims = {\n v: 1,\n aud: claims.audience,\n ...(claims.path !== undefined ? { pth: claims.path } : {}),\n ...(claims.locale !== undefined ? { loc: claims.locale } : {}),\n ...(claims.subject !== undefined ? { sub: claims.subject } : {}),\n pur: claims.purpose ?? DEFAULT_PURPOSE,\n iat: now,\n exp: now + ttl,\n jti: toBase64Url(id),\n };\n const payload = toBase64Url(encoder().encode(JSON.stringify(wire)));\n const signed = `${TOKEN_VERSION}.${payload}`;\n const key = await hmacKey(crypto, secret);\n const signature = new Uint8Array(await crypto.subtle.sign('HMAC', key, encoder().encode(signed)));\n return `${signed}.${toBase64Url(signature)}`;\n}\n\nfunction readToken(\n request: PreviewAuthorizationRequest,\n transport: PreviewTokenTransport | undefined,\n): string | null {\n if (transport?.kind === 'header') {\n return request.headers.get(transport.name ?? DEFAULT_HEADER_NAME);\n }\n let url: URL;\n try {\n url = new URL(request.url);\n } catch {\n return null;\n }\n const values = url.searchParams.getAll(transport?.param ?? DEFAULT_QUERY_PARAM);\n return values.length === 1 ? (values[0] ?? null) : null;\n}\n\nfunction parseClaims(bytes: Uint8Array): WireClaims | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(new TextDecoder().decode(bytes));\n } catch {\n return undefined;\n }\n if (typeof parsed !== 'object' || parsed === null) return undefined;\n const c = parsed as Record<string, unknown>;\n const optionalString = (key: string): boolean =>\n c[key] === undefined || typeof c[key] === 'string';\n if (\n c['v'] !== 1 ||\n typeof c['aud'] !== 'string' ||\n typeof c['pur'] !== 'string' ||\n typeof c['iat'] !== 'number' ||\n typeof c['exp'] !== 'number' ||\n typeof c['jti'] !== 'string' ||\n !optionalString('pth') ||\n !optionalString('loc') ||\n !optionalString('sub')\n ) {\n return undefined;\n }\n return c as unknown as WireClaims;\n}\n\nexport async function authorizeToken(\n request: PreviewAuthorizationRequest,\n strategy: SignedTokenStrategy,\n): Promise<PreviewAuthorization> {\n const secret = secretBytes(strategy.secret);\n const crypto = cryptoFor(strategy.crypto);\n if (crypto === undefined) return refused('unavailable');\n const token = readToken(request, strategy.transport);\n if (token === null || token.length === 0) return refused('missing-credential');\n if (token.length > MAX_TOKEN_LENGTH) return refused('invalid');\n const parts = token.split('.');\n if (parts.length !== 3 || parts[0] !== TOKEN_VERSION) return refused('invalid');\n const payloadText = parts[1] ?? '';\n const payloadBytes = fromBase64Url(payloadText);\n const signature = fromBase64Url(parts[2] ?? '');\n if (payloadBytes === undefined || signature?.byteLength !== 32) return refused('invalid');\n let verified: boolean;\n try {\n const key = await hmacKey(crypto, secret);\n verified = await crypto.subtle.verify(\n 'HMAC',\n key,\n signature,\n encoder().encode(`${TOKEN_VERSION}.${payloadText}`),\n );\n } catch {\n return refused('unavailable');\n }\n if (!verified) return refused('invalid');\n const claims = parseClaims(payloadBytes);\n if (claims === undefined) return refused('invalid');\n const now = (strategy.now ?? Date.now)();\n if (claims.exp <= now || claims.iat > claims.exp) return refused('expired');\n if (claims.aud !== strategy.audience) return refused('wrong-audience');\n if (claims.pur !== (strategy.purpose ?? DEFAULT_PURPOSE)) return refused('wrong-purpose');\n if (claims.pth !== undefined) {\n let pathname: string;\n try {\n pathname = new URL(request.url).pathname;\n } catch {\n return refused('invalid');\n }\n if (claims.pth !== pathname) return refused('wrong-path');\n }\n if (claims.loc !== undefined) {\n const locale = strategy.locale?.(request);\n if (locale !== claims.loc) return refused('wrong-locale');\n }\n if (strategy.replay !== undefined) {\n let first: boolean;\n try {\n first = await consumeTokenId(strategy.replay, claims.jti, claims.exp);\n } catch {\n return refused('unavailable');\n }\n if (!first) return refused('replayed');\n }\n return {\n authorized: true,\n outcome: 'authorized',\n context: createAuthorizedPreviewContext({\n strategy: 'signed-token',\n subject: claims.sub,\n authorizedAt: now,\n expiresAt: claims.exp,\n scope: {\n audience: claims.aud,\n ...(claims.pth !== undefined ? { path: claims.pth } : {}),\n ...(claims.loc !== undefined ? { locale: claims.loc } : {}),\n },\n payloadHeaders: {},\n }),\n };\n}\n\n/**\n * `true` when `id` was not seen before. A store that returns anything but\n * `true` from `consume` refuses the token: fail closed, since a forgotten\n * return would otherwise admit every replay. The 2.0 beta shape keeps its two\n * steps and its race; that is why it is deprecated rather than emulated.\n */\nasync function consumeTokenId(\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- the 2.0 beta shape is accepted until 3.0\n store: PreviewTokenReplayStore | PreviewTokenReplayChecks,\n id: string,\n expiresAt: number,\n): Promise<boolean> {\n if ('consume' in store) {\n // The store is consumer code; its answer is a value, not a type.\n const answer: unknown = await store.consume(id, expiresAt);\n return answer === true;\n }\n warnOnce(\n 'replay-is-used',\n 'A `signed-token` replay store with `isUsed` and `markUsed` is removed in 3.0: implement ' +\n '`consume(id, expiresAt)`, which checks and records in one step (ADR 0026).',\n );\n if (await store.isUsed(id)) return false;\n await store.markUsed(id, expiresAt);\n return true;\n}\n","/**\n * Shared checks for an opt-in Payload document capability (ADR 0006 §5c).\n * The verifier supplies authority; server reads and fragments only compare\n * their requested target against it, before forwarding credentials or rendering.\n */\nimport type {\n AuthorizedPreviewContext,\n AuthorizedPreviewDocument,\n AuthorizedPreviewPayloadScope,\n} from '@/types/authorized-preview';\n\nfunction pathSegment(value: unknown): value is string {\n return (\n typeof value === 'string' &&\n value.length > 0 &&\n value !== '.' &&\n value !== '..' &&\n !/[\\s\\p{Cc}\\p{Cs}/\\\\?#%]/u.test(value)\n );\n}\n\n/** @internal Numeric REST IDs and their string spelling name the same document. */\nexport function isPreviewDocumentID(value: unknown): value is string | number {\n return typeof value === 'number' ? Number.isSafeInteger(value) : pathSegment(value);\n}\n\n/** @internal Refuse ambiguous paths rather than depending on a proxy's decoding rules. */\nexport function payloadAPIBase(serverURL: unknown, apiRoute: unknown = '/api'): string | null {\n if (typeof serverURL !== 'string' || typeof apiRoute !== 'string') return null;\n try {\n const url = new URL(serverURL);\n if (\n !['http:', 'https:'].includes(url.protocol) ||\n url.username ||\n url.password ||\n url.search ||\n url.hash\n ) {\n return null;\n }\n // Inspect the raw path too: URL would otherwise erase dot segments first.\n const rawPath = serverURL.replace(/^[a-z]+:\\/\\/[^/]+/iu, '').replace(/\\/+$/, '');\n const route = apiRoute.replace(/^\\//, '').replace(/\\/$/, '');\n if (\n (rawPath !== '' && !rawPath.slice(1).split('/').every(pathSegment)) ||\n !route.split('/').every(pathSegment)\n ) {\n return null;\n }\n return `${url.origin}${url.pathname.replace(/\\/+$/, '')}/${route}`;\n } catch {\n return null;\n }\n}\n\n/** @internal Validate a JavaScript verifier's binding, not merely its TypeScript shape. */\nexport function isValidPayloadScope(value: unknown): value is AuthorizedPreviewPayloadScope {\n if (typeof value !== 'object' || value === null) return false;\n const scope = value as Record<string, unknown>;\n const document = scope['document'] as Record<string, unknown> | null | undefined;\n if (\n payloadAPIBase(scope['serverURL'], scope['apiRoute']) === null ||\n typeof scope['maxDepth'] !== 'number' ||\n !Number.isSafeInteger(scope['maxDepth']) ||\n scope['maxDepth'] < 0 ||\n typeof document !== 'object' ||\n document === null ||\n !pathSegment(document['slug'])\n ) {\n return false;\n }\n return (\n document['kind'] === 'global' ||\n (document['kind'] === 'collection' && isPreviewDocumentID(document['id']))\n );\n}\n\n/** @internal No clock renewal: every consumer checks the original absolute expiry. */\nexport function isPayloadScopeCurrent(context: AuthorizedPreviewContext): boolean {\n return (\n context.expiresAt !== undefined &&\n Number.isFinite(context.expiresAt) &&\n context.expiresAt > Date.now()\n );\n}\n\n/** @internal Both package consumers use the same kind/slug/ID comparison. */\nexport function matchesPreviewDocument(\n expected: AuthorizedPreviewDocument,\n actual: {\n readonly kind: 'collection' | 'global';\n readonly slug: string | undefined;\n readonly id?: unknown;\n },\n): boolean {\n return (\n expected.kind === actual.kind &&\n expected.slug === actual.slug &&\n (expected.kind === 'global' ||\n (isPreviewDocumentID(actual.id) && String(expected.id) === String(actual.id)))\n );\n}\n\n/** @internal A document response or form snapshot cannot contradict its bound identity. */\nexport function matchesPreviewDocumentData(\n expected: AuthorizedPreviewDocument,\n value: unknown,\n): boolean {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const data = value as Record<string, unknown>;\n if (expected.kind === 'global') {\n return !Object.hasOwn(data, 'globalType') || data['globalType'] === expected.slug;\n }\n return (\n Object.hasOwn(data, 'id') &&\n matchesPreviewDocument(expected, { kind: 'collection', slug: expected.slug, id: data['id'] })\n );\n}\n","/**\n * Authorized preview context: the one verdict every privileged preview\n * decision is keyed on. Intent (`?preview=true`, an iframe destination, a\n * referer) is client-chosen; this turns a session, a signed token or the\n * application's own verifier into a branded context. Threat model: ADR 0006.\n */\n\nimport {\n AUTHORIZED_PREVIEW_BRAND_KEY,\n createAuthorizedPreviewContext,\n isAuthorizedPreviewContext,\n type AuthorizedPreviewContext,\n type AuthorizedPreviewDocument,\n type AuthorizedPreviewPayloadScope,\n type AuthorizedPreviewScope,\n type PreviewAuthorizationStrategyName,\n} from '@/types/authorized-preview';\nimport {\n refused,\n type PreviewAuthorization,\n type PreviewAuthorizationRequest,\n} from './preview-verdict';\nimport { authorizeSession, type PayloadSessionStrategy } from './preview-session';\nimport { authorizeToken, type SignedTokenStrategy } from './preview-token';\nimport { isValidPayloadScope } from './preview-scope';\n\nexport {\n AUTHORIZED_PREVIEW_BRAND_KEY,\n isAuthorizedPreviewContext,\n type AuthorizedPreviewContext,\n type AuthorizedPreviewDocument,\n type AuthorizedPreviewPayloadScope,\n type AuthorizedPreviewScope,\n type PreviewAuthorizationStrategyName,\n};\nexport {\n PreviewConfigurationError,\n type PreviewAuthorization,\n type PreviewAuthorizationOutcome,\n type PreviewAuthorizationRequest,\n} from './preview-verdict';\nexport { extractCookie, type FetchLike, type PayloadSessionStrategy } from './preview-session';\nexport {\n issuePreviewToken,\n type IssuePreviewTokenOptions,\n type PreviewTokenClaims,\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- the 2.0 beta shape exists to be re-exported\n type PreviewTokenReplayChecks,\n type PreviewTokenReplayStore,\n type PreviewTokenTransport,\n type SignedTokenStrategy,\n type SubtleCryptoLike,\n} from './preview-token';\n\n/** Claims a consumer verifier returns for a request it accepts. */\nexport interface PreviewVerifierClaims {\n readonly subject?: string;\n readonly expiresAt?: number;\n readonly scope?: AuthorizedPreviewScope;\n readonly payloadHeaders?: Readonly<Record<string, string>>;\n}\n\n/** The application's own verification: claims authorize, `null` refuses, a throw is `unavailable`. */\nexport interface VerifierStrategy {\n readonly type: 'verifier';\n readonly verify: (\n request: PreviewAuthorizationRequest,\n ) => Promise<PreviewVerifierClaims | null> | PreviewVerifierClaims | null;\n readonly now?: () => number;\n}\n\nexport type PreviewAuthorizationStrategy =\n PayloadSessionStrategy | SignedTokenStrategy | VerifierStrategy;\n\n/** Decide whether `request` is an authorized preview; refusals resolve to `{ authorized: false }` and only a `PreviewConfigurationError` throws. */\nexport async function authorizePreviewRequest(\n request: PreviewAuthorizationRequest,\n strategy: PreviewAuthorizationStrategy,\n): Promise<PreviewAuthorization> {\n switch (strategy.type) {\n case 'payload-session':\n return authorizeSession(request, strategy);\n case 'signed-token':\n return authorizeToken(request, strategy);\n case 'verifier':\n return authorizeVerifier(request, strategy);\n }\n}\n\nasync function authorizeVerifier(\n request: PreviewAuthorizationRequest,\n strategy: VerifierStrategy,\n): Promise<PreviewAuthorization> {\n let claims: PreviewVerifierClaims | null;\n try {\n claims = await strategy.verify(request);\n } catch {\n return refused('unavailable');\n }\n if (claims === null) return refused('invalid');\n if (\n claims.scope?.payload !== undefined &&\n (!isValidPayloadScope(claims.scope.payload) || !Number.isFinite(claims.expiresAt))\n ) {\n return refused('invalid');\n }\n const now = (strategy.now ?? Date.now)();\n if (claims.expiresAt !== undefined && claims.expiresAt <= now) return refused('expired');\n return {\n authorized: true,\n outcome: 'authorized',\n context: createAuthorizedPreviewContext({\n strategy: 'verifier',\n subject: claims.subject,\n authorizedAt: now,\n expiresAt: claims.expiresAt,\n scope: claims.scope ?? {},\n payloadHeaders: claims.payloadHeaders ?? {},\n }),\n };\n}\n","/**\n * The body cap and phase timers use the same positive-integer validation.\n * Keeping it here leaves the endpoint's transport and request lifetime together\n * while all three existing limits retain their defaults and error messages.\n */\n\nexport function positiveIntegerLimit(\n name: 'bodyBytes' | 'timeoutMs' | 'totalTimeoutMs',\n value: number | undefined,\n fallback: number,\n maximum: number,\n): number {\n const resolved = value ?? fallback;\n if (!Number.isSafeInteger(resolved) || resolved <= 0 || resolved > maximum) {\n throw new RangeError(\n `payload-live-preview: createFragmentEndpoint() limits.${name} must be a positive integer no greater than ${String(maximum)}.`,\n );\n }\n return resolved;\n}\n","/**\n * The fragment wire protocol: what the browser posts to a fragment endpoint\n * and what it answers. Both sides validate the shape. The request names the\n * page by its own route and query and the boundary by its registry id; nothing\n * on the wire carries code, templates, import paths or file paths. See ADR 0011.\n */\n\n/** Bumped when the request or response shape changes incompatibly. @internal */\nexport const FRAGMENT_PROTOCOL_VERSION = 1;\n/** @internal */\nexport const FRAGMENT_VERSION_HEADER = 'x-payload-fragment-version';\n\n/** @internal */\nexport interface FragmentRequestBody {\n /** Registry id of the boundary (`data-payload-fragment`). */\n readonly fragment: string;\n /** `data-payload-fragment-key`, when several boundaries share one id. */\n readonly key?: string;\n /** The page route the boundary belongs to; authorization is bound to it. */\n readonly route: string;\n /** The page's query string, so a `previewToken` in the URL reaches the endpoint. */\n readonly search: string;\n readonly revision: number;\n readonly locale?: string;\n readonly collectionSlug?: string;\n readonly globalSlug?: string;\n /** The unsaved form state as the admin posted it, after the runtime's merge. */\n readonly fields: Readonly<Record<string, unknown>>;\n}\n\n/** @internal */\nexport interface FragmentResponseBody {\n /** The boundary's new inner HTML. */\n readonly html: string;\n readonly boundary: { readonly id: string; readonly key?: string };\n /** Echoes the request; the client discards a response for another revision. */\n readonly revision: number;\n readonly metadata: {\n readonly renderedAt: string;\n /** What rendered it, e.g. `astro-container`. */\n readonly renderer: string;\n readonly durationMs?: number;\n };\n}\n\n// Bounds the walk over a body anyone may post, not the content: a bulleted list\n// in a column's rich text inside a layout block is 13 levels, a list nested\n// five levels 29 (ADR 0027). The byte cap bounds the rest.\n/** Fixed upper bound for validation before authorization. @internal */\nexport const MAX_FIELD_DEPTH = 64;\n\nfunction depthOf(value: unknown, depth: number, maxDepth: number): number {\n if (depth > maxDepth || typeof value !== 'object' || value === null) return depth;\n let deepest = depth;\n for (const child of Object.values(value)) {\n deepest = Math.max(deepest, depthOf(child, depth + 1, maxDepth));\n if (deepest > maxDepth) break;\n }\n return deepest;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** Shape check for a request body; `null` when it is not one. @internal */\nexport function parseFragmentRequest(\n value: unknown,\n maxFieldDepth = MAX_FIELD_DEPTH,\n): FragmentRequestBody | null {\n const result = parseFragmentRequestResult(value, maxFieldDepth);\n return result === 'field-depth' ? null : result;\n}\n\n/** Request validation with a distinct depth refusal for endpoint diagnostics. @internal */\nexport function parseFragmentRequestResult(\n value: unknown,\n maxFieldDepth = MAX_FIELD_DEPTH,\n): FragmentRequestBody | 'field-depth' | null {\n if (!Number.isInteger(maxFieldDepth) || maxFieldDepth < 0 || maxFieldDepth > MAX_FIELD_DEPTH) {\n return null;\n }\n if (!isRecord(value)) return null;\n const fragment = value['fragment'];\n if (typeof fragment !== 'string' || !/^[a-z][a-z0-9-]{0,63}$/iu.test(fragment)) return null;\n const key = value['key'];\n if (key !== undefined && (typeof key !== 'string' || key.length > 128)) return null;\n const route = value['route'];\n if (typeof route !== 'string' || !route.startsWith('/') || route.length > 2048) return null;\n const search = value['search'];\n if (\n typeof search !== 'string' ||\n search.length > 4096 ||\n (search !== '' && !search.startsWith('?'))\n ) {\n return null;\n }\n const revision = value['revision'];\n if (typeof revision !== 'number' || !Number.isInteger(revision) || revision < 0) return null;\n const slugs: (string | undefined)[] = [];\n for (const name of ['locale', 'collectionSlug', 'globalSlug'] as const) {\n const slug = value[name];\n if (slug === undefined) {\n slugs.push(undefined);\n continue;\n }\n if (typeof slug !== 'string' || slug.length > 128) return null;\n slugs.push(slug);\n }\n const [locale, collectionSlug, globalSlug] = slugs;\n const fields = value['fields'];\n if (!isRecord(fields)) return null;\n if (depthOf(fields, 0, maxFieldDepth) > maxFieldDepth) return 'field-depth';\n return {\n fragment,\n ...(typeof key === 'string' ? { key } : {}),\n route,\n search,\n revision,\n ...(locale !== undefined ? { locale } : {}),\n ...(collectionSlug !== undefined ? { collectionSlug } : {}),\n ...(globalSlug !== undefined ? { globalSlug } : {}),\n fields,\n };\n}\n\n/** Shape check for a response body; `null` when it is not one. @internal */\nexport function parseFragmentResponse(value: unknown): FragmentResponseBody | null {\n if (!isRecord(value)) return null;\n const { html, boundary, revision, metadata } = value;\n if (typeof html !== 'string') return null;\n if (!isRecord(boundary) || typeof boundary['id'] !== 'string') return null;\n if (boundary['key'] !== undefined && typeof boundary['key'] !== 'string') return null;\n if (typeof revision !== 'number') return null;\n if (\n !isRecord(metadata) ||\n typeof metadata['renderedAt'] !== 'string' ||\n typeof metadata['renderer'] !== 'string'\n ) {\n return null;\n }\n return value as unknown as FragmentResponseBody;\n}\n","/**\n * The fragment endpoint, without a component system (ADR 0011): it renders a\n * registered boundary from unsaved form state for an authorized preview, and\n * nothing else. The browser names a registry id; the server decides what that\n * id renders.\n *\n * Everything here is framework-neutral — method and origin checks, the body\n * limit, the protocol, authorization, the registry lookup, the timeouts and the\n * response shape. Each server adapter binds one renderer and its native route\n * shape; Astro, Next.js, SvelteKit and Nuxt all delegate the decisions here.\n */\nimport {\n authorizePreviewRequest,\n type PreviewAuthorizationStrategy,\n} from '@security/preview-authorization';\nimport type { PreviewAuthorization } from '@security/preview-verdict';\nimport type { AuthorizedPreviewContext } from '@/types/authorized-preview';\nimport {\n isPayloadScopeCurrent,\n matchesPreviewDocument,\n matchesPreviewDocumentData,\n} from '@security/preview-scope';\nimport { runAuthorizeHook } from './authorize-hook';\nimport { warnOnce } from '@/types/dev-warning';\nimport type { PreviewAdapterOptions } from './options';\nimport { positiveIntegerLimit } from './fragment-limits';\nimport {\n FRAGMENT_PROTOCOL_VERSION,\n FRAGMENT_VERSION_HEADER,\n MAX_FIELD_DEPTH,\n parseFragmentRequestResult,\n type FragmentRequestBody,\n type FragmentResponseBody,\n} from '@/types/fragment-protocol';\n\n/** Everything a registry entry may use to compute its props. */\nexport interface FragmentRenderInput {\n readonly id: string;\n readonly key: string | undefined;\n readonly revision: number;\n readonly fields: Readonly<Record<string, unknown>>;\n readonly locale: string | undefined;\n readonly collectionSlug: string | undefined;\n readonly globalSlug: string | undefined;\n readonly route: string;\n readonly authorization: AuthorizedPreviewContext;\n /** Aborts when the request, its total deadline, or a render phase ends early. */\n readonly signal: AbortSignal;\n readonly request: Request;\n /** What the framework's server code put on this request: Astro `locals`, SvelteKit `event.locals`, Nuxt `event.context`; Next.js none (ADR 0029). */\n readonly locals: unknown;\n}\n\n/**\n * `Props extends object`, not `Record<string, unknown>`: an `interface` has no\n * implicit index signature, so the natural way to type a component's props\n * would not satisfy the narrower constraint and every consumer would have to\n * restate their props as a type alias. The renderer widens once, where the\n * props are handed to it.\n */\nexport interface FragmentRegistryEntry<Component, Props extends object = object> {\n readonly component: Component;\n /** Props for the component, computed from the input; never from request-controlled code. */\n readonly props: (input: FragmentRenderInput) => Props | Promise<Props>;\n}\n\nexport type FragmentRegistry<Component> = Readonly<\n Record<string, FragmentRegistryEntry<Component>>\n>;\n\n/** Renders a component with props to HTML. Each adapter supplies its own. */\nexport type FragmentRenderer<Component> = (\n component: Component,\n props: Record<string, unknown>,\n input: FragmentRenderInput,\n) => Promise<string>;\n\nexport interface FragmentEndpointOptions<Component> {\n /** The only things this endpoint can render. */\n readonly registry: FragmentRegistry<Component>;\n /**\n * The middleware's `authorizePreview` hook — same type, same rules: a\n * context `authorizePreviewRequest()` produced authorizes, anything else\n * refuses, a `PreviewConfigurationError` is loud. It is called with the\n * page request the fragment belongs to (route, search, and this request's\n * headers), so a token stays bound to its route and a session is the\n * visitor's own. One of `authorizePreview` and `authorize` is required.\n */\n readonly authorizePreview?: NonNullable<PreviewAdapterOptions['authorizePreview']>;\n /** A strategy for `authorizePreviewRequest()`, when there is no hook to share. Exclusive with `authorizePreview`. */\n readonly authorize?: PreviewAuthorizationStrategy;\n /** Override the adapter's renderer (tests, another component system). */\n readonly render?: FragmentRenderer<Component>;\n /** Origins besides the page's own that may call the endpoint. Default: none. */\n readonly allowedOrigins?: readonly string[];\n readonly limits?: {\n /** Largest streamed request body in bytes. Default 64 KiB. */\n readonly bodyBytes?: number;\n /** Body-read and per-render-phase timeout. Default 5000 ms. */\n readonly timeoutMs?: number;\n /** Maximum nesting depth of `fields`. Integer from 0 to 64; default 64. */\n readonly fieldDepth?: number;\n /** One deadline across body, authorization, props and rendering. Default: disabled. */\n readonly totalTimeoutMs?: number;\n };\n}\n\n/** What an adapter adds to the consumer's options: its renderer and the name that goes in the response metadata. */\nexport interface FragmentEndpointBinding<Component> {\n readonly render: FragmentRenderer<Component>;\n readonly rendererName: string;\n /** How the framework transport releases bytes after the endpoint's cap. */\n readonly overLimitBody?: 'cancel' | 'drain';\n}\n\nconst DEFAULT_BODY_BYTES = 64 * 1024;\nconst DEFAULT_TIMEOUT_MS = 5_000;\nconst MAX_TIMER_MS = 2_147_483_647;\n\nconst NO_STORE_HEADERS: Readonly<Record<string, string>> = {\n 'cache-control': 'private, no-store',\n 'x-content-type-options': 'nosniff',\n vary: 'Cookie',\n [FRAGMENT_VERSION_HEADER]: String(FRAGMENT_PROTOCOL_VERSION),\n};\n\n/** A refusal carries an error code and, for depth limits, the configured cap. */\nfunction refuse(status: number, error: string, maxDepth?: number): Response {\n return new Response(JSON.stringify({ error, ...(maxDepth !== undefined ? { maxDepth } : {}) }), {\n status,\n headers: { ...NO_STORE_HEADERS, 'content-type': 'application/json; charset=utf-8' },\n });\n}\n\nfunction sameOrigin(request: Request, allowed: ReadonlySet<string>): boolean {\n const site = request.headers.get('sec-fetch-site');\n if (site !== null && site !== 'same-origin' && site !== 'none') return false;\n const origin = request.headers.get('origin');\n if (origin === null) return true;\n return origin === new URL(request.url).origin || allowed.has(origin);\n}\n\nfunction scopeAllows(\n context: AuthorizedPreviewContext,\n body: FragmentRequestBody,\n page: URL,\n): boolean {\n const scope = context.scope;\n if (scope.locale !== undefined && scope.locale !== body.locale) return false;\n if (scope.payload !== undefined) {\n if (\n !isPayloadScopeCurrent(context) ||\n (scope.audience !== undefined && scope.audience !== page.origin) ||\n (scope.path !== undefined && scope.path !== page.pathname)\n ) {\n return false;\n }\n if (body.collectionSlug !== undefined && body.globalSlug !== undefined) return false;\n if (\n !matchesPreviewDocument(scope.payload.document, {\n kind: body.globalSlug === undefined ? 'collection' : 'global',\n slug: body.globalSlug ?? body.collectionSlug,\n id: body.fields['id'],\n })\n ) {\n return false;\n }\n if (!matchesPreviewDocumentData(scope.payload.document, body.fields)) return false;\n }\n return true;\n}\n\ntype BodyReadResult =\n | { readonly kind: 'parsed'; readonly value: unknown }\n | { readonly kind: 'too-large' | 'timed-out' | 'unreadable' };\n\ntype EndpointStopReason = 'request-aborted' | 'total-timeout' | 'phase-timeout';\n\nclass EndpointStopped extends Error {\n override readonly name = 'EndpointStopped';\n}\n\ninterface EndpointRequestScope {\n readonly signal: AbortSignal;\n readonly reason: () => EndpointStopReason | undefined;\n readonly run: <T>(work: () => T | PromiseLike<T>, phaseTimeoutMs?: number) => Promise<T>;\n readonly dispose: () => void;\n}\n\n/** One cooperative lifetime for all asynchronous work started by an accepted POST. */\nfunction createEndpointRequestScope(\n requestSignal: AbortSignal,\n totalTimeoutMs: number | undefined,\n): EndpointRequestScope {\n const controller = new AbortController();\n const deadline = totalTimeoutMs === undefined ? undefined : performance.now() + totalTimeoutMs;\n let stopped: EndpointStopReason | undefined;\n let resolveStopped: ((reason: EndpointStopReason) => void) | undefined;\n const stoppedPromise = new Promise<EndpointStopReason>((resolve) => {\n resolveStopped = resolve;\n });\n const stop = (reason: EndpointStopReason): void => {\n if (stopped !== undefined) return;\n stopped = reason;\n controller.abort(reason);\n resolveStopped?.(reason);\n };\n const abort = (): void => {\n stop('request-aborted');\n };\n requestSignal.addEventListener('abort', abort, { once: true });\n // AbortSignal does not replay an abort that landed just before registration.\n if (requestSignal.aborted) abort();\n const totalTimer =\n totalTimeoutMs === undefined\n ? undefined\n : setTimeout(() => {\n stop('total-timeout');\n }, totalTimeoutMs);\n const check = (): void => {\n // A long synchronous phase can finish before an overdue timer gets its turn.\n if (deadline !== undefined && performance.now() >= deadline) stop('total-timeout');\n if (stopped !== undefined) throw new EndpointStopped(stopped);\n };\n\n return {\n signal: controller.signal,\n reason: () => stopped,\n run: async <T>(work: () => T | PromiseLike<T>, phaseTimeoutMs?: number): Promise<T> => {\n check();\n const phaseTimer =\n phaseTimeoutMs === undefined\n ? undefined\n : setTimeout(() => {\n stop('phase-timeout');\n }, phaseTimeoutMs);\n try {\n // The race attaches rejection handlers to both promises, including a\n // late rejection by work that ignores the cooperative signal.\n const value = await Promise.race([\n Promise.resolve().then(() => {\n check();\n return work();\n }),\n stoppedPromise.then((reason) => {\n throw new EndpointStopped(reason);\n }),\n ]);\n // Cooperative work may settle from the abort event itself. The stop\n // remains authoritative, so no following phase starts after it.\n check();\n return value;\n } catch (error) {\n check();\n throw error;\n } finally {\n if (phaseTimer !== undefined) clearTimeout(phaseTimer);\n }\n },\n dispose: () => {\n if (totalTimer !== undefined) clearTimeout(totalTimer);\n requestSignal.removeEventListener('abort', abort);\n },\n };\n}\n\n/** A declared length may refuse early, but only consumed bytes may admit. */\nfunction declaredLengthExceeds(request: Request, limit: number): boolean {\n const declared = request.headers.get('content-length');\n if (declared === null || !/^[0-9]+$/u.test(declared)) return false;\n const normalized = declared.replace(/^0+/u, '') || '0';\n const boundary = String(limit);\n return (\n normalized.length > boundary.length ||\n (normalized.length === boundary.length && normalized > boundary)\n );\n}\n\n/** Cancel without letting a request-controlled stream delay or reject the response. */\nfunction cancelStream(\n stream: ReadableStream<Uint8Array> | null,\n reason: 'too-large' | 'timed-out' | 'unreadable',\n): void {\n if (stream === null || stream.locked) return;\n try {\n void Promise.resolve(stream.cancel(reason)).catch(() => undefined);\n } catch {\n // A broken transport is still one generic body refusal.\n }\n}\n\nfunction signalIsAborted(signal: AbortSignal): boolean {\n return signal.aborted;\n}\n\n/** Read one Web Request body under an actual-byte cap and one total read deadline. */\nasync function readBody(\n request: Request,\n signal: AbortSignal,\n limit: number,\n timeoutMs: number,\n overLimitBody: 'cancel' | 'drain',\n): Promise<BodyReadResult> {\n const stream = request.body;\n if (signalIsAborted(signal) || request.bodyUsed || stream?.locked === true) {\n cancelStream(stream, 'unreadable');\n return { kind: 'unreadable' };\n }\n if (declaredLengthExceeds(request, limit)) {\n // Do not cancel a body no application reader acquired. SvelteKit maps\n // cancellation to `IncomingMessage.destroy()`, which resets the socket\n // before it can write this endpoint's 413 response. The framework owns\n // disposal of an unread transport after the handler returns.\n return { kind: 'too-large' };\n }\n if (stream === null) return { kind: 'parsed', value: null };\n\n let reader: ReadableStreamDefaultReader<Uint8Array>;\n try {\n reader = stream.getReader();\n } catch {\n cancelStream(stream, 'unreadable');\n return { kind: 'unreadable' };\n }\n\n type StopReason = 'too-large' | 'timed-out' | 'unreadable';\n type ReadRace =\n | { readonly kind: 'read'; readonly result: ReadableStreamReadResult<Uint8Array> }\n | { readonly kind: 'read-error' }\n | { readonly kind: 'stopped'; readonly reason: StopReason };\n let stopped: StopReason | undefined;\n let resolveStopped: ((result: ReadRace) => void) | undefined;\n const stoppedPromise = new Promise<ReadRace>((resolve) => {\n resolveStopped = resolve;\n });\n const stop = (reason: StopReason): void => {\n if (stopped !== undefined) return;\n stopped = reason;\n resolveStopped?.({ kind: 'stopped', reason });\n try {\n void Promise.resolve(reader.cancel(reason)).catch(() => undefined);\n } catch {\n // The first stop reason remains authoritative even if cancellation fails.\n }\n };\n const abort = (): void => {\n stop('unreadable');\n };\n signal.addEventListener('abort', abort, { once: true });\n // An abort can land between the preflight check and listener registration.\n // AbortSignal does not replay that event to a late listener.\n if (signalIsAborted(signal)) abort();\n const timer = setTimeout(() => {\n stop('timed-out');\n }, timeoutMs);\n const decoder = new TextDecoder();\n let text = '';\n let total = 0;\n let overLimit = false;\n\n try {\n for (;;) {\n const read = Promise.resolve()\n .then(() => reader.read())\n .then<ReadRace, ReadRace>(\n (result) => ({ kind: 'read', result }),\n () => ({ kind: 'read-error' }),\n );\n const next = await Promise.race([read, stoppedPromise]);\n if (next.kind === 'stopped') return { kind: next.reason };\n if (next.kind === 'read-error') {\n if (overLimit) return { kind: 'too-large' };\n stop('unreadable');\n return { kind: 'unreadable' };\n }\n if (stopped !== undefined) return { kind: stopped };\n if (next.result.done) {\n if (overLimit) return { kind: 'too-large' };\n break;\n }\n if (overLimit) continue;\n if (next.result.value.byteLength > limit - total) {\n // SvelteKit's Node bridge implements Web-stream cancellation as\n // IncomingMessage.destroy(). Drain there under this same deadline so\n // the framework can write the 413; no discarded byte is retained or\n // parsed. Fetch-native transports still cancel immediately.\n if (overLimitBody === 'drain') {\n overLimit = true;\n continue;\n }\n stop('too-large');\n return { kind: 'too-large' };\n }\n total += next.result.value.byteLength;\n try {\n text += decoder.decode(next.result.value, { stream: true });\n } catch {\n stop('unreadable');\n return { kind: 'unreadable' };\n }\n }\n try {\n text += decoder.decode();\n return { kind: 'parsed', value: JSON.parse(text) as unknown };\n } catch {\n // A complete body under the byte cap can still be the wrong shape.\n return { kind: 'parsed', value: null };\n }\n } finally {\n clearTimeout(timer);\n signal.removeEventListener('abort', abort);\n try {\n reader.releaseLock();\n } catch {\n // Some non-conforming transports keep a read pending after cancel.\n }\n }\n}\n\ntype FragmentAuthorizer = (pageRequest: Request) => Promise<PreviewAuthorization>;\n\n/** One authorizer from the two options: the hook decides as it does in the middleware, a strategy as `authorizePreviewRequest()` does. */\nfunction authorizerFor<Component>(options: FragmentEndpointOptions<Component>): FragmentAuthorizer {\n const { authorize, authorizePreview } = options;\n if (authorizePreview !== undefined && authorize !== undefined) {\n throw new Error(\n 'payload-live-preview: createFragmentEndpoint() takes `authorizePreview` or `authorize`, ' +\n 'not both — pass the middleware hook as `authorizePreview`, or a strategy as `authorize`.',\n );\n }\n if (authorizePreview !== undefined) {\n return (pageRequest) => runAuthorizeHook(() => authorizePreview(pageRequest));\n }\n if (authorize !== undefined) {\n return (pageRequest) => authorizePreviewRequest(pageRequest, authorize);\n }\n throw new Error(\n 'payload-live-preview: createFragmentEndpoint() needs `authorizePreview` (the middleware hook) ' +\n 'or `authorize` (a strategy); without one it would render drafts for anyone.',\n );\n}\n\n/**\n * The endpoint as a plain `Request` → `Response` function. Adapters wrap it in\n * whatever their framework hands a route handler.\n */\nexport function createFragmentEndpointHandler<Component>(\n options: FragmentEndpointOptions<Component>,\n binding: FragmentEndpointBinding<Component>,\n): (request: Request, locals?: unknown) => Promise<Response> {\n const authorize = authorizerFor(options);\n const render = options.render ?? binding.render;\n const rendererName = options.render === undefined ? binding.rendererName : 'custom';\n const allowed = new Set(options.allowedOrigins ?? []);\n const bodyLimit = positiveIntegerLimit(\n 'bodyBytes',\n options.limits?.bodyBytes,\n DEFAULT_BODY_BYTES,\n Number.MAX_SAFE_INTEGER,\n );\n const timeoutMs = positiveIntegerLimit(\n 'timeoutMs',\n options.limits?.timeoutMs,\n DEFAULT_TIMEOUT_MS,\n MAX_TIMER_MS,\n );\n const totalTimeoutMs =\n options.limits?.totalTimeoutMs === undefined\n ? undefined\n : positiveIntegerLimit('totalTimeoutMs', options.limits.totalTimeoutMs, 0, MAX_TIMER_MS);\n const { fieldDepth = MAX_FIELD_DEPTH } = options.limits ?? {};\n if (!Number.isInteger(fieldDepth) || fieldDepth < 0 || fieldDepth > MAX_FIELD_DEPTH) {\n throw new TypeError(\n 'createFragmentEndpoint: limits.fieldDepth must be an integer from 0 to 64',\n );\n }\n const registry = options.registry;\n\n return async (request, locals) => {\n if (request.method !== 'POST') return refuse(405, 'method');\n if (!sameOrigin(request, allowed)) return refuse(403, 'origin');\n const type = request.headers.get('content-type') ?? '';\n if (!type.toLowerCase().startsWith('application/json')) return refuse(415, 'content-type');\n const scope = createEndpointRequestScope(request.signal, totalTimeoutMs);\n const bodyState = { started: false, read: false };\n try {\n const raw = await scope.run(() => {\n bodyState.started = true;\n return readBody(\n request,\n scope.signal,\n bodyLimit,\n timeoutMs,\n binding.overLimitBody ?? 'cancel',\n );\n });\n if (raw.kind !== 'parsed') {\n if (raw.kind === 'too-large') return refuse(413, 'body');\n if (raw.kind === 'timed-out') return refuse(408, 'body');\n return refuse(400, 'body');\n }\n const body = parseFragmentRequestResult(raw.value, fieldDepth);\n if (body === 'field-depth') return refuse(400, 'field-depth', fieldDepth);\n if (body === null) return refuse(400, 'shape');\n bodyState.read = true;\n\n // Authorize as the page would, so a token stays bound to the route it was\n // issued for and a session is the visitor's own.\n const origin = new URL(request.url).origin;\n const pageRequest = new Request(`${origin}${body.route}${body.search}`, {\n headers: request.headers,\n signal: scope.signal,\n });\n const authorization = await scope.run(() => authorize(pageRequest));\n if (\n !authorization.authorized ||\n !scopeAllows(authorization.context, body, new URL(pageRequest.url))\n ) {\n return refuse(403, 'unauthorized');\n }\n const entry = Object.prototype.hasOwnProperty.call(registry, body.fragment)\n ? registry[body.fragment]\n : undefined;\n if (entry === undefined) return refuse(404, 'fragment');\n\n const input: FragmentRenderInput = {\n locals,\n id: body.fragment,\n key: body.key,\n revision: body.revision,\n fields: body.fields,\n locale: body.locale,\n collectionSlug: body.collectionSlug,\n globalSlug: body.globalSlug,\n route: body.route,\n authorization: authorization.context,\n signal: scope.signal,\n request,\n };\n const started = Date.now();\n let html: string;\n try {\n const props = await scope.run(() => entry.props(input), timeoutMs);\n if (\n input.authorization.scope.payload !== undefined &&\n !isPayloadScopeCurrent(input.authorization)\n ) {\n return refuse(403, 'unauthorized');\n }\n // The one widening: the site types its props as it likes (see\n // FragmentRegistryEntry), the renderer takes a record of them.\n const record = props as Record<string, unknown>;\n html = await scope.run(() => render(entry.component, record, input), timeoutMs);\n if (\n input.authorization.scope.payload !== undefined &&\n !isPayloadScopeCurrent(input.authorization)\n ) {\n return refuse(403, 'unauthorized');\n }\n } catch (error) {\n if (error instanceof EndpointStopped) throw error;\n // The response stays generic; the server log is where the cause belongs,\n // and without it a 500 here is a boundary that silently never renders.\n warnOnce(\n `fragment-render:${body.fragment}`,\n `fragment \"${body.fragment}\" did not render: ${error instanceof Error ? error.message : String(error)}`,\n );\n return refuse(500, 'render');\n }\n const response: FragmentResponseBody = {\n html,\n boundary: { id: body.fragment, ...(body.key !== undefined ? { key: body.key } : {}) },\n revision: body.revision,\n metadata: {\n renderedAt: new Date().toISOString(),\n renderer: rendererName,\n durationMs: Date.now() - started,\n },\n };\n return new Response(JSON.stringify(response), {\n status: 200,\n headers: { ...NO_STORE_HEADERS, 'content-type': 'application/json; charset=utf-8' },\n });\n } catch (error) {\n if (!(error instanceof EndpointStopped)) throw error;\n // A pre-read stop still disposes the unread body, without acquiring it.\n if (!bodyState.started) cancelStream(request.body, 'unreadable');\n if (scope.reason() === 'total-timeout') return refuse(504, 'timeout');\n if (scope.reason() === 'phase-timeout') return refuse(500, 'render');\n return refuse(400, bodyState.read ? 'request' : 'body');\n } finally {\n scope.dispose();\n }\n };\n}\n","/**\n * The Next.js binding of the fragment endpoint: React as the renderer, and the\n * endpoint shaped as an App Router route handler. Everything the endpoint\n * decides is in `@adapters/shared/fragment-endpoint`.\n *\n * `react` and `react-dom` are optional peers loaded at first render. A project\n * that never renders a fragment — most of them — installs neither, and a\n * project that does has both anyway.\n */\nimport { lazyPeer, missingPeerError } from '@adapters/shared/optional-peer';\nimport {\n createFragmentEndpointHandler,\n type FragmentEndpointOptions as SharedOptions,\n type FragmentRegistry as SharedRegistry,\n type FragmentRegistryEntry as SharedRegistryEntry,\n type FragmentRenderer as SharedRenderer,\n type FragmentRenderInput,\n} from '@adapters/shared/fragment-endpoint';\n\nexport type { FragmentRenderInput } from '@adapters/shared/fragment-endpoint';\n\n/**\n * A React function component.\n *\n * The parameter is `never` rather than the props object it will receive:\n * parameters are checked contravariantly, so this accepts a component with any\n * props while a `Record<string, unknown>` would accept almost none. What the\n * component and its props have to agree on is checked by `defineFragment()`,\n * which is why that helper exists.\n */\nexport type ReactComponentLike = (props: never) => unknown;\n\nexport type FragmentRegistryEntry<Props extends object = object> = SharedRegistryEntry<\n ReactComponentLike,\n Props\n>;\n/** @internal */\nexport type FragmentRegistry = SharedRegistry<ReactComponentLike>;\n/** @internal */\nexport type FragmentRenderer = SharedRenderer<ReactComponentLike>;\nexport type FragmentEndpointOptions = SharedOptions<ReactComponentLike>;\n\nconst RENDERER_NAME = 'react-dom';\n\ninterface ReactRuntime {\n readonly createElement: (\n component: ReactComponentLike,\n props: Record<string, unknown>,\n ) => unknown;\n readonly renderToString: (element: unknown) => string;\n}\n\nconst loadReact = lazyPeer(async (): Promise<ReactRuntime> => {\n // Literal specifiers let the consumer's bundler resolve the same renderer peers\n // as its components. Loading still waits for the first fragment render.\n try {\n const [react, server] = await Promise.all([\n import('react') as Promise<{\n createElement: ReactRuntime['createElement'];\n }>,\n import('react-dom/server') as Promise<{\n renderToString: ReactRuntime['renderToString'];\n }>,\n ]);\n return { createElement: react.createElement, renderToString: server.renderToString };\n } catch (cause) {\n throw missingPeerError(['react', 'react-dom'], cause);\n }\n});\n\nconst renderWithReact: FragmentRenderer = async (component, props) => {\n const { createElement, renderToString } = await loadReact();\n return renderToString(createElement(component, props));\n};\n\n/**\n * Pairs a component with the props it takes, so the two cannot drift apart.\n * Without it a registry entry types its props as any record and a renamed prop\n * is found by the editor, in the preview, at the worst moment.\n *\n * ```ts\n * const registry = { hero: defineFragment(Hero, ({ fields }) => ({ title: String(fields.title ?? '') })) };\n * ```\n */\nexport function defineFragment<Props extends object>(\n component: (props: Props) => unknown,\n props: (input: FragmentRenderInput) => Props | Promise<Props>,\n): FragmentRegistryEntry<Props> {\n return { component, props };\n}\n\n/** Build the endpoint; export it as the `POST` of an App Router route handler. */\nexport function createFragmentEndpoint(\n options: FragmentEndpointOptions,\n): (request: Request) => Promise<Response> {\n const handler = createFragmentEndpointHandler(options, {\n render: renderWithReact,\n rendererName: RENDERER_NAME,\n });\n // Next.js calls a route handler as handler(request, { params }); that route\n // context is not the request's `locals` (ADR 0029), so only the request goes on.\n return (request) => handler(request);\n}\n","/**\n * `withLivePreview(nextConfig)` — the parts of a Next.js setup that belong in\n * `next.config.ts` rather than in a layout: the admin's host in\n * `allowedDevOrigins`, so Next's dev server does not refuse the admin's own\n * server actions behind a proxy, and `private, no-store` on a request that\n * carries preview intent.\n *\n * What it cannot do is inject the script: no config hook renders HTML. That\n * stays one import and one spread in `app/layout.tsx` (docs/nextjs.md), so this\n * is a two-line setup, not a one-line one — said plainly rather than implied\n * away.\n *\n * **And it writes no CSP.** A config rule cannot run `authorizePreview`, so it\n * can never be the place a privileged response change is decided (ADR 0006 §5).\n * It could not even widen `frame-ancestors` safely: Next collects every\n * matching rule into one object keyed by header name and applies it with\n * `setHeader`, and these rules are appended after the consumer's, so a policy\n * written here replaces the one the site already sends instead of adding to\n * it. Measured on Next.js 16.3.4 (`next build` + `next start`): a site sending\n * `frame-ancestors 'none'` answered a bare `/?preview=true` with\n * `frame-ancestors 'self' <admin>` and nothing else — its `script-src` gone,\n * for anyone who appends the query parameter. `frame-ancestors` for the admin\n * origin is `createLivePreviewMiddleware`'s, which merges into an existing\n * policy and only once the engine has authorized the request.\n */\n\n/** The slice of `next.config` this touches; everything else is passed through. */\nexport interface NextConfigLike {\n readonly allowedDevOrigins?: readonly string[];\n readonly headers?: () => Promise<readonly NextHeaderRule[]> | readonly NextHeaderRule[];\n readonly [option: string]: unknown;\n}\n\nexport interface NextHeaderRule {\n readonly source: string;\n readonly headers: readonly { readonly key: string; readonly value: string }[];\n readonly has?: readonly {\n readonly type: string;\n readonly key: string;\n readonly value?: string;\n }[];\n readonly [option: string]: unknown;\n}\n\nexport interface WithLivePreviewOptions {\n /** Payload admin origins. Required; their hosts are what `allowedDevOrigins` needs. */\n readonly allowedOrigins: readonly string[];\n /**\n * Query parameters that mark preview intent, matching the runtime's own\n * defaults. The cache header is set only for requests carrying one of them.\n */\n readonly previewQueryParams?: readonly string[];\n /** Add the admin origins to `allowedDevOrigins`. Default `true`. */\n readonly allowDevOrigins?: boolean;\n}\n\nconst DEFAULT_QUERY_PARAMS: readonly string[] = ['preview', 'draft', 'livePreview'];\n\nfunction hostOf(origin: string): string | undefined {\n try {\n return new URL(origin).host;\n } catch {\n return undefined;\n }\n}\n\n/** One rule per intent parameter: Next matches `has` entries as a conjunction. @internal */\nexport function previewHeaderRules(options: WithLivePreviewOptions): readonly NextHeaderRule[] {\n return (options.previewQueryParams ?? DEFAULT_QUERY_PARAMS).map((key) => ({\n source: '/:path*',\n // Next anchors `value` as a regular expression (`^${value}$`, matchHas in\n // next/dist/shared/lib/router/utils/prepare-destination). The runtime reads\n // `true` and `1` as intent, and so must the rule, or `?preview=1` stays\n // cacheable; the group keeps the anchors around both alternatives.\n has: [{ type: 'query', key, value: '(?:true|1)' }],\n headers: [\n // A preview response is one visitor's unsaved state; a shared cache must\n // never keep it, and the same rule the adapters apply belongs here. It\n // restricts and grants nothing, which is why an unverified request may\n // set it where it may not set a CSP.\n { key: 'Cache-Control', value: 'private, no-store' },\n ],\n }));\n}\n\n/**\n * ```ts\n * // next.config.ts\n * export default withLivePreview(nextConfig, {\n * allowedOrigins: [process.env.NEXT_PUBLIC_PAYLOAD_URL!],\n * });\n * ```\n */\nexport function withLivePreview(\n nextConfig: NextConfigLike,\n options: WithLivePreviewOptions,\n): NextConfigLike {\n if (options.allowedOrigins.length === 0) {\n throw new Error(\n 'payload-live-preview: withLivePreview() needs at least one admin origin in ' +\n '`allowedOrigins`; without one there is no host to add to `allowedDevOrigins` and the ' +\n 'call would configure nothing.',\n );\n }\n const rules = previewHeaderRules(options);\n const existingHeaders = nextConfig.headers;\n const devOrigins =\n options.allowDevOrigins === false\n ? nextConfig.allowedDevOrigins\n : [\n ...(nextConfig.allowedDevOrigins ?? []),\n ...options.allowedOrigins\n .map(hostOf)\n .filter((host): host is string => host !== undefined),\n ];\n\n return {\n ...nextConfig,\n ...(devOrigins === undefined ? {} : { allowedDevOrigins: [...new Set(devOrigins)] }),\n headers: async () => [...(await (existingHeaders?.() ?? [])), ...rules],\n };\n}\n","/**\n * The route half of `delivery: 'asset'` for Next.js.\n *\n * ```ts\n * // app/payload-live-preview/[file]/route.ts\n * import { createRuntimeAssetRoute } from 'payload-live-preview/nextjs';\n *\n * export const { GET } = createRuntimeAssetRoute();\n * ```\n *\n * The dynamic segment is what carries the content hash. The handler answers\n * only the file name this package build produces and 404s everything else, so a\n * client holding a year-old `immutable` copy of some other build gets an\n * honest miss rather than different bytes under the same name.\n *\n * No route segment config is exported with it. `dynamic: 'force-static'` would\n * be tempting — the bytes are the same for every request — but on a dynamic\n * segment it asks Next to prerender one arbitrary param at build time. The\n * caching that matters is the response's own `immutable`, which browsers and\n * CDNs honour without Next's help.\n */\n\nimport { runtimeAssetResponse } from '@adapters/shared/runtime-asset';\nimport type { LivePreviewNextOptions } from './adapter';\n\n/** What a route file re-exports. */\nexport interface RuntimeAssetRoute {\n readonly GET: (request: Request) => Response;\n}\n\n/**\n * Takes the adapter's own options so the one object can be passed to both\n * halves: only `assetPath` and `runtime` are read, but those two are exactly\n * what the page and the route have to agree on, and `runtime: LEAN_RUNTIME`\n * means the page asks for that artifact's hash.\n */\nexport function createRuntimeAssetRoute(options: LivePreviewNextOptions = {}): RuntimeAssetRoute {\n return { GET: (request) => runtimeAssetResponse(request.url, options) };\n}\n","/**\n * `<LivePreviewScript />` — the delivery that charges an anonymous visitor\n * nothing.\n *\n * A root layout renders for every request, and the two helpers that served it\n * until now build the script whoever is asking: `livePreviewScriptProps()` and\n * `renderLivePreviewScript()` are synchronous, so they cannot wait for a\n * verdict and do not try. That is why the demo answered a `curl` without a\n * cookie with 195 342 of 254 707 bytes of preview runtime — once in the\n * document, once more escaped into the RSC flight payload underneath it.\n *\n * An async server component can wait. This one runs the same policy every\n * adapter runs — intent, then `authorizePreview` — and returns `null` unless\n * the answer is yes. Not a few hundred bytes of bootstrap for the public:\n * nothing, the same as the Astro middleware, the SvelteKit handle and the Nuxt\n * Nitro plugin already deliver.\n *\n * **`next` is not imported here and must not become a dependency.** The\n * component takes the request as a prop, the way `<LivePreviewRouteRefresh />`\n * takes the router's refresh, and the caller builds it from what the framework\n * hands a server component:\n *\n * ```tsx\n * // app/layout.tsx — the App Router\n * import { headers } from 'next/headers';\n * import { LivePreviewScript } from 'payload-live-preview/nextjs';\n *\n * export default async function RootLayout({ children }: { children: ReactNode }) {\n * const livePreview = await LivePreviewScript({\n * request: new Request(SITE_URL, { headers: await headers() }),\n * inject: 'always',\n * allowedOrigins: [ADMIN_URL],\n * authorizePreview: authorize,\n * });\n * return (\n * <html lang=\"en\">\n * <head>{livePreview}</head>\n * <body>{children}</body>\n * </html>\n * );\n * }\n * ```\n *\n * It is awaited rather than rendered as `<LivePreviewScript />`: an element of\n * an async server component arrives in React's stream after the page, and the\n * React that Next.js 15.5 ships begins to hydrate `<head>` before it has, which\n * it reports as error #418 (docs/nextjs.md, \"Await it in the layout\").\n *\n * A `Request` rather than a shape of our own: it is what `authorizePreview`\n * and `shouldInject` already receive from the middleware, so one options object\n * serves both entry points and neither hook has to be written twice.\n *\n * The URL is the caller's to supply, and the recipe above says why `headers()`\n * alone is not enough: Next gives a server component the request headers and\n * cookies but not its URL, so a layout cannot see `?preview=true` and the\n * `query` signal — the 2.0 default — cannot fire there. `inject: 'always'`\n * then makes `authorizePreview` the single gate, which is the stricter reading\n * anyway and exactly what LP-8 needs. A page, which does get `searchParams`,\n * can pass the real URL and keep intent as the cheap pre-filter it is.\n * docs/nextjs.md carries both recipes.\n */\n\nimport { createPreviewPolicy } from '@adapters/shared/policy';\nimport { bindDecisionHooks } from '@adapters/shared/response';\nimport { lazyPeer } from '@adapters/shared/optional-peer';\nimport { livePreviewScriptProps, type LivePreviewNextOptions } from './adapter';\nimport type { LivePreviewScriptProps } from './adapter';\n\n/** What the component takes: every adapter option, plus the request it decides for. */\nexport interface LivePreviewScriptComponentProps extends LivePreviewNextOptions {\n /**\n * The request this render answers: in the App Router, a `Request` built from\n * the URL and `await headers()`. A promise is accepted so the caller need not\n * resolve `headers()` first.\n */\n readonly request: Request | Promise<Request>;\n /** CSP nonce for the element, when the application manages one. */\n readonly nonce?: string;\n}\n\n/**\n * The `<script>` this resolves to, described structurally rather than as\n * `ReactElement`: the entry must not carry React's types any more than its\n * code, and a JSX consumer accepts this shape as a node all the same.\n */\nexport interface LivePreviewScriptElement {\n readonly type: 'script';\n readonly props: LivePreviewScriptProps;\n readonly key: null;\n}\n\ntype CreateElement = (type: 'script', props: LivePreviewScriptProps) => LivePreviewScriptElement;\n\n/**\n * `react` is an optional peer of this package and a hard dependency of any app\n * that can render this component, so it is loaded at the first render that\n * produces an element — never at import, and never on a public request, which\n * returns before reaching this.\n */\nconst loadCreateElement = lazyPeer(async (): Promise<CreateElement> => {\n // A literal lets the app's bundler resolve its peer without an empty context.\n const react = (await import('react')) as {\n createElement: CreateElement;\n };\n return react.createElement;\n});\n\n/**\n * Resolves to the runtime's `<script>` element for an authorized preview and to\n * `null` for everyone else. Await it in the layout or page that owns `<head>`\n * and render the result there.\n */\nexport async function LivePreviewScript(\n props: LivePreviewScriptComponentProps,\n): Promise<LivePreviewScriptElement | null> {\n const { request, nonce, ...options } = props;\n const policy = createPreviewPolicy(options);\n const resolved = await request;\n const decision = await policy.decide(resolved, bindDecisionHooks(policy, options, resolved));\n if (!decision.inject) return null;\n const createElement = await loadCreateElement();\n return createElement(\n 'script',\n livePreviewScriptProps(nonce === undefined ? options : { ...options, nonce }),\n );\n}\n"],"mappings":"AAKA,IAGMA,EAAuB,eAG7B,SAASC,EAAgBC,EAAeC,GACtC,MAAMC,EAAOF,EAAMG,WAAWF,GAC9B,OAAgB,IAATC,GAAuB,KAATA,GAAwB,KAATA,GAAwB,KAATA,GAAwB,KAATA,CACpE,CAWA,SAASE,EAAkBJ,GACzB,IAAIK,EAAQ,EACRC,EAAMN,EAAMO,OAChB,KAAOF,EAAQC,GAAOP,EAAgBC,EAAOK,IAAQA,GAAS,EAC9D,KAAOC,EAAMD,GAASN,EAAgBC,EAAOM,EAAM,IAAIA,GAAO,EAC9D,OAAiB,IAAVD,GAAeC,IAAQN,EAAMO,OAASP,EAAQA,EAAMQ,MAAMH,EAAOC,EAC1E,CAGA,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ADuBD,EAAOyE,OAAOjE,EAAUT,EAAkBC,EAAQhH,EAASwH,KACpEuD,cACcuW,MAE1B,SACA5Q,OAAiC,IAAV/K,EAAsB3F,EAAU,IAAKA,EAAS2F,WAJ1C,IAM/B,Q","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"index.js","names":["CSP_ASCII_WHITESPACE","isCspWhitespace","value","index","code","charCodeAt","trimCspWhitespace","start","end","length","slice","asciiLowercase","replace","character","toLowerCase","buildFrameAncestors","options","self","origins","allowNone","seen","Set","out","push","add","origin","trimmed","trim","has","join","mergeCspPolicy","existing","additions","directives","Map","part","split","whitespaceIndex","search","name","set","rawName","rawAddition","Object","entries","addition","mode","current","get","merged","token","withoutNone","filter","assertMergeDepthExplicit","defaults","serverURL","mergeDepth","Error","isDevelopmentProcess","env","globalThis","process","warnOnce","key","message","holder","warned","console","warn","warnDeprecatedOptions","onUnboundChange","V2_ADAPTER_DEFAULTS","freeze","strict","previewSignals","V2_RUNTIME_DEFAULTS","disableReferrerDetection","eventSourcePolicy","skipUnchanged","sanitizerPolicy","V1_ADAPTER_DEFAULTS","V1_RUNTIME_DEFAULTS","RUNTIME_SOURCE","FRAGMENT_SOURCE","ROUTE_SOURCE","LOADER_SOURCE","LOADER_REACT_SOURCE","INLINE_CONFIG_KEYS","assertBuilt","source","artifact","strategyPrelude","config","fragmentEndpoint","routeStrategy","configStatement","profile","profileSlots","values","map","at","pop","JSON","stringify","buildConfigLiteral","wrapWithScriptTag","body","nonce","assertNonce","test","RangeError","normalizePath","path","runtimeAsset","runtime","fileName","contentHash","urlPath","assetPath","integrity","HEAD_INSERT","HTML_CONTENT_TYPE","META_CHARSET","resolvePolicyOptions","adapter","runtimeRow","disableLocalhostMatching","bindDecisionHooks","policy","request","shouldInject","authorizes","authorize","authorizePreview","renderScriptBody","facts","resolved","allowedOrigins","apiRoute","revealEditedField","debug","debounceMs","heartbeatMs","scopeBindingsByOwner","fragments","endpoint","onUnfaithfulPatch","autoBind","subfieldCoverage","hydration","softNavigationEvents","inlineScriptConfig","delivery","generateInlineScript","runtimeFor","asset","target","bootstrap","loaderFor","runtimeSrc","encode","generateLoaderScript","async","injectIntoResponse","response","scriptTag","headers","injected","html","head","exec","headEnd","headClose","indexOf","meta","injectIntoHead","clone","text","Headers","delete","Response","status","statusText","withCspHeader","decision","apply","withHeaders","cspMode","csp","cacheControl","vary","listed","includes","markUncacheable","applyCspHeaders","DEFAULT_QUERY_PARAMS","PreviewConfigurationError","refused","outcome","authorized","context","AUTHORIZED_PREVIEW_BRAND_KEY","BRAND","Symbol","for","isAuthorizedPreviewContext","isFrozen","createAuthorizedPreviewContext","fields","scope","payload","document","payloadHeaders","runAuthorizeHook","hook","result","error","isPreviewConfigurationError","verdictFrom","STAGED","NONE","isPreview","authorization","inject","exposeNonce","createPreviewPolicy","protocol","URL","assertStrictConfiguration","manageCsp","autoInject","decide","hooks","signals","queryParams","url","param","searchParams","getAll","alias","adminOrigins","configured","referer","refererOrigin","adminOrigin","hasPreviewIntent","previewQueryParams","previewIntentFor","verdict","frameAncestorsExtra","buildScriptSrcWithNonce","extra","strictDynamic","parts","e","scriptSrcExtra","policies","mergeCspHeader","buildPreviewCsp","generateCspNonce","bytes","Number","isInteger","String","crypto","fromGlobal","getRandomValues","resolveCrypto","buffer","Uint8Array","binary","byte","fromCharCode","btoa","Buffer","from","toString","replaceAll","base64UrlEncode","REACT_PAGE","createLivePreviewMiddleware","withCarriedNonce","applyDecision","livePreviewScriptProps","dangerouslySetInnerHTML","__html","renderLivePreviewScript","renderScriptTag","lazyPeer","load","pending","started","catch","cachedEncoder","DEFAULT_USERS_SLUG","COOKIE_NAME_PATTERN","COOKIE_VALUE_PATTERN","httpOriginFor","option","encoder","TextEncoder","fromBase64Url","padded","repeat","atob","pathSegment","isPreviewDocumentID","isSafeInteger","isPayloadScopeCurrent","expiresAt","isFinite","Date","now","matchesPreviewDocument","expected","actual","kind","slug","id","authorizePreviewRequest","strategy","type","cookieName","cookieNameFor","sentOrigin","header","maxLength","prefix","startsWith","extractCookie","maxCookieLength","timeoutMs","Math","max","fetchImpl","fetch","usersSlug","encodeURIComponent","forwarded","cookie","controller","AbortController","abort","signal","reason","isAborted","aborted","timer","addEventListener","once","setTimeout","DOMException","attempt","accept","ok","json","user","clearTimeout","removeEventListener","Array","isArray","collection","readUser","exp","readExpiry","subject","authorizedAt","authorizeSession","secret","byteLength","secretBytes","candidate","subtle","cryptoFor","transport","readToken","payloadText","payloadBytes","signature","verified","importKey","hash","hmacKey","verify","claims","parsed","parse","TextDecoder","decode","c","optionalString","parseClaims","iat","aud","audience","pur","purpose","pth","pathname","loc","locale","replay","first","store","consume","isUsed","markUsed","consumeTokenId","jti","sub","authorizeToken","username","password","rawPath","route","every","payloadAPIBase","isValidPayloadScope","authorizeVerifier","positiveIntegerLimit","fallback","maximum","FRAGMENT_VERSION_HEADER","MAX_FIELD_DEPTH","depthOf","depth","maxDepth","deepest","child","isRecord","parseFragmentRequestResult","maxFieldDepth","fragment","revision","slugs","collectionSlug","globalSlug","MAX_TIMER_MS","NO_STORE_HEADERS","refuse","EndpointStopped","cancelStream","stream","locked","Promise","resolve","cancel","signalIsAborted","createFragmentEndpointHandler","binding","pageRequest","authorizerFor","render","rendererName","allowed","bodyLimit","limits","bodyBytes","MAX_SAFE_INTEGER","totalTimeoutMs","fieldDepth","TypeError","registry","locals","method","site","sameOrigin","requestSignal","deadline","performance","stopped","resolveStopped","stoppedPromise","stop","totalTimer","check","run","work","phaseTimeoutMs","phaseTimer","race","then","dispose","createEndpointRequestScope","bodyState","read","raw","limit","overLimitBody","bodyUsed","declared","normalized","boundary","declaredLengthExceeds","reader","getReader","decoder","total","overLimit","next","done","releaseLock","readBody","Request","page","data","hasOwn","matchesPreviewDocumentData","scopeAllows","entry","prototype","hasOwnProperty","call","input","props","record","component","metadata","renderedAt","toISOString","renderer","durationMs","loadReact","react","server","all","createElement","renderToString","cause","packages","names","one","missingPeerError","renderWithReact","defineFragment","createFragmentEndpoint","handler","hostOf","host","previewHeaderRules","withLivePreview","nextConfig","rules","existingHeaders","devOrigins","allowDevOrigins","allowedDevOrigins","createRuntimeAssetRoute","GET","lastIndexOf","runtimeAssetResponse","loadCreateElement","LivePreviewScript"],"sources":["../../../src/security/csp.ts","../../../src/types/merge-depth.ts","../../../src/types/dev-warning.ts","../../../src/types/defaults-profile.ts","../../../src/inline/runtime.generated.ts","../../../src/inline/fragment.generated.ts","../../../src/inline/route.generated.ts","../../../src/inline/loader.generated.ts","../../../src/inline/loader-react.generated.ts","../../../src/types/inline-config.ts","../../../src/inline/generator.ts","../../../src/adapters/shared/runtime-asset.ts","../../../src/adapters/shared/html-inject.ts","../../../src/adapters/shared/policy-options.ts","../../../src/adapters/shared/response.ts","../../../src/adapters/shared/preview-request.ts","../../../src/security/preview-verdict.ts","../../../src/types/authorized-preview.ts","../../../src/adapters/shared/authorize-hook.ts","../../../src/adapters/shared/strict.ts","../../../src/adapters/shared/policy.ts","../../../src/core/navigation-lifecycle.ts","../../../src/adapters/nextjs/adapter.ts","../../../src/adapters/shared/optional-peer.ts","../../../src/security/preview-session.ts","../../../src/security/preview-token.ts","../../../src/security/preview-scope.ts","../../../src/security/preview-authorization.ts","../../../src/adapters/shared/fragment-limits.ts","../../../src/types/fragment-protocol.ts","../../../src/adapters/shared/fragment-endpoint.ts","../../../src/adapters/nextjs/fragments.ts","../../../src/adapters/nextjs/config.ts","../../../src/adapters/nextjs/asset-route.ts","../../../src/adapters/nextjs/script-component.ts"],"sourcesContent":["/**\n * Content-Security-Policy helpers: nonce generation, directive builders and\n * the header merge every adapter uses. Isomorphic; needs only Web Crypto.\n */\n\nconst DEFAULT_NONCE_BYTES = 16;\n\n/** CSP3's exact whitespace set: HTAB, LF, FF, CR, and SPACE. */\nconst CSP_ASCII_WHITESPACE = /[\\t\\n\\f\\r ]+/;\n\n/** Reads one code unit; an index past the end yields NaN, which matches nothing. */\nfunction isCspWhitespace(value: string, index: number): boolean {\n const code = value.charCodeAt(index);\n return code === 9 || code === 10 || code === 12 || code === 13 || code === 32;\n}\n\n/**\n * Trim CSP whitespace by scanning from both ends.\n *\n * The obvious `/^\\s+|\\s+$/` is superlinear by construction: for a long run the\n * trailing alternative is retried at every position. V8 happens to optimise the\n * shape away, but this header can come from a consumer's own response and this\n * module runs in every engine, so the guarantee has to come from the algorithm\n * rather than from one engine's optimiser.\n */\nfunction trimCspWhitespace(value: string): string {\n let start = 0;\n let end = value.length;\n while (start < end && isCspWhitespace(value, start)) start += 1;\n while (end > start && isCspWhitespace(value, end - 1)) end -= 1;\n return start === 0 && end === value.length ? value : value.slice(start, end);\n}\n\n/** CSP names are ASCII; Unicode case folding must not create directives. */\nfunction asciiLowercase(value: string): string {\n return value.replace(/[A-Z]/g, (character) => character.toLowerCase());\n}\n\n/** The one Web Crypto method this module calls; accepts Node's `webcrypto` without a cast. */\ninterface WebCryptoLike {\n getRandomValues: <T extends ArrayBufferView | null>(array: T) => T;\n}\n\nlet cryptoOverride: WebCryptoLike | undefined;\n\n/** Supply a Web Crypto implementation for runtimes without `globalThis.crypto`; `null` clears it. @internal */\nexport function setCspCrypto(crypto: WebCryptoLike | null): void {\n cryptoOverride = crypto ?? undefined;\n}\n\n/** A base64url nonce of `bytes` random bytes (default 16); throws without Web Crypto, since a predictable nonce silently defeats the CSP. @internal */\nexport function generateCspNonce(bytes: number = DEFAULT_NONCE_BYTES): string {\n if (!Number.isInteger(bytes) || bytes < 8) {\n throw new RangeError(`generateCspNonce: bytes must be an integer >= 8, got ${String(bytes)}`);\n }\n const crypto = resolveCrypto();\n if (!crypto) {\n throw new Error(\n 'generateCspNonce: Web Crypto is unavailable. On Node 18 call setCspCrypto(webcrypto) ' +\n \"once at startup, or run with --experimental-global-webcrypto. We won't fabricate \" +\n 'a predictable nonce — that would silently defeat the entire CSP.',\n );\n }\n const buffer = new Uint8Array(bytes);\n crypto.getRandomValues(buffer);\n return base64UrlEncode(buffer);\n}\n\nfunction resolveCrypto(): WebCryptoLike | undefined {\n if (cryptoOverride?.getRandomValues) return cryptoOverride;\n const fromGlobal = (globalThis as { crypto?: WebCryptoLike }).crypto;\n if (fromGlobal?.getRandomValues) return fromGlobal;\n return undefined;\n}\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n const base64 = typeof btoa === 'function' ? btoa(binary) : Buffer.from(bytes).toString('base64');\n return base64.replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');\n}\n\n/** A `frame-ancestors` source: `'self'`, `'none'`, or an origin. */\nexport type FrameAncestorSource = string;\n\nexport interface FrameAncestorsOptions {\n readonly self?: boolean;\n readonly origins?: readonly string[];\n readonly allowNone?: boolean;\n}\n\n/** The `frame-ancestors` value: `'self'` and the origins, deduplicated; `'none'` when empty. */\nexport function buildFrameAncestors(options: FrameAncestorsOptions = {}): string {\n const { self = true, origins = [], allowNone = false } = options;\n const seen = new Set<string>();\n const out: FrameAncestorSource[] = [];\n if (allowNone && !self && origins.length === 0) return \"'none'\";\n if (self) {\n out.push(\"'self'\");\n seen.add(\"'self'\");\n }\n for (const origin of origins) {\n const trimmed = origin.trim();\n if (trimmed.length === 0 || seen.has(trimmed)) continue;\n seen.add(trimmed);\n out.push(trimmed);\n }\n return out.length > 0 ? out.join(' ') : \"'none'\";\n}\n\n/**\n * A `script-src` value permitting one nonce plus optional extra sources.\n * `'strict-dynamic'` is opt-in: it makes CSP 3 browsers ignore `'self'` and\n * host sources, so every script on the page must then carry the nonce.\n * @internal\n */\nexport function buildScriptSrcWithNonce(\n nonce: string,\n options: {\n readonly self?: boolean;\n readonly extra?: readonly string[];\n readonly strictDynamic?: boolean;\n } = {},\n): string {\n if (nonce.length === 0) throw new RangeError('buildScriptSrcWithNonce: nonce is empty');\n const { self = true, extra = [], strictDynamic = false } = options;\n const parts: string[] = [];\n if (self) parts.push(\"'self'\");\n parts.push(`'nonce-${nonce}'`);\n if (strictDynamic) parts.push(\"'strict-dynamic'\");\n for (const e of extra) {\n const trimmed = e.trim();\n if (trimmed.length > 0) parts.push(trimmed);\n }\n return parts.join(' ');\n}\n\n/** `union` (default) adds sources to an existing directive; `replace` overwrites it. */\nexport interface CspDirectiveMerge {\n readonly value: string;\n readonly mode?: 'union' | 'replace';\n}\n\n/**\n * Merge directives into an existing `Content-Security-Policy` header value.\n * Commas separate policies (that is how `Headers.get()` joins repeated\n * headers); each is merged, because a browser enforces every policy and\n * widening only the last would leave the others blocking.\n */\nexport function mergeCspHeader(\n existing: string,\n additions: Readonly<Record<string, string | CspDirectiveMerge>>,\n): string {\n const policies = existing.split(',').filter((policy) => policy.trim().length > 0);\n if (policies.length === 0) return mergeCspPolicy('', additions);\n return policies.map((policy) => mergeCspPolicy(policy, additions)).join(', ');\n}\n\nfunction mergeCspPolicy(\n existing: string,\n additions: Readonly<Record<string, string | CspDirectiveMerge>>,\n): string {\n const directives = new Map<string, string>();\n for (const part of existing.split(';')) {\n const trimmed = trimCspWhitespace(part);\n if (trimmed.length === 0) continue;\n const whitespaceIndex = trimmed.search(CSP_ASCII_WHITESPACE);\n const name = asciiLowercase(whitespaceIndex < 0 ? trimmed : trimmed.slice(0, whitespaceIndex));\n // CSP3 §2.2.1: a user agent ignores later duplicates, so a looser\n // duplicate must not become the policy that is serialized.\n if (directives.has(name)) continue;\n const value = whitespaceIndex < 0 ? '' : trimCspWhitespace(trimmed.slice(whitespaceIndex));\n directives.set(name, value);\n }\n\n for (const [rawName, rawAddition] of Object.entries(additions)) {\n const name = asciiLowercase(rawName);\n const addition: CspDirectiveMerge =\n typeof rawAddition === 'string' ? { value: rawAddition } : rawAddition;\n const mode = addition.mode ?? 'union';\n const current = directives.get(name);\n if (mode === 'replace' || current === undefined || current.length === 0) {\n directives.set(name, addition.value);\n continue;\n }\n const seen = new Set<string>();\n const merged: string[] = [];\n for (const token of [\n ...current.split(CSP_ASCII_WHITESPACE),\n ...addition.value.split(CSP_ASCII_WHITESPACE),\n ]) {\n if (token.length === 0 || seen.has(token)) continue;\n seen.add(token);\n merged.push(token);\n }\n // `'none'` cannot coexist with other sources.\n const withoutNone = merged.filter((token) => token !== \"'none'\");\n directives.set(name, (withoutNone.length > 0 ? withoutNone : merged).join(' '));\n }\n\n const out: string[] = [];\n for (const [name, value] of directives) {\n out.push(value.length === 0 ? name : `${name} ${value}`);\n }\n return out.join('; ');\n}\n","/**\n * The one rule shared by the adapters, the client and the inline generator:\n * `serverURL` needs an explicit `mergeDepth` under the 2.0 defaults (ADR 0007,\n * entry 10). It lives in the leaf `types` domain because the inline generator\n * is server-side code that may not reach the browser runtime in `core`, and\n * three copies of the check had already drifted in what they treated as\n * \"no server\" and \"no depth\".\n */\n\nimport type { DefaultsProfile } from '@/types/defaults-profile';\n\n/**\n * The population depth is a deliberate choice; the 1.x default of 1 stays only\n * behind `defaults: 'v1'`. An empty `serverURL` fetches nothing and owes no\n * depth; `null` counts as omitted because the inline wire config carries it.\n */\nexport function assertMergeDepthExplicit(options: {\n readonly defaults?: DefaultsProfile | undefined;\n readonly serverURL?: string | undefined;\n readonly mergeDepth?: number | null | undefined;\n}): void {\n if (options.defaults === 'v1') return;\n if ((options.serverURL ?? '') === '' || options.mergeDepth != null) return;\n throw new Error(\n 'payload-live-preview: `serverURL` needs an explicit `mergeDepth` under the 2.0 defaults — ' +\n \"choose the population depth deliberately (0 for none), or pass `defaults: 'v1'` to keep \" +\n 'the 1.x default of 1 while migrating (ADR 0007, entry 10).',\n );\n}\n","/**\n * One development warning per process. The set of issued keys lives on\n * `globalThis` so two package copies in one process still warn once.\n */\n\nconst WARNED_KEY = '__payloadLivePreviewDeprecationsWarned';\n\n/** `true` outside a production build; `false` when `NODE_ENV` is production or unknown. */\nexport function isDevelopmentProcess(): boolean {\n try {\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process\n ?.env;\n if (env === undefined) return false;\n return env['NODE_ENV'] !== 'production';\n } catch {\n return false;\n }\n}\n\n/** Warn once per process for `key`, outside production only. */\nexport function warnOnce(key: string, message: string): void {\n if (!isDevelopmentProcess()) return;\n const holder = globalThis as unknown as Record<string, Set<string> | undefined>;\n const warned = (holder[WARNED_KEY] ??= new Set<string>());\n if (warned.has(key)) return;\n warned.add(key);\n try {\n console.warn(`[payload-live-preview] ${message}`);\n } catch {\n // A console that throws must not break a request.\n }\n}\n\n/**\n * The deprecated options the adapters and the inline generator both accept;\n * an adapter hands them on to the generator, and the shared keys keep that to\n * one warning each (ADR 0026).\n */\nexport function warnDeprecatedOptions(options: {\n readonly defaults?: string | undefined;\n readonly onUnboundChange?: string | undefined;\n}): void {\n if (options.defaults === 'v1') {\n warnOnce(\n 'defaults-v1',\n \"`defaults: 'v1'` is removed in 3.0: `pll migrate` writes the 1.x rows it stands for \" +\n 'into your options, where they keep working (ADR 0026).',\n );\n }\n if (options.onUnboundChange !== undefined) {\n warnOnce(\n 'on-unbound-change',\n \"`onUnboundChange` is removed in 3.0: name it `onUnfaithfulPatch`, where 'route' is \" +\n \"'escalate'; `pll migrate` renames it (ADR 0026).\",\n );\n }\n}\n\n/** Test hook: forget every warning issued so far. */\nexport function resetDevWarnings(): void {\n const holder = globalThis as unknown as Record<string, Set<string> | undefined>;\n holder[WARNED_KEY] = undefined;\n}\n","/**\n * The two defaults profiles, row by row. 2.0 ships `v2`; `defaults: 'v1'` opts\n * back into the 1.x table for a staged migration. Each row belongs to exactly\n * one side — the adapter's request decision or the browser runtime — and a\n * test asserts the profile assigns every readiness row that has an option, so\n * a row added later cannot be forgotten. See ADR 0007.\n *\n * It lives in the leaf `types` domain, like `merge-depth.ts`, because the\n * inline generator resolves the profile too, and the generator is server-side\n * code that may not reach the browser runtime in `core`.\n */\n\n/** `'v2'` is the 2.0 default; `'v1'` is the 1.x table. */\nexport type DefaultsProfile = 'v1' | 'v2';\n\n/** How the runtime decides which windows may post updates. */\nexport type EventSourcePolicy = 'any' | 'parent-or-opener';\n\n/** Readiness rows that are options, keyed by the option they set. */\nexport const READINESS_ROWS = Object.freeze({\n strict: 'production response changes require an authorized context',\n previewSignals: 'query-only intent signal',\n disableReferrerDetection: 'referrer trust off',\n eventSourcePolicy: 'messages must come from parent/opener',\n skipUnchanged: 'skip unchanged bindings by default',\n sanitizerPolicy: 'hardened sanitizer id/data-* policy',\n} as const);\n\n/** Options an adapter's request decision reads from the profile. */\nexport interface AdapterProfileDefaults {\n readonly strict: boolean;\n readonly previewSignals: readonly ('query' | 'fetch-dest' | 'referer')[];\n}\n\n/** Options the browser runtime reads from the profile (through the inline configuration). */\nexport interface RuntimeProfileDefaults {\n readonly disableReferrerDetection: boolean;\n readonly eventSourcePolicy: EventSourcePolicy;\n readonly skipUnchanged: boolean;\n readonly sanitizerPolicy: 'compat' | 'strict';\n}\n\nexport const V2_ADAPTER_DEFAULTS: AdapterProfileDefaults = Object.freeze({\n strict: true,\n previewSignals: Object.freeze(['query'] as const),\n});\n\nexport const V2_RUNTIME_DEFAULTS: RuntimeProfileDefaults = Object.freeze({\n disableReferrerDetection: true,\n eventSourcePolicy: 'parent-or-opener',\n skipUnchanged: true,\n sanitizerPolicy: 'strict',\n});\n\n/** The 1.x table, spelled out so the profiles compare row by row. */\nexport const V1_ADAPTER_DEFAULTS: AdapterProfileDefaults = Object.freeze({\n strict: false,\n previewSignals: Object.freeze(['query', 'fetch-dest', 'referer'] as const),\n});\n\nexport const V1_RUNTIME_DEFAULTS: RuntimeProfileDefaults = Object.freeze({\n disableReferrerDetection: false,\n eventSourcePolicy: 'any',\n skipUnchanged: false,\n sanitizerPolicy: 'compat',\n});\n\n/** Only an explicit `'v1'` opts out; everything else gets the hardened rows. */\nexport function adapterDefaultsFor(profile: DefaultsProfile | undefined): AdapterProfileDefaults {\n return profile === 'v1' ? V1_ADAPTER_DEFAULTS : V2_ADAPTER_DEFAULTS;\n}\n\nexport function runtimeDefaultsFor(profile: DefaultsProfile | undefined): RuntimeProfileDefaults {\n return profile === 'v1' ? V1_RUNTIME_DEFAULTS : V2_RUNTIME_DEFAULTS;\n}\n","// Auto-generated by scripts/build-runtime.ts — do not edit.\nexport interface RuntimeBuildInfo { readonly generatedAt: string; readonly size: number }\nexport const RUNTIME_SOURCE: string = /* @__PURE__ */ [\"(()=>{function e(e){return(\\\"object\\\"==typeof e&&null!==e||\\\"function\\\"==typeof e)&&\\\"function\\\"==typeof e.then&&(Promise.resolve(e).catch(()=>{}),!0)}function t(t){return(...n)=>{try{e(t(...n))}catch{}}}function n(){}function i(e){return e.onUnfaithfulPatch??(\\\"ignore\\\"===e.onUnboundChange?\\\"ignore\\\":\\\"escalate\\\")}function r(e,t,n,i){let r=e.onUnfaithfulPatch,l=t.reportedUnfaithful.has(n.element);if((l||\\\"escalate\\\"!==r)&&t.display.shortfall(t.activeUpdate,{kind:\\\"unfaithful\\\",field:n.fieldName}),!l&&(t.reportedUnfaithful.add(n.element),t.unfaithfulCount+=1,t.unfaithfulFields.add(n.fieldName),\\\"ignore\\\"!==r)){if(\\\"warn\\\"===r){e.warn(`[live-preview] LP0411: \\\"${n.fieldName}\\\" ${i}`);return}e.log(\\\"LP0411\\\",n.fieldName,i),t.unfaithfulPatches.push(n)}}function l(e,t){return!e.unfaithfulFields.has(t)&&(e.unfaithfulFields.add(t),e.unfaithfulCount+=1,!0)}function o(e){return\\\"INPUT\\\"===e.tagName||\\\"TEXTAREA\\\"===e.tagName?e.value:e.textContent}function s(e){let t=e.trim();return JSON.stringify(t.length>bi?`${t.slice(0,bi)}\\\\u2026`:t)}function a(){return function(){if(typ\",\"eof document>\\\"u\\\")return;let e=document.documentElement.getAttribute(\\\"lang\\\");return null===e||0===e.length?void 0:e}()??function(){if(typeof navigator>\\\"u\\\")return;let e=navigator.language;return\\\"string\\\"==typeof e&&e.length>0?e:void 0}()??\\\"en\\\"}function u(e){null!==e.timer&&(clearTimeout(e.timer),e.timer=null),e.messageNode?.remove(),e.messageNode=null}function d(e){if(++e.nodes>1e4)throw new Error(\\\"invalid or oversized field schema\\\")}function c(e,t,n){if(d(t),n>64||t.active.has(e))throw new Error(\\\"invalid or oversized field schema\\\");t.active.add(e)}function h(e){try{return f(e,{nodes:0,active:new WeakSet},0)}catch{return[]}}function f(e,t,n){if(!Array.isArray(e))return[];c(e,t,n);let i=[];for(let r of e){let e=p(r,t,n);e&&i.push(e)}return t.active.delete(e),i}function p(e,t,n){if(d(t),\\\"object\\\"!=typeof e||null===e)return;let i=e,r=i.name,l=i.type;if(\\\"string\\\"!=typeof r||0===r.length||\\\"string\\\"!=typeof l||0===l.length)return;let o=f(i.fields,t,n+1),s=function(e,t,n){if(\\\"object\\\"==typeof e&&null!==e&&!Array.isArray(e)){c(e,t,n);let i=[];for(let r in e){if(!Object.hasOwn(e,r))continue;d(t);let l=Reflect.get(e,r);\\\"object\\\"!=typeof l||null===l||[\\\"__proto__\\\",\\\"constructor\\\",\\\"prototype\\\"].includes(r)||i.push({...l,slug:r,fields:f(l.fields,t,n+1)})}return t.active.delete(e),i}if(!Array.isArray(e))return[];c(e,t,n);let i=[];for(let r of e){if(d(t),\\\"object\\\"!=typeof r||null===r)continue;let e=r,l=e.slug;if(\\\"string\\\"!=typeof l||0===l.length)continue;let o=f(e.fields,t,n+1);i.push({...e,slug:l,fields:o})}return t.active.delete(e),i}(i.blocks,t,n+1),a={...i,name:r,type:l},u=i.relationTo;if(Array.isArray(u)){let e=[];for(let n of u)d(t),e.push(n);a.relationTo=e}return o.length>0?a.fields=o:delete a.fields,s.length>0?a.blocks=s:delete a.blocks,a}function g(e,t){return void 0===e||t(e)}function m(e,t){return null==e||t(e)}function v(e){if(\\\"object\\\"!=typeof e||null===e)return!1;let t=Object.getPrototypeOf(e);return null===t||null===Object.getPrototypeOf(t)}function y(e,t=[]){let n=\\\"number\\\"==typeof e&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0,i=Math.min(4,n??1),r=new Set(t),l=new Set;for(let e of Ci)(i>=Ti[e].since||r.has(e))&&l.add(e);return{ours:4,...void 0!==n?{theirs:n}:{theirs:void 0},negotiated:i,capabilities:l,observed:r}}function b(e,t){return e.generation===t.generation&&e.revision===t.revision}function w(e){return function(e){if(!1===e.enableA11y)return null;let t=e.root,n=void 0===t?void 0:function(e){return 9===e.nodeType}(t)?t:t.ownerDocument;return new Ai(e.a11yLocale,n)}(e)}function S(e){if(typ\",\"eof window>\\\"u\\\")return;let t=[];window.parent!==window&&t.push(window.parent),window.opener instanceof Window&&t.push(window.opener),Ri.sendReady(t,e)}function A(e,t,n,i){for(let r of e){if($i.has(r.type)){let e=r.fields;e&&A(e,i&&\\\"tabs\\\"===r.type?\\\"\\\"===t?r.name:`${t}.${r.name}`:t,n,i);continue}let e=\\\"\\\"===t?r.name:`${t}.${r.name}`;if(n.set(e,r),\\\"group\\\"===r.type)r.fields&&A(r.fields,e,n,i);else if(\\\"array\\\"===r.type&&r.fields)A(r.fields,`${e}.*`,n,i);else if(\\\"blocks\\\"===r.type&&r.blocks)for(let t of r.blocks)A(t.fields,`${e}.*.${t.slug}`,n,i)}}function k(e,t){if(e.has(t))return e.get(t);let n=t.replace(/\\\\.\\\\d+(?=\\\\.|$)/g,\\\".*\\\");return e.has(n)?e.get(n):void 0}function T(e){if(\\\"object\\\"!=typeof e||null===e)return;let t=e.id;return\\\"string\\\"==typeof t||\\\"number\\\"==typeof t?t:void 0}function C(e){if(\\\"object\\\"!=typeof e||null===e)return;let t=e.blockType;return\\\"string\\\"==typeof t?t:void 0}function R(e,t){return t.every(e=>void 0!==T(e))?function(e,t){let n=[],i=new Map;for(let t=0;t<e.length;t+=1){let n=T(e[t]);void 0!==n&&i.set(n,t)}let r=new Set;for(let l=0;l<t.length;l+=1){let o=t[l],s=T(o);if(void 0===s){n.push({kind:\\\"insert\\\",index:l,value:o});continue}let a=i.get(s);if(void 0===a){n.push({kind:\\\"insert\\\",index:l,value:o});continue}r.add(a);let u=e[a];C(u)===C(o)?(a!==l&&n.push({kind:\\\"move\\\",from:a,to:l,value:o}),$(u,o)||n.push({kind:\\\"update\\\",index:l,value:o})):n.push({kind:\\\"replace\\\",index:l,oldValue:u,value:o})}for(let t=0;t<e.length;t+=1)r.has(t)||n.push({kind:\\\"remove\\\",index:t,value:e[t]});return n}(e,t):function(e,t){let n=[],i=Math.min(e.length,t.length);for(let r=0;r<i;r+=1)$(e[r],t[r])||n.push({kind:\\\"update\\\",index:r,value:t[r]});if(t.length>e.length)for(let i=e.length;i<t.length;i+=1)n.push({kind:\\\"insert\\\",index:i,value:t[i]});if(e.length>t.length)for(let i=t.length;i<e.length;i+=1)n.push({kind:\\\"remove\\\",index:i,value:e[i]});return n}(e,t)}function $(e,t){if(Object.is(e,t))return!0;if(\\\"object\\\"!=typeof e||\\\"object\\\"!=typeof t||null===e||null===t)return!1;let n=e,i=t,r=Object.keys(n),l=Object.keys(i);if(r.length!==l.length)return!1;for(let e of r)if(!Object.is(n[e],i[e]))return!1;return!0}function F(e){if(\\\"string\\\"!=typeof e)return!1;let t=e.trim().replace(Ei,\\\"\\\");if(0===t.length)return!1;if(t.startsWith(\\\"#\\\")||t.startsWith(\\\"?\\\")||Oi.test(t)||t.startsWith(\\\"/\\\"))return!0;try{let e=new URL(t);return Ni.has(e.protocol)}catch{return Mi.test(t)&&!function(e){let t=xi.exec(e.replace(Li,\\\"\\\"))?.[1];return void 0!==t&&!Ni.has(`${t.toLowerCase()}:`)}(t)}}function N(e){let t=e.trim().replace(Ei,\\\"\\\");return/^https?:\\\\/\\\\//i.test(t)||Oi.test(t)}function M(e){return!e.startsWith(\\\"on\\\")&&!Pi.has(e)}function O(e){return Ii.add(e),e}function E(e){switch(typeof e){case\\\"string\\\":return e.length>65536?void 0:`s:${e}`;case\\\"number\\\":return`n:${Object.is(e,-0)?\\\"-0\\\":String(e)}`;case\\\"boolean\\\":return\\\"b:\\\"+(e?\\\"1\\\":\\\"0\\\");case\\\"bigint\\\":return`i:${String(e)}`;case\\\"undefined\\\":return\\\"u\\\";case\\\"object\\\":{if(null===e)return\\\"z\\\";let t;try{t=JSON.stringify(e)}catch{return}return t.length>65536?void 0:`o:${t}`}case\\\"symbol\\\":case\\\"function\\\":return}}function L(){return!0}function x(e){return e.closest(`[${Wi}]`)}function P(e){let t=e.getAttribute(Bi);return null!==t&&t.length>0?\\\"patch\\\"===t||\\\"fragment\\\"===t||\\\"route\\\"===t?t:void 0:null!==x(e)?\\\"fragment\\\":null!==e.closest(\\\"head\\\")?\\\"route\\\":\\\"patch\\\"}function U(e){return`global:${e}`}function I(e,t){return void 0===t||\\\"\\\"===t?`collection:${e}`:`collection:${e}:${t}`}function j(e){return\\\"string\\\"==typeof e&&e.length>0}function W(e,t){return null!==t&&void 0!==e&&t.includes(e)}function D(e){let t=e.id;return\\\"string\\\"==typeof t&&t.length>0?t:\\\"number\\\"==typeof t&&Number.isFinite(t)?String(t):void 0}function B(e){return\\\"object\\\"==typeof e&&null!==e}function _(e){return Array.isArray(e)?\\\"array\\\":B(e)?\\\"object\\\":\\\"scalar\\\"}function z(e,t){return B(e)?e[t]:void 0}function V(e,t,n,i){let r=[],l=0,o=(e,t,n,s)=>{if(l+=1,i.covers(e))return;let a=E(n);if(void 0!==a&&a===E(t))return;if(!((void 0===t||_(t)===_(n))&&B(n)&&i.reachesBelow(e)&&s<_i)){r.push({path:e,value:n});return}let u=function(e,t){let n=new Set(Object.keys(t));if(B(e))for(let t of Object.keys(e))n.add(t);return[...n]}(t,n);0===u.length&&r.push({path:e,value:n});for(let i of u){if(l>=zi){r.push({path:e,value:n});return}o(`${e}.${i}`,z(t,i),z(n,i),s+1)}};return o(e,t,n,0),r}function q(e,t,n={}){let i=e=>!1===t||W(e,t),r=[];for(let[t,n]of e.entries())n.some(e=>i(e.owner))&&r.push(t);let l=e.rendered.filter(e=>void 0!==n[e.strategy]);return function(e,t){let n=new Set(e),i=[...t],r=(e,t)=>{let n=`${t}.`;for(let t of e)if(t.startsWith(n))return!0;return!1};return{covers:e=>n.has(e)||i.some(t=>t===e||e.startsWith(`${t}.`)),reachesBelow:e=>r(n,e)||r(i,e)}}(r,[...e.covers,...l].filter(e=>i(e.owner)).flatMap(e=>e.paths))}function H(e,t){if(void 0===t||0===t.length)return e;let n=`_${t}`;return e.endsWith(n)?e.slice(0,-n.length):e}function G(e,t,n,i=q(e,n)){let r,l=i.covers,o=i.reachesBelow;return i=>{let s=H(i,t);return l(i)||s!==i&&l(s)||(r??(r=function(e,t){let n=new Set;for(let[i,r]of e.entries())for(let e of r)!1!==t&&!W(e.owner,t)||void 0!==e.locale&&n.add(`${i}_${e.locale}`);return n}(e,n)),r.has(i))?\\\"whole\\\":o(i)||s!==i&&o(s)?\\\"below\\\":\\\"none\\\"}}function K(e,t,n,i,r){return X(n)?!X(t)||function(e,t,n){let i=void 0===n?void 0:k(n,e);return void 0!==i&&!qi.has(i.type)||!0===t.get(e)?.some(J)||function(e,t){let n=`${t}.`;for(let[t,i]of e.entries())if(t.startsWith(n))return!0;return!1}(t,e)}(e,i,r)?\\\"keep\\\":null==t?\\\"ask\\\":\\\"own\\\":\\\"ask\\\"}function J(e){return!qi.has(e.fieldType)}function X(e){return null===e||\\\"object\\\"!=typeof e&&\\\"function\\\"!=typeof e}function Q(e){return!0===e?.includes(\\\".\\\")}function Z(e,t){let n=t.globalSlug??t.collectionSlug;if(\\\"string\\\"!=typeof n||e.entitySlug!==n)return!0;let i=D(e),r=D(t.data??{});return void 0!==i&&void 0!==r&&i!==r}function Y(e){return null!==e&&e.forceRender&&!e.completed}function ee(e){try{return!0===e.matchMedia?.(\\\"(prefers-reduced-motion: reduce)\\\").matches}catch{return!1}}function te(e,t){let n=t.element.ownerDocument.defaultView;return null===n?\\\"no-element\\\":e.reveal(`${t.owner??\\\"\\\"} ${t.fieldName}`,t.element,n)}function ne(e){let t=e.getAttribute(Di);return{kind:\\\"fragment\\\",id:e.getAttribute(Wi)??\\\"\\\",key:null===t||0===t.length?void 0:t,code:\\\"LP0801\\\"}}function ie(e){if(null==e)return[];let t=new Set,n=[];for(let i of e.split(/[\\\\s,]+/)){let e=i.trim();0===e.length||t.has(e)||(t.add(e),n.push(e))}return n}function re(...e){let t=new Map;for(let n of e)for(let[e,i]of Object.entries(n)){let n=t.get(e);void 0===n&&(n=new Set,t.set(e,n));for(let e of i)n.add(e)}let n={};for(let[e,i]of t)n[e]=[...i];return n}function le(e,t){let n={};for(let i of t)i!==e&&(n[i]=[e]);return n}function oe(e){if(e.tagName.toLowerCase().includes(\\\"-\\\")&&!e.hasAttribute(sr)||ae(e)||e.hasAttribute(or))return!0;let t=e.getAttribute(\\\"contenteditable\\\");return null!==t&&\\\"false\\\"!==t}function se(e){return\\\"patch\\\"===e.getAttribute(rr)}function ae(e){return function(e){return\\\"astro-island\\\"===e.tagName.toLowerCase()||e.hasAttribute(rr)}(e)&&!se(e)}function ue(e){return\\\"astro-island\\\"===e.tagName.toLowerCase()&&e.hasAttribute(\\\"ssr\\\")}function de(e){return\\\"astro-island\\\"===e.tagName.toLowerCase()}function ce(e){let t=\\\"\\\";for(let n of e.querySelectorAll(\\\"astro-slot, template[data-astro-template]\\\"))n.parentElement?.closest(\\\"astro-island\\\")===e&&(t+=`${n.getAttribute(\\\"name\\\")??n.getAttribute(\\\"data-astro-template\\\")??\\\"\\\"}\\\\0${n.innerHTML}\\\\0`);return t}function he(e,t){if(!de(e)||!de(t))return!0;let n=ce(t);if(!ar.every(n=>e.getAttribute(n)===t.getAttribute(n))||(ur.get(e)??ce(e))!==n||e.getAttribute(\\\"props\\\")!==t.getAttribute(\\\"props\\\")&&!function(e){let t=e.ownerDocument.defaultView?.customElements.get(\\\"astro-island\\\");return void 0!==t&&e instanceof t&&Array.isArray(t.observedAttributes)&&t.observedAttributes.includes(\\\"props\\\")}(e))return ur.set(t,n),!1;ur.set(e,n);let i=t.getAttribute(\\\"props\\\");return i!==e.getAttribute(\\\"props\\\")&&(e.setAttribute(\\\"ssr\\\",\\\"\\\"),null===i?e.removeAttribute(\\\"props\\\"):e.setAttribute(\\\"props\\\",i)),!0}function fe(e){return Array.from(e.querySelectorAll(\\\"astro-island\\\"))}function pe(e){let t=e.ownerDocument.defaultView;if(void 0===t?.customElements.get(\\\"astro-island\\\"))return\\\"element\\\";let n=e.getAttribute(\\\"client\\\"),i=Reflect.get(t,\\\"Astro\\\");return null===n||\\\"object\\\"!=typeof i||null===i||void 0===Reflect.get(i,n)?\\\"directive\\\":void 0}function ge(e){let t=e.closest(Er)?.getAttribute(Tr);return null==t||0===t.length?void 0:t}function me(e){return Pr.has(e)||xr.test(e)}function ve(e,t){return e.fieldName===t.fieldName&&e.locale===t.locale&&e.owner===t.owner&&e.strategyKind===t.strategyKind&&e.fragmentBoundary===t.fragmentBoundary}function ye(e){let t=e.getAttribute(hr);if(null!==t&&me(t))return t;if(e.hasAttribute(wr))return\\\"richText\\\";if(e.hasAttribute(Sr))return\\\"html\\\";if(e.hasAttribute(kr))return\\\"structural-array\\\";if(e.hasAttribute(Ar))return\\\"array\\\";if(\\\"IMG\\\"===e.tagName)return\\\"image\\\";if(\\\"A\\\"===e.tagName)return\\\"url\\\";if(\\\"TIME\\\"===e.tagName)return\\\"date\\\";if(\\\"INPUT\\\"===e.tagName){let t=e.type;if(\\\"checkbox\\\"===t)return\\\"checkbox\\\";if(\\\"number\\\"===t)return\\\"number\\\";if(\\\"date\\\"===t||\\\"datetime-local\\\"===t)return\\\"date\\\"}return\\\"text\\\"}function be(){return!0}function we(){throw new Error(\\\"invalid or oversized legacy population\\\")}function Se(e){for(let t=0;t<e.length;t+=1){let n=e.charCodeAt(t);if(n<=31||127===n)return!0}return!1}function Ae(e,t){if(\\\"string\\\"!=typeof e||0===e.length||e.length>t||\\\".\\\"===e||\\\"..\\\"===e||e.includes(\\\"/\\\")||e.includes(\\\"\\\\\\\\\\\")||Se(e))return!1;try{return encodeURIComponent(e),!0}catch{return!1}}function ke(e){return Ae(e,128)&&!/[?#%]/u.test(e)&&!qr.has(e)}function Te(e){return Number.isFinite(e)?String(e):Ae(e,512)?e:we()}function Ce(e,t){return Object.hasOwn(e,t)?Reflect.get(e,t):void 0}function Re(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,configurable:!0,enumerable:!0})}function $e(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t-=1;return e.slice(0,t)}function Fe(e){let t=new WeakSet,n=0,i=0;return function e(r,l){if(++n>jr||l>Ir)return we();if(\\\"string\\\"==typeof r)return i+=r.length,i>_r&&we(),r;if(null==r||\\\"boolean\\\"==typeof r)return r;if(\\\"number\\\"==typeof r)return Number.isFinite(r)?r:we();if(!Array.isArray(r)&&!v(r))return we();if(Array.isArray(r)){r.length>jr&&we();for(let e=0;e<r.length;e+=1)Object.hasOwn(r,e)||we()}if(t.has(r))return we();t.add(r);let o=Array.isArray(r)?[]:{};for(let t of Object.keys(r))Re(o,t,e(Reflect.get(r,t),l+1));return t.delete(r),o}(e,0)}function Ne(e,t,n,i,r,l){function o(e,t,n,i){if(null==i||\\\"\\\"===i)return;let l=v(i)?Ce(i,\\\"id\\\"):i,o=Te(l);if(0===r){Re(e,t,l);return}let s=JSON.stringify([n,o]);c.add(s),c.size>Wr&&we();let a=d.get(n)??[];a.push({owner:e,key:t,id:o}),d.set(n,a)}function s(e,t,n){void 0!==n.hasMany&&\\\"boolean\\\"!=typeof n.hasMany&&we();let i=n.relationTo,r=Ce(e,t);if(Array.isArray(i)){0===i.length&&we();let e,t=v(r)?Ce(r,\\\"relationTo\\\"):void 0;for(let n of i)p(0),ke(n)||we(),n===t&&(e=n);if(null==r||\\\"\\\"===r)return;(!v(r)||void 0===e)&&we(),o(r,\\\"value\\\",e,Ce(r,\\\"value\\\"))}else ke(i)||we(),o(e,t,i,r)}function a(e,t){if(p(t),Array.isArray(e)||v(e)){if(v(e)&&Object.hasOwn(e,\\\"relationTo\\\")&&Object.hasOwn(e,\\\"value\\\")){let t=Ce(e,\\\"relationTo\\\");ke(t)||we(),o(e,\\\"value\\\",t,Ce(e,\\\"value\\\"));return}for(let n of Object.keys(e))a(Reflect.get(e,n),t+1)}}if(!Number.isSafeInteger(r)||r<0||r>Ir)return we();void 0!==l&&(\\\"string\\\"!=typeof l||l.length>128||Se(l))&&we();let u=Fe(e);if(!v(u))return we();let d=new Map,c=new Set,h=0,f=new WeakSet,p=e=>{(++h>jr||e>Ir)&&we()};(function e(t,n,i){p(i),f.has(t)&&we(),f.add(t);for(let r of t){p(i),(!v(r)||!Ae(r.name,512)||qr.has(r.name))&&we();let t=Ce(n,r.name);if(\\\"relationship\\\"===r.type||\\\"upload\\\"===r.type)if(r.hasMany)if(null!=t&&!Array.isArray(t)&&we(),Array.isArray(t))for(let e=0;e<t.length;e+=1)s(t,e,r);else s(n,r.name,r);else s(n,r.name,r);else if(\\\"group\\\"===r.type||\\\"tabs\\\"===r.type)null!=t&&!v(t)&&we(),v(t)&&r.fields&&e(r.fields,t,i+1);else if(\\\"row\\\"===r.type||\\\"collapsible\\\"===r.type)r.fields&&e(r.fields,n,i+1);else if(\\\"array\\\"===r.type||\\\"blocks\\\"===r.type){if(0===t?Re(n,r.name,[]):null!=t&&!Array.isArray(t)&&we(),Array.isArray(t))for(let n of t)if(v(n)||we(),\\\"array\\\"===r.type&&r.fields)e(r.fields,n,i+1);else if(\\\"blocks\\\"===r.type){let t=Ce(n,\\\"blockType\\\"),l=r.blocks?.find(e=>(p(i),e.slug===t));void 0===l&&we(),e(l.fields,n,i+1)}}else\\\"richText\\\"===r.type&&a(t,i+1)}f.delete(t)})(t,u,0),d.size>25&&we();let g=[];if(0===d.size)return{doc:u,requests:g};let m=new URL(n);(![\\\"http:\\\",\\\"https:\\\"].includes(m.protocol)||m.username||m.password||m.search||m.hash)&&we(),(!i.startsWith(\\\"/\\\")||i.includes(\\\"\\\\\\\\\\\")||/[%?#]/u.test(i)||Se(i))&&we(),i.split(\\\"/\\\").some(e=>\\\".\\\"===e||\\\"..\\\"===e)&&we();let y=`${$e(n)}${$e(i)}/`;for(let[e,t]of d){let n=[...new Set(t.map(e=>e.id))],i=0;for(;i<n.length;){let o=n[i];void 0===o&&we();let s=o.includes(\\\",\\\"),a=[],u=\\\"\\\";for(;i<n.length&&a.length<Vr;){let t=n[i];if(void 0===t||a.length>0&&(s||t.includes(\\\",\\\")))break;let o=[...a,t],d=new URLSearchParams({depth:String(r),limit:String(o.length)});void 0!==l&&d.set(\\\"locale\\\",l),d.set(s?\\\"where[id][equals]\\\":\\\"where[id][in]\\\",s?t:o.join(\\\",\\\"));let c=`${y}${encodeURIComponent(e)}?${d}`;if(c.length>Br){0===a.length&&we();break}new URL(c).origin!==m.origin&&we(),a.push(t),i+=1,u=c}(0===a.length||g.length>=Dr)&&we();let d=new Set(a);g.push({url:u,ids:d,slots:t.filter(e=>d.has(e.id))})}}return{doc:u,requests:g}}async function Me(e,t,n){let i,r,l=!1,o=!1,s=Symbol(),a=new Promise(e=>{r=()=>{e(s)}}),u=()=>{(!n()||t.aborted)&&we()},d=()=>{if(void 0!==i&&!l){l=!0;try{Promise.resolve(i.cancel()).catch(()=>{})}catch{}}},c=()=>{r?.(),d()};t.addEventListener(\\\"abort\\\",c,{once:!0});try{u();let t=e.body??null;if(u(),null===t){let t=e.json.bind(e);u();let n=await Promise.race([Promise.resolve().then(()=>(u(),t())),a]);return u(),n===s&&we(),n}let n=t.getReader.bind(t);u();let r=n();i=r,u();let l=[],d=0,c=0;for(;;){let e=Promise.resolve().then(()=>{u();let e=r.read.bind(r);return u(),e()}),t=await Promise.race([e,a]);if(u(),t===s&&we(),t.done)break;d+=t.value.byteLength,(++c>zr||d>_r)&&we(),l.push(t.value)}o=!0;let h=new Uint8Array(d),f=0;for(let e of l)h.set(e,f),f+=e.byteLength;try{return JSON.parse((new TextDecoder).decode(h))}catch{return we()}}finally{t.removeEventListener(\\\"abort\\\",c),o||d();try{i?.releaseLock()}catch{}}}function Oe(e,t){let n=Fe(t);v(n)||we();let i=Ce(n,\\\"docs\\\");(!Array.isArray(i)||i.length>Vr)&&we();let r=new Map;for(let t of i){v(t)||we();let n=Te(Ce(t,\\\"id\\\"));(!e.ids.has(n)||r.has(n))&&we(),r.set(n,t)}r.size!==e.ids.size&&we();for(let t of e.slots)Re(t.owner,t.key,r.get(t.id))}function Ee(e,t){return e.length>0&&e.length<=t&&\\\".\\\"!==e&&\\\"..\\\"!==e&&!e.includes(\\\"/\\\")&&!e.includes(\\\"\\\\\\\\\\\")&&!function(e){for(let t of e){let e=t.codePointAt(0)??0;if(e<=31||127===e)return!0}return!1}(e)}function Le(e){return Ee(e,128)&&!e.includes(\\\"?\\\")&&!e.includes(\\\"#\\\")}function xe(e){return\\\"number\\\"==typeof e?Number.isFinite(e):\\\"string\\\"==typeof e&&Ee(e,512)}function Pe(e){return e.has(\\\"schema-json\\\")?Kr:e.has(\\\"document-events\\\")||e.has(\\\"relationship-events\\\")?Jr:Xr}function Ue(e){if(\\\"attributes\\\"!==e.type||e.attributeName!==Qr||e.target.nodeType!==Zr)return null;let t=e.target;return\\\"astro-island\\\"!==t.tagName.toLowerCase()||t.hasAttribute(Qr)?null:t}function Ie(e){if(e.nodeType!==Zr)return!1;let t=e;return t.hasAttribute(cr)||t.matches(lr)||t.matches(Lr)||null!==t.querySelector(`[${cr}], ${lr}, ${Lr}`)}function je(){if(typ\",\"eof window>\\\"u\\\")return;let e=window;return e[ol]??(e[ol]={armed:!1,committed:!1,commits:[],onCommit:void 0,waiters:[]})}function We(){let e=je();if(void 0===e||e.armed)return;e.armed=!0;let t=window,n=t.__REACT_DEVTOOLS_GLOBAL_HOOK__??(t.__REACT_DEVTOOLS_GLOBAL_HOOK__=function(){let e=new Map;return{supportsFiber:!0,renderers:e,inject:t=>{let n=e.size+1;return e.set(n,t),n}}}()),i=n.onCommitFiberRoot;n.onCommitFiberRoot=function(t,n,...r){try{i?.call(this,t,n,...r)}catch{}void 0===e.onCommit?e.commits.push(n):e.onCommit(n)}}function De(e){e.committed=!0;let t=e.waiters;e.waiters=[];for(let e of t)e()}function Be(e,t){let n=e.waiters.indexOf(t);n>=0&&e.waiters.splice(n,1)}function _e(e,t,n){if(e.committed)return null;let i=null,r=()=>{null!==i&&clearTimeout(i),i=null,t(\\\"committed\\\")};return e.waiters.push(r),i=setTimeout(()=>{i=null,Be(e,r),t(\\\"timed-out\\\")},n),()=>{null!==i&&clearTimeout(i),i=null,Be(e,r)}}function ze(){if(typ\",\"eof window>\\\"u\\\")return;let e=window;return e[ul]??(e[ul]={armed:!1,committed:!1,waiters:[]})}function Ve(e){return Object.prototype.hasOwnProperty.call(e,al)?e[al]:void 0}function qe(){let e=ze();if(void 0===e||e.armed)return;e.armed=!0;let t=Element.prototype;void 0===Object.getOwnPropertyDescriptor(t,al)&&Object.defineProperty(t,al,{configurable:!0,get:()=>{},set(e){Object.defineProperty(this,al,{value:e,writable:!0,configurable:!0,enumerable:!0});let t=ze();void 0===t||t.committed||null===this.querySelector(sl)||function(e,t){let n=t?.$nuxt;!0!==n?.isHydrating||\\\"function\\\"!=typeof n.hook?De(e):n.hook(dl,()=>{e.committed||De(e)})}(t,e)}})}function He(e){let t=e.hydration;if(void 0===t){e.startNow();return}let n=cl[t](e.root,n=>{e.later(()=>{Ge(e,t,n)})});null!==n?(e.defer(n),e.hydrated(\\\"waiting\\\")):Ge(e,t,\\\"committed\\\")}function Ge(e,t,n){e.hydrated(n),\\\"timed-out\\\"===n&&e.warn(`[live-preview] LP0607: no ${hl[t]} in ${String(5e3)} ms; started without waiting for hydration.`),e.startNow()}function Ke(e){return 9===e.nodeType}function Je(e){return e.body}function Xe(e,t=ml){if(\\\"string\\\"!=typeof e)return!1;let n=e.trim();return!(n.length<t||yl.test(n)||vl.has(n.toLowerCase())||bl.test(n)||wl.test(n))}function Qe(e){return\\\"object\\\"==typeof e&&null!==e&&!Array.isArray(e)}function Ze(e,t,n=ml){let i=new Map,r=(e,t,n)=>{i.set(e,i.has(e)?null:{field:t,media:n})};for(let[i,l]of Object.entries(e)){if(Vi.has(i))continue;let e=H(i,t);if(Xe(l,n))r(l.trim(),e,!1);else if(Qe(l))if(\\\"string\\\"==typeof l.url)r(l.url,e,!0);else if(!(\\\"id\\\"in l)&&!(\\\"_id\\\"in l))for(let[t,i]of Object.entries(l))Vi.has(t)||!Xe(i,n)||r(i.trim(),`${e}.${t}`,!1)}return i}function Ye(e){if(e.namespaceURI!==Al||Sl.has(e.tagName)||e.hasAttribute(cr)||e.hasAttribute(gl)||e.hasAttribute(or)||ae(e))return!0;let t=e.getAttribute(\\\"contenteditable\\\");return null!==t&&\\\"false\\\"!==t}function et(e){let t;for(let n=e.firstChild;null!==n;n=n.nextSibling){if(1===n.nodeType)return;if(3!==n.nodeType)continue;let e=n.data.trim();if(0!==e.length){if(void 0!==t)return;t=e}}return t}function tt(e){return M(e)&&!e.startsWith(\\\"data-payload-\\\")&&\\\"value\\\"!==e}function nt(e,t,n){let i=e.byElement.get(t);void 0===i&&(i={attributes:new Map},e.byElement.set(t,i));let r=e.byField.get(n.field);return void 0===r&&(r=new Set,e.byField.set(n.field,r)),r.add(t),i}function it(e,t){for(let n=e.firstElementChild;null!==n;n=n.nextElementSibling){if(Ye(n))continue;let e=et(n),i=void 0===e?void 0:t.values.get(e);null!=i&&!i.media&&(nt(t,n,i).text=i.field);for(let e of n.getAttributeNames()){if(!tt(e))continue;let i=t.values.get(n.getAttribute(e)??\\\"\\\");null!=i&&(i.media&&(\\\"IMG\\\"!==n.tagName||\\\"src\\\"!==e)||nt(t,n,i).attributes.set(e,i))}it(n,t)}}function rt(e,t,n){let i=e.tagName;if(void 0!==t){let r={[cr]:t};if(\\\"A\\\"===i){let e=n.get(\\\"href\\\");void 0===e?r[hr]=\\\"text\\\":e!==t&&(r[pr]=e)}return{element:e,fieldName:t,matched:et(e)??\\\"\\\",stamps:r}}if(\\\"IMG\\\"===i){let t=n.get(\\\"src\\\");if(void 0!==t){let i=n.get(\\\"alt\\\");return{element:e,fieldName:t,matched:e.getAttribute(\\\"src\\\")??\\\"\\\",attribute:\\\"src\\\",stamps:{[cr]:t,...void 0!==i&&i!==t?{[mr]:i}:{}}}}}let r=n.entries().next();if(r.done)return;let[l,o]=r.value;return{element:e,fieldName:o,matched:e.getAttribute(l)??\\\"\\\",attribute:l,stamps:{[cr]:o,[fr]:l}}}function lt(e,t){let n={values:t,byElement:new Map,byField:new Map};t.size>0&&!Ye(e)&&it(e,n);let i=e=>1===n.byField.get(e)?.size,r=[];for(let[e,t]of n.byElement){let n=void 0!==t.text&&i(t.text)?t.text:void 0,l=new Map;for(let[e,n]of t.attributes)i(n.field)&&l.set(e,n.field);let o=rt(e,n,l);void 0!==o&&r.push(o)}return r}function ot(e){return 9===e.nodeType?e.body:e}function st(e,t){for(let n=t.length-1;n>=0;n-=1){let i=t[n];if(void 0!==i){i.observed&&e.observers.unobserveElement(i.element);for(let e=i.attributes.length-1;e>=0;e-=1){let t=i.attributes[e];if(void 0===t)continue;let{name:n,before:r,written:l}=t;r===l||i.element.getAttribute(n)!==l||(null===r?i.element.removeAttribute(n):i.element.setAttribute(n,r))}i.cacheTouched&&(i.element.hasAttribute(cr)?e.cache.add(i.element):e.cache.remove(i.element))}}}function at(e,t,n,i,r){let l=[],o=[],s=()=>(st(e,o),[]);for(let a of t){if(!r())return s();let{element:t}=a;if(t.hasAttribute(cr))continue;if(!r())return s();if(!1!==n&&!W(ge(t),n))continue;if(!r())return s();let u={element:t,attributes:[],cacheTouched:!1,observed:!1};o.push(u);for(let[e,n]of[...Object.entries(a.stamps),[Fr,a.matched]]){let i=t.getAttribute(e);if(!r()||(u.attributes.push({name:e,before:i,written:n}),t.setAttribute(e,n),!r()))return s()}if(u.cacheTouched=!0,void 0!==e.cache.add(t)){if(!r()||(e.observers.observeElement(t),u.observed=!0,!r())||(e.log(\\\"autoBind\\\",a.fieldName,\\\"\\\\u2192\\\",`<${t.tagName.toLowerCase()}>`,a.attribute??\\\"text\\\",JSON.stringify(a.matched),i),!r()))return s();l.push(a)}else st(e,[u]),o.pop()}return l}function ut(e,t,n,i=!1){if(i&&void 0!==n){let i=dt(e,`${t}_${n}`);if(void 0!==i)return i}let r=dt(e,t);if(void 0!==r)return r;if(t.includes(\\\".\\\")){let n=e,i=!0;for(let e of t.split(\\\".\\\")){if(kl.has(e)||null===n||\\\"object\\\"!=typeof n){i=!1;break}if(n=dt(n,e),void 0===n){i=!1;break}}if(i)return n}return void 0===n?void 0:dt(e,`${t}_${n}`)}function dt(e,t){if(!kl.has(t)&&Object.prototype.hasOwnProperty.call(e,t))return e[t]}function ct(e,t,n,i){return ut(e,n,t.locale??i,void 0!==t.locale)}function ht(e,t,n,i){let r=E(t);if(void 0===r)return;let l=[e.hrefField,e.srcField,e.altField],o=r;for(let t of l){if(void 0===t||0===t.length)continue;let r=E(ct(n,e,t,i));if(void 0===r)return;o+=`|${t}=${r}`}return o}function ft(e,t,n,i){if(!e.scopeBindingsByOwner)return!1;let{message:r}=n,l=function(e){if(j(e.globalSlug))return[U(e.globalSlug)];if(!j(e.collectionSlug))return null;let t=I(e.collectionSlug);return j(e.documentId)?[t,I(e.collectionSlug,e.documentId)]:[t]}({globalSlug:\\\"string\\\"==typeof r.globalSlug?r.globalSlug:void 0,collectionSlug:\\\"string\\\"==typeof r.collectionSlug?r.collectionSlug:void 0,documentId:D(i)});return null===l&&!t.warnedUnattributableMessage&&(t.warnedUnattributableMessage=!0,e.warn(\\\"[live-preview] LP0202: scopeBindingsByOwner: update names no document; nothing applied\\\")),l}function pt(e,t,n,i,r){!function(e,t,n){let i=0;for(let r of e)if(!n()||(r.dispatchEvent(new CustomEvent(ir,{detail:t,bubbles:!1})),i+=1,!n()))break}(n,{fields:t.fields,revision:e.revision.revision,receivedAt:e.receivedAt,locale:e.locale,displayed:r},i)}function gt(e,t,n,i,r){let{warned:l,warn:o}=e;if(l.has(n)||t(n))return;l.add(n);let s=`data-payload-field=\\\"${H(n,i)}\\\"`;o(\\\"\\\"!==r?`[live-preview] LP0203: field \\\"${n}\\\" has a value and no <\\\\u2026 ${s}> on this page; editing it changes nothing here. Expected where the page shows part of the document: inspect().fidelity.fields lists these, onUnfaithfulPatch decides whether a server render is asked for.`:`[live-preview] LP0201: no <\\\\u2026 ${s}> for the empty field \\\"${n}\\\"; render the anchor unconditionally so edits to an empty field have somewhere to land.`)}function mt(e){let t=typeof e;return\\\"string\\\"===t||\\\"number\\\"===t||\\\"boolean\\\"===t||\\\"bigint\\\"===t}function vt(e){return\\\"object\\\"==typeof e&&null!==e&&!Array.isArray(e)}function yt(e){let t=function(){let e=function(){let e=globalThis,t=e[Rl];if(void 0!==t)return t;let n={};return e[Rl]=n,n}();if(void 0!==e.override)return e.override;if(void 0!==e.auto)return e.auto;let t=function(){let e=globalThis.trustedTypes;return\\\"object\\\"!=typeof e||null===e?void 0:\\\"function\\\"==typeof e.createPolicy?e:void 0}();try{e.auto=void 0===t?null:t.createPolicy(Cl,{createHTML:e=>e})}catch{e.auto=null}return e.auto}();return null===t?e:t.createHTML(e)}function bt(e,t){for(let n of t.keyAttributes){let t=e.getAttribute(n);if(null!==t&&t.length>0)return`${n}=${t}`}}function wt(e,t,n){if(!kt(e,t))return t;let i=n.boundary??oe,r=i(e),l=i(t);if(r||l)return r&&l&&(n.retainBoundary?.(e,t)??1)?e:t;let o=Tt(e);return function(e,t){for(let n of Array.from(e.attributes))t.hasAttribute(n.name)||$l.has(n.name.toLowerCase())||e.removeAttribute(n.name);for(let n of Array.from(t.attributes))e.getAttribute(n.name)!==n.value&&e.setAttribute(n.name,n.value)}(e,t),!0!==n.retainChildrenOf?.(e,t)&&function(e,t,n){let i=function(e,t){let n,i=new Map;for(let r of Array.from(e.children)){let e=bt(r,t);if(void 0!==e){if(i.has(e)){n??(n=e.slice(e.indexOf(\\\"=\\\")+1));continue}i.set(e,r)}}return void 0!==n&&t.onDuplicateKey?.(e,n),i}(e,n),r=new Set(i.values()),l=Array.from(e.childNodes).filter(e=>!r.has(e)),o=new Set,s=new Set,a=Array.from(t.childNodes),u=e.firstChild,d=0;for(let t=0;t<a.length;t+=1){let r=a[t],c=null,h=r instanceof Element?bt(r,n):void 0;if(void 0!==h&&s.has(h)&&(h=void 0),void 0!==h){s.add(h);let e=i.get(h);if(void 0!==e&&!o.has(e)&&(c=St(e,r,n)===e?e:null,null===c)){e.replaceWith(r),o.add(r),u=r.nextSibling;continue}}else{for(;d<l.length;){let i=l[d];if(d+=1,!o.has(i)){if(kt(i,r)){c=St(i,r,n)===i?i:null,null===c&&(e.replaceChild(r,i),o.add(r),u=r.nextSibling);break}if(i instanceof Element){let n=a[t+1];if(!(r instanceof Element)||void 0!==n&&kt(i,n)){d-=1;break}e.replaceChild(r,i),o.add(r),u=r.nextSibling;break}if(!(r instanceof Element)){e.replaceChild(r,i),o.add(r),u=r.nextSibling;break}}}if(null===c&&o.has(r))continue}let f=c??r;for(o.add(f);null!==u&&u!==f&&!o.has(u)&&At(u);)u=u.nextSibling;f!==u&&e.insertBefore(f,u),u=f.nextSibling}for(let t of Array.from(e.childNodes))o.has(t)||t.remove()}(e,t,n),Ct(o),e}function St(e,t,n){return e instanceof Element&&t instanceof Element?wt(e,t,n):(e.nodeValue!==t.nodeValue&&(e.nodeValue=t.nodeValue),e)}function At(e){return e.nodeType===Node.TEXT_NODE&&0===(e.nodeValue??\\\"\\\").trim().length}function kt(e,t){return e.nodeType===t.nodeType&&(!(e instanceof Element&&t instanceof Element)||e.tagName===t.tagName&&e.namespaceURI===t.namespaceURI)}function Tt(e){let t=e.ownerDocument.activeElement;return t instanceof HTMLElement&&e.contains(t)?{element:t,selection:t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement?[t.selectionStart,t.selectionEnd]:null}:null}function Ct(e){if(null===e)return;let{element:t,selection:n}=e;if(t.ownerDocument.activeElement!==t&&t.isConnected)try{t.focus({preventScroll:!0});let[e,i]=n??[null,null];null!==e&&null!==i&&t.setSelectionRange(e,i)}catch{}}function Rt(e){Nl.has(e)||(Nl.add(e),function(e){try{console.warn(e)}catch{}}(`[live-preview] LP0409: the strict sanitizer removed \\\\`${e}\\\\` from written markup; the 1.x default (\\\\`sanitizerPolicy: 'compat'\\\\`) kept it. ${function(e){return e.startsWith(Ml)?\\\"A binding inside CMS content is refused by design \\\\u2014 an editor could otherwise aim a write at any element on the page (docs/security.md)\\\":\\\"id\\\"===e||\\\"name\\\"===e?\\\"CMS content that can name an element can shadow a global of that name \\\\u2014 DOM clobbering, refused by design (docs/security.md)\\\":\\\"Put it on an element the template owns, or set `sanitizerPolicy: 'compat'` to keep every `data-*` as 1.x did\\\"}(e)}.`))}function $t(e,t){return Ft(e,void 0,t)}function Ft(e,t,n){let i=n?.document??Nt();if(!i)throw new Error(\\\"sanitizeHtml needs a DOM\\\");if(\\\"\\\"===e)return\\\"\\\";let r=function(e,t){let n=e?.policy??t??Vl;if(!e){let e=new Map;for(let[t,n]of Object.entries(jl))e.set(t,n);return{allowedTags:Ol,attrByTag:e,allowFormControls:!1,templateMode:!1,mode:n,allowedData:new Set}}let i=new Set(Ol);if(e.additionalAllowedTags?.forEach(e=>i.add(e)),!0===e.allowFormControls)for(let e of El)i.add(e);let r=new Map;for(let[e,t]of Object.entries(jl))r.set(e,t);for(let[t,n]of Object.entries(e.additionalAllowedAttributes??{})){let e=new Set(r.get(t));for(let t of n)e.add(t);r.set(t,e)}return{allowedTags:i,attrByTag:r,allowFormControls:!0===e.allowFormControls,templateMode:!0===e.templateMode,mode:n,allowedData:new Set(e.allowedDataAttributes?.map(e=>e.toLowerCase()))}}(n,t),l=e;for(let e=0;e<Dl;e+=1){let e=i.createElement(\\\"template\\\");e.innerHTML=yt(l),Mt(e.content,r);let t=e.innerHTML;if(t===l)return t;l=t}return function(e,t){if(!function(){try{let e=glo\",\"balThis.process?.env;return void 0!==e&&\\\"production\\\"!==e.NODE_ENV}catch{return!1}}())return;let n=globalThis,i=n[Fl]??(n[Fl]=new Set);if(!i.has(e)){i.add(e);try{console.warn(`[payload-live-preview] ${t}`)}catch{}}}(\\\"sanitizer-unsettled\\\",`sanitizeHtml: the output did not settle after ${String(Dl)} passes, so it returned an empty string (ADR 0016).`),\\\"\\\"}function Nt(){if(!(typ\",\"eof document>\\\"u\\\"))return document}function Mt(e,t){for(let n of Array.from(e.childNodes))n.nodeType===Bl?Ot(n,t):n.nodeType===_l&&n.remove()}function Ot(e,t){let n=e.tagName.toLowerCase();!Ll.has(n)||t.allowFormControls&&El.has(n)?t.allowedTags.has(n)?(function(e,t,n){let i=n.attrByTag.get(t);for(let t of Array.from(e.attributes)){let r=t.name.toLowerCase();if(r.startsWith(\\\"on\\\")||\\\"style\\\"===r)e.removeAttribute(t.name);else if(\\\"is\\\"!==r){if(\\\"strict\\\"===n.mode){if(n.templateMode&&zl.has(r))continue;if(\\\"id\\\"===r||\\\"name\\\"===r||r.startsWith(Il)){e.removeAttribute(t.name),(\\\"name\\\"!==r||!0===i?.has(r))&&Rt(r);continue}if(r.startsWith(Ul)){n.allowedData.has(r)||(e.removeAttribute(t.name),Rt(r));continue}if(xl.has(r)||r.startsWith(Pl))continue}else if(xl.has(r)||r.startsWith(Pl)||r.startsWith(Ul))continue;i?.has(r)?(Wl.has(r)&&!F(t.value)||\\\"srcset\\\"===r&&!Et(t.value))&&e.removeAttribute(t.name):e.removeAttribute(t.name)}else e.setAttribute(\\\"is\\\",\\\"\\\")}}(e,n,t),\\\"a\\\"===n&&function(e){let t=e.getAttribute(\\\"href\\\");null===t||!N(t)||(e.setAttribute(\\\"rel\\\",\\\"noopener noreferrer\\\"),e.hasAttribute(\\\"target\\\")||e.setAttribute(\\\"target\\\",\\\"_blank\\\"))}(e),Mt(e,t)):(Mt(e,t),e.replaceWith(...e.childNodes)):e.remove()}function Et(e){for(let t of e.split(\\\",\\\")){let e=t.trim();if(0===e.length)continue;let[n=e]=e.split(/\\\\s/,1);if(!F(n)||!F(e))return!1}return!0}function Lt(e){return e.replace(Hl,e=>ql[e])}function xt(e){return e.replace(Kl,e=>Gl[e])}function Pt(e){let t=new Set;for(let n of e)if(\\\"object\\\"==typeof n&&null!==n)for(let e of Object.keys(n))t.add(e);return t}function Ut(e,t,n,i,r){let l=\\\"object\\\"==typeof t&&null!==t?t:null;return e.replace(Jl,(e,o)=>null!==l&&function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(l,o)?Lt(i(Reflect.get(l,o))):null===l&&\\\"value\\\"===o?Lt(i(t)):\\\"index\\\"===o?String(n):null!==l&&!0===r?.has(o)?\\\"\\\":e)}function It(e){let t=e.children,n=t[0];if(void 0===n)return[];let i=[];for(let{name:e,value:r}of Array.from(n.attributes)){if(!M(e)||e.startsWith(Xl))continue;let n=!0;for(let i=1;i<t.length&&n;i+=1)n=t[i]?.getAttribute(e)===r;n&&i.push([e,r])}return i}function jt(e,t){for(let[n,i]of t)e.hasAttribute(n)||e.setAttribute(n,i)}function Wt(e){if(null==e)return\\\"\\\";if(\\\"string\\\"==typeof e)return e;if(\\\"number\\\"==typeof e||\\\"boolean\\\"==typeof e||\\\"bigint\\\"==typeof e)return String(e);try{return JSON.stringify(e)}catch{return\\\"\\\"}}function Dt(e){return null==e||\\\"\\\"===e}function Bt(e,t){let n=e.get(t);return void 0!==n&&(e.delete(t),e.set(t,n)),n}function _t(e,t,n,i){return e.set(t,n),function(e,t){for(let n of e.keys()){if(e.size<=t)break;e.delete(n)}}(e,i),n}function zt(e){let t=Bt(to,e);if(void 0!==t)return t;let n=new Set(Ql);for(let t of e.matchAll(Yl)){let e=t[1]?.toLowerCase();void 0!==e&&n.add(e)}let i={};for(let e of n)i[e]=Zl;let r={additionalAllowedTags:[...n],additionalAllowedAttributes:i,allowFormControls:!0,templateMode:!0};return _t(to,e,r,eo)}function Vt(e){let t=Ht(e.container,e.patches,e);return null===t?null:Gt(t,e.store,{morph:e.morph??!0,onDuplicateKey:e.onDuplicateKey})}function qt(e,t){return t.hasAttribute(io)&&t.hasAttribute(ro)}function Ht(e,t,n){let i=function(e,t,n){let{template:i,nextItems:r,forceRender:l=!1,store:o,sanitizerPolicy:s}=n,a=o.get(e),u=It(e),d=Pt(r),c=Array.from(e.children),h=en(c,no),f=new Set,p=[];for(let o=0;o<r.length;o+=1){let g=r[o],m=Yt(g),v=void 0===m?c[o]??null:tn(h,m)??null;null!==v&&f.has(v)&&(v=null),null!==v&&f.add(v);let y=t.replaces.has(o),b=l||t.renders.has(o)||null===v?nn(e.ownerDocument,i,g,o,s,u,d):void 0;if(null===b)return null;let w=void 0===b?[]:Kt(y?null:v,b,g,void 0===m?void 0:a?.get(m),n);if(null===w)return null;p.push([o,v,b,w,y])}return p}(e,function(e){let t=new Set,n=new Set;for(let i of e)\\\"insert\\\"===i.kind||\\\"update\\\"===i.kind?t.add(i.index):\\\"replace\\\"===i.kind&&(t.add(i.index),n.add(i.index));return{renders:t,replaces:n}}(t),n);return null===i?null:[e,i,n.nextItems]}function Gt(e,t,n){let[i,r,l]=e,o=new Set,s=!1,a=Tt(i);for(let[e,l,a,u,d]of r){let r=l;if(void 0!==a){let e=!(!n.morph||d||null===l)&&wt(l,a,{keyAttributes:[no,io],boundary:oe,retainBoundary:he,retainChildrenOf:qt,...void 0!==n.onDuplicateKey?{onDuplicateKey:n.onDuplicateKey}:{}})===l;if(!e)for(let[e,t]of u)null!==e&&(Xt(e,t),t.replaceWith(e));for(let[,,e]of u)void 0!==e&&Gt(e,t,n);e?s=!0:(null!==l&&(l.replaceWith(a),s=!0),r=a)}if(null===r)continue;let c=i.children[e]??null;r!==c&&(i.insertBefore(r,c),s=!0),o.add(r)}for(let e of Array.from(i.children))o.has(e)||(e.remove(),s=!0);Ct(a);let u=function(e,t){let n=t.get(e);return n||(n=new Map,t.set(e,n)),n}(i,t);u.clear();for(let e of l)Zt(u,e);return s}function Kt(e,t,n,i,r){let l=en(null===e?[]:Jt(e),io),o=[];for(let e of Jt(t)){let t=e.getAttribute(io);if(null===t)continue;let s,a=tn(l,t)??null,u=e.getAttribute(ro),d=u?a:null,c=d?.getAttribute(ro)??null;if(u){let l=Qt(n,t);if(void 0!==l||null!==d){let n=l??[],o=R(null===d?[]:Qt(i,t)??[],n),a=null!==d&&c!==u;if((o.length>0||a)&&(s=Ht(d??e,o,{template:u,nextItems:n,forceRender:a,store:r.store,sanitizerPolicy:r.sanitizerPolicy})??void 0,void 0===s))return null}}o.push([d,e,s])}return o}function Jt(e){return Array.from(e.querySelectorAll(`[${io}]`)).filter(t=>{let n=t.parentElement;for(;null!==n&&n!==e;){if(n.hasAttribute(io))return!1;n=n.parentElement}return n===e})}function Xt(e,t){for(let n of Array.from(e.attributes))t.hasAttribute(n.name)||e.removeAttribute(n.name);for(let n of Array.from(t.attributes))e.getAttribute(n.name)!==n.value&&e.setAttribute(n.name,n.value)}function Qt(e,t){if(\\\"object\\\"!=typeof e||null===e)return;let n=e[t];return Array.isArray(n)?n:void 0}function Zt(e,t){let n=Yt(t);void 0!==n&&e.set(n,t)}function Yt(e){if(\\\"object\\\"!=typeof e||null===e)return;let t=e.id;return\\\"string\\\"==typeof t||\\\"number\\\"==typeof t?String(t):void 0}function en(e,t){let n=new Map;for(let i=e.length-1;i>=0;i-=1){let r=e[i];if(void 0===r)continue;let l=r.getAttribute(t);if(null===l)continue;let o=n.get(l);void 0===o?n.set(l,[r]):o.push(r)}return n}function tn(e,t){return e.get(t)?.pop()}function nn(e,t,n,i,r,l,o){let s=Ft(Ut(t,n,i,Wt,o),r,zt(t)),a=e.createElement(\\\"template\\\");a.innerHTML=yt(s);let u=a.content.firstElementChild;if(!u)return null;jt(u,l);let d=Yt(n);return void 0!==d&&u.setAttribute(no,d),u}function rn(e,t,n){t.warnedEscalationUnavailable||(t.warnedEscalationUnavailable=!0,e.warn(`[live-preview] LP0808: onUnfaithfulPatch: 'escalate' has nowhere to go: ${String(n)} field(s) fell short and no route or fragment strategy is configured. Set routeStrategy: true or fragments: { endpoint }, or onUnfaithfulPatch: 'warn' to keep the patch and say so.`))}function ln(e,t,n){let i=new Set(t);return{boundaries:t,strategy:e,ownerKeys:n,covers:e=>void 0!==e.fragmentBoundary&&i.has(e.fragmentBoundary)}}function on(e,t){return!1===t||W(ge(e),t)}function sn(t,n,i,r,l){let o=t.transformValue;if(void 0===o)return i;try{let t=o(n.fieldName,i,{element:n.element,allFields:r},l),s=e(t);if(!l())return i;if(s)throw new TypeError(`Transform for \\\"${n.fieldName}\\\" returned a thenable; transforms must be synchronous`);return t}catch(e){if(!l())return i;let n=e instanceof Error?e:new Error(String(e));return t.emitter.emit(\\\"error\\\",{error:n,context:\\\"transform\\\",code:\\\"LP0602\\\"}),i}}function an(){if(typ\",\"eof window>\\\"u\\\")return!1;try{return window.self!==window.top}catch{return!0}}function un(e){let t=e.trim();if(0!==t.length)try{let e=new URL(t);return\\\"http:\\\"!==e.protocol&&\\\"https:\\\"!==e.protocol||!po.test(e.origin)?void 0:e.origin}catch{return}}function dn(e){let t=e.format;return\\\"string\\\"==typeof t&&So.has(t)?t:\\\"number\\\"==typeof t?wo[t]:void 0}function cn(e){let t=e.indent;return\\\"number\\\"==typeof t&&t>0?t:0}function hn(e){return\\\"rtl\\\"===e.direction?' dir=\\\"rtl\\\"':\\\"ltr\\\"===e.direction?' dir=\\\"ltr\\\"':\\\"\\\"}function fn(e){let t=dn(e),n=cn(e),i=[];return void 0!==t&&i.push(`lp-align-${t}`),n>0&&i.push(`lp-indent-${String(n)}`),0===i.length?\\\"\\\":` class=\\\"${i.join(\\\" \\\")}\\\"`}function pn(e){return\\\"object\\\"==typeof e&&null!==e?e:void 0}function gn(e){return pn(e)}function mn(e,t){if(void 0===t||\\\"\\\"===t||!e.startsWith(\\\"/\\\"))return e;try{let n=new URL(t),i=new URL(e,n);return i.origin===n.origin?i.href:e}catch{return e}}function vn(e){return e.replace(/[^a-zA-Z0-9_-]/g,\\\"-\\\").toLowerCase()}function yn(e){return\\\"string\\\"==typeof e&&e.length>0?e:void 0}function bn(e){let t=yn(e.title)??yn(e.name)??yn(e.slug);return void 0!==t?t:void 0===e.id?void 0:String(e.id)}function wn(e){if(\\\"string\\\"==typeof e.text)return e.text;if(!e.children)return\\\"\\\";let t=\\\"\\\";for(let n of e.children)t+=wn(n);return t}function Sn(e){return`${\\\"number\\\"==typeof e.width?` width=\\\"${String(e.width)}\\\"`:\\\"\\\"}${\\\"number\\\"==typeof e.height?` height=\\\"${String(e.height)}\\\"`:\\\"\\\"}`}function An(e){return\\\"string\\\"==typeof e.mimeType?` type=\\\"${xt(e.mimeType)}\\\"`:\\\"\\\"}function kn(e){return Co.get(e)}function Tn(e,t,n,i){let r=pn(e.fields)??{},l=\\\"string\\\"==typeof r.blockType?r.blockType:\\\"\\\",o=vn(l),s=\\\"\\\"===o?i:`${i} ${i}--${o}`;if(\\\"\\\"!==l){let e=kn(l)??kn(o);if(e)return e(r,{renderChildren:t.renderChildren});t.onUnrenderedBlock?.(l,s)}return`<${n} class=\\\"${s}\\\"></${n}>`}function Cn(e,t){return\\\"number\\\"==typeof t&&t>1?` ${e}=\\\"${String(t)}\\\"`:\\\"\\\"}function Rn(e){if(\\\"object\\\"!=typeof e||null===e||!(\\\"root\\\"in e))return!1;let t=e.root;return\\\"object\\\"==typeof t&&null!==t&&\\\"children\\\"in t&&Array.isArray(t.children)}function $n(e,t){let n=function(e){return Fo.get(e)??$o[e]}(e.type);return n?n(e,t):void 0!==e.children?t.renderChildren(e.children):\\\"\\\"}function Fn(e){if(\\\"string\\\"==typeof e.text)return e.text;if(\\\"linebreak\\\"===e.type)return\\\"\\\\n\\\";if(void 0===e.children)return\\\"\\\";let t=\\\"\\\";for(let n of e.children)t+=Fn(n);return t}function Nn(e=\\\"text\\\"){let t=new WeakSet;return{name:e,render:O((e,n)=>{let i=e.element,r=function(e){return null==e?\\\"\\\":Rn(e)?function(e){return Rn(e)?e.root.children.map(Fn).join(\\\"\\\\n\\\").trim():\\\"\\\"}(e):\\\"string\\\"==typeof e?e:\\\"number\\\"==typeof e||\\\"boolean\\\"==typeof e?String(e):JSON.stringify(e)}(n);if(\\\"INPUT\\\"!==i.tagName&&\\\"TEXTAREA\\\"!==i.tagName){if(function(e){return null!==e.querySelector(\\\":scope > :not(br)\\\")}(i)&&!i.hasAttribute(Mo))return function(e,t,n){e.has(t)||(e.add(t),ai(`[live-preview] LP0402: Skipping text update for \\\"${n}\\\": <${t.tagName.toLowerCase()}> has structured children. Move data-payload-field to the value element, or add data-payload-text to replace them.`))}(t,i,e.fieldName),!1;r.includes(\\\"\\\\n\\\")||r.includes(\\\"\\\\r\\\")?i.innerHTML=yt(function(e){return Lt(e).replace(/\\\\r\\\\n|\\\\r|\\\\n/g,\\\"<br>\\\")}(r)):i.textContent=r}else i.value=r})}}function Mn(e,t){let n=e.cloneNode(!1);n.innerHTML=yt(t);let i=function(e,t){let n=e.firstElementChild;if(null!==n?.nextElementSibling||t.children.length<2||!Lo.has(n.tagName)||n.hasAttribute(cr))return null;for(let e of t.children)if(e.tagName===n.tagName&&e.className===n.className)return null;return n}(e,n)??e,r=new Map,l=n.querySelectorAll(Ro);if(l.length>0&&null!==i.firstElementChild){let e=[];On(i,n,e);for(let[t,n]of e)t.replaceWith(n),n.matches(Ro)||r.set(t.className,!1);for(let e of l)null!==e.parentNode&&r.set(e.className,!0)}return i.replaceChildren(...n.childNodes),r}function On(e,t,n){if(e.children.length!==t.children.length)return;let i=e.firstElementChild,r=t.firstElementChild;for(;null!==i&&null!==r;)r.matches(Ro)?n.push([r,i]):On(i,r,n),i=i.nextElementSibling,r=r.nextElementSibling}function En(e,t,n,i){i&&t.reportUnfaithful?.(e,`lost the markup the server drew for block \\\"${n}\\\"`);let r=i?Eo:Oo;r.has(n)||(r.add(n),ai(`[live-preview] ${i?`LP0413: no renderer for block \\\"${n}\\\", and the markup the server rendered for it is lost.`:`LP0410: no renderer for block \\\"${n}\\\"; keeping what the server rendered for it.`} Register one with registerBlockRenderer().`))}function Ln(e,t,n,i){if(\\\"string\\\"!=typeof n||0===n.length)return{kind:\\\"none\\\"};let r=mn(n,i);return F(r)?{kind:\\\"safe\\\",url:r}:(Uo.has(e)||(Uo.add(e),ai(`[live-preview] LP0401: refused an unsafe URL for \\\"${t}\\\" on <${e.tagName.toLowerCase()}>; the attribute was cleared.`)),{kind:\\\"unsafe\\\"})}function xn(e,t=e=>e){return{name:e,render(e,n,i){let r=e.element;if(Dt(n)){!function(e){\\\"INPUT\\\"!==e.tagName&&\\\"TEXTAREA\\\"!==e.tagName?(e.removeAttribute(\\\"href\\\"),e.textContent=\\\"\\\"):e.value=\\\"\\\"}(r);return}let l=Wt(n);if(\\\"INPUT\\\"!==r.tagName&&\\\"TEXTAREA\\\"!==r.tagName){if(\\\"A\\\"===r.tagName){let n=e.hrefField,o=void 0===n||0===n.length?t(l):ut(i.allFields,n,i.locale,void 0!==e.locale),s=Ln(r,e.fieldName,o);\\\"safe\\\"===s.kind?r.setAttribute(\\\"href\\\",s.url):\\\"unsafe\\\"===s.kind&&r.removeAttribute(\\\"href\\\")}r.textContent=l}else r.value=l}}}function Pn(e){for(let t of Do)e.removeAttribute(t)}function Un(e,t,n,i){e.src=t;let r=function(e,t){if(void 0===e?.sizes)return;let n=[];for(let i of Object.values(e.sizes)){if(\\\"string\\\"!=typeof i.url||\\\"number\\\"!=typeof i.width)continue;let e=mn(i.url,t);F(e)&&n.push(`${In(e)} ${String(i.width)}w`)}if(0!==n.length){if(\\\"number\\\"==typeof e.width&&\\\"string\\\"==typeof e.url){let i=mn(e.url,t);F(i)&&n.push(`${In(i)} ${String(e.width)}w`)}return n.join(\\\", \\\")}}(n,i);void 0!==r?e.setAttribute(\\\"srcset\\\",r):(e.removeAttribute(\\\"srcset\\\"),e.removeAttribute(\\\"sizes\\\"))}function In(e){return e.replace(/[\\\\s,]/g,encodeURIComponent)}function jn(e){\\\"IMG\\\"===e.tagName?Pn(e):e.style.backgroundImage=\\\"\\\"}function Wn(e){\\\"IMG\\\"!==e.tagName?(e.removeAttribute(\\\"href\\\"),e.textContent=\\\"\\\"):Pn(e)}function Dn(e){let t=pn(e);return void 0===t?Wt(e):bn(t)??\\\"\\\"}function Bn(e,t){let n=e??\\\"\\\";if(null==t)return n;let i=_n(t);return\\\"{}\\\"===i?n:`${n}|${i}`}function _n(e){if(null===e||\\\"object\\\"!=typeof e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(e=>_n(e)).join(\\\",\\\")}]`;let t=e,n=Object.keys(t).sort(),i=[];for(let e of n){let n=t[e];void 0!==n&&i.push(`${JSON.stringify(e)}:${_n(n)}`)}return`{${i.join(\\\",\\\")}}`}function zn(e){return{kind:\\\"date\\\",options:e}}function Vn(e){return{kind:\\\"number\\\",options:e}}function qn(e,t,n,i){if(void 0===t||\\\"\\\"===t)return;let r=function(e){let t=e.indexOf(\\\":\\\"),n=-1===t?e:e.slice(0,t),i=-1===t?void 0:e.slice(t+1);switch(n){case\\\"date\\\":return void 0===i?zn({dateStyle:\\\"medium\\\"}):Jo.has(i)?zn({dateStyle:i}):void 0;case\\\"time\\\":return void 0===i?zn({timeStyle:\\\"short\\\"}):Xo.has(i)?zn({timeStyle:i}):void 0;case\\\"datetime\\\":return void 0===i?zn({dateStyle:\\\"medium\\\",timeStyle:\\\"short\\\"}):Jo.has(i)?zn({dateStyle:i,timeStyle:\\\"short\\\"===i?\\\"short\\\":\\\"medium\\\"}):void 0;case\\\"number\\\":return void 0===i?Vn({}):Zo.test(i)?Vn({minimumFractionDigits:Number(i),maximumFractionDigits:Number(i)}):void 0;case\\\"currency\\\":return void 0!==i&&Qo.test(i)?Vn({style:\\\"currency\\\",currency:i.toUpperCase()}):void 0;case\\\"percent\\\":return void 0===i?Vn({style:\\\"percent\\\"}):void 0;default:return}}(t);if(void 0!==r)return r.kind===e?r.options:void 0;!function(e,t,n){Yo.has(e)||(Yo.add(e),ai(`[live-preview] LP0408: data-payload-format=\\\"${n}\\\" on \\\"${t}\\\" is not a known format; the default formatting was used. Known: date, time, datetime (each also :short|medium|long|full), number, number:0-4, currency:XXX, percent.`))}(n,i,t)}function Hn(e){return String(e).padStart(2,\\\"0\\\")}function Gn(){let e=new WeakMap,t=new WeakSet,n=new WeakMap,i=new WeakMap;return{name:\\\"structural-array\\\",render:O((r,l,o)=>{let s=Dt(l)?[]:l;if(!Array.isArray(s))return!1;let a=r.element,u=r.arrayTemplate;if(void 0===u||0===u.length)return function(e,t,n){e.has(t)||(e.add(t),ai(`[live-preview] LP0403: Skipping structural update for \\\"${n}\\\": <${t.tagName.toLowerCase()} data-payload-structural> needs data-payload-array-template (for example \\\"<li>{{label}}</li>\\\").`))}(t,a,r.fieldName),!1;let d=e.get(a),c=Kn(a),h=d?.values??function(e){return e.map((e,t)=>null===e?{__payloadDomPosition:t}:{id:e})}(c),f=R(h,s),p=function(e,t,n){return void 0===e||e.template!==t||!function(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}(e.domSnapshot,n)}(d,u,c);if(0===f.length&&!p)return e.set(a,{values:s.slice(),template:u,domSnapshot:c}),!1;!function(e,t,n,i,r){let l=r.map(Jn),o=new Set,s=l.find(e=>!(void 0===e||!o.has(e)&&(o.add(e),1)));if(void 0!==s&&Xn(e,t,n,s),l.some(e=>void 0===e)&&Qn(e,t,\\\"LP0404\\\",`LP0404: an item of \\\"${n}\\\" has no id and pairs by position, so an insert re-renders every row after it. Give items a stable id.`),i?.length===r.length&&r.length>1){let r=new Set(i.map(Jn).filter(e=>void 0!==e)),o=l.some(e=>void 0!==e&&r.has(e));r.size>0&&!o&&Qn(e,t,\\\"LP0406\\\",`LP0406: every key of \\\"${n}\\\" changed at once; the source generates ids per message, so no item can be retained across updates.`)}}(n,a,r.fieldName,d?.values,s);let g=Vt({template:u,container:a,patches:f,nextItems:s,store:i,forceRender:p,sanitizerPolicy:o.sanitizerPolicy,onDuplicateKey:(e,t)=>{Xn(n,e,r.fieldName,t)}});return null!==g&&(e.set(a,{values:s.slice(),template:u,domSnapshot:Kn(a)}),!!g&&void 0)})}}function Kn(e){return Array.from(e.children,e=>e.getAttribute(no))}function Jn(e){if(\\\"object\\\"!=typeof e||null===e)return;let t=e.id;return\\\"string\\\"==typeof t||\\\"number\\\"==typeof t?String(t):void 0}function Xn(e,t,n,i){Qn(e,t,\\\"LP0405\\\",`LP0405: two items of \\\"${n}\\\" share the key \\\"${i}\\\"; later ones pair by position. Make \\\\`id\\\\` unique per item.`)}function Qn(e,t,n,i){let r=e.get(t);void 0===r&&(r=new Set,e.set(t,r)),!r.has(n)&&(r.add(n),ai(`[live-preview] ${i}`))}function Zn(){return typeof __LIVE_PREVIEW_CONFIG__>\\\"u\\\"?[]:__LIVE_PREVIEW_CONFIG__}var Yn=Object.defineProperty,ei=e=>{throw TypeError(e)},ti=(e,t,n)=>((e,t,n)=>t in e?Yn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,\\\"symbol\\\"!=typeof t?t+\\\"\\\":t,n),ni=(e,t,n)=>t.has(e)||ei(\\\"Cannot \\\"+n),ii=(e,t,n)=>(ni(e,t,\\\"read from private field\\\"),n?n.call(e):t.get(e)),ri=(e,t,n)=>t.has(e)?ei(\\\"Cannot add the same private member more than once\\\"):t instanceof WeakSet?t.add(e):t.set(e,n),li=(e,t,n,i)=>(ni(e,t,\\\"write to private field\\\"),i?i.call(e,n):t.set(e,n),n),oi=(e,t,n)=>(ni(e,t,\\\"access private method\\\"),n),si=t((...e)=>console.error(...e)),ai=t((...e)=>console.warn(...e)),ui=t((...e)=>console.debug(...e)),di=class{constructor(){ri(this,fi);ri(this,ci,new Map);ri(this,hi,new Map)}on(e,t){return oi(this,fi,gi).call(this,ii(this,ci),e,t)}once(e,t){return oi(this,fi,gi).call(this,ii(this,hi),e,t)}off(e,t){oi(this,fi,mi).call(this,ii(this,ci),e,t),oi(this,fi,mi).call(this,ii(this,hi),e,t)}async emit(e,t){await oi(this,fi,pi).call(this,e,t)}async emitWhile(e,t,n){return oi(this,fi,pi).call(this,e,t,n)}listenerCount(e){return(ii(this,ci).get(e)?.size??0)+(ii(this,hi).get(e)?.size??0)}removeAllListeners(e){void 0!==e?(ii(this,ci).delete(e),ii(this,hi).delete(e)):(ii(this,ci).clear(),ii(this,hi).clear())}eventNames(){let e=new Set;for(let t of ii(this,ci).keys())e.add(t);for(let t of ii(this,hi).keys())e.add(t);return[...e]}},ci=new WeakMap,hi=new WeakMap,fi=new WeakSet,pi=async function(e,t,n){let i=()=>n?.()??!0;if(!i())return!1;let r=ii(this,ci).get(e);if(r)for(let n of[...r])if(!i()||(await oi(this,fi,vi).call(this,n,t,e),!i()))return!1;if(!i())return!1;let l=ii(this,hi).get(e);if(l&&l.size>0){let n=[...l];ii(this,hi).delete(e);for(let r of n)if(!i()||(await oi(this,fi,vi).call(this,r,t,e),!i()))return!1}return i()},gi=function(e,t,n){let i=e.get(t);return i||(i=new Set,e.set(t,i)),i.add(n),()=>{oi(this,fi,mi).call(this,e,t,n)}},mi=function(e,t,n){let i=e.get(t);void 0!==i&&(i.delete(n),0===i.size&&e.delete(t))},vi=async function(e,t,n){try{await e(t)}catch(e){let t=\\\"string\\\"==typeof n||\\\"number\\\"==typeof n?String(n):\\\"<event>\\\";si(`[live-preview] LP0601: handler for \\\"${t}\\\" threw:`,e)}},yi=new Set([\\\"date\\\",\\\"number\\\",\\\"checkbox\\\"]),bi=40,wi=\\\"payload-live-preview-a11y\\\",Si=new WeakMap,Ai=class{constructor(e,t){ti(this,\\\"german\\\");ti(this,\\\"document\\\");ti(this,\\\"lease\\\",null);let n=t??(typ\",\"eof document>\\\"u\\\"?null:document),i=n?.documentElement.getAttribute(\\\"lang\\\")??\\\"\\\";this.german=function(e){return/^de(?:[-_]|$)/i.test(e)}(e??(i.length>0?i:a())),this.document=n}mount(){let e=this.document;if(null==e?.body)return null;this.lease??(this.lease=function(e){let t=Si.get(e);return void 0===t&&(t={element:null,owned:!1,messageNode:null,refs:0,timer:null},Si.set(e,t)),t.refs+=1,t}(e));let t=this.lease,n=t.element;if(n?.isConnected&&n.ownerDocument===e)return n;if(null!==n){let e=t.owned;u(t),e&&n.remove()}let i=e.getElementById(wi);return t.owned=null===i,null===i&&(i=e.createElement(\\\"div\\\"),i.id=wi,i.setAttribute(\\\"role\\\",\\\"status\\\"),i.setAttribute(\\\"aria-live\\\",\\\"polite\\\"),i.setAttribute(\\\"aria-atomic\\\",\\\"true\\\"),i.style.cssText=\\\"position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap;border:0\\\",e.body.appendChild(i)),t.element=i,i}announceConnected(){this.say(this.german?\\\"Vorschau verbunden\\\":\\\"Live preview connected\\\")}announceDisconnected(){this.say(this.german?\\\"Vorschau getrennt\\\":\\\"Live preview disconnected\\\")}announceUpdate(e){e<=0||this.say(this.german?`${String(e)} ${1===e?\\\"\\\\xc4nderung\\\":\\\"\\\\xc4nderungen\\\"} angewendet`:`${String(e)} ${1===e?\\\"change\\\":\\\"changes\\\"} applied`)}announcePartial(){this.say(this.german?\\\"Vorschau teilweise aktualisiert\\\":\\\"Preview partly updated\\\")}detach(){let e=this.lease,t=this.document;if(null===e||null===t||(this.lease=null,e.refs-=1,e.refs>0))return;let n=e.element;null!==n&&u(e),e.owned&&n?.remove(),e.element=null,Si.delete(t)}say(e){let t=this.mount(),n=this.lease;if(null===t||null===n)return;let i=n.messageNode;i?.parentNode!==t?(i?.remove(),i=t.ownerDocument.createTextNode(t.hasChildNodes()?` ${e}`:e),n.messageNode=i,t.appendChild(i)):i.data=null===i.previousSibling?e:` ${e}`,null!==n.timer&&clearTimeout(n.timer);let r=setTimeout(()=>{n.timer===r&&n.element===t&&u(n)},1500);n.timer=r}},ki=[\\\"data\\\",\\\"fieldSchemaJSON\\\",\\\"globalSlug\\\",\\\"collectionSlug\\\",\\\"locale\\\",\\\"ready\\\",\\\"previewToken\\\",\\\"protocolVersion\\\"],Ti={basic:{since:1},\\\"schema-json\\\":{since:2,observed:\\\"schema\\\"},locale:{since:2,observed:\\\"locale\\\"},\\\"preview-token\\\":{since:3,observed:\\\"preview-token\\\"},\\\"nested-arrays\\\":{since:4},\\\"recursive-diffs\\\":{since:4},\\\"document-events\\\":{since:4,observed:\\\"document-event\\\"},\\\"relationship-events\\\":{since:4,observed:\\\"relationship-event\\\"}},Ci=Object.keys(Ti),Ri=class{constructor(e,t){ti(this,\\\"matcher\\\");ti(this,\\\"handlers\\\");ti(this,\\\"boundListener\\\");ti(this,\\\"attachedTarget\\\");ti(this,\\\"generation\\\",0);ti(this,\\\"revision\\\",0);ti(this,\\\"queueHead\\\");ti(this,\\\"queueTail\\\");ti(this,\\\"lastAccepted\\\");ti(this,\\\"replayedGeneration\\\",0);ti(this,\\\"latestAcceptedAttempt\\\");this.matcher=e,this.handlers=t}attach(e=window){if(void 0!==this.attachedTarget)return;let t=!1,n=i=>{if(!t||this.boundListener!==n)return;let r=this.generation;try{this.receive(i,r,e)}catch{let e;try{e=i.origin}catch{e=\\\"\\\"}this.reportInvalid(\\\"shape\\\",e,r)}};this.generation+=1,this.resetQueue(),this.attachedTarget=e,this.boundListener=n;try{e.addEventListener(\\\"message\\\",n)}catch(t){this.boundListener===n&&(this.attachedTarget=void 0,this.boundListener=void 0,this.resetQueue());try{e.removeEventListener(\\\"message\\\",n)}catch{}throw t}if(this.boundListener===n)t=!0;else try{e.removeEventListener(\\\"message\\\",n)}catch{}}detach(){let e=this.attachedTarget,t=this.boundListener;void 0===e||void 0===t||(this.attachedTarget=void 0,this.boundListener=void 0,this.resetQueue(),e.removeEventListener(\\\"message\\\",t))}advanceGeneration(){return void 0!==this.attachedTarget&&(this.generation+=1,this.resetQueue(),!0)}replayLastAccepted(){let e=this.lastAccepted,t=this.generation,n=this.handlers.onReplay;if(void 0===n||void 0===e||e.generation>=t||this.replayedGeneration===t||!this.matchesOrigin(e.origin,t)||this.lastAccepted!==e)return!1;this.replayedGeneration=t;let i={generation:t,revision:this.revision+=1};return this.invokeHandler(t,n,structuredClone(e.message),e.origin,i),!0}forgetLastAccepted(){this.lastAccepted=void 0,this.replayedGeneration=0,this.latestAcceptedAttempt=void 0}static sendReady(e,t){let n={type:\\\"payload-live-preview\\\",ready:!0,protocolVersion:4};for(let i of e)for(let e of t)try{i.postMessage(n,e)}catch{}}receive(e,t,n){let i=e.origin;if(!this.matchesOrigin(i,t)){this.reportInvalid(\\\"origin\\\",i,t);return}if(!this.matchesSource(e,n)){this.reportInvalid(\\\"source\\\",i,t);return}let r=e.data;if(function(e){return\\\"object\\\"==typeof e&&null!==e&&\\\"type\\\"in e&&\\\"string\\\"==typeof e.type}(r))switch(r.type){case\\\"payload-live-preview\\\":if(!function(e){let t=e;return!(void 0!==t.data&&null!==t.data&&!v(t.data))&&m(t.fieldSchemaJSON,e=>Array.isArray(e))&&m(t.globalSlug,e=>\\\"string\\\"==typeof e)&&m(t.collectionSlug,e=>\\\"string\\\"==typeof e)&&m(t.locale,e=>\\\"string\\\"==typeof e)&&m(t.ready,e=>\\\"boolean\\\"==typeof e)&&m(t.previewToken,e=>\\\"string\\\"==typeof e)&&m(t.protocolVersion,e=>\\\"number\\\"==typeof e)}(r)){this.reportInvalid(\\\"shape\\\",i,t);return}this.dispatchUpdate(function(e){let t={...e};for(let e of ki)null===Reflect.get(t,e)&&Reflect.deleteProperty(t,e);return Array.isArray(t.fieldSchemaJSON)?{...t,fieldSchemaJSON:h(t.fieldSchemaJSON)}:t}(r),i,t);return;case\\\"payload-document-event\\\":if(!function(e){let t=e;return g(t.action,e=>\\\"updated\\\"===e||\\\"created\\\"===e||\\\"deleted\\\"===e)&&g(t.slug,e=>\\\"string\\\"==typeof e)&&g(t.id,e=>\\\"string\\\"==typeof e||Number.isFinite(e))}(r)){this.reportInvalid(\\\"shape\\\",i,t);return}this.invokeHandler(t,this.handlers.onDocumentEvent,r,i);return;case\\\"payload-live-preview-focus\\\":{let e=function(e){let t=e.field;return\\\"string\\\"==typeof t&&t.length>0?t:void 0}(r);if(void 0===e){this.reportInvalid(\\\"shape\\\",i,t);return}this.invokeHandler(t,this.handlers.onFocusField,e,i);return}default:this.reportInvalid(\\\"type\\\",i,t)}else this.reportInvalid(\\\"shape\\\",i,t)}dispatchUpdate(e,t,n){let i=v(e.data);if(!this.isCurrentGeneration(n))return;let r=i?{generation:n,revision:this.revision+=1}:void 0,l=this.handlers.validateToken;if(!this.isCurrentGeneration(n))return;if(void 0===l){this.commitUpdate(e,t,n,r);return}if(!0===e.ready&&void 0===e.data){this.commitUpdate(e,t,n,void 0);return}let o={generation:n,message:e,origin:t,messageRevision:r,verdict:void 0,next:void 0};this.enqueue(o);let s;try{s=l(e.previewToken,t)}catch{this.settleValidation(o,!1);return}\\\"boolean\\\"!=typeof s?Promise.resolve(s).then(e=>{this.settleValidation(o,!0===e)},()=>{this.settleValidation(o,!1)}):this.settleValidation(o,s)}settleValidation(e,t){e.verdict=t,this.drainQueue(e.generation)}drainQueue(e){for(;this.isCurrentGeneration(e);){let t=this.queueHead;if(void 0===t)return;if(this.matchesOrigin(t.origin,e)){if(void 0===t.verdict)return;this.dequeue(t)&&(t.verdict?this.commitUpdate(t.message,t.origin,t.generation,t.messageRevision):this.reportInvalid(\\\"token\\\",t.origin,t.generation))}else{if(!this.dequeue(t))continue;this.reportInvalid(\\\"origin\\\",t.origin,t.generation)}}}commitUpdate(e,t,n,i){if(void 0===i)this.invokeHandler(n,this.handlers.onUpdate,e,t);else{let r={};this.latestAcceptedAttempt=r;let l=function(e){let t={...e};delete t.previewToken;try{return structuredClone(t)}catch{return null}}(e);if(this.latestAcceptedAttempt!==r||!this.isCurrentGeneration(n))return;this.lastAccepted=null===l?void 0:{generation:n,message:l,origin:t},this.invokeHandler(n,this.handlers.onUpdate,e,t,i)}}reportInvalid(e,t,n){this.invokeHandler(n,this.handlers.onInvalid,e,t)}matchesSource(e,t){if(\\\"parent-or-opener\\\"!==this.handlers.sourcePolicy)return!0;try{let n=e.source;if(\\\"object\\\"!=typeof n||null===n)return!1;let i=t.parent;return i!==t&&n===i||n===t.opener}catch{return!1}}matchesOrigin(e,t){try{return!0===(this.isCurrentGeneration(t)&&this.matcher(e))&&this.isCurrentGeneration(t)}catch{return!1}}invokeHandler(t,n,...i){if(void 0!==n&&this.isCurrentGeneration(t))try{e(n(...i))}catch{}}isCurrentGeneration(e){return void 0!==this.attachedTarget&&this.generation===e}enqueue(e){void 0===this.queueTail?this.queueHead=e:this.queueTail.next=e,this.queueTail=e}dequeue(e){return this.queueHead===e&&(this.queueHead=e.next,void 0===this.queueHead&&(this.queueTail=void 0),!0)}resetQueue(){this.queueHead=void 0,this.queueTail=void 0}},$i=new Set([\\\"tabs\\\",\\\"row\\\",\\\"collapsible\\\"]),Fi={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\\\"},Ni=new Set([\\\"http:\\\",\\\"https:\\\",\\\"mailto:\\\",\\\"tel:\\\"]),Mi=/^(?:\\\\.{1,2}\\\\/|[a-zA-Z0-9_-]+\\\\/?)/,Oi=/^[\\\\\\\\/]{2}/,Ei=/[\\\\t\\\\n\\\\r]/g,Li=/[\\\\s\\\\u0000-\\\\u001f\\\\u180e\\\\u2000-\\\\u2029]/g,xi=/^([a-z][a-z0-9+.-]*):/i,Pi=new Set([\\\"style\\\",\\\"srcdoc\\\",\\\"formaction\\\",\\\"form\\\",\\\"id\\\",\\\"name\\\",\\\"is\\\",\\\"srcset\\\",\\\"imagesrcset\\\"]),Ui=new Set([\\\"href\\\",\\\"src\\\",\\\"poster\\\",\\\"cite\\\",\\\"action\\\",\\\"xlink:href\\\",\\\"data\\\"]),Ii=new WeakSet,ji=class{constructor(){ti(this,\\\"previous\\\",null);ti(this,\\\"lastFields\\\");ti(this,\\\"priorFields\\\");ti(this,\\\"keepValues\\\",!1)}get previousFields(){return this.priorFields}get isBaseline(){return null===this.previous}diff(e,t,n=L){let i=this.previous,r=null===i,l=new Map,o=new Set,s=Object.entries(e);if(!n())return null;for(let[e,t]of s){let r=E(t);if(!n())return null;l.set(e,r),(null===i||void 0===r||i.get(e)!==r)&&o.add(e)}if(null!==i)for(let e of i.keys())l.has(e)||o.add(e);let a=new Set,u=Object.entries(t);if(!n())return null;for(let[e,t]of u)if(o.has(e))for(let e of t)if(a.add(e),!n())return null;return n()?(this.previous=l,this.priorFields=this.keepValues?this.lastFields:void 0,this.lastFields=this.keepValues?e:void 0,{changed:o,invalidated:a,baseline:r}):null}reset(){this.previous=null,this.lastFields=void 0,this.priorFields=void 0}},Wi=\\\"data-payload-fragment\\\",Di=\\\"data-payload-fragment-key\\\",Bi=\\\"data-payload-strategy\\\",_i=8,zi=1024,Vi=new Set([\\\"id\\\",\\\"_id\\\",\\\"createdAt\\\",\\\"updatedAt\\\",\\\"createdBy\\\",\\\"updatedBy\\\",\\\"_status\\\",\\\"globalType\\\",\\\"collection\\\",\\\"locale\\\",\\\"localized\\\"]),qi=new Set([\\\"text\\\",\\\"textarea\\\",\\\"email\\\",\\\"number\\\",\\\"checkbox\\\",\\\"date\\\",\\\"select\\\",\\\"radio\\\",\\\"point\\\",\\\"code\\\",\\\"json\\\",\\\"ui\\\",\\\"html\\\"]),Hi={},Gi=class{constructor(){ti(this,\\\"rawChanges\\\",new ji);ti(this,\\\"resolved\\\",null);ti(this,\\\"resolvedLocale\\\",null);ti(this,\\\"trailing\\\",null);ti(this,\\\"openUntil\\\",0);ti(this,\\\"requestAttempt\\\",0)}decide(e,t){let n=t.rawData;if(!function(e){let{cache:t,emitter:n}=e;if(t.islands.length>0||n.listenerCount(\\\"beforeUpdate\\\")>0||n.listenerCount(\\\"afterUpdate\\\")>0)return!0;for(let e of t.values())if(J(e)||e.fieldName.includes(\\\".\\\")||Q(e.hrefField)||Q(e.srcField)||Q(e.altField))return!0;return void 0!==e.strategies.fragment&&null!==e.root.querySelector(`[${Wi}]`)}(e))return t.forceRender&&(this.resolvedLocale=null),{merge:!1,fields:n};let{changed:i}=this.rawChanges.diff(n,Hi),r=this.resolvedLocale!==t.locale,l=this.resolved;if(null===l)return this.resolved=n,{merge:!0,fields:n};let o={...l};t.forceRender&&(this.resolvedLocale=null);let s=t.forceRender||r;for(let r of i){let i=n[r];if(Vi.has(r)){o[r]=i;continue}let a=K(r,l[r],i,e.cache,t.schemaIndex);\\\"own\\\"!==a&&(s=!0,this.resolvedLocale=null),\\\"keep\\\"!==a&&(o[r]=i)}return this.resolved=o,{merge:s,fields:o}}request(e,t,n){let i=++this.requestAttempt,r=Date.now();if(r>=this.openUntil)return this.openUntil=r+t,this.dropQueued(),this.requestAttempt!==i?{leading:!0,result:Promise.resolve({status:\\\"superseded\\\"})}:{leading:!0,result:e.merge(n)};let l=this.trailing,o=l?.pending??function(){let e;return{promise:new Promise(t=>{e=t}),settle:e}}(),s={request:n,pending:o,timer:null};if(this.trailing=s,this.openUntil=r+t,null!==l&&null!==l.timer&&clearTimeout(l.timer),this.trailing!==s)return{leading:!1,result:o.promise};let a=setTimeout(()=>{this.flush(e,s)},t);return this.trailing===s?s.timer=a:clearTimeout(a),{leading:!1,result:o.promise}}recordMerged(e,t){this.resolved=e,this.resolvedLocale=t}resetRawChanges(){this.rawChanges.reset()}destroy(){this.requestAttempt+=1,this.openUntil=0,this.dropQueued()}dropQueued(){let e=this.trailing;this.trailing=null,null!==e&&(null!==e.timer&&clearTimeout(e.timer),e.pending.settle({status:\\\"superseded\\\"}))}flush(e,t){this.trailing===t&&(this.trailing=null,t.timer=null,e.merge(t.request).then(t.pending.settle))}},Ki=class{constructor(){ti(this,\\\"negotiation\\\",y(void 0));ti(this,\\\"observed\\\",new Set)}observe(e,t){let n=e.filter(e=>!this.observed.has(e));if(0!==n.length){for(let e of n)this.observed.add(e);this.negotiation=y(this.negotiation.theirs,this.observed),t(\\\"protocol\\\",`observed=${n.join(\\\",\\\")}`)}}applyVersion(e,t){let n=this.negotiation;if(n.theirs===e)return;let i=y(e,this.observed);this.negotiation=i,i.negotiated!==n.negotiated&&t(\\\"protocol\\\",\\\"ours=4\\\",`theirs=${e}`,`negotiated=${i.negotiated}`)}},Ji=class{constructor(){ti(this,\\\"lastIdentity\\\")}inspect(e){let t=e.externallyUpdatedRelationship;if(\\\"object\\\"!=typeof t||null===t)return null;let n=JSON.stringify([t.entitySlug,D(t),t.updatedAt]);return{identity:n,edit:n!==this.lastIdentity&&Z(t,e)?t:null}}commit(e){let t=e.identity!==this.lastIdentity;return this.lastIdentity=e.identity,t?e.edit:null}},Xi=class{constructor(){ri(this,Qi)}reveal(e,t,n){return e===ii(this,Qi)?\\\"skipped-same\\\":(li(this,Qi,e),function(e,t){return function(e,t){let n=e.getBoundingClientRect(),i=n.bottom>0&&n.top<t.innerHeight,r=n.right>0&&n.left<t.innerWidth;return i&&r}(e,t)?\\\"already-visible\\\":(e.scrollIntoView({behavior:ee(t)?\\\"auto\\\":\\\"smooth\\\",block:\\\"center\\\"}),\\\"revealed\\\")}(t,n))}reset(){li(this,Qi,void 0)}},Qi=new WeakMap,Zi=class{constructor(){ti(this,\\\"seen\\\",new Map)}note(e,t,n){let i=E(n);if(void 0===i)return;let r=`${t.owner??\\\"\\\"}\\\\0${t.locale??\\\"\\\"}\\\\0${t.fieldName}`,l=this.seen.get(r);void 0!==l?l!==i&&(e.revealIdentities.push([r,i]),e.revealTarget??(e.revealTarget=t)):this.seen.set(r,i)}commit(e){for(let[t,n]of e.revealIdentities)this.seen.set(t,n);e.revealIdentities=[];let t=e.revealTarget;return e.revealTarget=void 0,t}},Yi=()=>{},er=class{constructor(){ti(this,\\\"host\\\",{outstanding:()=>!1,report:Yi,failed:Yi});ti(this,\\\"entry\\\",null);ti(this,\\\"ended\\\")}begin(e,t){let n=this.entry,i=null===n?void 0:this.view(n);null!==n&&(n.key=void 0),this.ended=void 0,this.entry={key:e,revision:t,shortfalls:[],seen:new Set,deferred:0,awaiting:0,reported:void 0,queued:!1},null!==n&&void 0!==i&&this.publish(n,\\\"pending\\\"===i.state?{...i,state:\\\"superseded\\\"}:i)}end(){let e=this.entry;if(null!==e){this.entry=null;try{this.ended=this.view(e)}finally{e.key=void 0}}}snapshot(){return null!==this.entry?this.view(this.entry):void 0===this.ended?void 0:{...this.ended,shortfalls:[...this.ended.shortfalls]}}shortfall(e,t){let n=this.entry;if(n?.key!==e)return;let i=JSON.stringify(t);n.seen.has(i)||(n.seen.add(i),n.shortfalls.push(t),this.requestSettle(n.key))}deferred(e,t){this.entry?.key===e&&(this.entry.deferred=t)}handIsland(e){let t=this.entry;if(t?.key!==e)return Yi;t.awaiting+=1;let n=!1;return()=>{n||this.entry!==t||(n=!0,t.awaiting-=1,this.settle(t))}}requestSettle(e){let t=this.entry;t?.key!==e||t.queued||(t.queued=!0,queueMicrotask(()=>{t.queued=!1;try{this.entry===t&&this.settle(t)}catch(e){this.host.failed(e)}}))}settle(e){let t=this.view(e);\\\"pending\\\"!==t.state&&this.publish(e,t)}publish(e,t){e.reported!==t.state&&(e.reported=t.state,this.host.report(t))}view(e){let t=void 0!==e.key&&this.host.outstanding(e.key)?\\\"pending\\\":e.shortfalls.length>0?\\\"partial\\\":e.awaiting>0?\\\"unconfirmed\\\":\\\"current\\\";return{revision:e.revision,state:t,shortfalls:[...e.shortfalls],deferred:e.deferred,awaitingIslands:e.awaiting}}},tr=class{constructor(){ti(this,\\\"started\\\",!1);ti(this,\\\"suspended\\\",!1);ti(this,\\\"deferredStart\\\",null);ti(this,\\\"hydration\\\",\\\"idle\\\");ti(this,\\\"activeUpdate\\\",null);ti(this,\\\"locale\\\");ti(this,\\\"schema\\\");ti(this,\\\"schemaIndex\\\");ti(this,\\\"updateCount\\\",0);ti(this,\\\"supersededCount\\\",0);ti(this,\\\"completedCount\\\",0);ti(this,\\\"skippedUnchangedCount\\\",0);ti(this,\\\"lastFlush\\\",null);ti(this,\\\"absentFields\\\",new Set);ti(this,\\\"warnedOrphanFields\\\",new Set);ti(this,\\\"warnedStrategy\\\",new WeakSet);ti(this,\\\"warnedUnattributableMessage\\\",!1);ti(this,\\\"warnedVisibilityGate\\\",!1);ti(this,\\\"warnedFragmentFallback\\\",!1);ti(this,\\\"warnedIslandStart\\\",!1);ti(this,\\\"warnedEscalationUnavailable\\\",!1);ti(this,\\\"warnedProtocolShape\\\",!1);ti(this,\\\"reportedUnfaithful\\\",new WeakSet);ti(this,\\\"checkedServerFormat\\\",new WeakSet);ti(this,\\\"unfaithfulPatches\\\",[]);ti(this,\\\"unfaithfulCount\\\",0);ti(this,\\\"escalatedCount\\\",0);ti(this,\\\"unfaithfulFields\\\",new Set);ti(this,\\\"autoBindSearchMs\\\");ti(this,\\\"autoBindGuesses\\\",null);ti(this,\\\"warnedForeignSource\\\",!1);ti(this,\\\"lastAppliedIdentity\\\",new WeakMap);ti(this,\\\"navigationReplayPending\\\",!1);ti(this,\\\"navigationBindingReplay\\\",!1);ti(this,\\\"revealLedger\\\",new Zi);ti(this,\\\"display\\\",new er);ti(this,\\\"fragmentStats\\\",{rendered:0,failed:0,superseded:0});ti(this,\\\"routeStats\\\",{refreshes:0,partial:0,failed:0,refused:0,loopStopped:0});ti(this,\\\"fragmentControllers\\\",new Map);ti(this,\\\"routeController\\\",null);ti(this,\\\"routeRetry\\\",null);ti(this,\\\"routeRefreshOwed\\\",!1);ti(this,\\\"routeAwaitsSave\\\",!1);ti(this,\\\"fragmentsOwed\\\",new Set);ti(this,\\\"readyTimers\\\",[]);ti(this,\\\"revealer\\\",new Xi);ti(this,\\\"changes\\\",new ji);ti(this,\\\"merges\\\",new Gi);ti(this,\\\"protocol\\\",new Ki);ti(this,\\\"relationships\\\",new Ji)}isRunning(){return this.started}isCurrent(e){return this.started&&this.activeUpdate===e}complete(e){this.display.requestSettle(e),!e.completed&&(e.completed=!0,e.countsAsUpdate&&(this.completedCount+=1))}forgetOwedWork(){this.routeRefreshOwed=!1,this.routeAwaitsSave=!1,this.fragmentsOwed.clear()}supersedeStrategies(){null!==this.routeRetry&&(clearTimeout(this.routeRetry),this.routeRetry=null,this.routeRefreshOwed=!0);for(let[e,t]of this.fragmentControllers){for(let e of t)this.fragmentsOwed.add(e);e.abort()}this.fragmentControllers.clear()}abortStrategies(){this.supersedeStrategies();let e=this.routeController;this.routeController=null,e?.abort()}},nr=class{constructor(e,t){ti(this,\\\"deps\\\",e);ti(this,\\\"state\\\",t);ti(this,\\\"instanceContext\\\");this.instanceContext=function(e){let t={};for(let[n,i]of Object.entries(e))void 0!==i&&(t[n]=i);return t}({renderRichText:e.renderRichText,sanitizerPolicy:e.sanitizerPolicy,serverURL:e.serverURL,reportUnfaithful:(n,i)=>{r(e,t,n,i)}})}apply(e){let{deps:t,state:n}=this,i=n.activeUpdate;if(null===i||void 0===e.revision||!b(i.revision,e.revision)||!n.isCurrent(i))return!1;let{target:l,value:a}=e,u=void 0!==i.schemaIndex?k(i.schemaIndex,l.fieldName):void 0,d=function(e,t){if(e.explicitFieldType)return e.fieldType;if(void 0!==t){let e=function(e){if(Object.prototype.hasOwnProperty.call(Fi,e))return Fi[e]}(t);if(void 0!==e)return e}return e.fieldType}(l,u?.type);\\\"text\\\"===d&&!0!==l.explicitFieldType&&function(e){if(\\\"object\\\"!=typeof e||null===e||!(\\\"root\\\"in e))return!1;let t=e.root;return\\\"object\\\"==typeof t&&null!==t&&Array.isArray(t.children)}(a)&&(d=\\\"richText\\\");let c;try{c=t.resolveRenderer(d,l)}catch(e){return this.fail(i,l.fieldName,e)}if(!n.isCurrent(i))return!1;let h=t.emitter.listenerCount(\\\"elementUpdate\\\")>0,f=h?function(e){return\\\"INPUT\\\"===e.tagName||\\\"TEXTAREA\\\"===e.tagName?e.value:\\\"IMG\\\"===e.tagName?e.src:e.textContent}(l.element):void 0;if(!n.isCurrent(i))return!1;let p={allFields:e.allFields,locale:l.locale??i.locale,schema:u,...this.instanceContext};!0===l.hidesWhenEmpty&&l.element.toggleAttribute(\\\"hidden\\\",function(e){return null==e||(\\\"string\\\"==typeof e?0===e.trim().length:Array.isArray(e)&&0===e.length)}(a));try{if(void 0!==l.targetAttribute){if(\\\"blocked\\\"===function(e,t,n){let i=t.toLowerCase().trim();if(0===i.length||!M(i))return\\\"blocked\\\";if(null==n)return e.removeAttribute(i),\\\"applied\\\";if(\\\"string\\\"!=typeof n&&\\\"number\\\"!=typeof n&&\\\"boolean\\\"!=typeof n)return\\\"blocked\\\";let r=String(n);return Ui.has(i)&&!F(r)?\\\"blocked\\\":(e.setAttribute(i,r),\\\"applied\\\")}(l.element,l.targetAttribute,a))return t.warn(`[live-preview] LP0401: refused to write \\\"${l.fieldName}\\\" into attribute \\\"${l.targetAttribute}\\\"`),n.display.shortfall(i,{kind:\\\"write\\\",field:l.fieldName,code:\\\"LP0401\\\"}),!1}else{if(void 0===c)return t.log(\\\"no renderer for\\\",d),r(t,n,l,`has no renderer for \\\"${d}\\\"`),!1;{let e=function(e,t,n,i){if(\\\"ignore\\\"===e.onUnfaithfulPatch||void 0!==n.format||!yi.has(i)||t.checkedServerFormat.has(n.element))return;t.checkedServerFormat.add(n.element);let r=o(n.element);return r.trim().length>0?r:void 0}(t,n,l,d);if(!1===function(e,t,n,i){return e.render(t,n,i)}(c,l,a,p)&&function(e){return Ii.has(e.render)}(c))return r(t,n,l,`is a value ${c.name} cannot render`),!1;void 0!==e&&function(e,t,n){let i=o(t.element);i!==n&&e.warn(`[live-preview] LP0412: \\\"${t.fieldName}\\\" showed ${s(n)}, the patch wrote ${s(i)} \\\\u2014 either an edit that arrived before the preview connected, or a template that formats this value differently. Set data-payload-format to match it.`)}(t,l,e)}}}catch(e){return this.fail(i,l.fieldName,e)}if(!n.isCurrent(i))return!1;h&&t.emitter.emitWhile(\\\"elementUpdate\\\",{element:l.element,fieldName:l.fieldName,previousValue:f,nextValue:a,revision:i.revision.revision,receivedAt:i.receivedAt,source:\\\"patch\\\"},()=>n.isCurrent(i));let g=n.isCurrent(i);return g&&(void 0!==e.valueIdentity?n.lastAppliedIdentity.set(l.element,e.valueIdentity):n.lastAppliedIdentity.delete(l.element)),g}fail(e,t,n){if(!this.state.isCurrent(e))return!1;this.state.display.shortfall(e,{kind:\\\"write\\\",field:t,code:\\\"LP0603\\\"});let i=n instanceof Error?n:new Error(String(n));return this.deps.emitter.emitWhile(\\\"error\\\",{error:i,context:\\\"renderer\\\",code:\\\"LP0603\\\"},()=>this.state.isCurrent(e)),!1}},ir=\\\"payload-live-preview:update\\\",rr=\\\"data-payload-island\\\",lr=`astro-island, [${rr}]`,or=\\\"data-payload-owned\\\",sr=\\\"data-payload-morph\\\",ar=[\\\"component-url\\\",\\\"component-export\\\",\\\"renderer-url\\\",\\\"client\\\",\\\"opts\\\",\\\"before-hydration-url\\\"],ur=new WeakMap,dr=new WeakSet,cr=\\\"data-payload-field\\\",hr=\\\"data-payload-type\\\",fr=\\\"data-payload-attribute\\\",pr=\\\"data-payload-href\\\",gr=\\\"data-payload-src\\\",mr=\\\"data-payload-alt\\\",vr=\\\"data-payload-array-template\\\",yr=\\\"data-payload-array-separator\\\",br=\\\"data-payload-locale\\\",wr=\\\"data-payload-richtext\\\",Sr=\\\"data-payload-html\\\",Ar=\\\"data-payload-array\\\",kr=\\\"data-payload-structural\\\",Tr=\\\"data-payload-owner\\\",Cr=\\\"data-payload-depends\\\",Rr=\\\"data-payload-strategy\\\",$r=\\\"data-payload-boundary\\\",Fr=\\\"data-payload-guessed\\\",Nr=\\\"data-payload-covers\\\",Mr=[cr,hr,fr,pr,gr,mr,vr,yr,br,wr,Sr,Ar,kr,Tr,Cr,Rr,$r,\\\"type\\\"],Or=`[${cr}]`,Er=`[${Tr}]`,Lr=`[${Wi}], [${Rr}=\\\"route\\\"]`,xr=/^[a-z][a-z0-9-]*:[a-z][a-z0-9-]*$/i,Pr=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\\\"]),Ur=class{constructor(e={}){ti(this,\\\"entriesByField\\\",new Map);ti(this,\\\"entryByElement\\\",new WeakMap);ti(this,\\\"filter\\\");ti(this,\\\"count\\\",0);ti(this,\\\"dependencies\\\",null);ti(this,\\\"islandRoots\\\",[]);ti(this,\\\"ownersByIsland\\\",new Map);ti(this,\\\"navigationRoots\\\",[]);ti(this,\\\"coverDeclarations\\\",[]);ti(this,\\\"renderedDeclarations\\\",[]);this.filter=e.filter??be}dependencyMap(){if(null!==this.dependencies)return this.dependencies;let e=[];for(let t of this.values())void 0!==t.dependsOn&&e.push(le(t.fieldName,t.dependsOn));return this.dependencies=re(...e),this.dependencies}get islands(){return this.islandRoots}get islandOwners(){return this.ownersByIsland}get covers(){return this.coverDeclarations}get rendered(){return this.renderedDeclarations}get navigationReplayRoots(){return this.navigationRoots}buildFromRoot(e){let t=performance.now();this.clear();let n=0;for(let t of e.querySelectorAll(Or))void 0!==this.add(t)&&(n+=1);return this.islandRoots=function(e){let t=[];for(let n of e.querySelectorAll(lr))se(n)||t.push(n);return t}(e),this.ownersByIsland=new Map(this.islandRoots.map(e=>[e,ge(e)])),this.navigationRoots=[...e.querySelectorAll(Lr)].filter(e=>this.filter(e)&&(e.hasAttribute(Wi)||0===(e.getAttribute(cr)??\\\"\\\").length)),this.coverDeclarations=[...e.querySelectorAll(`[${Nr}]`)].filter(e=>this.filter(e)).map(e=>({paths:ie(e.getAttribute(Nr)),owner:ge(e)})),this.renderedDeclarations=[...e.querySelectorAll(`[${Cr}]`)].filter(e=>this.filter(e)).flatMap(e=>{let t=function(e){if((e.getAttribute(Wi)??\\\"\\\").length>0)return\\\"fragment\\\";let t=e.getAttribute(Rr);return null!==t?\\\"route\\\"===t?\\\"route\\\":void 0:e.hasAttribute(cr)&&null!==e.closest(\\\"head\\\")?\\\"route\\\":void 0}(e);return void 0===t?[]:[{strategy:t,paths:ie(e.getAttribute(Cr)),owner:ge(e)}]}),{elementCount:n,fieldCount:this.entriesByField.size,durationMs:performance.now()-t}}add(e){let t=this.filter(e)?this.resolveBinding(e):void 0,n=this.entryByElement.get(e);if(this.dependencies=null,void 0!==t)return void 0!==n&&this.replaceEntry(n,t)?(this.entryByElement.set(e,t),t):(void 0!==n&&this.removeEntry(e,n),this.append(t),this.entryByElement.set(e,t),t);void 0!==n&&this.removeEntry(e,n)}remove(e){let t=this.entryByElement.get(e);return!!t&&(this.dependencies=null,this.removeEntry(e,t))}get(e){return this.entriesByField.get(e)}getByElement(e){return this.entryByElement.get(e)}get fieldCount(){return this.entriesByField.size}get elementCount(){return this.count}entries(){return this.entriesByField.entries()}*values(){for(let e of this.entriesByField.values())yield*e}has(e){return this.entryByElement.has(e)}clear(){this.entriesByField.clear(),this.entryByElement=new WeakMap,this.count=0,this.dependencies=null,this.islandRoots=[],this.ownersByIsland=new Map,this.navigationRoots=[],this.coverDeclarations=[],this.renderedDeclarations=[]}replaceEntry(e,t){if(e.fieldName!==t.fieldName)return!1;let n=this.entriesByField.get(e.fieldName),i=void 0===n?-1:n.indexOf(e);return!(void 0===n||i<0||(n[i]=t,0))}removeEntry(e,t){this.entryByElement.delete(e);let n=this.entriesByField.get(t.fieldName),i=void 0===n?-1:n.indexOf(t);return!(void 0===n||i<0||(n.splice(i,1),0===n.length&&this.entriesByField.delete(t.fieldName),this.count-=1,0))}append(e){let t=this.entriesByField.get(e.fieldName);t?t.push(e):this.entriesByField.set(e.fieldName,[e]),this.count+=1}resolveBinding(e){let t=e.getAttribute(cr);if(null===t||0===t.length)return;let n=e.getAttribute(hr),i=e.getAttribute(fr),r=e.getAttribute(pr),l=e.getAttribute(gr),o=e.getAttribute(mr),s=e.getAttribute(vr),a=e.getAttribute(yr),u=e.getAttribute(br),d=e.getAttribute(\\\"data-payload-format\\\"),c=ge(e),h=ie(e.getAttribute(Cr)),f=e.getAttribute(Rr),p=e.getAttribute(Fr),g=x(e);return{element:e,fieldName:t,fieldType:ye(e),explicitFieldType:null!==n&&me(n),strategyKind:P(e)??\\\"unknown\\\",...null!==g?{fragmentBoundary:g}:{},...null!==i&&i.length>0?{targetAttribute:i}:{},...null!==r&&r.length>0?{hrefField:r}:{},...null!==l&&l.length>0?{srcField:l}:{},...null!==o&&o.length>0?{altField:o}:{},...null!==s?{arrayTemplate:s}:{},...null!==a?{arraySeparator:a}:{},...null!==u&&u.length>0?{locale:u}:{},...null!==d&&d.length>0?{format:d}:{},...void 0!==c?{owner:c}:{},...h.length>0?{dependsOn:h}:{},...null!==f&&f.length>0?{strategy:f}:{},...e.hasAttribute($r)?{hidesWhenEmpty:!0}:{},...null!==p?{guessed:p}:{}}}},Ir=64,jr=1e4,Wr=1e3,Dr=64,Br=8192,_r=1048576,zr=1e4,Vr=20,qr=new Set([\\\"__proto__\\\",\\\"constructor\\\",\\\"prototype\\\"]),Hr=class{constructor(e){ti(this,\\\"serverURL\\\");ti(this,\\\"apiRoute\\\");ti(this,\\\"depth\\\");ti(this,\\\"fetchFn\\\");ti(this,\\\"log\\\");ti(this,\\\"inflight\\\",null);ti(this,\\\"attempt\\\",0);ti(this,\\\"destroyDepth\\\",0);this.serverURL=function(e){let t=e.length;for(;e.endsWith(\\\"/\\\",t);)t-=1;return e.slice(0,t)}(e.serverURL);let i=e.apiRoute??\\\"/api\\\";this.apiRoute=i.startsWith(\\\"/\\\")?i:`/${i}`,this.depth=e.depth??1,this.fetchFn=e.fetchFn,this.log=t(e.log??n)}canMerge(e){try{let t=e.schema;return void 0!==t?(Ne(e.data,t,this.serverURL,this.apiRoute,this.depth,e.locale),!0):null!==this.endpointOf(e)}catch{return!1}}endpointOf(e){try{let t=e.globalSlug;if(t)return Le(t)?{path:`globals/${encodeURIComponent(t)}`,field:\\\"globalType\\\",value:t}:null;let n=e.collectionSlug??\\\"\\\",i=e.data.id;return Le(n)&&xe(i)?{path:`${encodeURIComponent(n)}/${encodeURIComponent(String(i))}`,field:\\\"id\\\",value:String(i)}:null}catch{return null}}async merge(e){if(this.destroyDepth>0)return{status:\\\"superseded\\\"};let t=this.attempt+=1,n=this.inflight;this.inflight=null;let i=null,r=!1,l=()=>this.attempt!==t;try{if(n?.abort(),l())return{status:\\\"superseded\\\"};let t=e.schema;if(r=void 0!==t,void 0!==t){let n=Ne(e.data,t,this.serverURL,this.apiRoute,this.depth,e.locale);if(l())return{status:\\\"superseded\\\"};if(0===n.requests.length)return{status:\\\"merged\\\",doc:n.doc};let r=this.fetchFn??(\\\"function\\\"==typeof fetch?fetch:void 0);if(l())return{status:\\\"superseded\\\"};if(void 0===r)return{status:\\\"unavailable\\\"};i=new AbortController,this.inflight=i;for(let e of n.requests){let t=await r(e.url,{method:\\\"GET\\\",credentials:\\\"include\\\",redirect:\\\"error\\\",signal:i.signal});if(l())return{status:\\\"superseded\\\"};let n=t.ok;if(l())return{status:\\\"superseded\\\"};if(!n){let e=t.status;return l()?{status:\\\"superseded\\\"}:(i.abort(),l()?{status:\\\"superseded\\\"}:(this.log(\\\"merge HTTP\\\",e),l()?{status:\\\"superseded\\\"}:{status:\\\"unavailable\\\"}))}let o=await Me(t,i.signal,()=>!l());if(l())return{status:\\\"superseded\\\"};if(Oe(e,o),l())return{status:\\\"superseded\\\"}}return{status:\\\"merged\\\",doc:n.doc}}let o=this.endpointOf(e);if(l())return{status:\\\"superseded\\\"};if(null===o)return{status:\\\"unavailable\\\"};let s=this.fetchFn??(\\\"function\\\"==typeof fetch?fetch:void 0);if(l())return{status:\\\"superseded\\\"};if(void 0===s)return{status:\\\"unavailable\\\"};let a=JSON.stringify({data:e.data,depth:this.depth,flattenLocales:!1,locale:e.locale});if(l())return{status:\\\"superseded\\\"};i=new AbortController,this.inflight=i;let u=`${this.serverURL}${this.apiRoute}/${o.path}`,d=await s(u,{method:\\\"POST\\\",credentials:\\\"include\\\",headers:{\\\"Content-Type\\\":\\\"application/json\\\",\\\"X-Payload-HTTP-Method-Override\\\":\\\"GET\\\"},body:a,signal:i.signal});if(l())return{status:\\\"superseded\\\"};let c=d.ok;if(l())return{status:\\\"superseded\\\"};if(!c){let e=d.status;return l()?{status:\\\"superseded\\\"}:(this.log(\\\"merge HTTP\\\",e,u),l()?{status:\\\"superseded\\\"}:{status:\\\"unavailable\\\"})}let h=d.json.bind(d);if(l())return{status:\\\"superseded\\\"};let f=await h();if(l())return{status:\\\"superseded\\\"};if(null===f||\\\"object\\\"!=typeof f||Array.isArray(f))return this.log(\\\"merge invalid\\\",u),l()?{status:\\\"superseded\\\"}:{status:\\\"unavailable\\\"};let p=f,g=p[o.field],m=Object.hasOwn(p,o.field)&&(\\\"id\\\"===o.field?!xe(g)||String(g)!==o.value:g!==o.value);return l()?{status:\\\"superseded\\\"}:m?(this.log(\\\"merge invalid\\\",u),l()?{status:\\\"superseded\\\"}:{status:\\\"unavailable\\\"}):{status:\\\"merged\\\",doc:p}}catch(e){return l()||r&&(i?.abort(),l())?{status:\\\"superseded\\\"}:(this.log(\\\"merge exception\\\",r?new Error(\\\"legacy population could not be resolved\\\"):e),l()?{status:\\\"superseded\\\"}:{status:\\\"unavailable\\\"})}finally{this.inflight===i&&(this.inflight=null)}}destroy(){this.attempt+=1;let e=this.inflight;this.inflight=null,this.destroyDepth+=1;try{e?.abort()}finally{this.destroyDepth-=1}}},Gr=\\\"2.1.2\\\",Kr={name:\\\"payload-2\\\",fieldTyping:\\\"schema\\\",populatesRelationships:\\\"admin\\\",documentEvents:!1},Jr={name:\\\"payload-3\\\",fieldTyping:\\\"heuristic\\\",populatesRelationships:\\\"server\\\",documentEvents:!0},Xr={name:\\\"unknown\\\",fieldTyping:\\\"heuristic\\\",populatesRelationships:\\\"server\\\",documentEvents:!1},Qr=\\\"ssr\\\",Zr=1,Yr=class{constructor(e,t={}){ti(this,\\\"callbacks\\\");ti(this,\\\"debounceMs\\\");ti(this,\\\"rootMargin\\\");ti(this,\\\"visible\\\",new Set);ti(this,\\\"mutation\\\",null);ti(this,\\\"intersection\\\",null);ti(this,\\\"debounceTimer\\\",null);ti(this,\\\"generation\\\",0);this.callbacks=e,this.debounceMs=t.mutationDebounceMs??100,this.rootMargin=t.intersectionRootMargin??\\\"200px\\\"}start(e){let t=this.generation;this.stop();let n=t+1;if(this.generation!==n)return;let i=null,r=null;try{i=new MutationObserver(e=>{this.handleMutations(e,n)}),r=new IntersectionObserver(e=>{this.handleIntersection(e,n)},{rootMargin:this.rootMargin,threshold:0}),i.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[...Mr,rr,Qr]})}catch(e){throw i?.disconnect(),r?.disconnect(),e}this.generation===n?(this.mutation=i,this.intersection=r):(i.disconnect(),r.disconnect())}observeElement(e){this.intersection?.observe(e)}unobserveElement(e){this.intersection?.unobserve(e),this.visible.delete(e)}markVisible(e,t){t?this.visible.add(e):this.visible.delete(e)}isVisible(e){return this.visible.has(e)}stop(){this.generation+=1;let e=this.debounceTimer,t=this.mutation,n=this.intersection;this.debounceTimer=null,this.mutation=null,this.intersection=null,this.visible.clear(),null!==e&&clearTimeout(e);try{t?.disconnect()}finally{n?.disconnect()}}handleMutations(e,t){if(!this.isCurrentGeneration(t))return;for(let n of e){let e=Ue(n);if(null!==e&&(this.callbacks.onIslandHydrated?.(e),!this.isCurrentGeneration(t)))return}if(!function(e){for(let t of e){if(\\\"attributes\\\"===t.type&&t.attributeName===rr||\\\"attributes\\\"===t.type&&null!==t.attributeName&&Mr.includes(t.attributeName)&&(t.attributeName===cr||t.attributeName===Tr||t.target.nodeType===Zr&&t.target.hasAttribute(cr)))return!0;for(let e of t.addedNodes)if(Ie(e))return!0;for(let e of t.removedNodes)if(Ie(e))return!0}return!1}(e))return;null!==this.debounceTimer&&clearTimeout(this.debounceTimer);let n=setTimeout(()=>{!this.isCurrentGeneration(t)||this.debounceTimer!==n||(this.debounceTimer=null,this.callbacks.onStructuralChange())},this.debounceMs);this.debounceTimer=n}handleIntersection(e,t){for(let n of e){if(!this.isCurrentGeneration(t))return;let{target:e}=n;if(n.isIntersecting){if(this.visible.has(e))continue;this.visible.add(e),this.callbacks.onVisibilityChange(e,!0)}else this.visible.has(e)&&(this.visible.delete(e),this.callbacks.onVisibilityChange(e,!1))}}isCurrentGeneration(e){return this.generation===e&&null!==this.intersection}},el=class{constructor(e){ri(this,rl);ri(this,tl,[]);ri(this,nl);ri(this,il,!1);li(this,nl,e)}get closed(){return ii(this,il)}own(e){ii(this,il)?oi(this,rl,ll).call(this,e):ii(this,tl).push(e)}close(){if(ii(this,il))return;li(this,il,!0);let e=ii(this,tl).splice(0).reverse();for(let t of e)oi(this,rl,ll).call(this,t)}},tl=new WeakMap,nl=new WeakMap,il=new WeakMap,rl=new WeakSet,ll=function(e){try{e()}catch(e){ii(this,nl).call(this,\\\"runtime cleanup failed:\\\",e)}},ol=\\\"__livePreviewHydration\\\",sl=\\\"[data-payload-field]\\\",al=\\\"__vue_app__\\\",ul=\\\"__livePreviewVueHydration\\\",dl=\\\"app:suspense:resolve\\\",cl={react:(e,t)=>function(e,t=5e3){We();let n=je();if(void 0===n)return null;if(void 0===n.onCommit){let e=e=>{!n.committed&&function(e){let t=e;return null!=t&&function(e){let t=e;return 9===t?.nodeType||null!=t?.querySelector?.(sl)}(t.containerInfo)&&!function(e){let t=[];for(null!==e.current&&void 0!==e.current&&t.push(e.current);t.length>0;){let e=t.pop();if(void 0===e)continue;let n=e.memoizedState;if((13===e.tag||31===e.tag)&&\\\"object\\\"==typeof n&&null!==n&&\\\"dehydrated\\\"in n&&\\\"object\\\"==typeof n.dehydrated&&null!==n.dehydrated&&\\\"nodeType\\\"in n.dehydrated&&8===n.dehydrated.nodeType)return!0;null!==e.sibling&&void 0!==e.sibling&&t.push(e.sibling),null!==e.child&&void 0!==e.child&&t.push(e.child)}return!1}(t)}(e)&&De(n)};n.onCommit=e;for(let t of n.commits.splice(0))e(t)}return _e(n,e,t)}(t),vue:function(e,t,n=5e3){qe();let i=ze();return void 0===i?null:(!i.committed&&function(e){for(let t=e.querySelector(sl);null!==t;t=t.parentElement)if(void 0!==Ve(t))return!0;return!1}(e)&&De(i),_e(i,t,n))},sveltekit:function(e,t,n=5e3){let i=e.ownerDocument??e,r=()=>null!==i.querySelector(\\\"#svelte-announcer\\\");if(r()||!Object.keys(window).some(e=>e.startsWith(\\\"__sveltekit_\\\")))return null;let l={committed:!1,waiters:[]},o=new MutationObserver(()=>{!l.committed&&r()&&De(l)});o.observe(i,{childList:!0,subtree:!0});let s=_e(l,e=>{o.disconnect(),t(e)},n);return()=>{o.disconnect(),s?.()}}},hl={react:\\\"React commit\\\",vue:\\\"Vue mount\\\",sveltekit:\\\"SvelteKit mount\\\"},fl=class{constructor(e){ti(this,\\\"timeoutMs\\\");ti(this,\\\"onTimeout\\\");ti(this,\\\"handle\\\",null);ti(this,\\\"lastKick\\\",null);this.timeoutMs=e.timeoutMs??0,this.onTimeout=e.onTimeout}kick(){this.lastKick=Date.now(),!(this.timeoutMs<=0)&&(this.stop(),this.arm(this.timeoutMs))}resume(){if(this.timeoutMs<=0||null!==this.handle||null===this.lastKick)return!1;let e=Math.max(0,Date.now()-this.lastKick),t=this.timeoutMs-e;return t<=0?(this.lastKick=null,this.onTimeout(),!0):(this.arm(Math.min(t,this.timeoutMs)),!1)}arm(e){let t=setTimeout(()=>{this.handle===t&&(this.handle=null,this.lastKick=null,this.onTimeout())},e);this.handle=t}stop(){null!==this.handle&&(clearTimeout(this.handle),this.handle=null)}get lastKickAt(){return this.lastKick??0}get pending(){return null!==this.handle}},pl=class{constructor(){ti(this,\\\"current\\\",\\\"disconnected\\\")}get status(){return this.current}markConnected(){return this.transition(\\\"connected\\\")}markDisconnected(){return this.transition(\\\"disconnected\\\")}transition(e){return this.current!==e&&(this.current=e,!0)}},gl=\\\"data-payload-no-bind\\\",ml=13,vl=new Set([\\\"true\\\",\\\"false\\\",\\\"yes\\\",\\\"no\\\",\\\"on\\\",\\\"off\\\"]),yl=/^[\\\\d\\\\s.,:+/-]+$/u,bl=/^[a-z][a-z0-9_-]*$/u,wl=/^[a-z]{2,3}(?:[-_][A-Za-z0-9]{2,8})*$/u,Sl=new Set([\\\"SCRIPT\\\",\\\"STYLE\\\",\\\"TEMPLATE\\\",\\\"TITLE\\\",\\\"NOSCRIPT\\\",\\\"TEXTAREA\\\",\\\"SELECT\\\",\\\"OPTION\\\",\\\"INPUT\\\",\\\"IFRAME\\\"]),Al=\\\"http://www.w3.org/1999/xhtml\\\",kl=new Set([\\\"__proto__\\\",\\\"prototype\\\",\\\"constructor\\\"]),Tl=class{constructor(e,t,n){ti(this,\\\"deps\\\",e);ti(this,\\\"state\\\",t);ti(this,\\\"host\\\",n);ti(this,\\\"awaitingHydration\\\",new WeakSet);ti(this,\\\"delivered\\\",new WeakMap);ti(this,\\\"confirmations\\\",new WeakMap)}reapplyBindings(e){let t=this.currentTransaction();void 0!==t?.renderData&&this.host.schedule(t,t.renderData,e)}reapplyIslands(e,t=!1){let n=t?e.filter(e=>this.awaitingHydration.delete(e)):e,i=this.state.activeUpdate,r=t&&null!==i&&this.state.isCurrent(i)?i:this.currentTransaction();void 0!==r?.renderData&&this.dispatchIslands(r,r.renderData,n)}dispatchIslands(e,t,n){let i=ft(this.deps,this.state,e,t.fields),r=()=>!e.cancelled&&this.state.isCurrent(e);if(!r())return;let l=this.delivered.get(t);void 0===l&&(l=new WeakSet,this.delivered.set(t,l));for(let o of n){let n=ge(o);if(!r())return;if(!1!==i&&!W(n,i)){this.awaitingHydration.delete(o);continue}let s=this.confirmation(o,e);if(ue(o))this.awaitingHydration.add(o);else{if(this.awaitingHydration.delete(o),l.has(o))continue;l.add(o),pt(e,t,[o],r,s)}}}hasLateRouteBinding(e,t,n,i){for(let i of e){if((i.getAttribute(cr)??\\\"\\\").length>0||\\\"route\\\"!==i.getAttribute(Rr)||!1!==t&&!W(ge(i),t))continue;let e=ie(i.getAttribute(Cr));if(0===e.length||e.some(e=>n.touched.has(e)))return!0}for(let[r,l]of this.deps.cache.entries())for(let o of l){if(!e.has(o.element)||!1!==t&&!W(o.owner,t)||\\\"route\\\"!==(o.strategyKind??P(o.element)??\\\"unknown\\\"))continue;let l=ct(i.fields,o,r,n.locale);if(!this.state.isCurrent(n))return!1;if(void 0!==l)return!0}return!1}fieldsForElements(e,t){let n=new Set(t);for(let[t,i]of this.deps.cache.entries())i.some(t=>e.has(t.element))&&n.add(t);return n}unrunFragmentPlan(e,t,n){if(null===t)return null;let i=t.boundaries.filter(t=>!e.fragmentBoundariesRun.has(t)&&(void 0===n||[...n].some(e=>e===t||t.contains(e))));if(0===i.length)return null;let r=new Set(i);return{...t,boundaries:i,covers:e=>void 0!==e.fragmentBoundary&&r.has(e.fragmentBoundary)}}confirmation(e,t){let n=this.confirmations.get(e);if(n?.transaction===t)return n.displayed;let i=this.state.display.handIsland(t);return this.confirmations.set(e,{transaction:t,displayed:i}),i}currentTransaction(){let e=this.state.activeUpdate;return this.state.navigationBindingReplay&&null!==e&&this.state.isCurrent(e)?e:null}},Cl=\\\"payload-live-preview\\\",Rl=Symbol.for(\\\"payload-live-preview.trusted-types\\\"),$l=new Set([\\\"open\\\",\\\"value\\\",\\\"checked\\\",\\\"selected\\\"]),Fl=\\\"__payloadLivePreviewDeprecationsWarned\\\",Nl=new Set,Ml=\\\"data-payload-\\\",Ol=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\\\"]),El=new Set([\\\"input\\\",\\\"button\\\",\\\"textarea\\\",\\\"select\\\",\\\"option\\\",\\\"label\\\"]),Ll=new Set([\\\"script\\\",\\\"style\\\",\\\"iframe\\\",\\\"object\\\",\\\"embed\\\",\\\"link\\\",\\\"meta\\\",\\\"base\\\",\\\"form\\\",\\\"input\\\",\\\"button\\\",\\\"select\\\",\\\"textarea\\\",\\\"svg\\\",\\\"math\\\",\\\"template\\\",\\\"frame\\\",\\\"frameset\\\",\\\"noframes\\\",\\\"noscript\\\"]),xl=new Set([\\\"id\\\",\\\"class\\\",\\\"lang\\\",\\\"dir\\\",\\\"title\\\",\\\"role\\\",\\\"tabindex\\\"]),Pl=\\\"aria-\\\",Ul=\\\"data-\\\",Il=\\\"data-payload-\\\",jl={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\\\"])},Wl=new Set([\\\"href\\\",\\\"src\\\",\\\"cite\\\",\\\"poster\\\"]),Dl=6,Bl=1,_l=8,zl=(Error,new Set([\\\"id\\\",\\\"name\\\",\\\"data-payload-key\\\",\\\"data-payload-morph\\\",\\\"data-payload-nested-key\\\",\\\"data-payload-nested-template\\\"])),Vl=\\\"strict\\\",ql=(Object.freeze({allowedTags:Ol,removeCompletely:Ll,globalAttributes:xl,attributesByTag:jl,urlAttributes:Wl}),Object.freeze({\\\"&\\\":\\\"&\\\",\\\"<\\\":\\\"<\\\",\\\">\\\":\\\">\\\",'\\\"':\\\""\\\",\\\"'\\\":\\\"'\\\",\\\"/\\\":\\\"/\\\",\\\"`\\\":\\\"`\\\",\\\"=\\\":\\\"=\\\"})),Hl=/[&<>\\\"'/`=]/g,Gl=Object.freeze({\\\"&\\\":\\\"&\\\",\\\"<\\\":\\\"<\\\",\\\">\\\":\\\">\\\",'\\\"':\\\""\\\",\\\"'\\\":\\\"'\\\"}),Kl=/[&<>\\\"']/g,Jl=/\\\\{\\\\{([\\\\s\\\\S]*?)\\\\}\\\\}/g,Xl=\\\"data-payload-\\\",Ql=[\\\"input\\\",\\\"textarea\\\",\\\"select\\\",\\\"option\\\",\\\"button\\\",\\\"label\\\",\\\"details\\\",\\\"summary\\\",\\\"dialog\\\",\\\"video\\\",\\\"audio\\\",\\\"progress\\\",\\\"meter\\\"],Zl=[\\\"type\\\",\\\"name\\\",\\\"placeholder\\\",\\\"open\\\",\\\"disabled\\\",\\\"readonly\\\",\\\"required\\\",\\\"checked\\\",\\\"selected\\\",\\\"value\\\",\\\"min\\\",\\\"max\\\",\\\"step\\\",\\\"rows\\\",\\\"cols\\\",\\\"for\\\",\\\"controls\\\",\\\"muted\\\",\\\"loop\\\",\\\"poster\\\",\\\"src\\\"],Yl=/<([a-z][a-z0-9]*(?:-[a-z0-9]+)+)\\\\b/gi,eo=64,to=new Map,no=\\\"data-payload-key\\\",io=\\\"data-payload-nested-key\\\",ro=\\\"data-payload-nested-template\\\",lo=class{constructor(e,t,n){ti(this,\\\"deps\\\",e);ti(this,\\\"state\\\",t);ti(this,\\\"host\\\",n)}planFragments(e,t){let{deps:n,state:i}=this,r=n.strategies.fragment;if(void 0===r)return null;let l=new Set(r.plan(n.root,e));for(let e of i.fragmentsOwed)n.root.contains(e)?l.add(e):i.fragmentsOwed.delete(e);return ln(r,[...l].filter(e=>on(e,t)),t)}escalateUnfaithful(e,t,n,i){if(e.routeRefreshed){this.kept(e,n);return}let{fragment:r,route:l}=this.deps.strategies,o=void 0===r?void 0:function(e){let t=[];for(let n of e){let e=n.fragmentBoundary;if(void 0===e)return;t.includes(e)||t.push(e)}return t}(n),s=void 0===o||o.every(e=>on(e,i))?o:void 0;void 0===r||void 0===s?void 0!==l?(this.state.escalatedCount+=n.length,this.refreshRoute(e,t,l)):(rn(this.deps,this.state,n.length),this.kept(e,n)):(this.state.escalatedCount+=n.length,e.pendingFragments+=s.length,this.runFragments(e,t,ln(r,s,i)))}kept(e,t){for(let n of t)this.state.display.shortfall(e,{kind:\\\"unfaithful\\\",field:n.fieldName})}hasUnboundChange(e,t){let{deps:n,state:i}=this;if(e.baseline||e.routeRefreshed)return!1;let r=function(e,t,n,i,r,l){let o=q(e,i,l),s=G(e,n,i,o),a=[];for(let e of t){if(Vi.has(e))continue;let t=s(e);if(\\\"none\\\"===t&&a.push(e),\\\"below\\\"!==t||void 0===r)continue;let i=H(e,n),{previous:l,next:u}=r;for(let{path:t}of V(i,l[e],u[e],o))a.push(t)}return a}(n.cache,e.touched,e.locale,t,function(e,t,n){return\\\"declared\\\"===e&&void 0!==t&&void 0!==n?{previous:t,next:n}:void 0}(n.subfieldCoverage,i.changes.previousFields,e.renderData?.fields),n.strategies),o=0;for(let e of r)l(i,e)&&(o+=1);let[s]=r;if(void 0===s)return!1;if(\\\"escalate\\\"!==n.onUnfaithfulPatch||void 0===n.strategies.route){\\\"escalate\\\"===n.onUnfaithfulPatch&&rn(n,i,r.length);for(let t of r)i.display.shortfall(e,{kind:\\\"unbound\\\",field:t});return!1}return n.log(\\\"route\\\",\\\"LP0807\\\",`field \\\"${s}\\\" has no binding; refreshing the route`),i.escalatedCount+=o,!0}plansRoute(e,t,n){let i=e=>!1===n||W(e,n);if(e.plan(this.deps.root,t,{inScope:e=>i(ge(e))}))return!0;for(let[e,n]of this.deps.cache.entries())if(t.has(e)&&n.some(e=>\\\"route\\\"===e.strategyKind&&i(e.owner)))return!0;return!1}async runFragments(e,t,n){let{deps:i,state:r}=this,l=new AbortController,o=new Set(n.boundaries);for(let e of o)r.fragmentsOwed.delete(e);r.fragmentControllers.set(l,o);let s=t=>{o.delete(t)&&(e.pendingFragments-=1)},a=()=>r.isCurrent(e)&&!l.signal.aborted,u=e=>function(e,t,n){if(t.isConnected)return t;let i,r=t.getAttribute(Wi),l=t.getAttribute(Di);for(let t of e.querySelectorAll(`[${Wi}]`))if(t.getAttribute(Wi)===r&&t.getAttribute(Di)===l&&n(t)){if(void 0!==i)return;i=t}return i}(i.root,e,e=>on(e,n.ownerKeys)),{emitter:d}=i,{message:c}=e,h=e.revision.revision,f=e.receivedAt,p={root:i.root,revision:h,receivedAt:f,fields:t.fields,locale:e.locale,collectionSlug:\\\"string\\\"==typeof c.collectionSlug?c.collectionSlug:void 0,globalSlug:\\\"string\\\"==typeof c.globalSlug?c.globalSlug:void 0,signal:l.signal,isCurrent:a,log:(e,t)=>{i.log(\\\"fragment\\\",e,t)},morph:(e,t)=>{let n=a()?u(e):void 0;void 0!==n&&function(e,t,n){let i=e.ownerDocument.createElement(\\\"template\\\");i.innerHTML=yt(t);let r=e.cloneNode(!1);r.append(i.content);let l=fe(e);wt(e,r,{keyAttributes:[no],boundary:oe,retainBoundary:he}),function(e){for(let t of e)t.isConnected||dr.has(t)||(dr.add(t),t.dispatchEvent(new CustomEvent(\\\"astro:unmount\\\")))}(l);let o=new Set(l);for(let t of fe(e)){let e=o.has(t)?void 0:pe(t);void 0!==e&&n(t,e)}}(n,t,(e,t)=>{!function(e,t,n,i){if(t.warnedIslandStart)return;t.warnedIslandStart=!0;let r=\\\"element\\\"===i?\\\"<astro-island>\\\":`client:${n.getAttribute(\\\"client\\\")??\\\"\\\"}`;e.warn(`[live-preview] LP0809: a fragment island cannot start: this page never loaded ${r}; render one on the page`)}(this.deps,this.state,e,t)})},patch:i=>{let r=u(i);void 0!==r&&(r!==i&&this.host.rebuildCache(),this.patchFallback(e,t,r,n.ownerKeys,a))},rendered:(e,t,n)=>{s(e);let i=u(e)??e;d.emitWhile(\\\"fragmentRender\\\",{element:i,id:t,key:n,status:\\\"rendered\\\",revision:h,receivedAt:f},a)},failed:(t,n,l,o,c)=>{s(t);let p=u(t)??t;r.display.shortfall(e,{kind:\\\"fragment\\\",id:n,key:l,code:o});let g=`fragment \\\"${n}\\\" fell back to patch: ${c}`;i.log(\\\"fragment\\\",o,g),d.emitWhile(\\\"error\\\",{error:new Error(g),context:\\\"fragment\\\",code:o},a),d.emitWhile(\\\"fragmentRender\\\",{element:p,id:n,key:l,status:\\\"failed\\\",code:o,revision:h,receivedAt:f},a)}},g={rendered:0,failed:0,superseded:0};try{g=await n.strategy.render(p,n.boundaries)}catch(t){if(i.log(\\\"fragment\\\",\\\"LP0801\\\",t),a()){for(let t of n.boundaries)p.patch(t),r.display.shortfall(e,ne(t));g={rendered:0,failed:n.boundaries.length,superseded:0}}}r.fragmentStats.rendered+=g.rendered,r.fragmentStats.failed+=g.failed,r.fragmentStats.superseded+=g.superseded,r.fragmentControllers.delete(l);for(let e of o)s(e);a()&&(g.rendered>0&&this.host.restoreGuesses(e,t),0===e.pendingFragments&&0===i.scheduler.pendingCount&&r.complete(e),this.host.revealPending(e),a()&&(0===g.rendered||0===d.listenerCount(\\\"afterUpdate\\\")||d.emitWhile(\\\"afterUpdate\\\",{data:t,updatedCount:g.rendered,durationMs:Date.now()-f,revision:h,receivedAt:f,source:\\\"fragment\\\"},a)))}async refreshRoute(e,t,n){let{deps:i,state:r}=this;e.routeRefreshed?(r.routeStats.loopStopped+=1,i.log(\\\"route\\\",\\\"LP0805\\\",`revision ${String(e.revision.revision)} asked for a second refresh`)):(e.routeRefreshed=!0,await this.runRoute(e,t,n,!1).catch(e=>{this.routeFailed(e)}))}refreshAfterSave(){let{deps:e,state:t}=this,{route:n}=e.strategies,i=t.activeUpdate;!t.routeAwaitsSave||void 0===n||void 0===i?.renderData||(e.log(\\\"route\\\",\\\"document saved; refreshing the route\\\"),this.runRoute(i,i.renderData,n,!0).catch(e=>{this.routeFailed(e)}))}routeFailed(e){this.deps.log(\\\"route refresh failed:\\\",e)}armRouteRetry(e,t,n,i,r){let{state:l}=this;null!==l.routeRetry&&clearTimeout(l.routeRetry),l.routeRetry=setTimeout(()=>{l.routeRetry=null,l.isCurrent(e)&&this.runRoute(e,t,n,r).catch(e=>{this.routeFailed(e)})},i)}async runRoute(e,t,n,i){let{deps:r,state:l}=this,o=l.routeStats,s=new AbortController;l.routeController?.abort(),l.routeController=s;let a,u=()=>!s.signal.aborted;try{a=await n.refresh({revision:e.revision.revision,receivedAt:e.receivedAt,signal:s.signal,isCurrent:u,log:(e,t)=>{r.log(\\\"route\\\",e,t)},retryAfter:r=>{this.armRouteRetry(e,t,n,r,i)}})}catch(e){r.log(\\\"route\\\",\\\"LP0801\\\",e),a=\\\"failed\\\"}if(!u())return;l.routeController=null;let d=l.activeUpdate;if(null===d)return;let c=d.renderData,h=()=>l.isCurrent(d);if(\\\"partial\\\"===a?l.display.shortfall(d,{kind:\\\"route-saved\\\"}):(\\\"failed\\\"===a||\\\"superseded\\\"===a||\\\"refused\\\"===a&&null===l.routeRetry)&&l.display.shortfall(d,{kind:\\\"route-failed\\\",outcome:a}),\\\"refreshed\\\"!==a&&\\\"partial\\\"!==a)\\\"failed\\\"===a?o.failed+=1:\\\"refused\\\"===a&&(o.refused+=1),void 0!==c&&this.host.reapply(d,c);else{if(o.refreshes+=1,\\\"partial\\\"===a&&(o.partial+=1),l.routeAwaitsSave=\\\"partial\\\"===a&&!i,l.lastAppliedIdentity=new WeakMap,void 0!==c&&this.host.restoreGuesses(d,c),this.host.rebuildCache(),void 0===c||!h())return;this.host.reapply(d,c),r.emitter.listenerCount(\\\"afterUpdate\\\")>0&&r.emitter.emitWhile(\\\"afterUpdate\\\",{data:c,updatedCount:r.cache.elementCount,durationMs:Date.now()-d.receivedAt,revision:d.revision.revision,receivedAt:d.receivedAt,source:\\\"route\\\"},h)}}warnFragmentFallback(e){!function(e,t,n){t.warnedFragmentFallback||(t.warnedFragmentFallback=!0,e.warn(`[live-preview] LP0806: \\\"${n.fieldName}\\\" asks for the fragment strategy but no handler is configured; patching instead`))}(this.deps,this.state,e)}warnUnsupportedStrategy(e){!function(e,t,n){t.warnedStrategy.has(n.element)||(t.warnedStrategy.add(n.element),e.warn(`[live-preview] LP0407: \\\"${n.fieldName}\\\" asks for strategy \\\"${String(n.strategy)}\\\"; only patch, fragment and route exist`))}(this.deps,this.state,e)}patchFallback(e,t,n,i,r){if(r())for(let[l,o]of this.deps.cache.entries())for(let s of o){if(s.fragmentBoundary!==n||!1!==i&&!W(s.owner,i))continue;let o=ct(t.fields,s,l,e.locale);void 0===o||!r()||this.deps.scheduler.schedule({target:s,value:this.host.transform(s,o,t.fields,r),allFields:t.fields,revision:e.revision,data:t})}}},oo=new Set,so={kind:\\\"merge\\\"},ao=class{constructor(e,t,n){ti(this,\\\"deps\\\",e);ti(this,\\\"state\\\",t);ti(this,\\\"strategies\\\");ti(this,\\\"navigationReplay\\\");t.changes.keepValues=\\\"declared\\\"===e.subfieldCoverage,t.display.host=function(e,t){return{outstanding:n=>!n.completed||n.pendingFragments>0||null!==t.routeController||null!==t.routeRetry||e.scheduler.pendingCount>0,report:t=>{\\\"partial\\\"===t.state&&e.a11y?.announcePartial(),e.emitter.emit(\\\"revisionDisplay\\\",t)},failed:t=>{e.log(\\\"revision display failed:\\\",t)}}}(e,t),this.strategies=new lo(e,t,{reapply:(e,t)=>{this.scheduleAllFields(e,t)},transform:(t,n,i,r)=>sn(e,t,n,i,r),rebuildCache:n,restoreGuesses:(e,t)=>{this.restoreGuesses(e,t)},revealPending:e=>{this.revealPending(e)}}),this.navigationReplay=new Tl(e,t,{schedule:(e,t,n)=>{this.scheduleAllFields(e,t,n)}})}handleUpdate(e,t,n){let{deps:i,state:r}=this;i.heartbeat.kick(),r.protocol.observe(function(e){let t=[];return Array.isArray(e.fieldSchemaJSON)&&t.push(\\\"schema-json\\\"),\\\"string\\\"==typeof e.locale&&t.push(\\\"locale\\\"),\\\"string\\\"==typeof e.previewToken&&t.push(\\\"preview-token\\\"),\\\"object\\\"==typeof e.externallyUpdatedRelationship&&null!==e.externallyUpdatedRelationship&&t.push(\\\"relationship-events\\\"),t}(e),i.log);let l=e.data;void 0!==l?void 0!==n&&this.acceptDataUpdate(e,l,t,n,!0):void 0!==e.protocolVersion&&r.protocol.applyVersion(e.protocolVersion,i.log)}handleReplay(e,t,n){let i=e.data;void 0!==i&&this.acceptDataUpdate(e,i,t,n,!1)}reapplyNavigationBindings(e){this.navigationReplay.reapplyBindings(e)}reapplyNavigationIslands(e,t=!1){this.navigationReplay.reapplyIslands(e,t)}acceptDataUpdate(e,t,n,i,r){let{deps:l,state:o}=this,s=r?o.relationships.inspect(e):null,a=\\\"string\\\"==typeof e.locale?e.locale:o.locale,u=o.schema,d=o.schemaIndex;Array.isArray(e.fieldSchemaJSON)&&(u=e.fieldSchemaJSON,d=function(e,t=\\\"\\\"){let n=new Map;return A(e,t,n,!1),A(e,t,n,!0),n}(e.fieldSchemaJSON));let c=o.activeUpdate;if(!o.isRunning()||null!==c&&c.revision.revision>i.revision)return;let h=null===s?null:o.relationships.commit(s),f=c,p={revision:i,message:e,rawData:t,locale:a,schema:u,schemaIndex:d,receivedAt:Date.now(),forceRender:null!==h||Y(f),countsAsUpdate:r,renderData:void 0,fragmentBoundariesRun:new WeakSet,touched:new Set,baseline:!1,invalidated:new Set,revealTarget:void 0,revealIdentities:[],pendingFragments:0,routeRefreshed:!1,cancelled:!1,completed:!1};o.locale=a,o.schema=u,o.schemaIndex=d,null!==f&&!f.completed&&f.countsAsUpdate&&(o.supersededCount+=1),o.activeUpdate=p,r&&(o.updateCount+=1),o.display.begin(p,i.revision),o.isCurrent(p)&&(l.scheduler.acceptRevision(i),o.isCurrent(p)&&(o.supersedeStrategies(),o.isCurrent(p)&&(null!==h&&(l.emitter.emitWhile(\\\"relationshipUpdate\\\",{detail:h,timestamp:Date.now()},()=>o.isCurrent(p)),!o.isCurrent(p))||r&&void 0!==e.protocolVersion&&(o.protocol.applyVersion(e.protocolVersion,l.log),!o.isCurrent(p))||r&&l.connection.markConnected()&&(l.a11y?.announceConnected(),l.emitter.emit(\\\"connect\\\",{origin:n,timestamp:Date.now()}),!o.isCurrent(p)||(l.log(\\\"connection\\\",\\\"disconnected\\\",\\\"\\\\u2192\\\",\\\"connected\\\"),!o.isCurrent(p)))||this.processUpdate(p).catch(e=>{l.log(\\\"update failed:\\\",e)}))))}async processUpdate(e){let{deps:t,state:n}=this,i=await this.resolveIncomingFields(e);if(null===i||!n.isCurrent(e))return;let r=this.dataFor(e,i);t.emitter.listenerCount(\\\"beforeUpdate\\\")>0&&(!await t.emitter.emitWhile(\\\"beforeUpdate\\\",{data:r,revision:e.revision.revision,receivedAt:e.receivedAt,source:\\\"patch\\\",cancel:()=>{e.cancelled=!0,t.scheduler.cancelRevision(e.revision)}},()=>!e.cancelled&&n.isCurrent(e))||e.cancelled||!n.isCurrent(e))||this.applyFields(e,r,!1)}dataFor(e,t){let{message:n}=e;return{fields:t,...void 0!==e.schema?{schema:e.schema}:{},...\\\"string\\\"==typeof n.globalSlug?{globalSlug:n.globalSlug}:{},...\\\"string\\\"==typeof n.collectionSlug?{collectionSlug:n.collectionSlug}:{},...void 0!==e.locale?{locale:e.locale}:{}}}applyFields(e,t,n){let{deps:i,state:r}=this;if(!r.isCurrent(e))return;if(r.changes.isBaseline&&!n&&\\\"off\\\"!==i.autoBind){{let n=ft(i,r,e,t.fields);!function(e,t,n,i,r,l){if(!l())return 0;let o=performance.now(),s=ot(e.root),a=Ze(n,i);if(!l())return 0;let u=null===s?[]:lt(s,a);if(!l())return 0;let d=at(e,u,r,\\\"on the first message\\\",l);if(!l())return 0;let c=function(e,t){let n=new Set;for(let{fieldName:e,stamps:i}of t){n.add(e);for(let e of[pr,mr]){let t=i[e];void 0!==t&&n.add(t)}}let i=new Map;for(let[t,r]of e)null!==r&&n.has(r.field)&&i.set(t,r);return{fields:n,values:i}}(a,d),h=performance.now()-o;l()&&(t.autoBindGuesses=c,t.autoBindSearchMs=h,d.length)}(i,r,t.fields,e.locale,n,()=>r.isCurrent(e))}if(!r.isCurrent(e))return}let l=re(i.dependencies,i.cache.dependencyMap());if(!r.isCurrent(e))return;let o=r.changes.diff(t.fields,l,()=>r.isCurrent(e));if(null===o)return;let s=!n&&r.navigationReplayPending;s&&(r.navigationReplayPending=!1,r.navigationBindingReplay=!0),e.baseline=o.baseline&&!s,e.invalidated=n?oo:o.invalidated,e.touched=n?oo:new Set([...o.changed,...o.invalidated]),e.renderData=t,this.scheduleAllFields(e,t)}async resolveIncomingFields(e){let{deps:t,state:n}=this,i=e.rawData;if(null===t.merger)return i;let r=n.merges.decide(t,e);if(!r.merge)return r.fields;let{message:l}=e,o=n.merges.request(t.merger,t.mergeWindowMs,{collectionSlug:l.collectionSlug,globalSlug:l.globalSlug,data:i,...void 0===e.schema?{}:{schema:e.schema},locale:e.locale});if(!o.leading)return this.applyMerged(e,o.result).catch(e=>{t.log(\\\"update failed:\\\",e)}),r.fields;let s=await o.result;return n.isCurrent(e)?\\\"merged\\\"===s.status?(n.merges.recordMerged(s.doc,e.locale),s.doc):\\\"superseded\\\"===s.status?null:(n.display.shortfall(e,so),r.fields):null}async applyMerged(e,t){let{state:n}=this,i=await t;\\\"unavailable\\\"===i.status&&n.display.shortfall(e,so),\\\"merged\\\"===i.status&&n.isCurrent(e)&&(n.merges.recordMerged(i.doc,e.locale),this.applyFields(e,this.dataFor(e,i.doc),!0))}scheduleAllFields(e,t,n){let{deps:i,state:r}=this;if(!r.isCurrent(e))return;let l=void 0!==n,o=()=>r.isCurrent(e),s=ft(i,r,e,t.fields);if(!o())return;let{touched:a}=e,u=i.strategies.route;if(l&&void 0!==u&&!e.routeRefreshed&&this.navigationReplay.hasLateRouteBinding(n,s,e,t)){o()&&this.strategies.refreshRoute(e,t,u);return}let d=!l&&this.strategies.hasUnboundChange(e,s),c=r.routeRefreshOwed;if(!l&&void 0!==u&&!e.routeRefreshed&&(d||c||this.strategies.plansRoute(u,a,s))&&o()){r.routeRefreshOwed=!1,this.strategies.refreshRoute(e,t,u);return}let h=l?this.navigationReplay.fieldsForElements(n,a):a,f=this.navigationReplay.unrunFragmentPlan(e,this.strategies.planFragments(h,s),n);if(!o())return;let p=i.skipUnchanged,g=0;for(let[a,u]of i.cache.entries()){if(!o())return;for(let d of u){if(void 0!==n&&!n.has(d.element)||!1!==s&&!W(d.owner,s))continue;if(!0===f?.covers(d)){if(i.revealEditedField){let n=ct(t.fields,d,a,e.locale);r.revealLedger.note(e,d,n)}continue}let u=d.strategyKind??P(d.element)??\\\"unknown\\\";if(\\\"unknown\\\"===u){this.strategies.warnUnsupportedStrategy(d);continue}\\\"fragment\\\"===u&&null===f&&this.strategies.warnFragmentFallback(d);let c=ct(t.fields,d,a,e.locale);if(void 0===c){r.absentFields.add(a);continue}if(!l&&i.revealEditedField&&r.revealLedger.note(e,d,c),!o())return;let h=sn(i,d,c,t.fields,o);if(!o())return;let m=p?ht(d,h,t.fields,e.locale):void 0,v=r.lastAppliedIdentity.get(d.element);if(!e.forceRender&&i.skipUnchanged&&void 0!==m&&v===m&&!e.invalidated.has(a)){r.skippedUnchangedCount+=1;continue}let y={target:d,value:h,allFields:t.fields,revision:e.revision,...l?{}:{data:t},valueIdentity:m};i.scheduler.schedule(y),g+=1}}if(l||function(e,t,n,i,r){let{cache:l,strategies:o}=e,s={cache:l,warned:t,warn:e.warn};if(0===l.fieldCount||!1!==r&&!function(e,t){for(let n of e.values())if(W(n.owner,t))return!0;return!1}(l,r))return;let a=function(e,t,n,i){let r=G(e,t,n,q(e,n,i));return e=>\\\"none\\\"!==r(e)}(l,i,r,o);for(let[e,t]of Object.entries(n)){if(Vi.has(e))continue;if(mt(t)){gt(s,a,e,i,t);continue}if(!vt(t)||a(e))continue;let n=H(e,i);for(let[e,r]of Object.entries(t))!mt(r)||Vi.has(e)||gt(s,a,`${n}.${e}`,i,r)}if(\\\"declared\\\"!==e.subfieldCoverage)return;let u=function(e,t,n,i,r){let l=q(e,i,r),o=G(e,n,i,l),s=[];for(let[e,i]of Object.entries(t)){if(Vi.has(e)||\\\"below\\\"!==o(e))continue;let t=H(e,n);s.push(...V(t,void 0,i,l))}return s}(l,n,i,r,o);for(let{path:e,value:t}of u)if(mt(t)&>(s,a,e,i,t),vt(t))for(let[n,r]of Object.entries(t))mt(r)&>(s,a,`${e}.${n}`,i,r)}(i,r.warnedOrphanFields,t.fields,e.locale,s),o()){if(null!==f&&f.boundaries.length>0){for(let t of f.boundaries)e.fragmentBoundariesRun.add(t);e.pendingFragments+=f.boundaries.length,this.strategies.runFragments(e,t,f)}l||!o()||0===g&&(0===e.pendingFragments&&0===i.scheduler.pendingCount&&(r.complete(e),this.revealPending(e)),this.notifyIslands(e,t))}}notifyIslands(e,t){0!==e.touched.size&&this.navigationReplay.dispatchIslands(e,t,this.deps.cache.islands)}restoreGuesses(e,t){let{deps:n,state:i}=this;if(\\\"off\\\"!==n.autoBind&&null!==i.autoBindGuesses){let r=ft(n,i,e,t.fields);!function(e,t,n,i,r,l){if(!l())return 0;let o=t.autoBindGuesses,s=ot(e.root);if(null===o||0===o.fields.size||null===s)return 0;let a=new Map(o.values);for(let[e,t]of Ze(n,i)){if(null===t||!o.fields.has(t.field))continue;let n=a.get(e);void 0===n?a.set(e,t):n?.field!==t.field&&a.set(e,null)}if(!l())return 0;let u=lt(s,a);l()&&at(e,u,r,\\\"after a server render\\\",l).length}(n,i,t.fields,e.locale,r,()=>i.isCurrent(e))}}onFlush(e){let{deps:t,state:n}=this;n.lastFlush=e,e.deferred>0&&!n.warnedVisibilityGate&&(n.warnedVisibilityGate=!0,t.warn(`[live-preview] LP0301: visibility gate held ${String(e.deferred)} off-screen update(s) until scrolled into view; see visibilityGateThreshold`));let{revision:i,data:r}=e;if(void 0===i)return;let l=n.activeUpdate;if(null===l||!n.isCurrent(l)||!b(l.revision,i))return;n.display.deferred(l,e.deferred),0===l.pendingFragments&&n.complete(l);let o=()=>n.isCurrent(l)&&b(l.revision,i),s=r??l.renderData;if(this.revealPending(l),!o())return;let a=n.unfaithfulPatches;if(a.length>0){if(n.unfaithfulPatches=[],void 0!==s){let e=ft(t,n,l,s.fields);this.strategies.escalateUnfaithful(l,s,a,e)}if(!o())return}void 0!==r&&(e.applied>0&&t.a11y?.announceUpdate(e.applied),o()&&(this.notifyIslands(l,r),o()&&0!==e.applied&&0!==t.emitter.listenerCount(\\\"afterUpdate\\\")&&t.emitter.emitWhile(\\\"afterUpdate\\\",{data:r,updatedCount:e.applied,durationMs:e.durationMs,revision:i.revision,receivedAt:l.receivedAt,source:\\\"patch\\\"},o)))}revealPending(e){let t=this.state.revealLedger.commit(e);if(void 0!==t)try{te(this.state.revealer,t)}catch(e){this.deps.log(\\\"reveal\\\",e)}}revealField(e){let t=this.deps.cache.get(e)?.[0];return void 0===t?\\\"no-element\\\":te(this.state.revealer,t)}documentSaved(){this.strategies.refreshAfterSave()}},uo=class{constructor(e,t){ti(this,\\\"apply\\\");ti(this,\\\"debounceMs\\\");ti(this,\\\"maxWaitMs\\\");ti(this,\\\"isVisible\\\");ti(this,\\\"gateThresholdValue\\\");ti(this,\\\"gateDisabled\\\");ti(this,\\\"getCacheSize\\\");ti(this,\\\"onFlush\\\");ti(this,\\\"scheduleFrame\\\");ti(this,\\\"cancelFrame\\\");ti(this,\\\"pending\\\",new Map);ti(this,\\\"replay\\\",new Map);ti(this,\\\"activeFlushes\\\",new Set);ti(this,\\\"debounceTimer\\\",null);ti(this,\\\"debounceToken\\\",0);ti(this,\\\"deadlineTimer\\\",null);ti(this,\\\"frameHandle\\\",null);ti(this,\\\"frameFallback\\\",null);ti(this,\\\"frameToken\\\",0);ti(this,\\\"windowUntil\\\",0);ti(this,\\\"activeRevision\\\",null);ti(this,\\\"activeRevisionCancelled\\\",!1);ti(this,\\\"destroying\\\",!1);this.apply=e,this.debounceMs=t.debounceMs??50,this.maxWaitMs=t.maxWaitMs??4*this.debounceMs,this.isVisible=t.isVisible,this.gateThresholdValue=t.visibilityGateThreshold??50,this.gateDisabled=t.disableVisibilityGate??!1,this.getCacheSize=t.getCacheSize,this.onFlush=t.onFlush,this.scheduleFrame=t.scheduleFrame??(\\\"function\\\"==typeof requestAnimationFrame?requestAnimationFrame.bind(globalThis):e=>setTimeout(()=>{e(performance.now())},0)),this.cancelFrame=t.cancelFrame??(\\\"function\\\"==typeof cancelAnimationFrame?cancelAnimationFrame.bind(globalThis):e=>{clearTimeout(e)})}schedule(e){if(this.destroying||void 0!==e.revision&&(this.activeRevisionCancelled||null===this.activeRevision||!b(e.revision,this.activeRevision)))return;let t=this.pending.get(e.target.element);t?(t.value=e.value,t.allFields=e.allFields,t.revision=e.revision,t.data=e.data,t.valueIdentity=e.valueIdentity):this.pending.set(e.target.element,{target:e.target,value:e.value,allFields:e.allFields,revision:e.revision,data:e.data,valueIdentity:e.valueIdentity}),this.armDebounce()}acceptRevision(e){this.destroying||null!==this.activeRevision&&b(e,this.activeRevision)||null!==this.activeRevision&&function(e,t){return e.generation!==t.generation?e.generation-t.generation:e.revision-t.revision}(e,this.activeRevision)<0||(this.clearWork(),this.activeRevision=e,this.activeRevisionCancelled=!1,this.cancelScheduledWork())}cancelRevision(e){null===this.activeRevision||!b(e,this.activeRevision)||(this.clearWork(),this.activeRevisionCancelled=!0,this.cancelScheduledWork())}flushNow(){return this.cancelScheduledWork(),this.flush()}notifyVisible(e){let t=this.replay.get(e);if(!t||(this.replay.delete(e),!this.isCurrent(t)))return;let n=performance.now(),i=this.didApply(t)?1:0;this.onFlush?.(this.statsFor(t,i,0,performance.now()-n,1===i?[t.target.fieldName]:[]))}retarget(e){this.retargetBuffer(this.pending,e),this.retargetBuffer(this.replay,e);for(let t of this.activeFlushes)this.retargetBuffer(t,e)}forget(e){this.pending.delete(e),this.replay.delete(e);for(let t of this.activeFlushes)t.delete(e)}destroy(){if(!this.destroying){this.destroying=!0;try{this.clearWork(),this.activeRevision=null,this.activeRevisionCancelled=!1,this.windowUntil=0,this.cancelScheduledWork()}finally{this.destroying=!1}}}get pendingCount(){return this.pending.size}get replayCount(){return this.replay.size}get gateThreshold(){return this.gateThresholdValue}get gateActive(){return!this.gateDisabled&&this.getCacheSize()>this.gateThresholdValue}armDebounce(){let e=Date.now(),t=e>=this.windowUntil;if(this.windowUntil=e+this.debounceMs,t){this.requestFrame();return}let n=this.debounceToken+=1,i=this.debounceTimer;if(this.debounceTimer=null,null!==i&&clearTimeout(i),this.debounceToken!==n)return;let r=setTimeout(()=>{this.debounceToken===n&&(this.debounceTimer=null,this.pending.size>0&&this.requestFrame())},this.debounceMs);this.debounceToken===n&&(this.debounceTimer=r),null===this.deadlineTimer&&this.maxWaitMs>this.debounceMs&&(this.deadlineTimer=setTimeout(()=>{this.deadlineTimer=null,this.pending.size>0&&this.requestFrame()},this.maxWaitMs))}requestFrame(){let e=this.frameToken+=1,t=this.frameHandle;if(this.frameHandle=null,this.clearFrameFallback(),null!==t&&this.cancelFrame(t),this.frameToken!==e)return;let n=!1,i=()=>{if(this.frameToken!==e||n)return;n=!0;let t=this.frameHandle;this.frameHandle=null,this.clearFrameFallback(),null!==t&&this.cancelFrame(t),this.flush()},r=this.scheduleFrame(i);n||this.frameToken!==e||(this.frameHandle=r,this.frameFallback=setTimeout(i,100))}clearFrameFallback(){clearTimeout(this.frameFallback??void 0),this.frameFallback=null}flush(){let e=performance.now();this.clearDeadline();let t=this.gateActive,n=this.pending;this.pending=new Map;let i,r=0,l=[],o=0;this.activeFlushes.add(n);try{for(let e of n.values()){if(!this.isCurrent(e))continue;let n=!t||this.isVisible(e.target.element);if(this.isCurrent(e)){if(i??(i=e),!n){this.replay.set(e.target.element,e),o+=1;continue}this.replay.delete(e.target.element),this.didApply(e)&&(r+=1,l.push(e.target.fieldName))}}}finally{this.activeFlushes.delete(n)}let s=this.statsFor(i,r,o,performance.now()-e,l);return this.onFlush?.(s),s}isCurrent(e){return void 0===e.revision||!this.activeRevisionCancelled&&null!==this.activeRevision&&b(e.revision,this.activeRevision)}didApply(e){return!1!==this.apply(e)||!function(e){return Ii.has(e)}(this.apply)}retargetBuffer(e,t){let n=e.get(t.element);if(void 0!==n){if(!ve(n.target,t)){e.delete(t.element);return}n.target=t}}clearWork(){this.pending.clear(),this.replay.clear();for(let e of this.activeFlushes)e.clear()}statsFor(e,t,n,i,r){return{applied:t,appliedFields:r,deferred:n,durationMs:i,...void 0!==e?.revision?{revision:e.revision}:{},...void 0!==e?.data?{data:e.data}:{}}}clearDeadline(){null!==this.deadlineTimer&&(clearTimeout(this.deadlineTimer),this.deadlineTimer=null)}cancelScheduledWork(){let e=this.debounceTimer,t=this.frameHandle;this.debounceToken+=1,this.frameToken+=1,this.debounceTimer=null,this.frameHandle=null,this.clearDeadline(),this.clearFrameFallback(),null!==e&&clearTimeout(e),null!==t&&this.cancelFrame(t)}},co=[0,500,1e3,2e3],ho=class{constructor(e){ti(this,\\\"deps\\\");ti(this,\\\"state\\\",new tr);ti(this,\\\"pipeline\\\");ti(this,\\\"writer\\\");ti(this,\\\"rootSentinel\\\",null);ti(this,\\\"scope\\\",null);ti(this,\\\"closingSession\\\",!1);ti(this,\\\"observedRoot\\\",null);ti(this,\\\"replayRetainedOnStart\\\",!1);let{emitter:r,renderers:l}=e,o=void 0===e.log?n:t(e.log),s=void 0===e.warn?ai:t(e.warn),a=e.root??(typ\",\"eof document<\\\"u\\\"?document:void 0);if(void 0===a)throw new Error(\\\"LivePreviewRuntime: no document; pass options.root\\\");let u=new Ur({filter:e=>!function(e){let t=e;for(;null!==t;){if(ae(t))return!0;t=t.parentElement}return!1}(e)}),d=new Yr({onStructuralChange:()=>{this.rebuildCache()},onIslandHydrated:e=>{this.pipeline.reapplyNavigationIslands([e],!0)},onVisibilityChange:(e,t)=>{t&&c.notifyVisible(e)}},void 0!==e.intersectionRootMargin?{intersectionRootMargin:e.intersectionRootMargin}:{}),c=new uo(O(e=>this.writer.apply(e)),{...void 0!==e.debounceMs?{debounceMs:e.debounceMs}:{},...void 0!==e.disableVisibilityGate?{disableVisibilityGate:e.disableVisibilityGate}:{},...void 0!==e.visibilityGateThreshold?{visibilityGateThreshold:e.visibilityGateThreshold}:{},isVisible:e=>d.isVisible(e),getCacheSize:()=>u.elementCount,onFlush:e=>{this.pipeline.onFlush(e)}}),h=new Ri(e.originMatcher,{onUpdate:(e,t,n)=>{this.pipeline.handleUpdate(e,t,n)},onReplay:(e,t,n)=>{this.pipeline.handleReplay(e,t,n)},onDocumentEvent:()=>{this.state.protocol.observe([\\\"document-events\\\"],o),r.emit(\\\"documentSave\\\",{timestamp:Date.now()}),this.pipeline.documentSaved()},onFocusField:e=>{this.deps.revealEditedField&&this.pipeline.revealField(e)},onInvalid:(e,t)=>{if(\\\"token\\\"===e){let e=new Error(`Preview token rejected (origin: ${t})`);r.emit(\\\"error\\\",{error:e,context:\\\"token\\\",code:\\\"LP0502\\\"})}(\\\"shape\\\"===e||\\\"type\\\"===e)&&!this.state.warnedProtocolShape&&(this.state.warnedProtocolShape=!0,s(`[live-preview] LP0503: ${t} posted a message this runtime does not recognise (${\\\"type\\\"===e?\\\"unknown message type\\\":\\\"unexpected shape\\\"}); it was ignored. A newer Payload or a custom sender: check that the versions match.`)),\\\"source\\\"===e&&!this.state.warnedForeignSource&&(this.state.warnedForeignSource=!0,s(`[live-preview] LP0501: a message from ${t} was ignored because it did not come from the window that framed or opened this page. \\\\`eventSourcePolicy\\\\` is 'parent-or-opener' by default since 2.0, where 1.x accepted any window on a trusted origin. Set \\\\`eventSourcePolicy: 'any'\\\\` if the admin posts from elsewhere.`)),o(\\\"LP0501 message rejected:\\\",e,t)},...void 0!==e.validateToken?{validateToken:e.validateToken}:{},...void 0!==e.eventSourcePolicy?{sourcePolicy:e.eventSourcePolicy}:{}}),f=e.dataMerge;this.deps={emitter:r,cache:u,observers:d,scheduler:c,bus:h,connection:new pl,heartbeat:new fl({...void 0!==e.heartbeatMs?{timeoutMs:e.heartbeatMs}:{},onTimeout:()=>{this.onHeartbeatTimeout()}}),renderers:l,resolveRenderer:e.resolveRenderer??(e=>l[e]),transformValue:e.transformValue,renderRichText:e.renderRichText,sanitizerPolicy:e.sanitizerPolicy,root:a,readyTargets:\\\"function\\\"==typeof e.readyTargets?e.readyTargets:(e=>()=>e)(e.readyTargets),sendReady:e.sendReady??S,onHeartbeatTimeout:e.onHeartbeatTimeout,log:o,warn:s,a11y:w(e),serverURL:f?.serverURL,merger:void 0===f?null:new Hr({serverURL:f.serverURL,...void 0!==f.apiRoute?{apiRoute:f.apiRoute}:{},...void 0!==f.depth?{depth:f.depth}:{},...void 0!==f.fetchFn?{fetchFn:f.fetchFn}:{},log:o}),mergeWindowMs:e.debounceMs??50,scopeBindingsByOwner:!0===e.scopeBindingsByOwner,subfieldCoverage:e.subfieldCoverage??\\\"descendant\\\",lockedOrigin:e.lockedOrigin??(()=>{}),skipUnchanged:!0===e.skipUnchanged,dependencies:e.dependencies??{},strategies:e.strategies??{},revealEditedField:!0===e.revealEditedField,onUnfaithfulPatch:i(e),autoBind:e.autoBind??\\\"off\\\",hydration:e.hydration},this.writer=new nr(this.deps,this.state),this.pipeline=new ao(this.deps,this.state,()=>{this.rebuildCache()})}start(){let{state:e}=this;if(e.isRunning()||this.closingSession)return!1;e.suspended&&(this.replayRetainedOnStart=!0),e.started=!0,e.suspended=!1,this.openScope();try{return function(e){\\\"react\\\"===e.hydration?We():\\\"vue\\\"===e.hydration&&qe();let{root:t}=e;if(!Ke(t)||\\\"loading\\\"!==t.readyState){He(e);return}let n=()=>{e.isRunning()&&e.later(()=>{He(e)})};t.addEventListener(\\\"DOMContentLoaded\\\",n,{once:!0}),e.defer(()=>{t.removeEventListener(\\\"DOMContentLoaded\\\",n)})}(this.startupHost()),!0}catch(e){throw this.rollbackFailedStart(),e}}startupHost(){let{state:e,deps:t}=this;return{root:t.root,hydration:t.hydration,isRunning:()=>e.isRunning(),defer:t=>{e.deferredStart=t,this.scope?.own(()=>{e.deferredStart===t&&(e.deferredStart=null,t())})},later:t=>{e.deferredStart=null;try{t()}catch(e){this.rollbackFailedStart(),this.reportError(e,\\\"startup\\\",\\\"LP0605\\\")}},hydrated:t=>{e.hydration=t},warn:t.warn,startNow:()=>{this.startNow()}}}startNow(){let{state:e,deps:t}=this;if(!e.isRunning())return;let n=Ke(t.root)?Je(t.root):t.root;if(null===n)throw new Error(\\\"LivePreviewRuntime: document.body unavailable\\\");if(t.observers.start(n),this.observedRoot=n,this.watchRootReplacement(),this.buildCacheAndObserve(),!e.isRunning()||(t.bus.attach(),t.emitter.emitWhile(\\\"init\\\",{timestamp:Date.now()},()=>e.isRunning()),!e.isRunning()))return;let i=this.replayRetainedOnStart;this.replayRetainedOnStart=!1;let r=i&&t.heartbeat.resume();if(e.isRunning()&&(!i||r||(e.forgetOwedWork(),e.merges.resetRawChanges(),e.unfaithfulPatches=[],e.revealer.reset(),e.lastAppliedIdentity=new WeakMap,e.changes.reset(),e.navigationReplayPending=!0,t.bus.replayLastAccepted()||(e.navigationReplayPending=!1),e.isRunning())))for(let n of co){if(!e.isRunning())return;0===n?t.sendReady(t.readyTargets()):e.readyTimers.push(setTimeout(()=>{e.isRunning()&&this.sendReadyAfterStart()},n))}}suspend(){if(!this.state.isRunning())return!1;let e=this.release();return this.state.suspended=!0,e&&this.deps.emitter.emit(\\\"disconnect\\\",{reason:\\\"unload\\\",timestamp:Date.now()}),!0}destroy(){let{state:e,deps:t}=this;if(!e.isRunning()&&!e.suspended)return;let n=!!e.isRunning()&&this.release();e.suspended=!1,this.replayRetainedOnStart=!1,t.bus.forgetLastAccepted(),n&&t.emitter.emit(\\\"disconnect\\\",{reason:\\\"destroy\\\",timestamp:Date.now()}),t.a11y?.detach(),t.emitter.emit(\\\"destroy\\\",{timestamp:Date.now()})}openScope(){let{state:e,deps:t}=this,n=new el(t.log);n.own(()=>{t.merger?.destroy(),e.merges.destroy()}),n.own(()=>{t.scheduler.destroy()}),n.own(()=>{t.observers.stop()}),n.own(()=>{this.rootSentinel?.disconnect(),this.rootSentinel=null,this.observedRoot=null}),n.own(()=>{e.abortStrategies()}),n.own(()=>{t.bus.detach()}),n.own(()=>{t.heartbeat.stop()}),n.own(()=>{for(let t of e.readyTimers)clearTimeout(t);e.readyTimers.length=0}),this.scope=n}release(){let{state:e,deps:t}=this;e.display.end(),e.activeUpdate=null,e.navigationBindingReplay=!1,e.started=!1;let n=this.scope;this.scope=null,this.closingSession=!0;try{n?.close()}finally{this.closingSession=!1}return t.cache.clear(),t.connection.markDisconnected()}rollbackFailedStart(){this.release();try{this.deps.a11y?.detach()}catch(e){this.deps.log(\\\"runtime cleanup failed:\\\",e)}}refreshCache(){this.state.isRunning()&&(this.state.revealer.reset(),this.followReplacedRoot()||this.rebuildCache())}navigationCommit(){let{state:e,deps:t}=this;!e.isRunning()||null!==e.deferredStart||(this.cancelActiveUpdate(!0),t.merger?.destroy(),e.merges.destroy(),e.abortStrategies(),this.cancelActiveUpdate(!0),e.forgetOwedWork(),e.merges.resetRawChanges(),e.unfaithfulPatches=[],e.revealer.reset(),e.lastAppliedIdentity=new WeakMap,e.changes.reset(),e.isRunning()&&(t.bus.advanceGeneration(),e.navigationReplayPending=!0,this.followReplacedRoot()||this.rebuildCache(),e.isRunning()&&(t.bus.replayLastAccepted(),e.isRunning()&&this.sendReadyAfterStart())))}watchRootReplacement(){let{root:e}=this.deps;!Ke(e)||typeof MutationObserver>\\\"u\\\"||(this.rootSentinel?.disconnect(),this.rootSentinel=new MutationObserver(()=>{this.followReplacedRoot()}),this.rootSentinel.observe(e.documentElement,{childList:!0}))}followReplacedRoot(){let{root:e}=this.deps;if(!this.state.isRunning()||!Ke(e))return!1;let t=Je(e);return null!==t&&t!==this.observedRoot&&(this.observedRoot=t,this.deps.observers.start(t),this.rebuildCache(),!0)}get status(){return this.deps.connection.status}get cache(){return this.deps.cache}get updateCount(){return this.state.updateCount}get protocol(){return this.state.protocol.negotiation}inspect(){return function(e,t){let{cache:n,scheduler:i}=e,r=t.protocol.negotiation,l=t.activeUpdate,o=t.lastFlush,s=[],a=new Set,u=[];for(let[e,t]of n.entries()){s.push(e);for(let n of t)void 0!==n.owner&&a.add(n.owner),void 0!==n.guessed&&u.push({field:e,matched:n.guessed,attribute:n.targetAttribute??(\\\"IMG\\\"===n.element.tagName?\\\"src\\\":void 0)})}return{version:Gr,started:t.started,status:e.connection.status,origins:{trusted:[...e.readyTargets()],locked:e.lockedOrigin()},protocol:{ours:r.ours,theirs:r.theirs,negotiated:r.negotiated,capabilities:[...r.capabilities].sort(),observed:[...r.observed].sort(),profile:Pe(r.observed).name},revisions:{accepted:t.updateCount,superseded:t.supersededCount,completed:t.completedCount,skippedUnchanged:t.skippedUnchangedCount,active:null===l?void 0:l.revision.revision,display:t.display.snapshot()},bindings:{elements:n.elementCount,fields:n.fieldCount,fieldNames:s.sort(),absentFields:[...t.absentFields].sort(),orphanFields:[...t.warnedOrphanFields].sort(),ownerScoped:e.scopeBindingsByOwner,owners:[...a].sort(),guessed:u.sort((e,t)=>e.field.localeCompare(t.field)),autoBind:{mode:e.autoBind,searchMs:t.autoBindSearchMs}},route:{handler:void 0!==e.strategies.route,...t.routeStats},fidelity:{mode:e.onUnfaithfulPatch,canEscalate:void 0!==e.strategies.fragment||void 0!==e.strategies.route,unfaithful:t.unfaithfulCount,escalated:t.escalatedCount,fields:[...t.unfaithfulFields].sort()},hydration:{mode:e.hydration??\\\"off\\\",state:t.hydration},fragments:{handler:void 0!==e.strategies.fragment,inFlight:l?.pendingFragments??0,...t.fragmentStats},scheduler:{pending:i.pendingCount,deferred:i.replayCount,visibilityGateThreshold:i.gateThreshold,visibilityGateActive:i.gateActive,lastFlush:null===o?void 0:{applied:o.applied,appliedFields:o.appliedFields,deferred:o.deferred,durationMs:o.durationMs}},plugins:[],renderers:Object.keys(e.renderers).sort()}}(this.deps,this.state)}buildCacheAndObserve(){let{state:e,deps:t}=this;if(!e.isRunning())return;let n=t.cache.buildFromRoot(t.root);if(t.log(\\\"cache\\\",n),e.isRunning()&&(t.emitter.emitWhile(\\\"cacheRefresh\\\",n,()=>e.isRunning()),e.isRunning()))for(let n of t.cache.values()){if(!e.isRunning())return;t.observers.observeElement(n.element)}}rebuildCache(){let{state:e,deps:t}=this;if(!e.isRunning())return;let n=new Map,i=t.cache.islandOwners,r=new Set(t.cache.navigationReplayRoots);for(let e of t.cache.values())n.set(e.element,e),t.observers.unobserveElement(e.element);if(this.buildCacheAndObserve(),!e.isRunning())return;let l=new Set(t.cache.navigationReplayRoots.filter(e=>!r.has(e)));for(let e of t.cache.values()){let i=n.get(e.element);void 0!==i&&ve(i,e)?t.scheduler.retarget(e):(t.scheduler.forget(e.element),l.add(e.element)),n.delete(e.element)}for(let e of n.values())t.scheduler.forget(e.element);l.size>0&&this.pipeline.reapplyNavigationBindings(l);let o=t.cache.islands.filter(e=>!i.has(e)||t.scopeBindingsByOwner&&i.get(e)!==t.cache.islandOwners.get(e));o.length>0&&this.pipeline.reapplyNavigationIslands(o)}onHeartbeatTimeout(){let{state:e,deps:t}=this;if(!e.isRunning()||(this.cancelActiveUpdate(!1),t.merger?.destroy(),e.merges.destroy(),e.abortStrategies(),this.cancelActiveUpdate(!1),!e.isRunning()))return;t.bus.advanceGeneration(),t.bus.forgetLastAccepted(),e.navigationBindingReplay=!1;let n=t.connection.markDisconnected();try{t.onHeartbeatTimeout?.()}catch(e){t.log(\\\"heartbeat:\\\",e)}e.isRunning()&&(n&&this.isIdleDisconnected()&&(t.a11y?.announceDisconnected(),t.emitter.emitWhile(\\\"disconnect\\\",{reason:\\\"timeout\\\",timestamp:Date.now()},()=>this.isIdleDisconnected()),!e.isRunning()||(this.isIdleDisconnected()&&t.log(\\\"connection\\\",\\\"connected\\\",\\\"\\\\u2192\\\",\\\"disconnected\\\"),!e.isRunning()))||this.sendReadyAfterStart())}cancelActiveUpdate(e){let{state:t,deps:n}=this,i=t.activeUpdate;t.display.end(),t.activeUpdate=null,null!==i&&(i.cancelled=!0,n.scheduler.cancelRevision(i.revision),e&&!i.completed&&i.countsAsUpdate&&(t.supersededCount+=1))}sendReadyAfterStart(){try{this.deps.sendReady(this.deps.readyTargets())}catch(e){this.reportError(e,\\\"ready\\\",\\\"LP0606\\\")}}reportError(e,t,n){let i=e instanceof Error?e:new Error(String(e));this.deps.emitter.emit(\\\"error\\\",{error:i,context:t,code:n})}isIdleDisconnected(){return this.state.isRunning()&&\\\"disconnected\\\"===this.deps.connection.status&&null===this.state.activeUpdate}},fo=/^https?:\\\\/\\\\/(localhost|127\\\\.0\\\\.0\\\\.1)(?::\\\\d+)?$/i,po=/^https?:\\\\/\\\\/[^/?#\\\\s]+$/i,go=[3e3,3001,3333,4e3,4321,5e3,5173,5174,8e3,8080,8888,9e3],mo=class{constructor(e={}){ri(this,vo);let t=new Set;for(let n of e.additionalOrigins??[]){let e=un(n);void 0!==e&&t.add(e)}let n;if(e.enableReferrerDetection??1){let t=e.referrer??(typ\",\"eof document<\\\"u\\\"?document.referrer:\\\"\\\");if(t.length>0)try{let e=new URL(t).origin;e&&\\\"null\\\"!==e&&(n=e)}catch{}}let i=(e.enableLocalhostMatching??!0)&&(e.forceDevMode??function(){let e=function(){if(!(typ\",\"eof process>\\\"u\\\"))return\\\"production\\\"}();if(void 0!==e)return\\\"production\\\"!==e;if(typ\",\"eof window<\\\"u\\\"){let e=window.location.hostname;return\\\"localhost\\\"===e||\\\"127.0.0.1\\\"===e}return!1}());li(this,vo,[t,n,i,void 0!==n,void 0])}matches(e){return 0!==e.length&&\\\"null\\\"!==e&&(void 0!==ii(this,vo)[4]?e===ii(this,vo)[4]:!!(ii(this,vo)[0].has(e)||0===ii(this,vo)[0].size&&void 0!==ii(this,vo)[1]&&e===ii(this,vo)[1]||ii(this,vo)[2]&&fo.test(e)))}lockOrigin(e){return!!this.matches(e)&&(ii(this,vo)[4]=e,!0)}unlockOrigin(){let e=ii(this,vo)[4];return ii(this,vo)[4]=void 0,e}get lockedOrigin(){return ii(this,vo)[4]}enumerate(){if(void 0!==ii(this,vo)[4])return[ii(this,vo)[4]];let e=new Set(ii(this,vo)[0]);if(0===ii(this,vo)[0].size&&void 0!==ii(this,vo)[1]&&e.add(ii(this,vo)[1]),ii(this,vo)[2])for(let t of go)e.add(`http://localhost:${String(t)}`),e.add(`http://127.0.0.1:${String(t)}`);return[...e]}get referrerWasAvailable(){return ii(this,vo)[3]}get isProductionUnconfigured(){return!(!an()||ii(this,vo)[0].size>0||ii(this,vo)[2]||void 0!==ii(this,vo)[1])}get isReferrerOnlyTrust(){return!(ii(this,vo)[0].size>0||ii(this,vo)[2])&&void 0!==ii(this,vo)[1]}},vo=new WeakMap,yo=\\\"astro:page-load\\\",bo=\\\"astro:after-swap\\\",wo={1:\\\"left\\\",2:\\\"center\\\",3:\\\"right\\\",4:\\\"justify\\\"},So=new Set([\\\"left\\\",\\\"center\\\",\\\"right\\\",\\\"justify\\\",\\\"start\\\",\\\"end\\\"]),Ao=new Set([\\\"h1\\\",\\\"h2\\\",\\\"h3\\\",\\\"h4\\\",\\\"h5\\\",\\\"h6\\\"]),ko=' target=\\\"_blank\\\" rel=\\\"noopener noreferrer\\\"',To=(e,t)=>{let n=t.renderChildren(e.children??[]),i=pn(e.fields),r=function(e,t){if(\\\"internal\\\"===t?.linkType)return function(e){let t=pn(pn(e)?.value),n=t?.url;if(\\\"string\\\"==typeof n&&n.length>0)return n;let i=t?.slug;return\\\"string\\\"==typeof i&&i.length>0?`/${i}`:void 0}(t.doc);let n=t?.url??e.url;return\\\"string\\\"==typeof n&&n.length>0?n:void 0}(e,i);if(void 0===r||!F(r))return n;let l=\\\"string\\\"==typeof e.title?` title=\\\"${Lt(e.title)}\\\"`:\\\"\\\";return`<a href=\\\"${xt(r)}\\\"${function(e,t,n){if(!0===t?.newTab||N(n))return ko;let i=\\\"string\\\"==typeof e.target?e.target:\\\"\\\";return\\\"\\\"===i?\\\"\\\":\\\"_blank\\\"===i?ko:` target=\\\"${Lt(i)}\\\"`}(e,i,r)}${l}>${n}</a>`},Co=new Map,Ro=\\\".lp-block:empty,.lp-inline-block:empty\\\",$o={text:e=>{let t=Lt(\\\"string\\\"==typeof e.text?e.text:\\\"\\\"),n=\\\"number\\\"==typeof e.format?e.format:0;return!!(16&n)&&(t=`<code>${t}</code>`),!!(1&n)&&(t=`<strong>${t}</strong>`),!!(2&n)&&(t=`<em>${t}</em>`),!!(8&n)&&(t=`<u>${t}</u>`),!!(4&n)&&(t=`<s>${t}</s>`),!!(32&n)&&(t=`<sub>${t}</sub>`),!!(64&n)&&(t=`<sup>${t}</sup>`),!!(128&n)&&(t=`<mark>${t}</mark>`),t},paragraph:(e,t)=>{let n=t.renderChildren(e.children??[]);return`<p${hn(e)}${fn(e)}>${n}</p>`},heading:(e,t)=>{let n=\\\"string\\\"==typeof e.tag?e.tag.toLowerCase():\\\"h2\\\",i=Ao.has(n)?n:\\\"h2\\\",r=t.renderChildren(e.children??[]);return`<${i}${hn(e)}${fn(e)}>${r}</${i}>`},list:(e,t)=>{let n=\\\"string\\\"==typeof e.listType?e.listType:\\\"bullet\\\",i=\\\"number\\\"===n?\\\"ol\\\":\\\"ul\\\",r=\\\"number\\\"===n&&\\\"number\\\"==typeof e.start&&e.start>1?` start=\\\"${String(e.start)}\\\"`:\\\"\\\",l=\\\"check\\\"===n?' role=\\\"list\\\"':\\\"\\\",o=t.renderChildren(e.children??[]);return`<${i}${hn(e)}${fn(e)}${r}${l}>${o}</${i}>`},listitem:(e,t)=>{let n=t.renderChildren(e.children??[]);if(\\\"boolean\\\"==typeof e.checked)return`<li role=\\\"checkbox\\\" aria-checked=\\\"${e.checked?\\\"true\\\":\\\"false\\\"}\\\"${fn(e)}>${n}</li>`;let i=\\\"number\\\"==typeof e.value?` value=\\\"${Lt(String(e.value))}\\\"`:\\\"\\\";return`<li${hn(e)}${fn(e)}${i}>${n}</li>`},link:To,autolink:To,quote:(e,t)=>{let n=t.renderChildren(e.children??[]);return`<blockquote${hn(e)}${fn(e)}>${n}</blockquote>`},code:e=>{let t=vn(\\\"string\\\"==typeof e.language?e.language:\\\"\\\");return`<pre><code${\\\"\\\"===t?\\\"\\\":` class=\\\"language-${t}\\\"`}>${Lt(wn(e))}</code></pre>`},\\\"code-highlight\\\":e=>{let t=\\\"string\\\"==typeof e.text?e.text:\\\"\\\";return`<span${\\\"string\\\"==typeof e.highlightType?` class=\\\"token-${vn(e.highlightType)}\\\"`:\\\"\\\"}>${Lt(t)}</span>`},linebreak:()=>\\\"<br>\\\",horizontalrule:()=>\\\"<hr>\\\",tab:()=>\\\"\\\\t\\\",upload:e=>{let t=gn(e.value);if(void 0===t)return\\\"\\\";let n=t.url;if(\\\"string\\\"!=typeof n||!F(n))return\\\"\\\";let i=\\\"string\\\"==typeof t.mimeType?t.mimeType:\\\"\\\";return i.startsWith(\\\"video/\\\")?function(e,t){return`<video controls${Sn(e)}><source src=\\\"${xt(t)}\\\"${An(e)}></video>`}(t,n):i.startsWith(\\\"audio/\\\")?function(e,t){return`<audio controls><source src=\\\"${xt(t)}\\\"${An(e)}></audio>`}(t,n):\\\"\\\"===i||i.startsWith(\\\"image/\\\")?function(e,t){let n=\\\"string\\\"==typeof e.alt?Lt(e.alt):\\\"\\\";return`<img src=\\\"${xt(t)}\\\" alt=\\\"${n}\\\"${Sn(e)} loading=\\\"lazy\\\" decoding=\\\"async\\\">`}(t,n):function(e,t){let n=\\\"string\\\"==typeof e.filename?Lt(e.filename):Lt(t);return`<a href=\\\"${xt(t)}\\\" target=\\\"_blank\\\" rel=\\\"noopener noreferrer\\\">${n}</a>`}(t,n)},relationship:e=>{let t=\\\"string\\\"==typeof e.relationTo?e.relationTo:\\\"\\\",n=pn(e.value),i=Lt((n&&bn(n))??`#${t}`),r=vn(t),l=\\\"\\\"===r?' class=\\\"lp-relation\\\"':` class=\\\"lp-relation lp-relation--${r}\\\"`,o=n?.url;return\\\"string\\\"==typeof o&&F(o)?`<a href=\\\"${xt(o)}\\\"${l}>${i}</a>`:`<span${l}>${i}</span>`},block:(e,t)=>Tn(e,t,\\\"div\\\",\\\"lp-block\\\"),inlineBlock:(e,t)=>Tn(e,t,\\\"span\\\",\\\"lp-inline-block\\\"),table:(e,t)=>`<table${hn(e)}><tbody>${t.renderChildren(e.children??[])}</tbody></table>`,tablerow:(e,t)=>`<tr>${t.renderChildren(e.children??[])}</tr>`,tablecell:(e,t)=>{let n=\\\"number\\\"==typeof e.headerState?e.headerState:0,i=3&n?\\\"th\\\":\\\"td\\\";return`<${i}${1===n?' scope=\\\"col\\\"':2===n?' scope=\\\"row\\\"':\\\"\\\"}${Cn(\\\"colspan\\\",e.colSpan)}${Cn(\\\"rowspan\\\",e.rowSpan)}>${t.renderChildren(e.children??[])}</${i}>`}},Fo=new Map,No=!1,Mo=\\\"data-payload-text\\\",Oo=new Set,Eo=new Set,Lo=new Set([\\\"DIV\\\",\\\"SECTION\\\",\\\"ARTICLE\\\"]),xo={name:\\\"richText\\\",render:O((e,t,n)=>{let i=e.element;if(Dt(t)){i.textContent=\\\"\\\";return}let r=n.sanitizerPolicy;if(void 0!==n.renderRichText){let l=n.renderRichText(t,{fieldName:e.fieldName,element:i,locale:n.locale});i.innerHTML=yt(Ft(l,r));return}if(Rn(t)){let l=new Map,o=Mn(i,Ft(function(e,t={}){if(!Rn(e))return\\\"\\\";let n=function(e){let t={renderChildren:e=>{let n=\\\"\\\";for(let i of e)n+=$n(i,t);return n},resolveAlignment:dn,resolveIndent:cn,onUnrenderedBlock:e};return t}(t.onUnrenderedBlock).renderChildren(e.root.children);return!1===t.sanitize?n:void 0!==t.document?$t(n,{document:t.document}):!0===t.requireDocument||void 0!==Nt()?$t(n):(function(){if(!No){No=!0;try{console.warn('[live-preview] lexicalToHtml() has no sanitizer document and returned unsanitised HTML; pass { document } (linkedom, jsdom) per call. 3.0 throws here instead: opt in now with { requireDocument: true }. See \\\"HTML sanitization\\\" in docs/security.md.')}catch{}}}(),n)}(t,{sanitize:!1,onUnrenderedBlock:(e,t)=>{l.set(t,e)}}),r));for(let[t,i]of o){let r=l.get(t);void 0!==r&&En(e,n,r,i)}return}if(\\\"string\\\"!=typeof t)return!1;i.innerHTML=yt(Ft(t,r))})},Po={name:\\\"html\\\",render(e,t,n){if(Dt(t)){e.element.textContent=\\\"\\\";return}let i=\\\"string\\\"==typeof t?t:Wt(t);e.element.innerHTML=yt(Ft(i,n.sanitizerPolicy))}},Uo=new WeakSet,Io=xn(\\\"url\\\"),jo=/^[a-zA-Z][a-zA-Z0-9+.-]*:/,Wo=xn(\\\"email\\\",function(e){let t=e.trim();return jo.test(t)||!t.includes(\\\"@\\\")?t:`mailto:${t}`}),Do=[\\\"src\\\",\\\"srcset\\\",\\\"sizes\\\"],Bo={name:\\\"image\\\",render:O((e,t,n)=>{let i=e.element;if(Dt(t)){jn(i);return}let r=void 0!==e.locale,{media:l,candidate:o}=function(e,t,n,i){let r=void 0!==e.srcField&&e.srcField.length>0?ut(n.allFields,e.srcField,n.locale,i):t,l=gn(r);return{media:l,candidate:void 0===l?r:l.url}}(e,t,n,r),s=Ln(i,e.fieldName,o,void 0===l?void 0:n.serverURL);if(\\\"none\\\"===s.kind)return!1;if(\\\"unsafe\\\"!==s.kind){if(\\\"IMG\\\"===i.tagName){let t=i;Un(t,s.url,l,n.serverURL);let o=function(e,t,n,i,r){if(void 0!==t&&t.length>0){let e=ut(n,t,i,r);return\\\"string\\\"==typeof e?e:void 0}return e?.alt}(l,e.altField,n.allFields,n.locale,r);void 0!==o&&(t.alt=o);return}i.style.backgroundImage=`url('${function(e){return e.replace(/['\\\"()\\\\\\\\]/g,\\\"\\\\\\\\$&\\\")}(s.url)}')`}else jn(i)})},_o={name:\\\"upload\\\",render:O((e,t,n)=>{let i=e.element;if(Dt(t)){Wn(i);return}let r=gn(t);if(void 0===r)return!1;let l=Ln(i,e.fieldName,r.url,n.serverURL);if(\\\"none\\\"===l.kind)return!1;if(\\\"unsafe\\\"===l.kind){Wn(i);return}let o=l.url;if(\\\"IMG\\\"===i.tagName){let e=i;Un(e,o,r,n.serverURL),void 0!==r.alt&&(e.alt=r.alt);return}if(\\\"A\\\"===i.tagName){i.setAttribute(\\\"href\\\",o),i.textContent=r.filename??o;return}let s=Lt(r.filename??o);i.innerHTML=yt(`<a href=\\\"${xt(o)}\\\">${s}</a>`)})},zo={name:\\\"relationship\\\",render(e,t){let n=e.element;if(Dt(t))n.removeAttribute(\\\"href\\\"),n.textContent=\\\"\\\";else{if(\\\"A\\\"===n.tagName&&!Array.isArray(t)){let i=Ln(n,e.fieldName,pn(t)?.url);\\\"safe\\\"===i.kind?n.setAttribute(\\\"href\\\",i.url):\\\"unsafe\\\"===i.kind&&n.removeAttribute(\\\"href\\\")}n.textContent=Array.isArray(t)?t.map(Dn).join(\\\", \\\"):Dn(t)}}},Vo={name:\\\"select\\\",render(e,t,n){let i=e.element,r=Dt(t)?[]:function(e){return Array.isArray(e)?e.map(Wt):[Wt(e)]}(t);if(\\\"SELECT\\\"!==i.tagName){if(\\\"INPUT\\\"===i.tagName&&\\\"radio\\\"===i.type){let e=i;e.checked=r.includes(e.value);return}i.textContent=r.map(e=>function(e,t){let n=t.schema?.options;if(!Array.isArray(n))return e;for(let t of n){let n=pn(t);if(void 0!==n&&Wt(n.value)===e)return\\\"string\\\"==typeof n.label?n.label:e}return e}(e,n)).join(\\\", \\\")}else!function(e,t){if(e.multiple)for(let n of Array.from(e.options))n.selected=t.includes(n.value);else e.value=t[0]??\\\"\\\"}(i,r)}},qo=new Set([\\\"\\\",\\\"false\\\",\\\"0\\\",\\\"off\\\",\\\"no\\\"]),Ho={name:\\\"checkbox\\\",render(e,t){let n=e.element,i=function(e){return\\\"boolean\\\"==typeof e?e:\\\"string\\\"==typeof e?!qo.has(e.trim().toLowerCase()):\\\"number\\\"==typeof e?0!==e:null!=e}(t);\\\"INPUT\\\"!==n.tagName||\\\"checkbox\\\"!==n.type?n.hasAttribute(\\\"aria-checked\\\")?n.setAttribute(\\\"aria-checked\\\",i?\\\"true\\\":\\\"false\\\"):n.textContent=i?\\\"true\\\":\\\"false\\\":n.checked=i}},Go=new Map,Ko=new Map,Jo=new Set([\\\"short\\\",\\\"medium\\\",\\\"long\\\",\\\"full\\\"]),Xo=new Set([\\\"short\\\",\\\"medium\\\",\\\"long\\\",\\\"full\\\"]),Qo=/^[A-Za-z]{3}$/u,Zo=/^[0-4]$/u,Yo=new WeakSet,es={name:\\\"date\\\",render(e,t,n){let i=e.element;if(Dt(t)){\\\"INPUT\\\"===i.tagName?i.value=\\\"\\\":(i.removeAttribute(\\\"datetime\\\"),i.textContent=\\\"\\\");return}let r=\\\"number\\\"==typeof t?t:Wt(t),l=new Date(r),o=!Number.isNaN(l.getTime()),s=String(r);\\\"INPUT\\\"!==i.tagName?(\\\"TIME\\\"===i.tagName&&i.setAttribute(\\\"datetime\\\",o?l.toISOString():s),i.textContent=o?function(e,t,n){let i=t.locale??n.locale??a(),r=qn(\\\"date\\\",t.format,t.element,t.fieldName)??ts;try{return function(e,t){let n=Bn(e,t);return Bt(Ko,n)??_t(Ko,n,new Intl.DateTimeFormat(e,t),64)}(i,r).format(e)}catch{return e.toISOString()}}(l,e,n):s):i.value=o?function(e,t){let n=`${String(t.getFullYear()).padStart(4,\\\"0\\\")}-${Hn(t.getMonth()+1)}-${Hn(t.getDate())}`,i=`${Hn(t.getHours())}:${Hn(t.getMinutes())}`;return\\\"date\\\"===e?n:\\\"datetime-local\\\"===e?`${n}T${i}`:\\\"time\\\"===e?i:t.toISOString()}(i.type,l):s}},ts={dateStyle:\\\"medium\\\",timeStyle:\\\"short\\\"},ns={name:\\\"number\\\",render(e,t,n){let i=e.element;if(Dt(t)){\\\"INPUT\\\"===i.tagName?i.value=\\\"\\\":i.textContent=\\\"\\\";return}let r=\\\"number\\\"==typeof t?t:Number(Wt(t));Number.isNaN(r)?i.textContent=Wt(t):\\\"INPUT\\\"!==i.tagName?i.textContent=function(e,t,n){let i=t.locale??n.locale??a(),r=qn(\\\"number\\\",t.format,t.element,t.fieldName);try{return function(e,t){let n=Bn(e,t);return Bt(Go,n)??_t(Go,n,new Intl.NumberFormat(e,t),64)}(i,r).format(e)}catch{return String(e)}}(r,e,n):i.value=String(r)}},is={name:\\\"array\\\",render:O((e,t,n)=>{let i=e.element;if(Dt(t)){i.textContent=\\\"\\\";return}if(!Array.isArray(t))return!1;let r=e.arrayTemplate;if(void 0!==r&&r.length>0){let e=function(e,t){let n=Pt(t),i=\\\"\\\";for(let r=0;r<t.length;r+=1)i+=Ut(e,t[r],r,Wt,n);return i}(r,t),l=n.sanitizerPolicy,o=zt(r),s=It(i);i.innerHTML=yt(Ft(e,l,o));for(let e of Array.from(i.children))jt(e,s);return}i.textContent=t.map(Wt).join(e.arraySeparator??\\\", \\\")})},rs=new Map;!function(){if(typ\",\"eof window>\\\"u\\\"||!an()&&(typ\",\"eof window>\\\"u\\\"||null==window.opener))return;let e=window.__livePreview,t=JSON.stringify(Zn());if(void 0!==e&&(void 0===e.configSignature||e.configSignature===t))return e.refresh(),e;let[n=[],r=\\\"\\\",l=\\\"/api\\\",o=1,s=!1,a=50,u=!0,d=0,c=!1,h=50,f=\\\"200px\\\",p=!0,g=!1,m=!1,v=!0,y=\\\"parent-or-opener\\\",b=\\\"strict\\\",w,S=!1,A=!1,k,T,C=\\\"off\\\",R,$,F=[],N=\\\"descendant\\\"]=Zn(),M=function(e){let t=typeof __LIVE_PREVIEW_FRAGMENT__<\\\"u\\\"?__LIVE_PREVIEW_FRAGMENT__:void 0,n=t??(typeof __LIVE_PREVIEW_ROUTE__<\\\"u\\\"?__LIVE_PREVIEW_ROUTE__:void 0);if(void 0===n)return;let i=n.createRouteStrategy();return void 0===t||void 0===e||\\\"\\\"===e?{route:i}:{fragment:t.createFragmentStrategy({endpoint:e}),route:i}}(w),O=new mo({additionalOrigins:n,enableReferrerDetection:!p,enableLocalhostMatching:!g});O.isProductionUnconfigured?ai(\\\"[live-preview] LP0101: No trusted origin. Pass allowedOrigins to generateInlineScript() (or to the adapter) \\\\u2014 the runtime reads no environment variable in the browser.\\\"):O.isReferrerOnlyTrust&&ai(\\\"[live-preview] LP0102: document.referrer fallback trusts any framing site. Set allowedOrigins and a frame-ancestors CSP in production.\\\");let E=new di,L=function(){let e=[xo,Po,Io,Wo,Bo,_o,zo,Vo,{...Vo,name:\\\"radio\\\"},Ho,es,ns,is,{...is,name:\\\"blocks\\\"}];return function(e=[]){let t={};for(let n of e)t[n.name]=n;for(let[e,n]of rs)t[e]=n;return Object.freeze(t)}([Nn(\\\"text\\\"),Nn(\\\"textarea\\\"),...e,Gn()])}(),x=new ho({renderers:L,originMatcher:e=>O.matches(e),lockedOrigin:()=>O.lockedOrigin,readyTargets:()=>O.enumerate(),emitter:E,eventSourcePolicy:y,...\\\"\\\"!==r?{dataMerge:{serverURL:r,apiRoute:l,depth:o}}:{},debounceMs:a,heartbeatMs:d,intersectionRootMargin:f,disableVisibilityGate:c,visibilityGateThreshold:h,enableA11y:u,scopeBindingsByOwner:m,subfieldCoverage:N,skipUnchanged:v,revealEditedField:S,onUnfaithfulPatch:i({onUnfaithfulPatch:T,onUnboundChange:k}),autoBind:C,...void 0!==R?{hydration:R}:{},sanitizerPolicy:b,...void 0!==M?{strategies:M}:{},onHeartbeatTimeout:()=>{O.unlockOrigin()},...s?{log:(...e)=>{ui(\\\"[live-preview]\\\",...e)}}:{}});E.on(\\\"connect\\\",e=>{O.lockOrigin(e.origin)}),x.start(),e?.destroy();let P=function(e,t={}){let n=t.windowTarget??globalThis.window,i=t.documentTarget??globalThis.document,r=[...new Set(t.softNavigationEvents??[])],l=()=>{e.suspend()},o=t=>{!0===t.persisted&&e.resume()},s=!1,a=()=>{s=!0},u=t=>{if(t.type===yo){if(!s)return;s=!1}void 0===e.refreshAfterNavigation?e.refreshCache():e.refreshAfterNavigation()},d=!1;n?.addEventListener(\\\"pagehide\\\",l),n?.addEventListener(\\\"pageshow\\\",o);for(let e of r)i?.addEventListener(e,u);let c=r.includes(yo);return c&&i?.addEventListener(bo,a),()=>{if(!d){d=!0,n?.removeEventListener(\\\"pagehide\\\",l),n?.removeEventListener(\\\"pageshow\\\",o);for(let e of r)i?.removeEventListener(e,u);c&&i?.removeEventListener(bo,a)}}}({suspend:()=>x.suspend(),resume:()=>x.start(),refreshCache:()=>{x.refreshCache()},refreshAfterNavigation:()=>{x.navigationCommit()}},{softNavigationEvents:F}),U=Object.freeze({version:Gr,configSignature:t,destroy:()=>{P(),x.destroy();let e=window;e.__livePreview===U&&delete e.__livePreview},refresh:()=>{x.refreshCache()},refreshAfterNavigation:()=>{x.navigationCommit()},enumerateOrigins:()=>O.enumerate(),inspect:()=>x.inspect()});try{Object.defineProperty(window,\\\"__livePreview\\\",{value:U,writable:!1,configurable:!0})}catch(e){throw P(),x.destroy(),e}}()})();\"].join('');\nexport const RUNTIME_CONTENT_HASH = \"7ceb6c62609b6651\";\nexport const RUNTIME_INTEGRITY = \"sha384-Coz2yqSNCoBvf+uVeMxz4rQRJmCxivWyUL9wIDH8oexgXTuEFgbzl6Xl+MuWaJta\";\nexport const RUNTIME_BUILD_INFO: RuntimeBuildInfo = { generatedAt: \"2026-10-26T03:01:14.000Z\", size: 145546 };\n","// Auto-generated by scripts/build-runtime.ts — do not edit.\nexport const FRAGMENT_SOURCE = /* @__PURE__ */ [\"\\\"use strict\\\";var __LIVE_PREVIEW_FRAGMENT__=(()=>{var P=Object.defineProperty;var fe=Object.getOwnPropertyDescriptor;var me=Object.getOwnPropertyNames;var ye=Object.prototype.hasOwnProperty;var pe=(e,t)=>{for(var n in t)P(e,n,{get:t[n],enumerable:!0})},ge=(e,t,n,i)=>{if(t&&typeof t==\\\"object\\\"||typeof t==\\\"function\\\")for(let o of me(t))!ye.call(e,o)&&o!==n&&P(e,o,{get:()=>t[o],enumerable:!(i=fe(t,o))||i.enumerable});return e};var he=e=>ge(P({},\\\"__esModule\\\",{value:!0}),e);var Ye={};pe(Ye,{createFragmentStrategy:()=>ce,createRouteStrategy:()=>ue});function k(e,t){let n=new AbortController,i=!1,o=()=>{n.abort()};e.addEventListener(\\\"abort\\\",o,{once:!0});let r=setTimeout(()=>{i=!0,n.abort()},t);return{signal:n.signal,timedOut:()=>i,dispose:()=>{clearTimeout(r),e.removeEventListener(\\\"abort\\\",o)}}}function R(e){return e instanceof Error?e.message:String(e)}var D=\\\"data-payload-island\\\",Qe=`astro-island, [${D}]`,w=\\\"data-payload-owned\\\",be=\\\"data-payload-morph\\\";function F(e){if(e.tagName.toLowerCase().includes(\\\"-\\\")&&!e.hasAttribute(be)||z(e)||e.hasAttribute(w))return!0;let n=e.getAttribute(\\\"contenteditable\\\");return n!==null&&n!==\\\"false\\\"}function Ee(e){return e.tagName.toLowerCase()===\\\"astro-island\\\"||e.hasAttribute(D)}function Se(e){return e.getAttribute(D)===\\\"patch\\\"}function z(e){return Ee(e)&&!Se(e)}function V(e){let t=e;for(;t!==null;){if(z(t))return!0;t=t.parentElement}return!1}var Re=[\\\"component-url\\\",\\\"component-export\\\",\\\"renderer-url\\\",\\\"client\\\",\\\"opts\\\",\\\"before-hydration-url\\\"],v=new WeakMap,G=new WeakSet;function W(e){return e.tagName.toLowerCase()===\\\"astro-island\\\"}function q(e){let t=\\\"\\\";for(let n of e.querySelectorAll(\\\"astro-slot, template[data-astro-template]\\\")){if(n.parentElement?.closest(\\\"astro-island\\\")!==e)continue;let i=n.getAttribute(\\\"name\\\")??n.getAttribute(\\\"data-astro-template\\\")??\\\"\\\";t+=`${i}\\\\0${n.innerHTML}\\\\0`}return t}function Ae(e){let t=e.ownerDocument.defaultView?.customElements.get(\\\"astro-island\\\");return t!==void 0&&e instanceof t&&Array.isArray(t.observedAttributes)&&t.observedAttributes.includes(\\\"props\\\")}function j(e,t){if(!W(e)||!W(t))return!0;let n=q(t);if(!(Re.every(r=>e.getAttribute(r)===t.getAttribute(r))&&(v.get(e)??q(e))===n&&(e.getAttribute(\\\"props\\\")===t.getAttribute(\\\"props\\\")||Ae(e))))return v.set(t,n),!1;v.set(e,n);let o=t.getAttribute(\\\"props\\\");return o!==e.getAttribute(\\\"props\\\")&&(e.setAttribute(\\\"ssr\\\",\\\"\\\"),o===null?e.removeAttribute(\\\"props\\\"):e.setAttribute(\\\"props\\\",o)),!0}function Y(e){return Array.from(e.querySelectorAll(\\\"astro-island\\\"))}function X(e){for(let t of e)t.isConnected||G.has(t)||(G.add(t),t.dispatchEvent(new CustomEvent(\\\"astro:unmount\\\")))}function O(e){if(e==null)return[];let t=new Set,n=[];for(let i of e.split(/[\\\\s,]+/)){let o=i.trim();o.length===0||t.has(o)||(t.add(o),n.push(o))}return n}var A=\\\"data-payload-fragment\\\",I=\\\"data-payload-fragment-key\\\";var Te=\\\"data-payload-depends\\\";function _(e){let t=e.getAttribute(A);if(t===null||t.length===0)return null;let n=e.getAttribute(I);return{element:e,id:t,key:n===null||n.length===0?void 0:n,dependsOn:O(e.getAttribute(Te))}}function J(e,t){let n=[];for(let i of e.querySelectorAll(`[${A}]`)){let o=_(i);o===null||V(i)||o.dependsOn.length>0&&!o.dependsOn.some(r=>t.has(r))||n.push(o)}return n}var Q=\\\"x-payload-fragment-version\\\";function B(e){return typeof e==\\\"object\\\"&&e!==null&&!Array.isArray(e)}function Z(e){if(!B(e))return null;let{html:t,boundary:n,revision:i,metadata:o}=e;return typeof t!=\\\"string\\\"||!B(n)||typeof n.id!=\\\"string\\\"||n.key!==void 0&&typeof n.key!=\\\"string\\\"||typeof i!=\\\"number\\\"||!B(o)||typeof o.renderedAt!=\\\"string\\\"||typeof o.renderer!=\\\"string\\\"?null:e}function ee(e){let t={};for(let[n,i]of Object.entries(e))i!==void 0&&(t[n]=i);return t}function L(e){return e.reason instanceof Error?e.reason:new DOMException(\\\"The operation was aborted.\\\",\\\"AbortError\\\")}function C(e){return e?.aborted===!0}function te(e){let t=0,n=[],i=()=>{let o=n.shift();o===void 0?t-=1:o.resume()};return async(o,r)=>{if(r!==void 0&&C(r))throw L(r);if(t<e)t+=1;else if(await new Promise((d,m)=>{let l=()=>{},u={resume:()=>{l(),d()}};if(n.push(u),r!==void 0){let s=()=>{let c=n.indexOf(u);c!==-1&&(n.splice(c,1),l(),m(L(r)))};l=()=>{r.removeEventListener(\\\"abort\\\",s)},r.addEventListener(\\\"abort\\\",s,{once:!0}),C(r)&&s()}}),r!==void 0&&C(r))throw i(),L(r);try{return await o()}finally{i()}}}var xe=5e3,ke=4,Fe=512*1024,T={status:\\\"superseded\\\"};function b(e,t){return{status:\\\"failed\\\",code:e,reason:t}}function Oe(e){let t=()=>{throw new TypeError('createFragmentStrategy: endpoint must be a same-origin path starting with \\\"/\\\"')};if((typeof e!=\\\"string\\\"||!e.startsWith(\\\"/\\\")||e.startsWith(\\\"//\\\")||e.includes(\\\"\\\\\\\\\\\"))&&t(),typeof location<\\\"u\\\"){let n;try{n=new URL(e,location.href)}catch{n=void 0}n?.origin!==location.origin&&t()}return e}function Ie(e){return typeof e==\\\"object\\\"&&e!==null&&typeof e.getReader==\\\"function\\\"}async function Ne(e,t,n){let i=e.body;if(!Ie(i)){let u=await e.text();return new TextEncoder().encode(u).byteLength>t?null:u}let o=i.getReader(),r=()=>{o.cancel().catch(()=>{})};n.addEventListener(\\\"abort\\\",r,{once:!0});let d=new TextDecoder,m=\\\"\\\",l=0;try{for(;;){let{done:u,value:s}=await o.read();if(u)break;if(l+=s.byteLength,l>t)return r(),null;m+=d.decode(s,{stream:!0})}}finally{n.removeEventListener(\\\"abort\\\",r),o.releaseLock()}return m+d.decode()}function ne(e){let t=Oe(e.endpoint),n=e.timeoutMs??xe,i=e.maxResponseBytes??Fe,o=te(Math.max(1,e.maxConcurrent??ke)),r=new Map,d=new WeakMap,m=0,l=s=>{let c=d.get(s);return c!==void 0?c:(m+=1,d.set(s,m),m)};async function u(s,c){let a=()=>s.signal.aborted;if(a())return T;let h=e.location??location,p=ee({fragment:c.id,key:c.key,route:h.pathname,search:h.search,revision:s.revision,locale:s.locale,collectionSlug:s.collectionSlug,globalSlug:s.globalSlug,fields:s.fields}),f=k(s.signal,n),y=E=>a()?T:f.timedOut()?b(\\\"LP0801\\\",`timeout after ${String(n)} ms`):b(\\\"LP0801\\\",R(E)),g,x=!1;try{try{g=await(e.fetch??fetch)(t,{method:\\\"POST\\\",credentials:\\\"same-origin\\\",headers:{...e.headers,accept:\\\"application/json\\\",\\\"content-type\\\":\\\"application/json\\\",[Q]:String(1)},body:JSON.stringify(p),signal:f.signal})}catch(M){return y(M)}if(a())return T;if(g.status===401||g.status===403)return b(\\\"LP0803\\\",`endpoint refused the preview (${String(g.status)})`);if(!g.ok)return b(\\\"LP0801\\\",`endpoint answered ${String(g.status)}`);let E=g.headers.get(\\\"content-type\\\")??\\\"\\\";if(!E.toLowerCase().startsWith(\\\"application/json\\\"))return b(\\\"LP0802\\\",`unexpected content type \\\"${E}\\\"`);if(Number(g.headers.get(\\\"content-length\\\")??\\\"0\\\")>i)return b(\\\"LP0802\\\",\\\"response exceeds the size limit\\\");if(f.signal.aborted)return y(f.signal.reason);let N;try{x=!0,N=await Ne(g,i,f.signal)}catch(M){return y(M)}if(a())return T;if(f.timedOut())return b(\\\"LP0801\\\",`timeout after ${String(n)} ms`);if(N===null)return b(\\\"LP0802\\\",\\\"response exceeds the size limit\\\");let $;try{$=JSON.parse(N)}catch{return b(\\\"LP0802\\\",\\\"response is not JSON\\\")}let S=Z($);return S===null?b(\\\"LP0802\\\",\\\"response has the wrong shape\\\"):S.boundary.id!==c.id||S.boundary.key!==c.key?b(\\\"LP0802\\\",\\\"response is for another boundary\\\"):S.revision!==s.revision?T:{status:\\\"rendered\\\",html:S.html,metadata:S.metadata}}finally{if(f.dispose(),g!==void 0&&!x)try{g.body?.cancel().catch(()=>{})}catch{}}}return(s,c)=>{let a=JSON.stringify([l(s.signal),c.id,c.key,s.revision]),h=r.get(a);if(h!==void 0)return h;let p=!1,f=o(()=>(p=!0,u(s,c)),s.signal).catch(g=>{if(!p&&s.signal.aborted)return T;throw g});r.set(a,f);let y=()=>{r.get(a)===f&&r.delete(a)};return f.then(y,y),f}}var Me=new Set([\\\"open\\\",\\\"value\\\",\\\"checked\\\",\\\"selected\\\"]);function oe(e,t){for(let n of t.keyAttributes){let i=e.getAttribute(n);if(i!==null&&i.length>0)return`${n}=${i}`}}function H(e,t,n){if(!U(e,t))return t;let i=n.boundary??F,o=i(e),r=i(t);if(o||r)return!o||!r?t:n.retainBoundary?.(e,t)??!0?e:t;let d=Be(e);return Pe(e,t),n.retainChildrenOf?.(e,t)!==!0&&ve(e,t,n),Le(d),e}function Pe(e,t){for(let n of Array.from(e.attributes))t.hasAttribute(n.name)||Me.has(n.name.toLowerCase())||e.removeAttribute(n.name);for(let n of Array.from(t.attributes))e.getAttribute(n.name)!==n.value&&e.setAttribute(n.name,n.value)}function ve(e,t,n){let i=_e(e,n),o=new Set(i.values()),r=Array.from(e.childNodes).filter(c=>!o.has(c)),d=new Set,m=new Set,l=Array.from(t.childNodes),u=e.firstChild,s=0;for(let c=0;c<l.length;c+=1){let a=l[c],h=null,p=a instanceof Element?oe(a,n):void 0;if(p!==void 0&&m.has(p)&&(p=void 0),p!==void 0){m.add(p);let y=i.get(p);if(y!==void 0&&!d.has(y)&&(h=re(y,a,n)===y?y:null,h===null)){y.replaceWith(a),d.add(a),u=a.nextSibling;continue}}else{for(;s<r.length;){let y=r[s];if(s+=1,!d.has(y)){if(U(y,a)){h=re(y,a,n)===y?y:null,h===null&&(e.replaceChild(a,y),d.add(a),u=a.nextSibling);break}if(y instanceof Element){let g=l[c+1];if(!(a instanceof Element)||g!==void 0&&U(y,g)){s-=1;break}e.replaceChild(a,y),d.add(a),u=a.nextSibling;break}if(!(a instanceof Element)){e.replaceChild(a,y),d.add(a),u=a.nextSibling;break}}}if(h===null&&d.has(a))continue}let f=h??a;for(d.add(f);u!==null&&u!==f&&!d.has(u)&&De(u);)u=u.nextSibling;f!==u&&e.insertBefore(f,u),u=f.nextSibling}for(let c of Array.from(e.childNodes))d.has(c)||c.remove()}function re(e,t,n){return e instanceof Element&&t instanceof Element?H(e,t,n):(e.nodeValue!==t.nodeValue&&(e.nodeValue=t.nodeValue),e)}function De(e){return e.nodeType===Node.TEXT_NODE&&(e.nodeValue??\\\"\\\").trim().length===0}function U(e,t){return e.nodeType!==t.nodeType?!1:e instanceof Element&&t instanceof Element?e.tagName===t.tagName&&e.namespaceURI===t.namespaceURI:!0}function _e(e,t){let n=new Map,i;for(let o of Array.from(e.children)){let r=oe(o,t);if(r!==void 0){if(n.has(r)){i??(i=r.slice(r.indexOf(\\\"=\\\")+1));continue}n.set(r,o)}}return i!==void 0&&t.onDuplicateKey?.(e,i),n}function Be(e){let t=e.ownerDocument.activeElement;if(!(t instanceof HTMLElement)||!e.contains(t))return null;let n=t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement?[t.selectionStart,t.selectionEnd]:null;return{element:t,selection:n}}function Le(e){if(e===null)return;let{element:t,selection:n}=e;if(!(t.ownerDocument.activeElement===t||!t.isConnected))try{t.focus({preventScroll:!0});let[i,o]=n??[null,null];i!==null&&o!==null&&t.setSelectionRange(i,o)}catch{}}var ie=\\\"data-payload-key\\\";var Ce=\\\"__livePreviewRouteRefresh\\\";function Ue(){return typ\",\"eof window>\\\"u\\\"?void 0:window}function ae(){return Ue()?.[Ce]}var le=\\\"data-payload-strategy\\\",de=\\\"data-payload-field\\\",He=\\\"data-payload-depends\\\",Ke=\\\"x-payload-live-preview\\\",$e=8e3,Ge=\\\"route refresh returned no promise; re-applied before the host committed (see LivePreviewRouteRefresh)\\\",We=1e3;function qe(e){let t=e.getAttribute(le);return t!==null?t===\\\"route\\\":e.closest(\\\"head\\\")!==null}function ze(e){let t=e.getAttribute(de),n=O(e.getAttribute(He));return t===null||t.length===0?n:[t,...n]}function se(e){return e.hasAttribute(w)?!1:e.tagName===\\\"META\\\"?e.hasAttribute(\\\"name\\\")||e.hasAttribute(\\\"property\\\"):e.tagName===\\\"LINK\\\"&&e.getAttribute(\\\"rel\\\")===\\\"canonical\\\"}function Ve(e,t){let n=Array.from(e.head.children).find(l=>l.tagName===\\\"TITLE\\\"),i=Array.from(t.head.children).find(l=>l.tagName===\\\"TITLE\\\");!n?.hasAttribute(w)&&!i?.hasAttribute(w)&&t.title!==e.title&&(e.title=t.title);let o=Array.from(e.head.children).filter(se),r=Array.from(t.head.children).filter(se),d=Math.min(o.length,r.length);o.slice(0,d).forEach((l,u)=>{let s=r[u];if(s===void 0)return;if(l.tagName===s.tagName){for(let a of Array.from(l.attributes))s.hasAttribute(a.name)||l.removeAttribute(a.name);for(let a of Array.from(s.attributes))l.getAttribute(a.name)!==a.value&&l.setAttribute(a.name,a.value);return}let c=e.importNode(s,!0);l.replaceWith(c),o[u]=c});let m=o.at(-1);for(let l of r.slice(o.length)){let u=e.importNode(l,!0);m===void 0?e.head.append(u):m.after(u),m=u}for(let l of o.slice(r.length))l.remove()}function ue(e={}){let t=e.timeoutMs??$e,n=e.minIntervalMs??We,i=-1/0,o=!1;return{plan(r,d,m){for(let l of r.querySelectorAll(`[${de}], [${le}=\\\"route\\\"]`)){if(!qe(l)||m?.inScope(l)===!1)continue;let u=ze(l);if(u.length===0||u.some(s=>d.has(s)))return!0}return!1},async refresh(r){let d=Date.now(),m=n-(d-i);if(m>0)return r.retryAfter?.(m),r.log(\\\"LP0805\\\",`route refresh for revision ${String(r.revision)} refused: the previous one was ${String(d-i)} ms ago`),\\\"refused\\\";i=d;let l=e.document??document,u=e.location??location,s=e.window??window,c=k(r.signal,t),a=h=>{if(r.signal.aborted)return\\\"superseded\\\";let p=c.timedOut()?`route refresh timed out after ${String(t)} ms`:R(h);return r.log(\\\"LP0801\\\",p),\\\"failed\\\"};try{let h=ae();if(h!==void 0){try{let f=h();typeof f?.then!=\\\"function\\\"&&!o&&(o=!0,r.log(\\\"LP0810\\\",Ge)),await f}catch(f){return a(f)}return r.isCurrent()?\\\"partial\\\":\\\"superseded\\\"}let p;try{p=await(e.fetch??fetch)(u.href,{method:\\\"GET\\\",credentials:\\\"same-origin\\\",cache:\\\"no-store\\\",headers:{accept:\\\"text/html\\\",[Ke]:\\\"route\\\"},signal:c.signal})}catch(f){return a(f)}if(r.signal.aborted)return\\\"superseded\\\";if(!p.ok||!(p.headers.get(\\\"content-type\\\")??\\\"\\\").includes(\\\"text/html\\\"))return r.log(\\\"LP0802\\\",`route answered ${String(p.status)} ${p.headers.get(\\\"content-type\\\")??\\\"\\\"}`),\\\"failed\\\";try{let f=await p.text();if(!r.isCurrent())return\\\"superseded\\\";let y=new DOMParser().parseFromString(f,\\\"text/html\\\"),g=s.scrollX,x=s.scrollY;Ve(l,y);let E=Y(l.body);return H(l.body,y.body,{boundary:F,retainBoundary:j,keyAttributes:[ie,I,A],retainChildrenOf:K=>K.hasAttribute(A)}),X(E),s.scrollTo(g,x),\\\"partial\\\"}catch(f){return a(f)}}finally{c.dispose()}}}}function je(e){return{plan:(t,n)=>J(t,n).map(i=>i.element),async render(t,n){let i={rendered:0,failed:0,superseded:0},o={revision:t.revision,receivedAt:t.receivedAt,fields:t.fields,locale:t.locale,collectionSlug:t.collectionSlug,globalSlug:t.globalSlug,signal:t.signal};return await Promise.all(n.map(async r=>{let d=_(r);if(d===null)return;let m;try{m=await e(o,d)}catch(l){m={status:\\\"failed\\\",code:\\\"LP0801\\\",reason:R(l)}}if(!t.isCurrent()||m.status===\\\"superseded\\\"){i.superseded+=1,t.log(\\\"LP0804\\\",`fragment \\\"${d.id}\\\" for revision ${String(o.revision)} discarded as superseded`);return}if(m.status===\\\"rendered\\\"){t.morph(r,m.html),t.rendered(r,d.id,d.key),i.rendered+=1;return}t.failed(r,d.id,d.key,m.code,m.reason),t.isCurrent()&&t.patch(r),i.failed+=1})),i}}}function ce(e){return je(ne(e))}return he(Ye);})();\"].join('');\n","// Auto-generated by scripts/build-runtime.ts — do not edit.\nexport const ROUTE_SOURCE = /* @__PURE__ */ [\"\\\"use strict\\\";var __LIVE_PREVIEW_ROUTE__=(()=>{var S=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var V=Object.getOwnPropertyNames;var j=Object.prototype.hasOwnProperty;var X=(e,t)=>{for(var n in t)S(e,n,{get:t[n],enumerable:!0})},J=(e,t,n,i)=>{if(t&&typeof t==\\\"object\\\"||typeof t==\\\"function\\\")for(let r of V(t))!j.call(e,r)&&r!==n&&S(e,r,{get:()=>t[r],enumerable:!(i=G(t,r))||i.enumerable});return e};var Q=e=>J(S({},\\\"__esModule\\\",{value:!0}),e);var Re={};X(Re,{createRouteStrategy:()=>W});var T=\\\"data-payload-island\\\",xe=`astro-island, [${T}]`,E=\\\"data-payload-owned\\\",Z=\\\"data-payload-morph\\\";function h(e){if(e.tagName.toLowerCase().includes(\\\"-\\\")&&!e.hasAttribute(Z)||ne(e)||e.hasAttribute(E))return!0;let n=e.getAttribute(\\\"contenteditable\\\");return n!==null&&n!==\\\"false\\\"}function ee(e){return e.tagName.toLowerCase()===\\\"astro-island\\\"||e.hasAttribute(T)}function te(e){return e.getAttribute(T)===\\\"patch\\\"}function ne(e){return ee(e)&&!te(e)}var re=[\\\"component-url\\\",\\\"component-export\\\",\\\"renderer-url\\\",\\\"client\\\",\\\"opts\\\",\\\"before-hydration-url\\\"],R=new WeakMap,I=new WeakSet;function N(e){return e.tagName.toLowerCase()===\\\"astro-island\\\"}function M(e){let t=\\\"\\\";for(let n of e.querySelectorAll(\\\"astro-slot, template[data-astro-template]\\\")){if(n.parentElement?.closest(\\\"astro-island\\\")!==e)continue;let i=n.getAttribute(\\\"name\\\")??n.getAttribute(\\\"data-astro-template\\\")??\\\"\\\";t+=`${i}\\\\0${n.innerHTML}\\\\0`}return t}function oe(e){let t=e.ownerDocument.defaultView?.customElements.get(\\\"astro-island\\\");return t!==void 0&&e instanceof t&&Array.isArray(t.observedAttributes)&&t.observedAttributes.includes(\\\"props\\\")}function v(e,t){if(!N(e)||!N(t))return!0;let n=M(t);if(!(re.every(o=>e.getAttribute(o)===t.getAttribute(o))&&(R.get(e)??M(e))===n&&(e.getAttribute(\\\"props\\\")===t.getAttribute(\\\"props\\\")||oe(e))))return R.set(t,n),!1;R.set(e,n);let r=t.getAttribute(\\\"props\\\");return r!==e.getAttribute(\\\"props\\\")&&(e.setAttribute(\\\"ssr\\\",\\\"\\\"),r===null?e.removeAttribute(\\\"props\\\"):e.setAttribute(\\\"props\\\",r)),!0}function D(e){return Array.from(e.querySelectorAll(\\\"astro-island\\\"))}function P(e){for(let t of e)t.isConnected||I.has(t)||(I.add(t),t.dispatchEvent(new CustomEvent(\\\"astro:unmount\\\")))}var ie=new Set([\\\"open\\\",\\\"value\\\",\\\"checked\\\",\\\"selected\\\"]);function C(e,t){for(let n of t.keyAttributes){let i=e.getAttribute(n);if(i!==null&&i.length>0)return`${n}=${i}`}}function w(e,t,n){if(!x(e,t))return t;let i=n.boundary??h,r=i(e),o=i(t);if(r||o)return!r||!o?t:n.retainBoundary?.(e,t)??!0?e:t;let d=ue(e);return ae(e,t),n.retainChildrenOf?.(e,t)!==!0&&le(e,t,n),ce(d),e}function ae(e,t){for(let n of Array.from(e.attributes))t.hasAttribute(n.name)||ie.has(n.name.toLowerCase())||e.removeAttribute(n.name);for(let n of Array.from(t.attributes))e.getAttribute(n.name)!==n.value&&e.setAttribute(n.name,n.value)}function le(e,t,n){let i=de(e,n),r=new Set(i.values()),o=Array.from(e.childNodes).filter(f=>!r.has(f)),d=new Set,p=new Set,l=Array.from(t.childNodes),s=e.firstChild,c=0;for(let f=0;f<l.length;f+=1){let a=l[f],g=null,y=a instanceof Element?C(a,n):void 0;if(y!==void 0&&p.has(y)&&(y=void 0),y!==void 0){p.add(y);let u=i.get(y);if(u!==void 0&&!d.has(u)&&(g=B(u,a,n)===u?u:null,g===null)){u.replaceWith(a),d.add(a),s=a.nextSibling;continue}}else{for(;c<o.length;){let u=o[c];if(c+=1,!d.has(u)){if(x(u,a)){g=B(u,a,n)===u?u:null,g===null&&(e.replaceChild(a,u),d.add(a),s=a.nextSibling);break}if(u instanceof Element){let b=l[f+1];if(!(a instanceof Element)||b!==void 0&&x(u,b)){c-=1;break}e.replaceChild(a,u),d.add(a),s=a.nextSibling;break}if(!(a instanceof Element)){e.replaceChild(a,u),d.add(a),s=a.nextSibling;break}}}if(g===null&&d.has(a))continue}let m=g??a;for(d.add(m);s!==null&&s!==m&&!d.has(s)&&se(s);)s=s.nextSibling;m!==s&&e.insertBefore(m,s),s=m.nextSibling}for(let f of Array.from(e.childNodes))d.has(f)||f.remove()}function B(e,t,n){return e instanceof Element&&t instanceof Element?w(e,t,n):(e.nodeValue!==t.nodeValue&&(e.nodeValue=t.nodeValue),e)}function se(e){return e.nodeType===Node.TEXT_NODE&&(e.nodeValue??\\\"\\\").trim().length===0}function x(e,t){return e.nodeType!==t.nodeType?!1:e instanceof Element&&t instanceof Element?e.tagName===t.tagName&&e.namespaceURI===t.namespaceURI:!0}function de(e,t){let n=new Map,i;for(let r of Array.from(e.children)){let o=C(r,t);if(o!==void 0){if(n.has(o)){i??(i=o.slice(o.indexOf(\\\"=\\\")+1));continue}n.set(o,r)}}return i!==void 0&&t.onDuplicateKey?.(e,i),n}function ue(e){let t=e.ownerDocument.activeElement;if(!(t instanceof HTMLElement)||!e.contains(t))return null;let n=t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement?[t.selectionStart,t.selectionEnd]:null;return{element:t,selection:n}}function ce(e){if(e===null)return;let{element:t,selection:n}=e;if(!(t.ownerDocument.activeElement===t||!t.isConnected))try{t.focus({preventScroll:!0});let[i,r]=n??[null,null];i!==null&&r!==null&&t.setSelectionRange(i,r)}catch{}}var O=\\\"data-payload-key\\\";function _(e){if(e==null)return[];let t=new Set,n=[];for(let i of e.split(/[\\\\s,]+/)){let r=i.trim();r.length===0||t.has(r)||(t.add(r),n.push(r))}return n}var fe=\\\"__livePreviewRouteRefresh\\\";function me(){return typ\",\"eof window>\\\"u\\\"?void 0:window}function F(){return me()?.[fe]}var A=\\\"data-payload-fragment\\\",k=\\\"data-payload-fragment-key\\\";function L(e,t){let n=new AbortController,i=!1,r=()=>{n.abort()};e.addEventListener(\\\"abort\\\",r,{once:!0});let o=setTimeout(()=>{i=!0,n.abort()},t);return{signal:n.signal,timedOut:()=>i,dispose:()=>{clearTimeout(o),e.removeEventListener(\\\"abort\\\",r)}}}function U(e){return e instanceof Error?e.message:String(e)}var H=\\\"data-payload-strategy\\\",$=\\\"data-payload-field\\\",ye=\\\"data-payload-depends\\\",pe=\\\"x-payload-live-preview\\\",ge=8e3,Ee=\\\"route refresh returned no promise; re-applied before the host committed (see LivePreviewRouteRefresh)\\\",be=1e3;function he(e){let t=e.getAttribute(H);return t!==null?t===\\\"route\\\":e.closest(\\\"head\\\")!==null}function Ae(e){let t=e.getAttribute($),n=_(e.getAttribute(ye));return t===null||t.length===0?n:[t,...n]}function K(e){return e.hasAttribute(E)?!1:e.tagName===\\\"META\\\"?e.hasAttribute(\\\"name\\\")||e.hasAttribute(\\\"property\\\"):e.tagName===\\\"LINK\\\"&&e.getAttribute(\\\"rel\\\")===\\\"canonical\\\"}function Se(e,t){let n=Array.from(e.head.children).find(l=>l.tagName===\\\"TITLE\\\"),i=Array.from(t.head.children).find(l=>l.tagName===\\\"TITLE\\\");!n?.hasAttribute(E)&&!i?.hasAttribute(E)&&t.title!==e.title&&(e.title=t.title);let r=Array.from(e.head.children).filter(K),o=Array.from(t.head.children).filter(K),d=Math.min(r.length,o.length);r.slice(0,d).forEach((l,s)=>{let c=o[s];if(c===void 0)return;if(l.tagName===c.tagName){for(let a of Array.from(l.attributes))c.hasAttribute(a.name)||l.removeAttribute(a.name);for(let a of Array.from(c.attributes))l.getAttribute(a.name)!==a.value&&l.setAttribute(a.name,a.value);return}let f=e.importNode(c,!0);l.replaceWith(f),r[s]=f});let p=r.at(-1);for(let l of o.slice(r.length)){let s=e.importNode(l,!0);p===void 0?e.head.append(s):p.after(s),p=s}for(let l of r.slice(o.length))l.remove()}function W(e={}){let t=e.timeoutMs??ge,n=e.minIntervalMs??be,i=-1/0,r=!1;return{plan(o,d,p){for(let l of o.querySelectorAll(`[${$}], [${H}=\\\"route\\\"]`)){if(!he(l)||p?.inScope(l)===!1)continue;let s=Ae(l);if(s.length===0||s.some(c=>d.has(c)))return!0}return!1},async refresh(o){let d=Date.now(),p=n-(d-i);if(p>0)return o.retryAfter?.(p),o.log(\\\"LP0805\\\",`route refresh for revision ${String(o.revision)} refused: the previous one was ${String(d-i)} ms ago`),\\\"refused\\\";i=d;let l=e.document??document,s=e.location??location,c=e.window??window,f=L(o.signal,t),a=g=>{if(o.signal.aborted)return\\\"superseded\\\";let y=f.timedOut()?`route refresh timed out after ${String(t)} ms`:U(g);return o.log(\\\"LP0801\\\",y),\\\"failed\\\"};try{let g=F();if(g!==void 0){try{let m=g();typeof m?.then!=\\\"function\\\"&&!r&&(r=!0,o.log(\\\"LP0810\\\",Ee)),await m}catch(m){return a(m)}return o.isCurrent()?\\\"partial\\\":\\\"superseded\\\"}let y;try{y=await(e.fetch??fetch)(s.href,{method:\\\"GET\\\",credentials:\\\"same-origin\\\",cache:\\\"no-store\\\",headers:{accept:\\\"text/html\\\",[pe]:\\\"route\\\"},signal:f.signal})}catch(m){return a(m)}if(o.signal.aborted)return\\\"superseded\\\";if(!y.ok||!(y.headers.get(\\\"content-type\\\")??\\\"\\\").includes(\\\"text/html\\\"))return o.log(\\\"LP0802\\\",`route answered ${String(y.status)} ${y.headers.get(\\\"content-type\\\")??\\\"\\\"}`),\\\"failed\\\";try{let m=await y.text();if(!o.isCurrent())return\\\"superseded\\\";let u=new DOMParser().parseFromString(m,\\\"text/html\\\"),b=c.scrollX,q=c.scrollY;Se(l,u);let z=D(l.body);return w(l.body,u.body,{boundary:h,retainBoundary:v,keyAttributes:[O,k,A],retainChildrenOf:Y=>Y.hasAttribute(A)}),P(z),c.scrollTo(b,q),\\\"partial\\\"}catch(m){return a(m)}}finally{f.dispose()}}}}return Q(Re);})();\"].join('');\n","// Auto-generated by scripts/build-runtime.ts — do not edit.\nexport const LOADER_SOURCE: string = /* @__PURE__ */ [\"\\\"use strict\\\";(()=>{function o(){if(typ\",\"eof window>\\\"u\\\")return!1;try{return window.self!==window.top}catch{return!0}}function t(){return typ\",\"eof window>\\\"u\\\"?!1:window.opener!=null}function e(){return o()||t()}function i(){let n=document.createElement(\\\"script\\\");n.src=__LP_RUNTIME_SRC__,__LP_RUNTIME_INTEGRITY__!==\\\"\\\"&&(n.integrity=__LP_RUNTIME_INTEGRITY__,n.crossOrigin=\\\"anonymous\\\"),n.async=!0,document.head.appendChild(n)}e()&&i();})();\"].join('');\n","// Auto-generated by scripts/build-runtime.ts — do not edit.\nexport const LOADER_REACT_SOURCE: string = /* @__PURE__ */ [\"\\\"use strict\\\";(()=>{function c(){if(typ\",\"eof window>\\\"u\\\")return!1;try{return window.self!==window.top}catch{return!0}}function s(){return typ\",\"eof window>\\\"u\\\"?!1:window.opener!=null}function r(){return c()||s()}var i=\\\"__livePreviewHydration\\\";function f(){if(typ\",\"eof window>\\\"u\\\")return;let e=window;return e[i]??(e[i]={armed:!1,committed:!1,commits:[],onCommit:void 0,waiters:[]})}function d(){let e=f();if(e===void 0||e.armed)return;e.armed=!0;let n=window,o=n.__REACT_DEVTOOLS_GLOBAL_HOOK__??(n.__REACT_DEVTOOLS_GLOBAL_HOOK__=m()),u=o.onCommitFiberRoot;o.onCommitFiberRoot=function(a,t,...l){try{u?.call(this,a,t,...l)}catch{}e.onCommit===void 0?e.commits.push(t):e.onCommit(t)}}function m(){let e=new Map;return{supportsFiber:!0,renderers:e,inject:n=>{let o=e.size+1;return e.set(o,n),o}}}function p(){let e=document.createElement(\\\"script\\\");e.src=__LP_RUNTIME_SRC__,__LP_RUNTIME_INTEGRITY__!==\\\"\\\"&&(e.integrity=__LP_RUNTIME_INTEGRITY__,e.crossOrigin=\\\"anonymous\\\"),e.async=!0,document.head.appendChild(e)}d();r()&&p();})();\"].join('');\n","/**\n * The inline script's configuration and its positional wire order: the\n * generator writes the tuple, `src/core/runtime.ts` destructures it, and\n * `INLINE_CONFIG_KEYS` is where they agree. Append only, never reorder.\n */\n\nimport type { DefaultsProfile } from '@/types/defaults-profile';\n\nexport interface InlineScriptConfig {\n /** Trusted admin origins, merged with the detected ones. */\n readonly allowedOrigins?: readonly string[];\n /** Payload origin; every update is then re-fetched through the REST API with credentials. Requires `mergeDepth`. */\n readonly serverURL?: string;\n /** REST route prefix used with `serverURL`. Default `/api`. */\n readonly apiRoute?: string;\n /** Population depth used with `serverURL`. Required with `serverURL` unless `defaults: 'v1'`. */\n readonly mergeDepth?: number;\n /** Verbose console logging. Default `false`. */\n readonly debug?: boolean;\n /** Debounce window for incoming updates in ms. Default `50`. */\n readonly debounceMs?: number;\n /** Mount the screen-reader live region. Default `true`. */\n readonly enableA11y?: boolean;\n /** Heartbeat timeout in ms; `0` disables it (default), because the admin posts only on edits. */\n readonly heartbeatMs?: number;\n /** Apply every update regardless of viewport position. Default `false`. */\n readonly disableVisibilityGate?: boolean;\n /** Cache size above which off-screen updates wait for intersection. Default `50`. */\n readonly visibilityGateThreshold?: number;\n /** `rootMargin` of the IntersectionObserver. Default `'200px'`. */\n readonly intersectionRootMargin?: string;\n /** Ignore `document.referrer` as an origin source. Default `true`; `defaults: 'v1'` sets `false`. */\n readonly disableReferrerDetection?: boolean;\n /** Disable the dev-mode localhost matcher (any port on `localhost`/`127.0.0.1`). Default `false`. */\n readonly disableLocalhostMatching?: boolean;\n /** Update only bindings under a matching `data-payload-owner`. Default `false`. */\n readonly scopeBindingsByOwner?: boolean;\n /** Skip bindings whose value did not change. Default `true`; `defaults: 'v1'` sets `false`. */\n readonly skipUnchanged?: boolean;\n /** Scroll the preview to the field being edited. Default `false`. */\n readonly revealEditedField?: boolean;\n /** Which windows may post updates. Default `'parent-or-opener'`; `defaults: 'v1'` sets `'any'`. */\n readonly eventSourcePolicy?: 'any' | 'parent-or-opener';\n /** Sanitizer policy for rich text and HTML writes. Default `'strict'`; `defaults: 'v1'` sets `'compat'`. */\n readonly sanitizerPolicy?: 'compat' | 'strict';\n /** Same-origin path of a fragment endpoint; the script then carries the fragment client ahead of the runtime (ADR 0011). */\n readonly fragmentEndpoint?: string;\n /**\n * Carry the route strategy, so a binding in `<head>` or one marked\n * `data-payload-strategy=\"route\"` refreshes the route. `fragmentEndpoint`\n * implies it — the fragment prelude already contains it. Default `false`.\n */\n readonly routeStrategy?: boolean;\n /**\n * The 2.0 name for `onUnfaithfulPatch`, kept until 3.0. `'route'` means\n * `'escalate'`, `'ignore'` means `'ignore'`.\n *\n * @deprecated Renamed to `onUnfaithfulPatch`.\n */\n readonly onUnboundChange?: 'ignore' | 'route';\n /**\n * What to do when the runtime knows a patch cannot reach what the server\n * would have drawn. `'escalate'` (the default) hands the region to the\n * fragment strategy when a boundary covers it and to the route otherwise, so\n * it needs `fragmentEndpoint` or `routeStrategy` to do anything. `'warn'`\n * reports LP0411 and keeps the patch; `'ignore'` keeps it silently.\n */\n readonly onUnfaithfulPatch?: 'ignore' | 'warn' | 'escalate';\n /**\n * Find bindings by value on the connection's first message (ADR 0014): a\n * scalar whose value is the whole content of exactly one element is bound\n * to it as if `data-payload-field` stood there. Default `'off'`.\n */\n readonly autoBind?: 'off' | 'unique';\n /**\n * The framework that hydrates this page (ADR 0015). Under `'react'` the\n * runtime holds its first write until React has committed the tree that\n * holds the bindings — otherwise React finds markup it did not render,\n * throws `Hydration failed` and regenerates the tree, and the write is gone.\n * Under `'vue'` it holds the write until Vue has mounted the app around them\n * — otherwise Vue's hydration repairs the write back to the server's value,\n * quietly. Under `'sveltekit'` it holds the write until SvelteKit's root has\n * mounted, on a page SvelteKit's client runs on — otherwise Svelte's\n * hydration sets its own text back over it, as quietly. The Next.js, Nuxt\n * and SvelteKit adapters set it on every script they emit; a page built by\n * hand with `generateInlineScript()` may. Omitted: the runtime starts on\n * `DOMContentLoaded`, as on a static page.\n */\n readonly hydration?: 'react' | 'vue' | 'sveltekit';\n /**\n * Which defaults the omitted options fall back to, resolved by the generator\n * rather than the runtime, whose own fallbacks are the 2.0 rows: `'v1'`\n * writes its four runtime rows into their slots (an explicit option still\n * wins) and relaxes the `mergeDepth` check. The resolved value always\n * travels in slot 24, so a reader of the served page knows what an\n * empty slot means instead of guessing it — `pll doctor --v2` reads it. The\n * runtime does not use that value: every row the profile decides is already\n * in its slot. Slot 24 stays fixed as later options are appended.\n */\n readonly defaults?: DefaultsProfile;\n /**\n * Document events fired after a client router committed new markup. Each\n * rebuilds the binding cache and locally reapplies the last accepted state.\n * Adapter integrations set this from their framework lifecycle. It is a\n * low-level generator fact, not a `PreviewAdapterOptions` field. Empty by\n * default.\n */\n readonly softNavigationEvents?: readonly string[];\n /**\n * How a group counts as covered (ADR 0022). `'descendant'`, the 2.x default:\n * one bound path inside it covers all of it. `'declared'`: each changed path\n * inside such a group needs its own binding or a `data-payload-covers`\n * declaration; an uncovered one is an unbound change.\n */\n readonly subfieldCoverage?: 'descendant' | 'declared';\n /**\n * A runtime artifact to embed instead of the full one — today only\n * `LEAN_RUNTIME` from `payload-live-preview/lean`, which leaves out the\n * strategies, the keyed morph, the structural arrays, the item templates, the\n * announcer and auto-binding (about 7 KB gzip less on the page) and reports\n * LP0104 when a page needs one of them.\n *\n * It is an imported value rather than a `profile: 'lean'` string on purpose:\n * a second artifact behind a string option would sit in every build that can\n * reach the generator; measured, it grew each adapter entry by the artifact's\n * whole size. This way the bytes follow the import.\n *\n * Not serialized: it decides which bytes are emitted, not how they behave.\n */\n readonly runtime?: RuntimeArtifact;\n}\n\n/**\n * A runtime build this package produces. `source` is the IIFE the page runs;\n * the two digests describe the same bytes as a servable asset, so asset\n * delivery can hash-name and SRI-verify whichever artifact was chosen without\n * hashing anything at request time.\n */\nexport interface RuntimeArtifact {\n readonly profile: 'lean';\n readonly source: string;\n /** Short content hash, for the asset's file name. */\n readonly contentHash: string;\n /** `sha384-…`, for the bootstrap's `integrity` attribute. */\n readonly integrity: string;\n}\n\n/** Keys that travel in the wire tuple, in slot order. */\nexport const INLINE_CONFIG_KEYS = [\n 'allowedOrigins',\n 'serverURL',\n 'apiRoute',\n 'mergeDepth',\n 'debug',\n 'debounceMs',\n 'enableA11y',\n 'heartbeatMs',\n 'disableVisibilityGate',\n 'visibilityGateThreshold',\n 'intersectionRootMargin',\n 'disableReferrerDetection',\n 'disableLocalhostMatching',\n 'scopeBindingsByOwner',\n 'skipUnchanged',\n 'eventSourcePolicy',\n 'sanitizerPolicy',\n 'fragmentEndpoint',\n 'revealEditedField',\n 'routeStrategy',\n 'onUnboundChange',\n 'onUnfaithfulPatch',\n 'autoBind',\n 'hydration',\n 'defaults',\n 'softNavigationEvents',\n 'subfieldCoverage',\n] as const satisfies readonly Exclude<keyof InlineScriptConfig, 'runtime'>[];\n","/**\n * Wraps the build-time runtime IIFE with the consumer's configuration, and\n * places at most one strategy prelude ahead of it.\n */\n\nimport { warnDeprecatedOptions } from '@/types/dev-warning';\nimport { assertMergeDepthExplicit } from '@/types/merge-depth';\nimport { V1_RUNTIME_DEFAULTS } from '@/types/defaults-profile';\nimport { RUNTIME_SOURCE, RUNTIME_BUILD_INFO, type RuntimeBuildInfo } from './runtime.generated';\nimport { FRAGMENT_SOURCE } from './fragment.generated';\nimport { ROUTE_SOURCE } from './route.generated';\nimport { LOADER_SOURCE } from './loader.generated';\nimport { LOADER_REACT_SOURCE } from './loader-react.generated';\nimport { INLINE_CONFIG_KEYS, type InlineScriptConfig } from '@/types/inline-config';\n\nexport type { InlineScriptConfig, RuntimeArtifact } from '@/types/inline-config';\n\nfunction assertBuilt(source: string, artifact: string): void {\n if (source.length === 0) {\n throw new Error(\n `[live-preview] ${artifact} is empty. Run \\`npm run build:runtime\\` before bundling.`,\n );\n }\n}\n\n/** The inline script body without `<script>` tags; see `wrapWithScriptTag()`. */\nexport function generateInlineScript(config: InlineScriptConfig = {}): string {\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- read to warn about it\n warnDeprecatedOptions({ defaults: config.defaults, onUnboundChange: config.onUnboundChange });\n const runtime = runtimeFor(config);\n return [configStatement(config), ...strategyPrelude(config), runtime].join('\\n');\n}\n\n/**\n * The full runtime, or the artifact the consumer imported. The lean one leaves\n * out the strategies (docs/options.md), so the two preludes are refused with it\n * rather than emitted against a runtime that could never answer them.\n */\nfunction runtimeFor(config: InlineScriptConfig): string {\n const artifact = config.runtime;\n if (artifact === undefined) {\n assertBuilt(RUNTIME_SOURCE, 'runtime.generated.ts');\n return RUNTIME_SOURCE;\n }\n assertBuilt(artifact.source, `the ${artifact.profile} runtime`);\n if (config.fragmentEndpoint != null || config.routeStrategy === true) {\n throw new Error(\n `[live-preview] the ${artifact.profile} runtime and the fragment or route strategy exclude ` +\n 'each other: it carries no strategy runner, so the prelude would have nothing to talk to. ' +\n 'Drop the runtime option, or drop `fragmentEndpoint`/`routeStrategy`.',\n );\n }\n return artifact.source;\n}\n\n/**\n * At most one prelude, and the fragment one wins: it already contains the\n * route strategy, so emitting both would ship that code twice and leave two\n * globals where the runtime expects the fragment one to be authoritative.\n */\nfunction strategyPrelude(config: InlineScriptConfig): readonly string[] {\n if (config.fragmentEndpoint != null) {\n assertBuilt(FRAGMENT_SOURCE, 'fragment.generated.ts');\n return [FRAGMENT_SOURCE];\n }\n if (config.routeStrategy === true) {\n assertBuilt(ROUTE_SOURCE, 'route.generated.ts');\n return [ROUTE_SOURCE];\n }\n return [];\n}\n\n// `__LIVE_PREVIEW_CONFIG__` is a public presence signal: consumers' integration\n// tests grep for it, so the name outlives any refactor.\nfunction configStatement(config: InlineScriptConfig): string {\n return `var __LIVE_PREVIEW_CONFIG__=${buildConfigLiteral(config)};`;\n}\n\n/** The positional wire literal the runtime destructures; shared by the inline script and the loader. */\nfunction buildConfigLiteral(config: InlineScriptConfig): string {\n assertMergeDepthExplicit(config);\n const profile = profileSlots(config);\n // `null` counts as omitted, and omitted slots stay empty (`[,,1]`): a JSON\n // `null` would bypass the runtime's destructuring defaults. Defaults remains\n // in its established slot 24; later rows are append-only and may be absent.\n const values: unknown[] = INLINE_CONFIG_KEYS.map((key) => config[key] ?? profile[key]);\n while (values.at(-1) === undefined) values.pop();\n // `<` is escaped so a value containing `</script>` cannot end the tag.\n return `[${values\n .map((value) => (value === undefined ? '' : JSON.stringify(value)))\n .join(',')}]`.replace(/</g, '\\\\u003C');\n}\n\n/**\n * What the `defaults` profile puts on the wire. The runtime's own fallbacks are\n * the 2.0 rows, so `'v2'` fills nothing and `'v1'` has to write its four; the\n * profile itself goes into slot 24 either way, so a reader of the served page\n * learns which generation an empty slot belongs to (ADR 0007).\n */\nfunction profileSlots(config: InlineScriptConfig): Partial<InlineScriptConfig> {\n const defaults = config.defaults ?? 'v2';\n return defaults === 'v1' ? { ...V1_RUNTIME_DEFAULTS, defaults } : { defaults };\n}\n\n/** Where the runtime asset lives, and how the browser should verify it. */\nexport interface LoaderScriptTarget {\n /** URL the bootstrap appends. Same-origin or absolute; hashed by the caller. */\n readonly runtimeSrc: string;\n /** Subresource-integrity value, e.g. `sha384-…`; empty drops the check and the `crossorigin` it requires. */\n readonly integrity?: string;\n}\n\n/**\n * The static-delivery bootstrap: the configuration plus a few hundred bytes\n * appending the runtime inside a preview. The asset stays configuration-free.\n */\nexport function generateLoaderScript(\n config: InlineScriptConfig = {},\n target: LoaderScriptTarget,\n): string {\n const bootstrap = loaderFor(config);\n if (target.runtimeSrc === '') {\n throw new Error('[live-preview] generateLoaderScript needs a runtimeSrc.');\n }\n const encode = (value: string): string => JSON.stringify(value).replace(/</gu, '\\\\u003C');\n return [\n configStatement(config),\n `var __LP_RUNTIME_SRC__=${encode(target.runtimeSrc)};`,\n `var __LP_RUNTIME_INTEGRITY__=${encode(target.integrity ?? '')};`,\n ...strategyPrelude(config),\n bootstrap,\n ].join('\\n');\n}\n\n/**\n * The bootstrap, or the one armed for React's first commit (ADR 0015 F2): the\n * inline runtime is the first script in `<head>` and arms the signal itself,\n * while a fetched asset may evaluate after `react-dom` has, when it is too\n * late — so on a page that declares React the bootstrap arms before it\n * fetches. One script either way, never a prelude ahead of the plain one. A\n * page that declares Vue takes the plain one: Vue's mount leaves state on the\n * container that a late runtime can still read (`core/hydration-vue`).\n */\nfunction loaderFor(config: InlineScriptConfig): string {\n if (config.hydration === 'react') {\n assertBuilt(LOADER_REACT_SOURCE, 'loader-react.generated.ts');\n return LOADER_REACT_SOURCE;\n }\n assertBuilt(LOADER_SOURCE, 'loader.generated.ts');\n return LOADER_SOURCE;\n}\n\n/** Wrap a script body in `<script>`, with the CSP nonce attribute when given. */\nexport function wrapWithScriptTag(body: string, options: { nonce?: string } = {}): string {\n const nonceAttr = options.nonce !== undefined ? ` nonce=\"${assertNonce(options.nonce)}\"` : '';\n return `<script${nonceAttr}>${body}</script>`;\n}\n\n/** @internal */\nexport function runtimeBuildInfo(): RuntimeBuildInfo {\n return RUNTIME_BUILD_INFO;\n}\n\n/**\n * A nonce as CSP defines it: base64url characters only. Returned unchanged so\n * a caller can inline the result. Not re-exported from the package barrel — it\n * is shared with the adapters, not part of the public surface.\n */\nexport function assertNonce(nonce: string): string {\n if (!/^[A-Za-z0-9+/=_-]+$/.test(nonce)) {\n throw new RangeError('nonce contains characters CSP does not allow');\n }\n return nonce;\n}\n","/**\n * The runtime as a servable, cacheable asset — the request-time half of\n * `mode: 'loader'`.\n *\n * Name and integrity are constants of the package build (the artifact carries\n * both), so nothing here hashes anything per request and this module stays\n * reachable from a browser entry: no `node:crypto`, no Node builtins at all.\n *\n * The content hash is in the file name, which is what makes `immutable` honest:\n * different bytes are a different URL, so a year-long cache can never serve the\n * wrong runtime. A request for any other name under the mount path is a 404\n * rather than a redirect to the current one — a client asking for a hash we no\n * longer have is asking for bytes we cannot produce.\n */\n\nimport { RUNTIME_CONTENT_HASH, RUNTIME_INTEGRITY, RUNTIME_SOURCE } from '@inline/runtime.generated';\nimport type { RuntimeArtifact } from '@/types/inline-config';\n\n/** Where the asset route is mounted when nothing says otherwise. */\nexport const DEFAULT_ASSET_PATH = '/payload-live-preview';\n\nexport interface RuntimeAssetOptions {\n /**\n * Path the asset route is mounted at. Must match on both sides — the\n * bootstrap requests it and the route serves it. Default\n * `/payload-live-preview`; give it the framework's own base path as a prefix\n * when the app is not served from the site root.\n */\n readonly assetPath?: string;\n /** The artifact to serve; the default runtime when omitted. */\n readonly runtime?: RuntimeArtifact;\n}\n\nexport interface RuntimeAsset {\n /** The file name alone, `runtime.<hash>.js`. */\n readonly fileName: string;\n /** The absolute path the bootstrap requests, mount path included. */\n readonly urlPath: string;\n /** `sha384-…`, for the bootstrap's `integrity` attribute. */\n readonly integrity: string;\n /** The bytes to serve. */\n readonly source: string;\n}\n\n/**\n * One leading slash, no trailing one, so joining is a single concatenation.\n *\n * Trimmed by index rather than by `/^\\/+|\\/+$/`: that expression backtracks over\n * a long run of slashes and costs quadratic time on a path the consumer\n * configures (CodeQL js/polynomial-redos).\n */\nfunction normalizePath(path: string): string {\n let start = 0;\n let end = path.length;\n while (start < end && path[start] === '/') start += 1;\n while (end > start && path[end - 1] === '/') end -= 1;\n const trimmed = path.slice(start, end);\n return trimmed === '' ? '' : `/${trimmed}`;\n}\n\n/** Describe the asset for these options; deterministic per package version and artifact. */\nexport function runtimeAsset(options: RuntimeAssetOptions = {}): RuntimeAsset {\n const artifact = options.runtime;\n const hash = artifact?.contentHash ?? RUNTIME_CONTENT_HASH;\n const fileName = `runtime.${hash}.js`;\n return {\n fileName,\n urlPath: `${normalizePath(options.assetPath ?? DEFAULT_ASSET_PATH)}/${fileName}`,\n integrity: artifact?.integrity ?? RUNTIME_INTEGRITY,\n source: artifact?.source ?? RUNTIME_SOURCE,\n };\n}\n\n/**\n * A year, the longest `max-age` browsers honour, plus `immutable` so a reload\n * does not revalidate either. Safe only because the hash is in the name.\n */\nexport const ASSET_CACHE_CONTROL = 'public, max-age=31536000, immutable';\n\n/** The headers the asset is served with, on every framework. */\nexport function runtimeAssetHeaders(): Record<string, string> {\n return {\n 'content-type': 'text/javascript; charset=utf-8',\n 'cache-control': ASSET_CACHE_CONTROL,\n // The bootstrap sets `crossorigin=\"anonymous\"` for the integrity check;\n // same-origin needs no CORS header, and a CDN in front of it gets one that\n // says the bytes are public.\n 'access-control-allow-origin': '*',\n // Nothing here is HTML, and a browser that sniffs it as such would be wrong.\n 'x-content-type-options': 'nosniff',\n };\n}\n\n/**\n * The response for one requested URL: the asset when the file name is the one\n * this build produces, 404 otherwise.\n *\n * Only the file name is checked, never the mount path. Where the route sits is\n * the framework's business — the consumer put the file there — while the name\n * is ours, and it is the name that decides whether the bytes a client cached\n * for a year are still the bytes we would send.\n */\nexport function runtimeAssetResponse(url: string, options: RuntimeAssetOptions = {}): Response {\n const asset = runtimeAsset(options);\n // A query string is a cache-buster and must still resolve.\n const path = url.split('?')[0] ?? '';\n const requested = path.slice(path.lastIndexOf('/') + 1);\n if (requested !== asset.fileName) {\n return new Response('Not found', {\n status: 404,\n headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' },\n });\n }\n return new Response(asset.source, { status: 200, headers: runtimeAssetHeaders() });\n}\n","/**\n * Placing the runtime's script tag inside an HTML document, by text: the\n * adapters see a rendered string or a streamed chunk, never a DOM.\n */\n\n/** The opening `<head>` tag the runtime script is inserted into. */\nexport const HEAD_INSERT = /<head(\\s[^>]*)?>/i;\n\n/** `text/html` with or without parameters. */\nexport const HTML_CONTENT_TYPE = /text\\/html/i;\n\n// Browsers prescan only the first 1024 bytes for the encoding; a script\n// inserted ahead of `<meta charset>` would push it out of that window.\nconst META_CHARSET =\n /<meta\\s+(?:[^>]*\\s)?(?:charset\\s*=|http-equiv\\s*=\\s*[\"']?content-type)[^>]*>/i;\n\n/**\n * `html` with the script tag after `<meta charset>`, else right after\n * `<head>`; `undefined` when there is no `<head>` to insert into.\n */\nexport function injectIntoHead(html: string, scriptTag: string): string | undefined {\n const head = HEAD_INSERT.exec(html);\n if (head === null) return undefined;\n const headEnd = head.index + head[0].length;\n const headClose = html.indexOf('</head', headEnd);\n const meta = META_CHARSET.exec(html.slice(headEnd, headClose === -1 ? undefined : headClose));\n const at = meta === null ? headEnd : headEnd + meta.index + meta[0].length;\n return `${html.slice(0, at)}${scriptTag}${html.slice(at)}`;\n}\n","/**\n * The options the policy reads, and what they resolve to: the `defaults`\n * profile fills what an adapter left unset, and the inline-script config\n * carries only what was given so the runtime's own defaults stay the single\n * source of them.\n */\n\nimport type { generateInlineScript } from '@inline/generator';\nimport {\n adapterDefaultsFor,\n runtimeDefaultsFor,\n V2_RUNTIME_DEFAULTS,\n} from '@/types/defaults-profile';\nimport { warnDeprecatedOptions } from '@/types/dev-warning';\nimport { assertMergeDepthExplicit } from '@/types/merge-depth';\nimport type { InlineScriptConfig } from '@/types/inline-config';\nimport type { PreviewSignal } from './preview-request';\nimport type { PreviewAdapterOptions } from './options';\n\n/** The structural subset of any adapter's options the policy reads; hooks are bound per request. */\nexport type PreviewPolicyOptions = PreviewAdapterOptions<never>;\n\n/** The options after the `defaults` profile: explicit options win, the profile fills the rest. */\nexport interface ResolvedPolicyOptions {\n readonly strict: boolean;\n readonly previewSignals: readonly PreviewSignal[] | undefined;\n readonly skipUnchanged: boolean | undefined;\n readonly disableReferrerDetection: boolean | undefined;\n readonly disableLocalhostMatching: boolean | undefined;\n readonly eventSourcePolicy: 'any' | 'parent-or-opener' | undefined;\n readonly sanitizerPolicy: 'compat' | 'strict' | undefined;\n}\n\nexport function resolvePolicyOptions(options: PreviewPolicyOptions): ResolvedPolicyOptions {\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- read to warn about it\n warnDeprecatedOptions({ defaults: options.defaults, onUnboundChange: options.onUnboundChange });\n const adapter = adapterDefaultsFor(options.defaults);\n const runtime = runtimeDefaultsFor(options.defaults);\n // The inline runtime already defaults to the v2 rows, so only a differing\n // profile — an explicit `defaults: 'v1'` — needs a row on the wire.\n const runtimeRow = <K extends keyof typeof V2_RUNTIME_DEFAULTS>(\n key: K,\n ): (typeof V2_RUNTIME_DEFAULTS)[K] | undefined =>\n runtime[key] !== V2_RUNTIME_DEFAULTS[key] ? runtime[key] : undefined;\n return {\n strict: options.strict ?? adapter.strict,\n previewSignals: options.previewSignals ?? adapter.previewSignals,\n skipUnchanged: options.skipUnchanged ?? runtimeRow('skipUnchanged'),\n disableReferrerDetection:\n options.disableReferrerDetection ?? runtimeRow('disableReferrerDetection'),\n disableLocalhostMatching: options.disableLocalhostMatching,\n eventSourcePolicy: options.eventSourcePolicy ?? runtimeRow('eventSourcePolicy'),\n sanitizerPolicy: options.sanitizerPolicy ?? runtimeRow('sanitizerPolicy'),\n };\n}\n\n/**\n * What an adapter knows about the page beyond what a project configured: its\n * hydration owner and the document events its router fires after a commit.\n * These are facts, not project options.\n */\nexport type PageFacts = Pick<InlineScriptConfig, 'hydration' | 'softNavigationEvents'>;\n\n/** The inline-script configuration; only given options travel, so the runtime's own defaults stay the single source of them. */\nexport function inlineScriptConfig(\n options: PreviewPolicyOptions,\n facts: PageFacts = {},\n): Parameters<typeof generateInlineScript>[0] {\n assertMergeDepthExplicit(options);\n const resolved = resolvePolicyOptions(options);\n return {\n // The generator names it in slot 24 and, under `'v1'`, reads an\n // omitted `mergeDepth` as deliberate.\n ...(options.defaults !== undefined ? { defaults: options.defaults } : {}),\n ...(options.allowedOrigins !== undefined ? { allowedOrigins: options.allowedOrigins } : {}),\n ...(options.serverURL !== undefined ? { serverURL: options.serverURL } : {}),\n ...(options.apiRoute !== undefined ? { apiRoute: options.apiRoute } : {}),\n ...(options.mergeDepth !== undefined ? { mergeDepth: options.mergeDepth } : {}),\n ...(options.revealEditedField !== undefined\n ? { revealEditedField: options.revealEditedField }\n : {}),\n ...(options.debug !== undefined ? { debug: options.debug } : {}),\n ...(options.debounceMs !== undefined ? { debounceMs: options.debounceMs } : {}),\n ...(options.heartbeatMs !== undefined ? { heartbeatMs: options.heartbeatMs } : {}),\n ...(resolved.skipUnchanged !== undefined ? { skipUnchanged: resolved.skipUnchanged } : {}),\n ...(options.scopeBindingsByOwner !== undefined\n ? { scopeBindingsByOwner: options.scopeBindingsByOwner }\n : {}),\n ...(resolved.disableReferrerDetection !== undefined\n ? { disableReferrerDetection: resolved.disableReferrerDetection }\n : {}),\n ...(resolved.disableLocalhostMatching !== undefined\n ? { disableLocalhostMatching: resolved.disableLocalhostMatching }\n : {}),\n ...(resolved.eventSourcePolicy !== undefined\n ? { eventSourcePolicy: resolved.eventSourcePolicy }\n : {}),\n ...(resolved.sanitizerPolicy !== undefined\n ? { sanitizerPolicy: resolved.sanitizerPolicy }\n : {}),\n ...(options.runtime !== undefined ? { runtime: options.runtime } : {}),\n ...(options.fragments !== undefined ? { fragmentEndpoint: options.fragments.endpoint } : {}),\n // Only when no endpoint is configured: that prelude carries the route\n // strategy already, and asking for both would emit the larger one twice.\n ...(options.routeStrategy === true && options.fragments === undefined\n ? { routeStrategy: true }\n : {}),\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- the 2.0 name is carried through exactly here\n ...(options.onUnboundChange !== undefined ? { onUnboundChange: options.onUnboundChange } : {}),\n ...(options.onUnfaithfulPatch !== undefined\n ? { onUnfaithfulPatch: options.onUnfaithfulPatch }\n : {}),\n ...(options.autoBind !== undefined ? { autoBind: options.autoBind } : {}),\n ...(options.subfieldCoverage !== undefined\n ? { subfieldCoverage: options.subfieldCoverage }\n : {}),\n ...(facts.hydration !== undefined ? { hydration: facts.hydration } : {}),\n ...(facts.softNavigationEvents !== undefined\n ? { softNavigationEvents: facts.softNavigationEvents }\n : {}),\n };\n}\n","/**\n * Applying a decision to a fetch-style `Response`, and the request-side\n * glue every adapter repeats: hook binding and the manual script tag.\n */\n\nimport { generateInlineScript, generateLoaderScript, wrapWithScriptTag } from '@inline/generator';\nimport { runtimeAsset } from './runtime-asset';\nimport { HTML_CONTENT_TYPE, injectIntoHead } from './html-inject';\nimport { inlineScriptConfig, type PageFacts, type PreviewPolicyOptions } from './policy-options';\nimport type { PreviewDecision, PreviewDecisionHooks, PreviewPolicy } from './policy';\nimport type { PreviewAdapterOptions } from './options';\n\n/** The header surface shared by `Headers` and a Node response. */\nexport interface HeaderSink {\n get(name: string): string | null | undefined;\n set(name: string, value: string): void;\n}\n\n/** Bind an adapter's per-request hooks to `request`. */\nexport function bindDecisionHooks<Req>(\n policy: PreviewPolicy,\n options: Pick<PreviewAdapterOptions<Req>, 'authorizePreview' | 'shouldInject'>,\n request: Req,\n): PreviewDecisionHooks {\n return {\n shouldInject: () => options.shouldInject?.(request) ?? true,\n ...(policy.authorizes ? { authorize: () => options.authorizePreview?.(request) } : {}),\n };\n}\n\n/**\n * The script body alone, for a consumer that builds the element itself — a JSX\n * framework cannot render a tag that arrives as a string.\n *\n * The one place delivery is decided, so every adapter answers `delivery:\n * 'asset'` the same way: the bootstrap plus the URL and integrity of whichever\n * artifact was configured, and never the runtime itself.\n */\nexport function renderScriptBody(options: PreviewPolicyOptions, facts: PageFacts = {}): string {\n const config = inlineScriptConfig(options, facts);\n if (options.delivery !== 'asset') return generateInlineScript(config);\n const asset = runtimeAsset(options);\n return generateLoaderScript(config, { runtimeSrc: asset.urlPath, integrity: asset.integrity });\n}\n\n/** The `<script>` tag for manual embedding, with `nonce` when given. */\nexport function renderScriptTag(\n options: PreviewPolicyOptions & { readonly nonce?: string },\n facts: PageFacts = {},\n): string {\n const body = renderScriptBody(options, facts);\n return wrapWithScriptTag(body, options.nonce !== undefined ? { nonce: options.nonce } : {});\n}\n\n/** A changed response must never be stored as the public page, nor shared across sessions. */\nexport function markUncacheable(headers: HeaderSink): void {\n const cacheControl = headers.get('cache-control') ?? '';\n if (!/\\bno-store\\b/i.test(cacheControl)) headers.set('cache-control', 'private, no-store');\n const vary = (headers.get('vary') ?? '').trim();\n const listed = vary.split(',').map((token) => token.trim().toLowerCase());\n if (listed.includes('*') || listed.includes('cookie')) return;\n headers.set('vary', vary.length === 0 ? 'Cookie' : `${vary}, Cookie`);\n}\n\n/**\n * `response` with the script tag in its `<head>`, untouched when it has no\n * body (204/304/HEAD), is not HTML, or has no `<head>`. Headers describing\n * the old body — length, encoding, ETag — are dropped.\n */\nexport async function injectIntoResponse(response: Response, scriptTag: string): Promise<Response> {\n if (response.body === null) return response;\n if (!HTML_CONTENT_TYPE.test(response.headers.get('content-type') ?? '')) return response;\n const injected = injectIntoHead(await response.clone().text(), scriptTag);\n if (injected === undefined) return response;\n const headers = new Headers(response.headers);\n headers.delete('content-length');\n headers.delete('content-encoding');\n headers.delete('etag');\n return new Response(injected, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n\n/** Run `apply` on the response headers, cloning first when they are immutable (responses passed through from `fetch()`). */\nexport function withHeaders(response: Response, apply: (headers: Headers) => void): Response {\n try {\n apply(response.headers);\n return response;\n } catch {\n const headers = new Headers(response.headers);\n apply(headers);\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n }\n}\n\n/**\n * The header side of a decision on any sink: the merged CSP for its mode,\n * then the cache headers — those also when the mode is off, because an\n * injected body alone already makes the response private.\n */\nexport function applyCspHeaders(\n headers: HeaderSink,\n policy: PreviewPolicy,\n decision: PreviewDecision,\n nonce: string,\n): void {\n const mode = decision.cspMode;\n if (mode !== false) {\n const existing = headers.get('content-security-policy') ?? '';\n headers.set('content-security-policy', policy.csp(existing, nonce, mode));\n }\n markUncacheable(headers);\n}\n\n/** Set the merged CSP header for `mode` and mark the response uncacheable. */\nexport function withCspHeader(\n response: Response,\n policy: PreviewPolicy,\n decision: PreviewDecision,\n nonce: string,\n): Response {\n return withHeaders(response, (headers) => {\n applyCspHeaders(headers, policy, decision, nonce);\n });\n}\n\n/** Apply a decision end to end: inject, then CSP and cache headers. The response is returned as-is when nothing changes. */\nexport async function applyDecision(\n response: Response,\n policy: PreviewPolicy,\n decision: PreviewDecision,\n nonce: string,\n): Promise<Response> {\n if (!decision.inject && decision.cspMode === false) return response;\n const injected = decision.inject\n ? await injectIntoResponse(response, policy.scriptTag(nonce))\n : response;\n return withCspHeader(injected, policy, decision, nonce);\n}\n","/**\n * Server-side preview-intent detection. Every signal here is client-controlled:\n * a positive result is a delivery hint, never proof of identity or permission.\n * Verify with `authorizePreviewRequest()` before anything privileged.\n */\n\nimport { warnOnce } from '@/types/dev-warning';\n\n/** `query`: `?preview=true`; `fetch-dest`: `Sec-Fetch-Dest: iframe`; `referer`: an admin-origin Referer. */\nexport type PreviewSignal = 'query' | 'fetch-dest' | 'referer';\n\nexport interface PreviewRequestOptions {\n /** Which signals count. Default: all three. `['query']` is the adapters' 2.0 default. */\n readonly signals?: readonly PreviewSignal[];\n /** Query parameters (value `true` or `1`) that signal intent. Default `['preview', 'draft', 'livePreview']`. */\n readonly queryParams?: readonly string[];\n /** Admin origins whose Referer signals intent, e.g. `['https://cms.example.com']` — the adapters' option of the same name. */\n readonly allowedOrigins?: readonly string[];\n /** @deprecated Use `allowedOrigins`; removed in 3.0. Ignored when `allowedOrigins` is given. */\n readonly adminOrigins?: readonly string[];\n}\n\nconst DEFAULT_QUERY_PARAMS = ['preview', 'draft', 'livePreview'] as const;\n\n/** The request surface the predicate reads; `Request` satisfies it, Nitro/H3 events need a shim. */\nexport interface PreviewRequestLike {\n readonly url: string;\n readonly headers: { get(name: string): string | null };\n}\n\n/** Whether `request` carries live-preview intent. Intent, not authorization. */\nexport function hasPreviewIntent(\n request: PreviewRequestLike,\n options: PreviewRequestOptions = {},\n): boolean {\n const signals = new Set<PreviewSignal>(options.signals ?? ['query', 'fetch-dest', 'referer']);\n const queryParams = options.queryParams ?? DEFAULT_QUERY_PARAMS;\n\n if (signals.has('query')) {\n let url: URL | undefined;\n try {\n url = new URL(request.url);\n } catch {\n url = undefined;\n }\n if (url !== undefined) {\n for (const param of queryParams) {\n // The last value of a repeated key, as Next.js matches a `has` rule:\n // `withLivePreview()` marks the response by that reading, and the two\n // have to agree on `?preview=true&preview=0`.\n const value = url.searchParams.getAll(param).at(-1);\n if (value === 'true' || value === '1') return true;\n }\n }\n }\n\n if (signals.has('fetch-dest') && request.headers.get('sec-fetch-dest') === 'iframe') {\n return true;\n }\n\n // The 1.x spelling is honoured until 3.0; the canonical name wins when both are given.\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- the alias is read exactly here\n const alias = options.adminOrigins;\n if (alias !== undefined) {\n warnOnce(\n 'admin-origins',\n '`hasPreviewIntent({ adminOrigins })` is removed in 3.0: name the option `allowedOrigins`; ' +\n '`pll migrate` renames it (ADR 0026).',\n );\n }\n const configured = options.allowedOrigins ?? alias ?? [];\n const adminOrigins = signals.has('referer') ? configured : [];\n if (adminOrigins.length > 0) {\n const referer = request.headers.get('referer');\n if (referer !== null) {\n try {\n const refererOrigin = new URL(referer).origin;\n for (const adminOrigin of adminOrigins) {\n try {\n if (new URL(adminOrigin).origin === refererOrigin) return true;\n } catch {\n // A malformed configured origin matches nothing.\n }\n }\n } catch {\n // A malformed referer is not a signal.\n }\n }\n }\n\n return false;\n}\n","/**\n * The verdict shape every authorization strategy produces, and the one error\n * class that is allowed to escape it. Kept apart from the strategies so the\n * adapters can import the error without pulling in HMAC or session code.\n */\n\nimport type { AuthorizedPreviewContext } from '@/types/authorized-preview';\n\n/** Why a request was refused. `'authorized'` is the one non-refusal. */\nexport type PreviewAuthorizationOutcome =\n | 'authorized'\n | 'missing-credential'\n | 'invalid'\n | 'expired'\n | 'wrong-audience'\n | 'wrong-path'\n | 'wrong-locale'\n | 'wrong-purpose'\n | 'replayed'\n | 'unavailable';\n\n/** The result of `authorizePreviewRequest()`: a verdict, never an exception. */\nexport type PreviewAuthorization =\n | {\n readonly authorized: true;\n readonly outcome: 'authorized';\n readonly context: AuthorizedPreviewContext;\n }\n | {\n readonly authorized: false;\n readonly outcome: Exclude<PreviewAuthorizationOutcome, 'authorized'>;\n readonly context: null;\n };\n\n/** The request shape every strategy reads: a URL and a header getter. */\nexport interface PreviewAuthorizationRequest {\n readonly url: string;\n readonly headers: { get(name: string): string | null };\n /** Request lifetime, when supplied by the caller. Session fetches follow it. */\n readonly signal?: AbortSignal;\n}\n\n/**\n * A strategy was misconfigured — raised on first use and re-thrown by the\n * adapters rather than reported as `'unavailable'`, so it fails loudly.\n */\nexport class PreviewConfigurationError extends Error {\n override readonly name = 'PreviewConfigurationError';\n}\n\n/** Recognises the error across bundles, where `instanceof` sees a different class copy. */\nexport function isPreviewConfigurationError(error: unknown): error is PreviewConfigurationError {\n return (\n error instanceof PreviewConfigurationError ||\n (error instanceof Error && error.name === 'PreviewConfigurationError')\n );\n}\n\nexport function refused(\n outcome: Exclude<PreviewAuthorizationOutcome, 'authorized'>,\n): PreviewAuthorization {\n return { authorized: false, outcome, context: null };\n}\n","/**\n * The authorized preview context's shape and brand, in the leaf `types` domain\n * so producer and consumers recognise the same context. See ADR 0006.\n */\n\n/**\n * The brand key, in the type and on the object.\n *\n * This was a `unique symbol` until 2026-08-30. A `unique symbol` is nominal per\n * *declaration*, and the published entries each carry their own declaration\n * file — so `AuthorizedPreviewContext` from the root barrel was a different\n * type from the one in `./server` or in an adapter, and the documented flow\n * (authorize once, hand the context to the adapter hook and to the draft read)\n * did not type-check in any combination a consumer can write.\n *\n * That is the same trap the runtime brand below already avoids by using\n * `Symbol.for` rather than `Symbol()`; the lesson simply had not reached the\n * type. A shared string literal is identical in every bundle for the same\n * reason a registry symbol is.\n *\n * It is not what makes a context trustworthy. `isAuthorizedPreviewContext`\n * decides that, on the registry symbol and on `Object.isFrozen`, and every\n * consumption point calls it — the adapter policy, the draft read and the\n * binding emitter. Writing this key by hand buys nothing.\n */\nexport const AUTHORIZED_PREVIEW_BRAND_KEY = 'payload-live-preview.authorized-preview-context';\n\nexport type PreviewAuthorizationStrategyName = 'payload-session' | 'signed-token' | 'verifier';\n\n/** One server-authorized Payload document, not a query selected by the browser. */\nexport type AuthorizedPreviewDocument =\n | { readonly kind: 'collection'; readonly slug: string; readonly id: string | number }\n | { readonly kind: 'global'; readonly slug: string };\n\n/** Opt-in data capability, enforced by the fragment endpoint and `definePreview`. */\nexport interface AuthorizedPreviewPayloadScope {\n /** Payload base URL, distinct from the preview site's audience. */\n readonly serverURL: string;\n /** REST prefix, default `/api`. */\n readonly apiRoute?: string;\n readonly document: AuthorizedPreviewDocument;\n /** Maximum requested population depth, not a field-level ACL. */\n readonly maxDepth: number;\n}\n\n/** What a context is bound to; every field is optional because every strategy binds differently. */\nexport interface AuthorizedPreviewScope {\n /** The site origin the credential was issued for. */\n readonly audience?: string;\n /** The request pathname the credential is valid for. */\n readonly path?: string;\n readonly locale?: string;\n /** Requires a finite context expiry. Unscoped contexts keep their existing behavior. */\n readonly payload?: AuthorizedPreviewPayloadScope;\n}\n\n/** The verdict of a successful `authorizePreviewRequest()`: frozen, branded, produced only there. Carry it, do not rebuild it. */\nexport interface AuthorizedPreviewContext {\n readonly [AUTHORIZED_PREVIEW_BRAND_KEY]: true;\n readonly strategy: PreviewAuthorizationStrategyName;\n /** The user id, token subject, or whatever the verifier named. */\n readonly subject: string | undefined;\n /** Unix milliseconds. */\n readonly authorizedAt: number;\n /** Unix milliseconds, or `undefined` when the strategy does not know. */\n readonly expiresAt: number | undefined;\n readonly scope: AuthorizedPreviewScope;\n /** The minimal request material a draft read forwards to Payload — one verified cookie, never the whole `Cookie` header. */\n readonly payloadHeaders: Readonly<Record<string, string>>;\n}\n\n// A registry symbol: entries are separate bundles, and a per-bundle `Symbol()`\n// would refuse the other's contexts in the package while unit tests passed.\nconst BRAND = Symbol.for(AUTHORIZED_PREVIEW_BRAND_KEY);\n\n/**\n * Whether `value` carries the brand `authorizePreviewRequest()` gives it. A JSON round trip or an\n * unfrozen copy does not; a frozen spread copy keeps the registry symbol and passes, because the\n * brand is a runtime check, not a cryptographic one (ADR 0006).\n */\nexport function isAuthorizedPreviewContext(value: unknown): value is AuthorizedPreviewContext {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<PropertyKey, unknown>)[BRAND] === true &&\n Object.isFrozen(value)\n );\n}\n\n/** Internal: the one place a context is made. */\nexport function createAuthorizedPreviewContext(\n fields: Omit<AuthorizedPreviewContext, typeof AUTHORIZED_PREVIEW_BRAND_KEY>,\n): AuthorizedPreviewContext {\n const context = Object.freeze({\n ...fields,\n scope: Object.freeze({\n ...fields.scope,\n ...(fields.scope.payload === undefined\n ? {}\n : {\n payload: Object.freeze({\n ...fields.scope.payload,\n document: Object.freeze({ ...fields.scope.payload.document }),\n }),\n }),\n }),\n payloadHeaders: Object.freeze({ ...fields.payloadHeaders }),\n [BRAND]: true,\n [AUTHORIZED_PREVIEW_BRAND_KEY]: true,\n });\n // No cast: the frozen object carries the brand key the interface declares.\n return context;\n}\n","/**\n * Running an `authorizePreview` hook. What the hook may resolve to is\n * normalised here once, so the page policy and the fragment endpoint read the\n * same verdict from the same callback. See ADR 0006.\n */\n\nimport {\n isPreviewConfigurationError,\n refused,\n type PreviewAuthorization,\n} from '@security/preview-verdict';\n// From the leaf `types` domain on purpose: the security module would pull the\n// HMAC and session code into every adapter bundle for a ten-line brand check.\nimport { isAuthorizedPreviewContext } from '@/types/authorized-preview';\nimport type { PreviewAuthorizationHookResult } from './options';\n\n/** A bound hook: the adapter option with the request already applied. */\nexport type BoundAuthorizeHook = () =>\n PreviewAuthorizationHookResult | Promise<PreviewAuthorizationHookResult>;\n\n/**\n * The hook's result as a verdict. Only a context `authorizePreviewRequest()`\n * produced authorizes, bare or inside its verdict; a `{ authorized: true }`\n * literal, a copy, a boolean or nothing refuses as `'invalid'`.\n */\nexport function verdictFrom(result: PreviewAuthorizationHookResult): PreviewAuthorization {\n if (isAuthorizedPreviewContext(result)) {\n return { authorized: true, outcome: 'authorized', context: result };\n }\n if (typeof result === 'object' && result !== null && 'authorized' in result) {\n if (result.authorized && isAuthorizedPreviewContext(result.context)) {\n return { authorized: true, outcome: 'authorized', context: result.context };\n }\n return refused(result.authorized ? 'invalid' : result.outcome);\n }\n // `null`, `undefined`, a boolean, a look-alike literal: refused.\n return refused('invalid');\n}\n\n/**\n * Run a bound hook: a `PreviewConfigurationError` is re-thrown so a\n * misconfigured strategy is loud, any other failure is the `'unavailable'`\n * refusal — an identity provider being down must never authorize.\n */\nexport async function runAuthorizeHook(hook: BoundAuthorizeHook): Promise<PreviewAuthorization> {\n let result: PreviewAuthorizationHookResult;\n try {\n result = await hook();\n } catch (error) {\n if (isPreviewConfigurationError(error)) throw error;\n return refused('unavailable');\n }\n return verdictFrom(result);\n}\n","/**\n * What `strict` refuses at startup, so a misconfiguration fails the process\n * rather than a public response (ADR 0006).\n */\n\nimport { isDevelopmentProcess } from '@/types/dev-warning';\nimport { resolvePolicyOptions, type PreviewPolicyOptions } from './policy-options';\n\n/**\n * The sentence every strict refusal ends with.\n *\n * Each of these rules is new in 2.0, and the process that stops is one that\n * worked yesterday. Saying only the rule leaves an upgrader to find out that\n * there is a staged path at all — so the way out is in the message that stops\n * them, not only in the guide they have not opened yet.\n */\nconst STAGED =\n \" New in 2.0; `defaults: 'v1'` keeps the 1.x table while you migrate (docs/migration.md).\";\n\n/** The configuration errors `strict` exists to raise, at startup rather than on a public response. */\nexport function assertStrictConfiguration(options: PreviewPolicyOptions): void {\n if (typeof options.authorizePreview !== 'function') {\n throw new Error(\n 'payload-live-preview: strict mode requires `authorizePreview` — response changes ' +\n 'must be gated on a verified context, not on intent (ADR 0006).' +\n STAGED,\n );\n }\n const origins = options.allowedOrigins ?? [];\n if (origins.length === 0) {\n throw new Error(\n 'payload-live-preview: strict mode requires explicit, non-empty `allowedOrigins`.' + STAGED,\n );\n }\n if (!isDevelopmentProcess()) {\n for (const origin of origins) {\n let protocol: string | undefined;\n try {\n protocol = new URL(origin).protocol;\n } catch {\n protocol = undefined;\n }\n if (protocol !== 'https:') {\n throw new Error(\n `payload-live-preview: strict mode requires https admin origins in production; got \"${origin}\".` +\n STAGED,\n );\n }\n }\n }\n // The resolved signals, not the option: `defaults: 'v1'` fills in `referer`.\n if (resolvePolicyOptions(options).previewSignals?.includes('referer') === true) {\n throw new Error(\n \"payload-live-preview: strict mode disables referrer trust; remove 'referer' from \" +\n \"`previewSignals` (the 'v1' profile includes it).\",\n );\n }\n}\n","/**\n * The preview policy every framework adapter applies: intent, authorization,\n * injection, CSP. Pure — it reads a `{ url, headers.get }` request shape and\n * never touches a response; the adapter translates both ends. See ADR 0006.\n */\n\nimport {\n buildFrameAncestors,\n buildScriptSrcWithNonce,\n generateCspNonce,\n mergeCspHeader,\n} from '@security/csp';\nimport type { PreviewAuthorizationOutcome } from '@security/preview-verdict';\nimport type { AuthorizedPreviewContext } from '@/types/authorized-preview';\nimport { assertMergeDepthExplicit } from '@/types/merge-depth';\nimport { wrapWithScriptTag } from '@inline/generator';\n// Delivery is decided in one place; the policy caches whatever that produced.\nimport { renderScriptBody } from './response';\nimport { hasPreviewIntent, type PreviewRequestLike } from './preview-request';\nimport { warnOnce } from '@/types/dev-warning';\nimport { runAuthorizeHook, type BoundAuthorizeHook } from './authorize-hook';\nimport { resolvePolicyOptions, type PageFacts, type PreviewPolicyOptions } from './policy-options';\nimport { assertStrictConfiguration } from './strict';\n\nexport type { PreviewAuthorizationHookResult } from './options';\n\n/** How the adapter manages Content-Security-Policy, normalised. */\nexport type CspMode = false | 'frame-ancestors' | 'full';\n\n/** `manageCsp` normalised: unset and `true` both mean frame-ancestors only. */\nexport function normalizeCspMode(value: PreviewPolicyOptions['manageCsp']): CspMode {\n if (value === false) return false;\n if (value === 'full') return 'full';\n return 'frame-ancestors';\n}\n\n/** Whether the request shows preview intent under the options; `inject: 'always'` counts as intent. */\nexport function previewIntentFor(\n request: PreviewRequestLike,\n options: PreviewPolicyOptions,\n): boolean {\n const signals = resolvePolicyOptions(options).previewSignals;\n return (\n (options.inject ?? 'preview-only') === 'always' ||\n hasPreviewIntent(request, {\n ...(options.previewQueryParams !== undefined\n ? { queryParams: options.previewQueryParams }\n : {}),\n ...(signals !== undefined ? { signals } : {}),\n allowedOrigins: options.allowedOrigins ?? [],\n })\n );\n}\n\n/** The CSP header after merging: `frame-ancestors` always, a nonce'd `script-src` only in `'full'` mode. */\nexport function buildPreviewCsp(\n options: PreviewPolicyOptions,\n nonce: string,\n existing: string,\n mode: Exclude<CspMode, false>,\n): string {\n const additions: Record<string, string> = {\n 'frame-ancestors': buildFrameAncestors({\n self: true,\n origins: [...(options.allowedOrigins ?? []), ...(options.frameAncestorsExtra ?? [])],\n }),\n };\n if (mode === 'full') {\n additions['script-src'] = buildScriptSrcWithNonce(nonce, {\n self: true,\n strictDynamic: options.strictDynamic ?? false,\n ...(options.scriptSrcExtra !== undefined ? { extra: options.scriptSrcExtra } : {}),\n });\n }\n return mergeCspHeader(existing, additions);\n}\n\n/** What the policy decided for one request. */\nexport interface PreviewDecision {\n /** The request shows preview intent (or the adapter injects always). */\n readonly isPreview: boolean;\n /** The verified context, or `null` when there was no hook or it refused. */\n readonly authorization: AuthorizedPreviewContext | null;\n /** The hook's verdict, or `undefined` when no hook ran (no intent, or none configured). */\n readonly outcome: PreviewAuthorizationOutcome | undefined;\n /** Intent, authorization, `autoInject` and the adapter's content filter all agreed. */\n readonly inject: boolean;\n /** CSP directives to add, or `false`. Never set without intent, never after a refusal. */\n readonly cspMode: CspMode;\n /** Whether the request-scoped nonce may be handed to templates. */\n readonly exposeNonce: boolean;\n}\n\n/** The per-request hooks an adapter binds to its own request type. */\nexport interface PreviewDecisionHooks {\n /** The adapter's content filter, evaluated lazily once injection is otherwise decided. */\n readonly shouldInject?: () => boolean;\n /** The adapter's `authorizePreview` option, bound to the framework request. Called only on intent. */\n readonly authorize?: BoundAuthorizeHook;\n}\n\n/** A policy bound to one adapter's options. The script body depends on the options only and is built once. */\nexport interface PreviewPolicy {\n /**\n * Decide for a request: `hooks.authorize` runs only on intent, and a\n * `PreviewConfigurationError` from it is re-thrown while any other failure\n * becomes the `'unavailable'` refusal.\n */\n decide(request: PreviewRequestLike, hooks?: PreviewDecisionHooks): Promise<PreviewDecision>;\n /** The `<script>` tag for this policy's runtime, carrying `nonce`. */\n scriptTag(nonce: string): string;\n /** CSP header value for a decision that has a mode. */\n csp(existing: string, nonce: string, mode: Exclude<CspMode, false>): string;\n /** A fresh nonce. */\n nonce(): string;\n /** Whether `authorizePreview` is configured; `decide()` then requires the bound hook. */\n readonly authorizes: boolean;\n}\n\nconst NONE: PreviewDecision = Object.freeze({\n isPreview: false,\n authorization: null,\n outcome: undefined,\n inject: false,\n cspMode: false,\n exposeNonce: false,\n});\n\nexport function createPreviewPolicy(\n options: PreviewPolicyOptions,\n facts: PageFacts = {},\n): PreviewPolicy {\n const resolved = resolvePolicyOptions(options);\n assertMergeDepthExplicit(options);\n const authorizes = typeof options.authorizePreview === 'function';\n if (resolved.strict) {\n assertStrictConfiguration(options);\n } else if (!authorizes) {\n warnOnce(\n 'intent-only-preview',\n 'preview responses are gated on client-controlled intent only. Configure `authorizePreview` ' +\n '(see authorizePreviewRequest) before production; `strict: true` enforces it. ' +\n 'ADR 0006 explains why intent is not authorization.',\n );\n }\n const cspMode = normalizeCspMode(options.manageCsp);\n const autoInject = options.autoInject ?? true;\n let body: string | undefined;\n const scriptBody = (): string => {\n body ??= renderScriptBody(options, facts);\n return body;\n };\n return {\n authorizes,\n async decide(request, hooks = {}) {\n if (authorizes && hooks.authorize === undefined) {\n throw new Error(\n 'payload-live-preview: `authorizePreview` is configured but decide() was called ' +\n 'without an `authorize` hook; bind the hook to the request (bindDecisionHooks).',\n );\n }\n const isPreview = previewIntentFor(request, options);\n if (!isPreview) return NONE;\n let authorization: AuthorizedPreviewContext | null = null;\n let outcome: PreviewAuthorizationOutcome | undefined;\n if (hooks.authorize !== undefined) {\n const verdict = await runAuthorizeHook(hooks.authorize);\n outcome = verdict.outcome;\n if (!verdict.authorized) {\n return {\n isPreview,\n authorization: null,\n outcome,\n inject: false,\n cspMode: false,\n exposeNonce: false,\n };\n }\n authorization = verdict.context;\n }\n return {\n isPreview,\n authorization,\n outcome,\n inject: autoInject && (hooks.shouldInject?.() ?? true),\n cspMode,\n exposeNonce: true,\n };\n },\n scriptTag: (nonce) => wrapWithScriptTag(scriptBody(), { nonce }),\n csp: (existing, nonce, mode) => buildPreviewCsp(options, nonce, existing, mode),\n nonce: () => generateCspNonce(),\n };\n}\n","/**\n * Binds the document lifecycle the runtime cannot see: a back/forward-cache\n * restore re-runs no scripts, so a client that stayed attached comes back\n * bound to a frozen document and quietly stops updating; a soft navigation\n * replaces the content the binding cache describes. Both are silent failures.\n */\n\n/** The part of the client this owner drives. */\nexport interface NavigationLifecycleTarget {\n suspend(): boolean;\n resume(): boolean;\n /** Re-scan bindings after replacing markup without crossing a navigation boundary. */\n refreshCache(): void;\n /** Re-scan and replay the last accepted document after a committed router navigation. */\n refreshAfterNavigation?(): void;\n}\n\n/** Package-owned event dispatched after a framework router commit. @internal */\nexport const NAVIGATION_COMMIT_EVENT = 'payload-live-preview:navigation';\nconst ASTRO_INITIAL_PAGE_LOAD_EVENT = 'astro:page-load';\nconst ASTRO_AFTER_SWAP_EVENT = 'astro:after-swap';\n\nexport interface NavigationLifecycleOptions {\n /** Where `pagehide`/`pageshow` fire; they exist only on the window. Defaults to `window`. */\n readonly windowTarget?: EventTarget;\n /** Event target for soft-navigation events. Defaults to `document`. */\n readonly documentTarget?: EventTarget;\n /**\n * Events after which the DOM was replaced and the current editor state must\n * be replayed, e.g. `astro:page-load`. Empty by default: only the host knows\n * which its router fires.\n */\n readonly softNavigationEvents?: readonly string[];\n}\n\n/** Returns an unbind function; calling it twice is harmless. */\nexport function bindNavigationLifecycle(\n target: NavigationLifecycleTarget,\n options: NavigationLifecycleOptions = {},\n): () => void {\n const windowTarget = options.windowTarget ?? (globalThis as { window?: EventTarget }).window;\n const documentTarget =\n options.documentTarget ?? (globalThis as { document?: EventTarget }).document;\n const softEvents = [...new Set(options.softNavigationEvents ?? [])];\n\n const onPageHide = (): void => {\n target.suspend();\n };\n const onPageShow = (event: Event): void => {\n // Only a persisted restore needs reacquiring; an ordinary load already started.\n if ((event as Event & { readonly persisted?: boolean }).persisted === true) {\n target.resume();\n }\n };\n let astroNavigationArmed = false;\n const onAstroAfterSwap = (): void => {\n astroNavigationArmed = true;\n };\n const onSoftNavigation = (event: Event): void => {\n // Astro emits page-load for the initial document too. A client-router\n // commit is the page-load preceded by after-swap, including before the\n // browser's initial `load` when a subresource is slow.\n if (event.type === ASTRO_INITIAL_PAGE_LOAD_EVENT) {\n if (!astroNavigationArmed) return;\n astroNavigationArmed = false;\n }\n if (target.refreshAfterNavigation === undefined) target.refreshCache();\n else target.refreshAfterNavigation();\n };\n\n let unbound = false;\n\n windowTarget?.addEventListener('pagehide', onPageHide);\n windowTarget?.addEventListener('pageshow', onPageShow);\n for (const name of softEvents) documentTarget?.addEventListener(name, onSoftNavigation);\n const observesAstro = softEvents.includes(ASTRO_INITIAL_PAGE_LOAD_EVENT);\n if (observesAstro) documentTarget?.addEventListener(ASTRO_AFTER_SWAP_EVENT, onAstroAfterSwap);\n\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 if (observesAstro) {\n documentTarget?.removeEventListener(ASTRO_AFTER_SWAP_EVENT, onAstroAfterSwap);\n }\n };\n}\n","/**\n * Next.js adapter. The script goes into the root layout, because\n * `NextResponse.next()` carries no body for the middleware to inject into:\n * `livePreviewScriptProps()` for the App Router's JSX, `renderLivePreviewScript()`\n * for HTML a server assembles as a string.\n */\n\nimport {\n createPreviewPolicy,\n type PreviewDecision,\n type PreviewPolicy,\n} from '@adapters/shared/policy';\nimport {\n applyDecision,\n bindDecisionHooks,\n injectIntoResponse,\n renderScriptBody,\n renderScriptTag,\n withCspHeader,\n} from '@adapters/shared/response';\nimport { assertNonce } from '@inline/generator';\nimport type { PreviewAdapterOptions } from '@adapters/shared/options';\nimport type { PageFacts } from '@adapters/shared/policy-options';\nimport { NAVIGATION_COMMIT_EVENT } from '@core/navigation-lifecycle';\nimport { warnOnce } from '@/types/dev-warning';\n\nexport type { PreviewAdapterOptions } from '@adapters/shared/options';\n\nexport type LivePreviewNextOptions = PreviewAdapterOptions;\n\n/**\n * A Next page is a React tree, so every script this adapter emits declares\n * that React hydrates it (ADR 0015): the runtime then holds its first write\n * until React has committed the tree that holds the bindings, instead of\n * writing into markup React is about to compare with its own render. Knowledge\n * the adapter has, not an option a project sets.\n */\nconst REACT_PAGE: PageFacts = {\n hydration: 'react',\n softNavigationEvents: [NAVIGATION_COMMIT_EVENT],\n};\n\n/**\n * Middleware over the standard `Request`/`Response` pair: on preview intent it\n * authorizes, injects, merges CSP and marks the response uncacheable. Next.js\n * middleware has no `locals`, so the verdict is not published — call\n * `authorizePreviewRequest()` in the route when a page needs it.\n */\nexport function createLivePreviewMiddleware(\n options: LivePreviewNextOptions = {},\n): (request: Request, response: Response) => Promise<Response> {\n const policy = createPreviewPolicy(options, REACT_PAGE);\n return async (request, response) => {\n const decision = await policy.decide(request, bindDecisionHooks(policy, options, request));\n if (!decision.isPreview) return response;\n return decision.cspMode === 'full'\n ? withCarriedNonce(response, policy, decision)\n : applyDecision(response, policy, decision, policy.nonce());\n };\n}\n\n/**\n * `manageCsp: 'full'` lets only a script that carries its nonce run. In\n * `proxy.ts` the response is `NextResponse.next()`, which has no body, and the\n * layout renders the script without ever seeing that nonce; a `script-src`\n * nonce nothing carries would block it and Next's own inline scripts. A\n * response the middleware cannot inject into therefore keeps `frame-ancestors`.\n */\nasync function withCarriedNonce(\n response: Response,\n policy: PreviewPolicy,\n decision: PreviewDecision,\n): Promise<Response> {\n const nonce = policy.nonce();\n if (decision.inject) {\n const injected = await injectIntoResponse(response, policy.scriptTag(nonce));\n if (injected !== response) return withCspHeader(injected, policy, decision, nonce);\n }\n warnOnce(\n 'nextjs-full-csp-without-carrier',\n \"`manageCsp: 'full'` wrote `frame-ancestors` only: the middleware had no HTML body to put \" +\n 'the script in, and a nonce that reaches no script would block it. Keep `script-src` in your ' +\n 'own policy and pass its nonce to `LivePreviewScript`.',\n );\n return withCspHeader(response, policy, { ...decision, cspMode: 'frame-ancestors' }, nonce);\n}\n\n/** What a `<script>` element needs to carry the runtime; see `livePreviewScriptProps`. */\nexport interface LivePreviewScriptProps {\n readonly dangerouslySetInnerHTML: { readonly __html: string };\n /** Present only when a nonce was passed, so React omits the attribute otherwise. */\n readonly nonce?: string;\n}\n\n/**\n * Props for the `<script>` in `app/layout.tsx`:\n *\n * ```tsx\n * <script {...livePreviewScriptProps({ allowedOrigins: [ADMIN], serverURL: ADMIN, mergeDepth: 1 })} />\n * ```\n *\n * The nonce stays a prop rather than going into the body, because that is where\n * the framework — and any CSP handling built on it — expects the attribute.\n */\nexport function livePreviewScriptProps(\n options: LivePreviewNextOptions & { readonly nonce?: string } = {},\n): LivePreviewScriptProps {\n const html = renderScriptBody(options, REACT_PAGE);\n if (options.nonce === undefined) return { dangerouslySetInnerHTML: { __html: html } };\n return {\n dangerouslySetInnerHTML: { __html: html },\n nonce: assertNonce(options.nonce),\n };\n}\n\n/**\n * The complete `<script>` tag, for HTML a server builds as a string. A JSX\n * framework cannot render it — use `livePreviewScriptProps()` there.\n */\nexport function renderLivePreviewScript(\n options: LivePreviewNextOptions & { readonly nonce?: string } = {},\n): string {\n return renderScriptTag(options, REACT_PAGE);\n}\n","/**\n * An optional peer dependency, imported the first time it is actually needed.\n *\n * Every fragment binding renders with a component system this package does not\n * install: `astro`, `react`/`react-dom`, `svelte`, `vue`. A project that never\n * registers a fragment — most of them — must still be able to install and run\n * this package, so the import happens at the first render rather than at module\n * load. Each caller chooses a specifier its consumer can resolve.\n */\n\n/**\n * `load` runs once per process. Callers arriving while it is in flight share\n * that promise; a rejected one is forgotten rather than kept, so a project that\n * installs the package after the first request is not answered from the first\n * bad start for the rest of the process's life.\n */\nexport function lazyPeer<T>(load: () => Promise<T>): () => Promise<T> {\n let pending: Promise<T> | undefined;\n return () => {\n if (pending === undefined) {\n const started = load();\n pending = started;\n started.catch(() => {\n if (pending === started) pending = undefined;\n });\n }\n return pending;\n };\n}\n\n/**\n * The error a binding throws when its renderer's packages are not installed.\n * The endpoint answers 500 either way; this is what the server log says, and\n * without it the cause reads as \"render failed\".\n */\nexport function missingPeerError(packages: readonly string[], cause: unknown): Error {\n const names = packages.map((name) => `\\`${name}\\``).join(' and ');\n const one = packages.length === 1;\n return new Error(\n `payload-live-preview: this fragment endpoint renders with ${names}, ` +\n `${one ? 'an optional peer' : 'optional peers'} this package does not install. ` +\n `${one ? 'Install it' : 'Install them'}, or pass your own \\`render\\`.`,\n { cause },\n );\n}\n","/**\n * The `payload-session` strategy: forward exactly one named cookie to\n * `GET <serverURL>/api/<usersSlug>/me` and authorize when a user comes back.\n * A cookie-only request preserves working Payload 2 sessions. When `/me`\n * reports no user, one retry adds an `Origin` for Payload 3's CSRF check.\n */\n\nimport { createAuthorizedPreviewContext } from '@/types/authorized-preview';\nimport {\n PreviewConfigurationError,\n refused,\n type PreviewAuthorization,\n type PreviewAuthorizationRequest,\n} from './preview-verdict';\n\n/** A `fetch`-compatible function, injectable for tests. */\nexport type FetchLike = (\n input: string,\n init: { readonly headers: Record<string, string>; readonly signal: AbortSignal },\n) => Promise<{ readonly ok: boolean; readonly status: number; json(): Promise<unknown> }>;\n\nexport interface PayloadSessionStrategy {\n readonly type: 'payload-session';\n /** Payload server origin, e.g. `https://cms.example.com`. */\n readonly serverURL: string;\n /** Auth collection slug; `users` unless the project renamed it. */\n readonly usersSlug?: string;\n /** Cookie name; Payload's default is `payload-token`. */\n readonly cookieName?: string;\n /**\n * Send this listed origin with the cookie from the first request. Without\n * it, try the existing cookie-only request, then the origin of `serverURL`\n * once when `/me` reports a null user. Draft reads keep the accepted headers.\n */\n readonly origin?: string;\n /** Upper bound for the `/me` round trip. Below 250 ms is raised to 250 ms; default 3000. */\n readonly timeoutMs?: number;\n /** Longest cookie value accepted; longer ones are refused as `missing-credential`. Default 4096. */\n readonly maxCookieLength?: number;\n readonly fetch?: FetchLike;\n /** Clock, Unix milliseconds. Injectable for tests. */\n readonly now?: () => number;\n}\n\nconst DEFAULT_USERS_SLUG = 'users';\nconst DEFAULT_COOKIE_NAME = 'payload-token';\nconst DEFAULT_TIMEOUT_MS = 3_000;\nconst MIN_TIMEOUT_MS = 250;\nconst DEFAULT_MAX_COOKIE_LENGTH = 4_096;\nconst COOKIE_NAME_PATTERN = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\nconst COOKIE_VALUE_PATTERN = /^[A-Za-z0-9._~-]+$/;\n/** Below this an `exp` is Unix seconds; a millisecond timestamp passed it in 1973. */\nconst SECONDS_CEILING = 1e11;\n\n/**\n * Exactly one value for `name`, or `null` when absent, empty, over `maxLength`\n * or repeated — a repeated cookie is ambiguous and is refused, not guessed.\n */\nexport function extractCookie(\n header: string | null,\n name: string,\n maxLength: number = DEFAULT_MAX_COOKIE_LENGTH,\n): string | null {\n if (header === null || header.length === 0) return null;\n const prefix = `${name}=`;\n const values: string[] = [];\n for (const part of header.split(';')) {\n const trimmed = part.trim();\n if (trimmed.startsWith(prefix)) values.push(trimmed.slice(prefix.length));\n }\n if (values.length !== 1) return null;\n const value = values[0] ?? '';\n // A JWT is `[A-Za-z0-9._~-]`; anything else must not be forwarded in a header.\n if (value.length === 0 || value.length > maxLength || !COOKIE_VALUE_PATTERN.test(value)) {\n return null;\n }\n return value;\n}\n\nfunction cookieNameFor(configured: string | undefined): string {\n const name = configured ?? DEFAULT_COOKIE_NAME;\n if (!COOKIE_NAME_PATTERN.test(name)) {\n throw new PreviewConfigurationError(\n `payload-live-preview: cookie name \"${name}\" is not a valid cookie-name token`,\n );\n }\n return name;\n}\n\n/** The origin of an absolute http(s) URL; `option` names it in the error. */\nfunction httpOriginFor(value: string, option: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new PreviewConfigurationError(\n `payload-live-preview: ${option} \"${value}\" is not an absolute URL`,\n );\n }\n if (url.protocol !== 'https:' && url.protocol !== 'http:') {\n throw new PreviewConfigurationError(\n `payload-live-preview: ${option} must be http(s), got \"${url.protocol}\"`,\n );\n }\n return url.origin;\n}\n\nexport async function authorizeSession(\n request: PreviewAuthorizationRequest,\n strategy: PayloadSessionStrategy,\n): Promise<PreviewAuthorization> {\n const cookieName = cookieNameFor(strategy.cookieName);\n const origin = httpOriginFor(strategy.serverURL, 'serverURL');\n const sentOrigin =\n strategy.origin === undefined ? undefined : httpOriginFor(strategy.origin, 'origin');\n const value = extractCookie(\n request.headers.get('cookie'),\n cookieName,\n strategy.maxCookieLength ?? DEFAULT_MAX_COOKIE_LENGTH,\n );\n if (value === null) return refused('missing-credential');\n const now = strategy.now ?? Date.now;\n const timeoutMs = Math.max(MIN_TIMEOUT_MS, strategy.timeoutMs ?? DEFAULT_TIMEOUT_MS);\n // Retain AbortSignal.timeout's refusal of non-integral or non-finite values.\n if (!Number.isSafeInteger(timeoutMs)) return refused('unavailable');\n const fetchImpl: FetchLike = strategy.fetch ?? globalThis.fetch;\n const usersSlug = encodeURIComponent(strategy.usersSlug ?? DEFAULT_USERS_SLUG);\n const forwarded = `${cookieName}=${value}`;\n let payloadHeaders: Record<string, string> = { cookie: forwarded };\n if (sentOrigin !== undefined) payloadHeaders['origin'] = sentOrigin;\n const controller = new AbortController();\n const abort = (): void => {\n controller.abort(request.signal?.reason);\n };\n const isAborted = (): boolean => controller.signal.aborted;\n request.signal?.addEventListener('abort', abort, { once: true });\n if (request.signal?.aborted === true) abort();\n let timer: ReturnType<typeof setTimeout> | undefined;\n let body: unknown;\n try {\n if (isAborted()) return refused('unavailable');\n timer = setTimeout(() => {\n controller.abort(new DOMException('The operation timed out', 'TimeoutError'));\n }, timeoutMs);\n for (let attempt = 0; attempt < 2; attempt++) {\n // `depth=0`: the verdict needs the user's id, not its populated relations.\n const response = await fetchImpl(`${origin}/api/${usersSlug}/me?depth=0`, {\n headers: { ...payloadHeaders, accept: 'application/json' },\n signal: controller.signal,\n });\n if (isAborted()) return refused('unavailable');\n if (!response.ok) return refused(response.status === 401 ? 'invalid' : 'unavailable');\n body = await response.json();\n if (isAborted()) return refused('unavailable');\n // Payload 2 accepts an absent Origin; adding one unconditionally can\n // reject its valid session when only the frontend is in the CSRF list.\n if (\n attempt !== 0 ||\n sentOrigin !== undefined ||\n typeof body !== 'object' ||\n body === null ||\n (body as { user?: unknown }).user !== null\n ) {\n break;\n }\n payloadHeaders = { cookie: forwarded, origin };\n }\n } catch {\n return refused('unavailable');\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n request.signal?.removeEventListener('abort', abort);\n }\n const user = readUser(body, strategy.usersSlug ?? DEFAULT_USERS_SLUG);\n if (user === null) return refused('invalid');\n const expiresAt = readExpiry(body);\n if (expiresAt !== undefined && expiresAt <= now()) return refused('expired');\n return {\n authorized: true,\n outcome: 'authorized',\n context: createAuthorizedPreviewContext({\n strategy: 'payload-session',\n subject: user,\n authorizedAt: now(),\n expiresAt,\n scope: {},\n payloadHeaders,\n }),\n };\n}\n\n/** The user id from a `/me` body, or `null` when absent or from another auth collection — Payload answers `/me` for every one of them. */\nfunction readUser(body: unknown, usersSlug: string): string | null {\n if (typeof body !== 'object' || body === null || Array.isArray(body)) return null;\n const user = (body as { user?: unknown }).user;\n if (typeof user !== 'object' || user === null || Array.isArray(user)) return null;\n const collection =\n (body as { collection?: unknown }).collection ?? (user as { collection?: unknown }).collection;\n if (collection !== undefined && collection !== usersSlug) return null;\n const id = (user as { id?: unknown }).id;\n if (typeof id === 'string' && id.length > 0) return id;\n if (typeof id === 'number' && Number.isFinite(id)) return String(id);\n return null;\n}\n\n/** `/me` reports `exp` in Unix seconds; units are decided by magnitude so an expired millisecond value stays expired. */\nfunction readExpiry(body: unknown): number | undefined {\n const exp = (body as { exp?: unknown }).exp;\n if (typeof exp !== 'number' || !Number.isFinite(exp) || exp <= 0) return undefined;\n return exp < SECONDS_CEILING ? exp * 1000 : exp;\n}\n","/**\n * The `signed-token` strategy: a short-lived HMAC-SHA256 token minted by the\n * Payload side and verified by the site. Format and bindings: ADR 0006 §3.\n */\n\nimport { createAuthorizedPreviewContext } from '@/types/authorized-preview';\nimport { warnOnce } from '@/types/dev-warning';\nimport {\n PreviewConfigurationError,\n refused,\n type PreviewAuthorization,\n type PreviewAuthorizationRequest,\n} from './preview-verdict';\n\n/** The subset of Web Crypto the token strategy needs, injectable for environments that expose it elsewhere. */\nexport interface SubtleCryptoLike {\n readonly subtle: {\n importKey(\n format: 'raw',\n keyData: Uint8Array,\n algorithm: { readonly name: 'HMAC'; readonly hash: 'SHA-256' },\n extractable: false,\n keyUsages: readonly ('sign' | 'verify')[],\n ): Promise<CryptoKey>;\n sign(algorithm: 'HMAC', key: CryptoKey, data: Uint8Array): Promise<ArrayBuffer>;\n verify(\n algorithm: 'HMAC',\n key: CryptoKey,\n signature: Uint8Array,\n data: Uint8Array,\n ): Promise<boolean>;\n };\n getRandomValues<T extends Uint8Array>(array: T): T;\n}\n\n/** Where a signed token is read from on the request. */\nexport type PreviewTokenTransport =\n | { readonly kind: 'query'; readonly param?: string }\n | { readonly kind: 'header'; readonly name?: string };\n\n/**\n * Optional replay store. Not shipped: a per-process memory is useless behind\n * a load balancer, so the store is a deployment decision.\n */\nexport interface PreviewTokenReplayStore {\n /**\n * Record `id` as used until `expiresAt` and say whether this call was the\n * first: `true` admits the token, anything else refuses it as `replayed`, a\n * throw refuses it as `unavailable`. Check and record in one step (Redis\n * `SET NX PX`, a unique insert): a read followed by a write lets two requests\n * that carry the same token and arrive together both pass.\n */\n consume(id: string, expiresAt: number): Promise<boolean> | boolean;\n}\n\n/**\n * @deprecated The store shape of the 2.0 beta, removed in 3.0. Its two calls cannot be one\n * step, so two requests with the same token that arrive together both pass\n * `isUsed` before either reaches `markUsed`. Implement\n * {@link PreviewTokenReplayStore.consume} instead.\n */\nexport interface PreviewTokenReplayChecks {\n isUsed(id: string): Promise<boolean> | boolean;\n markUsed(id: string, expiresAt: number): Promise<void> | void;\n}\n\nexport interface SignedTokenStrategy {\n readonly type: 'signed-token';\n /** Shared secret, at least 32 bytes; shorter ones are refused on first use. */\n readonly secret: string | Uint8Array;\n /** The site origin tokens must name, e.g. `https://www.example.com`. */\n readonly audience: string;\n /** Purpose string tokens must carry. Default `live-preview`. */\n readonly purpose?: string;\n /** Default: query parameter `previewToken`. */\n readonly transport?: PreviewTokenTransport;\n /** Resolve the request's locale for the `loc` binding. Unset: tokens with `loc` are refused as `wrong-locale`. */\n readonly locale?: (request: PreviewAuthorizationRequest) => string | undefined;\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- the 2.0 beta shape is accepted until 3.0\n readonly replay?: PreviewTokenReplayStore | PreviewTokenReplayChecks;\n readonly crypto?: SubtleCryptoLike;\n readonly now?: () => number;\n}\n\n/** What `issuePreviewToken()` binds a token to. */\nexport interface PreviewTokenClaims {\n /** The site origin the token is for. */\n readonly audience: string;\n /** Request pathname the token opens. Recommended; omit only for a single-page preview. */\n readonly path?: string;\n readonly locale?: string;\n readonly subject?: string;\n readonly purpose?: string;\n /** Lifetime in milliseconds. Default ten minutes; capped at one hour. */\n readonly ttlMs?: number;\n}\n\nexport interface IssuePreviewTokenOptions {\n readonly secret: string | Uint8Array;\n readonly crypto?: SubtleCryptoLike;\n readonly now?: () => number;\n}\n\ninterface WireClaims {\n readonly v: 1;\n readonly aud: string;\n readonly pth?: string;\n readonly loc?: string;\n readonly sub?: string;\n readonly pur: string;\n readonly iat: number;\n readonly exp: number;\n readonly jti: string;\n}\n\nconst DEFAULT_PURPOSE = 'live-preview';\nconst DEFAULT_QUERY_PARAM = 'previewToken';\nconst DEFAULT_HEADER_NAME = 'x-preview-token';\nconst DEFAULT_TTL_MS = 10 * 60_000;\nconst MAX_TTL_MS = 60 * 60_000;\nconst MIN_SECRET_BYTES = 32;\nconst TOKEN_VERSION = 'v1';\n/** A real token is a few hundred bytes. */\nconst MAX_TOKEN_LENGTH = 4_096;\n\n// Lazy: a module-scope `new TextEncoder()` is a side effect a bundler must keep.\nlet cachedEncoder: TextEncoder | undefined;\nfunction encoder(): TextEncoder {\n cachedEncoder ??= new TextEncoder();\n return cachedEncoder;\n}\n\nfunction secretBytes(secret: string | Uint8Array): Uint8Array {\n const bytes = typeof secret === 'string' ? encoder().encode(secret) : secret;\n if (bytes.byteLength < MIN_SECRET_BYTES) {\n throw new PreviewConfigurationError(\n `payload-live-preview: the preview token secret must be at least ${String(MIN_SECRET_BYTES)} bytes`,\n );\n }\n return bytes;\n}\n\nfunction cryptoFor(configured: SubtleCryptoLike | undefined): SubtleCryptoLike | undefined {\n if (configured !== undefined) return configured;\n const candidate = (globalThis as { crypto?: unknown }).crypto;\n if (typeof (candidate as { subtle?: unknown } | undefined)?.subtle === 'object') {\n return candidate as SubtleCryptoLike;\n }\n return undefined;\n}\n\nasync function hmacKey(crypto: SubtleCryptoLike, secret: Uint8Array): Promise<CryptoKey> {\n return crypto.subtle.importKey('raw', secret, { name: 'HMAC', hash: 'SHA-256' }, false, [\n 'sign',\n 'verify',\n ]);\n}\n\nfunction toBase64Url(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nfunction fromBase64Url(text: string): Uint8Array | undefined {\n if (!/^[A-Za-z0-9_-]*$/.test(text)) return undefined;\n const padded =\n text.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (text.length % 4)) % 4);\n try {\n const binary = atob(padded);\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);\n return bytes;\n } catch {\n return undefined;\n }\n}\n\n/** Mint a preview token on the Payload side; pair with `buildLivePreviewUrl`. */\nexport async function issuePreviewToken(\n claims: PreviewTokenClaims,\n options: IssuePreviewTokenOptions,\n): Promise<string> {\n const crypto = cryptoFor(options.crypto);\n if (crypto === undefined) {\n throw new Error('payload-live-preview: no Web Crypto implementation available to sign tokens');\n }\n const secret = secretBytes(options.secret);\n const now = (options.now ?? Date.now)();\n const ttl = Math.min(MAX_TTL_MS, Math.max(1, claims.ttlMs ?? DEFAULT_TTL_MS));\n const id = new Uint8Array(16);\n crypto.getRandomValues(id);\n const wire: WireClaims = {\n v: 1,\n aud: claims.audience,\n ...(claims.path !== undefined ? { pth: claims.path } : {}),\n ...(claims.locale !== undefined ? { loc: claims.locale } : {}),\n ...(claims.subject !== undefined ? { sub: claims.subject } : {}),\n pur: claims.purpose ?? DEFAULT_PURPOSE,\n iat: now,\n exp: now + ttl,\n jti: toBase64Url(id),\n };\n const payload = toBase64Url(encoder().encode(JSON.stringify(wire)));\n const signed = `${TOKEN_VERSION}.${payload}`;\n const key = await hmacKey(crypto, secret);\n const signature = new Uint8Array(await crypto.subtle.sign('HMAC', key, encoder().encode(signed)));\n return `${signed}.${toBase64Url(signature)}`;\n}\n\nfunction readToken(\n request: PreviewAuthorizationRequest,\n transport: PreviewTokenTransport | undefined,\n): string | null {\n if (transport?.kind === 'header') {\n return request.headers.get(transport.name ?? DEFAULT_HEADER_NAME);\n }\n let url: URL;\n try {\n url = new URL(request.url);\n } catch {\n return null;\n }\n const values = url.searchParams.getAll(transport?.param ?? DEFAULT_QUERY_PARAM);\n return values.length === 1 ? (values[0] ?? null) : null;\n}\n\nfunction parseClaims(bytes: Uint8Array): WireClaims | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(new TextDecoder().decode(bytes));\n } catch {\n return undefined;\n }\n if (typeof parsed !== 'object' || parsed === null) return undefined;\n const c = parsed as Record<string, unknown>;\n const optionalString = (key: string): boolean =>\n c[key] === undefined || typeof c[key] === 'string';\n if (\n c['v'] !== 1 ||\n typeof c['aud'] !== 'string' ||\n typeof c['pur'] !== 'string' ||\n typeof c['iat'] !== 'number' ||\n typeof c['exp'] !== 'number' ||\n typeof c['jti'] !== 'string' ||\n !optionalString('pth') ||\n !optionalString('loc') ||\n !optionalString('sub')\n ) {\n return undefined;\n }\n return c as unknown as WireClaims;\n}\n\nexport async function authorizeToken(\n request: PreviewAuthorizationRequest,\n strategy: SignedTokenStrategy,\n): Promise<PreviewAuthorization> {\n const secret = secretBytes(strategy.secret);\n const crypto = cryptoFor(strategy.crypto);\n if (crypto === undefined) return refused('unavailable');\n const token = readToken(request, strategy.transport);\n if (token === null || token.length === 0) return refused('missing-credential');\n if (token.length > MAX_TOKEN_LENGTH) return refused('invalid');\n const parts = token.split('.');\n if (parts.length !== 3 || parts[0] !== TOKEN_VERSION) return refused('invalid');\n const payloadText = parts[1] ?? '';\n const payloadBytes = fromBase64Url(payloadText);\n const signature = fromBase64Url(parts[2] ?? '');\n if (payloadBytes === undefined || signature?.byteLength !== 32) return refused('invalid');\n let verified: boolean;\n try {\n const key = await hmacKey(crypto, secret);\n verified = await crypto.subtle.verify(\n 'HMAC',\n key,\n signature,\n encoder().encode(`${TOKEN_VERSION}.${payloadText}`),\n );\n } catch {\n return refused('unavailable');\n }\n if (!verified) return refused('invalid');\n const claims = parseClaims(payloadBytes);\n if (claims === undefined) return refused('invalid');\n const now = (strategy.now ?? Date.now)();\n if (claims.exp <= now || claims.iat > claims.exp) return refused('expired');\n if (claims.aud !== strategy.audience) return refused('wrong-audience');\n if (claims.pur !== (strategy.purpose ?? DEFAULT_PURPOSE)) return refused('wrong-purpose');\n if (claims.pth !== undefined) {\n let pathname: string;\n try {\n pathname = new URL(request.url).pathname;\n } catch {\n return refused('invalid');\n }\n if (claims.pth !== pathname) return refused('wrong-path');\n }\n if (claims.loc !== undefined) {\n const locale = strategy.locale?.(request);\n if (locale !== claims.loc) return refused('wrong-locale');\n }\n if (strategy.replay !== undefined) {\n let first: boolean;\n try {\n first = await consumeTokenId(strategy.replay, claims.jti, claims.exp);\n } catch {\n return refused('unavailable');\n }\n if (!first) return refused('replayed');\n }\n return {\n authorized: true,\n outcome: 'authorized',\n context: createAuthorizedPreviewContext({\n strategy: 'signed-token',\n subject: claims.sub,\n authorizedAt: now,\n expiresAt: claims.exp,\n scope: {\n audience: claims.aud,\n ...(claims.pth !== undefined ? { path: claims.pth } : {}),\n ...(claims.loc !== undefined ? { locale: claims.loc } : {}),\n },\n payloadHeaders: {},\n }),\n };\n}\n\n/**\n * `true` when `id` was not seen before. A store that returns anything but\n * `true` from `consume` refuses the token: fail closed, since a forgotten\n * return would otherwise admit every replay. The 2.0 beta shape keeps its two\n * steps and its race; that is why it is deprecated rather than emulated.\n */\nasync function consumeTokenId(\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- the 2.0 beta shape is accepted until 3.0\n store: PreviewTokenReplayStore | PreviewTokenReplayChecks,\n id: string,\n expiresAt: number,\n): Promise<boolean> {\n if ('consume' in store) {\n // The store is consumer code; its answer is a value, not a type.\n const answer: unknown = await store.consume(id, expiresAt);\n return answer === true;\n }\n warnOnce(\n 'replay-is-used',\n 'A `signed-token` replay store with `isUsed` and `markUsed` is removed in 3.0: implement ' +\n '`consume(id, expiresAt)`, which checks and records in one step (ADR 0026).',\n );\n if (await store.isUsed(id)) return false;\n await store.markUsed(id, expiresAt);\n return true;\n}\n","/**\n * Shared checks for an opt-in Payload document capability (ADR 0006 §5c).\n * The verifier supplies authority; server reads and fragments only compare\n * their requested target against it, before forwarding credentials or rendering.\n */\nimport type {\n AuthorizedPreviewContext,\n AuthorizedPreviewDocument,\n AuthorizedPreviewPayloadScope,\n} from '@/types/authorized-preview';\n\nfunction pathSegment(value: unknown): value is string {\n return (\n typeof value === 'string' &&\n value.length > 0 &&\n value !== '.' &&\n value !== '..' &&\n !/[\\s\\p{Cc}\\p{Cs}/\\\\?#%]/u.test(value)\n );\n}\n\n/** @internal Numeric REST IDs and their string spelling name the same document. */\nexport function isPreviewDocumentID(value: unknown): value is string | number {\n return typeof value === 'number' ? Number.isSafeInteger(value) : pathSegment(value);\n}\n\n/** @internal Refuse ambiguous paths rather than depending on a proxy's decoding rules. */\nexport function payloadAPIBase(serverURL: unknown, apiRoute: unknown = '/api'): string | null {\n if (typeof serverURL !== 'string' || typeof apiRoute !== 'string') return null;\n try {\n const url = new URL(serverURL);\n if (\n !['http:', 'https:'].includes(url.protocol) ||\n url.username ||\n url.password ||\n url.search ||\n url.hash\n ) {\n return null;\n }\n // Inspect the raw path too: URL would otherwise erase dot segments first.\n const rawPath = serverURL.replace(/^[a-z]+:\\/\\/[^/]+/iu, '').replace(/\\/+$/, '');\n const route = apiRoute.replace(/^\\//, '').replace(/\\/$/, '');\n if (\n (rawPath !== '' && !rawPath.slice(1).split('/').every(pathSegment)) ||\n !route.split('/').every(pathSegment)\n ) {\n return null;\n }\n return `${url.origin}${url.pathname.replace(/\\/+$/, '')}/${route}`;\n } catch {\n return null;\n }\n}\n\n/** @internal Validate a JavaScript verifier's binding, not merely its TypeScript shape. */\nexport function isValidPayloadScope(value: unknown): value is AuthorizedPreviewPayloadScope {\n if (typeof value !== 'object' || value === null) return false;\n const scope = value as Record<string, unknown>;\n const document = scope['document'] as Record<string, unknown> | null | undefined;\n if (\n payloadAPIBase(scope['serverURL'], scope['apiRoute']) === null ||\n typeof scope['maxDepth'] !== 'number' ||\n !Number.isSafeInteger(scope['maxDepth']) ||\n scope['maxDepth'] < 0 ||\n typeof document !== 'object' ||\n document === null ||\n !pathSegment(document['slug'])\n ) {\n return false;\n }\n return (\n document['kind'] === 'global' ||\n (document['kind'] === 'collection' && isPreviewDocumentID(document['id']))\n );\n}\n\n/** @internal No clock renewal: every consumer checks the original absolute expiry. */\nexport function isPayloadScopeCurrent(context: AuthorizedPreviewContext): boolean {\n return (\n context.expiresAt !== undefined &&\n Number.isFinite(context.expiresAt) &&\n context.expiresAt > Date.now()\n );\n}\n\n/** @internal Both package consumers use the same kind/slug/ID comparison. */\nexport function matchesPreviewDocument(\n expected: AuthorizedPreviewDocument,\n actual: {\n readonly kind: 'collection' | 'global';\n readonly slug: string | undefined;\n readonly id?: unknown;\n },\n): boolean {\n return (\n expected.kind === actual.kind &&\n expected.slug === actual.slug &&\n (expected.kind === 'global' ||\n (isPreviewDocumentID(actual.id) && String(expected.id) === String(actual.id)))\n );\n}\n\n/** @internal A document response or form snapshot cannot contradict its bound identity. */\nexport function matchesPreviewDocumentData(\n expected: AuthorizedPreviewDocument,\n value: unknown,\n): boolean {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const data = value as Record<string, unknown>;\n if (expected.kind === 'global') {\n return !Object.hasOwn(data, 'globalType') || data['globalType'] === expected.slug;\n }\n return (\n Object.hasOwn(data, 'id') &&\n matchesPreviewDocument(expected, { kind: 'collection', slug: expected.slug, id: data['id'] })\n );\n}\n","/**\n * Authorized preview context: the one verdict every privileged preview\n * decision is keyed on. Intent (`?preview=true`, an iframe destination, a\n * referer) is client-chosen; this turns a session, a signed token or the\n * application's own verifier into a branded context. Threat model: ADR 0006.\n */\n\nimport {\n AUTHORIZED_PREVIEW_BRAND_KEY,\n createAuthorizedPreviewContext,\n isAuthorizedPreviewContext,\n type AuthorizedPreviewContext,\n type AuthorizedPreviewDocument,\n type AuthorizedPreviewPayloadScope,\n type AuthorizedPreviewScope,\n type PreviewAuthorizationStrategyName,\n} from '@/types/authorized-preview';\nimport {\n refused,\n type PreviewAuthorization,\n type PreviewAuthorizationRequest,\n} from './preview-verdict';\nimport { authorizeSession, type PayloadSessionStrategy } from './preview-session';\nimport { authorizeToken, type SignedTokenStrategy } from './preview-token';\nimport { isValidPayloadScope } from './preview-scope';\n\nexport {\n AUTHORIZED_PREVIEW_BRAND_KEY,\n isAuthorizedPreviewContext,\n type AuthorizedPreviewContext,\n type AuthorizedPreviewDocument,\n type AuthorizedPreviewPayloadScope,\n type AuthorizedPreviewScope,\n type PreviewAuthorizationStrategyName,\n};\nexport {\n PreviewConfigurationError,\n type PreviewAuthorization,\n type PreviewAuthorizationOutcome,\n type PreviewAuthorizationRequest,\n} from './preview-verdict';\nexport { extractCookie, type FetchLike, type PayloadSessionStrategy } from './preview-session';\nexport {\n issuePreviewToken,\n type IssuePreviewTokenOptions,\n type PreviewTokenClaims,\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- the 2.0 beta shape exists to be re-exported\n type PreviewTokenReplayChecks,\n type PreviewTokenReplayStore,\n type PreviewTokenTransport,\n type SignedTokenStrategy,\n type SubtleCryptoLike,\n} from './preview-token';\n\n/** Claims a consumer verifier returns for a request it accepts. */\nexport interface PreviewVerifierClaims {\n readonly subject?: string;\n readonly expiresAt?: number;\n readonly scope?: AuthorizedPreviewScope;\n readonly payloadHeaders?: Readonly<Record<string, string>>;\n}\n\n/** The application's own verification: claims authorize, `null` refuses, a throw is `unavailable`. */\nexport interface VerifierStrategy {\n readonly type: 'verifier';\n readonly verify: (\n request: PreviewAuthorizationRequest,\n ) => Promise<PreviewVerifierClaims | null> | PreviewVerifierClaims | null;\n readonly now?: () => number;\n}\n\nexport type PreviewAuthorizationStrategy =\n PayloadSessionStrategy | SignedTokenStrategy | VerifierStrategy;\n\n/** Decide whether `request` is an authorized preview; refusals resolve to `{ authorized: false }` and only a `PreviewConfigurationError` throws. */\nexport async function authorizePreviewRequest(\n request: PreviewAuthorizationRequest,\n strategy: PreviewAuthorizationStrategy,\n): Promise<PreviewAuthorization> {\n switch (strategy.type) {\n case 'payload-session':\n return authorizeSession(request, strategy);\n case 'signed-token':\n return authorizeToken(request, strategy);\n case 'verifier':\n return authorizeVerifier(request, strategy);\n }\n}\n\nasync function authorizeVerifier(\n request: PreviewAuthorizationRequest,\n strategy: VerifierStrategy,\n): Promise<PreviewAuthorization> {\n let claims: PreviewVerifierClaims | null;\n try {\n claims = await strategy.verify(request);\n } catch {\n return refused('unavailable');\n }\n if (claims === null) return refused('invalid');\n if (\n claims.scope?.payload !== undefined &&\n (!isValidPayloadScope(claims.scope.payload) || !Number.isFinite(claims.expiresAt))\n ) {\n return refused('invalid');\n }\n const now = (strategy.now ?? Date.now)();\n if (claims.expiresAt !== undefined && claims.expiresAt <= now) return refused('expired');\n return {\n authorized: true,\n outcome: 'authorized',\n context: createAuthorizedPreviewContext({\n strategy: 'verifier',\n subject: claims.subject,\n authorizedAt: now,\n expiresAt: claims.expiresAt,\n scope: claims.scope ?? {},\n payloadHeaders: claims.payloadHeaders ?? {},\n }),\n };\n}\n","/**\n * The body cap and phase timers use the same positive-integer validation.\n * Keeping it here leaves the endpoint's transport and request lifetime together\n * while all three existing limits retain their defaults and error messages.\n */\n\nexport function positiveIntegerLimit(\n name: 'bodyBytes' | 'timeoutMs' | 'totalTimeoutMs',\n value: number | undefined,\n fallback: number,\n maximum: number,\n): number {\n const resolved = value ?? fallback;\n if (!Number.isSafeInteger(resolved) || resolved <= 0 || resolved > maximum) {\n throw new RangeError(\n `payload-live-preview: createFragmentEndpoint() limits.${name} must be a positive integer no greater than ${String(maximum)}.`,\n );\n }\n return resolved;\n}\n","/**\n * The fragment wire protocol: what the browser posts to a fragment endpoint\n * and what it answers. Both sides validate the shape. The request names the\n * page by its own route and query and the boundary by its registry id; nothing\n * on the wire carries code, templates, import paths or file paths. See ADR 0011.\n */\n\n/** Bumped when the request or response shape changes incompatibly. @internal */\nexport const FRAGMENT_PROTOCOL_VERSION = 1;\n/** @internal */\nexport const FRAGMENT_VERSION_HEADER = 'x-payload-fragment-version';\n\n/** @internal */\nexport interface FragmentRequestBody {\n /** Registry id of the boundary (`data-payload-fragment`). */\n readonly fragment: string;\n /** `data-payload-fragment-key`, when several boundaries share one id. */\n readonly key?: string;\n /** The page route the boundary belongs to; authorization is bound to it. */\n readonly route: string;\n /** The page's query string, so a `previewToken` in the URL reaches the endpoint. */\n readonly search: string;\n readonly revision: number;\n readonly locale?: string;\n readonly collectionSlug?: string;\n readonly globalSlug?: string;\n /** The unsaved form state as the admin posted it, after the runtime's merge. */\n readonly fields: Readonly<Record<string, unknown>>;\n}\n\n/** @internal */\nexport interface FragmentResponseBody {\n /** The boundary's new inner HTML. */\n readonly html: string;\n readonly boundary: { readonly id: string; readonly key?: string };\n /** Echoes the request; the client discards a response for another revision. */\n readonly revision: number;\n readonly metadata: {\n readonly renderedAt: string;\n /** What rendered it, e.g. `astro-container`. */\n readonly renderer: string;\n readonly durationMs?: number;\n };\n}\n\n// Bounds the walk over a body anyone may post, not the content: a bulleted list\n// in a column's rich text inside a layout block is 13 levels, a list nested\n// five levels 29 (ADR 0027). The byte cap bounds the rest.\n/** Fixed upper bound for validation before authorization. @internal */\nexport const MAX_FIELD_DEPTH = 64;\n\nfunction depthOf(value: unknown, depth: number, maxDepth: number): number {\n if (depth > maxDepth || typeof value !== 'object' || value === null) return depth;\n let deepest = depth;\n for (const child of Object.values(value)) {\n deepest = Math.max(deepest, depthOf(child, depth + 1, maxDepth));\n if (deepest > maxDepth) break;\n }\n return deepest;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** Shape check for a request body; `null` when it is not one. @internal */\nexport function parseFragmentRequest(\n value: unknown,\n maxFieldDepth = MAX_FIELD_DEPTH,\n): FragmentRequestBody | null {\n const result = parseFragmentRequestResult(value, maxFieldDepth);\n return result === 'field-depth' ? null : result;\n}\n\n/** Request validation with a distinct depth refusal for endpoint diagnostics. @internal */\nexport function parseFragmentRequestResult(\n value: unknown,\n maxFieldDepth = MAX_FIELD_DEPTH,\n): FragmentRequestBody | 'field-depth' | null {\n if (!Number.isInteger(maxFieldDepth) || maxFieldDepth < 0 || maxFieldDepth > MAX_FIELD_DEPTH) {\n return null;\n }\n if (!isRecord(value)) return null;\n const fragment = value['fragment'];\n if (typeof fragment !== 'string' || !/^[a-z][a-z0-9-]{0,63}$/iu.test(fragment)) return null;\n const key = value['key'];\n if (key !== undefined && (typeof key !== 'string' || key.length > 128)) return null;\n const route = value['route'];\n if (typeof route !== 'string' || !route.startsWith('/') || route.length > 2048) return null;\n const search = value['search'];\n if (\n typeof search !== 'string' ||\n search.length > 4096 ||\n (search !== '' && !search.startsWith('?'))\n ) {\n return null;\n }\n const revision = value['revision'];\n if (typeof revision !== 'number' || !Number.isInteger(revision) || revision < 0) return null;\n const slugs: (string | undefined)[] = [];\n for (const name of ['locale', 'collectionSlug', 'globalSlug'] as const) {\n const slug = value[name];\n if (slug === undefined) {\n slugs.push(undefined);\n continue;\n }\n if (typeof slug !== 'string' || slug.length > 128) return null;\n slugs.push(slug);\n }\n const [locale, collectionSlug, globalSlug] = slugs;\n const fields = value['fields'];\n if (!isRecord(fields)) return null;\n if (depthOf(fields, 0, maxFieldDepth) > maxFieldDepth) return 'field-depth';\n return {\n fragment,\n ...(typeof key === 'string' ? { key } : {}),\n route,\n search,\n revision,\n ...(locale !== undefined ? { locale } : {}),\n ...(collectionSlug !== undefined ? { collectionSlug } : {}),\n ...(globalSlug !== undefined ? { globalSlug } : {}),\n fields,\n };\n}\n\n/** Shape check for a response body; `null` when it is not one. @internal */\nexport function parseFragmentResponse(value: unknown): FragmentResponseBody | null {\n if (!isRecord(value)) return null;\n const { html, boundary, revision, metadata } = value;\n if (typeof html !== 'string') return null;\n if (!isRecord(boundary) || typeof boundary['id'] !== 'string') return null;\n if (boundary['key'] !== undefined && typeof boundary['key'] !== 'string') return null;\n if (typeof revision !== 'number') return null;\n if (\n !isRecord(metadata) ||\n typeof metadata['renderedAt'] !== 'string' ||\n typeof metadata['renderer'] !== 'string'\n ) {\n return null;\n }\n return value as unknown as FragmentResponseBody;\n}\n","/**\n * The fragment endpoint, without a component system (ADR 0011): it renders a\n * registered boundary from unsaved form state for an authorized preview, and\n * nothing else. The browser names a registry id; the server decides what that\n * id renders.\n *\n * Everything here is framework-neutral — method and origin checks, the body\n * limit, the protocol, authorization, the registry lookup, the timeouts and the\n * response shape. Each server adapter binds one renderer and its native route\n * shape; Astro, Next.js, SvelteKit and Nuxt all delegate the decisions here.\n */\nimport {\n authorizePreviewRequest,\n type PreviewAuthorizationStrategy,\n} from '@security/preview-authorization';\nimport type { PreviewAuthorization } from '@security/preview-verdict';\nimport type { AuthorizedPreviewContext } from '@/types/authorized-preview';\nimport {\n isPayloadScopeCurrent,\n matchesPreviewDocument,\n matchesPreviewDocumentData,\n} from '@security/preview-scope';\nimport { runAuthorizeHook } from './authorize-hook';\nimport { warnOnce } from '@/types/dev-warning';\nimport type { PreviewAdapterOptions } from './options';\nimport { positiveIntegerLimit } from './fragment-limits';\nimport {\n FRAGMENT_PROTOCOL_VERSION,\n FRAGMENT_VERSION_HEADER,\n MAX_FIELD_DEPTH,\n parseFragmentRequestResult,\n type FragmentRequestBody,\n type FragmentResponseBody,\n} from '@/types/fragment-protocol';\n\n/** Everything a registry entry may use to compute its props. */\nexport interface FragmentRenderInput {\n readonly id: string;\n readonly key: string | undefined;\n readonly revision: number;\n readonly fields: Readonly<Record<string, unknown>>;\n readonly locale: string | undefined;\n readonly collectionSlug: string | undefined;\n readonly globalSlug: string | undefined;\n readonly route: string;\n readonly authorization: AuthorizedPreviewContext;\n /** Aborts when the request, its total deadline, or a render phase ends early. */\n readonly signal: AbortSignal;\n readonly request: Request;\n /** What the framework's server code put on this request: Astro `locals`, SvelteKit `event.locals`, Nuxt `event.context`; Next.js none (ADR 0029). */\n readonly locals: unknown;\n}\n\n/**\n * `Props extends object`, not `Record<string, unknown>`: an `interface` has no\n * implicit index signature, so the natural way to type a component's props\n * would not satisfy the narrower constraint and every consumer would have to\n * restate their props as a type alias. The renderer widens once, where the\n * props are handed to it.\n */\nexport interface FragmentRegistryEntry<Component, Props extends object = object> {\n readonly component: Component;\n /** Props for the component, computed from the input; never from request-controlled code. */\n readonly props: (input: FragmentRenderInput) => Props | Promise<Props>;\n}\n\nexport type FragmentRegistry<Component> = Readonly<\n Record<string, FragmentRegistryEntry<Component>>\n>;\n\n/** Renders a component with props to HTML. Each adapter supplies its own. */\nexport type FragmentRenderer<Component> = (\n component: Component,\n props: Record<string, unknown>,\n input: FragmentRenderInput,\n) => Promise<string>;\n\nexport interface FragmentEndpointOptions<Component> {\n /** The only things this endpoint can render. */\n readonly registry: FragmentRegistry<Component>;\n /**\n * The middleware's `authorizePreview` hook — same type, same rules: a\n * context `authorizePreviewRequest()` produced authorizes, anything else\n * refuses, a `PreviewConfigurationError` is loud. It is called with the\n * page request the fragment belongs to (route, search, and this request's\n * headers), so a token stays bound to its route and a session is the\n * visitor's own. One of `authorizePreview` and `authorize` is required.\n */\n readonly authorizePreview?: NonNullable<PreviewAdapterOptions['authorizePreview']>;\n /** A strategy for `authorizePreviewRequest()`, when there is no hook to share. Exclusive with `authorizePreview`. */\n readonly authorize?: PreviewAuthorizationStrategy;\n /** Override the adapter's renderer (tests, another component system). */\n readonly render?: FragmentRenderer<Component>;\n /** Origins besides the page's own that may call the endpoint. Default: none. */\n readonly allowedOrigins?: readonly string[];\n readonly limits?: {\n /** Largest streamed request body in bytes. Default 64 KiB. */\n readonly bodyBytes?: number;\n /** Body-read and per-render-phase timeout. Default 5000 ms. */\n readonly timeoutMs?: number;\n /** Maximum nesting depth of `fields`. Integer from 0 to 64; default 64. */\n readonly fieldDepth?: number;\n /** One deadline across body, authorization, props and rendering. Default: disabled. */\n readonly totalTimeoutMs?: number;\n };\n}\n\n/** What an adapter adds to the consumer's options: its renderer and the name that goes in the response metadata. */\nexport interface FragmentEndpointBinding<Component> {\n readonly render: FragmentRenderer<Component>;\n readonly rendererName: string;\n /** How the framework transport releases bytes after the endpoint's cap. */\n readonly overLimitBody?: 'cancel' | 'drain';\n}\n\nconst DEFAULT_BODY_BYTES = 64 * 1024;\nconst DEFAULT_TIMEOUT_MS = 5_000;\nconst MAX_TIMER_MS = 2_147_483_647;\n\nconst NO_STORE_HEADERS: Readonly<Record<string, string>> = {\n 'cache-control': 'private, no-store',\n 'x-content-type-options': 'nosniff',\n vary: 'Cookie',\n [FRAGMENT_VERSION_HEADER]: String(FRAGMENT_PROTOCOL_VERSION),\n};\n\n/** A refusal carries an error code and, for depth limits, the configured cap. */\nfunction refuse(status: number, error: string, maxDepth?: number): Response {\n return new Response(JSON.stringify({ error, ...(maxDepth !== undefined ? { maxDepth } : {}) }), {\n status,\n headers: { ...NO_STORE_HEADERS, 'content-type': 'application/json; charset=utf-8' },\n });\n}\n\nfunction sameOrigin(request: Request, allowed: ReadonlySet<string>): boolean {\n const site = request.headers.get('sec-fetch-site');\n if (site !== null && site !== 'same-origin' && site !== 'none') return false;\n const origin = request.headers.get('origin');\n if (origin === null) return true;\n return origin === new URL(request.url).origin || allowed.has(origin);\n}\n\nfunction scopeAllows(\n context: AuthorizedPreviewContext,\n body: FragmentRequestBody,\n page: URL,\n): boolean {\n const scope = context.scope;\n if (scope.locale !== undefined && scope.locale !== body.locale) return false;\n if (scope.payload !== undefined) {\n if (\n !isPayloadScopeCurrent(context) ||\n (scope.audience !== undefined && scope.audience !== page.origin) ||\n (scope.path !== undefined && scope.path !== page.pathname)\n ) {\n return false;\n }\n if (body.collectionSlug !== undefined && body.globalSlug !== undefined) return false;\n if (\n !matchesPreviewDocument(scope.payload.document, {\n kind: body.globalSlug === undefined ? 'collection' : 'global',\n slug: body.globalSlug ?? body.collectionSlug,\n id: body.fields['id'],\n })\n ) {\n return false;\n }\n if (!matchesPreviewDocumentData(scope.payload.document, body.fields)) return false;\n }\n return true;\n}\n\ntype BodyReadResult =\n | { readonly kind: 'parsed'; readonly value: unknown }\n | { readonly kind: 'too-large' | 'timed-out' | 'unreadable' };\n\ntype EndpointStopReason = 'request-aborted' | 'total-timeout' | 'phase-timeout';\n\nclass EndpointStopped extends Error {\n override readonly name = 'EndpointStopped';\n}\n\ninterface EndpointRequestScope {\n readonly signal: AbortSignal;\n readonly reason: () => EndpointStopReason | undefined;\n readonly run: <T>(work: () => T | PromiseLike<T>, phaseTimeoutMs?: number) => Promise<T>;\n readonly dispose: () => void;\n}\n\n/** One cooperative lifetime for all asynchronous work started by an accepted POST. */\nfunction createEndpointRequestScope(\n requestSignal: AbortSignal,\n totalTimeoutMs: number | undefined,\n): EndpointRequestScope {\n const controller = new AbortController();\n const deadline = totalTimeoutMs === undefined ? undefined : performance.now() + totalTimeoutMs;\n let stopped: EndpointStopReason | undefined;\n let resolveStopped: ((reason: EndpointStopReason) => void) | undefined;\n const stoppedPromise = new Promise<EndpointStopReason>((resolve) => {\n resolveStopped = resolve;\n });\n const stop = (reason: EndpointStopReason): void => {\n if (stopped !== undefined) return;\n stopped = reason;\n controller.abort(reason);\n resolveStopped?.(reason);\n };\n const abort = (): void => {\n stop('request-aborted');\n };\n requestSignal.addEventListener('abort', abort, { once: true });\n // AbortSignal does not replay an abort that landed just before registration.\n if (requestSignal.aborted) abort();\n const totalTimer =\n totalTimeoutMs === undefined\n ? undefined\n : setTimeout(() => {\n stop('total-timeout');\n }, totalTimeoutMs);\n const check = (): void => {\n // A long synchronous phase can finish before an overdue timer gets its turn.\n if (deadline !== undefined && performance.now() >= deadline) stop('total-timeout');\n if (stopped !== undefined) throw new EndpointStopped(stopped);\n };\n\n return {\n signal: controller.signal,\n reason: () => stopped,\n run: async <T>(work: () => T | PromiseLike<T>, phaseTimeoutMs?: number): Promise<T> => {\n check();\n const phaseTimer =\n phaseTimeoutMs === undefined\n ? undefined\n : setTimeout(() => {\n stop('phase-timeout');\n }, phaseTimeoutMs);\n try {\n // The race attaches rejection handlers to both promises, including a\n // late rejection by work that ignores the cooperative signal.\n const value = await Promise.race([\n Promise.resolve().then(() => {\n check();\n return work();\n }),\n stoppedPromise.then((reason) => {\n throw new EndpointStopped(reason);\n }),\n ]);\n // Cooperative work may settle from the abort event itself. The stop\n // remains authoritative, so no following phase starts after it.\n check();\n return value;\n } catch (error) {\n check();\n throw error;\n } finally {\n if (phaseTimer !== undefined) clearTimeout(phaseTimer);\n }\n },\n dispose: () => {\n if (totalTimer !== undefined) clearTimeout(totalTimer);\n requestSignal.removeEventListener('abort', abort);\n },\n };\n}\n\n/** A declared length may refuse early, but only consumed bytes may admit. */\nfunction declaredLengthExceeds(request: Request, limit: number): boolean {\n const declared = request.headers.get('content-length');\n if (declared === null || !/^[0-9]+$/u.test(declared)) return false;\n const normalized = declared.replace(/^0+/u, '') || '0';\n const boundary = String(limit);\n return (\n normalized.length > boundary.length ||\n (normalized.length === boundary.length && normalized > boundary)\n );\n}\n\n/** Cancel without letting a request-controlled stream delay or reject the response. */\nfunction cancelStream(\n stream: ReadableStream<Uint8Array> | null,\n reason: 'too-large' | 'timed-out' | 'unreadable',\n): void {\n if (stream === null || stream.locked) return;\n try {\n void Promise.resolve(stream.cancel(reason)).catch(() => undefined);\n } catch {\n // A broken transport is still one generic body refusal.\n }\n}\n\nfunction signalIsAborted(signal: AbortSignal): boolean {\n return signal.aborted;\n}\n\n/** Read one Web Request body under an actual-byte cap and one total read deadline. */\nasync function readBody(\n request: Request,\n signal: AbortSignal,\n limit: number,\n timeoutMs: number,\n overLimitBody: 'cancel' | 'drain',\n): Promise<BodyReadResult> {\n const stream = request.body;\n if (signalIsAborted(signal) || request.bodyUsed || stream?.locked === true) {\n cancelStream(stream, 'unreadable');\n return { kind: 'unreadable' };\n }\n if (declaredLengthExceeds(request, limit)) {\n // Do not cancel a body no application reader acquired. SvelteKit maps\n // cancellation to `IncomingMessage.destroy()`, which resets the socket\n // before it can write this endpoint's 413 response. The framework owns\n // disposal of an unread transport after the handler returns.\n return { kind: 'too-large' };\n }\n if (stream === null) return { kind: 'parsed', value: null };\n\n let reader: ReadableStreamDefaultReader<Uint8Array>;\n try {\n reader = stream.getReader();\n } catch {\n cancelStream(stream, 'unreadable');\n return { kind: 'unreadable' };\n }\n\n type StopReason = 'too-large' | 'timed-out' | 'unreadable';\n type ReadRace =\n | { readonly kind: 'read'; readonly result: ReadableStreamReadResult<Uint8Array> }\n | { readonly kind: 'read-error' }\n | { readonly kind: 'stopped'; readonly reason: StopReason };\n let stopped: StopReason | undefined;\n let resolveStopped: ((result: ReadRace) => void) | undefined;\n const stoppedPromise = new Promise<ReadRace>((resolve) => {\n resolveStopped = resolve;\n });\n const stop = (reason: StopReason): void => {\n if (stopped !== undefined) return;\n stopped = reason;\n resolveStopped?.({ kind: 'stopped', reason });\n try {\n void Promise.resolve(reader.cancel(reason)).catch(() => undefined);\n } catch {\n // The first stop reason remains authoritative even if cancellation fails.\n }\n };\n const abort = (): void => {\n stop('unreadable');\n };\n signal.addEventListener('abort', abort, { once: true });\n // An abort can land between the preflight check and listener registration.\n // AbortSignal does not replay that event to a late listener.\n if (signalIsAborted(signal)) abort();\n const timer = setTimeout(() => {\n stop('timed-out');\n }, timeoutMs);\n const decoder = new TextDecoder();\n let text = '';\n let total = 0;\n let overLimit = false;\n\n try {\n for (;;) {\n const read = Promise.resolve()\n .then(() => reader.read())\n .then<ReadRace, ReadRace>(\n (result) => ({ kind: 'read', result }),\n () => ({ kind: 'read-error' }),\n );\n const next = await Promise.race([read, stoppedPromise]);\n if (next.kind === 'stopped') return { kind: next.reason };\n if (next.kind === 'read-error') {\n if (overLimit) return { kind: 'too-large' };\n stop('unreadable');\n return { kind: 'unreadable' };\n }\n if (stopped !== undefined) return { kind: stopped };\n if (next.result.done) {\n if (overLimit) return { kind: 'too-large' };\n break;\n }\n if (overLimit) continue;\n if (next.result.value.byteLength > limit - total) {\n // SvelteKit's Node bridge implements Web-stream cancellation as\n // IncomingMessage.destroy(). Drain there under this same deadline so\n // the framework can write the 413; no discarded byte is retained or\n // parsed. Fetch-native transports still cancel immediately.\n if (overLimitBody === 'drain') {\n overLimit = true;\n continue;\n }\n stop('too-large');\n return { kind: 'too-large' };\n }\n total += next.result.value.byteLength;\n try {\n text += decoder.decode(next.result.value, { stream: true });\n } catch {\n stop('unreadable');\n return { kind: 'unreadable' };\n }\n }\n try {\n text += decoder.decode();\n return { kind: 'parsed', value: JSON.parse(text) as unknown };\n } catch {\n // A complete body under the byte cap can still be the wrong shape.\n return { kind: 'parsed', value: null };\n }\n } finally {\n clearTimeout(timer);\n signal.removeEventListener('abort', abort);\n try {\n reader.releaseLock();\n } catch {\n // Some non-conforming transports keep a read pending after cancel.\n }\n }\n}\n\ntype FragmentAuthorizer = (pageRequest: Request) => Promise<PreviewAuthorization>;\n\n/** One authorizer from the two options: the hook decides as it does in the middleware, a strategy as `authorizePreviewRequest()` does. */\nfunction authorizerFor<Component>(options: FragmentEndpointOptions<Component>): FragmentAuthorizer {\n const { authorize, authorizePreview } = options;\n if (authorizePreview !== undefined && authorize !== undefined) {\n throw new Error(\n 'payload-live-preview: createFragmentEndpoint() takes `authorizePreview` or `authorize`, ' +\n 'not both — pass the middleware hook as `authorizePreview`, or a strategy as `authorize`.',\n );\n }\n if (authorizePreview !== undefined) {\n return (pageRequest) => runAuthorizeHook(() => authorizePreview(pageRequest));\n }\n if (authorize !== undefined) {\n return (pageRequest) => authorizePreviewRequest(pageRequest, authorize);\n }\n throw new Error(\n 'payload-live-preview: createFragmentEndpoint() needs `authorizePreview` (the middleware hook) ' +\n 'or `authorize` (a strategy); without one it would render drafts for anyone.',\n );\n}\n\n/**\n * The endpoint as a plain `Request` → `Response` function. Adapters wrap it in\n * whatever their framework hands a route handler.\n */\nexport function createFragmentEndpointHandler<Component>(\n options: FragmentEndpointOptions<Component>,\n binding: FragmentEndpointBinding<Component>,\n): (request: Request, locals?: unknown) => Promise<Response> {\n const authorize = authorizerFor(options);\n const render = options.render ?? binding.render;\n const rendererName = options.render === undefined ? binding.rendererName : 'custom';\n const allowed = new Set(options.allowedOrigins ?? []);\n const bodyLimit = positiveIntegerLimit(\n 'bodyBytes',\n options.limits?.bodyBytes,\n DEFAULT_BODY_BYTES,\n Number.MAX_SAFE_INTEGER,\n );\n const timeoutMs = positiveIntegerLimit(\n 'timeoutMs',\n options.limits?.timeoutMs,\n DEFAULT_TIMEOUT_MS,\n MAX_TIMER_MS,\n );\n const totalTimeoutMs =\n options.limits?.totalTimeoutMs === undefined\n ? undefined\n : positiveIntegerLimit('totalTimeoutMs', options.limits.totalTimeoutMs, 0, MAX_TIMER_MS);\n const { fieldDepth = MAX_FIELD_DEPTH } = options.limits ?? {};\n if (!Number.isInteger(fieldDepth) || fieldDepth < 0 || fieldDepth > MAX_FIELD_DEPTH) {\n throw new TypeError(\n 'createFragmentEndpoint: limits.fieldDepth must be an integer from 0 to 64',\n );\n }\n const registry = options.registry;\n\n return async (request, locals) => {\n if (request.method !== 'POST') return refuse(405, 'method');\n if (!sameOrigin(request, allowed)) return refuse(403, 'origin');\n const type = request.headers.get('content-type') ?? '';\n if (!type.toLowerCase().startsWith('application/json')) return refuse(415, 'content-type');\n const scope = createEndpointRequestScope(request.signal, totalTimeoutMs);\n const bodyState = { started: false, read: false };\n try {\n const raw = await scope.run(() => {\n bodyState.started = true;\n return readBody(\n request,\n scope.signal,\n bodyLimit,\n timeoutMs,\n binding.overLimitBody ?? 'cancel',\n );\n });\n if (raw.kind !== 'parsed') {\n if (raw.kind === 'too-large') return refuse(413, 'body');\n if (raw.kind === 'timed-out') return refuse(408, 'body');\n return refuse(400, 'body');\n }\n const body = parseFragmentRequestResult(raw.value, fieldDepth);\n if (body === 'field-depth') return refuse(400, 'field-depth', fieldDepth);\n if (body === null) return refuse(400, 'shape');\n bodyState.read = true;\n\n // Authorize as the page would, so a token stays bound to the route it was\n // issued for and a session is the visitor's own.\n const origin = new URL(request.url).origin;\n const pageRequest = new Request(`${origin}${body.route}${body.search}`, {\n headers: request.headers,\n signal: scope.signal,\n });\n const authorization = await scope.run(() => authorize(pageRequest));\n if (\n !authorization.authorized ||\n !scopeAllows(authorization.context, body, new URL(pageRequest.url))\n ) {\n return refuse(403, 'unauthorized');\n }\n const entry = Object.prototype.hasOwnProperty.call(registry, body.fragment)\n ? registry[body.fragment]\n : undefined;\n if (entry === undefined) return refuse(404, 'fragment');\n\n const input: FragmentRenderInput = {\n locals,\n id: body.fragment,\n key: body.key,\n revision: body.revision,\n fields: body.fields,\n locale: body.locale,\n collectionSlug: body.collectionSlug,\n globalSlug: body.globalSlug,\n route: body.route,\n authorization: authorization.context,\n signal: scope.signal,\n request,\n };\n const started = Date.now();\n let html: string;\n try {\n const props = await scope.run(() => entry.props(input), timeoutMs);\n if (\n input.authorization.scope.payload !== undefined &&\n !isPayloadScopeCurrent(input.authorization)\n ) {\n return refuse(403, 'unauthorized');\n }\n // The one widening: the site types its props as it likes (see\n // FragmentRegistryEntry), the renderer takes a record of them.\n const record = props as Record<string, unknown>;\n html = await scope.run(() => render(entry.component, record, input), timeoutMs);\n if (\n input.authorization.scope.payload !== undefined &&\n !isPayloadScopeCurrent(input.authorization)\n ) {\n return refuse(403, 'unauthorized');\n }\n } catch (error) {\n if (error instanceof EndpointStopped) throw error;\n // The response stays generic; the server log is where the cause belongs,\n // and without it a 500 here is a boundary that silently never renders.\n warnOnce(\n `fragment-render:${body.fragment}`,\n `fragment \"${body.fragment}\" did not render: ${error instanceof Error ? error.message : String(error)}`,\n );\n return refuse(500, 'render');\n }\n const response: FragmentResponseBody = {\n html,\n boundary: { id: body.fragment, ...(body.key !== undefined ? { key: body.key } : {}) },\n revision: body.revision,\n metadata: {\n renderedAt: new Date().toISOString(),\n renderer: rendererName,\n durationMs: Date.now() - started,\n },\n };\n return new Response(JSON.stringify(response), {\n status: 200,\n headers: { ...NO_STORE_HEADERS, 'content-type': 'application/json; charset=utf-8' },\n });\n } catch (error) {\n if (!(error instanceof EndpointStopped)) throw error;\n // A pre-read stop still disposes the unread body, without acquiring it.\n if (!bodyState.started) cancelStream(request.body, 'unreadable');\n if (scope.reason() === 'total-timeout') return refuse(504, 'timeout');\n if (scope.reason() === 'phase-timeout') return refuse(500, 'render');\n return refuse(400, bodyState.read ? 'request' : 'body');\n } finally {\n scope.dispose();\n }\n };\n}\n","/**\n * The Next.js binding of the fragment endpoint: React as the renderer, and the\n * endpoint shaped as an App Router route handler. Everything the endpoint\n * decides is in `@adapters/shared/fragment-endpoint`.\n *\n * `react` and `react-dom` are optional peers loaded at first render. A project\n * that never renders a fragment — most of them — installs neither, and a\n * project that does has both anyway.\n */\nimport { lazyPeer, missingPeerError } from '@adapters/shared/optional-peer';\nimport {\n createFragmentEndpointHandler,\n type FragmentEndpointOptions as SharedOptions,\n type FragmentRegistry as SharedRegistry,\n type FragmentRegistryEntry as SharedRegistryEntry,\n type FragmentRenderer as SharedRenderer,\n type FragmentRenderInput,\n} from '@adapters/shared/fragment-endpoint';\n\nexport type { FragmentRenderInput } from '@adapters/shared/fragment-endpoint';\n\n/**\n * A React function component.\n *\n * The parameter is `never` rather than the props object it will receive:\n * parameters are checked contravariantly, so this accepts a component with any\n * props while a `Record<string, unknown>` would accept almost none. What the\n * component and its props have to agree on is checked by `defineFragment()`,\n * which is why that helper exists.\n */\nexport type ReactComponentLike = (props: never) => unknown;\n\nexport type FragmentRegistryEntry<Props extends object = object> = SharedRegistryEntry<\n ReactComponentLike,\n Props\n>;\n/** @internal */\nexport type FragmentRegistry = SharedRegistry<ReactComponentLike>;\n/** @internal */\nexport type FragmentRenderer = SharedRenderer<ReactComponentLike>;\nexport type FragmentEndpointOptions = SharedOptions<ReactComponentLike>;\n\nconst RENDERER_NAME = 'react-dom';\n\ninterface ReactRuntime {\n readonly createElement: (\n component: ReactComponentLike,\n props: Record<string, unknown>,\n ) => unknown;\n readonly renderToString: (element: unknown) => string;\n}\n\nconst loadReact = lazyPeer(async (): Promise<ReactRuntime> => {\n // Literal specifiers let the consumer's bundler resolve the same renderer peers\n // as its components. Loading still waits for the first fragment render.\n try {\n const [react, server] = await Promise.all([\n import('react') as Promise<{\n createElement: ReactRuntime['createElement'];\n }>,\n import('react-dom/server') as Promise<{\n renderToString: ReactRuntime['renderToString'];\n }>,\n ]);\n return { createElement: react.createElement, renderToString: server.renderToString };\n } catch (cause) {\n throw missingPeerError(['react', 'react-dom'], cause);\n }\n});\n\nconst renderWithReact: FragmentRenderer = async (component, props) => {\n const { createElement, renderToString } = await loadReact();\n return renderToString(createElement(component, props));\n};\n\n/**\n * Pairs a component with the props it takes, so the two cannot drift apart.\n * Without it a registry entry types its props as any record and a renamed prop\n * is found by the editor, in the preview, at the worst moment.\n *\n * ```ts\n * const registry = { hero: defineFragment(Hero, ({ fields }) => ({ title: String(fields.title ?? '') })) };\n * ```\n */\nexport function defineFragment<Props extends object>(\n component: (props: Props) => unknown,\n props: (input: FragmentRenderInput) => Props | Promise<Props>,\n): FragmentRegistryEntry<Props> {\n return { component, props };\n}\n\n/** Build the endpoint; export it as the `POST` of an App Router route handler. */\nexport function createFragmentEndpoint(\n options: FragmentEndpointOptions,\n): (request: Request) => Promise<Response> {\n const handler = createFragmentEndpointHandler(options, {\n render: renderWithReact,\n rendererName: RENDERER_NAME,\n });\n // Next.js calls a route handler as handler(request, { params }); that route\n // context is not the request's `locals` (ADR 0029), so only the request goes on.\n return (request) => handler(request);\n}\n","/**\n * `withLivePreview(nextConfig)` — the parts of a Next.js setup that belong in\n * `next.config.ts` rather than in a layout: the admin's host in\n * `allowedDevOrigins`, so Next's dev server does not refuse the admin's own\n * server actions behind a proxy, and `private, no-store` on a request that\n * carries preview intent.\n *\n * What it cannot do is inject the script: no config hook renders HTML. That\n * stays one import and one spread in `app/layout.tsx` (docs/nextjs.md), so this\n * is a two-line setup, not a one-line one — said plainly rather than implied\n * away.\n *\n * **And it writes no CSP.** A config rule cannot run `authorizePreview`, so it\n * can never be the place a privileged response change is decided (ADR 0006 §5).\n * It could not even widen `frame-ancestors` safely: Next collects every\n * matching rule into one object keyed by header name and applies it with\n * `setHeader`, and these rules are appended after the consumer's, so a policy\n * written here replaces the one the site already sends instead of adding to\n * it. Measured on Next.js 16.3.4 (`next build` + `next start`): a site sending\n * `frame-ancestors 'none'` answered a bare `/?preview=true` with\n * `frame-ancestors 'self' <admin>` and nothing else — its `script-src` gone,\n * for anyone who appends the query parameter. `frame-ancestors` for the admin\n * origin is `createLivePreviewMiddleware`'s, which merges into an existing\n * policy and only once the engine has authorized the request.\n */\n\n/** The slice of `next.config` this touches; everything else is passed through. */\nexport interface NextConfigLike {\n readonly allowedDevOrigins?: readonly string[];\n readonly headers?: () => Promise<readonly NextHeaderRule[]> | readonly NextHeaderRule[];\n readonly [option: string]: unknown;\n}\n\nexport interface NextHeaderRule {\n readonly source: string;\n readonly headers: readonly { readonly key: string; readonly value: string }[];\n readonly has?: readonly {\n readonly type: string;\n readonly key: string;\n readonly value?: string;\n }[];\n readonly [option: string]: unknown;\n}\n\nexport interface WithLivePreviewOptions {\n /** Payload admin origins. Required; their hosts are what `allowedDevOrigins` needs. */\n readonly allowedOrigins: readonly string[];\n /**\n * Query parameters that mark preview intent, matching the runtime's own\n * defaults. The cache header is set only for requests carrying one of them.\n */\n readonly previewQueryParams?: readonly string[];\n /** Add the admin origins to `allowedDevOrigins`. Default `true`. */\n readonly allowDevOrigins?: boolean;\n}\n\nconst DEFAULT_QUERY_PARAMS: readonly string[] = ['preview', 'draft', 'livePreview'];\n\nfunction hostOf(origin: string): string | undefined {\n try {\n return new URL(origin).host;\n } catch {\n return undefined;\n }\n}\n\n/** One rule per intent parameter: Next matches `has` entries as a conjunction. @internal */\nexport function previewHeaderRules(options: WithLivePreviewOptions): readonly NextHeaderRule[] {\n return (options.previewQueryParams ?? DEFAULT_QUERY_PARAMS).map((key) => ({\n source: '/:path*',\n // Next anchors `value` as a regular expression (`^${value}$`, matchHas in\n // next/dist/shared/lib/router/utils/prepare-destination). The runtime reads\n // `true` and `1` as intent, and so must the rule, or `?preview=1` stays\n // cacheable; the group keeps the anchors around both alternatives.\n has: [{ type: 'query', key, value: '(?:true|1)' }],\n headers: [\n // A preview response is one visitor's unsaved state; a shared cache must\n // never keep it, and the same rule the adapters apply belongs here. It\n // restricts and grants nothing, which is why an unverified request may\n // set it where it may not set a CSP.\n { key: 'Cache-Control', value: 'private, no-store' },\n ],\n }));\n}\n\n/**\n * ```ts\n * // next.config.ts\n * export default withLivePreview(nextConfig, {\n * allowedOrigins: [process.env.NEXT_PUBLIC_PAYLOAD_URL!],\n * });\n * ```\n */\nexport function withLivePreview(\n nextConfig: NextConfigLike,\n options: WithLivePreviewOptions,\n): NextConfigLike {\n if (options.allowedOrigins.length === 0) {\n throw new Error(\n 'payload-live-preview: withLivePreview() needs at least one admin origin in ' +\n '`allowedOrigins`; without one there is no host to add to `allowedDevOrigins` and the ' +\n 'call would configure nothing.',\n );\n }\n const rules = previewHeaderRules(options);\n const existingHeaders = nextConfig.headers;\n const devOrigins =\n options.allowDevOrigins === false\n ? nextConfig.allowedDevOrigins\n : [\n ...(nextConfig.allowedDevOrigins ?? []),\n ...options.allowedOrigins\n .map(hostOf)\n .filter((host): host is string => host !== undefined),\n ];\n\n return {\n ...nextConfig,\n ...(devOrigins === undefined ? {} : { allowedDevOrigins: [...new Set(devOrigins)] }),\n headers: async () => [...(await (existingHeaders?.() ?? [])), ...rules],\n };\n}\n","/**\n * The route half of `delivery: 'asset'` for Next.js.\n *\n * ```ts\n * // app/payload-live-preview/[file]/route.ts\n * import { createRuntimeAssetRoute } from 'payload-live-preview/nextjs';\n *\n * export const { GET } = createRuntimeAssetRoute();\n * ```\n *\n * The dynamic segment is what carries the content hash. The handler answers\n * only the file name this package build produces and 404s everything else, so a\n * client holding a year-old `immutable` copy of some other build gets an\n * honest miss rather than different bytes under the same name.\n *\n * No route segment config is exported with it. `dynamic: 'force-static'` would\n * be tempting — the bytes are the same for every request — but on a dynamic\n * segment it asks Next to prerender one arbitrary param at build time. The\n * caching that matters is the response's own `immutable`, which browsers and\n * CDNs honour without Next's help.\n */\n\nimport { runtimeAssetResponse } from '@adapters/shared/runtime-asset';\nimport type { LivePreviewNextOptions } from './adapter';\n\n/** What a route file re-exports. */\nexport interface RuntimeAssetRoute {\n readonly GET: (request: Request) => Response;\n}\n\n/**\n * Takes the adapter's own options so the one object can be passed to both\n * halves: only `assetPath` and `runtime` are read, but those two are exactly\n * what the page and the route have to agree on, and `runtime: LEAN_RUNTIME`\n * means the page asks for that artifact's hash.\n */\nexport function createRuntimeAssetRoute(options: LivePreviewNextOptions = {}): RuntimeAssetRoute {\n return { GET: (request) => runtimeAssetResponse(request.url, options) };\n}\n","/**\n * `<LivePreviewScript />` — the delivery that charges an anonymous visitor\n * nothing.\n *\n * A root layout renders for every request, and the two helpers that served it\n * until now build the script whoever is asking: `livePreviewScriptProps()` and\n * `renderLivePreviewScript()` are synchronous, so they cannot wait for a\n * verdict and do not try. That is why the demo answered a `curl` without a\n * cookie with 195 342 of 254 707 bytes of preview runtime — once in the\n * document, once more escaped into the RSC flight payload underneath it.\n *\n * An async server component can wait. This one runs the same policy every\n * adapter runs — intent, then `authorizePreview` — and returns `null` unless\n * the answer is yes. Not a few hundred bytes of bootstrap for the public:\n * nothing, the same as the Astro middleware, the SvelteKit handle and the Nuxt\n * Nitro plugin already deliver.\n *\n * **`next` is not imported here and must not become a dependency.** The\n * component takes the request as a prop, the way `<LivePreviewRouteRefresh />`\n * takes the router's refresh, and the caller builds it from what the framework\n * hands a server component:\n *\n * ```tsx\n * // app/layout.tsx — the App Router\n * import { headers } from 'next/headers';\n * import { LivePreviewScript } from 'payload-live-preview/nextjs';\n *\n * export default async function RootLayout({ children }: { children: ReactNode }) {\n * const livePreview = await LivePreviewScript({\n * request: new Request(SITE_URL, { headers: await headers() }),\n * inject: 'always',\n * allowedOrigins: [ADMIN_URL],\n * authorizePreview: authorize,\n * });\n * return (\n * <html lang=\"en\">\n * <head>{livePreview}</head>\n * <body>{children}</body>\n * </html>\n * );\n * }\n * ```\n *\n * It is awaited rather than rendered as `<LivePreviewScript />`: an element of\n * an async server component arrives in React's stream after the page, and the\n * React that Next.js 15.5 ships begins to hydrate `<head>` before it has, which\n * it reports as error #418 (docs/nextjs.md, \"Await it in the layout\").\n *\n * A `Request` rather than a shape of our own: it is what `authorizePreview`\n * and `shouldInject` already receive from the middleware, so one options object\n * serves both entry points and neither hook has to be written twice.\n *\n * The URL is the caller's to supply, and the recipe above says why `headers()`\n * alone is not enough: Next gives a server component the request headers and\n * cookies but not its URL, so a layout cannot see `?preview=true` and the\n * `query` signal — the 2.0 default — cannot fire there. `inject: 'always'`\n * then makes `authorizePreview` the single gate, which is the stricter reading\n * anyway and exactly what LP-8 needs. A page, which does get `searchParams`,\n * can pass the real URL and keep intent as the cheap pre-filter it is.\n * docs/nextjs.md carries both recipes.\n */\n\nimport { createPreviewPolicy } from '@adapters/shared/policy';\nimport { bindDecisionHooks } from '@adapters/shared/response';\nimport { lazyPeer } from '@adapters/shared/optional-peer';\nimport { livePreviewScriptProps, type LivePreviewNextOptions } from './adapter';\nimport type { LivePreviewScriptProps } from './adapter';\n\n/** What the component takes: every adapter option, plus the request it decides for. */\nexport interface LivePreviewScriptComponentProps extends LivePreviewNextOptions {\n /**\n * The request this render answers: in the App Router, a `Request` built from\n * the URL and `await headers()`. A promise is accepted so the caller need not\n * resolve `headers()` first.\n */\n readonly request: Request | Promise<Request>;\n /** CSP nonce for the element, when the application manages one. */\n readonly nonce?: string;\n}\n\n/**\n * The `<script>` this resolves to, described structurally rather than as\n * `ReactElement`: the entry must not carry React's types any more than its\n * code, and a JSX consumer accepts this shape as a node all the same.\n */\nexport interface LivePreviewScriptElement {\n readonly type: 'script';\n readonly props: LivePreviewScriptProps;\n readonly key: null;\n}\n\ntype CreateElement = (type: 'script', props: LivePreviewScriptProps) => LivePreviewScriptElement;\n\n/**\n * `react` is an optional peer of this package and a hard dependency of any app\n * that can render this component, so it is loaded at the first render that\n * produces an element — never at import, and never on a public request, which\n * returns before reaching this.\n */\nconst loadCreateElement = lazyPeer(async (): Promise<CreateElement> => {\n // A literal lets the app's bundler resolve its peer without an empty context.\n const react = (await import('react')) as {\n createElement: CreateElement;\n };\n return react.createElement;\n});\n\n/**\n * Resolves to the runtime's `<script>` element for an authorized preview and to\n * `null` for everyone else. Await it in the layout or page that owns `<head>`\n * and render the result there.\n */\nexport async function LivePreviewScript(\n props: LivePreviewScriptComponentProps,\n): Promise<LivePreviewScriptElement | null> {\n const { request, nonce, ...options } = props;\n const policy = createPreviewPolicy(options);\n const resolved = await request;\n const decision = await policy.decide(resolved, bindDecisionHooks(policy, options, resolved));\n if (!decision.inject) return null;\n const createElement = await loadCreateElement();\n return createElement(\n 'script',\n livePreviewScriptProps(nonce === undefined ? options : { ...options, nonce }),\n );\n}\n"],"mappings":"AAKA,IAGMA,EAAuB,eAG7B,SAASC,EAAgBC,EAAeC,GACtC,MAAMC,EAAOF,EAAMG,WAAWF,GAC9B,OAAgB,IAATC,GAAuB,KAATA,GAAwB,KAATA,GAAwB,KAATA,GAAwB,KAATA,CACpE,CAWA,SAASE,EAAkBJ,GACzB,IAAIK,EAAQ,EACRC,EAAMN,E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