@murumets-ee/content-api 0.101.0 → 0.102.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -4
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{CountCache as e,SITE_COLUMN as t,SiteRequiredError as n,blockTreeFieldsOf as r,blockTreeTemplateOf as i,buildTranslationsSearchExists as a,decodeCursor as o,encodeCursor as s,filterTranslatableFields as c,getEntityTitleField as l,getSearchableConfig as u,hasSiteTemplates as d,isSiteBound as f,isSortOnlyInternalField as p,isTemplateDrawn as m,isValidSiteHandle as h}from"@murumets-ee/entity";import{LOCALE_PATTERN as g,REQUEST_ID_HEADER as _,escapeLikePattern as v,getApp as y,getAppOrUndefined as b,getContext as x,getCurrentSite as S,readSiteOriginIndex as C,readSiteRecord as w,requireSiteFor as T,resolveImplicitSite as E,resolveRequestId as D,runBounded as O,runWithContextAsync as ee,siteSecurityFields as te}from"@murumets-ee/core";import{z as k}from"zod";import{InMemoryRateLimitStore as ne,Semaphore as re,createClientIpResolver as ie,runWithDeadline as A}from"@murumets-ee/core/limits";import{schemaRegistry as j}from"@murumets-ee/db";import{QueryClient as ae}from"@murumets-ee/entity/query";import{and as oe,asc as se,desc as ce,eq as M,getTableColumns as N,gte as P,ilike as le,inArray as F,lte as ue,or as de,sql as I}from"drizzle-orm";const fe=/[\u200B-\u200D\u2060\uFEFF]/g;function L(e){return e.replace(fe,``).trim()}const pe=2048,me=k.object({limit:k.coerce.number().int().min(1).max(100).default(20),offset:k.coerce.number().int().min(0).default(0),sort:k.string().regex(/^-?[a-zA-Z_]+$/).optional(),locale:k.string().regex(g).optional(),fields:k.string().optional(),search:k.string().max(200).refine(e=>{let t=L(e);return t.length===0||t.length>=2},{message:`search must be at least 2 characters`}).optional(),cursor:k.string().max(500).optional(),populate:k.string().max(200).optional()}).strict(),he=k.object({locale:k.string().regex(g).optional(),fields:k.string().optional(),populate:k.string().max(200).optional(),page:k.string().regex(/^(?:[1-9][0-9]?|100)$/).transform(Number).optional()}).strict(),ge=k.object({locale:k.string().regex(g).optional()}).strict(),_e=/^filter\[([a-zA-Z0-9_]+)\]$/;function R(e,t){let n={};for(let[r,i]of e.searchParams.entries())t?.allowFilters===!0&&_e.test(r)||(n[r]=i);return n}const ve=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ye=/^\d{4}-\d{2}-\d{2}(?:[Tt ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:[Zz]|[+-]\d{2}:?\d{2})?)?$/;function be(e){if(!ye.test(e))return!1;let t=Date.parse(e);return Number.isNaN(t)?!1:e.length===10?new Date(t).toISOString().slice(0,10)===e:!0}function xe(e){if(e.trim()===``)return!1;let t=Number(e);return Number.isFinite(t)}function Se(e){return ve.test(e)}function Ce(e,t){switch(e.type){case`boolean`:return t===`true`?!0:t===`false`?!1:null;case`reference`:case`media`:return ve.test(t)?t:null;case`select`:return e.options.includes(t)?t:null;case`date`:return be(t.startsWith(`gte:`)||t.startsWith(`lte:`)?t.slice(4):t)?t:null;case`number`:return xe(t)?Number(t):null;case`text`:return t.length<=200?t:null;default:return null}}function z(e,t){return e.startsWith(`_`)||t?.internal===!0||t?.adminOnly===!0}function we(e,t){if(!e)return;let n=e.split(`,`).map(e=>e.trim()).filter(e=>{if(!Object.hasOwn(t,e))return!1;let n=t[e];return n!==void 0&&!z(e,n)&&n.type!==`blockTree`});return n.includes(`id`)||n.unshift(`id`),n}function Te(e,t){if(!e)return{fields:[],dropped:[],requested:0};let n=[...new Set(e.split(`,`).map(e=>e.trim()).filter(e=>e.length>0))],r=[],i=[];for(let e of n){if(!Object.hasOwn(t,e)){i.push(e);continue}let n=t[e];if(!n||z(e,n)||n.type!==`reference`){i.push(e);continue}r.push(e)}return{fields:r,dropped:i,requested:n.length}}const Ee=[`reference`,`populate`,`media`,`block`],De=200;function Oe(e){if(!Number.isInteger(e)||e<0)throw Error(`content-api: resolution budget ceiling must be a non-negative integer, received ${String(e)}.`);let t=e,n=0,r=new Map;return{claim(e,i){if(!Number.isInteger(i)||i<=0)return 0;let a=Math.min(i,t);t-=a,n+=a;let o=i-a;return o>0&&r.set(e,(r.get(e)??0)+o),a},get remaining(){return t},get granted(){return n},get hasDrops(){return r.size>0},dropSummary(){let e={};for(let t of Ee){let n=r.get(t);n!==void 0&&n>0&&(e[t]=n)}return e},ceiling:e}}function ke(e){if(e===void 0)return 200;if(!Number.isInteger(e)||e<0)throw Error(`content-api: \`maxResolutionsPerDocument\` must be an integer >= 0, received ${String(e)}. If this came from an environment variable, it is probably unset — omit the option to get the package default (200).`);return Math.min(e,200)}const Ae=2e3;function B(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function V(e){if(!B(e))return!1;let t=e=>e===void 0||typeof e==`string`&&e.length<=Ae,n=e=>e===void 0||typeof e==`number`&&Number.isFinite(e)&&e>=0;if(!t(e.title)||!t(e.text))return!1;let r=e.price;if(r!==void 0&&(!B(r)||typeof r.amount!=`number`||!Number.isFinite(r.amount)||r.amount<0||!n(r.compareAt)||!t(r.unit)))return!1;let i=e.facts;if(i!==void 0){if(!Array.isArray(i)||i.length>12)return!1;for(let e of i)if(!B(e)||typeof e.key!=`string`||typeof e.label!=`string`||typeof e.value!=`string`&&typeof e.value!=`number`||e.format!==void 0&&e.format!==`price`)return!1}let a=e.body;if(a!==void 0){if(!B(a)||typeof a.html!=`string`||a.html.length>5e5||!Array.isArray(a.headings)||a.headings.length>100)return!1;for(let e of a.headings)if(!B(e)||typeof e.id!=`string`||typeof e.text!=`string`||e.level!==2&&e.level!==3)return!1}let o=e.embed;if(o!==void 0&&(!B(o)||typeof o.provider!=`string`||typeof o.reference!=`string`))return!1;let s=e.breadcrumbs;if(s!==void 0){if(!Array.isArray(s)||s.length>8)return!1;for(let e of s){if(!B(e)||typeof e.label!=`string`||e.label.length>Ae)return!1;if(e.href!==void 0){if(typeof e.href!=`string`||e.href.length>1e3||!e.href.startsWith(`/`)||e.href.startsWith(`//`))return!1;for(let t of e.href){let e=t.codePointAt(0)??0;if(e<=32||e===127||t===`\\`)return!1}}}}return!0}const H=new Set([`price`,`number`,`text`]);function U(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return W(t.name)&&W(t.label)&&H.has(t.format)&&(t.unit===void 0||W(t.unit))}function W(e){if(typeof e!=`string`||e.length>1200)return!1;for(let t=0;t<e.length;t++)if(e.charCodeAt(t)<32)return!1;return!0}function je(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let{sources:t,values:n}=e;if(typeof t!=`object`||!t||Array.isArray(t)||typeof n!=`object`||!n||Array.isArray(n))return!1;let r=Object.entries(t);if(r.length>32)return!1;for(let[,e]of r){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(typeof t.label!=`string`||t.labelKey!==void 0&&typeof t.labelKey!=`string`||t.kind!==void 0&&t.kind!==`price`&&t.kind!==`text`&&t.kind!==`list`&&t.kind!==`facts`||t.facts!==void 0&&(!Array.isArray(t.facts)||t.facts.length>48||!t.facts.every(U))||t.fields!==void 0&&(!Array.isArray(t.fields)||t.fields.length>64||!t.fields.every(e=>typeof e==`string`)))return!1}let i=Object.entries(n);if(i.length>32)return!1;for(let[,e]of i){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.entries(e);if(t.length>200)return!1;for(let[,e]of t){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(t.amount!==void 0&&(typeof t.amount!=`number`||!Number.isFinite(t.amount))||t.compareAt!==void 0&&(typeof t.compareAt!=`number`||!Number.isFinite(t.compareAt))||t.unit!==void 0&&typeof t.unit!=`string`||t.text!==void 0&&!W(t.text)||t.items!==void 0&&(!Array.isArray(t.items)||t.items.length>100||!t.items.every(W)))return!1;if(t.facts!==void 0){if(typeof t.facts!=`object`||t.facts===null||Array.isArray(t.facts))return!1;let e=Object.entries(t.facts);if(e.length>48)return!1;for(let[,t]of e)if(!(typeof t==`number`&&Number.isFinite(t)||W(t)))return!1}}}return!0}const Me=new Set([`ok`,`unset`,`unavailable`,`over-budget`,`needs-document`]);function Ne(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(typeof t.status!=`string`||!Me.has(t.status)||t.entity!==null&&(typeof t.entity!=`string`||t.entity===``)||!Array.isArray(t.rows)||t.rows.length>100)return!1;if(t.page!==void 0){if(typeof t.page!=`object`||t.page===null||Array.isArray(t.page))return!1;let e=t.page;if(typeof e.number!=`number`||!Number.isInteger(e.number)||e.number<1||e.number>100||typeof e.hasNext!=`boolean`)return!1}if(t.status===`ok`&&t.entity===null||t.status!==`ok`&&t.rows.length>0||(t.status===`unset`||t.status===`unavailable`)&&t.entity!==null)return!1;for(let e of t.rows){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(typeof t.id!=`string`||t.id===``)return!1;for(let e of[t.title,t.text,t.href])if(e!==null&&typeof e!=`string`)return!1;if(t.image!==null){if(typeof t.image!=`object`||Array.isArray(t.image))return!1;let e=t.image;if(typeof e.url!=`string`||e.alt!==null&&typeof e.alt!=`string`)return!1;for(let t of[e.width,e.height])if(t!==null&&typeof t!=`number`)return!1}}return!0}function Pe(e){if(!Number.isInteger(e)||e<0)throw Error(`content-api: collection allowance must be a non-negative integer, received ${String(e)}.`);let t=e,n=0;return{claim:()=>t===0?(n+=1,!1):(--t,!0),refusedCount:()=>n}}const Fe=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;function Ie(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.keys(e);return t.length>16?!1:t.every(e=>Fe.test(e))}function Le(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(t.resolved!==1||!Array.isArray(t.blocks))return!1;let n=t.links;if(typeof n!=`object`||!n||Array.isArray(n))return!1;for(let e of Object.values(n))if(e!==null&&typeof e!=`string`)return!1;let r=new Set,i=t.refs;if(i!==void 0){if(!Array.isArray(i))return!1;for(let e of i){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(typeof t.entity!=`string`||t.entity===``||typeof t.id!=`string`||t.id===``)return!1;r.add(`${t.entity}\u0000${t.id}`)}}let a=t.collections;if(a!==void 0){if(typeof a!=`object`||!a||Array.isArray(a))return!1;let e=Object.entries(a);if(e.length>64)return!1;for(let[t,n]of e){if(t===``||!Ne(n))return!1;if(!(n.status!==`ok`||n.entity===null)){for(let e of n.rows)if(!r.has(`${n.entity}\u0000${e.id}`))return!1}}}let o=t.unresolved;if(o!==void 0){if(!Array.isArray(o))return!1;for(let e of o)if(!Re(e))return!1}return!(t.live!==void 0&&!je(t.live)||t.currency!==void 0&&typeof t.currency!=`string`||t.detail!==void 0&&!V(t.detail)||t.blockData!==void 0&&!Ie(t.blockData))}function Re(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return t.kind!==`media`&&t.kind!==`link`||typeof t.ref!=`string`?!1:t.reason===`unresolvable`||t.reason===`budget`}function ze(e){return r(e).filter(e=>!e.internal).map(e=>e.name)}const Be=Object.freeze({resolved:1,blocks:Object.freeze([]),links:Object.freeze({})});async function Ve(e,t,n){try{let r=await e(t,n.boundValues===void 0?n:{...n,boundValues:structuredClone(n.boundValues)});return Le(r)?{ok:!0,envelope:r}:{ok:!1,failure:`malformed`}}catch(e){return{ok:!1,failure:`threw`,error:e}}}async function He(e,t,n){let r=await Ve(e,t,n);if(r.ok)return{envelope:r.envelope};let i=await Ve(e,t,{...n,budget:Oe(0),claimCollection:void 0});return i.ok?{envelope:i.envelope,failure:r.failure,error:r.error}:{envelope:Be,failure:r.failure,retryFailure:i.failure,error:r.error??i.error}}async function Ue(e,t,n){if(t.length===0)return;let r=n.resolveBlocks;if(!r)return;let a=ze(e);if(a.length===0)return;let o=new Map;for(let t of a){let r;if(d(e,t)){if(n.siteOf===void 0)throw Error(`content-api: '${e.name}.${t}' declares siteTemplates but block resolution was given no siteOf to learn the row’s site`);r=await n.siteOf(e)}o.set(t,i(e,t,r))}let s=0,c=0,l=0,u,f,p=new Set,m=new Set,h=new Set;for(let i of t)for(let t of a){let a=i[t],d=o.get(t);if(d!==void 0&&!Object.hasOwn(i,t)||d===void 0&&a==null)continue;let g=await He(r,d===void 0?a:[],{locale:n.locale,budget:n.budget,entity:e.name,field:t,...d!==void 0&&{template:d},boundValues:{...i},...n.canReadEntity!==void 0&&{canReadEntity:n.canReadEntity},...n.collectionAllowance!==void 0&&{claimCollection:n.collectionAllowance.claim},...n.page!==void 0&&{page:n.page}});if(g.failure===`threw`?(s+=1,p.add(t),u??=g.error):g.failure===`malformed`&&(c+=1,m.add(t)),g.retryFailure!==void 0&&(l+=1,h.add(t),f??=g.error,n.cacheTags?.markUncacheable()),i[t]=g.envelope,g.envelope.refs!==void 0)for(let e of g.envelope.refs)n.cacheTags?.addDocument(e.entity,e.id);if(g.envelope.collections!==void 0)for(let e of Object.values(g.envelope.collections))e.entity!==null&&n.cacheTags?.addCollection(e.entity)}s>0&&n.logger?.warn({entity:e.name,fields:[...p],rows:t.length,failures:s,err:u},`content-api: block resolver threw — no tree is served as stored; each was re-resolved with an exhausted budget, so its media refs and link hrefs are stripped rather than carrying the urls recorded when an editor picked them. Fields that failed that retry as well are reported separately, as empty.`),c>0&&n.logger?.warn({entity:e.name,fields:[...m],rows:t.length,failures:c},`content-api: block resolver returned a value that is not a ResolvedBlockTree — no tree is served as stored; each was re-resolved with an exhausted budget, so its media refs and link hrefs are stripped rather than carrying the urls recorded when an editor picked them. Fields that failed that retry as well are reported separately, as empty.`),l>0&&n.logger?.warn({entity:e.name,fields:[...h],rows:t.length,failures:l,err:f},`content-api: block resolver failed TWICE, including on the in-memory retry — those fields are served as an empty resolved tree, so that content is missing from the response. Serving the stored tree instead would put the media urls recorded when an editor picked them, which may be signed, on a cacheable anonymous response.`)}const G=`lumi`,We=128,Ge=128,Ke=3072,qe=`media`,Je=/^[A-Za-z0-9_.-]+$/,Ye=`_`,Xe={enabled:!0,header:`Cache-Tag`,separator:`,`},Ze=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Qe=[`cache-control`,`vary`,`content-type`],$e=[`access-control-`];function et(e){if(e){if(e.enabled!==void 0&&typeof e.enabled!=`boolean`)throw Error(`content-api cache: \`cache.tags.enabled\` must be a boolean, received ${JSON.stringify(e.enabled)}.`);if(e.header!==void 0){if(typeof e.header!=`string`||!Ze.test(e.header))throw Error(`content-api cache: \`cache.tags.header\` must be a valid HTTP field name (RFC 9110 §5.1 token), received ${JSON.stringify(e.header)}. Common values: \`Cache-Tag\` (Cloudflare/Netlify, the default), \`Surrogate-Key\` (Fastly), \`Edge-Cache-Tag\` (Akamai).`);let t=e.header.toLowerCase();if(Qe.includes(t)||$e.some(e=>t.startsWith(e)))throw Error(`content-api cache: \`cache.tags.header\` may not be ${JSON.stringify(e.header)} — this package writes that header itself on the same responses, so the tags would either overwrite it or be overwritten, silently and on every request.`)}if(e.separator!==void 0&&e.separator!==`,`&&e.separator!==` `)throw Error(`content-api cache: \`cache.tags.separator\` must be ',' or ' ', received ${JSON.stringify(e.separator)}. Cloudflare and Akamai parse comma-separated tags; Fastly parses space-separated ones. A third separator would not error at the CDN — it would parse as one giant unmatched key, which is the silent failure this refuses.`)}}function tt(e){return{enabled:e?.enabled??Xe.enabled,header:e?.header??Xe.header,separator:e?.separator??Xe.separator}}function nt(e){return typeof e==`string`&&e!==``&&Je.test(e)}function rt(e,t){function n(e){if(t===void 0)return G;let n=t(e);return nt(n)?`${G}:${n}`:void 0}let r=new Set,i=0,a=!1,o=e.header.length+4,s=!1;function c(e){if(r.has(e))return;if(e.length>128||r.size>=128){i+=1;return}let t=e.length+(r.size===0?0:1);if(s||o+t>3072){s=!0,i+=1;return}o+=t,r.add(e)}return{addDocument(e,t){if(!nt(e)||!nt(t)){i+=1;return}let r=n(e);if(r===void 0){i+=1;return}c(`${r}:${e}:${t}`)},addCollection(e){if(!nt(e)){i+=1;return}let t=n(e);if(t===void 0){i+=1;return}c(`${t}:${e}`)},get tags(){return[...r]},markUncacheable(){a=!0},get dropped(){return i},get uncacheable(){return a},headers(){return!e.enabled||r.size===0?{}:{[e.header]:[...r].join(e.separator)}}}}const it=`_template`;function at(e){if(typeof e!=`string`)return;let t=e.trim();return t===``?void 0:t.slice(0,2e3)}async function ot(e,t,n,r){let i={...t};for(let e of Object.keys(t))e!==`id`&&delete t[e];let a=n.detailTemplates;if(!a)return;let o=n.locale??n.defaultLocale;if(o===void 0)return;try{let n=await a.publicRow({entity:e.name,row:i,locale:o}),r=at(n.title),s=at(n.description);r!==void 0&&(t.title=r),s!==void 0&&(t.description=s)}catch(t){n.logger?.warn({entity:e.name,err:t},`content-api: detail-template provider failed to project a row — served with its id only`),n.cacheTags?.markUncacheable()}if(!r)return;let s=n.resolveBlocks;if(!s||(n.cacheTags?.addCollection(a.entity),n.budget.claim(`block`,1)<1))return;let c;try{c=await a.readTemplate({entity:e.name,locale:o})}catch(t){n.logger?.warn({entity:e.name,err:t},`content-api: detail-template provider failed to read the template — the row is served without one and the response is not cacheable`),n.cacheTags?.markUncacheable();return}if(c===null||typeof c.id!=`string`||!Array.isArray(c.blocks))return;n.cacheTags?.addDocument(a.entity,c.id);let l=await He(s,c.blocks,{locale:n.locale,budget:n.budget,entity:e.name,field:it,boundValues:i,rowIsForeign:!0,...n.canReadEntity!==void 0&&{canReadEntity:n.canReadEntity},...n.collectionAllowance!==void 0&&{claimCollection:n.collectionAllowance.claim},...n.page!==void 0&&{page:n.page}});l.failure!==void 0&&n.logger?.warn({entity:e.name,field:it,failure:l.failure,retryFailure:l.retryFailure,err:l.error},`content-api: block resolver failed on a detail template — served re-resolved with an exhausted budget, or empty if that failed as well`),l.retryFailure!==void 0&&n.cacheTags?.markUncacheable(),K(l.envelope,n),t[it]=l.envelope}function K(e,t){if(e.refs!==void 0)for(let n of e.refs)t.cacheTags?.addDocument(n.entity,n.id);if(e.collections!==void 0)for(let n of Object.values(e.collections))n.entity!==null&&t.cacheTags?.addCollection(n.entity)}const st=[`NOT_FOUND`,`VALIDATION_ERROR`,`INTERNAL_ERROR`,`RATE_LIMITED`,`SERVICE_OVERLOADED`,`FORM_INVALID`,`CHALLENGE_FAILED`,`PAYLOAD_TOO_LARGE`];function q(e,t=200,n){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":`application/json`,...n}})}const ct={"Cache-Control":`no-store`},lt=new WeakMap;function ut(e){return lt.get(e)}function J(e,t,n,r,i){let a=q({error:{status:n,message:e,code:t,...i}},n,{...r,...ct});return lt.set(a,t),a}function Y(e){return J(`Not found`,`NOT_FOUND`,404,e)}function dt(e,t){return J(`Rate limit exceeded`,`RATE_LIMITED`,429,{...t,"Retry-After":String(e)})}function ft(e,t){return J(`Service overloaded`,`SERVICE_OVERLOADED`,503,{...t,"Retry-After":String(e)})}function pt(e){let t=[];for(let[n,r]of Object.entries(e.allFields))r.type!==`media`||z(n,r)||t.push([n,r]);return t}async function mt(e,t,n){if(t.length===0)return;let r=pt(e);if(r.length===0)return;let i=new Set;for(let e of t)for(let[t]of r){if(!Object.hasOwn(e,t))continue;let n=e[t];typeof n==`string`&&n!==``&&i.add(n)}let a=new Map;if(i.size>0&&n.resolveMedia){let t=[...i],r=n.budget.claim(`media`,t.length),o=t.slice(0,r);if(o.length>0)try{a=await n.resolveMedia(o,{locale:n.locale})}catch(t){n.logger?.warn({entity:e.name,err:t},"content-api: media resolver threw — media fields resolve to null (if this is a ForbiddenError, the requesting role is missing `media:view`)")}}else i.size>0&&n.logger?.debug({entity:e.name,mediaFields:r.map(([e])=>e)},"content-api: no `resolveMedia` provider wired — media fields resolve to null");for(let[e,t]of a)i.has(e)&&t?.id===e&&n.cacheTags?.addDocument(qe,e);for(let e of t)for(let[t]of r){if(!Object.hasOwn(e,t))continue;let n=e[t];e[t]=typeof n==`string`?a.get(n)??null:null}}const ht=20,gt=50,_t=k.object({q:k.string().max(200).refine(e=>L(e).length>=2,{message:`q must be at least 2 characters`}),types:k.string().max(808).optional(),limit:k.coerce.number().int().min(1).default(20),locale:k.string().regex(g).optional()}).strict();function vt(e){return u(e)===void 0||m(e)?!1:e.kind!==`singleton`}function yt(e,t){if(t===void 0)return[...e];let n=t.split(`,`).map(e=>e.trim()).filter(e=>e!==``);if(n.length===0)return null;for(let t of n)if(!e.includes(t))return null;return e.filter(e=>n.includes(e))}function bt(e){for(let[t,n]of pt(e)){let e=n.accept;if(e===void 0||e.length===0||e.some(e=>e===`*/*`||e.startsWith(`image/`)))return t}return null}function xt(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&typeof t.url==`string`}function St(e){let t=e.admin?.labelSingular;if(typeof t==`string`&&t.trim()!==``)return t.trim();let n=e.name.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/[_-]+/g,` `).trim().toLowerCase();return n===``?e.name:`${n.charAt(0).toUpperCase()}${n.slice(1)}`}function Ct(e,t){if(typeof e!=`string`)return null;let n=e.replace(/\s+/g,` `).trim();return n===``?null:n.length>t?`${n.slice(0,t-1).trimEnd()}…`:n}const wt=[`summary`,`excerpt`,`description`,`intro`,`lead`],Tt=new Set([`text`]);function Et(e,t,n){let r=null,i=e.allFields;for(let e of wt){let n=i[e];if(!(n===void 0||!Tt.has(n.type))&&(r=Ct(t[e],300),r!==null))break}let a=null,o=u(e);if(o)try{let e=o.projection({...t});r??=Ct(e.description,300),a=Ct(e.label,300)}catch{}return{title:Ct(t[n],300)??a??(typeof t.id==`string`?t.id:``),summary:r}}function Dt(e,t){let n=[];for(let r of[!0,!1]){let i=e.map(e=>e.hits.filter(e=>e.titleHit===r).map(e=>e.hit));for(let e=0;n.length<t;e++){let r=!1;for(let a of i){let i=a[e];if(i!==void 0&&(r=!0,n.push(i),n.length===t))break}if(!r)break}}return n}function Ot(e,t){let n=L(t).toLocaleLowerCase();return n!==``&&e.toLocaleLowerCase().includes(n)}const kt=`x-lumi-visitor-address`;function At(e,t,n){if(e===void 0)return t;if(!Number.isSafeInteger(e)||e<1)throw Error(`content-api search: \`${n}\` must be a positive integer (got ${e})`);return e}var jt=class{getClientIp;store;tokens;intervalMs;readVisitor=ie({header:kt,trustedProxyHops:1,surface:`content-api visitor search`});constructor(e,t){this.getClientIp=t,this.tokens=At(e?.searchesPerVisitorPerInstance,30,`searchesPerVisitorPerInstance`),this.intervalMs=At(e?.intervalMs,6e4,`intervalMs`),this.store=e?.store??new ne}consume(e,t,n){let r=this.keyFor(e,t);if(r!==void 0)return{decision:this.store.consume(`search:${r.key}`,{tokens:this.tokens,intervalMs:this.intervalMs},n),keyClass:r.keyClass}}keyFor(e,t){if(t.principalId!==void 0)return{key:`principal:${t.principalId}`,keyClass:`principal`};if(t.site!==void 0){let n=this.readVisitor(e.headers);if(n!==null)return{key:`visitor:${t.site}:${n}`,keyClass:`visitor`}}if(t.site!==void 0)return;let n=this.getClientIp?.(e);if(n!==void 0&&n!==``)return{key:`ip:${n}`,keyClass:`client-ip`}}};const Mt=64*1024,Nt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Pt=ie({header:kt,trustedProxyHops:1,surface:`content-api form submissions`}),Ft={"Cache-Control":`no-store`};function It(e,t){if(e.length!==3||e[0]!==`_forms`||e[2]!==t)return;let n=e[1];return n!==void 0&&Nt.test(n)?n:void 0}async function Lt(e,t){let n=e.headers.get(`content-type`)??``;if(!/^application\/json\s*(?:;|$)/i.test(n))return{ok:!1,reason:`invalid`};let r=e.headers.get(`content-length`);if(r!==null&&Number(r)>t)return{ok:!1,reason:`too_large`};if(e.body===null)return{ok:!1,reason:`invalid`};let i=e.body.getReader(),a=[],o=0;for(;;){let{done:e,value:n}=await i.read();if(e)break;if(o+=n.byteLength,o>t)return await i.cancel(),{ok:!1,reason:`too_large`};a.push(n)}let s=new Uint8Array(o),c=0;for(let e of a)s.set(e,c),c+=e.byteLength;try{return{ok:!0,value:JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(s))}}catch{return{ok:!1,reason:`invalid`}}}async function Rt(e){if(e.keySite===void 0)return Y(e.headers);let t=await e.forms.issueToken({site:e.keySite,formId:e.formId,purpose:new URL(e.req.url).searchParams.get(`for`)===`visitor`?`visitor`:`render`,visitorAddress:Pt(e.req.headers)});return t===null?Y(e.headers):t===`rate_limited`?dt(600,e.headers):q({data:t},200,{...e.headers,...Ft})}async function zt(e){if(e.keySite===void 0)return Y(e.headers);let t=await Lt(e.req,Mt);if(!t.ok)return t.reason===`too_large`?J(`Submission too large`,`PAYLOAD_TOO_LARGE`,413,e.headers):J(`Malformed submission`,`VALIDATION_ERROR`,400,e.headers);let n=await e.forms.submit({site:e.keySite,formId:e.formId,body:t.value,visitorAddress:Pt(e.req.headers)});switch(n.kind){case`accepted`:return q({data:{ok:!0}},200,{...e.headers,...Ft});case`invalid`:return Bt(n.fields,e.headers);case`rate_limited`:return dt(n.retryAfterSeconds,e.headers);case`challenge_failed`:return J(`Verification failed`,`CHALLENGE_FAILED`,400,e.headers);case`unavailable`:return ft(30,e.headers);case`not_found`:return Y(e.headers)}}function Bt(e,t){return J(`Some answers need attention`,`FORM_INVALID`,400,t,{fields:e})}function Vt(e){let t=Math.ceil(e/6);return{maxAge:t,swr:e-t}}const Ht=[`defaultMaxAge`,`defaultStaleWhileRevalidate`,`maxAge`,`staleWhileRevalidate`];function Ut(e,t){if(e!==void 0&&(typeof e!=`number`||!Number.isInteger(e)||e<0))throw Error(`content-api cache: \`${t}.maxStaleSeconds\` must be a non-negative integer, received ${JSON.stringify(e)}. Use 0 for \`no-store\` if you need a published edit visible on the very next request.`)}function Wt(e,t){for(let n of Ht)if(n in e)throw Error(`content-api cache: \`${t}.${n}\` was removed (D036). Use \`maxStaleSeconds\` — ONE number naming the TOTAL staleness window in seconds. The old pair's real window was their SUM and nothing said so, which is the defect D036 exists to close: \`defaultMaxAge: 10\` bought a 310-second window, not a 10-second one. The max-age / stale-while-revalidate split is now derived, so what is emitted always sums to what you declared.`)}function Gt(e){if(e){Wt(e,`cache`),Ut(e.maxStaleSeconds,`cache`),et(e.tags);for(let[t,n]of Object.entries(e.entities??{})){if(!n)continue;let e=`cache.entities.${t}`;Wt(n,e),Ut(n.maxStaleSeconds,e)}}}function Kt(e,t){let n=t?.entities?.[e];return n?.cacheable===!1?0:n?.maxStaleSeconds??t?.maxStaleSeconds??360}function qt(e,t){let n=Kt(e,t);if(n===0)return{"Cache-Control":`no-store`};let{maxAge:r,swr:i}=Vt(n);return{"Cache-Control":`public, max-age=${r}, stale-while-revalidate=${i}`}}const Jt=[`Origin`];function Yt(e,t){let n=new Set,r=[];for(let i of[...e?.split(`,`)??[],...Jt,...t]){let e=i.trim();if(e===``)continue;let t=e.toLowerCase();n.has(t)||(n.add(t),r.push(e))}return r.join(`, `)}function X(e,t,n,r,i,a){let o=(n!==`identified`&&i.kind!==`undeclared`&&a?.uncacheable!==!0?qt(e,r):{"Cache-Control":`no-store`})[`Cache-Control`]??`no-store`,s={"Cache-Control":n===`site-keyed`?o.replace(/^public\b/,`private`):o};return{...t,...s,...s[`Cache-Control`]===`no-store`?{}:a?.headers(),Vary:Yt(t.Vary,i.kind===`declared`?i.headers:[])}}function Xt(e,t,n,r){let i=r?.uncacheable===!0?{"Cache-Control":`no-store`}:qt(e,n);return{...t,...i,...i[`Cache-Control`]===`no-store`?{}:r?.headers(),Vary:Yt(void 0,[])}}function Zt(e,t){return{...e,Vary:Yt(e.Vary,t.kind===`declared`?t.headers:[])}}function Qt(e,t){if(!t)return{};let n=e.headers.get(`Origin`);return n!==null&&t.allowedOrigins.includes(n)?{"Access-Control-Allow-Origin":n,"Access-Control-Allow-Methods":`GET, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Accept, Authorization`,"Access-Control-Max-Age":String(t.maxAge??3600),Vary:`Origin`}:{Vary:`Origin`}}function $t(e,t,n){let r={...Qt(e,t),...qt(`_preflight`,n)};return new Response(null,{status:204,headers:r})}var en=class extends Error{constructor(){super(`Service overloaded`),this.name=`ServiceOverloadedError`}},tn=class extends Error{constructor(){super(`Request deadline exceeded`),this.name=`RequestDeadlineError`}};function nn(e,t,n){if(e===void 0)return t;if(!Number.isInteger(e)||e<0)throw Error(`content-api limits: \`${n}\` must be a non-negative integer (got ${e})`);return e}function rn(e,t,n){if(e===void 0)return t;if(!Number.isInteger(e)||e<1)throw Error(`content-api limits: \`${n}\` must be a positive integer (got ${e})`);return e}function an(e){return{maxConcurrentRequests:rn(e?.maxConcurrentRequests,64,`maxConcurrentRequests`),maxQueuedRequests:nn(e?.maxQueuedRequests,128,`maxQueuedRequests`),requestTimeoutMs:rn(e?.requestTimeoutMs,1e4,`requestTimeoutMs`),anonymousTokensPerInstance:rn(e?.anonymousTokensPerInstance,120,`anonymousTokensPerInstance`),intervalMs:rn(e?.intervalMs,6e4,`intervalMs`),maxBudgetPerInstance:rn(e?.maxBudgetPerInstance,6e3,`maxBudgetPerInstance`)}}var on=class{semaphore;store;limits;getClientIp;constructor(e){this.getClientIp=e?.getClientIp,this.limits=an(e),this.semaphore=new re(this.limits.maxConcurrentRequests,this.limits.maxQueuedRequests),this.store=e?.store??new ne}async acquire(e){await this.semaphore.acquire(()=>new en,e)}release(){this.semaphore.release()}async runGuarded(e){return await A(e,this.limits.requestTimeoutMs,()=>new tn)}consumeFairness(e,t,n){let r=this.resolveKey(e,t);if(r)return{decision:this.store.consume(r.key,{tokens:this.budgetFor(t),intervalMs:this.limits.intervalMs},n),keyClass:r.keyClass}}budgetFor(e){let t=e.budgetPerInstance??this.limits.anonymousTokensPerInstance;return Math.min(t,this.limits.maxBudgetPerInstance)}resolveKey(e,t){if(t.principalId!==void 0)return{key:`principal:${t.principalId}`,keyClass:`principal`};let n=this.getClientIp?.(e);if(n!==void 0&&n!==``)return{key:`ip:${n}`,keyClass:`client-ip`}}};function sn(e){let t=[];for(let[n,r]of Object.entries(e.allFields))r.type!==`reference`||z(n,r)||t.push([n,r]);return t}function cn(e){return typeof e==`string`&&e.length>0}function ln(e,t){return t===`many`?Array.isArray(e)?e.filter(cn):[]:cn(e)?[e]:[]}async function un(e,t,n,r,i=0){if(t.length===0)return;let a=sn(e);if(a.length===0)return;let o=new Map,s=[];for(let e of t)for(let[t,c]of a){if(!Object.hasOwn(e,t))continue;let a=ln(e[t],c.cardinality),l=i===0&&n.has(t),u=r.reachableEntity(c.entity);if(!u||a.length===0){s.push({row:e,field:t,cardinality:c.cardinality,groupKey:null,ids:a});continue}let d=`${u.name}::${l?`full`:`projection`}`,f=o.get(d);f||(f={target:u,expand:l,ids:new Set},o.set(d,f));for(let e of a)f.ids.add(e);s.push({row:e,field:t,cardinality:c.cardinality,groupKey:d,ids:a})}let c=new Map;for(let[e,t]of o){let n=[...t.ids],a=r.budget.claim(t.expand?`populate`:`reference`,n.length),o=n.slice(0,a);if(o.length===0){c.set(e,new Map);continue}let s=l(t.target),u=m(t.target),d=u?r.templateDrawnTitle:void 0,f=t.expand||d!==void 0?void 0:u?[`id`]:dn([`id`,s]),p=await r.readRowsByIds(t.target,o,f),h=new Map;if(t.expand){for(let e of p){let t=e.id;cn(t)&&h.set(t,e)}await un(t.target,p,new Set,r,i+1),await r.afterExpand?.(t.target,p)}else{let e=await fn(t.target.name,p,r);for(let[n,r]of p.entries()){let i=r.id;if(!cn(i))continue;let a=u?await d?.(t.target,r)??null:r[s];h.set(i,{id:i,entityType:t.target.name,title:typeof a==`string`?a:null,href:e[n]??null})}}for(let e of h.keys())r.cacheTags?.addDocument(t.target.name,e);c.set(e,h)}for(let e of s){let t=e.groupKey===null?void 0:c.get(e.groupKey);if(e.cardinality===`many`){e.row[e.field]=e.ids.map(e=>t?.get(e)).filter(e=>e!==void 0);continue}let n=e.ids[0];e.row[e.field]=n===void 0?null:t?.get(n)??null}}function dn(e){return[...new Set(e)]}async function fn(e,t,n){let r=n.resolveEntityHref;return r?O(t,async t=>{let i=t.id;if(!cn(i))return null;try{return await r({entity:e,id:i,...n.locale!==void 0&&{locale:n.locale}})??null}catch(t){return n.logger?.debug({entity:e,id:i,err:t},`content-api: resolveEntityHref threw — reference resolves without an href`),null}}):t.map(()=>null)}const pn={referenceProjection:{fields:{id:`string`,entityType:`string`,title:`string`,href:`string`},nullableFields:[`title`,`href`],nullable:!0,arrayForCardinalityMany:!0},mediaProjection:{fields:{id:`string`,url:`string`,mimeType:`string`,width:`number`,height:`number`,alt:`string`,title:`string`,variants:`object`,sources:`object`,avifSources:`object`,focalPoint:`object`,blurDataUrl:`string`},nullableFields:[`mimeType`,`width`,`height`,`alt`,`title`,`blurDataUrl`],optionalFields:[`avifSources`],nullable:!0,arrayForCardinalityMany:!1}};function mn(e,t){let n={type:e.type};return e.required&&(n.required=!0),e.translatable&&(n.translatable=!0),e.type===`select`&&(n.options=e.options),e.type===`blockTree`&&(n.selectable=!1),e.type===`media`&&(n.wire=`mediaProjection`),e.type===`reference`&&(n.cardinality=e.cardinality,n.wire=`referenceProjection`,t(e.entity)&&(n.entity=e.entity,n.populatable=!0)),n}function hn(e,t){let n=e.allFields,r={},i=m(e);for(let[e,a]of Object.entries(n))z(e,a)||i&&e!==`id`||(r[e]=mn(a,t));let a=u(e);for(let e of a?.fields??[]){let t=r[e];t&&(t.searchable=!0)}return{name:e.name,pluralName:`${e.name}s`,kind:e.kind??`collection`,...i&&{drawnBy:`template`},fields:r}}const gn={type:`string`},_n={type:`string`},vn={type:`string`,maxLength:200,maxItems:5};function yn(e){let{maxLimit:t,maxOffset:n,hasResolution:r,hasMenus:i,hasChrome:a}=e,o=[{id:`list`,path:`/:entity`,data:`array`,entityKind:`collection`,params:{limit:{type:`number`,min:1,max:t,default:Math.min(20,t)},offset:{type:`number`,min:0,max:n,default:0},sort:{type:`string`},locale:gn,fields:_n,search:{type:`string`,maxLength:200,minLength:2},cursor:{type:`string`,maxLength:500},populate:vn,"filter[<field>]":{type:`string`}},meta:{total:{type:`number`,nullable:!0,suppressedBy:[`search`]},limit:{type:`number`},offset:{type:`number`},hasMore:{type:`boolean`},nextCursor:{type:`string`,optional:!0}}},{id:`singleton`,path:`/:entity`,data:`object`,entityKind:`singleton`,params:{locale:gn,fields:_n,populate:vn}},{id:`count`,path:`/:entity/count`,data:`object`,entityKind:`collection`,params:{locale:gn}},{id:`byId`,path:`/:entity/:id`,data:`object`,entityKind:`collection`,params:{locale:gn,fields:_n,populate:vn}},{id:`bySlug`,path:`/:entity/slug/:slug`,data:`object`,entityKind:`collection`,params:{locale:gn,fields:_n,populate:vn}}];return r&&o.push({id:`resolve`,path:`/_resolve`,data:`object`,params:{path:{type:`string`,required:!0,maxLength:pe},locale:{type:`string`,required:!0}}},{id:`paths`,path:`/_paths`,data:`array`,params:{locale:{type:`string`,required:!0},entity:{type:`string`,required:!0,maxLength:100},cursor:{type:`string`},limit:{type:`number`,min:1,max:t,default:Math.min(20,t)}},meta:{limit:{type:`number`},hasMore:{type:`boolean`},nextCursor:{type:`string`,optional:!0}}},{id:`alternates`,path:`/_alternates`,data:`array`,params:{entity:{type:`string`,required:!0,maxLength:100},id:{type:`string`,required:!0}}}),o.push({id:`site`,path:`/_site`,data:`object`,params:{}}),o.push({id:`search`,path:`/_search`,data:`array`,params:{q:{type:`string`,required:!0,minLength:2,maxLength:200},types:{type:`string`,maxLength:808},limit:{type:`number`,default:20,min:1,max:50},locale:{type:`string`}},meta:{limit:{type:`number`}}}),i&&o.push({id:`menu`,path:`/_menu`,data:`object`,params:{handle:{type:`string`,required:!0,maxLength:128},locale:{type:`string`,required:!0},currentPath:{type:`string`,maxLength:pe}}}),a&&o.push({id:`chrome`,path:`/_chrome`,data:`object`,params:{locale:{type:`string`,required:!0},entity:{type:`string`,maxLength:100},id:{type:`string`}}}),o}function bn(e,t){if(!e.enabled)return null;let n=t?`${G}:{site}`:G;return{header:e.header,separator:e.separator,document:`${n}:{entity}:{id}`,collection:`${n}:{entity}`,sharedSite:t?`_`:null,maxTagLength:128,maxTagsPerResponse:128,maxHeaderBytes:Ke,uncovered:[`menuTargets`,`crossEntityPathChanges`,`mediaVariantStyles`,`outOfBandPathChanges`]}}function xn(e){let{entities:t,checkPermission:n,version:r}=e,i={maxResolutionsPerDocument:e.maxResolutionsPerDocument,anonymousRequestsPerInstance:e.limits.anonymousTokensPerInstance,rateLimitWindowMs:e.limits.intervalMs,maxRequestsPerInstance:e.limits.maxBudgetPerInstance,maxConcurrentRequests:e.limits.maxConcurrentRequests,requestTimeoutMs:e.limits.requestTimeoutMs},a=t.filter(e=>n(e.name)),o=new Set(a.map(e=>e.name)),s=e=>o.has(e);return{version:r,surface:yn(e),envelopes:{dataKey:`data`,metaKey:`meta`,errorKey:`error`,errorCodes:st},limits:i,projections:pn,cacheTags:bn(e.cacheTags,e.siteScopedTags===!0),entities:a.map(e=>hn(e,s))}}const Sn=`public`,Cn=new Set;function wn(e){return typeof e==`string`&&e!==``}function Tn(e){return Array.isArray(e)}const En=/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/;function Dn(e){let t=e.credentialHeaders;if(t!==void 0){if(!Tn(t))throw Error(`content-api: \`credentialHeaders\` must be an array of HTTP header names, received ${JSON.stringify(t)}.`);for(let e of t)if(!wn(e)||e===`*`||!En.test(e))throw Error(`content-api: \`credentialHeaders\` entry ${JSON.stringify(e)} is not a valid HTTP header name. Each entry is emitted verbatim in \`Vary\`, so it must be a bare field-name token (\`Cookie\`, \`Authorization\`, \`X-Preview-Token\`). \`*\` is refused: it means "never reuse this response", which is \`Cache-Control: no-store\` spelled obscurely — omit the option instead, which fails closed to exactly that.`)}if(!e.authenticate){if(t!==void 0&&t.length>0)throw Error("content-api: `credentialHeaders` was declared without an `authenticate` hook. This package parses no credential itself, so nothing reads those headers and listing them in `Vary` can only fragment a shared cache. Remove the option, or wire the `authenticate` hook it describes.");return{kind:`none`}}return t===void 0||t.length===0?{kind:`undeclared`}:{kind:`declared`,headers:t}}const On=k.object({path:k.string().min(1).max(pe),locale:k.string().regex(g)}).strict(),kn=k.object({locale:k.string().regex(g),entity:k.string().min(1).max(100),cursor:k.string().refine(e=>Se(e),`Invalid cursor`).optional(),limit:k.coerce.number().int().min(1).max(100).default(20)}).strict(),An=k.object({entity:k.string().min(1).max(100),id:k.string().refine(e=>Se(e),`Invalid id`)}).strict(),jn=[`header`,`footer`],Mn=k.object({locale:k.string().regex(g),entity:k.string().min(1).max(100).optional(),id:k.string().refine(e=>Se(e),`Invalid id`).optional()}).strict().refine(e=>e.entity===void 0==(e.id===void 0),`Both ?entity= and ?id= are required to name a document, or neither.`),Nn=k.object({}).strict();function Pn(e){return e instanceof n||e instanceof Error&&e.name===`SiteRequiredError`}const Fn=k.object({handle:k.string().min(1).max(128),locale:k.string().regex(g),currentPath:k.string().min(1).max(pe).optional()}).strict(),In=new Set([`_schema`,`_site`,`_resolve`,`_paths`,`_alternates`,`_menu`,`_chrome`,`_search`,`_forms`]),Ln=`v1`,Rn=/^v\d+$/;function zn(e){let t=new Map;for(let n of e){let e=`${n.name}s`;if(In.has(n.name)||In.has(e))throw Error(`@murumets-ee/content-api: entity name "${n.name}" collides with a reserved route segment (${[...In].join(`, `)}). Rename the entity — its API surface would otherwise be permanently unreachable, shadowed by the special dispatch that runs before entity-whitelist resolution.`);if(Rn.test(n.name)||Rn.test(e))throw Error(`@murumets-ee/content-api: entity name "${n.name}" is a reserved API-version segment. Every route is served under a version prefix (this instance mounts /v1/), and the prefix is matched as a PATTERN ("v" followed by digits) so that a future /v2/ can never be shadowed by an entity added in the meantime. Rename the entity.`);if(n.scope!==void 0&&n.scope!==`global`)throw Error(`@murumets-ee/content-api: entity "${n.name}" declares scope "${n.scope}", which this surface cannot serve. The public read path resolves no scope for a caller, so QueryClient would apply NO scope filter and return every tenant's rows to every caller. Remove it from the content-api whitelist, or serve it through a surface that establishes a scope in the request context.`);t.set(n.name,n),t.set(e,n)}return t}function Bn(e,n){let r=e[t];if(!r)throw Error(`site-bound '${n}' translations have no ${t} column`);return r}function Z(e){let t=j.get(e);if(t)return{table:t,cols:N(t)}}const Vn=new Set([`text`,`richtext`,`slug`,`select`]);function Hn(e,t,n){let r=u(e);if(!r)return;let i=t.trim();if(i.length===0)return;let o=Z(e.name);if(!o)return;let{cols:s}=o,l=[],d=`%${v(i)}%`,f=e.allFields,p=r.fields.filter(e=>{let t=Object.hasOwn(f,e)?f[e]:void 0;return t!==void 0&&Vn.has(t.type)&&!z(e,t)}),m=r.fts?.fields.some(e=>z(e,f[e]))??!1,h=Cn;if(r.fts&&!m){let e=s._search_tsv;if(e){let t=r.fts.language??`simple`;l.push(I`${e} @@ websearch_to_tsquery(${t}, ${i})`),h=new Set(r.fts.fields)}}for(let e of p){if(h.has(e))continue;let t=s[e];t&&l.push(le(t,d))}let g=c(e.allFields,p),_=s.id;if(n!==void 0&&g.length>0&&_){let t=j.get(`${e.name}_translations`);if(t){let e=a({idColumn:_,translationsTable:t,fields:g,locale:n,buildCondition:e=>le(e,d)});e&&l.push(e)}}if(l.length===0)return;let y=l[0];if(y)return l.length===1?y:de(y,...l.slice(1))}function Un(e,t,n){let r=Z(e.name);if(!r)return[];let{cols:i}=r,a=e.allFields,o=t.trim(),s=`%${v(o)}%`,c=[],d=l(e),f=Object.hasOwn(a,d)?a[d]:void 0,p,m=i[d];if(m&&f!==void 0&&Vn.has(f.type)&&!z(d,f)){let t=n!==void 0&&f.translatable===!0?Z(`${e.name}_translations`):void 0,r=t?.cols[d],a=t?.cols.entityId,o=t?.cols.locale,c=i.id;p=t&&r&&a&&o&&c&&n!==void 0?I`COALESCE((SELECT ${r} FROM ${t.table} WHERE ${a} = ${c} AND ${o} = ${n} LIMIT 1), ${m}) ILIKE ${s}`:le(m,s)}p&&c.push(I`CASE WHEN ${p} THEN 0 ELSE 1 END`);let h=u(e),g=h?.fts?.fields.some(e=>z(e,a[e]))??!1,_=i._search_tsv;if(h?.fts&&!g&&_){let e=h.fts.language??`simple`;c.push(ce(I`ts_rank(${_}, websearch_to_tsquery(${e}, ${o}))`))}let y=i.updatedAt;y&&c.push(ce(y));let b=i.id;return b&&c.push(se(b)),c}function Wn(e,t,n){let r=e.name;if(!t)return{orderBy:void 0};let i=t.startsWith(`-`),a=i?t.slice(1):t,o={orderBy:void 0,dropped:t};if(!Object.hasOwn(n,a))return o;let s=n[a];if(!s||s.type===`blockTree`||z(a,s)&&!p(e,a))return o;let c=Z(r);if(!c)return o;let l=c.cols[a];return l?{orderBy:i?ce(l):se(l),field:a}:o}function Gn(e,t,n){let r=[],i=[],a=Z(e);if(!a)return{conditions:r,dropped:i};let{cols:o}=a;for(let[e,a]of t.searchParams.entries()){let t=e.match(_e);if(!t)continue;let s=t[1];if(s===void 0)continue;if(!Object.hasOwn(n,s)){i.push(s);continue}let c=n[s];if(!c||c.type===`blockTree`){i.push(s);continue}if(z(s,c)){i.push(s);continue}let l=o[s];if(!l){i.push(s);continue}let u=Ce(c,a);if(u===null){i.push(s);continue}if(c.type===`date`&&typeof u==`string`){if(u.startsWith(`gte:`)){r.push(P(l,u.slice(4)));continue}if(u.startsWith(`lte:`)){r.push(ue(l,u.slice(4)));continue}}r.push(M(l,u))}return{conditions:r,dropped:i}}function Kn(e,t,n,r,i=!0){if(!(!i||t<=n))return J(`?${e}=${t} exceeds the maximum of ${n}.${e===`offset`?` Use ?cursor= for deep pagination.`:``}`,`VALIDATION_ERROR`,400,r)}function qn(e,t,n){return n?e:Math.min(e,t)}function Jn(e,t,{allowZero:n=!1}={}){if(t===void 0)return;let r=+!n;if(!Number.isInteger(t)||t<r)throw Error(`content-api: \`${e}\` must be an integer >= ${r}, received ${String(t)}. A ceiling below that does not tighten the bound, it removes it: the limit reaches the query layer falsy, no LIMIT clause is emitted, and the whole table is returned on a public route. If this came from an environment variable, it is probably unset.`)}function Q(e){return e.length<=256?e:`${e.slice(0,256)}…[truncated]`}const Yn=new WeakMap,Xn=new WeakMap;function Zn(e){if(e.requestId)try{Yn.set(e,y().logger.child({requestId:e.requestId,...e.user?.id!==void 0&&{principalId:e.user.id}}))}catch{}}async function Qn(e,t){let n=b();if(!n)return{locales:[]};let r=e??await E(n).catch(()=>void 0);if(r===void 0)return{locales:[]};let i=await w(n,r);if(!i)return{locales:[]};let a=e=>e!==void 0&&(i.locales.length===0||i.locales.includes(e)),o=n.config.sites?.multiple===!0?i.defaultLocale:void 0,s=a(o)?o:a(t)?t:i.locales[0];return{locales:i.locales,...s!==void 0&&{defaultLocale:s}}}function $(){let e=x();return(e?Yn.get(e):void 0)??y().logger}function $n(t){let{entities:n,defaultLocale:r,publicRole:i=`public`,cors:a,cache:c,onError:u,resolution:d,menus:g,chrome:v,forms:k,site:ne}=t,re=new Map;for(let[e,n]of Object.entries(t.siteForHost??{})){if(!h(n))throw Error(`content-api: \`siteForHost['${e}']\` is ${JSON.stringify(n)}, which is not a site handle.`);re.set(e.trim().toLowerCase(),n)}function ie(e){if(!e.multiSite)return;let t=b()?.entities;return n=>{let r=t?.get(n);return r!==void 0&&!f(r)?`_`:e.site??`_`}}let A=()=>{let e=x();return(e?Xn.get(e):void 0)??r};Jn(`maxLimit`,t.maxLimit),Jn(`maxOffset`,t.maxOffset,{allowZero:!0}),Gt(c);let j=tt(c?.tags);if(!wn(i))throw Error(`content-api: \`publicRole\` must be a non-empty string, received ${JSON.stringify(i)}. An empty public role matches no permission yet is not the anonymous role either, so every unauthenticated request reaches the read path with no groups and fails as a 500. If this came from an environment variable, it is probably unset — omit the option to get "public".`);let se=Math.min(t.maxLimit??100,100),ce=Math.min(t.maxOffset??1e3,1e3),N=Dn(t),P=new on(t.limits),le=new jt(t.search,t.search?.getClientIp??t.limits?.getClientIp);zn(n);let ue;function I(){if(ue)return ue;let e=b(),t=n;if(e){t=[];for(let r of n){let n=e.entities.get(r.name);if(n===void 0){e.logger.error(`content-api: "${r.name}" is in createContentApiHandler({ entities }) but the app does not register an entity of that name — it is NOT served. Register it through lumi.config (entities or a plugin) or remove it from the whitelist.`);continue}t.push(n)}}let r={list:t,map:zn(t)};return e&&(ue=r),r}if(Object.hasOwn(t,`exposeInternalFields`))throw Error("content-api: `exposeInternalFields` has been removed (plan/api D024). Its only sanctioned use was publishing `_overrides`, which D011 replaced by composing site chrome SERVER-side — so the field no longer needs to reach the wire, and no other internal field was ever safe to list (`_workflowStatus` and `_workflowAssignee` describe an editorial process and name a user; `_version`/`_versionedAt` expose revision cadence). Fetch composed chrome from `GET /_chrome` instead. Remove the option: it is refused rather than ignored, because silently dropping a field you configured is exactly the failure this package throws at construction to prevent.");let fe=new Set(g?.handles??[]),L=ke(t.maxResolutionsPerDocument),pe=new e(5e3),_e=null,ve=0;async function ye(){let e=Date.now();return(!_e||e-ve>3e4)&&(_e=await t.loadPermissions(),ve=e),_e}function be(){_e=null,ve=0}function xe(){return{id:Sn,role:i,hasIdentity:!1}}function Ce(e){try{$().warn({err:e},"content-api: `authenticate` hook threw — serving the anonymous principal")}catch{console.warn("[content-api] `authenticate` hook threw:",e)}}async function Ee(e){if(!t.authenticate)return xe();let n;try{n=await t.authenticate(e)}catch(e){return Ce(e),xe()}if(!n||!wn(n.role)||n.id!==void 0&&!wn(n.id)||n.name!==void 0&&typeof n.name!=`string`||n.email!==void 0&&typeof n.email!=`string`||n.site!==void 0&&!(typeof n.site==`string`&&h(n.site)))return xe();let r=n.rateBudgetPerInstance!==void 0&&Number.isSafeInteger(n.rateBudgetPerInstance)&&n.rateBudgetPerInstance>=1;return{id:n.id??Sn,hasIdentity:n.id!==void 0,role:n.role,...n.name!==void 0&&{name:n.name},...n.email!==void 0&&{email:n.email},...r&&{rateBudgetPerInstance:n.rateBudgetPerInstance},...n.site!==void 0&&{site:n.site}}}function De(e){if(re.size===0)return;let t=(e.headers.get(`host`)??new URL(e.url).host).trim().toLowerCase();return re.get(t)}async function Ae(e,t){let n=S();if(t.site!==void 0&&n!==void 0&&n!==t.site)return K({credentialSite:t.site,mountSite:n},`content-api: a credential bound to one site was presented to a mount running as another`),null;let r=t.site??n??De(e),i=b();if(!i)return{...r!==void 0&&{site:r},multiSite:!1};let a=i.config.sites?.multiple===!0,o=r??await E(i).catch(()=>void 0);if(o===void 0)return{multiSite:a};let s=await w(i,o);return r!==void 0&&(s===void 0||s.status!==`active`)?null:{...r!==void 0&&{site:r},...s!==void 0&&{record:s},multiSite:a}}async function B(e){let t=b(),n=t?.config.sites?.multiple===!0;if(!t||!n)return a;if(!e.headers.has(`Origin`))return a??{allowedOrigins:[]};try{let e=await C(t);return e.truncated&&at(`site-origin-index-truncated`,{listed:e.byOrigin.size},`content-api: the site registry holds more active sites than the origin index reads — some sites’ CORS preflights will be refused`),{allowedOrigins:[...new Set([...a?.allowedOrigins??[],...e.byOrigin.keys()])],...a?.maxAge!==void 0&&{maxAge:a.maxAge}}}catch(e){return K({err:e},`content-api: could not read site origins for CORS`),a}}function V(e){return e.hasIdentity||e.role!==i?`identified`:e.site===void 0?`anonymous`:`site-keyed`}function H(e,t,n){return e(t,n,`view`)}function U(e){let t=y();return new ae({entity:e,db:t.db.readOnly,logger:$().child({entity:e.name}),countCache:pe,contextResolver:()=>{let e=x();if(!(!e?.user||!e?.checker))return{user:e.user,checker:e.checker,...e.scope!==void 0&&{scope:e.scope},...te(e,t)}}})}function W(e,n,i,a){let o={budget:Oe(L),cacheTags:a,resolveMedia:t.resolveMedia,resolveBlocks:t.resolveBlocks,siteOf:e=>T(e),afterExpand:async(e,t)=>{if(m(e)){for(let n of t)await ot(e,n,Fe(o),!1);return}await mt(e,t,o),await Ue(e,t,o)},locale:i,reachableEntity:t=>{let r=I().map.get(t);if(!(!r||r.name!==t))return H(e,n,r.name)?r:void 0},canReadEntity:t=>{let r=I().map.get(t);return r!==void 0&&r.name===t&&H(e,n,t)},collectionAllowance:Pe(12),templateDrawnTitle:async(e,n)=>{let s=t.detailTemplates,c=i??r;if(!s||c===void 0)return null;try{let t=await s.publicRow({entity:e.name,row:n,locale:c}),r=typeof t.title==`string`?t.title.trim():``;return r===``?null:r.slice(0,2e3)}catch(t){return o.logger?.warn({entity:e.name,err:t},`content-api: detail-template provider failed to project a reference title`),a.markUncacheable(),null}},readRowsByIds:async(e,t,n)=>{let a=Z(e.name)?.cols.id;return!a||t.length===0||L===0?[]:await U(e).findMany({where:F(a,[...t]),limit:Math.min(t.length,L),...n!==void 0&&{select:[...n]},...i!==void 0&&{locale:i},defaultLocale:r})},resolveEntityHref:t.resolveEntityHref,logger:je()};return o}function je(){try{return $()}catch{return}}function Me(e,t,n){let r=e.collectionAllowance?.refusedCount()??0;if(r>0)try{$().warn({entity:t,path:Q(n),cap:12,refused:r},`content-api: per-response collection cap reached — the collection blocks past it rendered empty`)}catch{console.warn(`[content-api] collection cap reached for`,t,Q(n))}if(e.budget.hasDrops)try{$().warn({entity:t,path:Q(n),ceiling:e.budget.ceiling,resolved:e.budget.granted,dropped:e.budget.dropSummary()},`content-api: per-document resolution budget exhausted — response rendered with unresolved targets`)}catch{console.warn(`[content-api] resolution budget exhausted for`,t,Q(n))}}function Ne(e,t,n,r){let i=Te(e,n);return i.requested>5?{response:J(`?populate= names ${i.requested} fields, which exceeds the maximum of 5.`,`VALIDATION_ERROR`,400,r)}:(i.dropped.length>0&&je()?.debug({entity:t.name,droppedPopulate:i.dropped},`content-api: rejected ?populate= fields (unknown, internal, or not a reference)`),{fields:new Set(i.fields)})}function Fe(e){return{...e,detailTemplates:t.detailTemplates,defaultLocale:r}}async function Ie(e,t,n,r,i){await un(e,t,n,r),await mt(e,t,r),await Ue(e,t,r),Me(r,e.name,i)}async function Le(e,t,n,i,a,l){let u=new URL(e.url),d=me.safeParse(R(u,{allowFilters:!0}));if(!d.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,a);let{limit:f,offset:m,sort:h,locale:g,fields:_,search:v,cursor:y,populate:b}=d.data,x=u.searchParams.has(`limit`),S=Kn(`limit`,f,se,a,x);if(S)return S;let C=Kn(`offset`,m,ce,a);if(C)return C;let w=qn(f,se,x),T=t.allFields,E=Ne(b,t,T,a);if(`response`in E)return E.response;let D;if(y){let e=o(y);if(!e)return J(`Invalid cursor`,`VALIDATION_ERROR`,400,a);if(!Object.hasOwn(T,e.field)&&e.field!==`id`||e.field!==`id`&&z(e.field,T[e.field]))return J(`Invalid cursor field`,`VALIDATION_ERROR`,400,a);D=e}let O=[],ee=!1;if(v){let e=Hn(t,v,g??A());e&&(O.push(e),ee=!0)}let te=Gn(t.name,u,T);O.push(...te.conditions);let k=Wn(t,h,T),ne=k.orderBy;if(D!==void 0&&k.field!==void 0&&p(t,k.field))return J(`Invalid cursor for this sort`,`VALIDATION_ERROR`,400,a);let re=we(_,T);if(te.dropped.length>0||k.dropped!==void 0){let e=[...new Set(te.dropped)],n=e.slice(0,20).map(Q);$().info({entity:t.name,...te.dropped.length>0&&{droppedFilters:n,...e.length>n.length&&{droppedFiltersOmitted:e.length-n.length}},...k.dropped!==void 0&&{droppedSort:Q(k.dropped)}},`content-api: rejected query params (unknown, internal, or invalid)`)}let ie=U(t),j=g??A(),ae=ee,M={where:O.length>0?oe(...O):void 0,limit:ae?w+1:w,offset:m,orderBy:ne,select:re,locale:j,defaultLocale:r,cursor:D},[P,le]=await Promise.all([ie.findMany(M),ae?Promise.resolve(null):ie.count({where:O.length>0?oe(...O):void 0,locale:j})]),F=ae&&P.length>w?P.slice(0,w):P,ue=ae?P.length>w:m+w<(le??0),de;if(F.length>0&&F.length===w){let e=F[F.length-1],t=D?.field??k.field,n=D?.direction??(h?.startsWith(`-`)?`desc`:`asc`);t&&e[t]!==void 0&&(de=s(e,t,n))}l.addCollection(t.name);for(let e of F)l.addDocument(t.name,e.id);let I=W(i,n.role,j,l);return await Ie(t,F,E.fields,I,u.pathname),q({data:F,meta:{total:le,limit:w,offset:m,hasMore:ue,nextCursor:de}},200,X(t.name,a,V(n),c,N,l))}async function Re(e,t,n,r,i){let a=new URL(e.url),o=ge.safeParse(R(a));if(!o.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,r);let s=await U(t).count({locale:o.data.locale??A()});return i.addCollection(t.name),q({data:{count:s}},200,X(t.name,r,V(n),c,N,i))}async function ze(e,t,n,i,a,o,s){if(!Se(n))return Y(o);let l=new URL(e.url),u=he.safeParse(R(l));if(!u.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,o);let{locale:d,fields:f,populate:p,page:h}=u.data,g=t.allFields,_=m(t)?void 0:we(f,g),v=d??A(),y=Ne(p,t,g,o);if(`response`in y)return y.response;let b=await U(t).findById(n,{..._!==void 0&&{select:_},...v!==void 0&&{locale:v},defaultLocale:r});if(!b)return Y(o);s.addDocument(t.name,n);let x={...W(a,i.role,v,s),...h!==void 0&&h>1&&{page:h}};return m(t)?(await ot(t,b,Fe(x),!0),Me(x,t.name,l.pathname)):await Ie(t,[b],y.fields,x,l.pathname),q({data:b},200,X(t.name,o,V(i),c,N,s))}async function Be(e,t,n,i,a,o,s){let l=new URL(e.url),u=he.safeParse(R(l));if(!u.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,o);let d=t.allFields;if(!d.slug)return Y(o);let{locale:f,fields:p,populate:m,page:h}=u.data,g=we(p,d),_=f??A(),v=Ne(m,t,d,o);if(`response`in v)return v.response;let b=Z(t.name);if(!b)return Y(o);let x=b.cols.slug,S=b.cols.id;if(!x||!S)return Y(o);let C=U(t),w=d.slug,E=M(x,n);if(w.translatable&&_){let e=Z(`${t.name}_translations`);if(e){let r=e.cols.slug,i=e.cols.locale,a=e.cols.entityId;if(r&&i&&a){let o=y(),s=await T(t,o),c=oe(M(r,n),M(i,_)),l=await o.db.readOnly.select({entityId:a}).from(e.table).where(s===void 0?c:oe(c,M(Bn(e.cols,t.name),s)));l.length>0&&(E=de(F(S,l.map(e=>e.entityId)),M(x,n))??M(x,n))}}}let D=await C.findMany({where:E,limit:1,select:g,locale:_,defaultLocale:r});if(D.length===0)return Y(o);s.addCollection(t.name),s.addDocument(t.name,D[0]?.id);let O={...W(a,i.role,_,s),...h!==void 0&&h>1&&{page:h}};return await Ie(t,D,v.fields,O,l.pathname),q({data:D[0]},200,X(t.name,o,V(i),c,N,s))}async function Ve(e,t,n,i,a,o){let s=new URL(e.url),l=he.safeParse(R(s));if(!l.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,a);let{locale:u,fields:d,populate:f,page:p}=l.data,m=t.allFields,h=we(d,m),g=u??A(),_=Ne(f,t,m,a);if(`response`in _)return _.response;let v=(await U(t).findMany({limit:1,select:h,locale:g,defaultLocale:r}))[0];if(!v)return Y(a);o.addCollection(t.name),o.addDocument(t.name,v.id);let y={...W(i,n.role,g,o),...p!==void 0&&p>1&&{page:p}};return await Ie(t,[v],_.fields,y,s.pathname),q({data:v},200,X(t.name,a,V(n),c,N,o))}function G(e){return I().map.get(e)??I().map.get(e.endsWith(`s`)?e.slice(0,-1):e)}function We(e,t){if(process.env.NODE_ENV!==`development`)return;let n=JSON.stringify(e.slice(0,100)),r=t===void 0?`${n} is not in the content-api whitelist — add it to createContentApiHandler({ entities: [...] }) in your content route.`:`"${t.name}" is whitelisted but the requesting role lacks 'view' — grant it in the Permission Matrix, or seed it. Note that entity.access.view is advisory metadata the firewall never reads, so a restrictive value there is not the cause.`;console.warn(`[content-api] 404 for ${n}: ${r} (Both refusals are 404 by design — this line is the server-side disambiguation, and the response is unchanged.)`)}async function Ge(e,t,n,r,i){if(!d)return Y(r);let a=new URL(e.url),o=On.safeParse(R(a));if(!o.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,r);let{path:s,locale:l}=o.data,u=await d.resolvePath(s,l);if(u.kind===`none`)return Y(r);if(u.kind===`redirect`)return q({data:u},200,{...r,"Cache-Control":`no-store`});let f=G(u.entityType);return!f||!H(n,t.role,f.name)?(We(u.entityType,f),Y(r)):(i.addCollection(f.name),i.addDocument(f.name,u.id),q({data:u},200,X(f.name,r,V(t),c,N,i)))}async function qe(e,t,n,r,i){if(!d)return Y(r);let a=new URL(e.url),o=kn.safeParse(R(a));if(!o.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,r);let{locale:s,entity:l,cursor:u,limit:f}=o.data,p=a.searchParams.has(`limit`),m=Kn(`limit`,f,se,r,p);if(m)return m;let h=qn(f,se,p),g=G(l);if(!g||!H(n,t.role,g.name))return We(l,g),Y(r);let _=d.enumeratePaths({locale:s,entityType:g.name,...u!==void 0&&{afterDocumentId:u}}),v=[];for await(let e of _)if(v.push(e),v.length===h)break;let y=v.length===h,b=y?v[v.length-1]?.id:void 0;i.addCollection(g.name);for(let e of v)i.addDocument(g.name,e.id);return q({data:v,meta:{limit:h,hasMore:y,nextCursor:b}},200,X(g.name,r,V(t),c,N,i))}async function Je(e,t,n,r,i){if(!d)return Y(r);let a=new URL(e.url),o=An.safeParse(R(a));if(!o.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,r);let{entity:s,id:l}=o.data,u=G(s);if(!u||!H(n,t.role,u.name))return We(s,u),Y(r);let f=x()?.availableLocales,p=await d.getAlternates(u.name,l),m=f?p.filter(e=>f.includes(e.locale)):p;return i.addCollection(u.name),i.addDocument(u.name,l),q({data:m},200,X(u.name,r,V(t),c,N,i))}async function Ye(e,t,n,r){if(!g)return Y(n);let i=new URL(e.url),a=Fn.safeParse(R(i));if(!a.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,n);let{handle:o,locale:s,currentPath:l}=a.data;if(!fe.has(o))return Y(n);let u=await g.getMenu(o,{locale:s,...l!==void 0&&{currentPath:l}});return u?(r.addDocument(`_menu`,o),q({data:u},200,t.site===void 0?Xt(`_menu`,n,c,r):X(`_menu`,n,V(t),c,N,r))):Y(n)}async function Xe(e,t,n,r,i,a){if(!Nn.safeParse(R(new URL(e.url))).success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,i);let o=n.record;if(!o)return Y(i);let s=await ne?.getI18n(o.handle);if((s?.locales??o.locales).length===0)return at(`site-i18n-unwired:${o.handle}`,{site:o.handle},"content-api: GET /_site cannot answer — this site serves every enabled locale and the mount wires no `site.getI18n` to say which those are. Wire it (see the content route the admin app ships), or give the site an explicit locale list."),Y(i);let l=s?.locales??o.locales,u=s?.defaultLocale??r.defaultLocale??l[0];if(u===void 0)return Y(i);let d={handle:o.handle,name:o.name,locales:l.length>0?[...l]:[u],defaultLocale:u,routingStrategy:s?.routingStrategy??o.routingStrategy??`no-prefix-default`,origins:[...o.origins]};return a.addDocument(`_site`,o.handle),q({data:d},200,X(`_site`,i,V(t),c,N,a))}async function Ze(e,n,i,a,o,s){let u=le.consume(e,{principalId:n.hasIdentity?n.id:void 0,site:n.site});if(u&&!u.decision.allowed)return K({limit:`search`,keyClass:u.keyClass},`content-api: caller exceeded its visitor-search budget`),dt(u.decision.retryAfterSeconds,o);let d=new URL(e.url),f=_t.safeParse(R(d));if(!f.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,o);let{q:p,types:m,limit:h,locale:g}=f.data,_=Kn(`limit`,h,50,o);if(_)return _;let v=yt(a.record?.searchTypes??[],m);if(v===null||v.length===0)return Y(o);let y=[];for(let e of v){let t=I().map.get(e);if(t!==void 0&&t.name===e&&H(i,n.role,e)&&vt(t)){y.push(t);continue}if(We(e,t),m!==void 0)return Y(o);at(`search-type:${a.site??``}:${e}`,{site:a.site,type:e},`content-api: a type in the site's searchTypes cannot be searched by this caller — it is skipped`)}if(y.length===0)return Y(o);let b=g??A(),x=[];for(let e of y){s.addCollection(e.name);let t=Hn(e,p,b);if(!t)continue;let n=await U(e).findMany({where:t,limit:h,orderBy:Un(e,p,b),locale:b,defaultLocale:r}),i=l(e),a=Object.hasOwn(e.allFields,i)?e.allFields[i]:void 0,o=a!==void 0&&Vn.has(a.type),c=[];for(let t of n){let n=t.id;if(typeof n!=`string`)continue;let{title:r,summary:a}=Et(e,t,i),s=t[i];c.push({hit:{entity:e,row:t,id:n,title:r,summary:a},titleHit:o&&typeof s==`string`&&Ot(s,p)})}c.length>0&&x.push({hits:c})}let S=Dt(x,h),C=W(i,n.role,b,s);for(let e of S)s.addDocument(e.entity.name,e.id);let w=new Map;for(let e of y){let t=S.filter(t=>t.entity===e);if(t.length===0)continue;let n=bt(e);if(n===null)continue;let r=t.map(e=>({id:e.id,[n]:e.row[n]}));await mt(e,r,C),t.forEach((e,t)=>{w.set(e,r[t]?.[n]??null)})}let T=t.resolveEntityHref,E=await O(S,async e=>{if(!T)return null;try{return await T({entity:e.entity.name,id:e.id,...b!==void 0&&{locale:b}})??null}catch(t){return $().debug({entity:e.entity.name,id:e.id,err:t},`content-api: resolveEntityHref threw — search result served without a path`),null}});return Me(C,`_search`,d.pathname),q({data:S.map((e,t)=>{let n=w.get(e);return{type:e.entity.name,typeLabel:St(e.entity),id:e.id,title:e.title,summary:e.summary,image:xt(n)?n:null,path:E[t]??null}}),meta:{limit:h}},200,X(`_search`,o,V(n),c,N,s))}async function Qe(e,n,r,i,a){if(!v)return Y(i);let o=new URL(e.url),s=Mn.safeParse(R(o));if(!s.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,i);let{locale:l,entity:u,id:d}=s.data;if(!H(r,n.role,v.entity))return Y(i);let f;if(u!==void 0&&d!==void 0){let e=G(u);e&&H(r,n.role,e.name)?f={entityType:e.name,id:d}:je()?.debug({entity:u,locale:l},`content-api: _chrome document is unreachable for this caller — serving the site default`)}a.addCollection(v.entity),f!==void 0&&a.addDocument(f.entityType,f.id);let p=W(r,n.role,l,a),m=await v.getChrome({locale:l,...f!==void 0&&{document:f},budget:p.budget}),h=e=>e&&typeof e==`object`?{blocks:Array.isArray(e.blocks)?e.blocks:[],overridden:e.overridden===!0}:null,g=async(e,n)=>{if(n===null||!t.resolveBlocks||n.blocks.length===0)return n;let r=await He(t.resolveBlocks,n.blocks,{locale:l,budget:p.budget,entity:v.entity,field:e,...p.canReadEntity!==void 0&&{canReadEntity:p.canReadEntity},...p.collectionAllowance!==void 0&&{claimCollection:p.collectionAllowance.claim}});r.failure===`threw`?je()?.warn({entity:v.entity,region:e,err:r.error},`content-api: block resolver threw — this chrome region is not served as stored; it was re-resolved with an exhausted budget, so its media refs and link hrefs are stripped rather than carrying the urls recorded when an editor picked them`):r.failure===`malformed`&&je()?.warn({entity:v.entity,region:e},`content-api: block resolver returned a value that is not a ResolvedBlockTree — this chrome region is not served as stored; it was re-resolved with an exhausted budget, so its media refs and link hrefs are stripped rather than carrying the urls recorded when an editor picked them`),r.retryFailure!==void 0&&(a.markUncacheable(),je()?.warn({entity:v.entity,region:e,err:r.error},`content-api: block resolver failed TWICE, including on the in-memory retry — serving this chrome region EMPTY, so whatever it held is missing from every page render. Serving the stored region instead would put the media urls recorded when an editor picked them, which may be signed, on a cacheable anonymous response`));let i=r.envelope;if(i.refs!==void 0)for(let e of i.refs)a.addDocument(e.entity,e.id);if(i.collections!==void 0)for(let e of Object.values(i.collections))e.entity!==null&&a.addCollection(e.entity);return{blocks:[...i.blocks],overridden:n.overridden,resolved:i.resolved,links:i.links,...i.unresolved!==void 0&&i.unresolved.length>0&&{unresolved:i.unresolved},...i.refs!==void 0&&i.refs.length>0&&{refs:i.refs},...i.collections!==void 0&&{collections:i.collections},...i.live!==void 0&&{live:i.live},...i.currency!==void 0&&{currency:i.currency}}},_={};for(let e of jn)_[e]=await g(e,h(m?.[e]));let y={header:_.header??null,footer:_.footer??null};return Me(p,v.entity,o.pathname),q({data:y},200,X(v.entity,i,V(n),c,N,a))}async function $e(e,t){let n=D(e),r={},i=S(),a={requestId:n,...i!==void 0&&{site:i}};return Zn(a),await ee(a,async()=>{let i=await ct(e,t,n,r);return et(i,n),nt(i,e,n,r),i})}function et(e,t){(e.headers.get(`Cache-Control`)??``).includes(`no-store`)&&e.headers.set(_,t)}function nt(e,t,n,r){if(!u||e.status<400)return;let i=ut(e);if(i!==void 0)try{Promise.resolve(u({status:e.status,code:i,path:Q(new URL(t.url).pathname),...r.entity!==void 0&&{entity:r.entity},requestId:n,...r.principalId!==void 0&&{principalId:r.principalId}})).catch(st)}catch(e){st(e)}}let it=new Set;function at(e,t,n){it.has(e)||(it.add(e),K(t,n))}function K(e,t){try{$().warn(e,t)}catch{try{console.warn(`[content-api]`,t,e)}catch{}}}function st(e){try{$().warn({err:e},"content-api: `onError` monitoring hook failed")}catch{}}async function ct(e,t,n,r){let i=Qt(e,await B(e)),a=Zt(i,N);try{await P.acquire(e.signal)}catch(e){return e instanceof en?(K({limit:`survival`,maxConcurrentRequests:P.limits.maxConcurrentRequests,maxQueuedRequests:P.limits.maxQueuedRequests},`content-api: shedding load — concurrency slots and wait queue both full`),ft(1,a)):(K({err:e},`content-api: acquiring a concurrency slot failed`),J(`Internal server error`,`INTERNAL_ERROR`,500,a))}try{return await P.runGuarded(a=>lt(e,t,n,r,i,a))}catch(e){if(e instanceof tn)return K({limit:`deadline`,requestTimeoutMs:P.limits.requestTimeoutMs},`content-api: request exceeded the wall clock`),ft(1,a);throw e}finally{P.release()}}async function lt(e,t,n,i,o,s){let c=o;try{let l=t.path;if(!l||l.length===0||l[0]!==`v1`)return Y(o);let u=l.slice(1);if(u.length===0)return Y(o);if(new URL(e.url).searchParams.has(`site`))return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,Zt(o,N));let f=await Ee(e),p=f.role,h=await Ae(e,f);if(h===null)return Y(Zt(a?{Vary:`Origin`}:{},N));let _=h.multiSite?Qt(e,{allowedOrigins:h.record?.origins??[],...a?.maxAge!==void 0&&{maxAge:a.maxAge}}):o,y=P.consumeFairness(e,{principalId:f.hasIdentity?f.id:void 0,budgetPerInstance:f.rateBudgetPerInstance}),b=Zt(_,N);c=b;let x=rt(j,ie(h));if(y&&!y.decision.allowed)return K({limit:`fairness`,keyClass:y.keyClass},`content-api: caller exceeded its per-instance budget`),dt(y.decision.retryAfterSeconds,b);let S=await ye();i.principalId=f.id;let C=h.site,w=await Qn(C,r),T=new URL(e.url).searchParams.get(`locale`);if(T!==null&&T!==``&&w.locales.length>0&&!w.locales.includes(T))return J(`Locale '${T}' is not served by this site`,`VALIDATION_ERROR`,400,b);let E={user:{id:f.id,groups:p?[p]:[],...f.name!==void 0&&{name:f.name},...f.email!==void 0&&{email:f.email}},checker:S,requestId:n,...C!==void 0&&{site:C},...w.locales.length>0&&{availableLocales:w.locales}};w.defaultLocale!==void 0&&Xn.set(E,w.defaultLocale),Zn(E);let D=await ee(E,async()=>{if(s?.aborted)throw new tn;if(e.method===`POST`){let t=It(u,`submissions`);return k===void 0||t===void 0?Y(b):zt({forms:k,keySite:f.site,formId:t,headers:b,req:e})}if(u[0]===`_forms`){let t=It(u,`token`);return k===void 0||t===void 0?Y(b):Rt({forms:k,keySite:f.site,formId:t,headers:b,req:e})}if(u[0]===`_schema`)return q(xn({entities:I().list,checkPermission:e=>H(S,p,e),version:`v1`,maxLimit:se,maxOffset:ce,maxResolutionsPerDocument:L,limits:P.limits,hasResolution:d!==void 0,hasMenus:g!==void 0,hasChrome:v!==void 0,cacheTags:j,siteScopedTags:h.multiSite}),200,{...b,"Cache-Control":`no-store`});if(u[0]===`_resolve`)return Ge(e,f,S,b,x);if(u[0]===`_paths`)return qe(e,f,S,b,x);if(u[0]===`_alternates`)return Je(e,f,S,b,x);if(u[0]===`_menu`)return Ye(e,f,b,x);if(u[0]===`_site`)return Xe(e,f,h,w,b,x);if(u[0]===`_chrome`)return Qe(e,f,S,b,x);if(u[0]===`_search`&&u.length===1)return Ze(e,f,S,h,b,x);let t=u[0];if(t===void 0)return Y(b);let n=G(t);if(!n||!H(S,p,n.name))return We(t,n),Y(b);if(i.entity=n.name,n.kind===`singleton`)return u.length===1?Ve(e,n,f,S,b,x):Y(b);if(m(n)){let t=u[1];return u.length===2&&t!==void 0?ze(e,n,t,f,S,b,x):Y(b)}return u.length===1?Le(e,n,f,S,b,x):u[1]===`count`?Re(e,n,f,b,x):u[1]===`slug`&&u[2]?Be(e,n,u[2],f,S,b,x):u.length===2&&u[1]!==void 0?ze(e,n,u[1],f,S,b,x):Y(b)});return x.dropped>0&&D.headers.has(j.header)&&K({dropped:x.dropped,emitted:x.tags.length,maxTags:128,maxHeaderBytes:Ke,...i.entity!==void 0&&{entity:i.entity},path:Q(new URL(e.url).pathname)},`content-api: cache tags refused — this response depends on documents it does not name, so a purge for them will not invalidate it`),D}catch(t){if(t instanceof tn)throw t;if(Pn(t))return Y(c);let n=new URL(e.url).pathname;try{$().error({err:t,path:Q(n)},`content-api handler error`)}catch{console.error(`[content-api] handler error:`,t)}return J(`Internal server error`,`INTERNAL_ERROR`,500,c)}}return{GET:(e,t)=>$e(e,t),POST:(e,t)=>$e(e,t),OPTIONS:async e=>$t(e,await B(e),c),invalidatePermissionCache:be}}export{Ln as API_VERSION,G as CACHE_TAG_NAMESPACE,ht as DEFAULT_SEARCH_RESULTS,it as DETAIL_TEMPLATE_FIELD,st as ERROR_CODES,Ge as MAX_CACHE_TAGS_PER_RESPONSE,Ke as MAX_CACHE_TAG_HEADER_BYTES,We as MAX_CACHE_TAG_LENGTH,Mt as MAX_FORM_BODY_BYTES,De as MAX_RESOLUTIONS_PER_DOCUMENT,gt as MAX_SEARCH_RESULTS,qe as MEDIA_TAG_ENTITY,Ye as SHARED_SITE_TAG_SEGMENT,kt as VISITOR_ADDRESS_HEADER,$n as createContentApiHandler,Le as isResolvedBlockTree};
|
|
1
|
+
import{CountCache as e,SITE_COLUMN as t,SiteRequiredError as n,blockTreeFieldsOf as r,blockTreeTemplateOf as i,buildTranslationsSearchExists as a,decodeCursor as o,encodeCursor as s,filterTranslatableFields as c,getEntityTitleField as l,getSearchableConfig as u,hasSiteTemplates as d,isSiteBound as f,isSortOnlyInternalField as p,isTemplateDrawn as m,isValidSiteHandle as h}from"@murumets-ee/entity";import{LOCALE_PATTERN as g,REQUEST_ID_HEADER as _,escapeLikePattern as v,getApp as y,getAppOrUndefined as b,getContext as x,getCurrentSite as S,readSiteOriginIndex as C,readSiteRecord as w,requireSiteFor as T,resolveImplicitSite as E,resolveRequestId as D,runBounded as O,runWithContextAsync as ee,siteSecurityFields as te}from"@murumets-ee/core";import{z as k}from"zod";import{InMemoryRateLimitStore as ne,Semaphore as re,createClientIpResolver as ie,runWithDeadline as A}from"@murumets-ee/core/limits";import{schemaRegistry as j}from"@murumets-ee/db";import{QueryClient as ae}from"@murumets-ee/entity/query";import{and as oe,asc as se,desc as ce,eq as M,getTableColumns as N,gte as P,ilike as le,inArray as F,lte as ue,or as de,sql as I}from"drizzle-orm";const fe=/[\u200B-\u200D\u2060\uFEFF]/g;function L(e){return e.replace(fe,``).trim()}const pe=2048,me=k.object({limit:k.coerce.number().int().min(1).max(100).default(20),offset:k.coerce.number().int().min(0).default(0),sort:k.string().regex(/^-?[a-zA-Z_]+$/).optional(),locale:k.string().regex(g).optional(),fields:k.string().optional(),search:k.string().max(200).refine(e=>{let t=L(e);return t.length===0||t.length>=2},{message:`search must be at least 2 characters`}).optional(),cursor:k.string().max(500).optional(),populate:k.string().max(200).optional()}).strict(),he=k.object({locale:k.string().regex(g).optional(),fields:k.string().optional(),populate:k.string().max(200).optional(),page:k.string().regex(/^(?:[1-9][0-9]?|100)$/).transform(Number).optional()}).strict(),ge=k.object({locale:k.string().regex(g).optional()}).strict(),_e=/^filter\[([a-zA-Z0-9_]+)\]$/;function R(e,t){let n={};for(let[r,i]of e.searchParams.entries())t?.allowFilters===!0&&_e.test(r)||(n[r]=i);return n}const ve=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ye=/^\d{4}-\d{2}-\d{2}(?:[Tt ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:[Zz]|[+-]\d{2}:?\d{2})?)?$/;function be(e){if(!ye.test(e))return!1;let t=Date.parse(e);return Number.isNaN(t)?!1:e.length===10?new Date(t).toISOString().slice(0,10)===e:!0}function xe(e){if(e.trim()===``)return!1;let t=Number(e);return Number.isFinite(t)}function Se(e){return ve.test(e)}function Ce(e,t){switch(e.type){case`boolean`:return t===`true`?!0:t===`false`?!1:null;case`reference`:case`media`:return ve.test(t)?t:null;case`select`:return e.options.includes(t)?t:null;case`date`:return be(t.startsWith(`gte:`)||t.startsWith(`lte:`)?t.slice(4):t)?t:null;case`number`:return xe(t)?Number(t):null;case`text`:return t.length<=200?t:null;default:return null}}function z(e,t){return e.startsWith(`_`)||t?.internal===!0||t?.adminOnly===!0}function we(e,t){if(!e)return;let n=e.split(`,`).map(e=>e.trim()).filter(e=>{if(!Object.hasOwn(t,e))return!1;let n=t[e];return n!==void 0&&!z(e,n)&&n.type!==`blockTree`});return n.includes(`id`)||n.unshift(`id`),n}function Te(e,t){if(!e)return{fields:[],dropped:[],requested:0};let n=[...new Set(e.split(`,`).map(e=>e.trim()).filter(e=>e.length>0))],r=[],i=[];for(let e of n){if(!Object.hasOwn(t,e)){i.push(e);continue}let n=t[e];if(!n||z(e,n)||n.type!==`reference`){i.push(e);continue}r.push(e)}return{fields:r,dropped:i,requested:n.length}}const Ee=[`reference`,`populate`,`media`,`block`],De=200;function Oe(e){if(!Number.isInteger(e)||e<0)throw Error(`content-api: resolution budget ceiling must be a non-negative integer, received ${String(e)}.`);let t=e,n=0,r=new Map;return{claim(e,i){if(!Number.isInteger(i)||i<=0)return 0;let a=Math.min(i,t);t-=a,n+=a;let o=i-a;return o>0&&r.set(e,(r.get(e)??0)+o),a},get remaining(){return t},get granted(){return n},get hasDrops(){return r.size>0},dropSummary(){let e={};for(let t of Ee){let n=r.get(t);n!==void 0&&n>0&&(e[t]=n)}return e},ceiling:e}}function ke(e){if(e===void 0)return 200;if(!Number.isInteger(e)||e<0)throw Error(`content-api: \`maxResolutionsPerDocument\` must be an integer >= 0, received ${String(e)}. If this came from an environment variable, it is probably unset — omit the option to get the package default (200).`);return Math.min(e,200)}const Ae=2e3;function B(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function V(e){if(!B(e))return!1;let t=e=>e===void 0||typeof e==`string`&&e.length<=Ae,n=e=>e===void 0||typeof e==`number`&&Number.isFinite(e)&&e>=0;if(!t(e.title)||!t(e.text))return!1;let r=e.price;if(r!==void 0&&(!B(r)||typeof r.amount!=`number`||!Number.isFinite(r.amount)||r.amount<0||!n(r.compareAt)||!t(r.unit)))return!1;let i=e.facts;if(i!==void 0){if(!Array.isArray(i)||i.length>12)return!1;for(let e of i)if(!B(e)||typeof e.key!=`string`||typeof e.label!=`string`||typeof e.value!=`string`&&typeof e.value!=`number`||e.format!==void 0&&e.format!==`price`)return!1}let a=e.body;if(a!==void 0){if(!B(a)||typeof a.html!=`string`||a.html.length>5e5||!Array.isArray(a.headings)||a.headings.length>100)return!1;for(let e of a.headings)if(!B(e)||typeof e.id!=`string`||typeof e.text!=`string`||e.level!==2&&e.level!==3)return!1}let o=e.embed;if(o!==void 0&&(!B(o)||typeof o.provider!=`string`||typeof o.reference!=`string`))return!1;let s=e.breadcrumbs;if(s!==void 0){if(!Array.isArray(s)||s.length>8)return!1;for(let e of s){if(!B(e)||typeof e.label!=`string`||e.label.length>Ae)return!1;if(e.href!==void 0){if(typeof e.href!=`string`||e.href.length>1e3||!e.href.startsWith(`/`)||e.href.startsWith(`//`))return!1;for(let t of e.href){let e=t.codePointAt(0)??0;if(e<=32||e===127||t===`\\`)return!1}}}}return!0}const H=new Set([`price`,`number`,`text`]);function U(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return W(t.name)&&W(t.label)&&H.has(t.format)&&(t.unit===void 0||W(t.unit))}function W(e){if(typeof e!=`string`||e.length>1200)return!1;for(let t=0;t<e.length;t++)if(e.charCodeAt(t)<32)return!1;return!0}function je(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let{sources:t,values:n}=e;if(typeof t!=`object`||!t||Array.isArray(t)||typeof n!=`object`||!n||Array.isArray(n))return!1;let r=Object.entries(t);if(r.length>32)return!1;for(let[,e]of r){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(typeof t.label!=`string`||t.labelKey!==void 0&&typeof t.labelKey!=`string`||t.kind!==void 0&&t.kind!==`price`&&t.kind!==`text`&&t.kind!==`list`&&t.kind!==`facts`||t.facts!==void 0&&(!Array.isArray(t.facts)||t.facts.length>48||!t.facts.every(U))||t.fields!==void 0&&(!Array.isArray(t.fields)||t.fields.length>64||!t.fields.every(e=>typeof e==`string`)))return!1}let i=Object.entries(n);if(i.length>32)return!1;for(let[,e]of i){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.entries(e);if(t.length>200)return!1;for(let[,e]of t){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(t.amount!==void 0&&(typeof t.amount!=`number`||!Number.isFinite(t.amount))||t.compareAt!==void 0&&(typeof t.compareAt!=`number`||!Number.isFinite(t.compareAt))||t.unit!==void 0&&typeof t.unit!=`string`||t.text!==void 0&&!W(t.text)||t.items!==void 0&&(!Array.isArray(t.items)||t.items.length>100||!t.items.every(W)))return!1;if(t.facts!==void 0){if(typeof t.facts!=`object`||t.facts===null||Array.isArray(t.facts))return!1;let e=Object.entries(t.facts);if(e.length>48)return!1;for(let[,t]of e)if(!(typeof t==`number`&&Number.isFinite(t)||W(t)))return!1}}}return!0}const Me=new Set([`ok`,`unset`,`unavailable`,`over-budget`,`needs-document`]);function Ne(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(typeof t.status!=`string`||!Me.has(t.status)||t.entity!==null&&(typeof t.entity!=`string`||t.entity===``)||!Array.isArray(t.rows)||t.rows.length>100)return!1;if(t.page!==void 0){if(typeof t.page!=`object`||t.page===null||Array.isArray(t.page))return!1;let e=t.page;if(typeof e.number!=`number`||!Number.isInteger(e.number)||e.number<1||e.number>100||typeof e.hasNext!=`boolean`)return!1}if(t.status===`ok`&&t.entity===null||t.status!==`ok`&&t.rows.length>0||(t.status===`unset`||t.status===`unavailable`)&&t.entity!==null)return!1;for(let e of t.rows){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(typeof t.id!=`string`||t.id===``)return!1;for(let e of[t.title,t.text,t.href])if(e!==null&&typeof e!=`string`)return!1;if(t.image!==null){if(typeof t.image!=`object`||Array.isArray(t.image))return!1;let e=t.image;if(typeof e.url!=`string`||e.alt!==null&&typeof e.alt!=`string`)return!1;for(let t of[e.width,e.height])if(t!==null&&typeof t!=`number`)return!1}}return!0}function Pe(e){if(!Number.isInteger(e)||e<0)throw Error(`content-api: collection allowance must be a non-negative integer, received ${String(e)}.`);let t=e,n=0;return{claim:()=>t===0?(n+=1,!1):(--t,!0),refusedCount:()=>n}}const Fe=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;function Ie(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.keys(e);return t.length>16?!1:t.every(e=>Fe.test(e))}function Le(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(t.resolved!==1||!Array.isArray(t.blocks))return!1;let n=t.links;if(typeof n!=`object`||!n||Array.isArray(n))return!1;for(let e of Object.values(n))if(e!==null&&typeof e!=`string`)return!1;let r=new Set,i=t.refs;if(i!==void 0){if(!Array.isArray(i))return!1;for(let e of i){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(typeof t.entity!=`string`||t.entity===``||typeof t.id!=`string`||t.id===``)return!1;r.add(`${t.entity}\u0000${t.id}`)}}let a=t.collections;if(a!==void 0){if(typeof a!=`object`||!a||Array.isArray(a))return!1;let e=Object.entries(a);if(e.length>64)return!1;for(let[t,n]of e){if(t===``||!Ne(n))return!1;if(!(n.status!==`ok`||n.entity===null)){for(let e of n.rows)if(!r.has(`${n.entity}\u0000${e.id}`))return!1}}}let o=t.unresolved;if(o!==void 0){if(!Array.isArray(o))return!1;for(let e of o)if(!Re(e))return!1}return!(t.live!==void 0&&!je(t.live)||t.currency!==void 0&&typeof t.currency!=`string`||t.detail!==void 0&&!V(t.detail)||t.blockData!==void 0&&!Ie(t.blockData))}function Re(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return t.kind!==`media`&&t.kind!==`link`||typeof t.ref!=`string`?!1:t.reason===`unresolvable`||t.reason===`budget`}function ze(e){return r(e).filter(e=>!e.internal).map(e=>e.name)}const Be=Object.freeze({resolved:1,blocks:Object.freeze([]),links:Object.freeze({})});async function Ve(e,t,n){try{let r=await e(t,n.boundValues===void 0?n:{...n,boundValues:structuredClone(n.boundValues)});return Le(r)?{ok:!0,envelope:r}:{ok:!1,failure:`malformed`}}catch(e){return{ok:!1,failure:`threw`,error:e}}}async function He(e,t,n){let r=await Ve(e,t,n);if(r.ok)return{envelope:r.envelope};let i=await Ve(e,t,{...n,budget:Oe(0),claimCollection:void 0});return i.ok?{envelope:i.envelope,failure:r.failure,error:r.error}:{envelope:Be,failure:r.failure,retryFailure:i.failure,error:r.error??i.error}}async function Ue(e,t,n){if(t.length===0)return;let r=n.resolveBlocks;if(!r)return;let a=ze(e);if(a.length===0)return;let o=new Map;for(let t of a){let r;if(d(e,t)){if(n.siteOf===void 0)throw Error(`content-api: '${e.name}.${t}' declares siteTemplates but block resolution was given no siteOf to learn the row’s site`);r=await n.siteOf(e)}o.set(t,i(e,t,r))}let s=0,c=0,l=0,u,f,p=new Set,m=new Set,h=new Set;for(let i of t)for(let t of a){let a=i[t],d=o.get(t);if(d!==void 0&&!Object.hasOwn(i,t)||d===void 0&&a==null)continue;let g=await He(r,d===void 0?a:[],{locale:n.locale,budget:n.budget,entity:e.name,field:t,...d!==void 0&&{template:d},boundValues:{...i},...n.canReadEntity!==void 0&&{canReadEntity:n.canReadEntity},...n.collectionAllowance!==void 0&&{claimCollection:n.collectionAllowance.claim},...n.page!==void 0&&{page:n.page}});if(g.failure===`threw`?(s+=1,p.add(t),u??=g.error):g.failure===`malformed`&&(c+=1,m.add(t)),g.retryFailure!==void 0&&(l+=1,h.add(t),f??=g.error,n.cacheTags?.markUncacheable()),i[t]=g.envelope,g.envelope.refs!==void 0)for(let e of g.envelope.refs)n.cacheTags?.addDocument(e.entity,e.id);if(g.envelope.collections!==void 0)for(let e of Object.values(g.envelope.collections))e.entity!==null&&n.cacheTags?.addCollection(e.entity)}s>0&&n.logger?.warn({entity:e.name,fields:[...p],rows:t.length,failures:s,err:u},`content-api: block resolver threw — no tree is served as stored; each was re-resolved with an exhausted budget, so its media refs and link hrefs are stripped rather than carrying the urls recorded when an editor picked them. Fields that failed that retry as well are reported separately, as empty.`),c>0&&n.logger?.warn({entity:e.name,fields:[...m],rows:t.length,failures:c},`content-api: block resolver returned a value that is not a ResolvedBlockTree — no tree is served as stored; each was re-resolved with an exhausted budget, so its media refs and link hrefs are stripped rather than carrying the urls recorded when an editor picked them. Fields that failed that retry as well are reported separately, as empty.`),l>0&&n.logger?.warn({entity:e.name,fields:[...h],rows:t.length,failures:l,err:f},`content-api: block resolver failed TWICE, including on the in-memory retry — those fields are served as an empty resolved tree, so that content is missing from the response. Serving the stored tree instead would put the media urls recorded when an editor picked them, which may be signed, on a cacheable anonymous response.`)}const G=`lumi`,We=128,Ge=128,Ke=3072,qe=`media`,Je=/^[A-Za-z0-9_.-]+$/,Ye=`_`,Xe={enabled:!0,header:`Cache-Tag`,separator:`,`},Ze=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Qe=[`cache-control`,`vary`,`content-type`],$e=[`access-control-`];function et(e){if(e){if(e.enabled!==void 0&&typeof e.enabled!=`boolean`)throw Error(`content-api cache: \`cache.tags.enabled\` must be a boolean, received ${JSON.stringify(e.enabled)}.`);if(e.header!==void 0){if(typeof e.header!=`string`||!Ze.test(e.header))throw Error(`content-api cache: \`cache.tags.header\` must be a valid HTTP field name (RFC 9110 §5.1 token), received ${JSON.stringify(e.header)}. Common values: \`Cache-Tag\` (Cloudflare/Netlify, the default), \`Surrogate-Key\` (Fastly), \`Edge-Cache-Tag\` (Akamai).`);let t=e.header.toLowerCase();if(Qe.includes(t)||$e.some(e=>t.startsWith(e)))throw Error(`content-api cache: \`cache.tags.header\` may not be ${JSON.stringify(e.header)} — this package writes that header itself on the same responses, so the tags would either overwrite it or be overwritten, silently and on every request.`)}if(e.separator!==void 0&&e.separator!==`,`&&e.separator!==` `)throw Error(`content-api cache: \`cache.tags.separator\` must be ',' or ' ', received ${JSON.stringify(e.separator)}. Cloudflare and Akamai parse comma-separated tags; Fastly parses space-separated ones. A third separator would not error at the CDN — it would parse as one giant unmatched key, which is the silent failure this refuses.`)}}function tt(e){return{enabled:e?.enabled??Xe.enabled,header:e?.header??Xe.header,separator:e?.separator??Xe.separator}}function nt(e){return typeof e==`string`&&e!==``&&Je.test(e)}function rt(e,t){function n(e){if(t===void 0)return G;let n=t(e);return nt(n)?`${G}:${n}`:void 0}let r=new Set,i=0,a=!1,o=e.header.length+4,s=!1;function c(e){if(r.has(e))return;if(e.length>128||r.size>=128){i+=1;return}let t=e.length+(r.size===0?0:1);if(s||o+t>3072){s=!0,i+=1;return}o+=t,r.add(e)}return{addDocument(e,t){if(!nt(e)||!nt(t)){i+=1;return}let r=n(e);if(r===void 0){i+=1;return}c(`${r}:${e}:${t}`)},addCollection(e){if(!nt(e)){i+=1;return}let t=n(e);if(t===void 0){i+=1;return}c(`${t}:${e}`)},get tags(){return[...r]},markUncacheable(){a=!0},get dropped(){return i},get uncacheable(){return a},headers(){return!e.enabled||r.size===0?{}:{[e.header]:[...r].join(e.separator)}}}}const it=`_template`;function at(e){if(typeof e!=`string`)return;let t=e.trim();return t===``?void 0:t.slice(0,2e3)}async function ot(e,t,n,r){let i={...t};for(let e of Object.keys(t))e!==`id`&&delete t[e];let a=n.detailTemplates;if(!a)return;let o=n.locale??n.defaultLocale;if(o===void 0)return;try{let n=await a.publicRow({entity:e.name,row:i,locale:o}),r=at(n.title),s=at(n.description);r!==void 0&&(t.title=r),s!==void 0&&(t.description=s)}catch(t){n.logger?.warn({entity:e.name,err:t},`content-api: detail-template provider failed to project a row — served with its id only`),n.cacheTags?.markUncacheable()}if(!r)return;let s=n.resolveBlocks;if(!s||(n.cacheTags?.addCollection(a.entity),n.budget.claim(`block`,1)<1))return;let c;try{c=await a.readTemplate({entity:e.name,locale:o})}catch(t){n.logger?.warn({entity:e.name,err:t},`content-api: detail-template provider failed to read the template — the row is served without one and the response is not cacheable`),n.cacheTags?.markUncacheable();return}if(c===null||typeof c.id!=`string`||!Array.isArray(c.blocks))return;n.cacheTags?.addDocument(a.entity,c.id);let l=await He(s,c.blocks,{locale:n.locale,budget:n.budget,entity:e.name,field:it,boundValues:i,rowIsForeign:!0,...n.canReadEntity!==void 0&&{canReadEntity:n.canReadEntity},...n.collectionAllowance!==void 0&&{claimCollection:n.collectionAllowance.claim},...n.page!==void 0&&{page:n.page}});l.failure!==void 0&&n.logger?.warn({entity:e.name,field:it,failure:l.failure,retryFailure:l.retryFailure,err:l.error},`content-api: block resolver failed on a detail template — served re-resolved with an exhausted budget, or empty if that failed as well`),l.retryFailure!==void 0&&n.cacheTags?.markUncacheable(),K(l.envelope,n),t[it]=l.envelope}function K(e,t){if(e.refs!==void 0)for(let n of e.refs)t.cacheTags?.addDocument(n.entity,n.id);if(e.collections!==void 0)for(let n of Object.values(e.collections))n.entity!==null&&t.cacheTags?.addCollection(n.entity)}const st=[`NOT_FOUND`,`VALIDATION_ERROR`,`INTERNAL_ERROR`,`RATE_LIMITED`,`SERVICE_OVERLOADED`,`FORM_INVALID`,`CHALLENGE_FAILED`,`PAYLOAD_TOO_LARGE`];function q(e,t=200,n){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":`application/json`,...n}})}const ct={"Cache-Control":`no-store`},lt=new WeakMap;function ut(e){return lt.get(e)}function J(e,t,n,r,i){let a=q({error:{status:n,message:e,code:t,...i}},n,{...r,...ct});return lt.set(a,t),a}function Y(e){return J(`Not found`,`NOT_FOUND`,404,e)}function dt(e,t){return J(`Rate limit exceeded`,`RATE_LIMITED`,429,{...t,"Retry-After":String(e)})}function ft(e,t){return J(`Service overloaded`,`SERVICE_OVERLOADED`,503,{...t,"Retry-After":String(e)})}function pt(e){let t=[];for(let[n,r]of Object.entries(e.allFields))r.type!==`media`||z(n,r)||t.push([n,r]);return t}async function mt(e,t,n){if(t.length===0)return;let r=pt(e);if(r.length===0)return;let i=new Set;for(let e of t)for(let[t]of r){if(!Object.hasOwn(e,t))continue;let n=e[t];typeof n==`string`&&n!==``&&i.add(n)}let a=new Map;if(i.size>0&&n.resolveMedia){let t=[...i],r=n.budget.claim(`media`,t.length),o=t.slice(0,r);if(o.length>0)try{a=await n.resolveMedia(o,{locale:n.locale})}catch(t){n.logger?.warn({entity:e.name,err:t},"content-api: media resolver threw — media fields resolve to null (if this is a ForbiddenError, the requesting role is missing `media:view`)")}}else i.size>0&&n.logger?.debug({entity:e.name,mediaFields:r.map(([e])=>e)},"content-api: no `resolveMedia` provider wired — media fields resolve to null");for(let[e,t]of a)i.has(e)&&t?.id===e&&n.cacheTags?.addDocument(qe,e);for(let e of t)for(let[t]of r){if(!Object.hasOwn(e,t))continue;let n=e[t];e[t]=typeof n==`string`?a.get(n)??null:null}}const ht=20,gt=50,_t=k.object({q:k.string().max(200).refine(e=>L(e).length>=2,{message:`q must be at least 2 characters`}),types:k.string().max(808).optional(),limit:k.coerce.number().int().min(1).default(20),locale:k.string().regex(g).optional()}).strict();function vt(e){return u(e)===void 0||m(e)?!1:e.kind!==`singleton`}function yt(e,t){if(t===void 0)return[...e];let n=t.split(`,`).map(e=>e.trim()).filter(e=>e!==``);if(n.length===0)return null;for(let t of n)if(!e.includes(t))return null;return e.filter(e=>n.includes(e))}function bt(e){for(let[t,n]of pt(e)){let e=n.accept;if(e===void 0||e.length===0||e.some(e=>e===`*/*`||e.startsWith(`image/`)))return t}return null}function xt(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&typeof t.url==`string`}function St(e){let t=e.admin?.labelSingular;if(typeof t==`string`&&t.trim()!==``)return t.trim();let n=e.name.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/[_-]+/g,` `).trim().toLowerCase();return n===``?e.name:`${n.charAt(0).toUpperCase()}${n.slice(1)}`}function Ct(e,t){if(typeof e!=`string`)return null;let n=e.replace(/\s+/g,` `).trim();return n===``?null:n.length>t?`${n.slice(0,t-1).trimEnd()}…`:n}const wt=[`summary`,`excerpt`,`description`,`intro`,`lead`],Tt=new Set([`text`]);function Et(e,t,n){let r=null,i=e.allFields;for(let e of wt){let n=i[e];if(!(n===void 0||!Tt.has(n.type))&&(r=Ct(t[e],300),r!==null))break}let a=null,o=u(e);if(o)try{let e=o.projection({...t});r??=Ct(e.description,300),a=Ct(e.label,300)}catch{}return{title:Ct(t[n],300)??a??(typeof t.id==`string`?t.id:``),summary:r}}function Dt(e,t){let n=[];for(let r of[!0,!1]){let i=e.map(e=>e.hits.filter(e=>e.titleHit===r).map(e=>e.hit));for(let e=0;n.length<t;e++){let r=!1;for(let a of i){let i=a[e];if(i!==void 0&&(r=!0,n.push(i),n.length===t))break}if(!r)break}}return n}function Ot(e,t){let n=L(t).toLocaleLowerCase();return n!==``&&e.toLocaleLowerCase().includes(n)}const kt=`x-lumi-visitor-address`;function At(e,t,n){if(e===void 0)return t;if(!Number.isSafeInteger(e)||e<1)throw Error(`content-api search: \`${n}\` must be a positive integer (got ${e})`);return e}var jt=class{getClientIp;store;tokens;intervalMs;readVisitor=ie({header:kt,trustedProxyHops:1,surface:`content-api visitor search`});constructor(e,t){this.getClientIp=t,this.tokens=At(e?.searchesPerVisitorPerInstance,30,`searchesPerVisitorPerInstance`),this.intervalMs=At(e?.intervalMs,6e4,`intervalMs`),this.store=e?.store??new ne}consume(e,t,n){let r=this.keyFor(e,t);if(r!==void 0)return{decision:this.store.consume(`search:${r.key}`,{tokens:this.tokens,intervalMs:this.intervalMs},n),keyClass:r.keyClass}}keyFor(e,t){if(t.principalId!==void 0)return{key:`principal:${t.principalId}`,keyClass:`principal`};if(t.site!==void 0){let n=this.readVisitor(e.headers);if(n!==null)return{key:`visitor:${t.site}:${n}`,keyClass:`visitor`}}if(t.site!==void 0)return;let n=this.getClientIp?.(e);if(n!==void 0&&n!==``)return{key:`ip:${n}`,keyClass:`client-ip`}}};const Mt=64*1024,Nt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Pt=ie({header:kt,trustedProxyHops:1,surface:`content-api form submissions`}),Ft={"Cache-Control":`no-store`};function It(e,t){if(e.length!==3||e[0]!==`_forms`||e[2]!==t)return;let n=e[1];return n!==void 0&&Nt.test(n)?n:void 0}async function Lt(e,t){let n=e.headers.get(`content-type`)??``;if(!/^application\/json\s*(?:;|$)/i.test(n))return{ok:!1,reason:`invalid`};let r=e.headers.get(`content-length`);if(r!==null&&Number(r)>t)return{ok:!1,reason:`too_large`};if(e.body===null)return{ok:!1,reason:`invalid`};let i=e.body.getReader(),a=[],o=0;for(;;){let{done:e,value:n}=await i.read();if(e)break;if(o+=n.byteLength,o>t)return await i.cancel(),{ok:!1,reason:`too_large`};a.push(n)}let s=new Uint8Array(o),c=0;for(let e of a)s.set(e,c),c+=e.byteLength;try{return{ok:!0,value:JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(s))}}catch{return{ok:!1,reason:`invalid`}}}async function Rt(e){if(e.keySite===void 0)return Y(e.headers);let t=await e.forms.issueToken({site:e.keySite,formId:e.formId,purpose:new URL(e.req.url).searchParams.get(`for`)===`visitor`?`visitor`:`render`,visitorAddress:Pt(e.req.headers)});return t===null?Y(e.headers):t===`rate_limited`?dt(600,e.headers):q({data:t},200,{...e.headers,...Ft})}async function zt(e){if(e.keySite===void 0)return Y(e.headers);let t=await Lt(e.req,Mt);if(!t.ok)return t.reason===`too_large`?J(`Submission too large`,`PAYLOAD_TOO_LARGE`,413,e.headers):J(`Malformed submission`,`VALIDATION_ERROR`,400,e.headers);let n=await e.forms.submit({site:e.keySite,formId:e.formId,body:t.value,visitorAddress:Pt(e.req.headers)});switch(n.kind){case`accepted`:return q({data:{ok:!0}},200,{...e.headers,...Ft});case`invalid`:return Bt(n.fields,e.headers);case`rate_limited`:return dt(n.retryAfterSeconds,e.headers);case`challenge_failed`:return J(`Verification failed`,`CHALLENGE_FAILED`,400,e.headers);case`unavailable`:return ft(30,e.headers);case`not_found`:return Y(e.headers)}}function Bt(e,t){return J(`Some answers need attention`,`FORM_INVALID`,400,t,{fields:e})}function Vt(e){let t=Math.ceil(e/6);return{maxAge:t,swr:e-t}}const Ht=[`defaultMaxAge`,`defaultStaleWhileRevalidate`,`maxAge`,`staleWhileRevalidate`];function Ut(e,t){if(e!==void 0&&(typeof e!=`number`||!Number.isInteger(e)||e<0))throw Error(`content-api cache: \`${t}.maxStaleSeconds\` must be a non-negative integer, received ${JSON.stringify(e)}. Use 0 for \`no-store\` if you need a published edit visible on the very next request.`)}function Wt(e,t){for(let n of Ht)if(n in e)throw Error(`content-api cache: \`${t}.${n}\` was removed (D036). Use \`maxStaleSeconds\` — ONE number naming the TOTAL staleness window in seconds. The old pair's real window was their SUM and nothing said so, which is the defect D036 exists to close: \`defaultMaxAge: 10\` bought a 310-second window, not a 10-second one. The max-age / stale-while-revalidate split is now derived, so what is emitted always sums to what you declared.`)}function Gt(e){if(e){Wt(e,`cache`),Ut(e.maxStaleSeconds,`cache`),et(e.tags);for(let[t,n]of Object.entries(e.entities??{})){if(!n)continue;let e=`cache.entities.${t}`;Wt(n,e),Ut(n.maxStaleSeconds,e)}}}function Kt(e,t){let n=t?.entities?.[e];return n?.cacheable===!1?0:n?.maxStaleSeconds??t?.maxStaleSeconds??360}function qt(e,t){let n=Kt(e,t);if(n===0)return{"Cache-Control":`no-store`};let{maxAge:r,swr:i}=Vt(n);return{"Cache-Control":`public, max-age=${r}, stale-while-revalidate=${i}`}}const Jt=[`Origin`];function Yt(e,t){let n=new Set,r=[];for(let i of[...e?.split(`,`)??[],...Jt,...t]){let e=i.trim();if(e===``)continue;let t=e.toLowerCase();n.has(t)||(n.add(t),r.push(e))}return r.join(`, `)}function X(e,t,n,r,i,a){let o=(n!==`identified`&&i.kind!==`undeclared`&&a?.uncacheable!==!0?qt(e,r):{"Cache-Control":`no-store`})[`Cache-Control`]??`no-store`,s={"Cache-Control":n===`site-keyed`?o.replace(/^public\b/,`private`):o};return{...t,...s,...s[`Cache-Control`]===`no-store`?{}:a?.headers(),Vary:Yt(t.Vary,i.kind===`declared`?i.headers:[])}}function Xt(e,t,n,r){let i=r?.uncacheable===!0?{"Cache-Control":`no-store`}:qt(e,n);return{...t,...i,...i[`Cache-Control`]===`no-store`?{}:r?.headers(),Vary:Yt(void 0,[])}}function Zt(e,t){return{...e,Vary:Yt(e.Vary,t.kind===`declared`?t.headers:[])}}function Qt(e,t){if(!t)return{};let n=e.headers.get(`Origin`);return n!==null&&t.allowedOrigins.includes(n)?{"Access-Control-Allow-Origin":n,"Access-Control-Allow-Methods":`GET, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Accept, Authorization`,"Access-Control-Max-Age":String(t.maxAge??3600),Vary:`Origin`}:{Vary:`Origin`}}function $t(e,t,n){let r={...Qt(e,t),...qt(`_preflight`,n)};return new Response(null,{status:204,headers:r})}var en=class extends Error{constructor(){super(`Service overloaded`),this.name=`ServiceOverloadedError`}},tn=class extends Error{constructor(){super(`Request deadline exceeded`),this.name=`RequestDeadlineError`}};function nn(e,t,n){if(e===void 0)return t;if(!Number.isInteger(e)||e<0)throw Error(`content-api limits: \`${n}\` must be a non-negative integer (got ${e})`);return e}function rn(e,t,n){if(e===void 0)return t;if(!Number.isInteger(e)||e<1)throw Error(`content-api limits: \`${n}\` must be a positive integer (got ${e})`);return e}function an(e){return{maxConcurrentRequests:rn(e?.maxConcurrentRequests,64,`maxConcurrentRequests`),maxQueuedRequests:nn(e?.maxQueuedRequests,128,`maxQueuedRequests`),requestTimeoutMs:rn(e?.requestTimeoutMs,1e4,`requestTimeoutMs`),anonymousTokensPerInstance:rn(e?.anonymousTokensPerInstance,120,`anonymousTokensPerInstance`),intervalMs:rn(e?.intervalMs,6e4,`intervalMs`),maxBudgetPerInstance:rn(e?.maxBudgetPerInstance,6e3,`maxBudgetPerInstance`)}}var on=class{semaphore;store;limits;getClientIp;constructor(e){this.getClientIp=e?.getClientIp,this.limits=an(e),this.semaphore=new re(this.limits.maxConcurrentRequests,this.limits.maxQueuedRequests),this.store=e?.store??new ne}async acquire(e){await this.semaphore.acquire(()=>new en,e)}release(){this.semaphore.release()}async runGuarded(e){return await A(e,this.limits.requestTimeoutMs,()=>new tn)}consumeFairness(e,t,n){let r=this.resolveKey(e,t);if(r)return{decision:this.store.consume(r.key,{tokens:this.budgetFor(t),intervalMs:this.limits.intervalMs},n),keyClass:r.keyClass}}budgetFor(e){let t=e.budgetPerInstance??this.limits.anonymousTokensPerInstance;return Math.min(t,this.limits.maxBudgetPerInstance)}resolveKey(e,t){if(t.principalId!==void 0)return{key:`principal:${t.principalId}`,keyClass:`principal`};let n=this.getClientIp?.(e);if(n!==void 0&&n!==``)return{key:`ip:${n}`,keyClass:`client-ip`}}};function sn(e){let t=[];for(let[n,r]of Object.entries(e.allFields))r.type!==`reference`||z(n,r)||t.push([n,r]);return t}function cn(e){return typeof e==`string`&&e.length>0}function ln(e,t){return t===`many`?Array.isArray(e)?e.filter(cn):[]:cn(e)?[e]:[]}async function un(e,t,n,r,i=0){if(t.length===0)return;let a=sn(e);if(a.length===0)return;let o=new Map,s=[];for(let c of t)for(let[t,l]of a){if(!Object.hasOwn(c,t))continue;let a=ln(c[t],l.cardinality),u=i===0&&n.has(t),d=r.reachableEntity(l.entity===`_self`?e.name:l.entity);if(!d||a.length===0){s.push({row:c,field:t,cardinality:l.cardinality,groupKey:null,ids:a});continue}let f=`${d.name}::${u?`full`:`projection`}`,p=o.get(f);p||(p={target:d,expand:u,ids:new Set},o.set(f,p));for(let e of a)p.ids.add(e);s.push({row:c,field:t,cardinality:l.cardinality,groupKey:f,ids:a})}let c=new Map;for(let[e,t]of o){let n=[...t.ids],a=r.budget.claim(t.expand?`populate`:`reference`,n.length),o=n.slice(0,a);if(o.length===0){c.set(e,new Map);continue}let s=l(t.target),u=m(t.target),d=u?r.templateDrawnTitle:void 0,f=t.expand||d!==void 0?void 0:u?[`id`]:dn([`id`,s]),p=await r.readRowsByIds(t.target,o,f),h=new Map;if(t.expand){for(let e of p){let t=e.id;cn(t)&&h.set(t,e)}await un(t.target,p,new Set,r,i+1),await r.afterExpand?.(t.target,p)}else{let e=await fn(t.target.name,p,r);for(let[n,r]of p.entries()){let i=r.id;if(!cn(i))continue;let a=u?await d?.(t.target,r)??null:r[s];h.set(i,{id:i,entityType:t.target.name,title:typeof a==`string`?a:null,href:e[n]??null})}}for(let e of h.keys())r.cacheTags?.addDocument(t.target.name,e);c.set(e,h)}for(let e of s){let t=e.groupKey===null?void 0:c.get(e.groupKey);if(e.cardinality===`many`){e.row[e.field]=e.ids.map(e=>t?.get(e)).filter(e=>e!==void 0);continue}let n=e.ids[0];e.row[e.field]=n===void 0?null:t?.get(n)??null}}function dn(e){return[...new Set(e)]}async function fn(e,t,n){let r=n.resolveEntityHref;return r?O(t,async t=>{let i=t.id;if(!cn(i))return null;try{return await r({entity:e,id:i,...n.locale!==void 0&&{locale:n.locale}})??null}catch(t){return n.logger?.debug({entity:e,id:i,err:t},`content-api: resolveEntityHref threw — reference resolves without an href`),null}}):t.map(()=>null)}const pn={referenceProjection:{fields:{id:`string`,entityType:`string`,title:`string`,href:`string`},nullableFields:[`title`,`href`],nullable:!0,arrayForCardinalityMany:!0},mediaProjection:{fields:{id:`string`,url:`string`,mimeType:`string`,width:`number`,height:`number`,alt:`string`,title:`string`,variants:`object`,sources:`object`,avifSources:`object`,focalPoint:`object`,blurDataUrl:`string`},nullableFields:[`mimeType`,`width`,`height`,`alt`,`title`,`blurDataUrl`],optionalFields:[`avifSources`],nullable:!0,arrayForCardinalityMany:!1}};function mn(e,t,n){let r={type:e.type};if(e.required&&(r.required=!0),e.translatable&&(r.translatable=!0),e.type===`select`&&(r.options=e.options),e.type===`blockTree`&&(r.selectable=!1),e.type===`media`&&(r.wire=`mediaProjection`),e.type===`reference`){r.cardinality=e.cardinality,r.wire=`referenceProjection`;let i=e.entity===`_self`?n:e.entity;t(i)&&(r.entity=i,r.populatable=!0)}return r}function hn(e,t){let n=e.allFields,r={},i=m(e);for(let[a,o]of Object.entries(n))z(a,o)||i&&a!==`id`||(r[a]=mn(o,t,e.name));let a=u(e);for(let e of a?.fields??[]){let t=r[e];t&&(t.searchable=!0)}return{name:e.name,pluralName:`${e.name}s`,kind:e.kind??`collection`,...i&&{drawnBy:`template`},fields:r}}const gn={type:`string`},_n={type:`string`},vn={type:`string`,maxLength:200,maxItems:5};function yn(e){let{maxLimit:t,maxOffset:n,hasResolution:r,hasMenus:i,hasChrome:a}=e,o=[{id:`list`,path:`/:entity`,data:`array`,entityKind:`collection`,params:{limit:{type:`number`,min:1,max:t,default:Math.min(20,t)},offset:{type:`number`,min:0,max:n,default:0},sort:{type:`string`},locale:gn,fields:_n,search:{type:`string`,maxLength:200,minLength:2},cursor:{type:`string`,maxLength:500},populate:vn,"filter[<field>]":{type:`string`}},meta:{total:{type:`number`,nullable:!0,suppressedBy:[`search`]},limit:{type:`number`},offset:{type:`number`},hasMore:{type:`boolean`},nextCursor:{type:`string`,optional:!0}}},{id:`singleton`,path:`/:entity`,data:`object`,entityKind:`singleton`,params:{locale:gn,fields:_n,populate:vn}},{id:`count`,path:`/:entity/count`,data:`object`,entityKind:`collection`,params:{locale:gn}},{id:`byId`,path:`/:entity/:id`,data:`object`,entityKind:`collection`,params:{locale:gn,fields:_n,populate:vn}},{id:`bySlug`,path:`/:entity/slug/:slug`,data:`object`,entityKind:`collection`,params:{locale:gn,fields:_n,populate:vn}}];return r&&o.push({id:`resolve`,path:`/_resolve`,data:`object`,params:{path:{type:`string`,required:!0,maxLength:pe},locale:{type:`string`,required:!0}}},{id:`paths`,path:`/_paths`,data:`array`,params:{locale:{type:`string`,required:!0},entity:{type:`string`,required:!0,maxLength:100},cursor:{type:`string`},limit:{type:`number`,min:1,max:t,default:Math.min(20,t)}},meta:{limit:{type:`number`},hasMore:{type:`boolean`},nextCursor:{type:`string`,optional:!0}}},{id:`alternates`,path:`/_alternates`,data:`array`,params:{entity:{type:`string`,required:!0,maxLength:100},id:{type:`string`,required:!0}}}),o.push({id:`site`,path:`/_site`,data:`object`,params:{}}),o.push({id:`search`,path:`/_search`,data:`array`,params:{q:{type:`string`,required:!0,minLength:2,maxLength:200},types:{type:`string`,maxLength:808},limit:{type:`number`,default:20,min:1,max:50},locale:{type:`string`}},meta:{limit:{type:`number`}}}),i&&o.push({id:`menu`,path:`/_menu`,data:`object`,params:{handle:{type:`string`,required:!0,maxLength:128},locale:{type:`string`,required:!0},currentPath:{type:`string`,maxLength:pe}}}),a&&o.push({id:`chrome`,path:`/_chrome`,data:`object`,params:{locale:{type:`string`,required:!0},entity:{type:`string`,maxLength:100},id:{type:`string`}}}),o}function bn(e,t){if(!e.enabled)return null;let n=t?`${G}:{site}`:G;return{header:e.header,separator:e.separator,document:`${n}:{entity}:{id}`,collection:`${n}:{entity}`,sharedSite:t?`_`:null,maxTagLength:128,maxTagsPerResponse:128,maxHeaderBytes:Ke,uncovered:[`menuTargets`,`crossEntityPathChanges`,`mediaVariantStyles`,`outOfBandPathChanges`]}}function xn(e){let{entities:t,checkPermission:n,version:r}=e,i={maxResolutionsPerDocument:e.maxResolutionsPerDocument,anonymousRequestsPerInstance:e.limits.anonymousTokensPerInstance,rateLimitWindowMs:e.limits.intervalMs,maxRequestsPerInstance:e.limits.maxBudgetPerInstance,maxConcurrentRequests:e.limits.maxConcurrentRequests,requestTimeoutMs:e.limits.requestTimeoutMs},a=t.filter(e=>n(e.name)),o=new Set(a.map(e=>e.name)),s=e=>o.has(e);return{version:r,surface:yn(e),envelopes:{dataKey:`data`,metaKey:`meta`,errorKey:`error`,errorCodes:st},limits:i,projections:pn,cacheTags:bn(e.cacheTags,e.siteScopedTags===!0),entities:a.map(e=>hn(e,s))}}const Sn=`public`,Cn=new Set;function wn(e){return typeof e==`string`&&e!==``}function Tn(e){return Array.isArray(e)}const En=/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/;function Dn(e){let t=e.credentialHeaders;if(t!==void 0){if(!Tn(t))throw Error(`content-api: \`credentialHeaders\` must be an array of HTTP header names, received ${JSON.stringify(t)}.`);for(let e of t)if(!wn(e)||e===`*`||!En.test(e))throw Error(`content-api: \`credentialHeaders\` entry ${JSON.stringify(e)} is not a valid HTTP header name. Each entry is emitted verbatim in \`Vary\`, so it must be a bare field-name token (\`Cookie\`, \`Authorization\`, \`X-Preview-Token\`). \`*\` is refused: it means "never reuse this response", which is \`Cache-Control: no-store\` spelled obscurely — omit the option instead, which fails closed to exactly that.`)}if(!e.authenticate){if(t!==void 0&&t.length>0)throw Error("content-api: `credentialHeaders` was declared without an `authenticate` hook. This package parses no credential itself, so nothing reads those headers and listing them in `Vary` can only fragment a shared cache. Remove the option, or wire the `authenticate` hook it describes.");return{kind:`none`}}return t===void 0||t.length===0?{kind:`undeclared`}:{kind:`declared`,headers:t}}const On=k.object({path:k.string().min(1).max(pe),locale:k.string().regex(g)}).strict(),kn=k.object({locale:k.string().regex(g),entity:k.string().min(1).max(100),cursor:k.string().refine(e=>Se(e),`Invalid cursor`).optional(),limit:k.coerce.number().int().min(1).max(100).default(20)}).strict(),An=k.object({entity:k.string().min(1).max(100),id:k.string().refine(e=>Se(e),`Invalid id`)}).strict(),jn=[`header`,`footer`],Mn=k.object({locale:k.string().regex(g),entity:k.string().min(1).max(100).optional(),id:k.string().refine(e=>Se(e),`Invalid id`).optional()}).strict().refine(e=>e.entity===void 0==(e.id===void 0),`Both ?entity= and ?id= are required to name a document, or neither.`),Nn=k.object({}).strict();function Pn(e){return e instanceof n||e instanceof Error&&e.name===`SiteRequiredError`}const Fn=k.object({handle:k.string().min(1).max(128),locale:k.string().regex(g),currentPath:k.string().min(1).max(pe).optional()}).strict(),In=new Set([`_schema`,`_site`,`_resolve`,`_paths`,`_alternates`,`_menu`,`_chrome`,`_search`,`_forms`]),Ln=`v1`,Rn=/^v\d+$/;function zn(e){let t=new Map;for(let n of e){let e=`${n.name}s`;if(In.has(n.name)||In.has(e))throw Error(`@murumets-ee/content-api: entity name "${n.name}" collides with a reserved route segment (${[...In].join(`, `)}). Rename the entity — its API surface would otherwise be permanently unreachable, shadowed by the special dispatch that runs before entity-whitelist resolution.`);if(Rn.test(n.name)||Rn.test(e))throw Error(`@murumets-ee/content-api: entity name "${n.name}" is a reserved API-version segment. Every route is served under a version prefix (this instance mounts /v1/), and the prefix is matched as a PATTERN ("v" followed by digits) so that a future /v2/ can never be shadowed by an entity added in the meantime. Rename the entity.`);if(n.scope!==void 0&&n.scope!==`global`)throw Error(`@murumets-ee/content-api: entity "${n.name}" declares scope "${n.scope}", which this surface cannot serve. The public read path resolves no scope for a caller, so QueryClient would apply NO scope filter and return every tenant's rows to every caller. Remove it from the content-api whitelist, or serve it through a surface that establishes a scope in the request context.`);t.set(n.name,n),t.set(e,n)}return t}function Bn(e,n){let r=e[t];if(!r)throw Error(`site-bound '${n}' translations have no ${t} column`);return r}function Z(e){let t=j.get(e);if(t)return{table:t,cols:N(t)}}const Vn=new Set([`text`,`richtext`,`slug`,`select`]);function Hn(e,t,n){let r=u(e);if(!r)return;let i=t.trim();if(i.length===0)return;let o=Z(e.name);if(!o)return;let{cols:s}=o,l=[],d=`%${v(i)}%`,f=e.allFields,p=r.fields.filter(e=>{let t=Object.hasOwn(f,e)?f[e]:void 0;return t!==void 0&&Vn.has(t.type)&&!z(e,t)}),m=r.fts?.fields.some(e=>z(e,f[e]))??!1,h=Cn;if(r.fts&&!m){let e=s._search_tsv;if(e){let t=r.fts.language??`simple`;l.push(I`${e} @@ websearch_to_tsquery(${t}, ${i})`),h=new Set(r.fts.fields)}}for(let e of p){if(h.has(e))continue;let t=s[e];t&&l.push(le(t,d))}let g=c(e.allFields,p),_=s.id;if(n!==void 0&&g.length>0&&_){let t=j.get(`${e.name}_translations`);if(t){let e=a({idColumn:_,translationsTable:t,fields:g,locale:n,buildCondition:e=>le(e,d)});e&&l.push(e)}}if(l.length===0)return;let y=l[0];if(y)return l.length===1?y:de(y,...l.slice(1))}function Un(e,t,n){let r=Z(e.name);if(!r)return[];let{cols:i}=r,a=e.allFields,o=t.trim(),s=`%${v(o)}%`,c=[],d=l(e),f=Object.hasOwn(a,d)?a[d]:void 0,p,m=i[d];if(m&&f!==void 0&&Vn.has(f.type)&&!z(d,f)){let t=n!==void 0&&f.translatable===!0?Z(`${e.name}_translations`):void 0,r=t?.cols[d],a=t?.cols.entityId,o=t?.cols.locale,c=i.id;p=t&&r&&a&&o&&c&&n!==void 0?I`COALESCE((SELECT ${r} FROM ${t.table} WHERE ${a} = ${c} AND ${o} = ${n} LIMIT 1), ${m}) ILIKE ${s}`:le(m,s)}p&&c.push(I`CASE WHEN ${p} THEN 0 ELSE 1 END`);let h=u(e),g=h?.fts?.fields.some(e=>z(e,a[e]))??!1,_=i._search_tsv;if(h?.fts&&!g&&_){let e=h.fts.language??`simple`;c.push(ce(I`ts_rank(${_}, websearch_to_tsquery(${e}, ${o}))`))}let y=i.updatedAt;y&&c.push(ce(y));let b=i.id;return b&&c.push(se(b)),c}function Wn(e,t,n){let r=e.name;if(!t)return{orderBy:void 0};let i=t.startsWith(`-`),a=i?t.slice(1):t,o={orderBy:void 0,dropped:t};if(!Object.hasOwn(n,a))return o;let s=n[a];if(!s||s.type===`blockTree`||z(a,s)&&!p(e,a))return o;let c=Z(r);if(!c)return o;let l=c.cols[a];return l?{orderBy:i?ce(l):se(l),field:a}:o}function Gn(e,t,n){let r=[],i=[],a=Z(e);if(!a)return{conditions:r,dropped:i};let{cols:o}=a;for(let[e,a]of t.searchParams.entries()){let t=e.match(_e);if(!t)continue;let s=t[1];if(s===void 0)continue;if(!Object.hasOwn(n,s)){i.push(s);continue}let c=n[s];if(!c||c.type===`blockTree`){i.push(s);continue}if(z(s,c)){i.push(s);continue}let l=o[s];if(!l){i.push(s);continue}let u=Ce(c,a);if(u===null){i.push(s);continue}if(c.type===`date`&&typeof u==`string`){if(u.startsWith(`gte:`)){r.push(P(l,u.slice(4)));continue}if(u.startsWith(`lte:`)){r.push(ue(l,u.slice(4)));continue}}r.push(M(l,u))}return{conditions:r,dropped:i}}function Kn(e,t,n,r,i=!0){if(!(!i||t<=n))return J(`?${e}=${t} exceeds the maximum of ${n}.${e===`offset`?` Use ?cursor= for deep pagination.`:``}`,`VALIDATION_ERROR`,400,r)}function qn(e,t,n){return n?e:Math.min(e,t)}function Jn(e,t,{allowZero:n=!1}={}){if(t===void 0)return;let r=+!n;if(!Number.isInteger(t)||t<r)throw Error(`content-api: \`${e}\` must be an integer >= ${r}, received ${String(t)}. A ceiling below that does not tighten the bound, it removes it: the limit reaches the query layer falsy, no LIMIT clause is emitted, and the whole table is returned on a public route. If this came from an environment variable, it is probably unset.`)}function Q(e){return e.length<=256?e:`${e.slice(0,256)}…[truncated]`}const Yn=new WeakMap,Xn=new WeakMap;function Zn(e){if(e.requestId)try{Yn.set(e,y().logger.child({requestId:e.requestId,...e.user?.id!==void 0&&{principalId:e.user.id}}))}catch{}}async function Qn(e,t){let n=b();if(!n)return{locales:[]};let r=e??await E(n).catch(()=>void 0);if(r===void 0)return{locales:[]};let i=await w(n,r);if(!i)return{locales:[]};let a=e=>e!==void 0&&(i.locales.length===0||i.locales.includes(e)),o=n.config.sites?.multiple===!0?i.defaultLocale:void 0,s=a(o)?o:a(t)?t:i.locales[0];return{locales:i.locales,...s!==void 0&&{defaultLocale:s}}}function $(){let e=x();return(e?Yn.get(e):void 0)??y().logger}function $n(t){let{entities:n,defaultLocale:r,publicRole:i=`public`,cors:a,cache:c,onError:u,resolution:d,menus:g,chrome:v,forms:k,site:ne}=t,re=new Map;for(let[e,n]of Object.entries(t.siteForHost??{})){if(!h(n))throw Error(`content-api: \`siteForHost['${e}']\` is ${JSON.stringify(n)}, which is not a site handle.`);re.set(e.trim().toLowerCase(),n)}function ie(e){if(!e.multiSite)return;let t=b()?.entities;return n=>{let r=t?.get(n);return r!==void 0&&!f(r)?`_`:e.site??`_`}}let A=()=>{let e=x();return(e?Xn.get(e):void 0)??r};Jn(`maxLimit`,t.maxLimit),Jn(`maxOffset`,t.maxOffset,{allowZero:!0}),Gt(c);let j=tt(c?.tags);if(!wn(i))throw Error(`content-api: \`publicRole\` must be a non-empty string, received ${JSON.stringify(i)}. An empty public role matches no permission yet is not the anonymous role either, so every unauthenticated request reaches the read path with no groups and fails as a 500. If this came from an environment variable, it is probably unset — omit the option to get "public".`);let se=Math.min(t.maxLimit??100,100),ce=Math.min(t.maxOffset??1e3,1e3),N=Dn(t),P=new on(t.limits),le=new jt(t.search,t.search?.getClientIp??t.limits?.getClientIp);zn(n);let ue;function I(){if(ue)return ue;let e=b(),t=n;if(e){t=[];for(let r of n){let n=e.entities.get(r.name);if(n===void 0){e.logger.error(`content-api: "${r.name}" is in createContentApiHandler({ entities }) but the app does not register an entity of that name — it is NOT served. Register it through lumi.config (entities or a plugin) or remove it from the whitelist.`);continue}t.push(n)}}let r={list:t,map:zn(t)};return e&&(ue=r),r}if(Object.hasOwn(t,`exposeInternalFields`))throw Error("content-api: `exposeInternalFields` has been removed (plan/api D024). Its only sanctioned use was publishing `_overrides`, which D011 replaced by composing site chrome SERVER-side — so the field no longer needs to reach the wire, and no other internal field was ever safe to list (`_workflowStatus` and `_workflowAssignee` describe an editorial process and name a user; `_version`/`_versionedAt` expose revision cadence). Fetch composed chrome from `GET /_chrome` instead. Remove the option: it is refused rather than ignored, because silently dropping a field you configured is exactly the failure this package throws at construction to prevent.");let fe=new Set(g?.handles??[]),L=ke(t.maxResolutionsPerDocument),pe=new e(5e3),_e=null,ve=0;async function ye(){let e=Date.now();return(!_e||e-ve>3e4)&&(_e=await t.loadPermissions(),ve=e),_e}function be(){_e=null,ve=0}function xe(){return{id:Sn,role:i,hasIdentity:!1}}function Ce(e){try{$().warn({err:e},"content-api: `authenticate` hook threw — serving the anonymous principal")}catch{console.warn("[content-api] `authenticate` hook threw:",e)}}async function Ee(e){if(!t.authenticate)return xe();let n;try{n=await t.authenticate(e)}catch(e){return Ce(e),xe()}if(!n||!wn(n.role)||n.id!==void 0&&!wn(n.id)||n.name!==void 0&&typeof n.name!=`string`||n.email!==void 0&&typeof n.email!=`string`||n.site!==void 0&&!(typeof n.site==`string`&&h(n.site)))return xe();let r=n.rateBudgetPerInstance!==void 0&&Number.isSafeInteger(n.rateBudgetPerInstance)&&n.rateBudgetPerInstance>=1;return{id:n.id??Sn,hasIdentity:n.id!==void 0,role:n.role,...n.name!==void 0&&{name:n.name},...n.email!==void 0&&{email:n.email},...r&&{rateBudgetPerInstance:n.rateBudgetPerInstance},...n.site!==void 0&&{site:n.site}}}function De(e){if(re.size===0)return;let t=(e.headers.get(`host`)??new URL(e.url).host).trim().toLowerCase();return re.get(t)}async function Ae(e,t){let n=S();if(t.site!==void 0&&n!==void 0&&n!==t.site)return K({credentialSite:t.site,mountSite:n},`content-api: a credential bound to one site was presented to a mount running as another`),null;let r=t.site??n??De(e),i=b();if(!i)return{...r!==void 0&&{site:r},multiSite:!1};let a=i.config.sites?.multiple===!0,o=r??await E(i).catch(()=>void 0);if(o===void 0)return{multiSite:a};let s=await w(i,o);return r!==void 0&&(s===void 0||s.status!==`active`)?null:{...r!==void 0&&{site:r},...s!==void 0&&{record:s},multiSite:a}}async function B(e){let t=b(),n=t?.config.sites?.multiple===!0;if(!t||!n)return a;if(!e.headers.has(`Origin`))return a??{allowedOrigins:[]};try{let e=await C(t);return e.truncated&&at(`site-origin-index-truncated`,{listed:e.byOrigin.size},`content-api: the site registry holds more active sites than the origin index reads — some sites’ CORS preflights will be refused`),{allowedOrigins:[...new Set([...a?.allowedOrigins??[],...e.byOrigin.keys()])],...a?.maxAge!==void 0&&{maxAge:a.maxAge}}}catch(e){return K({err:e},`content-api: could not read site origins for CORS`),a}}function V(e){return e.hasIdentity||e.role!==i?`identified`:e.site===void 0?`anonymous`:`site-keyed`}function H(e,t,n){return e(t,n,`view`)}function U(e){let t=y();return new ae({entity:e,db:t.db.readOnly,logger:$().child({entity:e.name}),countCache:pe,contextResolver:()=>{let e=x();if(!(!e?.user||!e?.checker))return{user:e.user,checker:e.checker,...e.scope!==void 0&&{scope:e.scope},...te(e,t)}}})}function W(e,n,i,a){let o={budget:Oe(L),cacheTags:a,resolveMedia:t.resolveMedia,resolveBlocks:t.resolveBlocks,siteOf:e=>T(e),afterExpand:async(e,t)=>{if(m(e)){for(let n of t)await ot(e,n,Fe(o),!1);return}await mt(e,t,o),await Ue(e,t,o)},locale:i,reachableEntity:t=>{let r=I().map.get(t);if(!(!r||r.name!==t))return H(e,n,r.name)?r:void 0},canReadEntity:t=>{let r=I().map.get(t);return r!==void 0&&r.name===t&&H(e,n,t)},collectionAllowance:Pe(12),templateDrawnTitle:async(e,n)=>{let s=t.detailTemplates,c=i??r;if(!s||c===void 0)return null;try{let t=await s.publicRow({entity:e.name,row:n,locale:c}),r=typeof t.title==`string`?t.title.trim():``;return r===``?null:r.slice(0,2e3)}catch(t){return o.logger?.warn({entity:e.name,err:t},`content-api: detail-template provider failed to project a reference title`),a.markUncacheable(),null}},readRowsByIds:async(e,t,n)=>{let a=Z(e.name)?.cols.id;return!a||t.length===0||L===0?[]:await U(e).findMany({where:F(a,[...t]),limit:Math.min(t.length,L),...n!==void 0&&{select:[...n]},...i!==void 0&&{locale:i},defaultLocale:r})},resolveEntityHref:t.resolveEntityHref,logger:je()};return o}function je(){try{return $()}catch{return}}function Me(e,t,n){let r=e.collectionAllowance?.refusedCount()??0;if(r>0)try{$().warn({entity:t,path:Q(n),cap:12,refused:r},`content-api: per-response collection cap reached — the collection blocks past it rendered empty`)}catch{console.warn(`[content-api] collection cap reached for`,t,Q(n))}if(e.budget.hasDrops)try{$().warn({entity:t,path:Q(n),ceiling:e.budget.ceiling,resolved:e.budget.granted,dropped:e.budget.dropSummary()},`content-api: per-document resolution budget exhausted — response rendered with unresolved targets`)}catch{console.warn(`[content-api] resolution budget exhausted for`,t,Q(n))}}function Ne(e,t,n,r){let i=Te(e,n);return i.requested>5?{response:J(`?populate= names ${i.requested} fields, which exceeds the maximum of 5.`,`VALIDATION_ERROR`,400,r)}:(i.dropped.length>0&&je()?.debug({entity:t.name,droppedPopulate:i.dropped},`content-api: rejected ?populate= fields (unknown, internal, or not a reference)`),{fields:new Set(i.fields)})}function Fe(e){return{...e,detailTemplates:t.detailTemplates,defaultLocale:r}}async function Ie(e,t,n,r,i){await un(e,t,n,r),await mt(e,t,r),await Ue(e,t,r),Me(r,e.name,i)}async function Le(e,t,n,i,a,l){let u=new URL(e.url),d=me.safeParse(R(u,{allowFilters:!0}));if(!d.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,a);let{limit:f,offset:m,sort:h,locale:g,fields:_,search:v,cursor:y,populate:b}=d.data,x=u.searchParams.has(`limit`),S=Kn(`limit`,f,se,a,x);if(S)return S;let C=Kn(`offset`,m,ce,a);if(C)return C;let w=qn(f,se,x),T=t.allFields,E=Ne(b,t,T,a);if(`response`in E)return E.response;let D;if(y){let e=o(y);if(!e)return J(`Invalid cursor`,`VALIDATION_ERROR`,400,a);if(!Object.hasOwn(T,e.field)&&e.field!==`id`||e.field!==`id`&&z(e.field,T[e.field]))return J(`Invalid cursor field`,`VALIDATION_ERROR`,400,a);D=e}let O=[],ee=!1;if(v){let e=Hn(t,v,g??A());e&&(O.push(e),ee=!0)}let te=Gn(t.name,u,T);O.push(...te.conditions);let k=Wn(t,h,T),ne=k.orderBy;if(D!==void 0&&k.field!==void 0&&p(t,k.field))return J(`Invalid cursor for this sort`,`VALIDATION_ERROR`,400,a);let re=we(_,T);if(te.dropped.length>0||k.dropped!==void 0){let e=[...new Set(te.dropped)],n=e.slice(0,20).map(Q);$().info({entity:t.name,...te.dropped.length>0&&{droppedFilters:n,...e.length>n.length&&{droppedFiltersOmitted:e.length-n.length}},...k.dropped!==void 0&&{droppedSort:Q(k.dropped)}},`content-api: rejected query params (unknown, internal, or invalid)`)}let ie=U(t),j=g??A(),ae=ee,M={where:O.length>0?oe(...O):void 0,limit:ae?w+1:w,offset:m,orderBy:ne,select:re,locale:j,defaultLocale:r,cursor:D},[P,le]=await Promise.all([ie.findMany(M),ae?Promise.resolve(null):ie.count({where:O.length>0?oe(...O):void 0,locale:j})]),F=ae&&P.length>w?P.slice(0,w):P,ue=ae?P.length>w:m+w<(le??0),de;if(F.length>0&&F.length===w){let e=F[F.length-1],t=D?.field??k.field,n=D?.direction??(h?.startsWith(`-`)?`desc`:`asc`);t&&e[t]!==void 0&&(de=s(e,t,n))}l.addCollection(t.name);for(let e of F)l.addDocument(t.name,e.id);let I=W(i,n.role,j,l);return await Ie(t,F,E.fields,I,u.pathname),q({data:F,meta:{total:le,limit:w,offset:m,hasMore:ue,nextCursor:de}},200,X(t.name,a,V(n),c,N,l))}async function Re(e,t,n,r,i){let a=new URL(e.url),o=ge.safeParse(R(a));if(!o.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,r);let s=await U(t).count({locale:o.data.locale??A()});return i.addCollection(t.name),q({data:{count:s}},200,X(t.name,r,V(n),c,N,i))}async function ze(e,t,n,i,a,o,s){if(!Se(n))return Y(o);let l=new URL(e.url),u=he.safeParse(R(l));if(!u.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,o);let{locale:d,fields:f,populate:p,page:h}=u.data,g=t.allFields,_=m(t)?void 0:we(f,g),v=d??A(),y=Ne(p,t,g,o);if(`response`in y)return y.response;let b=await U(t).findById(n,{..._!==void 0&&{select:_},...v!==void 0&&{locale:v},defaultLocale:r});if(!b)return Y(o);s.addDocument(t.name,n);let x={...W(a,i.role,v,s),...h!==void 0&&h>1&&{page:h}};return m(t)?(await ot(t,b,Fe(x),!0),Me(x,t.name,l.pathname)):await Ie(t,[b],y.fields,x,l.pathname),q({data:b},200,X(t.name,o,V(i),c,N,s))}async function Be(e,t,n,i,a,o,s){let l=new URL(e.url),u=he.safeParse(R(l));if(!u.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,o);let d=t.allFields;if(!d.slug)return Y(o);let{locale:f,fields:p,populate:m,page:h}=u.data,g=we(p,d),_=f??A(),v=Ne(m,t,d,o);if(`response`in v)return v.response;let b=Z(t.name);if(!b)return Y(o);let x=b.cols.slug,S=b.cols.id;if(!x||!S)return Y(o);let C=U(t),w=d.slug,E=M(x,n);if(w.translatable&&_){let e=Z(`${t.name}_translations`);if(e){let r=e.cols.slug,i=e.cols.locale,a=e.cols.entityId;if(r&&i&&a){let o=y(),s=await T(t,o),c=oe(M(r,n),M(i,_)),l=await o.db.readOnly.select({entityId:a}).from(e.table).where(s===void 0?c:oe(c,M(Bn(e.cols,t.name),s)));l.length>0&&(E=de(F(S,l.map(e=>e.entityId)),M(x,n))??M(x,n))}}}let D=await C.findMany({where:E,limit:1,select:g,locale:_,defaultLocale:r});if(D.length===0)return Y(o);s.addCollection(t.name),s.addDocument(t.name,D[0]?.id);let O={...W(a,i.role,_,s),...h!==void 0&&h>1&&{page:h}};return await Ie(t,D,v.fields,O,l.pathname),q({data:D[0]},200,X(t.name,o,V(i),c,N,s))}async function Ve(e,t,n,i,a,o){let s=new URL(e.url),l=he.safeParse(R(s));if(!l.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,a);let{locale:u,fields:d,populate:f,page:p}=l.data,m=t.allFields,h=we(d,m),g=u??A(),_=Ne(f,t,m,a);if(`response`in _)return _.response;let v=(await U(t).findMany({limit:1,select:h,locale:g,defaultLocale:r}))[0];if(!v)return Y(a);o.addCollection(t.name),o.addDocument(t.name,v.id);let y={...W(i,n.role,g,o),...p!==void 0&&p>1&&{page:p}};return await Ie(t,[v],_.fields,y,s.pathname),q({data:v},200,X(t.name,a,V(n),c,N,o))}function G(e){return I().map.get(e)??I().map.get(e.endsWith(`s`)?e.slice(0,-1):e)}function We(e,t){if(process.env.NODE_ENV!==`development`)return;let n=JSON.stringify(e.slice(0,100)),r=t===void 0?`${n} is not in the content-api whitelist — add it to createContentApiHandler({ entities: [...] }) in your content route.`:`"${t.name}" is whitelisted but the requesting role lacks 'view' — grant it in the Permission Matrix, or seed it. Note that entity.access.view is advisory metadata the firewall never reads, so a restrictive value there is not the cause.`;console.warn(`[content-api] 404 for ${n}: ${r} (Both refusals are 404 by design — this line is the server-side disambiguation, and the response is unchanged.)`)}async function Ge(e,t,n,r,i){if(!d)return Y(r);let a=new URL(e.url),o=On.safeParse(R(a));if(!o.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,r);let{path:s,locale:l}=o.data,u=await d.resolvePath(s,l);if(u.kind===`none`)return Y(r);if(u.kind===`redirect`)return q({data:u},200,{...r,"Cache-Control":`no-store`});let f=G(u.entityType);return!f||!H(n,t.role,f.name)?(We(u.entityType,f),Y(r)):(i.addCollection(f.name),i.addDocument(f.name,u.id),q({data:u},200,X(f.name,r,V(t),c,N,i)))}async function qe(e,t,n,r,i){if(!d)return Y(r);let a=new URL(e.url),o=kn.safeParse(R(a));if(!o.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,r);let{locale:s,entity:l,cursor:u,limit:f}=o.data,p=a.searchParams.has(`limit`),m=Kn(`limit`,f,se,r,p);if(m)return m;let h=qn(f,se,p),g=G(l);if(!g||!H(n,t.role,g.name))return We(l,g),Y(r);let _=d.enumeratePaths({locale:s,entityType:g.name,...u!==void 0&&{afterDocumentId:u}}),v=[];for await(let e of _)if(v.push(e),v.length===h)break;let y=v.length===h,b=y?v[v.length-1]?.id:void 0;i.addCollection(g.name);for(let e of v)i.addDocument(g.name,e.id);return q({data:v,meta:{limit:h,hasMore:y,nextCursor:b}},200,X(g.name,r,V(t),c,N,i))}async function Je(e,t,n,r,i){if(!d)return Y(r);let a=new URL(e.url),o=An.safeParse(R(a));if(!o.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,r);let{entity:s,id:l}=o.data,u=G(s);if(!u||!H(n,t.role,u.name))return We(s,u),Y(r);let f=x()?.availableLocales,p=await d.getAlternates(u.name,l),m=f?p.filter(e=>f.includes(e.locale)):p;return i.addCollection(u.name),i.addDocument(u.name,l),q({data:m},200,X(u.name,r,V(t),c,N,i))}async function Ye(e,t,n,r){if(!g)return Y(n);let i=new URL(e.url),a=Fn.safeParse(R(i));if(!a.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,n);let{handle:o,locale:s,currentPath:l}=a.data;if(!fe.has(o))return Y(n);let u=await g.getMenu(o,{locale:s,...l!==void 0&&{currentPath:l}});return u?(r.addDocument(`_menu`,o),q({data:u},200,t.site===void 0?Xt(`_menu`,n,c,r):X(`_menu`,n,V(t),c,N,r))):Y(n)}async function Xe(e,t,n,r,i,a){if(!Nn.safeParse(R(new URL(e.url))).success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,i);let o=n.record;if(!o)return Y(i);let s=await ne?.getI18n(o.handle);if((s?.locales??o.locales).length===0)return at(`site-i18n-unwired:${o.handle}`,{site:o.handle},"content-api: GET /_site cannot answer — this site serves every enabled locale and the mount wires no `site.getI18n` to say which those are. Wire it (see the content route the admin app ships), or give the site an explicit locale list."),Y(i);let l=s?.locales??o.locales,u=s?.defaultLocale??r.defaultLocale??l[0];if(u===void 0)return Y(i);let d={handle:o.handle,name:o.name,locales:l.length>0?[...l]:[u],defaultLocale:u,routingStrategy:s?.routingStrategy??o.routingStrategy??`no-prefix-default`,origins:[...o.origins]};return a.addDocument(`_site`,o.handle),q({data:d},200,X(`_site`,i,V(t),c,N,a))}async function Ze(e,n,i,a,o,s){let u=le.consume(e,{principalId:n.hasIdentity?n.id:void 0,site:n.site});if(u&&!u.decision.allowed)return K({limit:`search`,keyClass:u.keyClass},`content-api: caller exceeded its visitor-search budget`),dt(u.decision.retryAfterSeconds,o);let d=new URL(e.url),f=_t.safeParse(R(d));if(!f.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,o);let{q:p,types:m,limit:h,locale:g}=f.data,_=Kn(`limit`,h,50,o);if(_)return _;let v=yt(a.record?.searchTypes??[],m);if(v===null||v.length===0)return Y(o);let y=[];for(let e of v){let t=I().map.get(e);if(t!==void 0&&t.name===e&&H(i,n.role,e)&&vt(t)){y.push(t);continue}if(We(e,t),m!==void 0)return Y(o);at(`search-type:${a.site??``}:${e}`,{site:a.site,type:e},`content-api: a type in the site's searchTypes cannot be searched by this caller — it is skipped`)}if(y.length===0)return Y(o);let b=g??A(),x=[];for(let e of y){s.addCollection(e.name);let t=Hn(e,p,b);if(!t)continue;let n=await U(e).findMany({where:t,limit:h,orderBy:Un(e,p,b),locale:b,defaultLocale:r}),i=l(e),a=Object.hasOwn(e.allFields,i)?e.allFields[i]:void 0,o=a!==void 0&&Vn.has(a.type),c=[];for(let t of n){let n=t.id;if(typeof n!=`string`)continue;let{title:r,summary:a}=Et(e,t,i),s=t[i];c.push({hit:{entity:e,row:t,id:n,title:r,summary:a},titleHit:o&&typeof s==`string`&&Ot(s,p)})}c.length>0&&x.push({hits:c})}let S=Dt(x,h),C=W(i,n.role,b,s);for(let e of S)s.addDocument(e.entity.name,e.id);let w=new Map;for(let e of y){let t=S.filter(t=>t.entity===e);if(t.length===0)continue;let n=bt(e);if(n===null)continue;let r=t.map(e=>({id:e.id,[n]:e.row[n]}));await mt(e,r,C),t.forEach((e,t)=>{w.set(e,r[t]?.[n]??null)})}let T=t.resolveEntityHref,E=await O(S,async e=>{if(!T)return null;try{return await T({entity:e.entity.name,id:e.id,...b!==void 0&&{locale:b}})??null}catch(t){return $().debug({entity:e.entity.name,id:e.id,err:t},`content-api: resolveEntityHref threw — search result served without a path`),null}});return Me(C,`_search`,d.pathname),q({data:S.map((e,t)=>{let n=w.get(e);return{type:e.entity.name,typeLabel:St(e.entity),id:e.id,title:e.title,summary:e.summary,image:xt(n)?n:null,path:E[t]??null}}),meta:{limit:h}},200,X(`_search`,o,V(n),c,N,s))}async function Qe(e,n,r,i,a){if(!v)return Y(i);let o=new URL(e.url),s=Mn.safeParse(R(o));if(!s.success)return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,i);let{locale:l,entity:u,id:d}=s.data;if(!H(r,n.role,v.entity))return Y(i);let f;if(u!==void 0&&d!==void 0){let e=G(u);e&&H(r,n.role,e.name)?f={entityType:e.name,id:d}:je()?.debug({entity:u,locale:l},`content-api: _chrome document is unreachable for this caller — serving the site default`)}a.addCollection(v.entity),f!==void 0&&a.addDocument(f.entityType,f.id);let p=W(r,n.role,l,a),m=await v.getChrome({locale:l,...f!==void 0&&{document:f},budget:p.budget}),h=e=>e&&typeof e==`object`?{blocks:Array.isArray(e.blocks)?e.blocks:[],overridden:e.overridden===!0}:null,g=async(e,n)=>{if(n===null||!t.resolveBlocks||n.blocks.length===0)return n;let r=await He(t.resolveBlocks,n.blocks,{locale:l,budget:p.budget,entity:v.entity,field:e,...p.canReadEntity!==void 0&&{canReadEntity:p.canReadEntity},...p.collectionAllowance!==void 0&&{claimCollection:p.collectionAllowance.claim}});r.failure===`threw`?je()?.warn({entity:v.entity,region:e,err:r.error},`content-api: block resolver threw — this chrome region is not served as stored; it was re-resolved with an exhausted budget, so its media refs and link hrefs are stripped rather than carrying the urls recorded when an editor picked them`):r.failure===`malformed`&&je()?.warn({entity:v.entity,region:e},`content-api: block resolver returned a value that is not a ResolvedBlockTree — this chrome region is not served as stored; it was re-resolved with an exhausted budget, so its media refs and link hrefs are stripped rather than carrying the urls recorded when an editor picked them`),r.retryFailure!==void 0&&(a.markUncacheable(),je()?.warn({entity:v.entity,region:e,err:r.error},`content-api: block resolver failed TWICE, including on the in-memory retry — serving this chrome region EMPTY, so whatever it held is missing from every page render. Serving the stored region instead would put the media urls recorded when an editor picked them, which may be signed, on a cacheable anonymous response`));let i=r.envelope;if(i.refs!==void 0)for(let e of i.refs)a.addDocument(e.entity,e.id);if(i.collections!==void 0)for(let e of Object.values(i.collections))e.entity!==null&&a.addCollection(e.entity);return{blocks:[...i.blocks],overridden:n.overridden,resolved:i.resolved,links:i.links,...i.unresolved!==void 0&&i.unresolved.length>0&&{unresolved:i.unresolved},...i.refs!==void 0&&i.refs.length>0&&{refs:i.refs},...i.collections!==void 0&&{collections:i.collections},...i.live!==void 0&&{live:i.live},...i.currency!==void 0&&{currency:i.currency}}},_={};for(let e of jn)_[e]=await g(e,h(m?.[e]));let y={header:_.header??null,footer:_.footer??null};return Me(p,v.entity,o.pathname),q({data:y},200,X(v.entity,i,V(n),c,N,a))}async function $e(e,t){let n=D(e),r={},i=S(),a={requestId:n,...i!==void 0&&{site:i}};return Zn(a),await ee(a,async()=>{let i=await ct(e,t,n,r);return et(i,n),nt(i,e,n,r),i})}function et(e,t){(e.headers.get(`Cache-Control`)??``).includes(`no-store`)&&e.headers.set(_,t)}function nt(e,t,n,r){if(!u||e.status<400)return;let i=ut(e);if(i!==void 0)try{Promise.resolve(u({status:e.status,code:i,path:Q(new URL(t.url).pathname),...r.entity!==void 0&&{entity:r.entity},requestId:n,...r.principalId!==void 0&&{principalId:r.principalId}})).catch(st)}catch(e){st(e)}}let it=new Set;function at(e,t,n){it.has(e)||(it.add(e),K(t,n))}function K(e,t){try{$().warn(e,t)}catch{try{console.warn(`[content-api]`,t,e)}catch{}}}function st(e){try{$().warn({err:e},"content-api: `onError` monitoring hook failed")}catch{}}async function ct(e,t,n,r){let i=Qt(e,await B(e)),a=Zt(i,N);try{await P.acquire(e.signal)}catch(e){return e instanceof en?(K({limit:`survival`,maxConcurrentRequests:P.limits.maxConcurrentRequests,maxQueuedRequests:P.limits.maxQueuedRequests},`content-api: shedding load — concurrency slots and wait queue both full`),ft(1,a)):(K({err:e},`content-api: acquiring a concurrency slot failed`),J(`Internal server error`,`INTERNAL_ERROR`,500,a))}try{return await P.runGuarded(a=>lt(e,t,n,r,i,a))}catch(e){if(e instanceof tn)return K({limit:`deadline`,requestTimeoutMs:P.limits.requestTimeoutMs},`content-api: request exceeded the wall clock`),ft(1,a);throw e}finally{P.release()}}async function lt(e,t,n,i,o,s){let c=o;try{let l=t.path;if(!l||l.length===0||l[0]!==`v1`)return Y(o);let u=l.slice(1);if(u.length===0)return Y(o);if(new URL(e.url).searchParams.has(`site`))return J(`Invalid query parameters`,`VALIDATION_ERROR`,400,Zt(o,N));let f=await Ee(e),p=f.role,h=await Ae(e,f);if(h===null)return Y(Zt(a?{Vary:`Origin`}:{},N));let _=h.multiSite?Qt(e,{allowedOrigins:h.record?.origins??[],...a?.maxAge!==void 0&&{maxAge:a.maxAge}}):o,y=P.consumeFairness(e,{principalId:f.hasIdentity?f.id:void 0,budgetPerInstance:f.rateBudgetPerInstance}),b=Zt(_,N);c=b;let x=rt(j,ie(h));if(y&&!y.decision.allowed)return K({limit:`fairness`,keyClass:y.keyClass},`content-api: caller exceeded its per-instance budget`),dt(y.decision.retryAfterSeconds,b);let S=await ye();i.principalId=f.id;let C=h.site,w=await Qn(C,r),T=new URL(e.url).searchParams.get(`locale`);if(T!==null&&T!==``&&w.locales.length>0&&!w.locales.includes(T))return J(`Locale '${T}' is not served by this site`,`VALIDATION_ERROR`,400,b);let E={user:{id:f.id,groups:p?[p]:[],...f.name!==void 0&&{name:f.name},...f.email!==void 0&&{email:f.email}},checker:S,requestId:n,...C!==void 0&&{site:C},...w.locales.length>0&&{availableLocales:w.locales}};w.defaultLocale!==void 0&&Xn.set(E,w.defaultLocale),Zn(E);let D=await ee(E,async()=>{if(s?.aborted)throw new tn;if(e.method===`POST`){let t=It(u,`submissions`);return k===void 0||t===void 0?Y(b):zt({forms:k,keySite:f.site,formId:t,headers:b,req:e})}if(u[0]===`_forms`){let t=It(u,`token`);return k===void 0||t===void 0?Y(b):Rt({forms:k,keySite:f.site,formId:t,headers:b,req:e})}if(u[0]===`_schema`)return q(xn({entities:I().list,checkPermission:e=>H(S,p,e),version:`v1`,maxLimit:se,maxOffset:ce,maxResolutionsPerDocument:L,limits:P.limits,hasResolution:d!==void 0,hasMenus:g!==void 0,hasChrome:v!==void 0,cacheTags:j,siteScopedTags:h.multiSite}),200,{...b,"Cache-Control":`no-store`});if(u[0]===`_resolve`)return Ge(e,f,S,b,x);if(u[0]===`_paths`)return qe(e,f,S,b,x);if(u[0]===`_alternates`)return Je(e,f,S,b,x);if(u[0]===`_menu`)return Ye(e,f,b,x);if(u[0]===`_site`)return Xe(e,f,h,w,b,x);if(u[0]===`_chrome`)return Qe(e,f,S,b,x);if(u[0]===`_search`&&u.length===1)return Ze(e,f,S,h,b,x);let t=u[0];if(t===void 0)return Y(b);let n=G(t);if(!n||!H(S,p,n.name))return We(t,n),Y(b);if(i.entity=n.name,n.kind===`singleton`)return u.length===1?Ve(e,n,f,S,b,x):Y(b);if(m(n)){let t=u[1];return u.length===2&&t!==void 0?ze(e,n,t,f,S,b,x):Y(b)}return u.length===1?Le(e,n,f,S,b,x):u[1]===`count`?Re(e,n,f,b,x):u[1]===`slug`&&u[2]?Be(e,n,u[2],f,S,b,x):u.length===2&&u[1]!==void 0?ze(e,n,u[1],f,S,b,x):Y(b)});return x.dropped>0&&D.headers.has(j.header)&&K({dropped:x.dropped,emitted:x.tags.length,maxTags:128,maxHeaderBytes:Ke,...i.entity!==void 0&&{entity:i.entity},path:Q(new URL(e.url).pathname)},`content-api: cache tags refused — this response depends on documents it does not name, so a purge for them will not invalidate it`),D}catch(t){if(t instanceof tn)throw t;if(Pn(t))return Y(c);let n=new URL(e.url).pathname;try{$().error({err:t,path:Q(n)},`content-api handler error`)}catch{console.error(`[content-api] handler error:`,t)}return J(`Internal server error`,`INTERNAL_ERROR`,500,c)}}return{GET:(e,t)=>$e(e,t),POST:(e,t)=>$e(e,t),OPTIONS:async e=>$t(e,await B(e),c),invalidatePermissionCache:be}}export{Ln as API_VERSION,G as CACHE_TAG_NAMESPACE,ht as DEFAULT_SEARCH_RESULTS,it as DETAIL_TEMPLATE_FIELD,st as ERROR_CODES,Ge as MAX_CACHE_TAGS_PER_RESPONSE,Ke as MAX_CACHE_TAG_HEADER_BYTES,We as MAX_CACHE_TAG_LENGTH,Mt as MAX_FORM_BODY_BYTES,De as MAX_RESOLUTIONS_PER_DOCUMENT,gt as MAX_SEARCH_RESULTS,qe as MEDIA_TAG_ENTITY,Ye as SHARED_SITE_TAG_SEGMENT,kt as VISITOR_ADDRESS_HEADER,$n as createContentApiHandler,Le as isResolvedBlockTree};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|