@aiquants/daily-report 0.48.0 → 0.49.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/CHANGELOG.md +36 -0
- package/README.md +45 -24
- package/dist/client.d.mts +11 -3
- package/dist/client.d.ts +11 -3
- package/dist/client.js +5 -5
- package/dist/client.mjs +5 -5
- package/dist/server.js +1 -1
- package/dist/server.mjs +1 -1
- package/dist/styles/daily-report.standalone.css +1 -1
- package/package.json +1 -1
package/dist/server.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var ea=e=>{throw TypeError(e)};var ta=(e,t,r)=>t.has(e)||ea("Cannot "+r);var nr=(e,t,r)=>(ta(e,t,"read from private field"),r?r.call(e):t.get(e)),wn=(e,t,r)=>t.has(e)?ea("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),In=(e,t,r,n)=>(ta(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var vt=e=>typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"||e===null||e===void 0?String(e):Array.isArray(e)?"array":typeof e,K=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${vt(r)}`),Ye=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),_n=(e,t,r)=>K(e,`one of ${r.map(n=>JSON.stringify(n)).join(", ")}`,t),ie=(e,t,r,n)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r&&(n===void 0||t<=n))return t;throw K(e,n===void 0?`an integer >= ${r}`:`an integer from ${r} to ${n}`,t)},Ne=(e,t,r,n)=>t===void 0?n:ie(e,t,r),or=(e,t)=>{if(t===void 0)throw Ye(e,"a function");if(typeof t!="function")throw K(e,"a function",t);return t};var se=()=>Math.floor(performance.now());var xn=Object.freeze({defaultTtlMs:6e4,maxBuckets:4096,maxBytes:512*1024*1024}),Qe=class extends Error{constructor(t){super(`cache miss refused (${t})`),this.name="SqlResultCacheMissRefusal",this.reason=t}},Cn=e=>({async getEpoch(t){try{let r=await e?.getClient();if(!r)return null;let n=await r.get(t);return n?Number(n):0}catch{return null}},async incrementEpoch(t){try{let r=await e?.getClient();if(!r)return;await r.incr(t)}catch{}}}),ar=(e,t)=>t?e.map(r=>structuredClone(r)):e,bc=8,Dc=32,Tc=24,Ac=16,Ec=-(2**30),wc=2**30-1,Ic=e=>Number.isInteger(e)&&e>=Ec&&e<=wc&&!Object.is(e,-0),_c=(e,t)=>{let r=0,n=[e];for(;n.length>0&&r<=t;){let o=n.pop();if(r+=Dc,ArrayBuffer.isView(o)){r+=o.byteLength;continue}let a=Array.isArray(o)?o:Object.keys(o).map(i=>o[i]);r+=bc*a.length;for(let i of a)typeof i=="string"?r+=Tc+2*i.length:typeof i=="number"&&!Ic(i)?r+=Ac:typeof i=="object"&&i!==null&&n.push(i)}return r},ir=class{constructor(t,r){this.epochStore=r;this.buckets=new Map;this.totalBytes=0;this.inFlight=new Map;this.forcedFetches=new Map;this.maybeRefreshAhead=t=>{let r=t.refreshAheadRatio;if(r===void 0)return;let{cacheKey:n}=t,o=this.buckets.get(n);if(!o)return;let a=t.ttlMsOverride??this.defaultTtlMs;if(a-(o.expireAt-se())<a*r||this.inFlight.has(n))return;let l;l=(async()=>{let s=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,c=await t.fetcher();return this.inFlight.get(n)===l&&this.writeBucket(n,{records:c,expireAt:se()+a,epoch:s}),c})(),this.inFlight.set(n,l),l.catch(()=>{}).finally(()=>{this.inFlight.get(n)===l&&this.inFlight.delete(n)})};this.startFetch=(t,r)=>{let{cacheKey:n,admission:o}=t,a;a=(async()=>{let l=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,s=o===void 0?null:await o.acquire(o.signal);if(o!==void 0&&s===null)throw new Qe(o.signal.aborted?"aborted":"busy");try{for(let d of r)d();let c=await t.fetcher();return this.inFlight.get(n)===a&&this.writeBucket(n,{records:c,expireAt:se()+(t.ttlMsOverride??this.defaultTtlMs),epoch:l}),c}finally{s?.()}})(),this.inFlight.set(n,a);let i=()=>{this.inFlight.get(n)===a&&this.inFlight.delete(n)};return a.then(i,i),a};this.forcedFetch=t=>{let{cacheKey:r}=t,n=t.onFetchStart===void 0?[]:[t.onFetchStart],o=this.forcedFetches.get(r);if(o===void 0)return this.runForcedFetch(t,n);if(o.pending===null){let a=[],i=()=>this.runForcedFetch(t,a);o.pending={promise:o.running.then(i,i),onFetchStarts:a}}return o.pending.onFetchStarts.push(...n),o.pending.promise};this.runForcedFetch=(t,r)=>{let{cacheKey:n}=t,o=this.startFetch(t,r);this.forcedFetches.set(n,{running:o,pending:null});let a=()=>{let i=this.forcedFetches.get(n);i?.running===o&&i.pending===null&&this.forcedFetches.delete(n)};return o.then(a,a),o};this.getOrFetch=async t=>{let{cacheKey:r,forceRefresh:n,snapshot:o,admission:a}=t;if(n){if(a?.signal.aborted)throw new Qe("aborted");return this.dropBucket(r),ar(await this.readOwnOrRetry(this.forcedFetch(t),t),o)}let i=this.buckets.get(r);if(i&&i.expireAt>se())if(t.epochKey){let s=await this.epochStore.getEpoch(t.epochKey);if(s===null||i.epoch===s)return this.maybeRefreshAhead(t),ar(i.records,o);this.dropBucket(r)}else return this.maybeRefreshAhead(t),ar(i.records,o);let l=this.inFlight.get(r);if(l!==void 0)return ar(await this.readOwnOrRetry(l,t),o);if(a?.signal.aborted)throw new Qe("aborted");return ar(await this.startFetch(t,t.onFetchStart===void 0?[]:[t.onFetchStart]),o)};this.readOwnOrRetry=async(t,r)=>{try{return await t}catch(n){let{admission:o}=r;if(!(n instanceof Qe&&(o===void 0||n.reason==="aborted"&&!o.signal.aborted)))throw n;return this.getOrFetch({...r,snapshot:!1})}};this.clearAll=()=>{this.buckets.clear(),this.totalBytes=0,this.inFlight.clear()};this.invalidatePrefix=t=>{for(let r of this.buckets.keys())r.startsWith(t)&&this.dropBucket(r);for(let r of this.inFlight.keys())r.startsWith(t)&&this.inFlight.delete(r)};this.defaultTtlMs=Ne("cacheDefaultTtlMs",t.defaultTtlMs,1,xn.defaultTtlMs),this.maxBuckets=Ne("cacheMaxBuckets",t.maxBuckets,1,xn.maxBuckets),this.maxBytes=Ne("cacheMaxBytes",t.maxBytes,1,xn.maxBytes),this.lastSweepAt=se()}dropBucket(t){let r=this.buckets.get(t);r!==void 0&&(this.buckets.delete(t),this.totalBytes-=r.bytes)}writeBucket(t,r){this.dropBucket(t);let n=_c(r.records,this.maxBytes);if(n>this.maxBytes)return;this.buckets.set(t,{...r,bytes:n}),this.totalBytes+=n;let o=se();o-this.lastSweepAt>=this.defaultTtlMs&&this.sweepExpired(o);for(let a of this.buckets.keys()){if(this.buckets.size<=this.maxBuckets&&this.totalBytes<=this.maxBytes)break;this.dropBucket(a)}}sweepExpired(t){this.lastSweepAt=t;for(let[r,n]of this.buckets)n.expireAt<=t&&this.dropBucket(r)}};import{crossOriginRefusal as rm}from"@aiquants/request-isolation";var xc=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var ra=e=>e<10?`0${e}`:`${e}`,Cc=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=ra(e.getMonth()+1),n=ra(e.getDate());return`${t}-${r}-${n}`},jt=e=>{let t=xc.exec(e);if(t===null)return null;let[,r,,n,o]=t,a=Number(r),i=Number(n),l=Number(o);if(a<1)return null;let s=new Date(0);return s.setUTCFullYear(a,i-1,l),s.getUTCFullYear()!==a||s.getUTCMonth()!==i-1||s.getUTCDate()!==l?null:`${r}-${n}-${o}`},Pr=e=>jt(e)===e;var Ve=e=>e==null?null:e instanceof Date?Cc(e):jt(e);import{z as Mc}from"zod/v3";var it=e=>Number.isSafeInteger(e)&&e>0,Oe=Mc.number().int().positive().max(Number.MAX_SAFE_INTEGER);import{z as ee}from"zod/v3";var vr=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|-[1-9][0-9]{0,15})$/;var Mn=/^[0-9a-f]{64}$/u;var Lt=e=>typeof e=="string"&&Mn.test(e);var Nt=Symbol("daily-report wire mismatch"),ze=(e,t,r)=>(e.issues.push({...r,path:t===null?[...e.path]:[...e.path,t]}),Nt),ia=e=>e===null?"null":Array.isArray(e)?"array":Number.isNaN(e)?"nan":typeof e,Et=(e,t)=>({code:"invalid_type",expected:e,received:ia(t)}),kc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Pc=e=>{let t=0;for(let r in e)t+=1;return t},na=(e,t,r)=>{let n={};for(let o=0;o<r;o+=1){let a=t[o];a in e&&(n[a]=e[a])}return n},Wt=e=>{let t=Object.keys(e),r=Object.values(e);return(n,o)=>{if(!kc(n))return ze(o,null,Et("object",n));let a=null,i=!1,l=0;for(let s=0;s<t.length;s+=1){let c=t[s],d=n[c];d!==void 0&&(l+=1);let u=r[s](d,o,c);if(u===Nt){i=!0;continue}a===null&&u!==d&&(a=na(n,t,s)),a!==null&&(u!==void 0||c in n)&&(a[c]=u)}return i?Nt:a!==null?a:Pc(n)===l?n:na(n,t,t.length)}},sr=e=>(t,r,n)=>{r.path.push(n);let o=e(t,r);return r.path.pop(),o},lr=e=>(t,r,n)=>{if(!Array.isArray(t))return ze(r,n,Et("array",t));r.path.push(n);let o=t,a=!1;for(let i=0;i<t.length;i+=1){let l=t[i],s=e(l,r,i);s===Nt?a=!0:s!==l&&(o===t&&(o=t.slice()),o[i]=s)}return r.path.pop(),a?Nt:o},pe=(e,t,r)=>e==null||typeof e=="string"?e:ze(t,r,Et("string",e)),oa=(e,t,r)=>e===null||typeof e=="string"?e:ze(t,r,Et("string",e)),aa=(e,t,r)=>typeof e=="string"?e:ze(t,r,Et("string",e)),vc=(e,t,r)=>e===null||typeof e=="number"&&!Number.isNaN(e)?e:ze(t,r,Et("number",e)),cr=(e,t,r)=>typeof e=="boolean"?e:ze(t,r,Et("boolean",e)),sa=(e,t,r)=>typeof e!="string"?ze(t,r,Et("string",e)):Lt(e)?e:ze(t,r,{code:"invalid_string",validation:"regex",message:"a content digest is 64 lowercase hex digits"}),Lc=(e,t,r)=>e===null?null:sa(e,t,r),kn=(e,t,r)=>{if(typeof e=="number"&&it(e))return e;for(let{message:n,path:o,...a}of Oe.safeParse(e).error.issues)ze(t,r,a);return Nt},la={present:!0,absent:!0,unknown:!0},ca=Object.keys(la),Nc=ca.map(e=>`'${e}'`).join(" | "),Oc=(e,t,r)=>typeof e!="string"?ze(t,r,{code:"invalid_type",expected:Nc,received:ia(e)}):Object.hasOwn(la,e)?e:ze(t,r,{code:"invalid_enum_value",received:e,options:[...ca]}),ua=Wt({name:pe,affiliation:pe}),da=Wt({name:pe,text:pe,color:pe}),pa=Wt({id:kn,name:pe,color:pe}),ma=Wt({id:kn,userId:pe,userName:pe,content:pe,createdAt:pe,isMine:cr}),Hc=Wt({id:aa,fileName:aa,fileType:oa,fileSize:vc,createdAt:oa,state:Oc,hasThumbnail:cr}),Fc=Wt({reportHubId:kn,date:pe,createdAt:pe,author:pe,userId:pe,sourceType:pe,employeeName:pe,updatedBy:pe,updatedAt:pe,category:pe,creationCategory:pe,visitTimeFrom:pe,visitTimeTo:pe,customerName:pe,interviewers:lr(sr(ua)),subject:pe,content:pe,externalComments:lr(sr(da)),isRead:cr,isStarred:cr,contentDigest:sa,readContentDigest:Lc,isDraft:cr,labels:lr(sr(pa)),postedComments:lr(sr(ma)),attachments:lr(sr(Hc))}),ur=(e,t)=>{let r={path:[],issues:[]},n=e(t,r);return n===Nt?{ok:!1,issues:r.issues}:{ok:!0,value:n}},ya=e=>ur(Fc,e),ha=e=>ur(ua,e),fa=e=>ur(da,e),Ra=e=>ur(pa,e),Sa=e=>ur(ma,e);var ga=15e3,ba="lastEventId",$c=/^\d{1,15}-\d{1,15}$/,Da=e=>$c.test(e),wt="0-0",dr=e=>ee.unknown().transform((t,r)=>{let n=e(t);if(n.ok)return n.value;for(let o of n.issues)r.addIssue({...o,fatal:!0});return ee.NEVER}),hh=dr(ha),fh=dr(fa),Rh=dr(Ra),Uc=dr(Sa),pr=dr(ya),mr=ee.string().regex(vr),Ta=ee.object({type:ee.literal("connected")}),Aa=ee.object({type:ee.literal("status-update"),reportHubId:Oe,statusType:ee.enum(["star","read"]),value:ee.boolean(),readContentDigest:ee.string().regex(Mn).nullable(),clientTempId:mr}),Pn=ee.string(),Ea=ee.object({type:ee.literal("comment-add"),reportHubId:Oe,comment:Uc,clientTempId:mr,sourceType:Pn}),wa=ee.object({type:ee.literal("comment-delete"),reportHubId:Oe,commentId:Oe,clientTempId:mr,sourceType:Pn}),Lr={recipientRawUserId:Oe.optional()},vn=Aa.extend(Lr),Ln=Ea.extend(Lr),Nn=wa.extend(Lr),Yt={reportHubId:Oe,report:pr,clientTempId:mr},On={...Lr,actorRawUserId:Oe},Hn={viewerIsActor:ee.boolean()},Bc=ee.object({type:ee.literal("report-create"),...Yt,...Hn}),Vc=ee.object({type:ee.literal("report-update"),...Yt,...Hn}),qc=ee.object({type:ee.literal("report-publish"),...Yt,...Hn}),Fn=ee.object({type:ee.literal("report-create"),...Yt,...On}),$n=ee.object({type:ee.literal("report-update"),...Yt,...On}),Un=ee.object({type:ee.literal("report-publish"),...Yt,...On}),Nr=ee.object({type:ee.literal("report-delete"),reportHubId:Oe,clientTempId:mr,sourceType:Pn}),Sh=ee.discriminatedUnion("type",[Ta,Aa,Ea,wa,Bc,Vc,qc,Nr]),Bn=ee.discriminatedUnion("type",[Ta,vn,Ln,Nn,Fn,$n,Un,Nr]);var Ia="ids-columns";var jc=/^[0-9a-f]{1,16}$/,_a=e=>it(e.reportHubId)&&(e.businessDate===null||Pr(e.businessDate)),xa=e=>typeof e=="string"&&jc.test(e),Th=Object.freeze({kind:"absent"}),Ah=Object.freeze({kind:"value",value:null});var zt=(e,t,r)=>{let n=[],o=[],a=[],i=[],l=[],s=new Map;for(let c=t;c<r;c++){let{reportHubId:d,businessDate:u,sourceType:h}=e[c];n.push(d),o.length>0&&o[o.length-1]===u?a[a.length-1]+=1:(o.push(u),a.push(1));let m=h===void 0?null:h,y=s.get(m);y===void 0&&(y=i.length,i.push(m),s.set(m,y)),l.push(y)}return{ids:n,dates:o,counts:a,sourceTypes:i,sources:l}},Or=e=>{let t=2166136261,r=-624069552;for(let n of e){let o=n.reportHubId;t^=o&255,t=Math.imul(t,16777619),t^=o>>>8&255,t=Math.imul(t,16777619),t^=o>>>16&255,t=Math.imul(t,16777619),t^=o>>>24&255,t=Math.imul(t,16777619),r^=o>>>24&255,r=Math.imul(r,16777619),r^=o>>>16&255,r=Math.imul(r,16777619),r^=o>>>8&255,r=Math.imul(r,16777619),r^=o&255,r=Math.imul(r,16777619);let a=n.businessDate;if(a===null)t^=1,t=Math.imul(t,16777619),r^=1,r=Math.imul(r,16777619);else for(let i=0;i<a.length;i++){let l=a.charCodeAt(i);t^=l&255,t=Math.imul(t,16777619),r^=l&255,r=Math.imul(r,16777619)}}return t^=e.length,t=Math.imul(t,16777619),r^=e.length,r=Math.imul(r,16777619),((t>>>0).toString(16).padStart(8,"0")+(r>>>0).toString(16).padStart(8,"0")).replace(/^0+(?=.)/,"")},Ca=(e,t,r,n)=>e!==r?e===null?1:r===null||e>r?-1:1:n-t,Wc=(e,t,r,n)=>Ca(e,t,r,n)<0,Vn=(e,t)=>Ca(e.businessDate,e.reportHubId,t.businessDate,t.reportHubId),Ma=e=>{for(let t=1;t<e.length;t++)if(!Wc(e[t-1].businessDate,e[t-1].reportHubId,e[t].businessDate,e[t].reportHubId))return!1;return!0},ka=(e,t)=>{let r=e.findIndex(n=>Vn({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var le=Object.freeze({businessDate:"business-date",idsStream:Ia,report:"report",search:"search",reports:"reports",searchMarks:"search-marks",searchFacets:"search-facets",action:"action"}),be=Object.freeze({businessDate:"businessDate",reportHubId:"reportHubId",searchQuery:"q",searchCombine:"combine",searchAuthor:"author",searchSourceType:"sourceType",searchCustomer:"customer",reportIds:"ids",forceRefresh:"forceRefresh",cursorReportHubId:"cursor_report_hub_id",cursorBusinessDate:"cursor_business_date",cursorSnapshot:"cursor_snapshot"});var Pa=(e,t,r=console)=>{let n=o=>typeof o=="string"?[`${t} ${o}`]:[t,o];return{debug:(o,...a)=>{e<=0&&r.debug(...n(o),...a)},info:(o,...a)=>{e<=1&&r.info(...n(o),...a)},warn:(o,...a)=>{e<=2&&r.warn(...n(o),...a)},error:(o,...a)=>{e<=3&&r.error(...n(o),...a)}}},_h=Object.freeze(["API","Action","Attachment","ExternalSource","Isolation","Reads","Refresh","Search","SSE","SseReader","Server","Service","Streams","Visibility","ActionProvider","DetailLoader","IdsStream","SseConnection"]),va=e=>`[DailyReport${e}]`,De=(e,t,r)=>e===void 0?Pa(t,va(r)):Pa(0,va(r),e);import{z as Ot}from"zod/v3";var yr=e=>({reportHubId:e,outcome:"not_found"}),Ph=Ot.discriminatedUnion("outcome",[Ot.object({reportHubId:Oe,outcome:Ot.literal("ok"),report:pr}).strict(),Ot.object({reportHubId:Oe,outcome:Ot.literal("not_found")}).strict(),Ot.object({reportHubId:Oe,outcome:Ot.literal("failed")}).strict()]);var Yc="legacy-",qn=e=>`${Yc}${e}`;var zc=/^[1-9][0-9]*$/,Gc=/^(?:0|[1-9][0-9]*)$/,Xe=e=>{if(e===null||!zc.test(e))return null;let t=Number(e);return it(t)?t:null},jn=e=>{if(e===null||!Gc.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},Wn=e=>e==="true"?!0:e==="false"?!1:null,hr=e=>e===null?!1:Wn(e);var La=Object.freeze(["subject","content","author","employeeName","updatedBy","category","creationCategory","customerName"]),mt=Object.freeze({field:e=>e,interviewer:(e,t)=>`interviewer:${e}:${t}`,attachment:e=>`attachment:${e}`,comment:(e,t)=>`comment:${e}:${t}`});var Kc=16777619,Yn=2166136261,zn=(e,t,r,n)=>{let o=e;for(let a=r;a<n;a++)o^=t.charCodeAt(a),o=Math.imul(o,Kc);return o>>>0},Na=e=>zn(Yn,e,0,e.length),Jc=String.fromCodePoint(3),Qc=String.fromCodePoint(2),Xc=String.fromCodePoint(1),Hr=e=>Na(e.map(t=>t.map(r=>r.map(n=>`${n.tier}${n.text}`).join(Jc)).join(Qc)).join(Xc));var Oa=e=>e==="intersection"||e==="union",Ce=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),Gn=2,Fr=2,Ht=Object.freeze({word:0,reading:1});var Kn=(e,t)=>({ids:e.map(r=>r.reportHubId),businessDates:e.map(r=>r.businessDate),sourceTypes:e.map(r=>r.sourceType),words:t});var Fh=2*(1+Gn);import{z as Vh}from"zod/v3";var Ha=e=>e.issues.map(t=>`${t.path.length===0?"(root)":t.path.join(".")}: ${t.code}`).join("; ");var we=Object.freeze({intent:"intent",clientTempId:"clientTempId",businessDate:"businessDate",operationTimestamp:"operationTimestamp",reportHubId:"reportHubId",title:"title",content:"content",isStarred:"isStarred",isRead:"isRead",contentDigest:"contentDigest",commentId:"commentId"});var $r=Math.max(1,Math.floor(10.556701030927835));var Ze=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var Me=e=>{let{windowMs:t,tallies:r,writeSuppressed:n}=e,o=new Map,a=i=>{let l={since:new Date().toISOString(),count:0,tallies:Object.fromEntries(r.map(c=>[c,0]))};o.set(i,l),Ze(()=>{o.delete(i),l.count>0&&n(i,l)},t)};return{record:(i,l,s)=>{let c=o.get(i);if(c!==void 0){c.count+=1,c.tallies[l]+=1;return}s(),a(i)}}};var yt=Object.freeze({maxValuesPerFacet:16,maxValueLength:200,maxTotalValueLength:300});var Gh=Object.freeze({authors:Object.freeze([]),sourceTypes:Object.freeze([]),customers:Object.freeze([])}),Zc=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Jn=e=>{let t=e.trim();return t.length===0?null:t.replace(Zc,"\uFFFD")},eu=e=>{let t=Jn(e);return t===null?"filter-blank-value":t!==e?"filter-value-not-canonical":e.length>yt.maxValueLength?"filter-value-too-long":null},tu=e=>{if(e.length>yt.maxValuesPerFacet)return"filter-too-many-values";let t=new Set;for(let r of e){let n=eu(r);if(n!==null)return n;if(t.has(r))return"filter-duplicate-value";t.add(r)}return null},ru=e=>{let t=0;for(let r of e.authors)t+=r.length;for(let r of e.customers)t+=r.length;return t},Fa=e=>{for(let t of[e.authors,e.sourceTypes,e.customers]){let r=tu(t);if(r!==null)return r}return ru(e)>yt.maxTotalValueLength?"filters-too-long":null};var $a=e=>e.trim().length===0;var Qn=e=>e!==null&&vr.test(e)?e:null,Xn=e=>Oa(e)?e:null,Zn=e=>{if(e===null)return null;let t=e.split(",");if(t.length>Ce.maxDetailIds)return null;let r=[];for(let n of t){let o=Xe(n);if(o===null||r.includes(o))return null;r.push(o)}return r},Ua=e=>{let[t,...r]=e;return t===void 0?null:[t,...r]},Ba=(e,t)=>{let r={authors:e.getAll(be.searchAuthor),sourceTypes:e.getAll(be.searchSourceType),customers:e.getAll(be.searchCustomer)},n=Fa(r);if(n!==null)return{ok:!1,reason:n};let o=new Set(t.map(i=>i.toLowerCase())),a=new Set;for(let i of r.sourceTypes){let l=i.toLowerCase();if(!o.has(l))return{ok:!1,reason:"filter-unknown-source-type"};if(a.has(l))return{ok:!1,reason:"filter-duplicate-value"};a.add(l)}return{ok:!0,filters:{sourceTypes:a.size===0?null:a,authors:Ua(r.authors),customers:Ua(r.customers)}}},Va=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var ja=Object.freeze({status:400,error:"Invalid form"}),Wa=e=>({status:413,error:"Form too large",measuredBy:e}),nu=(e,t,r)=>{let n=0;return e.pipeThrough(new TransformStream({transform(o,a){if(n+=o.byteLength,n>t){r(),a.error(new Error(`action form body exceeds ${t} bytes`));return}a.enqueue(o)}}))},ou=async e=>{let t=jn(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:Wa("declared")};let r=!1,n=e.body===null?null:nu(e.body,1048576,()=>{r=!0}),o=new Headers,a=e.headers.get("Content-Type");a!==null&&o.set("Content-Type",a);let i;try{i=await new Response(n,{headers:o}).formData()}catch{return{refusal:r?Wa("counted"):ja}}let l=Va(i);return l===null?{refusal:ja}:{fields:l}},za=(e,t)=>{let r=e.get(t);if(r===null)return{error:`${t} required`};let n=Wn(r);return n===null?{error:`Invalid ${t}`}:{value:n}},au=(e,t)=>{let r=za(e,we.isStarred);return"error"in r?r:{command:{...t,intent:"toggleStar",value:r.value}}},iu=(e,t)=>{let r=za(e,we.isRead);if("error"in r)return r;let n=e.get(we.contentDigest);return r.value?n===null?{error:`${we.contentDigest} required`}:Lt(n)?{command:{...t,intent:"toggleRead",value:!0,contentDigest:n}}:{error:`Invalid ${we.contentDigest}`}:n===null?{command:{...t,intent:"toggleRead",value:!1}}:{error:`${we.contentDigest} is not allowed when ${we.isRead} is false`}},Ga=Object.freeze({update:(e,t,r)=>{let n=e.get(we.title),o=e.get(we.content);if(n!==null&&n.length>r.titleMaxLength)return{error:"Invalid title"};let a={};return n!==null&&(a.title=n),o!==null&&(a.content=o),{command:{...t,intent:"update",changes:a}}},publish:(e,t)=>({command:{...t,intent:"publish"}}),delete:(e,t)=>({command:{...t,intent:"delete"}}),toggleStar:au,toggleRead:iu,addComment:(e,t)=>{let r=e.get(we.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=Xe(e.get(we.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),su=e=>Object.hasOwn(Ga,e),lu=(e,t)=>{let r=e.get(we.intent),n=e.get(we.businessDate),o=n===null?null:jt(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get(we.operationTimestamp),i=jn(a);if(a!==null&&i===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get(we.clientTempId);if(!l)return{error:"clientTempId required"};let s=Qn(l);if(s===null)return{error:"Invalid clientTempId"};if(r==="create")return o===null?{error:"businessDate required"}:{command:{intent:r,clientTempId:s,businessDate:o,operationTimestamp:i}};let c=Xe(e.get(we.reportHubId));return c===null?{error:"Invalid reportHubId"}:r===null||!su(r)?{error:"Invalid intent"}:Ga[r](e,{clientTempId:s,businessDate:o,operationTimestamp:i,reportHubId:c},t)},Ka=async(e,t)=>{let r=await ou(e);if("refusal"in r)return r;let n=lu(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},cu=6e4,uu="form_too_large",Ya=["declared","counted"],Ja=e=>{let t=Me({windowMs:cu,tallies:Ya,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${Ya.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(uu,r,n)}};var Ft=Object.freeze({[le.businessDate]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[le.idsStream]:{body:"stream",admission:["refresh-bucket","stream-slots","cache","miss-gate"]},[le.report]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[le.search]:{body:"json",cache:"etag",admission:["search-limiter"]},[le.reports]:{body:"json",cache:"etag",admission:["search-limiter"]},[le.searchMarks]:{body:"json",cache:"no-store",admission:["search-limiter"]},[le.searchFacets]:{body:"json",cache:"etag",admission:["search-limiter"]}}),Qa=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),eo=e=>e!==void 0&&Object.hasOwn(Ft,e);var to=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),Xa=e=>Object.hasOwn(to,e);var du="download",pu="thumbnail",mu="1";var ro=e=>{let t=e.getAll(pu),r=e.getAll(du);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&Xa(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===mu?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};import{NO_CROSS_ORIGIN_NAVIGATION as Ru}from"@aiquants/request-isolation";import{createHash as yu}from"crypto";var no=e=>`"${yu("sha256").update(e).digest("hex")}"`,Za=e=>no(JSON.stringify(e));var st=Object.freeze({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'"}),oo=(e,t)=>{if(e===null)return!1;for(let r of e.split(",")){let n=r.trim();if((n.startsWith("W/")?n.slice(2):n)===t)return!0}return!1},ei=(e,t,r,n=200)=>{let o=JSON.stringify(r),a=no(o),i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate",ETag:a,...st});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&oo(e.headers.get("If-None-Match"),a)?new Response(null,{status:304,headers:i}):new Response(o,{status:n,headers:i})},ao=(e,t,r)=>{let n=new Headers({...t===null?{}:{"Content-Type":"application/json"},"Cache-Control":"no-store",...st});return e&&n.append("Set-Cookie",e),new Response(t===null?null:JSON.stringify(t),{status:r,headers:n})},io=e=>(t,r,n,o)=>{if(o!==200)return ao(r,n,o);if(e===null||n===null)throw new Error(`[daily-report] API route: a 200 JSON answer needs an answer of a JSON 200 and a body; got ${e===null?"a responder without one":"an answer"} and ${n===null?"no body":"a body"}`);return e(t,r,n)},hu=5e3/1e3,fu=new Map([[503,hu]]),Ae=e=>{let t=fu.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var lo="Cross-site request rejected",Su="Not Found",ti=["api","action","sse","attachment"],ri=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...st}}),gu=()=>ri(403,lo),Ur=()=>ri(404,Su),fr=Object.freeze({...Ru,frameworkDataRefusal:()=>null,crossSiteRejection:gu}),ni=e=>new URL(e.url).pathname.endsWith(".data"),bu=6e4,Du="refusals",Tu=32,Au=/^[a-z-]+$/,so=e=>{if(e===null)return"-";let t=e.slice(0,Tu);return Au.test(t)&&t===e?e:JSON.stringify(t)},oi=e=>{let t=Me({windowMs:bu,tallies:ti,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${ti.map(i=>`${i}:${a[i]}`).join(",")}`)}});return(r,n,o)=>{let a=()=>{let{headers:i}=o;e.warn(`cross_site_rejected route=${r} reason=${n} site=${so(i.get("Sec-Fetch-Site"))} mode=${so(i.get("Sec-Fetch-Mode"))} dest=${so(i.get("Sec-Fetch-Dest"))} method=${o.method}`)};t.record(Du,r,a)}};var ai=(e,t)=>(r,n)=>{let o=n?"markAttachmentPresent":"markAttachmentMissing";e[o](r).catch(a=>{t.error(`${o} failed attachment=${r} message=${a instanceof Error?a.message:"unknown"}`)})};var Eu="same-origin",wu="SAMEORIGIN",Gt=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":Eu,"X-Frame-Options":wu}),Br=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...Gt});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},ii=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),Iu=/^[\x20-\x7E]+$/,_u=/^[\w.+-]+\/[\w.+-]+/,co=e=>e&&Iu.test(e)&&_u.test(e)?e:null,xu=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,si=e=>encodeURIComponent(e.replace(xu,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),li=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),Rr={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},ci={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},Vr=e=>typeof e=="string"&&Object.hasOwn(ci,e),qr=e=>ci[e],ht="Attachment request failed";var lt=e=>{let t=ie("limit",e.limit,1),r=ie("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:ie("queue.max",e.queue.max,0),maxPerOwner:ie("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:ie("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],i=new Map,l=new Map,s=(p,f)=>p.get(f)??0,c=(p,f,D)=>{let E=s(p,f)+D;E<=0?p.delete(f):p.set(f,E)},d=p=>s(l,p)<r,u=p=>o<t&&d(p),h=p=>(o+=1,c(l,p,1),R(p)),m=()=>{let p=-1,f=r;for(let[D,E]of a.entries()){let S=s(l,E.owner);if(S<f&&(p=D,f=S,S===0))break}return p},y=()=>{for(;o<t;){let p=m();if(p<0)return;let[f]=a.splice(p,1);c(i,f.owner,-1),f.grant(h(f.owner))}},R=p=>{let f=!1;return()=>{f||(f=!0,o-=1,c(l,p,-1),y())}};return{canAcquire:u,acquire:(p,f)=>{if(f.aborted)return Promise.resolve(null);if(u(p))return Promise.resolve(h(p));if(n===null||a.length>=n.max||s(i,p)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:D}=n,E=S=>{let g=()=>{let O=a.indexOf(x);O<0||(a.splice(O,1),c(i,p,-1),T(),S(null))},C=Ze(g,D),T=()=>{clearTimeout(C),f.removeEventListener("abort",g)},x={owner:p,grant:O=>{T(),S(O)}};a.push(x),c(i,p,1),f.addEventListener("abort",g,{once:!0})};return new Promise(E)}}};var Cu=1024,uo="Too many requests",Mu=(e,t)=>{ie("limitPerWindow",e,1),ie("windowMs",t,1);let r=new Map,n=(a,i)=>{i<=a.lastRefillMs||(a.tokens=Math.min(e,a.tokens+(i-a.lastRefillMs)*e/t),a.lastRefillMs=i)},o=(a,i)=>{let l=r.get(a);l&&r.delete(a);let s=l??{tokens:e,lastRefillMs:i};n(s,i),r.set(a,s);for(let c of r.keys()){if(r.size<=Cu)break;r.delete(c)}return s};return{consume:(a,i)=>{let l=o(a,i);return l.tokens<1?!1:(l.tokens-=1,!0)},refund:(a,i,l)=>{let s=r.get(a);s&&(n(s,i),s.tokens=Math.min(e,s.tokens+l))}}},ft=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(ie("windowMs",r,1e3)%1e3!==0)throw K("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=Mu(e.limitPerWindow,r),i=Object.freeze({status:429,message:uo,headers:Object.freeze({"Retry-After":String(r/1e3)})}),l=Me({windowMs:r,tallies:[t],writeSuppressed:(s,{count:c,since:d})=>{n.warn(`${t}_suppressed count=${c} since=${d} ${o(s)}`)}});return{spend:(s,c)=>a.consume(s,se())?null:(l.record(s,t,()=>n.warn(`429 ${c} reason=${t}`)),i),refund:(s,c)=>{a.refund(s,se(),c)}}};var Pu=256*1024,ui=6e4,vu=e=>Math.ceil(e/2),Lu=new Uint8Array(new ArrayBuffer(0)),Nu=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=Lu,t()},i=l=>{clearTimeout(o),o=Ze(()=>{l.error(new Error(`attachment body idle for ${ui} ms`)),a()},ui)};return new ReadableStream({start(l){i(l)},pull(l){let s=Math.min(n+Pu,r.byteLength);if(s>n&&l.enqueue(r.slice(n,s)),n=s,n>=r.byteLength){l.close(),a();return}i(l)},cancel(){a()}},{highWaterMark:0})},di=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=ft({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:s=>`viewer=${s}`}),l=lt({limit:e.concurrency,maxHeldPerOwner:vu(e.concurrency),queue:null});return async s=>{let{request:c,delivery:d,attachmentId:u,internalUserId:h,readAttachment:m,cookie:y,fail:R}=s,p=e.maxBytes,f=i.spend(h,`attachment=${u} viewer=${h}`);if(f)return R(f.status,f.message,f.headers);let D=await n(c,"initial");if(!D.ok)return R(503,Rr[503],Ae(503));let E=await t.getAttachmentForUser(D.scope,u,h);if(!E)return o.warn(`404 attachment=${u} viewer=${h} reason=not_visible`),R(404,"Attachment not found");if(E.fileSize!=null&&E.fileSize>p)return o.warn(`413 attachment=${u} viewer=${h} reason=db_size`),R(413,"Attachment too large");let S=co(E.fileType),g=`filename="${li(E.fileName)}"; filename*=UTF-8''${si(E.fileName)}`,C=await l.acquire(h,c.signal);if(!C)return c.signal.aborted?(o.info(`503 attachment=${u} viewer=${h} reason=aborted`),R(503,"Attachment request aborted")):(o.warn(`503 attachment=${u} viewer=${h} reason=concurrency`),R(503,"Too many concurrent downloads",Ae(503)));let T=!1;try{let x=await m(E.filePath,{maxBytes:p,head:c.method==="HEAD",principal:r(h),signal:c.signal});if(c.signal.aborted)return o.info(`503 attachment=${u} viewer=${h} reason=aborted`),R(503,"Attachment request aborted");if(!x.ok){if(!Vr(x.reason))return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=failure_reason`),R(500,ht);let F=qr(x.reason);return x.reason==="not_found"&&a(u,!1),o.warn(`${F} attachment=${u} viewer=${h} reason=${x.reason} code=${x.code??"-"}`),R(F,Rr[F],Ae(F))}if(x.bytes.byteLength>p)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=over_max_bytes`),R(500,ht);let O=c.method==="HEAD";if(O&&x.size!==void 0&&x.size>p)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=over_max_bytes`),R(500,ht);if(!O&&x.size!==void 0&&x.size!==x.bytes.byteLength)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=size_mismatch`),R(500,ht);let w=S??co(x.contentType),v=w!==null&&ii.has(w),_=v?w:"application/octet-stream",q=v&&d.kind!=="download"?"inline":"attachment",J=O?x.size:x.bytes.byteLength,G=new Headers({"Content-Type":_,"Content-Disposition":`${q}; ${g}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...Gt});return J!==void 0&&G.set("Content-Length",String(J)),y&&G.append("Set-Cookie",y),a(u,!0),o.info(`200 attachment=${u} viewer=${h} type=${_} disposition=${q} bytes=${J??"-"}`),O?new Response(null,{status:200,headers:G}):(T=!0,new Response(Nu(x.bytes,C),{status:200,headers:G}))}finally{T||C()}}};var qe=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),$f=qe.queueWaitMs+qe.readMs+qe.renderMs+qe.transferMarginMs;import{Buffer as Ou}from"buffer";var yi=new Set([194,198,202,206]),Hu=new Set([192,193,194,195]),hi=216,Fu=217,fi=218,$u=4,Uu=64,Bu=2,pi=8,mi=28,It=12,po=8,Vu=20,Ri=It+po+10,qu=2,Rt=(e,t)=>e[t]<<8|e[t+1],Kt=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];return n},ct=(e,t,r)=>{if(e.byteLength<t+r.length)return!1;for(let n=0;n<r.length;n+=1)if(e[t+n]!==r.charCodeAt(n))return!1;return!0},Si=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,gi=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),bi=e=>(e.stepsLeft-=1,e.stepsLeft>=0),Di=e=>e[0]===255&&e[1]===hi,Ti=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!bi(r))return null;n+=1}while(n<e.byteLength&&e[n]===255);if(n>=e.byteLength)return null;let o=e[n];if(n+=1,o===Fu)return"eoi";if(o===0||o===hi)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=Rt(e,n),i=n+a;return a<2||i>e.byteLength?null:(r.marker=o,r.body=n+2,r.length=a,r.end=i,"segment")}},ju=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!bi(r))return null;if(a+1>=n)return n;let i=e[a+1];if(i===255)a+=1;else if(i===0||i>=208&&i<=215){if(a+=2,a>=n||e[a]!==255)break}else return a}o=a}},Ai=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=Rt(e,r+1),a=Rt(e,r+3),i=e[r+5];if(a===0||o===0||i===0||n!==8+3*i)return null;let l=[];for(let s=0;s<i;s+=1){let c=e[r+7+3*s],d=c>>4,u=c&15;if(d<1||d>4||u<1||u>4)return null;l.push({id:e[r+6+3*s],horizontal:d,vertical:u})}return{marker:t,width:a,height:o,components:l}},Ei=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>$u||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},wi=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:yi.has(e.marker)||t<e.components.length}),mo=e=>{if(!Di(e))return null;let t=gi(e.byteLength),r=null;for(let n=2;;){if(Ti(e,n,t)!=="segment")return null;if(Si(t.marker)){if(r!==null||(r=Ai(e,t),r===null))return null}else if(t.marker===fi){if(r===null)return null;let o=Ei(e,t);return o===null?null:wi(r,o.length)}n=t.end}},Ii=e=>{let t=Math.max(...e.components.map(n=>n.horizontal)),r=Math.max(...e.components.map(n=>n.vertical));return e.components.map(({horizontal:n,vertical:o})=>{let a=Math.ceil(e.width*n/(t*pi)),i=Math.ceil(e.height*o/(r*pi));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},_i=e=>e.multiScan?Ii(e).reduce((r,n)=>r+n,0)*Uu*Bu:0,Wu=896,xi=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!Di(e))return null;let n=Ou.from(e.buffer,e.byteOffset,e.byteLength),o=gi(r),a=null,i=null,l=new Map,s=0,c=0,d=0;for(let u=2;;){let h=Ti(e,u,o);if(h===null)return null;if(h==="eoi")return i===null?null:{header:i,blockVisits:c};if(u=o.end,Si(o.marker)){if(a!==null||!Hu.has(o.marker)||(a=Ai(e,o),a===null))return null;let m=Ii(a);l=new Map;for(let[y,R]of a.components.entries()){let p=l.get(R.id);l.set(R.id,p===void 0?m[y]:Math.max(p,m[y]))}s=a.components.length*(yi.has(a.marker)?Wu:1)}else if(o.marker===fi){if(a===null||d===s)return null;let m=Ei(e,o);if(m===null)return null;for(let R of m){let p=l.get(R);if(p===void 0)return null;c+=p}if(d+=1,i===null&&(i=wi(a,m.length)),c>t||!i.multiScan)return{header:i,blockVisits:c};let y=ju(n,o.end,o);if(y===null)return null;u=y}}},Ci=e=>{if(e.byteLength<24||Rt(e,8)!==0||Rt(e,10)!==13||!ct(e,12,"IHDR"))return null;let t=Rt(e,16)*65536+Rt(e,18),r=Rt(e,20)*65536+Rt(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},Yu=e=>{if(ct(e,It,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=Kt(e,26,2)&16383,r=Kt(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(ct(e,It,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=Kt(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return ct(e,It,"VP8X")?e.byteLength<Ri?null:{width:Kt(e,24,3)+1,height:Kt(e,27,3)+1}:null},Mi=e=>{if(Ci(e)===null||e.byteLength<=mi)return null;switch(e[mi]){case 0:return!1;case 1:return!0;default:return null}},ki=(e,t)=>{if(ct(e,It,"VP8 "))return"lossy";if(ct(e,It,"VP8L"))return"lossless";if(!ct(e,It,"VP8X")||e.byteLength<Ri)return null;if((e[Vu]&qu)!==0)return"animated";let r=!1,n=t;for(let o=It;o+po<=e.byteLength;){if(n-=1,n<0)return null;if(ct(e,o,"VP8L"))return"lossless";if(ct(e,o,"VP8 "))return r?"lossy-alpha":"lossy";ct(e,o,"ALPH")&&(r=!0);let a=Kt(e,o+4,4);o+=po+a+a%2}return null},Pi={png:Ci,jpeg:mo,webp:Yu};var yo=Object.freeze(["image/webp","image/jpeg","image/png"]),ho=1024*1024;var zu=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Gu={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},Ku=new Set(yo),Ju=e=>typeof e=="string"&&Ku.has(e),Qu=256,jr=(e,t)=>e.fileType===null||!zu.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,Xu=[137,80,78,71,13,10,26,10],Zu=[255,216,255],ed=[[71,73,70,56,55,97],[71,73,70,56,57,97]],td=[82,73,70,70],rd=[87,69,66,80],Sr=(e,t,r)=>{if(e.byteLength<r+t.length)return!1;for(let[n,o]of t.entries())if(e[r+n]!==o)return!1;return!0},fo=e=>{if(Sr(e,Xu,0))return"png";if(Sr(e,Zu,0))return"jpeg";for(let t of ed)if(Sr(e,t,0))return"gif";return Sr(e,td,0)&&Sr(e,rd,8)?"webp":null},vi=e=>{let t=JSON.stringify([e.rendererId,e.box.maxWidth,e.box.maxHeight,e.attachmentId,e.filePath,e.fileType,e.fileSize]);return{key:t,etag:Za([t])}},Li=(e,t)=>{if(!Ju(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>ho)return"too_large";let r=Gu[e.contentType];if(fo(e.bytes)!==r)return"signature";let n=Pi[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},Ni=e=>{ie("maxBytes",e.maxBytes,0),ie("maxEntries",e.maxEntries,0);let t=new Map,r=0,n=o=>{let a=t.get(o);a&&(t.delete(o),r-=a.weight)};return{get:o=>{let a=t.get(o);if(a)return t.delete(o),t.set(o,a),a.entry},set:(o,a)=>{n(o);let i=(a.kind==="thumbnail"?a.bytes.byteLength:0)+Qu;if(i>e.maxBytes||e.maxEntries===0)return;let l=a.kind==="thumbnail"?{kind:"thumbnail",bytes:a.bytes.slice(),contentType:a.contentType}:a;t.set(o,{entry:l,weight:i}),r+=i;for(let s of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(s)}}}};var Ro=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,i=se(),l=new AbortController,s=!1,c,d,u=()=>{a(se()-i)},h=S=>{c=Ze(()=>{s=!0,S({timedOut:!0}),d=Ze(u,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},m=new Promise(h),y=AbortSignal.any([r,l.signal]),R=S=>{S(n(y))},p=new Promise(R),f=S=>(clearTimeout(c),clearTimeout(d),s&&o(se()-i,S.kind==="error"?{error:S.error}:null),S),D=p.then(S=>f({kind:"value",value:S}),S=>f({kind:"error",error:S}));return{outcome:Promise.race([p.then(S=>({timedOut:!1,value:S})),m]),settled:D}};var St={404:"Attachment not found",500:ht,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},Oi=(e,t)=>{if(typeof e!="object"||e===null)return{failure:{kind:"failure",status:500,reason:"port_contract",code:"result"}};let r=e;if(!r.ok)return r.reason==="unsupported"?{entry:{kind:"unrenderable",reason:"unsupported"}}:r.reason==="failed"?{failure:{kind:"failure",status:502,reason:"render_failed"}}:{failure:{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"}};let n=Li(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},nd=e=>{let t=new AbortController,r=()=>{t.abort()},n=Ze(r,qe.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},Hi=()=>{},od=(e,t)=>t.aborted?Promise.resolve():new Promise(r=>{let n=()=>{t.removeEventListener("abort",n),r()};t.addEventListener("abort",n,{once:!0}),e.then(n)}),Fi=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:i}=e,l=new Map,s=(m,y)=>{let R=y.then(Hi,Hi);l.set(m,R);let p=()=>{l.get(m)===R&&l.delete(m)};R.then(p)},c=async(m,y)=>{let R=l.get(m.key);if(R===void 0)return t.acquire(m.owner,y);let p=nd(y);try{if(await od(R,p.signal),p.signal.aborted)return null;let f=r.get(m.key);return f!==void 0?{...f,identity:"verified"}:await t.acquire(m.owner,p.signal)}finally{p.end()}},d=(m,y)=>{if(m.fileSize===null)return y.kind==="exact"?"verified":"unrecorded";if(y.kind==="exact"?y.bytes===m.fileSize:m.fileSize>y.maxBytes)return"verified";let p=y.kind==="exact"?String(y.bytes):`>${y.maxBytes}`;return i.warn(`size_mismatch expected=${m.fileSize} got=${p} attachment=${m.attachmentId} viewer=${m.owner} variant=thumbnail`),"unverified"},u=(m,y)=>(R,p)=>{let f=p===null?"":` message=${p.error instanceof Error?p.error.message:"unknown"}`;i.warn(`${m}_overrun ms=${R} attachment=${y.attachmentId} viewer=${y.owner} variant=thumbnail${f}`)},h=(m,y)=>R=>{i.warn(`${m}_stuck ms=${R} attachment=${y.attachmentId} viewer=${y.owner} variant=thumbnail`)};return async(m,y)=>{let R=await c(m,y);if(R===null)return{kind:"failure",status:503,reason:y.aborted?"aborted":"queue"};if(typeof R!="function")return R;let p=R,f=null;try{if(y.aborted)return{kind:"failure",status:503,reason:"aborted"};let D=r.get(m.key);if(D!==void 0)return{...D,identity:"verified"};let E=Ro({budgetMs:qe.readMs,flightSignal:y,call:F=>m.readAttachment(m.filePath,{maxBytes:n,head:!1,principal:o(m.owner),signal:F}),onOverrun:u("read",m),onStuck:h("read",m)}),S=await E.outcome;if(S.timedOut)return f=E.settled,y.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(y.aborted)return{kind:"failure",status:503,reason:"aborted"};let g=S.value;if(!g.ok&&g.reason!=="too_large")return Vr(g.reason)?(g.reason==="not_found"&&a(m.attachmentId,!1),{kind:"failure",status:qr(g.reason),reason:g.reason,code:g.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(g.ok&&g.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let C=d(m,g.ok?{kind:"exact",bytes:g.bytes.byteLength}:{kind:"over",maxBytes:n}),T=F=>{C==="verified"&&r.set(m.key,F)},x=F=>(T(F),{...F,identity:C});if(!g.ok)return x({kind:"unrenderable",reason:"too_large"});let O=fo(g.bytes);if(O===null)return x({kind:"unrenderable",reason:"signature"});let w=Ro({budgetMs:qe.renderMs,flightSignal:y,call:F=>m.renderer.render(g.bytes,{format:O,maxWidth:m.box.maxWidth,maxHeight:m.box.maxHeight,signal:F}),onOverrun:u("render",m),onStuck:h("render",m)}),v=F=>{if(F.kind==="error")return;let I=Oi(F.value,m.box);"entry"in I&&T(I.entry)},_=null,q=()=>(_===null&&(_=w.settled.then(v),s(m.key,_)),_);y.addEventListener("abort",q,{once:!0});let J=await w.outcome.finally(()=>y.removeEventListener("abort",q));if(J.timedOut||y.aborted)return f=q(),y.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let G=Oi(J.value,m.box);return"entry"in G?x(G.entry):G.failure}finally{f===null?p():f.then(p,p)}}};var $i=()=>{let e=new Map;return{join:(t,r,n)=>{let o=()=>{let s=new AbortController,c=()=>{e.get(t)?.controller===s&&e.delete(t)},u={promise:n(s.signal).finally(c),controller:s,waiters:0};return e.set(t,u),u},a=e.get(t)??o();a.waiters+=1;let i=()=>{a.waiters-=1,!(a.waiters>0)&&(a.controller.abort(),e.get(t)===a&&e.delete(t))};r.aborted?i():r.addEventListener("abort",i,{once:!0});let l=()=>{r.removeEventListener("abort",i)};return a.promise.finally(l)}}};var Vi=10,ad=1/Vi,Ui=1-ad,id=1024,sd=64,ld=8,Bi="private, no-cache",cd="no-store",ud=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),dd=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},qi=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:s}=l,c=(S,g)=>ft({reason:S,limitPerWindow:g,windowMs:6e4,logger:o,windowFields:C=>`viewer=${C} variant=thumbnail`}),d=c("rate_limit",l.rateLimitPerMinute),u=c("revalidation_rate_limit",l.rateLimitPerMinute*Vi),h=lt({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:sd,maxPerOwner:ld,maxWaitMs:qe.queueWaitMs}}),m=Ni({maxBytes:l.cacheBytes,maxEntries:id}),y=$i(),R=Fi({gate:h,cache:m,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),p=(S,g,C,T)=>{let x=`attachment=${S.attachmentId} viewer=${S.internalUserId} variant=thumbnail cache=${T}`;if(g.kind==="failure")return o[dd(g)](`${g.status} ${x} reason=${g.reason} code=${g.code??"-"}`),S.fail(g.status,St[g.status],Ae(g.status));let O=ud[g.identity];if(g.kind==="unrenderable")return o.info(`404 ${x} reason=${g.reason}${O}`),S.fail(404,St[404]);let w=g.identity==="verified"?{"Cache-Control":Bi,ETag:C}:{"Cache-Control":cd},v=new Headers({"Content-Type":g.contentType,"Content-Length":String(g.bytes.byteLength),...w,"Content-Security-Policy":"default-src 'none'; sandbox",...Gt});return S.cookie&&v.append("Set-Cookie",S.cookie),o.info(`200 ${x} type=${g.contentType} bytes=${g.bytes.byteLength}${O}`),new Response(g.bytes,{status:200,headers:v})},f=(S,g)=>{let C=S.spend(g.internalUserId,`attachment=${g.attachmentId} viewer=${g.internalUserId} variant=thumbnail`);return C===null?null:g.fail(C.status,C.message,C.headers)},D=S=>f(d,S),E=(S,g)=>g?f(u,S):D(S);return async(S,g)=>{let{request:C,attachmentId:T,internalUserId:x,readAttachment:O,cookie:w,fail:v}=S,_=to[g],q=C.headers.get("If-None-Match"),J=q!==null,G=E(S,J);if(G)return G;let F=await n(C,"initial");if(!F.ok)return v(503,St[503],Ae(503));let I=await t.getAttachmentForUser(F.scope,T,x),W=I!==null&&jr(I,i)?vi({rendererId:s.id,box:_,attachmentId:T,filePath:I.filePath,fileType:I.fileType,fileSize:I.fileSize}):null;if(W&&oo(q,W.etag)){let b=new Headers({"Cache-Control":Bi,ETag:W.etag,...Gt});return w&&b.append("Set-Cookie",w),o.info(`304 attachment=${T} viewer=${x} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:b})}if(J){let b=D(S);if(b)return b}if(!I)return o.warn(`404 attachment=${T} viewer=${x} variant=thumbnail reason=not_visible`),v(404,St[404]);if(!W)return d.refund(x,Ui),o.info(`404 attachment=${T} viewer=${x} variant=thumbnail reason=not_eligible`),v(404,St[404]);let{key:ce,etag:ne}=W,de=m.get(ce);if(de)return d.refund(x,Ui),p(S,{...de,identity:"verified"},ne,"hit");let Se=b=>R({key:ce,attachmentId:T,filePath:I.filePath,fileSize:I.fileSize,box:_,owner:x,readAttachment:O,renderer:s},b),Q;try{Q=await y.join(ce,C.signal,Se)}catch(b){return o.error(`500 attachment=${T} viewer=${x} variant=thumbnail cache=miss reason=port_exception message=${b instanceof Error?b.message:"unknown"}`),v(500,St[500])}return p(S,Q,ne,"miss")}};var pd='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',md=()=>Br(403,lo,{cookie:null}),ji=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=ro(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>Br(404,Rr[404],{cookie:null}),crossSiteRejection:md}),Wi=e=>{let{authenticate:t,service:r,encodeUserId:n,resolveViewerScope:o,logger:a}=e,i=r.attachmentDelivery,l={service:r,encodeUserId:n,resolveViewerScope:o,logger:a,recordObjectState:ai(r,a)},s=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:di({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:qi({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:c,params:d})=>{let u=null,h=(m,y,R={})=>Br(m,y,{cookie:u,extraHeaders:R});try{let{user:m,cookie:y}=await t(c,{failureRedirect:null});if(u=y??null,!m)return h(401,"Unauthorized");let R=ro(new URL(c.url).searchParams);if(R.kind==="invalid")return h(400,"Invalid attachment request");if(R.kind==="thumbnail"&&c.method!=="GET")return h(405,"Method not allowed",{Allow:"GET"});if(c.method!=="GET"&&c.method!=="HEAD")return h(405,"Method not allowed",{Allow:"GET, HEAD"});if(s===null)return h(404,"Attachment not found");if(d.token===void 0)throw new Error(pd);let p=s.idCodec.decode(d.token);if(p===null||!it(p))return h(400,"Invalid attachment token");let f=await r.getUserIdByExternalId(m.id);if(!f)return h(403,"Forbidden");let D={request:c,delivery:R,attachmentId:p,internalUserId:f,readAttachment:s.read,cookie:u,fail:h};return R.kind!=="thumbnail"?await s.serveOriginal(D):s.serveThumbnail===null?h(404,St[404]):await s.serveThumbnail(D,R.variant)}catch(m){if(m instanceof Response)throw m;return a.error(`500 attachment=? viewer=? reason=unexpected message=${m instanceof Error?m.message:"unknown"}`),h(500,ht)}}};var yd=32*1024*1024,hd=60,fd=4,Rd=120,Sd=2,gd=8*1024*1024,Wr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),bd=e=>{if(e===void 0)throw Ye("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!Wr(e))throw K("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw Ye("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw K("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw K("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},Dd=e=>{if(e===void 0)return null;if(!Wr(e))throw K("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:bd(e.renderer),rateLimitPerMinute:Ne("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,Rd),concurrency:Ne("attachments.thumbnails.concurrency",e.concurrency,1,Sd),cacheBytes:Ne("attachments.thumbnails.cacheBytes",e.cacheBytes,0,gd)})},Yi=e=>{let t=e;if(t===void 0)return null;if(!Wr(t))throw K("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw Ye("attachments.idCodec","injected when attachments is given");if(!Wr(r)||typeof r.encode!="function"||typeof r.decode!="function")throw K("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw Ye("attachments.read","injected when attachments is given");if(typeof n!="function")throw K("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:Ne("attachments.maxBytes",t.maxBytes,1,yd),rateLimitPerMinute:Ne("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,hd),concurrency:Ne("attachments.concurrency",t.concurrency,1,fd),thumbnails:Dd(t.thumbnails)})},Td=Object.freeze([["attachmentIdCodec","attachments.idCodec"],["readAttachment","attachments.read"],["attachmentMaxBytes","attachments.maxBytes"],["attachmentRateLimitPerMinute","attachments.rateLimitPerMinute"],["attachmentConcurrency","attachments.concurrency"],["attachmentThumbnailRenderer","attachments.thumbnails.renderer"],["attachmentThumbnailRateLimitPerMinute","attachments.thumbnails.rateLimitPerMinute"],["attachmentThumbnailConcurrency","attachments.thumbnails.concurrency"],["attachmentThumbnailCacheBytes","attachments.thumbnails.cacheBytes"]]),Yr=e=>{for(let[t,r]of Td)if(Object.hasOwn(e,t))throw Ye(r,`given in place of the flat key ${t}`)};var Gi=8,Ad=8*Gi,Ed=128,wd=2,Ki=wd*Ed,Id=4*Ki,_d=6e4,xd=6e4,Cd="Too many reads",zi=Object.freeze(Object.keys(Ft).filter(e=>Ft[e].admission.includes("miss-gate"))),Ji=e=>{let t=lt({limit:Ad,maxHeldPerOwner:Gi,queue:{max:Id,maxPerOwner:Ki,maxWaitMs:_d}}),r=Me({windowMs:xd,tallies:zi,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`cache_miss_admission_suppressed count=${o} since=${a} viewer=${n} endpoints=${zi.map(l=>`${l}:${i[l]}`).join(",")}`)}});return{admissionFor:(n,o,a)=>({signal:a,acquire:async i=>{let l=await t.acquire(n,i);return l===null&&!i.aborted&&r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=cache_miss_admission`)),l}})}},zr=(e,t,r)=>{let n=e(t,r,{error:{message:Cd}},503);for(let[o,a]of Object.entries(Ae(503)))n.headers.set(o,a);return n};var Qi=e=>{let t=e.get(be.cursorReportHubId),r=e.get(be.cursorBusinessDate),n=e.get(be.cursorSnapshot),o=xa(n)?n:null,a=null;if(t!==null){let l=Xe(t);if(l===null)return{refused:"cursor"};let s={businessDate:r,reportHubId:l};if(!_a(s))return{refused:"cursor"};a=s}else if(r!==null)return{refused:"cursor"};let i=hr(e.get(be.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var Gr=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,Md=2,kd=16,Pd=Md*kd,vd=6e4,Xi=()=>{},Ld=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},Zi=e=>{let t=lt({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:Pd,queue:null}),r=Me({windowMs:vd,tallies:["sse","ids-stream"],writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`streams_per_viewer_suppressed count=${o} since=${a} viewer=${n} routes=sse:${i.sse},ids-stream:${i["ids-stream"]}`)}});return{admit:async(n,o,a)=>{if(n===null)return Xi;if(a.aborted){if(t.canAcquire(n))return Xi}else{let i=await t.acquire(n,a);if(i!==null)return Ld(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var Kr=30,os=4e3,Nd="stream interrupted by server error",Od="Too many streams",Hd=15e3,as=Symbol("ids-stream-heartbeat"),es=()=>{},ts=e=>e.return(void 0).then(es,es),Fd=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(as),Hd)}),stop:()=>clearTimeout(e)}};async function*rs(e,t,r,n){let o=t?ka(e,t):0,a=!0;for(;;){let i=Math.min(o+(a?r:os),e.length),l=zt(e,o,i),s=i>o?e[i-1]:void 0;o=i;let c=o>=e.length;if(yield{kind:"chunk",...l,nextCursor:c||s===void 0?null:{businessDate:s.businessDate,reportHubId:s.reportHubId},isLast:c,...a?{total:e.length}:{},...a?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...a&&n.restarted?{restarted:!0}:{}},a=!1,c)return}}var is=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform",...st});return e&&t.append("Set-Cookie",e),t},ns=(e,t,r,n,o)=>{let a=async(d,u)=>{o(),u&&await ts(t);try{d.close()}catch{}},i=new TextEncoder,l=!1,s=null,c=new ReadableStream({async pull(d){if(l||r.aborted){await a(d,!0);return}let u=Fd();try{s===null&&(s=t.next());let h=await Promise.race([s,u.fired]);if(u.stop(),h===as){if(l||r.aborted){await a(d,!0);return}d.enqueue(i.encode(`
|
|
1
|
+
var ea=e=>{throw TypeError(e)};var ta=(e,t,r)=>t.has(e)||ea("Cannot "+r);var nr=(e,t,r)=>(ta(e,t,"read from private field"),r?r.call(e):t.get(e)),wn=(e,t,r)=>t.has(e)?ea("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),In=(e,t,r,n)=>(ta(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var vt=e=>typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"||e===null||e===void 0?String(e):Array.isArray(e)?"array":typeof e,K=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${vt(r)}`),Ye=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),_n=(e,t,r)=>K(e,`one of ${r.map(n=>JSON.stringify(n)).join(", ")}`,t),ie=(e,t,r,n)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r&&(n===void 0||t<=n))return t;throw K(e,n===void 0?`an integer >= ${r}`:`an integer from ${r} to ${n}`,t)},Ne=(e,t,r,n)=>t===void 0?n:ie(e,t,r),or=(e,t)=>{if(t===void 0)throw Ye(e,"a function");if(typeof t!="function")throw K(e,"a function",t);return t};var se=()=>Math.floor(performance.now());var xn=Object.freeze({defaultTtlMs:6e4,maxBuckets:4096,maxBytes:512*1024*1024}),Qe=class extends Error{constructor(t){super(`cache miss refused (${t})`),this.name="SqlResultCacheMissRefusal",this.reason=t}},Cn=e=>({async getEpoch(t){try{let r=await e?.getClient();if(!r)return null;let n=await r.get(t);return n?Number(n):0}catch{return null}},async incrementEpoch(t){try{let r=await e?.getClient();if(!r)return;await r.incr(t)}catch{}}}),ar=(e,t)=>t?e.map(r=>structuredClone(r)):e,bc=8,Dc=32,Tc=24,Ac=16,Ec=-(2**30),wc=2**30-1,Ic=e=>Number.isInteger(e)&&e>=Ec&&e<=wc&&!Object.is(e,-0),_c=(e,t)=>{let r=0,n=[e];for(;n.length>0&&r<=t;){let o=n.pop();if(r+=Dc,ArrayBuffer.isView(o)){r+=o.byteLength;continue}let a=Array.isArray(o)?o:Object.keys(o).map(i=>o[i]);r+=bc*a.length;for(let i of a)typeof i=="string"?r+=Tc+2*i.length:typeof i=="number"&&!Ic(i)?r+=Ac:typeof i=="object"&&i!==null&&n.push(i)}return r},ir=class{constructor(t,r){this.epochStore=r;this.buckets=new Map;this.totalBytes=0;this.inFlight=new Map;this.forcedFetches=new Map;this.maybeRefreshAhead=t=>{let r=t.refreshAheadRatio;if(r===void 0)return;let{cacheKey:n}=t,o=this.buckets.get(n);if(!o)return;let a=t.ttlMsOverride??this.defaultTtlMs;if(a-(o.expireAt-se())<a*r||this.inFlight.has(n))return;let l;l=(async()=>{let s=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,c=await t.fetcher();return this.inFlight.get(n)===l&&this.writeBucket(n,{records:c,expireAt:se()+a,epoch:s}),c})(),this.inFlight.set(n,l),l.catch(()=>{}).finally(()=>{this.inFlight.get(n)===l&&this.inFlight.delete(n)})};this.startFetch=(t,r)=>{let{cacheKey:n,admission:o}=t,a;a=(async()=>{let l=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,s=o===void 0?null:await o.acquire(o.signal);if(o!==void 0&&s===null)throw new Qe(o.signal.aborted?"aborted":"busy");try{for(let d of r)d();let c=await t.fetcher();return this.inFlight.get(n)===a&&this.writeBucket(n,{records:c,expireAt:se()+(t.ttlMsOverride??this.defaultTtlMs),epoch:l}),c}finally{s?.()}})(),this.inFlight.set(n,a);let i=()=>{this.inFlight.get(n)===a&&this.inFlight.delete(n)};return a.then(i,i),a};this.forcedFetch=t=>{let{cacheKey:r}=t,n=t.onFetchStart===void 0?[]:[t.onFetchStart],o=this.forcedFetches.get(r);if(o===void 0)return this.runForcedFetch(t,n);if(o.pending===null){let a=[],i=()=>this.runForcedFetch(t,a);o.pending={promise:o.running.then(i,i),onFetchStarts:a}}return o.pending.onFetchStarts.push(...n),o.pending.promise};this.runForcedFetch=(t,r)=>{let{cacheKey:n}=t,o=this.startFetch(t,r);this.forcedFetches.set(n,{running:o,pending:null});let a=()=>{let i=this.forcedFetches.get(n);i?.running===o&&i.pending===null&&this.forcedFetches.delete(n)};return o.then(a,a),o};this.getOrFetch=async t=>{let{cacheKey:r,forceRefresh:n,snapshot:o,admission:a}=t;if(n){if(a?.signal.aborted)throw new Qe("aborted");return this.dropBucket(r),ar(await this.readOwnOrRetry(this.forcedFetch(t),t),o)}let i=this.buckets.get(r);if(i&&i.expireAt>se())if(t.epochKey){let s=await this.epochStore.getEpoch(t.epochKey);if(s===null||i.epoch===s)return this.maybeRefreshAhead(t),ar(i.records,o);this.dropBucket(r)}else return this.maybeRefreshAhead(t),ar(i.records,o);let l=this.inFlight.get(r);if(l!==void 0)return ar(await this.readOwnOrRetry(l,t),o);if(a?.signal.aborted)throw new Qe("aborted");return ar(await this.startFetch(t,t.onFetchStart===void 0?[]:[t.onFetchStart]),o)};this.readOwnOrRetry=async(t,r)=>{try{return await t}catch(n){let{admission:o}=r;if(!(n instanceof Qe&&(o===void 0||n.reason==="aborted"&&!o.signal.aborted)))throw n;return this.getOrFetch({...r,snapshot:!1})}};this.clearAll=()=>{this.buckets.clear(),this.totalBytes=0,this.inFlight.clear()};this.invalidatePrefix=t=>{for(let r of this.buckets.keys())r.startsWith(t)&&this.dropBucket(r);for(let r of this.inFlight.keys())r.startsWith(t)&&this.inFlight.delete(r)};this.defaultTtlMs=Ne("cacheDefaultTtlMs",t.defaultTtlMs,1,xn.defaultTtlMs),this.maxBuckets=Ne("cacheMaxBuckets",t.maxBuckets,1,xn.maxBuckets),this.maxBytes=Ne("cacheMaxBytes",t.maxBytes,1,xn.maxBytes),this.lastSweepAt=se()}dropBucket(t){let r=this.buckets.get(t);r!==void 0&&(this.buckets.delete(t),this.totalBytes-=r.bytes)}writeBucket(t,r){this.dropBucket(t);let n=_c(r.records,this.maxBytes);if(n>this.maxBytes)return;this.buckets.set(t,{...r,bytes:n}),this.totalBytes+=n;let o=se();o-this.lastSweepAt>=this.defaultTtlMs&&this.sweepExpired(o);for(let a of this.buckets.keys()){if(this.buckets.size<=this.maxBuckets&&this.totalBytes<=this.maxBytes)break;this.dropBucket(a)}}sweepExpired(t){this.lastSweepAt=t;for(let[r,n]of this.buckets)n.expireAt<=t&&this.dropBucket(r)}};import{crossOriginRefusal as rm}from"@aiquants/request-isolation";var xc=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var ra=e=>e<10?`0${e}`:`${e}`,Cc=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=ra(e.getMonth()+1),n=ra(e.getDate());return`${t}-${r}-${n}`},jt=e=>{let t=xc.exec(e);if(t===null)return null;let[,r,,n,o]=t,a=Number(r),i=Number(n),l=Number(o);if(a<1)return null;let s=new Date(0);return s.setUTCFullYear(a,i-1,l),s.getUTCFullYear()!==a||s.getUTCMonth()!==i-1||s.getUTCDate()!==l?null:`${r}-${n}-${o}`},Pr=e=>jt(e)===e;var Ve=e=>e==null?null:e instanceof Date?Cc(e):jt(e);import{z as Mc}from"zod/v3";var it=e=>Number.isSafeInteger(e)&&e>0,Oe=Mc.number().int().positive().max(Number.MAX_SAFE_INTEGER);import{z as ee}from"zod/v3";var vr=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|-[1-9][0-9]{0,15})$/;var Mn=/^[0-9a-f]{64}$/u;var Lt=e=>typeof e=="string"&&Mn.test(e);var Nt=Symbol("daily-report wire mismatch"),ze=(e,t,r)=>(e.issues.push({...r,path:t===null?[...e.path]:[...e.path,t]}),Nt),ia=e=>e===null?"null":Array.isArray(e)?"array":Number.isNaN(e)?"nan":typeof e,Et=(e,t)=>({code:"invalid_type",expected:e,received:ia(t)}),kc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Pc=e=>{let t=0;for(let r in e)t+=1;return t},na=(e,t,r)=>{let n={};for(let o=0;o<r;o+=1){let a=t[o];a in e&&(n[a]=e[a])}return n},Wt=e=>{let t=Object.keys(e),r=Object.values(e);return(n,o)=>{if(!kc(n))return ze(o,null,Et("object",n));let a=null,i=!1,l=0;for(let s=0;s<t.length;s+=1){let c=t[s],d=n[c];d!==void 0&&(l+=1);let u=r[s](d,o,c);if(u===Nt){i=!0;continue}a===null&&u!==d&&(a=na(n,t,s)),a!==null&&(u!==void 0||c in n)&&(a[c]=u)}return i?Nt:a!==null?a:Pc(n)===l?n:na(n,t,t.length)}},sr=e=>(t,r,n)=>{r.path.push(n);let o=e(t,r);return r.path.pop(),o},lr=e=>(t,r,n)=>{if(!Array.isArray(t))return ze(r,n,Et("array",t));r.path.push(n);let o=t,a=!1;for(let i=0;i<t.length;i+=1){let l=t[i],s=e(l,r,i);s===Nt?a=!0:s!==l&&(o===t&&(o=t.slice()),o[i]=s)}return r.path.pop(),a?Nt:o},pe=(e,t,r)=>e==null||typeof e=="string"?e:ze(t,r,Et("string",e)),oa=(e,t,r)=>e===null||typeof e=="string"?e:ze(t,r,Et("string",e)),aa=(e,t,r)=>typeof e=="string"?e:ze(t,r,Et("string",e)),vc=(e,t,r)=>e===null||typeof e=="number"&&!Number.isNaN(e)?e:ze(t,r,Et("number",e)),cr=(e,t,r)=>typeof e=="boolean"?e:ze(t,r,Et("boolean",e)),sa=(e,t,r)=>typeof e!="string"?ze(t,r,Et("string",e)):Lt(e)?e:ze(t,r,{code:"invalid_string",validation:"regex",message:"a content digest is 64 lowercase hex digits"}),Lc=(e,t,r)=>e===null?null:sa(e,t,r),kn=(e,t,r)=>{if(typeof e=="number"&&it(e))return e;for(let{message:n,path:o,...a}of Oe.safeParse(e).error.issues)ze(t,r,a);return Nt},la={present:!0,absent:!0,unknown:!0},ca=Object.keys(la),Nc=ca.map(e=>`'${e}'`).join(" | "),Oc=(e,t,r)=>typeof e!="string"?ze(t,r,{code:"invalid_type",expected:Nc,received:ia(e)}):Object.hasOwn(la,e)?e:ze(t,r,{code:"invalid_enum_value",received:e,options:[...ca]}),ua=Wt({name:pe,affiliation:pe}),da=Wt({name:pe,text:pe,color:pe}),pa=Wt({id:kn,name:pe,color:pe}),ma=Wt({id:kn,userId:pe,userName:pe,content:pe,createdAt:pe,isMine:cr}),Hc=Wt({id:aa,fileName:aa,fileType:oa,fileSize:vc,createdAt:oa,state:Oc,hasThumbnail:cr}),Fc=Wt({reportHubId:kn,date:pe,createdAt:pe,author:pe,userId:pe,sourceType:pe,employeeName:pe,updatedBy:pe,updatedAt:pe,category:pe,creationCategory:pe,visitTimeFrom:pe,visitTimeTo:pe,customerName:pe,interviewers:lr(sr(ua)),subject:pe,content:pe,externalComments:lr(sr(da)),isRead:cr,isStarred:cr,contentDigest:sa,readContentDigest:Lc,isDraft:cr,labels:lr(sr(pa)),postedComments:lr(sr(ma)),attachments:lr(sr(Hc))}),ur=(e,t)=>{let r={path:[],issues:[]},n=e(t,r);return n===Nt?{ok:!1,issues:r.issues}:{ok:!0,value:n}},ya=e=>ur(Fc,e),ha=e=>ur(ua,e),fa=e=>ur(da,e),Ra=e=>ur(pa,e),Sa=e=>ur(ma,e);var ga=15e3,ba="lastEventId",$c=/^\d{1,15}-\d{1,15}$/,Da=e=>$c.test(e),wt="0-0",dr=e=>ee.unknown().transform((t,r)=>{let n=e(t);if(n.ok)return n.value;for(let o of n.issues)r.addIssue({...o,fatal:!0});return ee.NEVER}),hh=dr(ha),fh=dr(fa),Rh=dr(Ra),Uc=dr(Sa),pr=dr(ya),mr=ee.string().regex(vr),Ta=ee.object({type:ee.literal("connected")}),Aa=ee.object({type:ee.literal("status-update"),reportHubId:Oe,statusType:ee.enum(["star","read"]),value:ee.boolean(),readContentDigest:ee.string().regex(Mn).nullable(),clientTempId:mr}),Pn=ee.string(),Ea=ee.object({type:ee.literal("comment-add"),reportHubId:Oe,comment:Uc,clientTempId:mr,sourceType:Pn}),wa=ee.object({type:ee.literal("comment-delete"),reportHubId:Oe,commentId:Oe,clientTempId:mr,sourceType:Pn}),Lr={recipientRawUserId:Oe.optional()},vn=Aa.extend(Lr),Ln=Ea.extend(Lr),Nn=wa.extend(Lr),Yt={reportHubId:Oe,report:pr,clientTempId:mr},On={...Lr,actorRawUserId:Oe},Hn={viewerIsActor:ee.boolean()},Bc=ee.object({type:ee.literal("report-create"),...Yt,...Hn}),Vc=ee.object({type:ee.literal("report-update"),...Yt,...Hn}),qc=ee.object({type:ee.literal("report-publish"),...Yt,...Hn}),Fn=ee.object({type:ee.literal("report-create"),...Yt,...On}),$n=ee.object({type:ee.literal("report-update"),...Yt,...On}),Un=ee.object({type:ee.literal("report-publish"),...Yt,...On}),Nr=ee.object({type:ee.literal("report-delete"),reportHubId:Oe,clientTempId:mr,sourceType:Pn}),Sh=ee.discriminatedUnion("type",[Ta,Aa,Ea,wa,Bc,Vc,qc,Nr]),Bn=ee.discriminatedUnion("type",[Ta,vn,Ln,Nn,Fn,$n,Un,Nr]);var Ia="ids-columns";var jc=/^[0-9a-f]{1,16}$/,_a=e=>it(e.reportHubId)&&(e.businessDate===null||Pr(e.businessDate)),xa=e=>typeof e=="string"&&jc.test(e),Th=Object.freeze({kind:"absent"}),Ah=Object.freeze({kind:"value",value:null});var zt=(e,t,r)=>{let n=[],o=[],a=[],i=[],l=[],s=new Map;for(let c=t;c<r;c++){let{reportHubId:d,businessDate:u,sourceType:h}=e[c];n.push(d),o.length>0&&o[o.length-1]===u?a[a.length-1]+=1:(o.push(u),a.push(1));let m=h===void 0?null:h,y=s.get(m);y===void 0&&(y=i.length,i.push(m),s.set(m,y)),l.push(y)}return{ids:n,dates:o,counts:a,sourceTypes:i,sources:l}},Or=e=>{let t=2166136261,r=-624069552;for(let n of e){let o=n.reportHubId;t^=o&255,t=Math.imul(t,16777619),t^=o>>>8&255,t=Math.imul(t,16777619),t^=o>>>16&255,t=Math.imul(t,16777619),t^=o>>>24&255,t=Math.imul(t,16777619),r^=o>>>24&255,r=Math.imul(r,16777619),r^=o>>>16&255,r=Math.imul(r,16777619),r^=o>>>8&255,r=Math.imul(r,16777619),r^=o&255,r=Math.imul(r,16777619);let a=n.businessDate;if(a===null)t^=1,t=Math.imul(t,16777619),r^=1,r=Math.imul(r,16777619);else for(let i=0;i<a.length;i++){let l=a.charCodeAt(i);t^=l&255,t=Math.imul(t,16777619),r^=l&255,r=Math.imul(r,16777619)}}return t^=e.length,t=Math.imul(t,16777619),r^=e.length,r=Math.imul(r,16777619),((t>>>0).toString(16).padStart(8,"0")+(r>>>0).toString(16).padStart(8,"0")).replace(/^0+(?=.)/,"")},Ca=(e,t,r,n)=>e!==r?e===null?1:r===null||e>r?-1:1:n-t,Wc=(e,t,r,n)=>Ca(e,t,r,n)<0,Vn=(e,t)=>Ca(e.businessDate,e.reportHubId,t.businessDate,t.reportHubId),Ma=e=>{for(let t=1;t<e.length;t++)if(!Wc(e[t-1].businessDate,e[t-1].reportHubId,e[t].businessDate,e[t].reportHubId))return!1;return!0},ka=(e,t)=>{let r=e.findIndex(n=>Vn({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var le=Object.freeze({businessDate:"business-date",idsStream:Ia,report:"report",search:"search",reports:"reports",searchMarks:"search-marks",searchFacets:"search-facets",action:"action"}),be=Object.freeze({businessDate:"businessDate",reportHubId:"reportHubId",searchQuery:"q",searchCombine:"combine",searchAuthor:"author",searchSourceType:"sourceType",searchCustomer:"customer",reportIds:"ids",forceRefresh:"forceRefresh",cursorReportHubId:"cursor_report_hub_id",cursorBusinessDate:"cursor_business_date",cursorSnapshot:"cursor_snapshot"});var Pa=(e,t,r=console)=>{let n=o=>typeof o=="string"?[`${t} ${o}`]:[t,o];return{debug:(o,...a)=>{e<=0&&r.debug(...n(o),...a)},info:(o,...a)=>{e<=1&&r.info(...n(o),...a)},warn:(o,...a)=>{e<=2&&r.warn(...n(o),...a)},error:(o,...a)=>{e<=3&&r.error(...n(o),...a)}}},_h=Object.freeze(["API","Action","Attachment","ExternalSource","Isolation","Reads","Refresh","Search","SSE","SseReader","Server","Service","Streams","Visibility","ActionProvider","DetailLoader","IdsStream","SseConnection","SessionGate"]),va=e=>`[DailyReport${e}]`,De=(e,t,r)=>e===void 0?Pa(t,va(r)):Pa(0,va(r),e);import{z as Ot}from"zod/v3";var yr=e=>({reportHubId:e,outcome:"not_found"}),Ph=Ot.discriminatedUnion("outcome",[Ot.object({reportHubId:Oe,outcome:Ot.literal("ok"),report:pr}).strict(),Ot.object({reportHubId:Oe,outcome:Ot.literal("not_found")}).strict(),Ot.object({reportHubId:Oe,outcome:Ot.literal("failed")}).strict()]);var Yc="legacy-",qn=e=>`${Yc}${e}`;var zc=/^[1-9][0-9]*$/,Gc=/^(?:0|[1-9][0-9]*)$/,Xe=e=>{if(e===null||!zc.test(e))return null;let t=Number(e);return it(t)?t:null},jn=e=>{if(e===null||!Gc.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},Wn=e=>e==="true"?!0:e==="false"?!1:null,hr=e=>e===null?!1:Wn(e);var La=Object.freeze(["subject","content","author","employeeName","updatedBy","category","creationCategory","customerName"]),mt=Object.freeze({field:e=>e,interviewer:(e,t)=>`interviewer:${e}:${t}`,attachment:e=>`attachment:${e}`,comment:(e,t)=>`comment:${e}:${t}`});var Kc=16777619,Yn=2166136261,zn=(e,t,r,n)=>{let o=e;for(let a=r;a<n;a++)o^=t.charCodeAt(a),o=Math.imul(o,Kc);return o>>>0},Na=e=>zn(Yn,e,0,e.length),Jc=String.fromCodePoint(3),Qc=String.fromCodePoint(2),Xc=String.fromCodePoint(1),Hr=e=>Na(e.map(t=>t.map(r=>r.map(n=>`${n.tier}${n.text}`).join(Jc)).join(Qc)).join(Xc));var Oa=e=>e==="intersection"||e==="union",Ce=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),Gn=2,Fr=2,Ht=Object.freeze({word:0,reading:1});var Kn=(e,t)=>({ids:e.map(r=>r.reportHubId),businessDates:e.map(r=>r.businessDate),sourceTypes:e.map(r=>r.sourceType),words:t});var Fh=2*(1+Gn);import{z as Vh}from"zod/v3";var Ha=e=>e.issues.map(t=>`${t.path.length===0?"(root)":t.path.join(".")}: ${t.code}`).join("; ");var we=Object.freeze({intent:"intent",clientTempId:"clientTempId",businessDate:"businessDate",operationTimestamp:"operationTimestamp",reportHubId:"reportHubId",title:"title",content:"content",isStarred:"isStarred",isRead:"isRead",contentDigest:"contentDigest",commentId:"commentId"});var $r=Math.max(1,Math.floor(10.556701030927835));var Ze=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var Me=e=>{let{windowMs:t,tallies:r,writeSuppressed:n}=e,o=new Map,a=i=>{let l={since:new Date().toISOString(),count:0,tallies:Object.fromEntries(r.map(c=>[c,0]))};o.set(i,l),Ze(()=>{o.delete(i),l.count>0&&n(i,l)},t)};return{record:(i,l,s)=>{let c=o.get(i);if(c!==void 0){c.count+=1,c.tallies[l]+=1;return}s(),a(i)}}};var yt=Object.freeze({maxValuesPerFacet:16,maxValueLength:200,maxTotalValueLength:300});var Gh=Object.freeze({authors:Object.freeze([]),sourceTypes:Object.freeze([]),customers:Object.freeze([])}),Zc=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Jn=e=>{let t=e.trim();return t.length===0?null:t.replace(Zc,"\uFFFD")},eu=e=>{let t=Jn(e);return t===null?"filter-blank-value":t!==e?"filter-value-not-canonical":e.length>yt.maxValueLength?"filter-value-too-long":null},tu=e=>{if(e.length>yt.maxValuesPerFacet)return"filter-too-many-values";let t=new Set;for(let r of e){let n=eu(r);if(n!==null)return n;if(t.has(r))return"filter-duplicate-value";t.add(r)}return null},ru=e=>{let t=0;for(let r of e.authors)t+=r.length;for(let r of e.customers)t+=r.length;return t},Fa=e=>{for(let t of[e.authors,e.sourceTypes,e.customers]){let r=tu(t);if(r!==null)return r}return ru(e)>yt.maxTotalValueLength?"filters-too-long":null};var $a=e=>e.trim().length===0;var Qn=e=>e!==null&&vr.test(e)?e:null,Xn=e=>Oa(e)?e:null,Zn=e=>{if(e===null)return null;let t=e.split(",");if(t.length>Ce.maxDetailIds)return null;let r=[];for(let n of t){let o=Xe(n);if(o===null||r.includes(o))return null;r.push(o)}return r},Ua=e=>{let[t,...r]=e;return t===void 0?null:[t,...r]},Ba=(e,t)=>{let r={authors:e.getAll(be.searchAuthor),sourceTypes:e.getAll(be.searchSourceType),customers:e.getAll(be.searchCustomer)},n=Fa(r);if(n!==null)return{ok:!1,reason:n};let o=new Set(t.map(i=>i.toLowerCase())),a=new Set;for(let i of r.sourceTypes){let l=i.toLowerCase();if(!o.has(l))return{ok:!1,reason:"filter-unknown-source-type"};if(a.has(l))return{ok:!1,reason:"filter-duplicate-value"};a.add(l)}return{ok:!0,filters:{sourceTypes:a.size===0?null:a,authors:Ua(r.authors),customers:Ua(r.customers)}}},Va=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var ja=Object.freeze({status:400,error:"Invalid form"}),Wa=e=>({status:413,error:"Form too large",measuredBy:e}),nu=(e,t,r)=>{let n=0;return e.pipeThrough(new TransformStream({transform(o,a){if(n+=o.byteLength,n>t){r(),a.error(new Error(`action form body exceeds ${t} bytes`));return}a.enqueue(o)}}))},ou=async e=>{let t=jn(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:Wa("declared")};let r=!1,n=e.body===null?null:nu(e.body,1048576,()=>{r=!0}),o=new Headers,a=e.headers.get("Content-Type");a!==null&&o.set("Content-Type",a);let i;try{i=await new Response(n,{headers:o}).formData()}catch{return{refusal:r?Wa("counted"):ja}}let l=Va(i);return l===null?{refusal:ja}:{fields:l}},za=(e,t)=>{let r=e.get(t);if(r===null)return{error:`${t} required`};let n=Wn(r);return n===null?{error:`Invalid ${t}`}:{value:n}},au=(e,t)=>{let r=za(e,we.isStarred);return"error"in r?r:{command:{...t,intent:"toggleStar",value:r.value}}},iu=(e,t)=>{let r=za(e,we.isRead);if("error"in r)return r;let n=e.get(we.contentDigest);return r.value?n===null?{error:`${we.contentDigest} required`}:Lt(n)?{command:{...t,intent:"toggleRead",value:!0,contentDigest:n}}:{error:`Invalid ${we.contentDigest}`}:n===null?{command:{...t,intent:"toggleRead",value:!1}}:{error:`${we.contentDigest} is not allowed when ${we.isRead} is false`}},Ga=Object.freeze({update:(e,t,r)=>{let n=e.get(we.title),o=e.get(we.content);if(n!==null&&n.length>r.titleMaxLength)return{error:"Invalid title"};let a={};return n!==null&&(a.title=n),o!==null&&(a.content=o),{command:{...t,intent:"update",changes:a}}},publish:(e,t)=>({command:{...t,intent:"publish"}}),delete:(e,t)=>({command:{...t,intent:"delete"}}),toggleStar:au,toggleRead:iu,addComment:(e,t)=>{let r=e.get(we.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=Xe(e.get(we.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),su=e=>Object.hasOwn(Ga,e),lu=(e,t)=>{let r=e.get(we.intent),n=e.get(we.businessDate),o=n===null?null:jt(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get(we.operationTimestamp),i=jn(a);if(a!==null&&i===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get(we.clientTempId);if(!l)return{error:"clientTempId required"};let s=Qn(l);if(s===null)return{error:"Invalid clientTempId"};if(r==="create")return o===null?{error:"businessDate required"}:{command:{intent:r,clientTempId:s,businessDate:o,operationTimestamp:i}};let c=Xe(e.get(we.reportHubId));return c===null?{error:"Invalid reportHubId"}:r===null||!su(r)?{error:"Invalid intent"}:Ga[r](e,{clientTempId:s,businessDate:o,operationTimestamp:i,reportHubId:c},t)},Ka=async(e,t)=>{let r=await ou(e);if("refusal"in r)return r;let n=lu(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},cu=6e4,uu="form_too_large",Ya=["declared","counted"],Ja=e=>{let t=Me({windowMs:cu,tallies:Ya,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${Ya.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(uu,r,n)}};var Ft=Object.freeze({[le.businessDate]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[le.idsStream]:{body:"stream",admission:["refresh-bucket","stream-slots","cache","miss-gate"]},[le.report]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[le.search]:{body:"json",cache:"etag",admission:["search-limiter"]},[le.reports]:{body:"json",cache:"etag",admission:["search-limiter"]},[le.searchMarks]:{body:"json",cache:"no-store",admission:["search-limiter"]},[le.searchFacets]:{body:"json",cache:"etag",admission:["search-limiter"]}}),Qa=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),eo=e=>e!==void 0&&Object.hasOwn(Ft,e);var to=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),Xa=e=>Object.hasOwn(to,e);var du="download",pu="thumbnail",mu="1";var ro=e=>{let t=e.getAll(pu),r=e.getAll(du);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&Xa(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===mu?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};import{NO_CROSS_ORIGIN_NAVIGATION as Ru}from"@aiquants/request-isolation";import{createHash as yu}from"crypto";var no=e=>`"${yu("sha256").update(e).digest("hex")}"`,Za=e=>no(JSON.stringify(e));var st=Object.freeze({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'"}),oo=(e,t)=>{if(e===null)return!1;for(let r of e.split(",")){let n=r.trim();if((n.startsWith("W/")?n.slice(2):n)===t)return!0}return!1},ei=(e,t,r,n=200)=>{let o=JSON.stringify(r),a=no(o),i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate",ETag:a,...st});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&oo(e.headers.get("If-None-Match"),a)?new Response(null,{status:304,headers:i}):new Response(o,{status:n,headers:i})},ao=(e,t,r)=>{let n=new Headers({...t===null?{}:{"Content-Type":"application/json"},"Cache-Control":"no-store",...st});return e&&n.append("Set-Cookie",e),new Response(t===null?null:JSON.stringify(t),{status:r,headers:n})},io=e=>(t,r,n,o)=>{if(o!==200)return ao(r,n,o);if(e===null||n===null)throw new Error(`[daily-report] API route: a 200 JSON answer needs an answer of a JSON 200 and a body; got ${e===null?"a responder without one":"an answer"} and ${n===null?"no body":"a body"}`);return e(t,r,n)},hu=5e3/1e3,fu=new Map([[503,hu]]),Ae=e=>{let t=fu.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var lo="Cross-site request rejected",Su="Not Found",ti=["api","action","sse","attachment"],ri=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...st}}),gu=()=>ri(403,lo),Ur=()=>ri(404,Su),fr=Object.freeze({...Ru,frameworkDataRefusal:()=>null,crossSiteRejection:gu}),ni=e=>new URL(e.url).pathname.endsWith(".data"),bu=6e4,Du="refusals",Tu=32,Au=/^[a-z-]+$/,so=e=>{if(e===null)return"-";let t=e.slice(0,Tu);return Au.test(t)&&t===e?e:JSON.stringify(t)},oi=e=>{let t=Me({windowMs:bu,tallies:ti,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${ti.map(i=>`${i}:${a[i]}`).join(",")}`)}});return(r,n,o)=>{let a=()=>{let{headers:i}=o;e.warn(`cross_site_rejected route=${r} reason=${n} site=${so(i.get("Sec-Fetch-Site"))} mode=${so(i.get("Sec-Fetch-Mode"))} dest=${so(i.get("Sec-Fetch-Dest"))} method=${o.method}`)};t.record(Du,r,a)}};var ai=(e,t)=>(r,n)=>{let o=n?"markAttachmentPresent":"markAttachmentMissing";e[o](r).catch(a=>{t.error(`${o} failed attachment=${r} message=${a instanceof Error?a.message:"unknown"}`)})};var Eu="same-origin",wu="SAMEORIGIN",Gt=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":Eu,"X-Frame-Options":wu}),Br=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...Gt});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},ii=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),Iu=/^[\x20-\x7E]+$/,_u=/^[\w.+-]+\/[\w.+-]+/,co=e=>e&&Iu.test(e)&&_u.test(e)?e:null,xu=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,si=e=>encodeURIComponent(e.replace(xu,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),li=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),Rr={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},ci={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},Vr=e=>typeof e=="string"&&Object.hasOwn(ci,e),qr=e=>ci[e],ht="Attachment request failed";var lt=e=>{let t=ie("limit",e.limit,1),r=ie("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:ie("queue.max",e.queue.max,0),maxPerOwner:ie("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:ie("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],i=new Map,l=new Map,s=(p,f)=>p.get(f)??0,c=(p,f,D)=>{let E=s(p,f)+D;E<=0?p.delete(f):p.set(f,E)},d=p=>s(l,p)<r,u=p=>o<t&&d(p),h=p=>(o+=1,c(l,p,1),R(p)),m=()=>{let p=-1,f=r;for(let[D,E]of a.entries()){let S=s(l,E.owner);if(S<f&&(p=D,f=S,S===0))break}return p},y=()=>{for(;o<t;){let p=m();if(p<0)return;let[f]=a.splice(p,1);c(i,f.owner,-1),f.grant(h(f.owner))}},R=p=>{let f=!1;return()=>{f||(f=!0,o-=1,c(l,p,-1),y())}};return{canAcquire:u,acquire:(p,f)=>{if(f.aborted)return Promise.resolve(null);if(u(p))return Promise.resolve(h(p));if(n===null||a.length>=n.max||s(i,p)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:D}=n,E=S=>{let g=()=>{let O=a.indexOf(x);O<0||(a.splice(O,1),c(i,p,-1),T(),S(null))},C=Ze(g,D),T=()=>{clearTimeout(C),f.removeEventListener("abort",g)},x={owner:p,grant:O=>{T(),S(O)}};a.push(x),c(i,p,1),f.addEventListener("abort",g,{once:!0})};return new Promise(E)}}};var Cu=1024,uo="Too many requests",Mu=(e,t)=>{ie("limitPerWindow",e,1),ie("windowMs",t,1);let r=new Map,n=(a,i)=>{i<=a.lastRefillMs||(a.tokens=Math.min(e,a.tokens+(i-a.lastRefillMs)*e/t),a.lastRefillMs=i)},o=(a,i)=>{let l=r.get(a);l&&r.delete(a);let s=l??{tokens:e,lastRefillMs:i};n(s,i),r.set(a,s);for(let c of r.keys()){if(r.size<=Cu)break;r.delete(c)}return s};return{consume:(a,i)=>{let l=o(a,i);return l.tokens<1?!1:(l.tokens-=1,!0)},refund:(a,i,l)=>{let s=r.get(a);s&&(n(s,i),s.tokens=Math.min(e,s.tokens+l))}}},ft=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(ie("windowMs",r,1e3)%1e3!==0)throw K("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=Mu(e.limitPerWindow,r),i=Object.freeze({status:429,message:uo,headers:Object.freeze({"Retry-After":String(r/1e3)})}),l=Me({windowMs:r,tallies:[t],writeSuppressed:(s,{count:c,since:d})=>{n.warn(`${t}_suppressed count=${c} since=${d} ${o(s)}`)}});return{spend:(s,c)=>a.consume(s,se())?null:(l.record(s,t,()=>n.warn(`429 ${c} reason=${t}`)),i),refund:(s,c)=>{a.refund(s,se(),c)}}};var Pu=256*1024,ui=6e4,vu=e=>Math.ceil(e/2),Lu=new Uint8Array(new ArrayBuffer(0)),Nu=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=Lu,t()},i=l=>{clearTimeout(o),o=Ze(()=>{l.error(new Error(`attachment body idle for ${ui} ms`)),a()},ui)};return new ReadableStream({start(l){i(l)},pull(l){let s=Math.min(n+Pu,r.byteLength);if(s>n&&l.enqueue(r.slice(n,s)),n=s,n>=r.byteLength){l.close(),a();return}i(l)},cancel(){a()}},{highWaterMark:0})},di=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=ft({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:s=>`viewer=${s}`}),l=lt({limit:e.concurrency,maxHeldPerOwner:vu(e.concurrency),queue:null});return async s=>{let{request:c,delivery:d,attachmentId:u,internalUserId:h,readAttachment:m,cookie:y,fail:R}=s,p=e.maxBytes,f=i.spend(h,`attachment=${u} viewer=${h}`);if(f)return R(f.status,f.message,f.headers);let D=await n(c,"initial");if(!D.ok)return R(503,Rr[503],Ae(503));let E=await t.getAttachmentForUser(D.scope,u,h);if(!E)return o.warn(`404 attachment=${u} viewer=${h} reason=not_visible`),R(404,"Attachment not found");if(E.fileSize!=null&&E.fileSize>p)return o.warn(`413 attachment=${u} viewer=${h} reason=db_size`),R(413,"Attachment too large");let S=co(E.fileType),g=`filename="${li(E.fileName)}"; filename*=UTF-8''${si(E.fileName)}`,C=await l.acquire(h,c.signal);if(!C)return c.signal.aborted?(o.info(`503 attachment=${u} viewer=${h} reason=aborted`),R(503,"Attachment request aborted")):(o.warn(`503 attachment=${u} viewer=${h} reason=concurrency`),R(503,"Too many concurrent downloads",Ae(503)));let T=!1;try{let x=await m(E.filePath,{maxBytes:p,head:c.method==="HEAD",principal:r(h),signal:c.signal});if(c.signal.aborted)return o.info(`503 attachment=${u} viewer=${h} reason=aborted`),R(503,"Attachment request aborted");if(!x.ok){if(!Vr(x.reason))return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=failure_reason`),R(500,ht);let F=qr(x.reason);return x.reason==="not_found"&&a(u,!1),o.warn(`${F} attachment=${u} viewer=${h} reason=${x.reason} code=${x.code??"-"}`),R(F,Rr[F],Ae(F))}if(x.bytes.byteLength>p)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=over_max_bytes`),R(500,ht);let O=c.method==="HEAD";if(O&&x.size!==void 0&&x.size>p)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=over_max_bytes`),R(500,ht);if(!O&&x.size!==void 0&&x.size!==x.bytes.byteLength)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=size_mismatch`),R(500,ht);let w=S??co(x.contentType),v=w!==null&&ii.has(w),_=v?w:"application/octet-stream",q=v&&d.kind!=="download"?"inline":"attachment",J=O?x.size:x.bytes.byteLength,G=new Headers({"Content-Type":_,"Content-Disposition":`${q}; ${g}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...Gt});return J!==void 0&&G.set("Content-Length",String(J)),y&&G.append("Set-Cookie",y),a(u,!0),o.info(`200 attachment=${u} viewer=${h} type=${_} disposition=${q} bytes=${J??"-"}`),O?new Response(null,{status:200,headers:G}):(T=!0,new Response(Nu(x.bytes,C),{status:200,headers:G}))}finally{T||C()}}};var qe=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),$f=qe.queueWaitMs+qe.readMs+qe.renderMs+qe.transferMarginMs;import{Buffer as Ou}from"buffer";var yi=new Set([194,198,202,206]),Hu=new Set([192,193,194,195]),hi=216,Fu=217,fi=218,$u=4,Uu=64,Bu=2,pi=8,mi=28,It=12,po=8,Vu=20,Ri=It+po+10,qu=2,Rt=(e,t)=>e[t]<<8|e[t+1],Kt=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];return n},ct=(e,t,r)=>{if(e.byteLength<t+r.length)return!1;for(let n=0;n<r.length;n+=1)if(e[t+n]!==r.charCodeAt(n))return!1;return!0},Si=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,gi=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),bi=e=>(e.stepsLeft-=1,e.stepsLeft>=0),Di=e=>e[0]===255&&e[1]===hi,Ti=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!bi(r))return null;n+=1}while(n<e.byteLength&&e[n]===255);if(n>=e.byteLength)return null;let o=e[n];if(n+=1,o===Fu)return"eoi";if(o===0||o===hi)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=Rt(e,n),i=n+a;return a<2||i>e.byteLength?null:(r.marker=o,r.body=n+2,r.length=a,r.end=i,"segment")}},ju=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!bi(r))return null;if(a+1>=n)return n;let i=e[a+1];if(i===255)a+=1;else if(i===0||i>=208&&i<=215){if(a+=2,a>=n||e[a]!==255)break}else return a}o=a}},Ai=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=Rt(e,r+1),a=Rt(e,r+3),i=e[r+5];if(a===0||o===0||i===0||n!==8+3*i)return null;let l=[];for(let s=0;s<i;s+=1){let c=e[r+7+3*s],d=c>>4,u=c&15;if(d<1||d>4||u<1||u>4)return null;l.push({id:e[r+6+3*s],horizontal:d,vertical:u})}return{marker:t,width:a,height:o,components:l}},Ei=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>$u||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},wi=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:yi.has(e.marker)||t<e.components.length}),mo=e=>{if(!Di(e))return null;let t=gi(e.byteLength),r=null;for(let n=2;;){if(Ti(e,n,t)!=="segment")return null;if(Si(t.marker)){if(r!==null||(r=Ai(e,t),r===null))return null}else if(t.marker===fi){if(r===null)return null;let o=Ei(e,t);return o===null?null:wi(r,o.length)}n=t.end}},Ii=e=>{let t=Math.max(...e.components.map(n=>n.horizontal)),r=Math.max(...e.components.map(n=>n.vertical));return e.components.map(({horizontal:n,vertical:o})=>{let a=Math.ceil(e.width*n/(t*pi)),i=Math.ceil(e.height*o/(r*pi));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},_i=e=>e.multiScan?Ii(e).reduce((r,n)=>r+n,0)*Uu*Bu:0,Wu=896,xi=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!Di(e))return null;let n=Ou.from(e.buffer,e.byteOffset,e.byteLength),o=gi(r),a=null,i=null,l=new Map,s=0,c=0,d=0;for(let u=2;;){let h=Ti(e,u,o);if(h===null)return null;if(h==="eoi")return i===null?null:{header:i,blockVisits:c};if(u=o.end,Si(o.marker)){if(a!==null||!Hu.has(o.marker)||(a=Ai(e,o),a===null))return null;let m=Ii(a);l=new Map;for(let[y,R]of a.components.entries()){let p=l.get(R.id);l.set(R.id,p===void 0?m[y]:Math.max(p,m[y]))}s=a.components.length*(yi.has(a.marker)?Wu:1)}else if(o.marker===fi){if(a===null||d===s)return null;let m=Ei(e,o);if(m===null)return null;for(let R of m){let p=l.get(R);if(p===void 0)return null;c+=p}if(d+=1,i===null&&(i=wi(a,m.length)),c>t||!i.multiScan)return{header:i,blockVisits:c};let y=ju(n,o.end,o);if(y===null)return null;u=y}}},Ci=e=>{if(e.byteLength<24||Rt(e,8)!==0||Rt(e,10)!==13||!ct(e,12,"IHDR"))return null;let t=Rt(e,16)*65536+Rt(e,18),r=Rt(e,20)*65536+Rt(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},Yu=e=>{if(ct(e,It,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=Kt(e,26,2)&16383,r=Kt(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(ct(e,It,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=Kt(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return ct(e,It,"VP8X")?e.byteLength<Ri?null:{width:Kt(e,24,3)+1,height:Kt(e,27,3)+1}:null},Mi=e=>{if(Ci(e)===null||e.byteLength<=mi)return null;switch(e[mi]){case 0:return!1;case 1:return!0;default:return null}},ki=(e,t)=>{if(ct(e,It,"VP8 "))return"lossy";if(ct(e,It,"VP8L"))return"lossless";if(!ct(e,It,"VP8X")||e.byteLength<Ri)return null;if((e[Vu]&qu)!==0)return"animated";let r=!1,n=t;for(let o=It;o+po<=e.byteLength;){if(n-=1,n<0)return null;if(ct(e,o,"VP8L"))return"lossless";if(ct(e,o,"VP8 "))return r?"lossy-alpha":"lossy";ct(e,o,"ALPH")&&(r=!0);let a=Kt(e,o+4,4);o+=po+a+a%2}return null},Pi={png:Ci,jpeg:mo,webp:Yu};var yo=Object.freeze(["image/webp","image/jpeg","image/png"]),ho=1024*1024;var zu=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Gu={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},Ku=new Set(yo),Ju=e=>typeof e=="string"&&Ku.has(e),Qu=256,jr=(e,t)=>e.fileType===null||!zu.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,Xu=[137,80,78,71,13,10,26,10],Zu=[255,216,255],ed=[[71,73,70,56,55,97],[71,73,70,56,57,97]],td=[82,73,70,70],rd=[87,69,66,80],Sr=(e,t,r)=>{if(e.byteLength<r+t.length)return!1;for(let[n,o]of t.entries())if(e[r+n]!==o)return!1;return!0},fo=e=>{if(Sr(e,Xu,0))return"png";if(Sr(e,Zu,0))return"jpeg";for(let t of ed)if(Sr(e,t,0))return"gif";return Sr(e,td,0)&&Sr(e,rd,8)?"webp":null},vi=e=>{let t=JSON.stringify([e.rendererId,e.box.maxWidth,e.box.maxHeight,e.attachmentId,e.filePath,e.fileType,e.fileSize]);return{key:t,etag:Za([t])}},Li=(e,t)=>{if(!Ju(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>ho)return"too_large";let r=Gu[e.contentType];if(fo(e.bytes)!==r)return"signature";let n=Pi[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},Ni=e=>{ie("maxBytes",e.maxBytes,0),ie("maxEntries",e.maxEntries,0);let t=new Map,r=0,n=o=>{let a=t.get(o);a&&(t.delete(o),r-=a.weight)};return{get:o=>{let a=t.get(o);if(a)return t.delete(o),t.set(o,a),a.entry},set:(o,a)=>{n(o);let i=(a.kind==="thumbnail"?a.bytes.byteLength:0)+Qu;if(i>e.maxBytes||e.maxEntries===0)return;let l=a.kind==="thumbnail"?{kind:"thumbnail",bytes:a.bytes.slice(),contentType:a.contentType}:a;t.set(o,{entry:l,weight:i}),r+=i;for(let s of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(s)}}}};var Ro=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,i=se(),l=new AbortController,s=!1,c,d,u=()=>{a(se()-i)},h=S=>{c=Ze(()=>{s=!0,S({timedOut:!0}),d=Ze(u,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},m=new Promise(h),y=AbortSignal.any([r,l.signal]),R=S=>{S(n(y))},p=new Promise(R),f=S=>(clearTimeout(c),clearTimeout(d),s&&o(se()-i,S.kind==="error"?{error:S.error}:null),S),D=p.then(S=>f({kind:"value",value:S}),S=>f({kind:"error",error:S}));return{outcome:Promise.race([p.then(S=>({timedOut:!1,value:S})),m]),settled:D}};var St={404:"Attachment not found",500:ht,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},Oi=(e,t)=>{if(typeof e!="object"||e===null)return{failure:{kind:"failure",status:500,reason:"port_contract",code:"result"}};let r=e;if(!r.ok)return r.reason==="unsupported"?{entry:{kind:"unrenderable",reason:"unsupported"}}:r.reason==="failed"?{failure:{kind:"failure",status:502,reason:"render_failed"}}:{failure:{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"}};let n=Li(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},nd=e=>{let t=new AbortController,r=()=>{t.abort()},n=Ze(r,qe.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},Hi=()=>{},od=(e,t)=>t.aborted?Promise.resolve():new Promise(r=>{let n=()=>{t.removeEventListener("abort",n),r()};t.addEventListener("abort",n,{once:!0}),e.then(n)}),Fi=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:i}=e,l=new Map,s=(m,y)=>{let R=y.then(Hi,Hi);l.set(m,R);let p=()=>{l.get(m)===R&&l.delete(m)};R.then(p)},c=async(m,y)=>{let R=l.get(m.key);if(R===void 0)return t.acquire(m.owner,y);let p=nd(y);try{if(await od(R,p.signal),p.signal.aborted)return null;let f=r.get(m.key);return f!==void 0?{...f,identity:"verified"}:await t.acquire(m.owner,p.signal)}finally{p.end()}},d=(m,y)=>{if(m.fileSize===null)return y.kind==="exact"?"verified":"unrecorded";if(y.kind==="exact"?y.bytes===m.fileSize:m.fileSize>y.maxBytes)return"verified";let p=y.kind==="exact"?String(y.bytes):`>${y.maxBytes}`;return i.warn(`size_mismatch expected=${m.fileSize} got=${p} attachment=${m.attachmentId} viewer=${m.owner} variant=thumbnail`),"unverified"},u=(m,y)=>(R,p)=>{let f=p===null?"":` message=${p.error instanceof Error?p.error.message:"unknown"}`;i.warn(`${m}_overrun ms=${R} attachment=${y.attachmentId} viewer=${y.owner} variant=thumbnail${f}`)},h=(m,y)=>R=>{i.warn(`${m}_stuck ms=${R} attachment=${y.attachmentId} viewer=${y.owner} variant=thumbnail`)};return async(m,y)=>{let R=await c(m,y);if(R===null)return{kind:"failure",status:503,reason:y.aborted?"aborted":"queue"};if(typeof R!="function")return R;let p=R,f=null;try{if(y.aborted)return{kind:"failure",status:503,reason:"aborted"};let D=r.get(m.key);if(D!==void 0)return{...D,identity:"verified"};let E=Ro({budgetMs:qe.readMs,flightSignal:y,call:F=>m.readAttachment(m.filePath,{maxBytes:n,head:!1,principal:o(m.owner),signal:F}),onOverrun:u("read",m),onStuck:h("read",m)}),S=await E.outcome;if(S.timedOut)return f=E.settled,y.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(y.aborted)return{kind:"failure",status:503,reason:"aborted"};let g=S.value;if(!g.ok&&g.reason!=="too_large")return Vr(g.reason)?(g.reason==="not_found"&&a(m.attachmentId,!1),{kind:"failure",status:qr(g.reason),reason:g.reason,code:g.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(g.ok&&g.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let C=d(m,g.ok?{kind:"exact",bytes:g.bytes.byteLength}:{kind:"over",maxBytes:n}),T=F=>{C==="verified"&&r.set(m.key,F)},x=F=>(T(F),{...F,identity:C});if(!g.ok)return x({kind:"unrenderable",reason:"too_large"});let O=fo(g.bytes);if(O===null)return x({kind:"unrenderable",reason:"signature"});let w=Ro({budgetMs:qe.renderMs,flightSignal:y,call:F=>m.renderer.render(g.bytes,{format:O,maxWidth:m.box.maxWidth,maxHeight:m.box.maxHeight,signal:F}),onOverrun:u("render",m),onStuck:h("render",m)}),v=F=>{if(F.kind==="error")return;let I=Oi(F.value,m.box);"entry"in I&&T(I.entry)},_=null,q=()=>(_===null&&(_=w.settled.then(v),s(m.key,_)),_);y.addEventListener("abort",q,{once:!0});let J=await w.outcome.finally(()=>y.removeEventListener("abort",q));if(J.timedOut||y.aborted)return f=q(),y.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let G=Oi(J.value,m.box);return"entry"in G?x(G.entry):G.failure}finally{f===null?p():f.then(p,p)}}};var $i=()=>{let e=new Map;return{join:(t,r,n)=>{let o=()=>{let s=new AbortController,c=()=>{e.get(t)?.controller===s&&e.delete(t)},u={promise:n(s.signal).finally(c),controller:s,waiters:0};return e.set(t,u),u},a=e.get(t)??o();a.waiters+=1;let i=()=>{a.waiters-=1,!(a.waiters>0)&&(a.controller.abort(),e.get(t)===a&&e.delete(t))};r.aborted?i():r.addEventListener("abort",i,{once:!0});let l=()=>{r.removeEventListener("abort",i)};return a.promise.finally(l)}}};var Vi=10,ad=1/Vi,Ui=1-ad,id=1024,sd=64,ld=8,Bi="private, no-cache",cd="no-store",ud=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),dd=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},qi=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:s}=l,c=(S,g)=>ft({reason:S,limitPerWindow:g,windowMs:6e4,logger:o,windowFields:C=>`viewer=${C} variant=thumbnail`}),d=c("rate_limit",l.rateLimitPerMinute),u=c("revalidation_rate_limit",l.rateLimitPerMinute*Vi),h=lt({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:sd,maxPerOwner:ld,maxWaitMs:qe.queueWaitMs}}),m=Ni({maxBytes:l.cacheBytes,maxEntries:id}),y=$i(),R=Fi({gate:h,cache:m,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),p=(S,g,C,T)=>{let x=`attachment=${S.attachmentId} viewer=${S.internalUserId} variant=thumbnail cache=${T}`;if(g.kind==="failure")return o[dd(g)](`${g.status} ${x} reason=${g.reason} code=${g.code??"-"}`),S.fail(g.status,St[g.status],Ae(g.status));let O=ud[g.identity];if(g.kind==="unrenderable")return o.info(`404 ${x} reason=${g.reason}${O}`),S.fail(404,St[404]);let w=g.identity==="verified"?{"Cache-Control":Bi,ETag:C}:{"Cache-Control":cd},v=new Headers({"Content-Type":g.contentType,"Content-Length":String(g.bytes.byteLength),...w,"Content-Security-Policy":"default-src 'none'; sandbox",...Gt});return S.cookie&&v.append("Set-Cookie",S.cookie),o.info(`200 ${x} type=${g.contentType} bytes=${g.bytes.byteLength}${O}`),new Response(g.bytes,{status:200,headers:v})},f=(S,g)=>{let C=S.spend(g.internalUserId,`attachment=${g.attachmentId} viewer=${g.internalUserId} variant=thumbnail`);return C===null?null:g.fail(C.status,C.message,C.headers)},D=S=>f(d,S),E=(S,g)=>g?f(u,S):D(S);return async(S,g)=>{let{request:C,attachmentId:T,internalUserId:x,readAttachment:O,cookie:w,fail:v}=S,_=to[g],q=C.headers.get("If-None-Match"),J=q!==null,G=E(S,J);if(G)return G;let F=await n(C,"initial");if(!F.ok)return v(503,St[503],Ae(503));let I=await t.getAttachmentForUser(F.scope,T,x),W=I!==null&&jr(I,i)?vi({rendererId:s.id,box:_,attachmentId:T,filePath:I.filePath,fileType:I.fileType,fileSize:I.fileSize}):null;if(W&&oo(q,W.etag)){let b=new Headers({"Cache-Control":Bi,ETag:W.etag,...Gt});return w&&b.append("Set-Cookie",w),o.info(`304 attachment=${T} viewer=${x} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:b})}if(J){let b=D(S);if(b)return b}if(!I)return o.warn(`404 attachment=${T} viewer=${x} variant=thumbnail reason=not_visible`),v(404,St[404]);if(!W)return d.refund(x,Ui),o.info(`404 attachment=${T} viewer=${x} variant=thumbnail reason=not_eligible`),v(404,St[404]);let{key:ce,etag:ne}=W,de=m.get(ce);if(de)return d.refund(x,Ui),p(S,{...de,identity:"verified"},ne,"hit");let Se=b=>R({key:ce,attachmentId:T,filePath:I.filePath,fileSize:I.fileSize,box:_,owner:x,readAttachment:O,renderer:s},b),Q;try{Q=await y.join(ce,C.signal,Se)}catch(b){return o.error(`500 attachment=${T} viewer=${x} variant=thumbnail cache=miss reason=port_exception message=${b instanceof Error?b.message:"unknown"}`),v(500,St[500])}return p(S,Q,ne,"miss")}};var pd='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',md=()=>Br(403,lo,{cookie:null}),ji=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=ro(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>Br(404,Rr[404],{cookie:null}),crossSiteRejection:md}),Wi=e=>{let{authenticate:t,service:r,encodeUserId:n,resolveViewerScope:o,logger:a}=e,i=r.attachmentDelivery,l={service:r,encodeUserId:n,resolveViewerScope:o,logger:a,recordObjectState:ai(r,a)},s=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:di({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:qi({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:c,params:d})=>{let u=null,h=(m,y,R={})=>Br(m,y,{cookie:u,extraHeaders:R});try{let{user:m,cookie:y}=await t(c,{failureRedirect:null});if(u=y??null,!m)return h(401,"Unauthorized");let R=ro(new URL(c.url).searchParams);if(R.kind==="invalid")return h(400,"Invalid attachment request");if(R.kind==="thumbnail"&&c.method!=="GET")return h(405,"Method not allowed",{Allow:"GET"});if(c.method!=="GET"&&c.method!=="HEAD")return h(405,"Method not allowed",{Allow:"GET, HEAD"});if(s===null)return h(404,"Attachment not found");if(d.token===void 0)throw new Error(pd);let p=s.idCodec.decode(d.token);if(p===null||!it(p))return h(400,"Invalid attachment token");let f=await r.getUserIdByExternalId(m.id);if(!f)return h(403,"Forbidden");let D={request:c,delivery:R,attachmentId:p,internalUserId:f,readAttachment:s.read,cookie:u,fail:h};return R.kind!=="thumbnail"?await s.serveOriginal(D):s.serveThumbnail===null?h(404,St[404]):await s.serveThumbnail(D,R.variant)}catch(m){if(m instanceof Response)throw m;return a.error(`500 attachment=? viewer=? reason=unexpected message=${m instanceof Error?m.message:"unknown"}`),h(500,ht)}}};var yd=32*1024*1024,hd=60,fd=4,Rd=120,Sd=2,gd=8*1024*1024,Wr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),bd=e=>{if(e===void 0)throw Ye("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!Wr(e))throw K("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw Ye("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw K("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw K("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},Dd=e=>{if(e===void 0)return null;if(!Wr(e))throw K("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:bd(e.renderer),rateLimitPerMinute:Ne("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,Rd),concurrency:Ne("attachments.thumbnails.concurrency",e.concurrency,1,Sd),cacheBytes:Ne("attachments.thumbnails.cacheBytes",e.cacheBytes,0,gd)})},Yi=e=>{let t=e;if(t===void 0)return null;if(!Wr(t))throw K("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw Ye("attachments.idCodec","injected when attachments is given");if(!Wr(r)||typeof r.encode!="function"||typeof r.decode!="function")throw K("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw Ye("attachments.read","injected when attachments is given");if(typeof n!="function")throw K("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:Ne("attachments.maxBytes",t.maxBytes,1,yd),rateLimitPerMinute:Ne("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,hd),concurrency:Ne("attachments.concurrency",t.concurrency,1,fd),thumbnails:Dd(t.thumbnails)})},Td=Object.freeze([["attachmentIdCodec","attachments.idCodec"],["readAttachment","attachments.read"],["attachmentMaxBytes","attachments.maxBytes"],["attachmentRateLimitPerMinute","attachments.rateLimitPerMinute"],["attachmentConcurrency","attachments.concurrency"],["attachmentThumbnailRenderer","attachments.thumbnails.renderer"],["attachmentThumbnailRateLimitPerMinute","attachments.thumbnails.rateLimitPerMinute"],["attachmentThumbnailConcurrency","attachments.thumbnails.concurrency"],["attachmentThumbnailCacheBytes","attachments.thumbnails.cacheBytes"]]),Yr=e=>{for(let[t,r]of Td)if(Object.hasOwn(e,t))throw Ye(r,`given in place of the flat key ${t}`)};var Gi=8,Ad=8*Gi,Ed=128,wd=2,Ki=wd*Ed,Id=4*Ki,_d=6e4,xd=6e4,Cd="Too many reads",zi=Object.freeze(Object.keys(Ft).filter(e=>Ft[e].admission.includes("miss-gate"))),Ji=e=>{let t=lt({limit:Ad,maxHeldPerOwner:Gi,queue:{max:Id,maxPerOwner:Ki,maxWaitMs:_d}}),r=Me({windowMs:xd,tallies:zi,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`cache_miss_admission_suppressed count=${o} since=${a} viewer=${n} endpoints=${zi.map(l=>`${l}:${i[l]}`).join(",")}`)}});return{admissionFor:(n,o,a)=>({signal:a,acquire:async i=>{let l=await t.acquire(n,i);return l===null&&!i.aborted&&r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=cache_miss_admission`)),l}})}},zr=(e,t,r)=>{let n=e(t,r,{error:{message:Cd}},503);for(let[o,a]of Object.entries(Ae(503)))n.headers.set(o,a);return n};var Qi=e=>{let t=e.get(be.cursorReportHubId),r=e.get(be.cursorBusinessDate),n=e.get(be.cursorSnapshot),o=xa(n)?n:null,a=null;if(t!==null){let l=Xe(t);if(l===null)return{refused:"cursor"};let s={businessDate:r,reportHubId:l};if(!_a(s))return{refused:"cursor"};a=s}else if(r!==null)return{refused:"cursor"};let i=hr(e.get(be.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var Gr=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,Md=2,kd=16,Pd=Md*kd,vd=6e4,Xi=()=>{},Ld=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},Zi=e=>{let t=lt({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:Pd,queue:null}),r=Me({windowMs:vd,tallies:["sse","ids-stream"],writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`streams_per_viewer_suppressed count=${o} since=${a} viewer=${n} routes=sse:${i.sse},ids-stream:${i["ids-stream"]}`)}});return{admit:async(n,o,a)=>{if(n===null)return Xi;if(a.aborted){if(t.canAcquire(n))return Xi}else{let i=await t.acquire(n,a);if(i!==null)return Ld(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var Kr=30,os=4e3,Nd="stream interrupted by server error",Od="Too many streams",Hd=15e3,as=Symbol("ids-stream-heartbeat"),es=()=>{},ts=e=>e.return(void 0).then(es,es),Fd=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(as),Hd)}),stop:()=>clearTimeout(e)}};async function*rs(e,t,r,n){let o=t?ka(e,t):0,a=!0;for(;;){let i=Math.min(o+(a?r:os),e.length),l=zt(e,o,i),s=i>o?e[i-1]:void 0;o=i;let c=o>=e.length;if(yield{kind:"chunk",...l,nextCursor:c||s===void 0?null:{businessDate:s.businessDate,reportHubId:s.reportHubId},isLast:c,...a?{total:e.length}:{},...a?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...a&&n.restarted?{restarted:!0}:{}},a=!1,c)return}}var is=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform",...st});return e&&t.append("Set-Cookie",e),t},ns=(e,t,r,n,o)=>{let a=async(d,u)=>{o(),u&&await ts(t);try{d.close()}catch{}},i=new TextEncoder,l=!1,s=null,c=new ReadableStream({async pull(d){if(l||r.aborted){await a(d,!0);return}let u=Fd();try{s===null&&(s=t.next());let h=await Promise.race([s,u.fired]);if(u.stop(),h===as){if(l||r.aborted){await a(d,!0);return}d.enqueue(i.encode(`
|
|
2
2
|
`));return}s=null;let{value:m,done:y}=h;if(y){await a(d,!1);return}if(l||r.aborted){await a(d,!0);return}d.enqueue(i.encode(`${JSON.stringify(m)}
|
|
3
3
|
`))}catch(h){if(u.stop(),s=null,o(),l||r.aborted)return;h instanceof Qe||n.error(`ids-stream emission failed: ${h instanceof Error?h.message:String(h)}`);try{let m={kind:"error",error:Nd};d.enqueue(i.encode(`${JSON.stringify(m)}
|
|
4
4
|
`)),d.close()}catch{}}},cancel(){l=!0,o(),ts(t)}});return new Response(c,{status:200,headers:is(e)})},ss=e=>{let{service:t,logger:r,streamSlots:n,missGate:o,refuseForcedRead:a}=e,i=async(l,s,c,d,u,h,m)=>{let y=!1,R=null,p=null,f=new Promise((S,g)=>{R=S,p=g});f.catch(()=>{});let D=t.getDailyReportIdsByExternalId(c,s.id,{forceRefresh:l.forceRefresh,admission:m,onFetchStart:l.cursor?void 0:()=>{y=!0,t.readSseStreamAnchor().then(S=>t.getDailyReportIdsFirstPageByExternalId(c,s.id,Kr).then(g=>({items:g,streamAnchor:S}))).then(S=>R?.(S),S=>p?.(S))}});if(D.catch(()=>{}),l.cursor){let{items:S,streamAnchor:g,snapshot:C}=await D,T=l.snapshot!==null&&l.snapshot===C;return ns(d,rs(S,T?l.cursor:null,Kr,{snapshot:C,restarted:!T,streamAnchor:g}),u,r,h)}let E=(async function*(){let S=await Promise.race([D.then(T=>({kind:"full",source:T}),T=>({kind:"full-error",error:T})),f.then(T=>({kind:"page",page:T}),()=>({kind:"page-error"}))]),g=null,C=!1;if(S.kind==="full")g=S.source;else if(S.kind==="page"){let{items:T,streamAnchor:x}=S.page;if(T.length<Kr){yield{kind:"chunk",...zt(T,0,T.length),nextCursor:null,isLast:!0,total:T.length,streamAnchor:x};return}yield{kind:"chunk",...zt(T,0,T.length),nextCursor:null,isLast:!1,provisional:!0},C=!0}else if(S.kind==="full-error"&&y){let T=await f.catch(()=>null);T&&T.items.length>0&&(yield{kind:"chunk",...zt(T.items,0,T.items.length),nextCursor:null,isLast:!1,provisional:!0})}g===null&&(g=await D),yield*rs(g.items,null,C?os:Kr,{snapshot:g.snapshot,streamAnchor:g.streamAnchor})})();return ns(d,E,u,r,h)};return async(l,s,c,d,u,h)=>{let m=Qi(l.searchParams);if("refused"in m)return h(c,s,{error:{message:m.refused==="cursor"?"Invalid cursor":"Invalid forceRefresh"}},400);let{query:y}=m;if(y.forceRefresh){let D=a(d,c,s,h);if(D!==null)return D}let R=Gr(c),p=await t.getUserIdByExternalId(d.id),f=await n.admit(p,"ids-stream",R);if(f===null){let D=h(c,s,{error:{message:Od}},503);for(let[E,S]of Object.entries(Ae(503)))D.headers.set(E,S);return D}if(R.aborted)return new Response(null,{status:200,headers:is(s)});try{return await i(y,d,u,s,R,f,p===null?void 0:o.admissionFor(p,le.idsStream,R))}catch(D){if(f(),D instanceof Qe)return zr(h,c,s);throw D}}};import{inArray as $d,sql as Jr}from"drizzle-orm";var je="Internal",ls=e=>e.trim().toLowerCase();var Ud="",Bd=64,Vd=e=>e.toLowerCase(),cs=e=>{let t=new Set;if(!Array.isArray(e))return t;for(let r of e){if(typeof r!="string")continue;let n=ls(r);n.length>0&&t.add(n)}return t};function Ie(e,t){return e===null?!0:t==null?!1:e.has(Vd(t))}function Fe(e){return e!==null&&e.size===0}var qd=4e3,go=e=>{let t=e.getSQLType();if(!t.startsWith("nvarchar("))throw K("tables.hub.sourceType","an nvarchar(n) column with a declared length (source types compare as UTF-16 bytes)",t);return ie("tables.hub.sourceType.length",e.length,1,qd)};function br(e,t){if(t===null)return;let r=go(e),n=[...t].filter(a=>a.length<=r);if(n.length===0)return Jr`1 = 0`;let o=Jr.raw(`VARBINARY(${2*r})`);return $d(Jr`CAST(LOWER(${e}) AS ${o})`,n.map(a=>Jr`CAST(${a} AS ${o})`))}var Jt,Qt,gr=class gr{constructor(t,r){wn(this,Jt);wn(this,Qt);In(this,Jt,t),In(this,Qt,r)}get visible(){return nr(this,Jt)===null?null:new Set(nr(this,Jt))}get commentable(){return nr(this,Qt)===null?null:new Set(nr(this,Qt))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=cs(r?t.read:t);if(!r||t.comment===void 0)return new gr(n,n);let o=new Set;for(let a of cs(t.comment))n.has(a)&&o.add(a);return new gr(n,o)}static unrestricted(t){return new gr(null,null)}};Jt=new WeakMap,Qt=new WeakMap;var et=gr,So=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"),jd=new Set(["read","comment"]),ds=e=>{if(So(e))return et.restrictTo(e);if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=Object.keys(e);if("unrestricted"in e){let o=e.unrestricted;return t.length===1&&typeof o=="string"&&o.trim().length>0?et.unrestricted(o):null}let{read:r,comment:n}=e;return t.every(o=>jd.has(o))&&So(r)?n===void 0?et.restrictTo({read:r}):So(n)?et.restrictTo({read:r,comment:n}):null:null};function Qr(e){let t=us(e.visible),r=us(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function us(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(Ud);if(t.length<=Bd)return`s:${t}`;let r=2166136261;for(let n=0;n<t.length;n++)r^=t.charCodeAt(n),r=Math.imul(r,16777619);return`sh:${(r>>>0).toString(16)}`}var ps=(e,t,r,n)=>Ie(n.commentable,t)||e.authorUserId===r;import{parseQuerySets as _p}from"@aiquants/fuzzy-search";import{createHash as Wd}from"crypto";import{setImmediate as ms}from"timers/promises";import{clusterCountOf as Yd,DEFAULT_NORMALIZE_OPTIONS as Zr,InteriorPairs as zd,isAnswerTier as Gd,normalizeText as Kd,queryNeedles as Jd,resolveNormalizeOptions as Qd,toMappedFormsInto as Xd,trimmedRange as Zd}from"@aiquants/fuzzy-search/normalize";var en=`
|