@aiquants/daily-report 0.40.0 → 0.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.mjs CHANGED
@@ -1,12 +1,12 @@
1
- var ao=e=>{throw TypeError(e)};var io=(e,t,r)=>t.has(e)||ao("Cannot "+r);var Ot=(e,t,r)=>(io(e,t,"read from private field"),r?r.call(e):t.get(e)),jr=(e,t,r)=>t.has(e)?ao("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Wr=(e,t,r,n)=>(io(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var zr=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,ne=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${zr(r)}`),Qe=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),Gr=(e,t,r)=>ne(e,`one of ${r.map(n=>JSON.stringify(n)).join(", ")}`,t),te=(e,t,r,n)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r&&(n===void 0||t<=n))return t;throw ne(e,n===void 0?`an integer >= ${r}`:`an integer from ${r} to ${n}`,t)},ht=(e,t,r,n)=>t===void 0?n:te(e,t,r);var ue=()=>Math.floor(performance.now());var $e=class extends Error{constructor(t){super(`cache miss refused (${t})`),this.name="SqlResultCacheMissRefusal",this.reason=t}},Kr=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{}}}),Ft=(e,t)=>t?e.map(r=>structuredClone(r)):e,ol=8,al=(e,t)=>{let r=0,n=[e];for(;n.length>0&&r<=t;){let o=n.pop();if(ArrayBuffer.isView(o)){r+=o.byteLength;continue}let a=Array.isArray(o)?o:Object.keys(o).map(i=>o[i]);r+=ol*a.length;for(let i of a)typeof i=="string"?r+=2*i.length:typeof i=="object"&&i!==null&&n.push(i)}return r},Ht=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-ue())<a*r||this.inFlight.has(n))return;let l;l=(async()=>{let c=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,s=await t.fetcher();return this.inFlight.get(n)===l&&this.writeBucket(n,{records:s,expireAt:ue()+a,epoch:c}),s})(),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,c=o===void 0?null:await o.acquire(o.signal);if(o!==void 0&&c===null)throw new $e(o.signal.aborted?"aborted":"busy");try{for(let m of r)m();let s=await t.fetcher();return this.inFlight.get(n)===a&&this.writeBucket(n,{records:s,expireAt:ue()+(t.ttlMsOverride??this.defaultTtlMs),epoch:l}),s}finally{c?.()}})(),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 $e("aborted");return this.dropBucket(r),Ft(await this.readOwnOrRetry(this.forcedFetch(t),t),o)}let i=this.buckets.get(r);if(i&&i.expireAt>ue())if(t.epochKey){let c=await this.epochStore.getEpoch(t.epochKey);if(c===null||i.epoch===c)return this.maybeRefreshAhead(t),Ft(i.records,o);this.dropBucket(r)}else return this.maybeRefreshAhead(t),Ft(i.records,o);let l=this.inFlight.get(r);if(l!==void 0)return Ft(await this.readOwnOrRetry(l,t),o);if(a?.signal.aborted)throw new $e("aborted");return Ft(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 $e&&(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=te("defaultTtlMs",t.defaultTtlMs,1),this.maxBuckets=te("maxBuckets",t.maxBuckets,1),this.maxBytes=te("maxBytes",t.maxBytes,1),this.lastSweepAt=ue()}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=al(r.records,this.maxBytes);if(n>this.maxBytes)return;this.buckets.set(t,{...r,bytes:n}),this.totalBytes+=n;let o=ue();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)}};var il=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var so=e=>e<10?`0${e}`:`${e}`,sl=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=so(e.getMonth()+1),n=so(e.getDate());return`${t}-${r}-${n}`},It=e=>{let t=il.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 c=new Date(0);return c.setUTCFullYear(a,i-1,l),c.getUTCFullYear()!==a||c.getUTCMonth()!==i-1||c.getUTCDate()!==l?null:`${r}-${n}-${o}`},or=e=>It(e)===e;var ve=e=>e==null?null:e instanceof Date?sl(e):It(e);import{z as ll}from"zod";var lt=e=>Number.isSafeInteger(e)&&e>0,be=ll.number().int().positive().max(Number.MAX_SAFE_INTEGER);var lo="ids-columns";var _t=(e,t,r)=>{let n=[],o=[],a=[],i=[],l=[],c=new Map;for(let s=t;s<r;s++){let{reportHubId:m,businessDate:u,sourceType:f}=e[s];n.push(m),o.length>0&&o[o.length-1]===u?a[a.length-1]+=1:(o.push(u),a.push(1));let h=f===void 0?null:f,R=c.get(h);R===void 0&&(R=i.length,i.push(h),c.set(h,R)),l.push(R)}return{ids:n,dates:o,counts:a,sourceTypes:i,sources:l}},ar=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+(?=.)/,"")},co=(e,t,r,n)=>e!==r?e===null?1:r===null||e>r?-1:1:n-t,cl=(e,t,r,n)=>co(e,t,r,n)<0,Jr=(e,t)=>co(e.businessDate,e.reportHubId,t.businessDate,t.reportHubId),uo=e=>{for(let t=1;t<e.length;t++)if(!cl(e[t-1].businessDate,e[t-1].reportHubId,e[t].businessDate,e[t].reportHubId))return!1;return!0},po=(e,t)=>{let r=e.findIndex(n=>Jr({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var ie=Object.freeze({businessDate:"business-date",idsStream:lo,report:"report",search:"search",reports:"reports",searchMarks:"search-marks",searchFacets:"search-facets",action:"action"}),Re=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 mo=(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)}}},sm=Object.freeze(["API","Action","Attachment","ExternalSource","Isolation","Reads","Refresh","Search","SSE","SseReader","Server","Service","Streams","Visibility","ActionProvider","DetailLoader","IdsStream","SseConnection"]),yo=e=>`[DailyReport${e}]`,Se=(e,t,r)=>e===void 0?mo(t,yo(r)):mo(0,yo(r),e);var ul="legacy-",Qr=e=>`${ul}${e}`;var dl=/^[1-9][0-9]*$/,pl=/^(?:0|[1-9][0-9]*)$/,Be=e=>{if(e===null||!dl.test(e))return null;let t=Number(e);return lt(t)?t:null},Xr=e=>{if(e===null||!pl.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},Zr=e=>e==="true"?!0:e==="false"?!1:null,Ut=e=>e===null?!1:Zr(e);var ho=Object.freeze(["subject","content","author","employeeName","updatedBy","category","creationCategory","customerName"]),Xe=Object.freeze({field:e=>e,interviewer:(e,t)=>`interviewer:${e}:${t}`,attachment:e=>`attachment:${e}`,comment:(e,t)=>`comment:${e}:${t}`});var ml=16777619,en=2166136261,tn=(e,t,r,n)=>{let o=e;for(let a=r;a<n;a++)o^=t.charCodeAt(a),o=Math.imul(o,ml);return o>>>0},fo=e=>tn(en,e,0,e.length),yl=String.fromCodePoint(3),hl=String.fromCodePoint(2),fl=String.fromCodePoint(1),ir=e=>fo(e.map(t=>t.map(r=>r.map(n=>`${n.tier}${n.text}`).join(yl)).join(hl)).join(fl));var Ro=e=>e==="intersection"||e==="union",_e=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),rn=2,sr=2,ft=Object.freeze({word:0,reading:1});var nn=(e,t)=>({ids:e.map(r=>r.reportHubId),businessDates:e.map(r=>r.businessDate),sourceTypes:e.map(r=>r.sourceType),words:t});var mm=2*(1+rn);import{z as Dm}from"zod";var lr=/^(?:[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})$/;import{z as C}from"zod";var So=15e3,go="lastEventId",Rl=/^\d{1,15}-\d{1,15}$/,bo=e=>Rl.test(e),Sl=C.object({name:C.string().nullish(),affiliation:C.string().nullish()}),gl=C.object({name:C.string().nullish(),text:C.string().nullish(),color:C.string().nullish()}),bl=C.object({id:be,name:C.string().nullish(),color:C.string().nullish()}),Do=C.object({id:be,userId:C.string().nullish(),userName:C.string().nullish(),content:C.string().nullish(),createdAt:C.string().nullish(),isMine:C.boolean()}),Dl=C.object({id:C.string(),fileName:C.string(),fileType:C.string().nullable(),fileSize:C.number().nullable(),createdAt:C.string().nullable(),state:C.enum(["present","absent","unknown"]),hasThumbnail:C.boolean().default(!1)}),on=C.object({reportHubId:be,date:C.string().nullish(),createdAt:C.string().nullish(),author:C.string().nullish(),userId:C.string().nullish(),sourceType:C.string().nullish(),employeeName:C.string().nullish(),updatedBy:C.string().nullish(),updatedAt:C.string().nullish(),category:C.string().nullish(),creationCategory:C.string().nullish(),visitTimeFrom:C.string().nullish(),visitTimeTo:C.string().nullish(),customerName:C.string().nullish(),interviewers:C.array(Sl),subject:C.string().nullish(),content:C.string().nullish(),externalComments:C.array(gl),isRead:C.boolean(),isStarred:C.boolean(),isDraft:C.boolean(),labels:C.array(bl),postedComments:C.array(Do),attachments:C.array(Dl).default([])}),Rt=C.string().regex(lr),Al=C.object({type:C.literal("connected")}),cr=C.object({type:C.literal("status-update"),reportHubId:be,statusType:C.enum(["star","read"]),value:C.boolean(),clientTempId:Rt,recipientRawUserId:be.optional()}),an=C.string().optional(),sn=C.object({type:C.literal("comment-add"),reportHubId:be,comment:Do,clientTempId:Rt,recipientRawUserId:be.optional(),sourceType:an}),ln=C.object({type:C.literal("comment-delete"),reportHubId:be,commentId:be,clientTempId:Rt,recipientRawUserId:be.optional(),sourceType:an}),cn=C.object({type:C.literal("report-create"),reportHubId:be,report:on,clientTempId:Rt,recipientRawUserId:be.optional()}),un=C.object({type:C.literal("report-update"),reportHubId:be,report:on,clientTempId:Rt,recipientRawUserId:be.optional()}),dn=C.object({type:C.literal("report-publish"),reportHubId:be,report:on,clientTempId:Rt,recipientRawUserId:be.optional()}),pn=C.object({type:C.literal("report-delete"),reportHubId:be,clientTempId:Rt,sourceType:an}),Ao=C.discriminatedUnion("type",[Al,cr,sn,ln,cn,un,dn,pn]);var Oe=Object.freeze({intent:"intent",clientTempId:"clientTempId",businessDate:"businessDate",operationTimestamp:"operationTimestamp",reportHubId:"reportHubId",title:"title",content:"content",isStarred:"isStarred",isRead:"isRead",commentId:"commentId"});var ur=Math.max(1,Math.floor(10.556701030927835));var Ve=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var Fe=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(s=>[s,0]))};o.set(i,l),Ve(()=>{o.delete(i),l.count>0&&n(i,l)},t)};return{record:(i,l,c)=>{let s=o.get(i);if(s!==void 0){s.count+=1,s.tallies[l]+=1;return}c(),a(i)}}};var Ze=Object.freeze({maxValuesPerFacet:16,maxValueLength:200,maxTotalValueLength:300});var _m=Object.freeze({authors:Object.freeze([]),sourceTypes:Object.freeze([]),customers:Object.freeze([])}),Tl=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,mn=e=>{let t=e.trim();return t.length===0?null:t.replace(Tl,"\uFFFD")},El=e=>{let t=mn(e);return t===null?"filter-blank-value":t!==e?"filter-value-not-canonical":e.length>Ze.maxValueLength?"filter-value-too-long":null},wl=e=>{if(e.length>Ze.maxValuesPerFacet)return"filter-too-many-values";let t=new Set;for(let r of e){let n=El(r);if(n!==null)return n;if(t.has(r))return"filter-duplicate-value";t.add(r)}return null},Il=e=>{let t=0;for(let r of e.authors)t+=r.length;for(let r of e.customers)t+=r.length;return t},To=e=>{for(let t of[e.authors,e.sourceTypes,e.customers]){let r=wl(t);if(r!==null)return r}return Il(e)>Ze.maxTotalValueLength?"filters-too-long":null};var Eo=e=>e.trim().length===0;var yn=e=>e!==null&&lr.test(e)?e:null,hn=e=>Ro(e)?e:null,fn=e=>{if(e===null)return null;let t=e.split(",");if(t.length>_e.maxDetailIds)return null;let r=[];for(let n of t){let o=Be(n);if(o===null||r.includes(o))return null;r.push(o)}return r},wo=e=>{let[t,...r]=e;return t===void 0?null:[t,...r]},Io=(e,t)=>{let r={authors:e.getAll(Re.searchAuthor),sourceTypes:e.getAll(Re.searchSourceType),customers:e.getAll(Re.searchCustomer)},n=To(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:wo(r.authors),customers:wo(r.customers)}}},_o=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var Co=Object.freeze({status:400,error:"Invalid form"}),Mo=e=>({status:413,error:"Form too large",measuredBy:e}),_l=(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)}}))},xl=async e=>{let t=Xr(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:Mo("declared")};let r=!1,n=e.body===null?null:_l(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?Mo("counted"):Co}}let l=_o(i);return l===null?{refusal:Co}:{fields:l}},Po=(e,t)=>(r,n)=>{let o=r.get(t);if(o===null)return{error:`${t} required`};let a=Zr(o);return a===null?{error:`Invalid ${t}`}:{command:{...n,intent:e,value:a}}},No=Object.freeze({update:(e,t,r)=>{let n=e.get(Oe.title),o=e.get(Oe.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:Po("toggleStar",Oe.isStarred),toggleRead:Po("toggleRead",Oe.isRead),addComment:(e,t)=>{let r=e.get(Oe.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=Be(e.get(Oe.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),Cl=e=>Object.hasOwn(No,e),Ml=(e,t)=>{let r=e.get(Oe.intent),n=e.get(Oe.businessDate),o=n===null?null:It(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get(Oe.operationTimestamp),i=Xr(a);if(a!==null&&i===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get(Oe.clientTempId);if(!l)return{error:"clientTempId required"};let c=yn(l);if(c===null)return{error:"Invalid clientTempId"};if(r==="create")return o===null?{error:"businessDate required"}:{command:{intent:r,clientTempId:c,businessDate:o,operationTimestamp:i}};let s=Be(e.get(Oe.reportHubId));return s===null?{error:"Invalid reportHubId"}:r===null||!Cl(r)?{error:"Invalid intent"}:No[r](e,{clientTempId:c,businessDate:o,operationTimestamp:i,reportHubId:s},t)},ko=async(e,t)=>{let r=await xl(e);if("refusal"in r)return r;let n=Ml(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},Pl=6e4,Ll="form_too_large",Lo=["declared","counted"],vo=e=>{let t=Fe({windowMs:Pl,tallies:Lo,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${Lo.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(Ll,r,n)}};var St=Object.freeze({[ie.businessDate]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[ie.idsStream]:{body:"stream",admission:["refresh-bucket","stream-slots","cache","miss-gate"]},[ie.report]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[ie.search]:{body:"json",cache:"etag",admission:["search-limiter"]},[ie.reports]:{body:"json",cache:"etag",admission:["search-limiter"]},[ie.searchMarks]:{body:"json",cache:"no-store",admission:["search-limiter"]},[ie.searchFacets]:{body:"json",cache:"etag",admission:["search-limiter"]}}),Oo=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),Rn=e=>e!==void 0&&Object.hasOwn(St,e);var Sn=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),Fo=e=>Object.hasOwn(Sn,e);var Nl="download",kl="thumbnail",vl="1";var gn=e=>{let t=e.getAll(kl),r=e.getAll(Nl);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&Fo(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===vl?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};import{createHash as Ol}from"crypto";var bn=e=>`"${Ol("sha256").update(e).digest("hex")}"`,Ho=e=>bn(JSON.stringify(e));var je=Object.freeze({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'"}),Dn=(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},Uo=(e,t,r,n=200)=>{let o=JSON.stringify(r),a=bn(o),i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate",ETag:a,...je});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&Dn(e.headers.get("If-None-Match"),a)?new Response(null,{status:304,headers:i}):new Response(o,{status:n,headers:i})},An=(e,t,r)=>{let n=new Headers({...t===null?{}:{"Content-Type":"application/json"},"Cache-Control":"no-store",...je});return e&&n.append("Set-Cookie",e),new Response(t===null?null:JSON.stringify(t),{status:r,headers:n})},Tn=e=>(t,r,n,o)=>{if(o!==200)return An(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)},Fl=5e3/1e3,Hl=new Map([[503,Fl]]),Me=e=>{let t=Hl.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var wn="Cross-site request rejected",Ul="Not Found",$l=new Set(["same-origin","none"]),Bl=new Set(["GET","HEAD","OPTIONS"]),$o=["api","action","sse","attachment"],Bo=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...je}}),Vl=()=>Bo(403,wn),dr=()=>Bo(404,Ul),$t=Object.freeze({navigable:()=>!1,frameworkDataRefusal:()=>null,crossSiteRejection:Vl}),Vo=e=>new URL(e.url).pathname.endsWith(".data"),ql=e=>{let t=e.headers.get("Origin");return t===null?!0:URL.canParse(t)&&new URL(t).host===new URL(e.url).host},qo=(e,t)=>{let r=e.headers.get("Sec-Fetch-Site");return r===null?!(Bl.has(e.method)||ql(e)):$l.has(r)?!1:!(e.method==="GET"&&e.headers.get("Sec-Fetch-Mode")==="navigate"&&e.headers.get("Sec-Fetch-Dest")==="document"&&t.navigable(e))},Yl=6e4,jl="refusals",Wl=32,zl=/^[a-z-]+$/,En=e=>{if(e===null)return"-";let t=e.slice(0,Wl);return zl.test(t)&&t===e?e:JSON.stringify(t)},Yo=e=>{let t=Fe({windowMs:Yl,tallies:$o,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${$o.map(i=>`${i}:${a[i]}`).join(",")}`)}});return(r,n)=>{let o=()=>{let{headers:a}=n;e.warn(`cross_site_rejected route=${r} site=${En(a.get("Sec-Fetch-Site"))} mode=${En(a.get("Sec-Fetch-Mode"))} dest=${En(a.get("Sec-Fetch-Dest"))} method=${n.method}`)};t.record(jl,r,o)}};var jo=(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 Gl="same-origin",Kl="SAMEORIGIN",xt=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":Gl,"X-Frame-Options":Kl}),pr=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...xt});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},Wo=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),Jl=/^[\x20-\x7E]+$/,Ql=/^[\w.+-]+\/[\w.+-]+/,In=e=>e&&Jl.test(e)&&Ql.test(e)?e:null,Xl=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,zo=e=>encodeURIComponent(e.replace(Xl,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),Go=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),mr={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},Ko={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},yr=e=>typeof e=="string"&&Object.hasOwn(Ko,e),hr=e=>Ko[e],et="Attachment request failed";var We=e=>{let t=te("limit",e.limit,1),r=te("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:te("queue.max",e.queue.max,0),maxPerOwner:te("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:te("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],i=new Map,l=new Map,c=(S,A)=>S.get(A)??0,s=(S,A,x)=>{let F=c(S,A)+x;F<=0?S.delete(A):S.set(A,F)},m=S=>c(l,S)<r,u=S=>o<t&&m(S),f=S=>(o+=1,s(l,S,1),b(S)),h=()=>{let S=-1,A=r;for(let[x,F]of a.entries()){let E=c(l,F.owner);if(E<A&&(S=x,A=E,E===0))break}return S},R=()=>{for(;o<t;){let S=h();if(S<0)return;let[A]=a.splice(S,1);s(i,A.owner,-1),A.grant(f(A.owner))}},b=S=>{let A=!1;return()=>{A||(A=!0,o-=1,s(l,S,-1),R())}};return{canAcquire:u,acquire:(S,A)=>{if(A.aborted)return Promise.resolve(null);if(u(S))return Promise.resolve(f(S));if(n===null||a.length>=n.max||c(i,S)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:x}=n,F=E=>{let D=()=>{let de=a.indexOf(H);de<0||(a.splice(de,1),s(i,S,-1),M(),E(null))},$=Ve(D,x),M=()=>{clearTimeout($),A.removeEventListener("abort",D)},H={owner:S,grant:de=>{M(),E(de)}};a.push(H),s(i,S,1),A.addEventListener("abort",D,{once:!0})};return new Promise(F)}}};var Zl=1024,_n="Too many requests",ec=(e,t)=>{te("limitPerWindow",e,1),te("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 c=l??{tokens:e,lastRefillMs:i};n(c,i),r.set(a,c);for(let s of r.keys()){if(r.size<=Zl)break;r.delete(s)}return c};return{consume:(a,i)=>{let l=o(a,i);return l.tokens<1?!1:(l.tokens-=1,!0)},refund:(a,i,l)=>{let c=r.get(a);c&&(n(c,i),c.tokens=Math.min(e,c.tokens+l))}}},tt=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(te("windowMs",r,1e3)%1e3!==0)throw ne("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=ec(e.limitPerWindow,r),i=Object.freeze({status:429,message:_n,headers:Object.freeze({"Retry-After":String(r/1e3)})}),l=Fe({windowMs:r,tallies:[t],writeSuppressed:(c,{count:s,since:m})=>{n.warn(`${t}_suppressed count=${s} since=${m} ${o(c)}`)}});return{spend:(c,s)=>a.consume(c,ue())?null:(l.record(c,t,()=>n.warn(`429 ${s} reason=${t}`)),i),refund:(c,s)=>{a.refund(c,ue(),s)}}};var rc=256*1024,Jo=6e4,nc=e=>Math.ceil(e/2),oc=new Uint8Array(new ArrayBuffer(0)),ac=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=oc,t()},i=l=>{clearTimeout(o),o=Ve(()=>{l.error(new Error(`attachment body idle for ${Jo} ms`)),a()},Jo)};return new ReadableStream({start(l){i(l)},pull(l){let c=Math.min(n+rc,r.byteLength);if(c>n&&l.enqueue(r.slice(n,c)),n=c,n>=r.byteLength){l.close(),a();return}i(l)},cancel(){a()}},{highWaterMark:0})},Qo=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=tt({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:c=>`viewer=${c}`}),l=We({limit:e.concurrency,maxHeldPerOwner:nc(e.concurrency),queue:null});return async c=>{let{request:s,delivery:m,attachmentId:u,internalUserId:f,readAttachment:h,cookie:R,fail:b}=c,S=e.maxBytes,A=i.spend(f,`attachment=${u} viewer=${f}`);if(A)return b(A.status,A.message,A.headers);let x=await n(s),F=await t.getAttachmentForUser(x,u,f);if(!F)return o.warn(`404 attachment=${u} viewer=${f} reason=not_visible`),b(404,"Attachment not found");if(F.fileSize!=null&&F.fileSize>S)return o.warn(`413 attachment=${u} viewer=${f} reason=db_size`),b(413,"Attachment too large");let E=In(F.fileType),D=`filename="${Go(F.fileName)}"; filename*=UTF-8''${zo(F.fileName)}`,$=await l.acquire(f,s.signal);if(!$)return s.signal.aborted?(o.info(`503 attachment=${u} viewer=${f} reason=aborted`),b(503,"Attachment request aborted")):(o.warn(`503 attachment=${u} viewer=${f} reason=concurrency`),b(503,"Too many concurrent downloads",Me(503)));let M=!1;try{let H=await h(F.filePath,{maxBytes:S,head:s.method==="HEAD",principal:r(f),signal:s.signal});if(s.signal.aborted)return o.info(`503 attachment=${u} viewer=${f} reason=aborted`),b(503,"Attachment request aborted");if(!H.ok){if(!yr(H.reason))return o.error(`500 attachment=${u} viewer=${f} reason=port_contract code=failure_reason`),b(500,et);let me=hr(H.reason);return H.reason==="not_found"&&a(u,!1),o.warn(`${me} attachment=${u} viewer=${f} reason=${H.reason} code=${H.code??"-"}`),b(me,mr[me],Me(me))}if(H.bytes.byteLength>S)return o.error(`500 attachment=${u} viewer=${f} reason=port_contract code=over_max_bytes`),b(500,et);let de=s.method==="HEAD";if(de&&H.size!==void 0&&H.size>S)return o.error(`500 attachment=${u} viewer=${f} reason=port_contract code=over_max_bytes`),b(500,et);if(!de&&H.size!==void 0&&H.size!==H.bytes.byteLength)return o.error(`500 attachment=${u} viewer=${f} reason=port_contract code=size_mismatch`),b(500,et);let pe=E??In(H.contentType),ge=pe!==null&&Wo.has(pe),G=ge?pe:"application/octet-stream",se=ge&&m.kind!=="download"?"inline":"attachment",re=de?H.size:H.bytes.byteLength,ce=new Headers({"Content-Type":G,"Content-Disposition":`${se}; ${D}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...xt});return re!==void 0&&ce.set("Content-Length",String(re)),R&&ce.append("Set-Cookie",R),a(u,!0),o.info(`200 attachment=${u} viewer=${f} type=${G} disposition=${se} bytes=${re??"-"}`),de?new Response(null,{status:200,headers:ce}):(M=!0,new Response(ac(H.bytes,$),{status:200,headers:ce}))}finally{M||$()}}};var Pe=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),hy=Pe.queueWaitMs+Pe.readMs+Pe.renderMs+Pe.transferMarginMs;import{Buffer as ic}from"buffer";var ea=new Set([194,198,202,206]),sc=new Set([192,193,194,195]),ta=216,lc=217,ra=218,cc=4,uc=64,dc=2,Xo=8,Zo=28,ct=12,xn=8,pc=20,na=ct+xn+10,mc=2,rt=(e,t)=>e[t]<<8|e[t+1],Ct=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];return n},ze=(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},oa=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,aa=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),ia=e=>(e.stepsLeft-=1,e.stepsLeft>=0),sa=e=>e[0]===255&&e[1]===ta,la=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!ia(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===lc)return"eoi";if(o===0||o===ta)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")}},yc=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!ia(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}},ca=(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 c=0;c<i;c+=1){let s=e[r+7+3*c],m=s>>4,u=s&15;if(m<1||m>4||u<1||u>4)return null;l.push({id:e[r+6+3*c],horizontal:m,vertical:u})}return{marker:t,width:a,height:o,components:l}},ua=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>cc||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},da=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:ea.has(e.marker)||t<e.components.length}),Cn=e=>{if(!sa(e))return null;let t=aa(e.byteLength),r=null;for(let n=2;;){if(la(e,n,t)!=="segment")return null;if(oa(t.marker)){if(r!==null||(r=ca(e,t),r===null))return null}else if(t.marker===ra){if(r===null)return null;let o=ua(e,t);return o===null?null:da(r,o.length)}n=t.end}},pa=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*Xo)),i=Math.ceil(e.height*o/(r*Xo));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},ma=e=>e.multiScan?pa(e).reduce((r,n)=>r+n,0)*uc*dc:0,hc=896,ya=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!sa(e))return null;let n=ic.from(e.buffer,e.byteOffset,e.byteLength),o=aa(r),a=null,i=null,l=new Map,c=0,s=0,m=0;for(let u=2;;){let f=la(e,u,o);if(f===null)return null;if(f==="eoi")return i===null?null:{header:i,blockVisits:s};if(u=o.end,oa(o.marker)){if(a!==null||!sc.has(o.marker)||(a=ca(e,o),a===null))return null;let h=pa(a);l=new Map;for(let[R,b]of a.components.entries()){let S=l.get(b.id);l.set(b.id,S===void 0?h[R]:Math.max(S,h[R]))}c=a.components.length*(ea.has(a.marker)?hc:1)}else if(o.marker===ra){if(a===null||m===c)return null;let h=ua(e,o);if(h===null)return null;for(let b of h){let S=l.get(b);if(S===void 0)return null;s+=S}if(m+=1,i===null&&(i=da(a,h.length)),s>t||!i.multiScan)return{header:i,blockVisits:s};let R=yc(n,o.end,o);if(R===null)return null;u=R}}},ha=e=>{if(e.byteLength<24||rt(e,8)!==0||rt(e,10)!==13||!ze(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}},fc=e=>{if(ze(e,ct,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=Ct(e,26,2)&16383,r=Ct(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(ze(e,ct,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=Ct(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return ze(e,ct,"VP8X")?e.byteLength<na?null:{width:Ct(e,24,3)+1,height:Ct(e,27,3)+1}:null},fa=e=>{if(ha(e)===null||e.byteLength<=Zo)return null;switch(e[Zo]){case 0:return!1;case 1:return!0;default:return null}},Ra=(e,t)=>{if(ze(e,ct,"VP8 "))return"lossy";if(ze(e,ct,"VP8L"))return"lossless";if(!ze(e,ct,"VP8X")||e.byteLength<na)return null;if((e[pc]&mc)!==0)return"animated";let r=!1,n=t;for(let o=ct;o+xn<=e.byteLength;){if(n-=1,n<0)return null;if(ze(e,o,"VP8L"))return"lossless";if(ze(e,o,"VP8 "))return r?"lossy-alpha":"lossy";ze(e,o,"ALPH")&&(r=!0);let a=Ct(e,o+4,4);o+=xn+a+a%2}return null},Sa={png:ha,jpeg:Cn,webp:fc};var Mn=Object.freeze(["image/webp","image/jpeg","image/png"]),Pn=1024*1024;var Rc=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Sc={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},gc=new Set(Mn),bc=e=>typeof e=="string"&&gc.has(e),Dc=256,fr=(e,t)=>e.fileType===null||!Rc.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,Ac=[137,80,78,71,13,10,26,10],Tc=[255,216,255],Ec=[[71,73,70,56,55,97],[71,73,70,56,57,97]],wc=[82,73,70,70],Ic=[87,69,66,80],Bt=(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},Ln=e=>{if(Bt(e,Ac,0))return"png";if(Bt(e,Tc,0))return"jpeg";for(let t of Ec)if(Bt(e,t,0))return"gif";return Bt(e,wc,0)&&Bt(e,Ic,8)?"webp":null},ga=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:Ho([t])}},ba=(e,t)=>{if(!bc(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>Pn)return"too_large";let r=Sc[e.contentType];if(Ln(e.bytes)!==r)return"signature";let n=Sa[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},Da=e=>{te("maxBytes",e.maxBytes,0),te("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)+Dc;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 c of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(c)}}}};var Nn=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,i=ue(),l=new AbortController,c=!1,s,m,u=()=>{a(ue()-i)},f=E=>{s=Ve(()=>{c=!0,E({timedOut:!0}),m=Ve(u,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},h=new Promise(f),R=AbortSignal.any([r,l.signal]),b=E=>{E(n(R))},S=new Promise(b),A=E=>(clearTimeout(s),clearTimeout(m),c&&o(ue()-i,E.kind==="error"?{error:E.error}:null),E),x=S.then(E=>A({kind:"value",value:E}),E=>A({kind:"error",error:E}));return{outcome:Promise.race([S.then(E=>({timedOut:!1,value:E})),h]),settled:x}};var ut={404:"Attachment not found",500:et,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},Aa=(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=ba(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},_c=e=>{let t=new AbortController,r=()=>{t.abort()},n=Ve(r,Pe.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},Ta=()=>{},xc=(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)}),Ea=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:i}=e,l=new Map,c=(h,R)=>{let b=R.then(Ta,Ta);l.set(h,b);let S=()=>{l.get(h)===b&&l.delete(h)};b.then(S)},s=async(h,R)=>{let b=l.get(h.key);if(b===void 0)return t.acquire(h.owner,R);let S=_c(R);try{if(await xc(b,S.signal),S.signal.aborted)return null;let A=r.get(h.key);return A!==void 0?{...A,identity:"verified"}:await t.acquire(h.owner,S.signal)}finally{S.end()}},m=(h,R)=>{if(h.fileSize===null)return R.kind==="exact"?"verified":"unrecorded";if(R.kind==="exact"?R.bytes===h.fileSize:h.fileSize>R.maxBytes)return"verified";let S=R.kind==="exact"?String(R.bytes):`>${R.maxBytes}`;return i.warn(`size_mismatch expected=${h.fileSize} got=${S} attachment=${h.attachmentId} viewer=${h.owner} variant=thumbnail`),"unverified"},u=(h,R)=>(b,S)=>{let A=S===null?"":` message=${S.error instanceof Error?S.error.message:"unknown"}`;i.warn(`${h}_overrun ms=${b} attachment=${R.attachmentId} viewer=${R.owner} variant=thumbnail${A}`)},f=(h,R)=>b=>{i.warn(`${h}_stuck ms=${b} attachment=${R.attachmentId} viewer=${R.owner} variant=thumbnail`)};return async(h,R)=>{let b=await s(h,R);if(b===null)return{kind:"failure",status:503,reason:R.aborted?"aborted":"queue"};if(typeof b!="function")return b;let S=b,A=null;try{if(R.aborted)return{kind:"failure",status:503,reason:"aborted"};let x=r.get(h.key);if(x!==void 0)return{...x,identity:"verified"};let F=Nn({budgetMs:Pe.readMs,flightSignal:R,call:me=>h.readAttachment(h.filePath,{maxBytes:n,head:!1,principal:o(h.owner),signal:me}),onOverrun:u("read",h),onStuck:f("read",h)}),E=await F.outcome;if(E.timedOut)return A=F.settled,R.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(R.aborted)return{kind:"failure",status:503,reason:"aborted"};let D=E.value;if(!D.ok&&D.reason!=="too_large")return yr(D.reason)?(D.reason==="not_found"&&a(h.attachmentId,!1),{kind:"failure",status:hr(D.reason),reason:D.reason,code:D.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(D.ok&&D.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let $=m(h,D.ok?{kind:"exact",bytes:D.bytes.byteLength}:{kind:"over",maxBytes:n}),M=me=>{$==="verified"&&r.set(h.key,me)},H=me=>(M(me),{...me,identity:$});if(!D.ok)return H({kind:"unrenderable",reason:"too_large"});let de=Ln(D.bytes);if(de===null)return H({kind:"unrenderable",reason:"signature"});let pe=Nn({budgetMs:Pe.renderMs,flightSignal:R,call:me=>h.renderer.render(D.bytes,{format:de,maxWidth:h.box.maxWidth,maxHeight:h.box.maxHeight,signal:me}),onOverrun:u("render",h),onStuck:f("render",h)}),ge=me=>{if(me.kind==="error")return;let he=Aa(me.value,h.box);"entry"in he&&M(he.entry)},G=null,se=()=>(G===null&&(G=pe.settled.then(ge),c(h.key,G)),G);R.addEventListener("abort",se,{once:!0});let re=await pe.outcome.finally(()=>R.removeEventListener("abort",se));if(re.timedOut||R.aborted)return A=se(),R.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let ce=Aa(re.value,h.box);return"entry"in ce?H(ce.entry):ce.failure}finally{A===null?S():A.then(S,S)}}};var wa=()=>{let e=new Map;return{join:(t,r,n)=>{let o=()=>{let c=new AbortController,s=()=>{e.get(t)?.controller===c&&e.delete(t)},u={promise:n(c.signal).finally(s),controller:c,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 xa=10,Cc=1/xa,Ia=1-Cc,Mc=1024,Pc=64,Lc=8,_a="private, no-cache",Nc="no-store",kc=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),vc=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},Ca=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:c}=l,s=(E,D)=>tt({reason:E,limitPerWindow:D,windowMs:6e4,logger:o,windowFields:$=>`viewer=${$} variant=thumbnail`}),m=s("rate_limit",l.rateLimitPerMinute),u=s("revalidation_rate_limit",l.rateLimitPerMinute*xa),f=We({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:Pc,maxPerOwner:Lc,maxWaitMs:Pe.queueWaitMs}}),h=Da({maxBytes:l.cacheBytes,maxEntries:Mc}),R=wa(),b=Ea({gate:f,cache:h,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),S=(E,D,$,M)=>{let H=`attachment=${E.attachmentId} viewer=${E.internalUserId} variant=thumbnail cache=${M}`;if(D.kind==="failure")return o[vc(D)](`${D.status} ${H} reason=${D.reason} code=${D.code??"-"}`),E.fail(D.status,ut[D.status],Me(D.status));let de=kc[D.identity];if(D.kind==="unrenderable")return o.info(`404 ${H} reason=${D.reason}${de}`),E.fail(404,ut[404]);let pe=D.identity==="verified"?{"Cache-Control":_a,ETag:$}:{"Cache-Control":Nc},ge=new Headers({"Content-Type":D.contentType,"Content-Length":String(D.bytes.byteLength),...pe,"Content-Security-Policy":"default-src 'none'; sandbox",...xt});return E.cookie&&ge.append("Set-Cookie",E.cookie),o.info(`200 ${H} type=${D.contentType} bytes=${D.bytes.byteLength}${de}`),new Response(D.bytes,{status:200,headers:ge})},A=(E,D)=>{let $=E.spend(D.internalUserId,`attachment=${D.attachmentId} viewer=${D.internalUserId} variant=thumbnail`);return $===null?null:D.fail($.status,$.message,$.headers)},x=E=>A(m,E),F=(E,D)=>D?A(u,E):x(E);return async(E,D)=>{let{request:$,attachmentId:M,internalUserId:H,readAttachment:de,cookie:pe,fail:ge}=E,G=Sn[D],se=$.headers.get("If-None-Match"),re=se!==null,ce=F(E,re);if(ce)return ce;let me=await n($),he=await t.getAttachmentForUser(me,M,H),oe=he!==null&&fr(he,i)?ga({rendererId:c.id,box:G,attachmentId:M,filePath:he.filePath,fileType:he.fileType,fileSize:he.fileSize}):null;if(oe&&Dn(se,oe.etag)){let T=new Headers({"Cache-Control":_a,ETag:oe.etag,...xt});return pe&&T.append("Set-Cookie",pe),o.info(`304 attachment=${M} viewer=${H} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:T})}if(re){let T=x(E);if(T)return T}if(!he)return o.warn(`404 attachment=${M} viewer=${H} variant=thumbnail reason=not_visible`),ge(404,ut[404]);if(!oe)return m.refund(H,Ia),o.info(`404 attachment=${M} viewer=${H} variant=thumbnail reason=not_eligible`),ge(404,ut[404]);let{key:ke,etag:Ue}=oe,it=h.get(ke);if(it)return m.refund(H,Ia),S(E,{...it,identity:"verified"},Ue,"hit");let st=T=>b({key:ke,attachmentId:M,filePath:he.filePath,fileSize:he.fileSize,box:G,owner:H,readAttachment:de,renderer:c},T),Ee;try{Ee=await R.join(ke,$.signal,st)}catch(T){return o.error(`500 attachment=${M} viewer=${H} variant=thumbnail cache=miss reason=port_exception message=${T instanceof Error?T.message:"unknown"}`),ge(500,ut[500])}return S(E,Ee,Ue,"miss")}};var Oc='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',Fc=()=>pr(403,wn,{cookie:null}),Ma=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=gn(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>pr(404,mr[404],{cookie:null}),crossSiteRejection:Fc}),Pa=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:jo(r,a)},c=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:Qo({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:Ca({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:s,params:m})=>{let u=null,f=(h,R,b={})=>pr(h,R,{cookie:u,extraHeaders:b});try{let{user:h,cookie:R}=await t(s,{failureRedirect:null});if(u=R??null,!h)return f(401,"Unauthorized");let b=gn(new URL(s.url).searchParams);if(b.kind==="invalid")return f(400,"Invalid attachment request");if(b.kind==="thumbnail"&&s.method!=="GET")return f(405,"Method not allowed",{Allow:"GET"});if(s.method!=="GET"&&s.method!=="HEAD")return f(405,"Method not allowed",{Allow:"GET, HEAD"});if(c===null)return f(404,"Attachment not found");if(m.token===void 0)throw new Error(Oc);let S=c.idCodec.decode(m.token);if(S===null||!lt(S))return f(400,"Invalid attachment token");let A=await r.getUserIdByExternalId(h.id);if(!A)return f(403,"Forbidden");let x={request:s,delivery:b,attachmentId:S,internalUserId:A,readAttachment:c.read,cookie:u,fail:f};return b.kind!=="thumbnail"?await c.serveOriginal(x):c.serveThumbnail===null?f(404,ut[404]):await c.serveThumbnail(x,b.variant)}catch(h){if(h instanceof Response)throw h;return a.error(`500 attachment=? viewer=? reason=unexpected message=${h instanceof Error?h.message:"unknown"}`),f(500,et)}}};var Hc=32*1024*1024,Uc=60,$c=4,Bc=120,Vc=2,qc=8*1024*1024,Rr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Yc=e=>{if(e===void 0)throw Qe("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!Rr(e))throw ne("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw Qe("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw ne("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw ne("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},jc=e=>{if(e===void 0)return null;if(!Rr(e))throw ne("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:Yc(e.renderer),rateLimitPerMinute:ht("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,Bc),concurrency:ht("attachments.thumbnails.concurrency",e.concurrency,1,Vc),cacheBytes:ht("attachments.thumbnails.cacheBytes",e.cacheBytes,0,qc)})},La=e=>{let t=e;if(t===void 0)return null;if(!Rr(t))throw ne("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw Qe("attachments.idCodec","injected when attachments is given");if(!Rr(r)||typeof r.encode!="function"||typeof r.decode!="function")throw ne("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw Qe("attachments.read","injected when attachments is given");if(typeof n!="function")throw ne("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:ht("attachments.maxBytes",t.maxBytes,1,Hc),rateLimitPerMinute:ht("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,Uc),concurrency:ht("attachments.concurrency",t.concurrency,1,$c),thumbnails:jc(t.thumbnails)})},Wc=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"]]),Sr=e=>{for(let[t,r]of Wc)if(Object.hasOwn(e,t))throw Qe(r,`given in place of the flat key ${t}`)};var ka=8,zc=8*ka,Gc=128,Kc=2,va=Kc*Gc,Jc=4*va,Qc=6e4,Xc=6e4,Zc="Too many reads",Na=Object.freeze(Object.keys(St).filter(e=>St[e].admission.includes("miss-gate"))),Oa=e=>{let t=We({limit:zc,maxHeldPerOwner:ka,queue:{max:Jc,maxPerOwner:va,maxWaitMs:Qc}}),r=Fe({windowMs:Xc,tallies:Na,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`cache_miss_admission_suppressed count=${o} since=${a} viewer=${n} endpoints=${Na.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}})}},gr=(e,t,r)=>{let n=e(t,r,{error:{message:Zc}},503);for(let[o,a]of Object.entries(Me(503)))n.headers.set(o,a);return n};var eu=/^[0-9a-f]{1,16}$/,tu=e=>lt(e.reportHubId)&&(e.businessDate===null||or(e.businessDate)),ru=e=>typeof e=="string"&&eu.test(e);var Fa=e=>{let t=e.get(Re.cursorReportHubId),r=e.get(Re.cursorBusinessDate),n=e.get(Re.cursorSnapshot),o=ru(n)?n:null,a=null;if(t!==null){let l=Be(t);if(l===null)return{refused:"cursor"};let c={businessDate:r,reportHubId:l};if(!tu(c))return{refused:"cursor"};a=c}else if(r!==null)return{refused:"cursor"};let i=Ut(e.get(Re.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var br=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,nu=2,ou=16,au=nu*ou,iu=6e4,Ha=()=>{},su=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},Ua=e=>{let t=We({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:au,queue:null}),r=Fe({windowMs:iu,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 Ha;if(a.aborted){if(t.canAcquire(n))return Ha}else{let i=await t.acquire(n,a);if(i!==null)return su(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var Dr=30,Ya=4e3,lu="stream interrupted by server error",cu="Too many streams",uu=15e3,ja=Symbol("ids-stream-heartbeat"),$a=()=>{},Ba=e=>e.return(void 0).then($a,$a),du=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(ja),uu)}),stop:()=>clearTimeout(e)}};async function*Va(e,t,r,n){let o=t?po(e,t):0,a=!0;for(;;){let i=Math.min(o+(a?r:Ya),e.length),l=_t(e,o,i),c=i>o?e[i-1]:void 0;o=i;let s=o>=e.length;if(yield{kind:"chunk",...l,nextCursor:s||c===void 0?null:{businessDate:c.businessDate,reportHubId:c.reportHubId},isLast:s,...a?{total:e.length}:{},...a?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...a&&n.restarted?{restarted:!0}:{}},a=!1,s)return}}var Wa=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform",...je});return e&&t.append("Set-Cookie",e),t},qa=(e,t,r,n,o)=>{let a=async(m,u)=>{o(),u&&await Ba(t);try{m.close()}catch{}},i=new TextEncoder,l=!1,c=null,s=new ReadableStream({async pull(m){if(l||r.aborted){await a(m,!0);return}let u=du();try{c===null&&(c=t.next());let f=await Promise.race([c,u.fired]);if(u.stop(),f===ja){if(l||r.aborted){await a(m,!0);return}m.enqueue(i.encode(`
2
- `));return}c=null;let{value:h,done:R}=f;if(R){await a(m,!1);return}if(l||r.aborted){await a(m,!0);return}m.enqueue(i.encode(`${JSON.stringify(h)}
3
- `))}catch(f){if(u.stop(),c=null,o(),l||r.aborted)return;f instanceof $e||n.error(`ids-stream emission failed: ${f instanceof Error?f.message:String(f)}`);try{let h={kind:"error",error:lu};m.enqueue(i.encode(`${JSON.stringify(h)}
4
- `)),m.close()}catch{}}},cancel(){l=!0,o(),Ba(t)}});return new Response(s,{status:200,headers:Wa(e)})},za=e=>{let{service:t,logger:r,streamSlots:n,missGate:o,refuseForcedRead:a}=e,i=async(l,c,s,m,u,f,h)=>{let R=!1,b=null,S=null,A=new Promise((E,D)=>{b=E,S=D});A.catch(()=>{});let x=t.getDailyReportIdsByExternalId(s,c.id,{forceRefresh:l.forceRefresh,admission:h,onFetchStart:l.cursor?void 0:()=>{R=!0,t.readSseStreamAnchor().then(E=>t.getDailyReportIdsFirstPageByExternalId(s,c.id,Dr).then(D=>({items:D,streamAnchor:E}))).then(E=>b?.(E),E=>S?.(E))}});if(x.catch(()=>{}),l.cursor){let{items:E,streamAnchor:D,snapshot:$}=await x,M=l.snapshot!==null&&l.snapshot===$;return qa(m,Va(E,M?l.cursor:null,Dr,{snapshot:$,restarted:!M,streamAnchor:D}),u,r,f)}let F=(async function*(){let E=await Promise.race([x.then(M=>({kind:"full",source:M}),M=>({kind:"full-error",error:M})),A.then(M=>({kind:"page",page:M}),()=>({kind:"page-error"}))]),D=null,$=!1;if(E.kind==="full")D=E.source;else if(E.kind==="page"){let{items:M,streamAnchor:H}=E.page;if(M.length<Dr){yield{kind:"chunk",..._t(M,0,M.length),nextCursor:null,isLast:!0,total:M.length,streamAnchor:H};return}yield{kind:"chunk",..._t(M,0,M.length),nextCursor:null,isLast:!1,provisional:!0},$=!0}else if(E.kind==="full-error"&&R){let M=await A.catch(()=>null);M&&M.items.length>0&&(yield{kind:"chunk",..._t(M.items,0,M.items.length),nextCursor:null,isLast:!1,provisional:!0})}D===null&&(D=await x),yield*Va(D.items,null,$?Ya:Dr,{snapshot:D.snapshot,streamAnchor:D.streamAnchor})})();return qa(m,F,u,r,f)};return async(l,c,s,m,u,f)=>{let h=Fa(l.searchParams);if("refused"in h)return f(s,c,{error:{message:h.refused==="cursor"?"Invalid cursor":"Invalid forceRefresh"}},400);let{query:R}=h;if(R.forceRefresh){let x=a(m,s,c,f);if(x!==null)return x}let b=br(s),S=await t.getUserIdByExternalId(m.id),A=await n.admit(S,"ids-stream",b);if(A===null){let x=f(s,c,{error:{message:cu}},503);for(let[F,E]of Object.entries(Me(503)))x.headers.set(F,E);return x}if(b.aborted)return new Response(null,{status:200,headers:Wa(c)});try{return await i(R,m,u,c,b,A,S===null?void 0:o.admissionFor(S,ie.idsStream,b))}catch(x){if(A(),x instanceof $e)return gr(f,s,c);throw x}}};import{inArray as pu,sql as Ga}from"drizzle-orm";var mu="",yu=64,hu=e=>e.toLowerCase(),fu=e=>e.trim().toLowerCase();function Ka(e){if(e==null)return null;if(!Array.isArray(e))return new Set;let t=new Set;for(let r of e){if(typeof r!="string")continue;let n=fu(r);n.length>0&&t.add(n)}return t}function Le(e,t){return e===null?!0:t==null?!1:e.has(hu(t))}function Ne(e){return e!==null&&e.size===0}function qt(e,t){if(t!==null)return t.size===0?Ga`1 = 0`:pu(Ga`LOWER(${e})`,[...t])}var Mt,Pt,Vt=class Vt{constructor(t,r){jr(this,Mt);jr(this,Pt);Wr(this,Mt,t),Wr(this,Pt,r)}get visible(){return Ot(this,Mt)===null?null:new Set(Ot(this,Mt))}get commentable(){return Ot(this,Pt)===null?null:new Set(Ot(this,Pt))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=Ka(r?t.read:t),o=r?t.comment:void 0;if(o===void 0)return new Vt(n,n);let a=Ka(o),i=new Set;for(let l of a??[])n.has(l)&&i.add(l);return new Vt(n,i)}static unrestricted(t){return new Vt(null,null)}};Mt=new WeakMap,Pt=new WeakMap;var He=Vt;function Yt(e){let t=Ja(e.visible),r=Ja(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function Ja(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(mu);if(t.length<=yu)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 Qa=(e,t,r,n)=>Le(n.commentable,t)||e.authorUserId!==null&&e.authorUserId===r;import{parseQuerySets as Qu}from"@aiquants/fuzzy-search";import{createHash as Ru}from"crypto";import{setImmediate as Xa}from"timers/promises";import{clusterCountOf as Su,DEFAULT_NORMALIZE_OPTIONS as Tr,InteriorPairs as gu,isAnswerTier as bu,normalizeText as Du,queryNeedles as Au,resolveNormalizeOptions as Tu,toMappedFormsInto as Eu,trimmedRange as wu}from"@aiquants/fuzzy-search/normalize";var Er=`
5
- `,kn=4e3,Iu=1,ei=new Set([8203,8288,65279,173]),_u=new RegExp(`[${String.fromCodePoint(...ei)}]`,"gu"),xu=new RegExp(`\\r\\n|[\\n\\r${String.fromCodePoint(133,8232,8233)}]`,"gu"),Cu=/(\s+)/u,Mu=/^\s+$/u,Pu=/^(?:(?=\p{Lo})[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]|[A-Za-z0-9])$/u,Lu=new Set([8205,1536,1537,1538,1539,1540,1541,1757,1807,2192,2193,2274,69821,69837,70082,70083,71999,72001,72250,72324,72325,72326,72327,72328,72329,73030,73474]),jt=e=>e.replace(_u,""),ti=e=>{let t=jt(e);if(t.length===e.length)return{text:t,rawIndex:null};let r=new Uint32Array(t.length),n=0;for(let o=0;o<e.length;o++)ei.has(e.charCodeAt(o))||(r[n++]=o);return{text:t,rawIndex:r}},vn=e=>Du(e,Tr),Ar=e=>vn(jt(e)),Nu=Tu({...Tr,convertRomaji:!0},"[daily-report] search reading options"),ku=3,vu=/^[-ー]+/u,Ou=/[^\p{L}\p{M}]/gu,Fu=/ー{2,}/gu,Hu=/\p{Script=Latin}/u,Za=/(?=\p{L})\p{Script=Latin}/u,Uu=e=>Su(e.replace(vu,"").replace(Ou,"").replace(Fu,"\u30FC")),$u=(e,t)=>{for(let r of t)if(!bu(r.tier)||r.splitTier!==null)throw new Error(`[daily-report] search readings: queryNeedles gave an unfinished needle for the word ${JSON.stringify(e)} (text ${JSON.stringify(r.text)}, tier ${r.tier}, splitTier ${r.splitTier})`)},ri=e=>{if(!Za.test(e))return[];let t=Ar(e);if(!Za.test(t))return[];let r=Au(t,Nu,!1);$u(t,r);let n=[];for(let o of r){if(o.tier===ft.word)continue;let a=Ar(o.text);if(!(a.length===0||a.length>_e.maxWordLength)&&!(a===t||Hu.test(a))&&!(Uu(a)<ku||n.includes(a))&&(n.push(a),n.length===rn))break}return n},ni=(e,t)=>{let r=e.charCodeAt(t-1),n=e.charCodeAt(t);return r>=55296&&r<=56319&&n>=56320&&n<=57343},Bu=(e,t)=>{let r=e.codePointAt(t),n=t>=2&&ni(e,t-1)?t-2:t-1;return Pu.test(String.fromCodePoint(r))&&!Lu.has(e.codePointAt(n))},Vu=(e,t,r)=>{let n=[],o=0,a=0;for(;e.length-a>r;){let i=a+r;for(;i>a&&!Bu(e,i);)i--;i===a&&(i=a+r,ni(e,i)&&i--,o++),n.push({start:t+a,end:t+i}),a=i}return n.push({start:t+a,end:t+e.length}),{pieces:n,forcedCuts:o}},wr=(e,t)=>{if(e.length<=t)return{chunks:[[{start:0,end:e.length}]],forcedCuts:0};let r=[],n=0,o=0,a=0,i=0,l=()=>{i>0&&r.push([{start:a,end:a+i}]),i=0};for(let c of e.split(Cu)){let s=o;if(o+=c.length,i+c.length<=t){i===0&&(a=s),i+=c.length;continue}if(l(),Mu.test(c))continue;if(c.length<=t){a=s,i=c.length;continue}let m=Vu(c,s,t);n+=m.forcedCuts,r.push(m.pieces)}return l(),{chunks:r,forcedCuts:n}},On=(e,t)=>{let r=wr(e,t),n=[];for(let o of r.chunks){let a=o.map(i=>vn(e.slice(i.start,i.end))).join("");a.length>0&&n.push(a)}return{text:n.join(" "),forcedCuts:r.forcedCuts}},Fn=(e,t)=>{let r=0;for(let n of e.matchAll(xu))t(e.slice(r,n.index),r),r=n.index+n[0].length;t(e.slice(r),r)},qu=(e,t)=>{if(e.partialReadings!==null)throw new Error(`[daily-report] search marks: the mapped forms of the piece ${JSON.stringify(t)} carry partial readings`);return e.canonical},oi=(e,t)=>{let r="",n=[],o=[];for(let a of t.chunks){let i="",l=[],c=[];for(let s of a){let m=e.slice(s.start,s.end),u=qu(Eu(m,Tr,new gu(0)),m),[f,h]=wu(u.text);i+=u.text.slice(f,h);for(let R=f;R<h;R++)l.push(s.start+u.start[R]),c.push(s.start+u.end[R])}if(i.length!==0){r.length>0&&(r+=" ",n.push(o[o.length-1]),o.push(l[0])),r+=i;for(let s=0;s<l.length;s++)n.push(l[s]),o.push(c[s])}}return{text:r,start:n,end:o}},Ir=(e,t=kn)=>{let r=[],n=0;return Fn(jt(e),o=>{let a=On(o,t);n+=a.forcedCuts,a.text.length>0&&r.push(a.text)}),{text:r.join(Er),forcedCuts:n}},ai=e=>e.filter(t=>t.length>0).join(Er),Yu=e=>{let t=[];for(let r=0;r<=65535;r++)r>=55296&&r<=57343||t.push(e+String.fromCharCode(r));return t.join(`
6
- `)},ju=[`\u3067\u3093${String.fromCodePoint(8203)}\u3077\u3093 \uFF83\uFF9E\uFF9D\uFF8C\uFF9F\uFF9D\r
7
- \u30C7\u30F3\u30D7\u30F3`,"\u30DD\u30C6\u30C8-25kg \u30A2--1 \u30FC\u30FC\u30E1\u30F3 \u4F50\u3005\u6728","\u6F22\u5B57\u304B\u306A\u30AB\u30CAABC123\u6F22\u5B57\u304B\u306A\u30AB\u30CAABC123\u6F22\u5B57\u304B\u306A\u30AB\u30CA",`\uFF71\uFF72\uFF73\uFF74\uFF75\uFF76\uFF9E\uFF77\uFF9E\uFF78\uFF9E\uFF79\uFF9E\uFF7A\uFF9E${String.fromCodePoint(8232)}\u6B21\u306E\u884C`],Wu=["","\u30A2","\u4F50"," "],zu=()=>JSON.stringify(ju.map(e=>Ir(e,8))),Gu=e=>`dr-search-v${Iu};fz=${e.slice(0,16)};u=${process.versions.unicode};icu=${process.versions.icu}`;var Ku=async()=>{let e=Ru("sha256");e.update(JSON.stringify(Tr));for(let t of Wu)await Xa(),e.update("\0"),e.update(vn(Yu(t)));return await Xa(),e.update("\0"),e.update(zu()),Gu(e.digest("hex"))},Ju=e=>{let t=null;return()=>{if(t===null){let r=e();t=r,r.catch(()=>{t=null})}return t}},Hn=Ju(Ku);var Xu=/^-+/u,Zu=/\s+/u,ii=e=>{let t=Xu.exec(e);return t===null?[e]:[e,"\u30FC".repeat(t[0].length)+e.slice(t[0].length)]},ed=(e,t)=>{let r=[...ii(e).map(n=>({text:n,tier:ft.word})),...t.flatMap(n=>ii(n).map(o=>({text:o,tier:ft.reading})))];return r.filter((n,o)=>r.findIndex(a=>a.text===n.text)===o)},td=e=>JSON.stringify(e.map(({text:t,tier:r})=>JSON.stringify([r,t])).sort()),_r=(e,t)=>{if(e.length>_e.maxQueryLength)return{ok:!1,reason:"too-long"};let r=[],n=new Set,o=0;for(let{query:a}of Qu(jt(e),t).sets){let i=[],l=new Set;for(let s of a.split(Zu)){let m=Ar(s);if(m.length===0)return{ok:!1,reason:"blank-word"};if(m.length>_e.maxWordLength)return{ok:!1,reason:"word-too-long"};let u=ed(m,ri(s)),f=td(u);l.has(f)||(l.add(f),i.push({alternatives:u}))}if(i.length>_e.maxWordsPerSet)return{ok:!1,reason:"too-many-words-in-set"};let c=JSON.stringify([...l].sort());n.has(c)||(n.add(c),o+=i.length,r.push({words:i}))}return r.length===0?{ok:!1,reason:"empty"}:r.length>_e.maxSets?{ok:!1,reason:"too-many-sets"}:o>_e.maxWords?{ok:!1,reason:"too-many-words"}:{ok:!0,plan:{combine:t,sets:r}}},Wt=e=>e.sets.map(t=>t.words.map(r=>r.alternatives));var Uh=Object.freeze({sourceTypes:null,authors:null,customers:null}),rd=e=>e.sourceTypes!==null||e.authors!==null||e.customers!==null,si=(e,t,r)=>{if(Eo(e)&&rd(r))return{ok:!0,criteria:{plan:null,filters:r}};let n=_r(e,t);return n.ok?{ok:!0,criteria:{plan:n.plan,filters:r}}:{ok:!1,reason:n.reason}};var li=6e4,nd=1,od=3200,ci=2e3,ad=Object.freeze({search:od,reports:ci,"search-marks":ci,"search-facets":null}),id=(e,t)=>{let r=ad[e];return r===null?null:{max:t,maxPerOwner:sr,maxWaitMs:r}},zt=e=>{let{concurrency:t,route:r,logger:n}=e,o=tt({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:li,logger:n,windowFields:()=>`route=${r}`}),a=We({limit:t,maxHeldPerOwner:Math.max(1,Math.floor(t/2)),queue:id(r,t)}),i=Object.freeze({status:429,message:_n,headers:Object.freeze({"Retry-After":String(nd)})}),l=Fe({windowMs:li,tallies:["busy"],writeSuppressed:(c,{count:s,since:m})=>{n.warn(`busy_suppressed count=${s} since=${m} route=${r} concurrency=${t}`)}});return{admit:async(c,s)=>{let m=o.spend(c,r);if(m!==null)return{refusal:m};let u=await a.acquire(c,s);return u!==null?{release:u}:(o.refund(c,1),s.aborted||l.record(r,"busy",()=>n.warn(`429 ${r} reason=busy concurrency=${t}`)),{refusal:i})}}};import{systemSseRuntime as yd}from"@aiquants/sse";import{createSseResponse as hd,readLastEventId as fd,startSseHeartbeat as Rd,terminalStreamResponse as Sd}from"@aiquants/sse/server";var Gt=(e,t)=>{let r=e.message.data;if(!r)return{entry:{id:e.id,message:null},json:void 0};let n;try{n=JSON.parse(r)}catch(i){return t.error(`SSE message ${e.id} is not JSON:`,i),{entry:{id:e.id,message:null},json:void 0}}let o=Ao.safeParse(n);if(!o.success)return t.error("SSE message validation failed:",o.error.format()),{entry:{id:e.id,message:null},json:n};let a=Object.freeze({parsed:o.data,published:n,text:r});return{entry:Object.freeze({id:e.id,message:a}),json:n}},sd=["externalComments","postedComments"],ui=new WeakMap,ld=e=>{let t=ui.get(e);if(t!==void 0)return t;let r={recipientRemoved:null,commentsRedacted:null};return ui.set(e,r),r},di=e=>{let{recipientRawUserId:t,...r}=e;return r},pi=(e,t)=>{let{published:r}=e;if(!(t||Object.hasOwn(r,"recipientRawUserId")))return e.text;let n=ld(e);if(t){if(n.commentsRedacted===null){let o=di(r),a=o.report;n.commentsRedacted=JSON.stringify({...o,report:{...a,...Object.fromEntries(sd.map(i=>[i,[]]))}})}return n.commentsRedacted}return n.recipientRemoved===null&&(n.recipientRemoved=JSON.stringify(di(r))),n.recipientRemoved};import{systemSseRuntime as ud}from"@aiquants/sse";import{createSharedSource as dd}from"@aiquants/sse/shared-source";var gt="daily-report:ids:",bt="daily-report:business-date:",xr=(e,t)=>`${e}st:${t}`,Un=e=>`${gt}user:${e}:`,mi=(e,t)=>xr(Un(e),t),cd=e=>`${bt}${e}:`,yi=(e,t)=>xr(cd(e),t),Kt=e=>`daily-report:date:${e}:user:`,Lt=(e,t)=>`${Kt(e)}${t}:`,hi=(e,t,r)=>xr(Lt(e,t),r),Ge=e=>`daily-report:detail:${e}:user:`,Cr=(e,t)=>`${Ge(e)}${t}:`,fi=(e,t,r)=>xr(Cr(e,t),r);var dt=(e,t)=>{let[r,n]=e.split("-").map(Number),[o,a]=t.split("-").map(Number);return r!==o?r<o:n<=a},pd=5e3,md=ur,Jt=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=Se(t.logger,1,"SseReader"),this._source=this._createSource()}ready(){return this._position().then(()=>{})}subscribe(t,r){return this._source.subscribe({next:n=>{this._lastId=n.id,t(n)},error:n=>r(n instanceof Error?n:new Error(String(n)))})}async destroy(){await this._source.dispose(),this._generation+=1,this._positioning=null,this._lastId=null,this._source=this._createSource()}_position(){if(this._lastId!==null)return Promise.resolve(this._lastId);if(this._positioning===null){let t=this._generation;this._positioning=this._readTail().then(r=>{if(t!==this._generation)throw new Error("SSE reader was destroyed while the stream tail was being read");return this._positioning=null,this._lastId=r,r},r=>{throw t===this._generation&&(this._positioning=null),r})}return this._positioning}async _readTail(){let t=await this.config.redis?.getClient();if(!t)throw new Error("Failed to get Redis client to read the SSE stream tail");let r=await t.xRevRange(this.config.streamKey,"+","-",{COUNT:1});return r.length>0?r[0].id:"0-0"}_createSource(){return dd({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:ud,onListenerError:t=>this._logger.error("SSE reader subscriber threw:",t),onStopError:t=>this._logger.error("SSE reader failed to stop:",t)})}async _start(t){let r=await this._position(),n=await this.config.redis?.createClient();if(!n)throw new Error("Failed to create Redis client for SSE reader");n.on("error",i=>{this._logger.error("Redis client error:",i)});let o=!1,a=this._readLoop(n,t,r,()=>o);return async()=>{if(o=!0,n.isOpen)try{await n.quit()}catch{}await a}}async _readLoop(t,r,n,o){let a=n;try{for(;!o()&&t.isOpen;){let i=await t.xRead([{key:this.config.streamKey,id:a}],{BLOCK:pd,COUNT:md});if(i)for(let l of i)for(let c of l.messages){a=c.id;let{entry:s,json:m}=Gt(c,this._logger);this._invalidateCaches(m),r.next(s)}}}catch(i){o()||(this._logger.error("xRead loop error:",i),r.fail(i instanceof Error?i:new Error(String(i))));return}o()||r.fail(new Error("Redis client for SSE reader closed unexpectedly"))}_invalidateCaches(t){if(t===null||typeof t!="object")return;let{type:r,reportHubId:n}=t;(r==="report-create"||r==="report-delete"||r==="report-publish")&&this.config.cache.invalidatePrefix(gt),(r==="comment-add"||r==="comment-delete"||r==="status-update")&&typeof n=="number"&&this.config.cache.invalidatePrefix(Ge(n))}};var gi=Object.freeze({...$t,route:"sse",frameworkDataRefusal:dr}),Ri=864e5,gd={baseMs:2e3,jitterMs:8e3},bi=6e4,$n=ur,Di=JSON.stringify({type:"connected"}),Si="0-0",bd=(e,t,r,n)=>{if(r===null&&n===null)return!0;let o=typeof t.sourceType=="string"?t.sourceType:void 0;switch(e.type){case"connected":case"status-update":return!0;case"report-create":case"report-update":case"report-publish":return Le(r,e.report.sourceType);case"comment-add":case"comment-delete":return Le(n,o??"Internal");case"report-delete":return Le(r,o)}},Dd=(e,t)=>t===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"?!1:!Le(t,e.report.sourceType),Ad=(e,t)=>{e.writeEvent({event:null,id:t,data:Di})},Td=(e,t,r)=>{let{message:n}=t;if(n===null)return;let{parsed:o,published:a}=n,i=typeof a.recipientRawUserId=="number"?a.recipientRawUserId:void 0;if((o.type==="status-update"||i!==void 0)&&i!==r.internalUserId||!bd(o,a,r.visibleSet,r.commentableSet)){Ad(e,t.id);return}e.writeEvent({event:null,id:t.id,data:pi(n,Dd(o,r.commentableSet))})},Ai=e=>{let{authenticate:t,service:r,resolveViewerScope:n,redis:o,sseReader:a,streamKey:i,streamSlots:l,logger:c}=e,s=async(m,u)=>{let{request:f,internalUserId:h,cursor:R}=u,b=u.initialScope.visible,S=u.initialScope.commentable,A=0,x=setInterval(()=>{let G=++A;n(f,"refresh").then(se=>{G===A&&(b=se.visible,S=se.commentable)})},bi);m.onClose(()=>clearInterval(x));let F=R===null?Si:R,E=R!==null&&o!==void 0,D=[],$=null,M=G=>{dt(G.id,F)||(F=G.id,Td(m,G,{internalUserId:h,visibleSet:b,commentableSet:S}))},H=async(G,se)=>{let[re]=await G.xRange(i,"-","+",{COUNT:1});return re!==void 0&&!dt(re.id,se)},de=async(G,se)=>{if(await H(G,se))return!1;let re=se;for(;;){let ce=await G.xRange(i,re,"+",{COUNT:$n}),me=ce[0];if(me!==void 0&&me.id!==re&&await H(G,re))return!1;for(let Ke of ce){if($!==null&&dt($,Ke.id))return!0;dt(Ke.id,F)||M(Gt(Ke,c).entry)}let he=ce.at(-1);if(ce.length<$n||he===void 0||m.isClosed())return!0;re=he.id}},pe=a.subscribe(G=>{if(!E){M(G);return}dt(G.id,F)||($===null&&($=G.id),D.push(G))},G=>{c.error(`[SSE:${h}] Fan-Out reader error:`,G),m.close()});if(m.onClose(pe),R===null){await a.ready();try{let G=await o?.getClient();if(G){let se=await G.xRevRange(i,"+","-",{COUNT:1});se.length>0&&!dt(se[0].id,F)&&(F=se[0].id)}}catch{}}if(m.writeEvent({event:null,id:F===Si?null:F,data:Di}),Rd(m,{intervalMs:So,retry:gd,runtime:yd}),R===null||o===void 0)return;await a.ready();let ge=await o.getClient();if(ge===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await de(ge,R)){m.writeRetry(Ri),m.writeEvent({event:"resync-required",id:null,data:""}),m.close();return}E=!1;for(let G of D.splice(0))M(G)};return async({request:m,params:u})=>{let f,h=()=>{let b=new Headers;f!==void 0&&b.append("Set-Cookie",f);for(let[S,A]of Object.entries(je))b.set(S,A);return b},R=b=>Sd(b,{data:"",retryMs:Ri,headers:h()});try{let b=await t(m,{failureRedirect:null});f=b.cookie;let{user:S}=b;if(!S)return R("auth-required");let A=await r.getUserIdByExternalId(S.id);if(!A)return R("forbidden");if(u.endpoint!=="updates")return new Response("Not Found",{status:404,headers:h()});let x=fd(m,go);if(x!==null&&!bo(x))return c.warn(`[SSE:${A}] malformed resume cursor; asking the client to resync`),R("resync-required");let F=br(m),E=await l.admit(A,"sse",F);if(E===null){let $=h();for(let[M,H]of Object.entries(Me(503)))$.set(M,H);return new Response("Too many streams",{status:503,headers:$})}let D=!1;try{let $=await n(m,"initial");return hd({requestSignal:F,headers:h(),onError:(M,H)=>c.error(`[SSE:${A}] ${H} failed:`,M),produce:M=>(D=!0,M.onClose(E),s(M,{request:m,internalUserId:A,cursor:x,initialScope:$}))})}finally{D||E()}}catch(b){if(b instanceof Response)throw b;let S=b instanceof Error?b:new Error(String(b));return c.error(`500 sse name=${S.name} message=${S.message}`),new Response("Internal Server Error",{status:500,headers:h()})}}};var Ti=(e,t)=>{let r=new Headers({...t?.headers,"Content-Type":"application/json",...je});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},Ed=Object.freeze({...$t,route:"api",frameworkDataRefusal:({params:e})=>Rn(e.endpoint)&&St[e.endpoint].body==="stream"?dr():null}),wd=Object.freeze({...$t,route:"action"}),Id=(e,t,r)=>({...r,status:"OK",intent:e.intent,reportHubId:t,clientTempId:e.clientTempId}),xi=6e4,Ci=5,_d=Ci*Math.ceil(xi/500),xd=2,Cd=6,Md=6e4,Pd=Ci*xd*Cd,Ld=2,Nd=10,kd=2,vd=10,Ei=(e,t)=>Math.max(e,sr)*t,Mi=(e,t)=>{for(let[r,n]of Object.entries(t))e.headers.set(r,n);return e},Od=Object.freeze({etag:(e,t,r)=>Uo(e,t,r,200),"no-store":(e,t,r)=>An(t,r,200)}),Fd=e=>Tn(e.body==="json"?Od[e.cache]:null),wi=Tn(null),Ii=(e,t,r,n)=>Mi(e(t,r,{error:{message:n.message}},n.status),n.headers),_i=(e,t,r)=>Mi(e(t,r,null,503),Me(503));function Bn(e){Sr(e);let{authenticate:t,service:r,encodeUserId:n,redis:o,sseReader:a,streamKey:i}=e,l={titleMaxLength:te("service.titleMaxLength",r.titleMaxLength,1)},c=e.loginRedirectPath??"/auth/login",s=Se(e.logger,3,"API"),m=Se(e.logger,3,"Visibility"),u=Se(e.logger,1,"SSE"),f=Se(e.logger,1,"Attachment"),h=Se(e.logger,2,"Isolation"),R=Se(e.logger,2,"Action"),b=Se(e.logger,2,"Search"),S=Se(e.logger,2,"Refresh"),A=Se(e.logger,2,"Streams"),x=Se(e.logger,2,"Reads"),F=tt({reason:"refresh_rate_limit",limitPerWindow:Pd,windowMs:Md,logger:S,windowFields:()=>"route=api"}),E=Ua(A),D=Oa(x),$=async(T,O,N,P,U,W)=>{let K=await r.getUserIdByExternalId(O.id);try{return await W(K===null?void 0:D.admissionFor(K,T,N.signal))}catch(z){if(z instanceof $e)return gr(U,N,P);throw z}},M=(T,O,N,P,U)=>{let W=F.spend(O.id,`endpoint=${T}`);return W===null?null:Ii(U,N,P,W)},H=async(T,O="initial")=>{let N=e.resolveVisibleSourceTypes;if(!N)return He.unrestricted("no visibility port injected: this deployment does not restrict by source type");try{let P=await N(T,{reason:O});return P==null?He.unrestricted("visibility port returned null/undefined: this deployment opts out of source-type filtering"):He.restrictTo(P)}catch(P){return m.error("resolveVisibleSourceTypes threw; failing closed (deny all)",P),He.restrictTo([])}},de=async({request:T})=>{let{user:O,cookie:N}=await t(T,{failureRedirect:c}),P=new Headers;N&&P.append("Set-Cookie",N);let U=await r.getUserIdByExternalId(O.id),W=U?n(U):null;return{data:{user:O,userId:W},headers:P}},pe=T=>{let{limiter:O}=T;return async(N,P,U,W,K,z)=>{if(O===null)return z(U,P,{error:{message:"Unknown endpoint"}},404);let X=T.parse(N);if(!X.ok)return z(U,P,X.invalid,400);let k=await r.getUserIdByExternalId(W.id);if(!k)return z(U,P,T.emptyAnswer(X.parsed),200);let{signal:ae}=U,fe=await O.admit(k,ae);if("refusal"in fe)return ae.aborted?_i(z,U,P):Ii(z,U,P,fe.refusal);try{ae.throwIfAborted();let ye=await T.read(X.parsed,{userId:k,user:W,scope:K},ae);return ae.throwIfAborted(),z(U,P,ye,200)}catch(ye){if(ae.aborted&&ye===ae.reason)return _i(z,U,P);throw ye}finally{fe.release()}}},ge=r.searchLimits===null?null:zt({...r.searchLimits,route:ie.search,logger:b}),G=r.searchLimits===null?null:zt({concurrency:Ei(r.searchLimits.concurrency,Ld),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*Nd,route:ie.reports,logger:b}),se=r.searchLimits===null?null:zt({concurrency:Ei(r.searchLimits.concurrency,kd),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*vd,route:ie.searchMarks,logger:b}),re=r.searchLimits===null?null:zt({...r.searchLimits,route:ie.searchFacets,logger:b}),ce={[ie.businessDate]:async(T,O,N,P,U,W)=>{let K=T.searchParams.get(Re.businessDate),z=K===null?null:It(K);if(z===null)return W(N,O,{error:{message:"Invalid business date"}},400);let X=Ut(T.searchParams.get(Re.forceRefresh));if(X===null)return W(N,O,{error:{message:"Invalid forceRefresh"}},400);let k=X?M(ie.businessDate,P,N,O,W):null;return k!==null?k:$(ie.businessDate,P,N,O,W,async ae=>{let fe=await r.getDailyReportsByBusinessDateByExternalId(U,z,P.id,{forceRefresh:X,admission:ae});return W(N,O,{businessDate:z,reports:fe},200)})},[ie.idsStream]:za({service:r,logger:s,streamSlots:E,missGate:D,refuseForcedRead:(T,O,N,P)=>M(ie.idsStream,T,O,N,P)}),[ie.report]:async(T,O,N,P,U,W)=>{let K=Be(T.searchParams.get(Re.reportHubId));if(K===null)return W(N,O,{error:{message:"Invalid reportHubId"}},400);let z=Ut(T.searchParams.get(Re.forceRefresh));if(z===null)return W(N,O,{error:{message:"Invalid forceRefresh"}},400);let X=z?M(ie.report,P,N,O,W):null;return X!==null?X:$(ie.report,P,N,O,W,async k=>{let ae=await r.getDailyReportDetailByIdByExternalId(U,K,P.id,{snapshot:!0,forceRefresh:z,admission:k});return ae?W(N,O,{report:ae},200):W(N,O,{error:{message:"Report not found"}},404)})},[ie.search]:pe({limiter:ge,parse:T=>{let O=T.searchParams.get(Re.searchQuery),N=hn(T.searchParams.get(Re.searchCombine));if(O===null||N===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let P=Io(T.searchParams,r.searchFilterSourceTypes);if(!P.ok)return{ok:!1,invalid:{error:{message:"Invalid search filters",reason:P.reason}}};let U=si(O,N,P.filters);if(!U.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:U.reason}}};let{criteria:W}=U;return{ok:!0,parsed:{criteria:W,words:W.plan===null?[]:Wt(W.plan)}}},emptyAnswer:({words:T})=>nn([],T),read:async({criteria:T,words:O},{userId:N,scope:P})=>nn(await r.searchDailyReports(P,N,T),O)}),[ie.reports]:pe({limiter:G,parse:T=>{let O=fn(T.searchParams.get(Re.reportIds));return O===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:O}},emptyAnswer:()=>({reports:[]}),read:async(T,{user:O,scope:N})=>({reports:await r.getDailyReportDetailsByIdsByExternalId(N,T,O.id)})}),[ie.searchMarks]:pe({limiter:se,parse:T=>{let O=T.searchParams.get(Re.searchQuery),N=hn(T.searchParams.get(Re.searchCombine));if(O===null||N===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let P=_r(O,N);if(!P.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:P.reason}}};let U=fn(T.searchParams.get(Re.reportIds));return U===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:{plan:P.plan,ids:U}}},emptyAnswer:({plan:T})=>({wordsDigest:ir(Wt(T)),reports:[],deferred:[]}),read:({plan:T,ids:O},{userId:N,scope:P},U)=>r.markDailyReportSearchHits(P,N,T,O,{signal:U})}),[ie.searchFacets]:pe({limiter:re,parse:()=>({ok:!0,parsed:null}),emptyAnswer:()=>({sourceTypes:[],authors:[],customers:[]}),read:(T,{userId:O,scope:N})=>r.listDailyReportSearchFacets(N,O)})},me=async({request:T,params:O})=>{let{user:N,cookie:P}=await t(T,{failureRedirect:null}),U=P??null;if(!N)return wi(T,U,{error:{message:"Unauthorized"}},401);let W=O.endpoint;if(!Rn(W))return wi(T,U,{error:{message:"Unknown endpoint"}},404);let K=St[W],z=Fd(K),X=Oo[K.body];if(!X.includes(T.method)){let ae=z(T,U,{error:{message:"Method not allowed"}},405);return ae.headers.set("Allow",X.join(", ")),ae}let k=ue();try{let ae=new URL(T.url),fe=await H(T),ye=await ce[W](ae,U,T,N,fe,z);return K.body==="json"&&s.debug(ye.headers.has("ETag")?`${ye.status} endpoint=${W} etag_match=${ye.status===304}`:`${ye.status} endpoint=${W}`),ye}catch(ae){let fe=ue()-k,ye=ae instanceof Error?ae:new Error(String(ae));return s.error(`500 endpoint=${W} elapsed=${fe}ms name=${ye.name} code=${"code"in ye?ye.code:"N/A"} message=${ye.message}`,ye),z(T,U,{error:{message:"Internal Server Error"}},500)}},he=vo(R),Ke=tt({reason:"rate_limit",limitPerWindow:_d,windowMs:xi,logger:R,windowFields:()=>"route=action"}),oe=async(T,O,N,P,U)=>{let{clientTempId:W}=T;if(T.intent==="create"){let k=await r.createDailyReport(O,T.businessDate,W);return U(T,k.reportHubId,{report:k})}let{reportHubId:K,businessDate:z}=T,X=async(k,ae)=>{try{let fe=await ae(k.value);return U(k,K,{updatedStatus:{isStarred:fe.isStarred,isRead:fe.isRead},operationTimestamp:k.operationTimestamp})}catch(fe){if(fe instanceof Error&&fe.message==="Not Found")return P({error:"Report not found"},{status:404});throw fe}};switch(T.intent){case"update":try{return await r.updateDailyReport(K,O,T.changes,W),U(T,K,{})}catch(k){if(k instanceof Error){if(k.message==="Unauthorized")return P({error:"Unauthorized"},{status:403});if(k.message==="Not Found")return P({error:"Report not found"},{status:404})}throw k}case"publish":try{let k=await r.publishDailyReport(K,O,W);return U(T,K,{report:k})}catch(k){if(k instanceof Error){if(k.message==="Unauthorized")return P({error:"Unauthorized"},{status:403});if(k.message==="Not Found")return P({error:"Report not found"},{status:404})}throw k}case"delete":try{return await r.deleteDailyReport(K,O,W),U(T,K,{})}catch(k){if(k instanceof Error){if(k.message==="Unauthorized")return P({error:"Unauthorized"},{status:403});if(k.message==="Not Found")return P({error:"Report not found"},{status:404})}throw k}case"toggleStar":return await X(T,k=>r.setStarStatus(N,O,K,z,k,W));case"toggleRead":return await X(T,k=>r.setReadStatus(N,O,K,z,k,W));case"addComment":try{let k=await r.addComment(N,O,K,T.content,z,W);return U(T,K,{newComment:k})}catch(k){if(k instanceof Error){if(k.message==="Not Found")return P({error:"Report not found"},{status:404});if(k.message.startsWith("Comments are restricted"))return P({error:"Comments are restricted for this report"},{status:403})}throw k}case"deleteComment":try{return await r.deleteComment(N,O,K,T.commentId,z,W),U(T,K,{deletedCommentId:T.commentId})}catch(k){if(k instanceof Error){if(k.message==="Unauthorized")return P({error:"Unauthorized"},{status:403});if(k.message==="Not Found")return P({error:"Comment not found"},{status:404})}throw k}}},ke=async({request:T,params:O})=>{let{user:N,cookie:P}=await t(T,{failureRedirect:null}),U=(z,X)=>Ti(z,{...X,setCookie:P}),W=(z,X,k)=>Ti(Id(z,X,k),{setCookie:P});if(!N)return U({error:"Unauthorized"},{status:401});let K=ue();try{if(O.endpoint!==ie.action)return U({error:"Unknown endpoint"},{status:404});let z=Ke.spend(N.id,"action");if(z!==null)return U({error:z.message},{status:z.status,headers:z.headers});let X=await ko(T,l);if("refusal"in X){let{refusal:ye}=X;return ye.status===413&&he(ye.measuredBy),U({error:ye.error},{status:ye.status})}let{command:k}=X;if(k.intent==="clearCache"&&!e.enableDevCacheClear)return U({error:"Invalid intent"},{status:400});let ae=await r.getUserIdByExternalId(N.id);if(!ae)return U({error:"User not found"},{status:404});let fe=await H(T);return k.intent==="clearCache"?(await r.clearCache(),U({status:"OK",intent:"clearCache"})):await oe(k,ae,fe,U,W)}catch(z){if(z instanceof Response)throw z;let X=ue()-K,k=z instanceof Error?z:new Error(String(z));return s.error(`500 action elapsed=${X}ms name=${k.name} message=${k.message}`,k),U({error:"Internal Server Error"},{status:500})}},Ue=Ai({authenticate:t,service:r,resolveViewerScope:H,redis:o,sseReader:a,streamKey:i,streamSlots:E,logger:u}),it=Pa({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:H,logger:f}),st=Yo(h),Ee=(T,O)=>async N=>{let P=Vo(N.request)?T.frameworkDataRefusal(N):null;if(P!==null)throw P;return qo(N.request,T)?(st(T.route,N.request),T.crossSiteRejection()):O(N)};return{index:{loader:de},api:{loader:Ee(Ed,me),action:Ee(wd,ke)},sse:{loader:Ee(gi,Ue)},attachment:{loader:Ee(Ma,it)}}}import{chunk as yp,MAX_IN_LIST as hp,runWithTransactionRetry as fp}from"@aiquants/mssql";import{and as Ae,asc as Ce,desc as Nt,eq as V,getColumns as Rp,inArray as ot,isNull as kt,sql as Kn}from"drizzle-orm";import{sql as pt}from"drizzle-orm";var Pi=e=>{if(e.length===0)throw new Error("[daily-report] draft rule: draftLabelNames must hold at least one name (a rule without names would show every draft to every viewer)");return pt.join(e.map(t=>pt`${t}`),pt`, `)},Pr=(e,t)=>{let{hub:r,hubLabel:n,label:o}=e;return pt`EXISTS (SELECT 1 FROM ${n} INNER JOIN ${o} ON ${o.id} = ${n.labelId} WHERE ${n.hubId} = ${r.id} AND ${o.name} IN (${Pi(t)}))`},Li=(e,t)=>{let{hubLabel:r,label:n}=e;return pt`${r.labelId} IN (SELECT ${n.id} FROM ${n} WHERE ${n.name} IN (${Pi(t)}))`},Lr=(e,t,r,n)=>{let{hub:o}=e,a=n==="author-or-authorless"?pt`${o.userId} = ${t} OR ${o.userId} IS NULL`:pt`${o.userId} = ${t}`;return pt`(${a} OR NOT ${Pr(e,r)})`};var Hd=["tables","externalSourceTexts","concurrency","rateLimitPerMinute"],Ud=["document","comment"],$d=["hubId","searchText","sourceDigest","normalizerVersion","indexedAt","rowVersion","authorName","customerName"],Bd=["hubId","ordinal","authorUserId","commentText"],Vn=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Ni=(e,t,r)=>{for(let n of Object.keys(t))if(!r.includes(n))throw Gr(e,n,r)},ki=(e,t,r)=>{if(typeof t!="object"||t===null)throw ne(e,"a table object",t);let n=t;for(let o of r)if(typeof n[o]!="object"||n[o]===null)throw ne(`${e}.${o}`,"a column",n[o])},vi=(e,t)=>{if(!Vn(e))throw ne("search","a plain object",e);Ni("search key",e,Hd);let{tables:r}=e;if(!Vn(r))throw ne("search.tables","a plain object with document and comment",r);Ni("search.tables key",r,Ud),ki("search.tables.document",r.document,$d),ki("search.tables.comment",r.comment,Bd);let n=new Map;if(e.externalSourceTexts!==void 0){if(!Vn(e.externalSourceTexts))throw ne("search.externalSourceTexts","a plain object",e.externalSourceTexts);for(let[o,a]of Object.entries(e.externalSourceTexts)){if(!t.includes(o))throw Gr("search.externalSourceTexts key",o,t);if(typeof a!="function")throw ne(`search.externalSourceTexts.${o}`,"a function",a);n.set(o,a)}}return{tables:r,externalSourceTexts:n,concurrency:te("search.concurrency",e.concurrency,1),rateLimitPerMinute:te("search.rateLimitPerMinute",e.rateLimitPerMinute,1)}};var mt=e=>{let t=typeof e=="object"&&e!==null?e.recordset:void 0;if(!Array.isArray(t))throw new Error("[daily-report] search: the database result has no recordset");return t},Dt=(e,t)=>{let r=typeof e=="string"?Be(e):typeof e=="number"&&lt(e)?e:null;if(r===null)throw new Error(`[daily-report] search: column ${t} holds no positive id`);return r},At=(e,t)=>{if(e===null||typeof e=="string")return e;throw new Error(`[daily-report] search: column ${t} holds no string`)};import{sql as B}from"drizzle-orm";var Vd=/[[%_]/gu,qd=e=>e.replace(Vd,t=>`[${t}]`),Oi=e=>`%${qd(e)}%`;var qe=Object.freeze({reportHubId:"report_hub_id",businessDate:"business_date",sourceType:"source_type"}),Tt=Object.freeze({reportHubId:"report_hub_id",matchedSets:"matched_sets"}),Xt=Object.freeze({value:"value"}),we=Object.freeze({hubId:"hub_id",sourceDigest:"source_digest",normalizerVersion:"normalizer_version"}),Y=e=>B`${B.identifier(e.name)}`,Qt=e=>B.join(e.map(t=>B`${t}`),B`, `),Fi=(e,t)=>B`SELECT ${Y(e.id)} AS ${B.identifier(we.hubId)} FROM ${e} WITH (UPDLOCK, ROWLOCK) WHERE ${e.id} IN (${Qt(t)}) ORDER BY ${e.id}`,Yd=(e,t,r)=>{let{hub:n}=e,{document:o,comment:a}=e.search,i=t.alternatives.map(u=>Oi(u.text)),l=B.join(i.map(u=>B`${o.searchText} LIKE ${u}`),B` OR `),c=B.join(i.map(u=>B`${a.commentText} LIKE ${u}`),B` OR `),s=qt(n.sourceType,r.scope.commentable),m=s===void 0?B``:B` AND (${s} OR ${a.authorUserId} = ${r.userId})`;return B`((${l}) OR EXISTS (SELECT 1 FROM ${a} WHERE ${a.hubId} = ${n.id} AND (${c})${m}))`},Hi=(e,t,r)=>B`(${B.join(t.words.map(n=>Yd(e,n,r)),B` AND `)})`,qn=(e,t,r,n)=>{let{hub:o}=e,a=[B`${o.deletedAt} IS NULL`,Lr(e,t.userId,r,"author")],i=qt(o.sourceType,t.scope.visible);return i!==void 0&&a.push(i),n!==void 0&&a.push(B`${o.id} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${JSON.stringify(n)}))`),a},jd=(e,t)=>{let{hub:r}=e,{document:n}=e.search,o=[];if(t.sourceTypes!==null){if(t.sourceTypes.size===0)throw new Error("[daily-report] search: a source-type filter must hold at least one source type");o.push(B`LOWER(${r.sourceType}) IN (${Qt([...t.sourceTypes])})`)}return t.authors!==null&&o.push(B`${n.authorName} IN (${Qt(t.authors)})`),t.customers!==null&&o.push(B`${n.customerName} IN (${Qt(t.customers)})`),o},Ui=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,{plan:l}=t,c=[...qn(e,r,n,o),...jd(e,t.filters)];if(l!==null){let s=l.combine==="intersection"?B` AND `:B` OR `;c.push(B`(${B.join(l.sets.map(m=>Hi(e,m,r)),s)})`)}return B`SELECT ${Y(a.id)} AS ${B.identifier(qe.reportHubId)}, CONVERT(char(10), ${Y(a.businessDate)}, 23) AS ${B.identifier(qe.businessDate)}, ${Y(a.sourceType)} AS ${B.identifier(qe.sourceType)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${B.join(c,B` AND `)} ORDER BY ${a.businessDate} DESC, ${a.id} DESC`},$i=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,l=B.join(t.sets.map((c,s)=>B`(CASE WHEN ${Hi(e,c,r)} THEN ${2**s} ELSE 0 END)`),B` + `);return B`SELECT ${Y(a.id)} AS ${B.identifier(Tt.reportHubId)}, ${l} AS ${B.identifier(Tt.matchedSets)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${B.join(qn(e,r,n,o),B` AND `)}`},Bi=(e,t,r,n)=>{let{hub:o}=e,{document:a}=e.search,i=a[t],l=[...qn(e,r,n),B`${i} IS NOT NULL`];return B`SELECT ${i} AS ${B.identifier(Xt.value)} FROM ${o} INNER JOIN ${a} ON ${a.hubId} = ${o.id} WHERE ${B.join(l,B` AND `)} GROUP BY ${i} ORDER BY ${i}`},Vi=(e,t,r)=>{let{document:n,comment:o}=e,a=JSON.stringify(t.map(c=>({[n.hubId.name]:c.hubId,[n.searchText.name]:c.searchText,[n.sourceDigest.name]:c.sourceDigest,[n.normalizerVersion.name]:r,[n.authorName.name]:c.authorName,[n.customerName.name]:c.customerName}))),i=JSON.stringify(t.flatMap(c=>c.comments.map(s=>({[o.hubId.name]:c.hubId,[o.ordinal.name]:s.ordinal,[o.authorUserId.name]:s.authorUserId,[o.commentText.name]:s.commentText})))),l=JSON.stringify(t.map(c=>c.hubId));return B`MERGE ${n} WITH (HOLDLOCK) AS t USING (SELECT * FROM OPENJSON(${a}) WITH (${Y(n.hubId)} bigint, ${Y(n.searchText)} nvarchar(max), ${Y(n.sourceDigest)} char(64), ${Y(n.normalizerVersion)} varchar(64), ${Y(n.authorName)} nvarchar(max), ${Y(n.customerName)} nvarchar(max))) AS s ON t.${Y(n.hubId)} = s.${Y(n.hubId)}
8
- WHEN MATCHED THEN UPDATE SET t.${Y(n.searchText)} = s.${Y(n.searchText)}, t.${Y(n.sourceDigest)} = CONVERT(binary(32), s.${Y(n.sourceDigest)}, 2), t.${Y(n.normalizerVersion)} = s.${Y(n.normalizerVersion)}, t.${Y(n.authorName)} = s.${Y(n.authorName)}, t.${Y(n.customerName)} = s.${Y(n.customerName)}, t.${Y(n.indexedAt)} = SYSUTCDATETIME()
9
- WHEN NOT MATCHED THEN INSERT (${Y(n.hubId)}, ${Y(n.searchText)}, ${Y(n.sourceDigest)}, ${Y(n.normalizerVersion)}, ${Y(n.authorName)}, ${Y(n.customerName)}) VALUES (s.${Y(n.hubId)}, s.${Y(n.searchText)}, CONVERT(binary(32), s.${Y(n.sourceDigest)}, 2), s.${Y(n.normalizerVersion)}, s.${Y(n.authorName)}, s.${Y(n.customerName)});
1
+ var Eo=e=>{throw TypeError(e)};var wo=(e,t,r)=>t.has(e)||Eo("Cannot "+r);var Wt=(e,t,r)=>(wo(e,t,"read from private field"),r?r.call(e):t.get(e)),cn=(e,t,r)=>t.has(e)?Eo("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),un=(e,t,r,n)=>(wo(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var dn=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,J=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${dn(r)}`),rt=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),pn=(e,t,r)=>J(e,`one of ${r.map(n=>JSON.stringify(n)).join(", ")}`,t),ue=(e,t,r,n)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r&&(n===void 0||t<=n))return t;throw J(e,n===void 0?`an integer >= ${r}`:`an integer from ${r} to ${n}`,t)},xe=(e,t,r,n)=>t===void 0?n:ue(e,t,r);var ae=()=>Math.floor(performance.now());var mn=Object.freeze({defaultTtlMs:6e4,maxBuckets:4096,maxBytes:512*1024*1024}),$e=class extends Error{constructor(t){super(`cache miss refused (${t})`),this.name="SqlResultCacheMissRefusal",this.reason=t}},yn=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{}}}),zt=(e,t)=>t?e.map(r=>structuredClone(r)):e,Ul=8,$l=32,Vl=24,Yl=16,ql=-(2**30),jl=2**30-1,Wl=e=>Number.isInteger(e)&&e>=ql&&e<=jl&&!Object.is(e,-0),zl=(e,t)=>{let r=0,n=[e];for(;n.length>0&&r<=t;){let o=n.pop();if(r+=$l,ArrayBuffer.isView(o)){r+=o.byteLength;continue}let a=Array.isArray(o)?o:Object.keys(o).map(i=>o[i]);r+=Ul*a.length;for(let i of a)typeof i=="string"?r+=Vl+2*i.length:typeof i=="number"&&!Wl(i)?r+=Yl:typeof i=="object"&&i!==null&&n.push(i)}return r},Gt=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-ae())<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:ae()+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 $e(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:ae()+(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 $e("aborted");return this.dropBucket(r),zt(await this.readOwnOrRetry(this.forcedFetch(t),t),o)}let i=this.buckets.get(r);if(i&&i.expireAt>ae())if(t.epochKey){let s=await this.epochStore.getEpoch(t.epochKey);if(s===null||i.epoch===s)return this.maybeRefreshAhead(t),zt(i.records,o);this.dropBucket(r)}else return this.maybeRefreshAhead(t),zt(i.records,o);let l=this.inFlight.get(r);if(l!==void 0)return zt(await this.readOwnOrRetry(l,t),o);if(a?.signal.aborted)throw new $e("aborted");return zt(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 $e&&(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=xe("cacheDefaultTtlMs",t.defaultTtlMs,1,mn.defaultTtlMs),this.maxBuckets=xe("cacheMaxBuckets",t.maxBuckets,1,mn.maxBuckets),this.maxBytes=xe("cacheMaxBytes",t.maxBytes,1,mn.maxBytes),this.lastSweepAt=ae()}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=zl(r.records,this.maxBytes);if(n>this.maxBytes)return;this.buckets.set(t,{...r,bytes:n}),this.totalBytes+=n;let o=ae();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)}};var Gl=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var Io=e=>e<10?`0${e}`:`${e}`,Kl=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=Io(e.getMonth()+1),n=Io(e.getDate());return`${t}-${r}-${n}`},vt=e=>{let t=Gl.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}`},gr=e=>vt(e)===e;var Ce=e=>e==null?null:e instanceof Date?Kl(e):vt(e);import{z as Jl}from"zod/v3";var Je=e=>Number.isSafeInteger(e)&&e>0,be=Jl.number().int().positive().max(Number.MAX_SAFE_INTEGER);import{z as de}from"zod/v3";var br=/^(?:[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 At=Symbol("daily-report wire mismatch"),Qe=(e,t,r)=>(e.issues.push({...r,path:t===null?[...e.path]:[...e.path,t]}),At),Mo=e=>e===null?"null":Array.isArray(e)?"array":Number.isNaN(e)?"nan":typeof e,Et=(e,t)=>({code:"invalid_type",expected:e,received:Mo(t)}),Ql=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Xl=e=>{let t=0;for(let r in e)t+=1;return t},_o=(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},Ot=e=>{let t=Object.keys(e),r=Object.values(e);return(n,o)=>{if(!Ql(n))return Qe(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===At){i=!0;continue}a===null&&u!==d&&(a=_o(n,t,s)),a!==null&&(u!==void 0||c in n)&&(a[c]=u)}return i?At:a!==null?a:Xl(n)===l?n:_o(n,t,t.length)}},Kt=e=>(t,r,n)=>{r.path.push(n);let o=e(t,r);return r.path.pop(),o},Jt=e=>(t,r,n)=>{if(!Array.isArray(t))return Qe(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===At?a=!0:s!==l&&(o===t&&(o=t.slice()),o[i]=s)}return r.path.pop(),a?At:o},se=(e,t,r)=>e==null||typeof e=="string"?e:Qe(t,r,Et("string",e)),xo=(e,t,r)=>e===null||typeof e=="string"?e:Qe(t,r,Et("string",e)),Co=(e,t,r)=>typeof e=="string"?e:Qe(t,r,Et("string",e)),Zl=(e,t,r)=>e===null||typeof e=="number"&&!Number.isNaN(e)?e:Qe(t,r,Et("number",e)),Qt=(e,t,r)=>typeof e=="boolean"?e:Qe(t,r,Et("boolean",e)),hn=(e,t,r)=>{if(typeof e=="number"&&Je(e))return e;for(let{message:n,path:o,...a}of be.safeParse(e).error.issues)Qe(t,r,a);return At},Po={present:!0,absent:!0,unknown:!0},Lo=Object.keys(Po),ec=Lo.map(e=>`'${e}'`).join(" | "),tc=(e,t,r)=>typeof e!="string"?Qe(t,r,{code:"invalid_type",expected:ec,received:Mo(e)}):Object.hasOwn(Po,e)?e:Qe(t,r,{code:"invalid_enum_value",received:e,options:[...Lo]}),ko=Ot({name:se,affiliation:se}),No=Ot({name:se,text:se,color:se}),vo=Ot({id:hn,name:se,color:se}),Oo=Ot({id:hn,userId:se,userName:se,content:se,createdAt:se,isMine:Qt}),rc=Ot({id:Co,fileName:Co,fileType:xo,fileSize:Zl,createdAt:xo,state:tc,hasThumbnail:Qt}),nc=Ot({reportHubId:hn,date:se,createdAt:se,author:se,userId:se,sourceType:se,employeeName:se,updatedBy:se,updatedAt:se,category:se,creationCategory:se,visitTimeFrom:se,visitTimeTo:se,customerName:se,interviewers:Jt(Kt(ko)),subject:se,content:se,externalComments:Jt(Kt(No)),isRead:Qt,isStarred:Qt,isDraft:Qt,labels:Jt(Kt(vo)),postedComments:Jt(Kt(Oo)),attachments:Jt(Kt(rc))}),Xt=(e,t)=>{let r={path:[],issues:[]},n=e(t,r);return n===At?{ok:!1,issues:r.issues}:{ok:!0,value:n}},Fo=e=>Xt(nc,e),Ho=e=>Xt(ko,e),Bo=e=>Xt(No,e),Uo=e=>Xt(vo,e),$o=e=>Xt(Oo,e);var Vo=15e3,Yo="lastEventId",oc=/^\d{1,15}-\d{1,15}$/,qo=e=>oc.test(e),Zt=e=>de.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 de.NEVER}),sy=Zt(Ho),ly=Zt(Bo),cy=Zt(Uo),ac=Zt($o),fn=Zt(Fo),wt=de.string().regex(br),ic=de.object({type:de.literal("connected")}),Dr=de.object({type:de.literal("status-update"),reportHubId:be,statusType:de.enum(["star","read"]),value:de.boolean(),clientTempId:wt,recipientRawUserId:be.optional()}),Rn=de.string(),Sn=de.object({type:de.literal("comment-add"),reportHubId:be,comment:ac,clientTempId:wt,recipientRawUserId:be.optional(),sourceType:Rn}),gn=de.object({type:de.literal("comment-delete"),reportHubId:be,commentId:be,clientTempId:wt,recipientRawUserId:be.optional(),sourceType:Rn}),bn=de.object({type:de.literal("report-create"),reportHubId:be,report:fn,clientTempId:wt,recipientRawUserId:be.optional()}),Dn=de.object({type:de.literal("report-update"),reportHubId:be,report:fn,clientTempId:wt,recipientRawUserId:be.optional()}),Tn=de.object({type:de.literal("report-publish"),reportHubId:be,report:fn,clientTempId:wt,recipientRawUserId:be.optional()}),An=de.object({type:de.literal("report-delete"),reportHubId:be,clientTempId:wt,sourceType:Rn}),jo=de.discriminatedUnion("type",[ic,Dr,Sn,gn,bn,Dn,Tn,An]);var Wo="ids-columns";var sc=/^[0-9a-f]{1,16}$/,zo=e=>Je(e.reportHubId)&&(e.businessDate===null||gr(e.businessDate)),Go=e=>typeof e=="string"&&sc.test(e),my=Object.freeze({kind:"absent"}),yy=Object.freeze({kind:"value",value:null});var Ft=(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:R}=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=R===void 0?null:R,p=s.get(m);p===void 0&&(p=i.length,i.push(m),s.set(m,p)),l.push(p)}return{ids:n,dates:o,counts:a,sourceTypes:i,sources:l}},Tr=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+(?=.)/,"")},Ko=(e,t,r,n)=>e!==r?e===null?1:r===null||e>r?-1:1:n-t,lc=(e,t,r,n)=>Ko(e,t,r,n)<0,En=(e,t)=>Ko(e.businessDate,e.reportHubId,t.businessDate,t.reportHubId),Jo=e=>{for(let t=1;t<e.length;t++)if(!lc(e[t-1].businessDate,e[t-1].reportHubId,e[t].businessDate,e[t].reportHubId))return!1;return!0},Qo=(e,t)=>{let r=e.findIndex(n=>En({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var oe=Object.freeze({businessDate:"business-date",idsStream:Wo,report:"report",search:"search",reports:"reports",searchMarks:"search-marks",searchFacets:"search-facets",action:"action"}),ye=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 Xo=(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)}}},Sy=Object.freeze(["API","Action","Attachment","ExternalSource","Isolation","Reads","Refresh","Search","SSE","SseReader","Server","Service","Streams","Visibility","ActionProvider","DetailLoader","IdsStream","SseConnection"]),Zo=e=>`[DailyReport${e}]`,he=(e,t,r)=>e===void 0?Xo(t,Zo(r)):Xo(0,Zo(r),e);var cc="legacy-",wn=e=>`${cc}${e}`;var uc=/^[1-9][0-9]*$/,dc=/^(?:0|[1-9][0-9]*)$/,Ve=e=>{if(e===null||!uc.test(e))return null;let t=Number(e);return Je(t)?t:null},In=e=>{if(e===null||!dc.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},_n=e=>e==="true"?!0:e==="false"?!1:null,er=e=>e===null?!1:_n(e);var ea=Object.freeze(["subject","content","author","employeeName","updatedBy","category","creationCategory","customerName"]),nt=Object.freeze({field:e=>e,interviewer:(e,t)=>`interviewer:${e}:${t}`,attachment:e=>`attachment:${e}`,comment:(e,t)=>`comment:${e}:${t}`});var pc=16777619,xn=2166136261,Cn=(e,t,r,n)=>{let o=e;for(let a=r;a<n;a++)o^=t.charCodeAt(a),o=Math.imul(o,pc);return o>>>0},ta=e=>Cn(xn,e,0,e.length),mc=String.fromCodePoint(3),yc=String.fromCodePoint(2),hc=String.fromCodePoint(1),Ar=e=>ta(e.map(t=>t.map(r=>r.map(n=>`${n.tier}${n.text}`).join(mc)).join(yc)).join(hc));var ra=e=>e==="intersection"||e==="union",Ae=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),Mn=2,Er=2,It=Object.freeze({word:0,reading:1});var Pn=(e,t)=>({ids:e.map(r=>r.reportHubId),businessDates:e.map(r=>r.businessDate),sourceTypes:e.map(r=>r.sourceType),words:t});var Ey=2*(1+Mn);import{z as _y}from"zod/v3";var Oe=Object.freeze({intent:"intent",clientTempId:"clientTempId",businessDate:"businessDate",operationTimestamp:"operationTimestamp",reportHubId:"reportHubId",title:"title",content:"content",isStarred:"isStarred",isRead:"isRead",commentId:"commentId"});var wr=Math.max(1,Math.floor(10.556701030927835));var Ye=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var Fe=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),Ye(()=>{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 ot=Object.freeze({maxValuesPerFacet:16,maxValueLength:200,maxTotalValueLength:300});var ky=Object.freeze({authors:Object.freeze([]),sourceTypes:Object.freeze([]),customers:Object.freeze([])}),fc=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Ln=e=>{let t=e.trim();return t.length===0?null:t.replace(fc,"\uFFFD")},Rc=e=>{let t=Ln(e);return t===null?"filter-blank-value":t!==e?"filter-value-not-canonical":e.length>ot.maxValueLength?"filter-value-too-long":null},Sc=e=>{if(e.length>ot.maxValuesPerFacet)return"filter-too-many-values";let t=new Set;for(let r of e){let n=Rc(r);if(n!==null)return n;if(t.has(r))return"filter-duplicate-value";t.add(r)}return null},gc=e=>{let t=0;for(let r of e.authors)t+=r.length;for(let r of e.customers)t+=r.length;return t},na=e=>{for(let t of[e.authors,e.sourceTypes,e.customers]){let r=Sc(t);if(r!==null)return r}return gc(e)>ot.maxTotalValueLength?"filters-too-long":null};var oa=e=>e.trim().length===0;var kn=e=>e!==null&&br.test(e)?e:null,Nn=e=>ra(e)?e:null,vn=e=>{if(e===null)return null;let t=e.split(",");if(t.length>Ae.maxDetailIds)return null;let r=[];for(let n of t){let o=Ve(n);if(o===null||r.includes(o))return null;r.push(o)}return r},aa=e=>{let[t,...r]=e;return t===void 0?null:[t,...r]},ia=(e,t)=>{let r={authors:e.getAll(ye.searchAuthor),sourceTypes:e.getAll(ye.searchSourceType),customers:e.getAll(ye.searchCustomer)},n=na(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:aa(r.authors),customers:aa(r.customers)}}},sa=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var ca=Object.freeze({status:400,error:"Invalid form"}),ua=e=>({status:413,error:"Form too large",measuredBy:e}),bc=(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)}}))},Dc=async e=>{let t=In(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:ua("declared")};let r=!1,n=e.body===null?null:bc(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?ua("counted"):ca}}let l=sa(i);return l===null?{refusal:ca}:{fields:l}},da=(e,t)=>(r,n)=>{let o=r.get(t);if(o===null)return{error:`${t} required`};let a=_n(o);return a===null?{error:`Invalid ${t}`}:{command:{...n,intent:e,value:a}}},ma=Object.freeze({update:(e,t,r)=>{let n=e.get(Oe.title),o=e.get(Oe.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:da("toggleStar",Oe.isStarred),toggleRead:da("toggleRead",Oe.isRead),addComment:(e,t)=>{let r=e.get(Oe.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=Ve(e.get(Oe.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),Tc=e=>Object.hasOwn(ma,e),Ac=(e,t)=>{let r=e.get(Oe.intent),n=e.get(Oe.businessDate),o=n===null?null:vt(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get(Oe.operationTimestamp),i=In(a);if(a!==null&&i===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get(Oe.clientTempId);if(!l)return{error:"clientTempId required"};let s=kn(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=Ve(e.get(Oe.reportHubId));return c===null?{error:"Invalid reportHubId"}:r===null||!Tc(r)?{error:"Invalid intent"}:ma[r](e,{clientTempId:s,businessDate:o,operationTimestamp:i,reportHubId:c},t)},ya=async(e,t)=>{let r=await Dc(e);if("refusal"in r)return r;let n=Ac(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},Ec=6e4,wc="form_too_large",pa=["declared","counted"],ha=e=>{let t=Fe({windowMs:Ec,tallies:pa,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${pa.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(wc,r,n)}};var _t=Object.freeze({[oe.businessDate]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[oe.idsStream]:{body:"stream",admission:["refresh-bucket","stream-slots","cache","miss-gate"]},[oe.report]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[oe.search]:{body:"json",cache:"etag",admission:["search-limiter"]},[oe.reports]:{body:"json",cache:"etag",admission:["search-limiter"]},[oe.searchMarks]:{body:"json",cache:"no-store",admission:["search-limiter"]},[oe.searchFacets]:{body:"json",cache:"etag",admission:["search-limiter"]}}),fa=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),On=e=>e!==void 0&&Object.hasOwn(_t,e);var Fn=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),Ra=e=>Object.hasOwn(Fn,e);var Ic="download",_c="thumbnail",xc="1";var Hn=e=>{let t=e.getAll(_c),r=e.getAll(Ic);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&Ra(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===xc?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};import{createHash as Cc}from"crypto";var Bn=e=>`"${Cc("sha256").update(e).digest("hex")}"`,Sa=e=>Bn(JSON.stringify(e));var Xe=Object.freeze({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'"}),Un=(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},ga=(e,t,r,n=200)=>{let o=JSON.stringify(r),a=Bn(o),i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate",ETag:a,...Xe});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&Un(e.headers.get("If-None-Match"),a)?new Response(null,{status:304,headers:i}):new Response(o,{status:n,headers:i})},$n=(e,t,r)=>{let n=new Headers({...t===null?{}:{"Content-Type":"application/json"},"Cache-Control":"no-store",...Xe});return e&&n.append("Set-Cookie",e),new Response(t===null?null:JSON.stringify(t),{status:r,headers:n})},Vn=e=>(t,r,n,o)=>{if(o!==200)return $n(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)},Mc=5e3/1e3,Pc=new Map([[503,Mc]]),Ne=e=>{let t=Pc.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var qn="Cross-site request rejected",Lc="Not Found",kc=new Set(["same-origin","none"]),Nc=new Set(["GET","HEAD","OPTIONS"]),ba=["api","action","sse","attachment"],Da=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...Xe}}),vc=()=>Da(403,qn),Ir=()=>Da(404,Lc),tr=Object.freeze({navigable:()=>!1,frameworkDataRefusal:()=>null,crossSiteRejection:vc}),Ta=e=>new URL(e.url).pathname.endsWith(".data"),Oc=e=>{let t=e.headers.get("Origin");return t===null?!0:URL.canParse(t)&&new URL(t).host===new URL(e.url).host},Aa=(e,t)=>{let r=e.headers.get("Sec-Fetch-Site");return r===null?!(Nc.has(e.method)||Oc(e)):kc.has(r)?!1:!(e.method==="GET"&&e.headers.get("Sec-Fetch-Mode")==="navigate"&&e.headers.get("Sec-Fetch-Dest")==="document"&&t.navigable(e))},Fc=6e4,Hc="refusals",Bc=32,Uc=/^[a-z-]+$/,Yn=e=>{if(e===null)return"-";let t=e.slice(0,Bc);return Uc.test(t)&&t===e?e:JSON.stringify(t)},Ea=e=>{let t=Fe({windowMs:Fc,tallies:ba,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${ba.map(i=>`${i}:${a[i]}`).join(",")}`)}});return(r,n)=>{let o=()=>{let{headers:a}=n;e.warn(`cross_site_rejected route=${r} site=${Yn(a.get("Sec-Fetch-Site"))} mode=${Yn(a.get("Sec-Fetch-Mode"))} dest=${Yn(a.get("Sec-Fetch-Dest"))} method=${n.method}`)};t.record(Hc,r,o)}};var wa=(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 $c="same-origin",Vc="SAMEORIGIN",Ht=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":$c,"X-Frame-Options":Vc}),_r=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...Ht});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},Ia=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),Yc=/^[\x20-\x7E]+$/,qc=/^[\w.+-]+\/[\w.+-]+/,jn=e=>e&&Yc.test(e)&&qc.test(e)?e:null,jc=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,_a=e=>encodeURIComponent(e.replace(jc,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),xa=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),xr={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},Ca={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},Cr=e=>typeof e=="string"&&Object.hasOwn(Ca,e),Mr=e=>Ca[e],at="Attachment request failed";var Ze=e=>{let t=ue("limit",e.limit,1),r=ue("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:ue("queue.max",e.queue.max,0),maxPerOwner:ue("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:ue("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],i=new Map,l=new Map,s=(y,S)=>y.get(S)??0,c=(y,S,I)=>{let D=s(y,S)+I;D<=0?y.delete(S):y.set(S,D)},d=y=>s(l,y)<r,u=y=>o<t&&d(y),R=y=>(o+=1,c(l,y,1),f(y)),m=()=>{let y=-1,S=r;for(let[I,D]of a.entries()){let h=s(l,D.owner);if(h<S&&(y=I,S=h,h===0))break}return y},p=()=>{for(;o<t;){let y=m();if(y<0)return;let[S]=a.splice(y,1);c(i,S.owner,-1),S.grant(R(S.owner))}},f=y=>{let S=!1;return()=>{S||(S=!0,o-=1,c(l,y,-1),p())}};return{canAcquire:u,acquire:(y,S)=>{if(S.aborted)return Promise.resolve(null);if(u(y))return Promise.resolve(R(y));if(n===null||a.length>=n.max||s(i,y)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:I}=n,D=h=>{let g=()=>{let Y=a.indexOf(C);Y<0||(a.splice(Y,1),c(i,y,-1),_(),h(null))},M=Ye(g,I),_=()=>{clearTimeout(M),S.removeEventListener("abort",g)},C={owner:y,grant:Y=>{_(),h(Y)}};a.push(C),c(i,y,1),S.addEventListener("abort",g,{once:!0})};return new Promise(D)}}};var Wc=1024,Wn="Too many requests",zc=(e,t)=>{ue("limitPerWindow",e,1),ue("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<=Wc)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))}}},it=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(ue("windowMs",r,1e3)%1e3!==0)throw J("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=zc(e.limitPerWindow,r),i=Object.freeze({status:429,message:Wn,headers:Object.freeze({"Retry-After":String(r/1e3)})}),l=Fe({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,ae())?null:(l.record(s,t,()=>n.warn(`429 ${c} reason=${t}`)),i),refund:(s,c)=>{a.refund(s,ae(),c)}}};var Kc=256*1024,Ma=6e4,Jc=e=>Math.ceil(e/2),Qc=new Uint8Array(new ArrayBuffer(0)),Xc=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=Qc,t()},i=l=>{clearTimeout(o),o=Ye(()=>{l.error(new Error(`attachment body idle for ${Ma} ms`)),a()},Ma)};return new ReadableStream({start(l){i(l)},pull(l){let s=Math.min(n+Kc,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})},Pa=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=it({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:s=>`viewer=${s}`}),l=Ze({limit:e.concurrency,maxHeldPerOwner:Jc(e.concurrency),queue:null});return async s=>{let{request:c,delivery:d,attachmentId:u,internalUserId:R,readAttachment:m,cookie:p,fail:f}=s,y=e.maxBytes,S=i.spend(R,`attachment=${u} viewer=${R}`);if(S)return f(S.status,S.message,S.headers);let I=await n(c),D=await t.getAttachmentForUser(I,u,R);if(!D)return o.warn(`404 attachment=${u} viewer=${R} reason=not_visible`),f(404,"Attachment not found");if(D.fileSize!=null&&D.fileSize>y)return o.warn(`413 attachment=${u} viewer=${R} reason=db_size`),f(413,"Attachment too large");let h=jn(D.fileType),g=`filename="${xa(D.fileName)}"; filename*=UTF-8''${_a(D.fileName)}`,M=await l.acquire(R,c.signal);if(!M)return c.signal.aborted?(o.info(`503 attachment=${u} viewer=${R} reason=aborted`),f(503,"Attachment request aborted")):(o.warn(`503 attachment=${u} viewer=${R} reason=concurrency`),f(503,"Too many concurrent downloads",Ne(503)));let _=!1;try{let C=await m(D.filePath,{maxBytes:y,head:c.method==="HEAD",principal:r(R),signal:c.signal});if(c.signal.aborted)return o.info(`503 attachment=${u} viewer=${R} reason=aborted`),f(503,"Attachment request aborted");if(!C.ok){if(!Cr(C.reason))return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=failure_reason`),f(500,at);let F=Mr(C.reason);return C.reason==="not_found"&&a(u,!1),o.warn(`${F} attachment=${u} viewer=${R} reason=${C.reason} code=${C.code??"-"}`),f(F,xr[F],Ne(F))}if(C.bytes.byteLength>y)return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=over_max_bytes`),f(500,at);let Y=c.method==="HEAD";if(Y&&C.size!==void 0&&C.size>y)return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=over_max_bytes`),f(500,at);if(!Y&&C.size!==void 0&&C.size!==C.bytes.byteLength)return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=size_mismatch`),f(500,at);let L=h??jn(C.contentType),N=L!==null&&Ia.has(L),b=N?L:"application/octet-stream",k=N&&d.kind!=="download"?"inline":"attachment",U=Y?C.size:C.bytes.byteLength,O=new Headers({"Content-Type":b,"Content-Disposition":`${k}; ${g}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...Ht});return U!==void 0&&O.set("Content-Length",String(U)),p&&O.append("Set-Cookie",p),a(u,!0),o.info(`200 attachment=${u} viewer=${R} type=${b} disposition=${k} bytes=${U??"-"}`),Y?new Response(null,{status:200,headers:O}):(_=!0,new Response(Xc(C.bytes,M),{status:200,headers:O}))}finally{_||M()}}};var ve=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),Dh=ve.queueWaitMs+ve.readMs+ve.renderMs+ve.transferMarginMs;import{Buffer as Zc}from"buffer";var Na=new Set([194,198,202,206]),eu=new Set([192,193,194,195]),va=216,tu=217,Oa=218,ru=4,nu=64,ou=2,La=8,ka=28,dt=12,zn=8,au=20,Fa=dt+zn+10,iu=2,st=(e,t)=>e[t]<<8|e[t+1],Bt=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];return n},et=(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},Ha=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,Ba=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),Ua=e=>(e.stepsLeft-=1,e.stepsLeft>=0),$a=e=>e[0]===255&&e[1]===va,Va=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!Ua(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===tu)return"eoi";if(o===0||o===va)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=st(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")}},su=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!Ua(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}},Ya=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=st(e,r+1),a=st(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}},qa=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>ru||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},ja=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:Na.has(e.marker)||t<e.components.length}),Gn=e=>{if(!$a(e))return null;let t=Ba(e.byteLength),r=null;for(let n=2;;){if(Va(e,n,t)!=="segment")return null;if(Ha(t.marker)){if(r!==null||(r=Ya(e,t),r===null))return null}else if(t.marker===Oa){if(r===null)return null;let o=qa(e,t);return o===null?null:ja(r,o.length)}n=t.end}},Wa=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*La)),i=Math.ceil(e.height*o/(r*La));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},za=e=>e.multiScan?Wa(e).reduce((r,n)=>r+n,0)*nu*ou:0,lu=896,Ga=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!$a(e))return null;let n=Zc.from(e.buffer,e.byteOffset,e.byteLength),o=Ba(r),a=null,i=null,l=new Map,s=0,c=0,d=0;for(let u=2;;){let R=Va(e,u,o);if(R===null)return null;if(R==="eoi")return i===null?null:{header:i,blockVisits:c};if(u=o.end,Ha(o.marker)){if(a!==null||!eu.has(o.marker)||(a=Ya(e,o),a===null))return null;let m=Wa(a);l=new Map;for(let[p,f]of a.components.entries()){let y=l.get(f.id);l.set(f.id,y===void 0?m[p]:Math.max(y,m[p]))}s=a.components.length*(Na.has(a.marker)?lu:1)}else if(o.marker===Oa){if(a===null||d===s)return null;let m=qa(e,o);if(m===null)return null;for(let f of m){let y=l.get(f);if(y===void 0)return null;c+=y}if(d+=1,i===null&&(i=ja(a,m.length)),c>t||!i.multiScan)return{header:i,blockVisits:c};let p=su(n,o.end,o);if(p===null)return null;u=p}}},Ka=e=>{if(e.byteLength<24||st(e,8)!==0||st(e,10)!==13||!et(e,12,"IHDR"))return null;let t=st(e,16)*65536+st(e,18),r=st(e,20)*65536+st(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},cu=e=>{if(et(e,dt,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=Bt(e,26,2)&16383,r=Bt(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(et(e,dt,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=Bt(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return et(e,dt,"VP8X")?e.byteLength<Fa?null:{width:Bt(e,24,3)+1,height:Bt(e,27,3)+1}:null},Ja=e=>{if(Ka(e)===null||e.byteLength<=ka)return null;switch(e[ka]){case 0:return!1;case 1:return!0;default:return null}},Qa=(e,t)=>{if(et(e,dt,"VP8 "))return"lossy";if(et(e,dt,"VP8L"))return"lossless";if(!et(e,dt,"VP8X")||e.byteLength<Fa)return null;if((e[au]&iu)!==0)return"animated";let r=!1,n=t;for(let o=dt;o+zn<=e.byteLength;){if(n-=1,n<0)return null;if(et(e,o,"VP8L"))return"lossless";if(et(e,o,"VP8 "))return r?"lossy-alpha":"lossy";et(e,o,"ALPH")&&(r=!0);let a=Bt(e,o+4,4);o+=zn+a+a%2}return null},Xa={png:Ka,jpeg:Gn,webp:cu};var Kn=Object.freeze(["image/webp","image/jpeg","image/png"]),Jn=1024*1024;var uu=new Set(["image/png","image/jpeg","image/gif","image/webp"]),du={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},pu=new Set(Kn),mu=e=>typeof e=="string"&&pu.has(e),yu=256,Pr=(e,t)=>e.fileType===null||!uu.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,hu=[137,80,78,71,13,10,26,10],fu=[255,216,255],Ru=[[71,73,70,56,55,97],[71,73,70,56,57,97]],Su=[82,73,70,70],gu=[87,69,66,80],rr=(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},Qn=e=>{if(rr(e,hu,0))return"png";if(rr(e,fu,0))return"jpeg";for(let t of Ru)if(rr(e,t,0))return"gif";return rr(e,Su,0)&&rr(e,gu,8)?"webp":null},Za=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:Sa([t])}},ei=(e,t)=>{if(!mu(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>Jn)return"too_large";let r=du[e.contentType];if(Qn(e.bytes)!==r)return"signature";let n=Xa[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},ti=e=>{ue("maxBytes",e.maxBytes,0),ue("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)+yu;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 Xn=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,i=ae(),l=new AbortController,s=!1,c,d,u=()=>{a(ae()-i)},R=h=>{c=Ye(()=>{s=!0,h({timedOut:!0}),d=Ye(u,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},m=new Promise(R),p=AbortSignal.any([r,l.signal]),f=h=>{h(n(p))},y=new Promise(f),S=h=>(clearTimeout(c),clearTimeout(d),s&&o(ae()-i,h.kind==="error"?{error:h.error}:null),h),I=y.then(h=>S({kind:"value",value:h}),h=>S({kind:"error",error:h}));return{outcome:Promise.race([y.then(h=>({timedOut:!1,value:h})),m]),settled:I}};var pt={404:"Attachment not found",500:at,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},ri=(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=ei(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},bu=e=>{let t=new AbortController,r=()=>{t.abort()},n=Ye(r,ve.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},ni=()=>{},Du=(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)}),oi=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:i}=e,l=new Map,s=(m,p)=>{let f=p.then(ni,ni);l.set(m,f);let y=()=>{l.get(m)===f&&l.delete(m)};f.then(y)},c=async(m,p)=>{let f=l.get(m.key);if(f===void 0)return t.acquire(m.owner,p);let y=bu(p);try{if(await Du(f,y.signal),y.signal.aborted)return null;let S=r.get(m.key);return S!==void 0?{...S,identity:"verified"}:await t.acquire(m.owner,y.signal)}finally{y.end()}},d=(m,p)=>{if(m.fileSize===null)return p.kind==="exact"?"verified":"unrecorded";if(p.kind==="exact"?p.bytes===m.fileSize:m.fileSize>p.maxBytes)return"verified";let y=p.kind==="exact"?String(p.bytes):`>${p.maxBytes}`;return i.warn(`size_mismatch expected=${m.fileSize} got=${y} attachment=${m.attachmentId} viewer=${m.owner} variant=thumbnail`),"unverified"},u=(m,p)=>(f,y)=>{let S=y===null?"":` message=${y.error instanceof Error?y.error.message:"unknown"}`;i.warn(`${m}_overrun ms=${f} attachment=${p.attachmentId} viewer=${p.owner} variant=thumbnail${S}`)},R=(m,p)=>f=>{i.warn(`${m}_stuck ms=${f} attachment=${p.attachmentId} viewer=${p.owner} variant=thumbnail`)};return async(m,p)=>{let f=await c(m,p);if(f===null)return{kind:"failure",status:503,reason:p.aborted?"aborted":"queue"};if(typeof f!="function")return f;let y=f,S=null;try{if(p.aborted)return{kind:"failure",status:503,reason:"aborted"};let I=r.get(m.key);if(I!==void 0)return{...I,identity:"verified"};let D=Xn({budgetMs:ve.readMs,flightSignal:p,call:F=>m.readAttachment(m.filePath,{maxBytes:n,head:!1,principal:o(m.owner),signal:F}),onOverrun:u("read",m),onStuck:R("read",m)}),h=await D.outcome;if(h.timedOut)return S=D.settled,p.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(p.aborted)return{kind:"failure",status:503,reason:"aborted"};let g=h.value;if(!g.ok&&g.reason!=="too_large")return Cr(g.reason)?(g.reason==="not_found"&&a(m.attachmentId,!1),{kind:"failure",status:Mr(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 M=d(m,g.ok?{kind:"exact",bytes:g.bytes.byteLength}:{kind:"over",maxBytes:n}),_=F=>{M==="verified"&&r.set(m.key,F)},C=F=>(_(F),{...F,identity:M});if(!g.ok)return C({kind:"unrenderable",reason:"too_large"});let Y=Qn(g.bytes);if(Y===null)return C({kind:"unrenderable",reason:"signature"});let L=Xn({budgetMs:ve.renderMs,flightSignal:p,call:F=>m.renderer.render(g.bytes,{format:Y,maxWidth:m.box.maxWidth,maxHeight:m.box.maxHeight,signal:F}),onOverrun:u("render",m),onStuck:R("render",m)}),N=F=>{if(F.kind==="error")return;let z=ri(F.value,m.box);"entry"in z&&_(z.entry)},b=null,k=()=>(b===null&&(b=L.settled.then(N),s(m.key,b)),b);p.addEventListener("abort",k,{once:!0});let U=await L.outcome.finally(()=>p.removeEventListener("abort",k));if(U.timedOut||p.aborted)return S=k(),p.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let O=ri(U.value,m.box);return"entry"in O?C(O.entry):O.failure}finally{S===null?y():S.then(y,y)}}};var ai=()=>{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 li=10,Tu=1/li,ii=1-Tu,Au=1024,Eu=64,wu=8,si="private, no-cache",Iu="no-store",_u=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),xu=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},ci=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:s}=l,c=(h,g)=>it({reason:h,limitPerWindow:g,windowMs:6e4,logger:o,windowFields:M=>`viewer=${M} variant=thumbnail`}),d=c("rate_limit",l.rateLimitPerMinute),u=c("revalidation_rate_limit",l.rateLimitPerMinute*li),R=Ze({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:Eu,maxPerOwner:wu,maxWaitMs:ve.queueWaitMs}}),m=ti({maxBytes:l.cacheBytes,maxEntries:Au}),p=ai(),f=oi({gate:R,cache:m,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),y=(h,g,M,_)=>{let C=`attachment=${h.attachmentId} viewer=${h.internalUserId} variant=thumbnail cache=${_}`;if(g.kind==="failure")return o[xu(g)](`${g.status} ${C} reason=${g.reason} code=${g.code??"-"}`),h.fail(g.status,pt[g.status],Ne(g.status));let Y=_u[g.identity];if(g.kind==="unrenderable")return o.info(`404 ${C} reason=${g.reason}${Y}`),h.fail(404,pt[404]);let L=g.identity==="verified"?{"Cache-Control":si,ETag:M}:{"Cache-Control":Iu},N=new Headers({"Content-Type":g.contentType,"Content-Length":String(g.bytes.byteLength),...L,"Content-Security-Policy":"default-src 'none'; sandbox",...Ht});return h.cookie&&N.append("Set-Cookie",h.cookie),o.info(`200 ${C} type=${g.contentType} bytes=${g.bytes.byteLength}${Y}`),new Response(g.bytes,{status:200,headers:N})},S=(h,g)=>{let M=h.spend(g.internalUserId,`attachment=${g.attachmentId} viewer=${g.internalUserId} variant=thumbnail`);return M===null?null:g.fail(M.status,M.message,M.headers)},I=h=>S(d,h),D=(h,g)=>g?S(u,h):I(h);return async(h,g)=>{let{request:M,attachmentId:_,internalUserId:C,readAttachment:Y,cookie:L,fail:N}=h,b=Fn[g],k=M.headers.get("If-None-Match"),U=k!==null,O=D(h,U);if(O)return O;let F=await n(M),z=await t.getAttachmentForUser(F,_,C),q=z!==null&&Pr(z,i)?Za({rendererId:s.id,box:b,attachmentId:_,filePath:z.filePath,fileType:z.fileType,fileSize:z.fileSize}):null;if(q&&Un(k,q.etag)){let E=new Headers({"Cache-Control":si,ETag:q.etag,...Ht});return L&&E.append("Set-Cookie",L),o.info(`304 attachment=${_} viewer=${C} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:E})}if(U){let E=I(h);if(E)return E}if(!z)return o.warn(`404 attachment=${_} viewer=${C} variant=thumbnail reason=not_visible`),N(404,pt[404]);if(!q)return d.refund(C,ii),o.info(`404 attachment=${_} viewer=${C} variant=thumbnail reason=not_eligible`),N(404,pt[404]);let{key:ne,etag:ge}=q,Pe=m.get(ne);if(Pe)return d.refund(C,ii),y(h,{...Pe,identity:"verified"},ge,"hit");let me=E=>f({key:ne,attachmentId:_,filePath:z.filePath,fileSize:z.fileSize,box:b,owner:C,readAttachment:Y,renderer:s},E),G;try{G=await p.join(ne,M.signal,me)}catch(E){return o.error(`500 attachment=${_} viewer=${C} variant=thumbnail cache=miss reason=port_exception message=${E instanceof Error?E.message:"unknown"}`),N(500,pt[500])}return y(h,G,ge,"miss")}};var Cu='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',Mu=()=>_r(403,qn,{cookie:null}),ui=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=Hn(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>_r(404,xr[404],{cookie:null}),crossSiteRejection:Mu}),di=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:wa(r,a)},s=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:Pa({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:ci({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:c,params:d})=>{let u=null,R=(m,p,f={})=>_r(m,p,{cookie:u,extraHeaders:f});try{let{user:m,cookie:p}=await t(c,{failureRedirect:null});if(u=p??null,!m)return R(401,"Unauthorized");let f=Hn(new URL(c.url).searchParams);if(f.kind==="invalid")return R(400,"Invalid attachment request");if(f.kind==="thumbnail"&&c.method!=="GET")return R(405,"Method not allowed",{Allow:"GET"});if(c.method!=="GET"&&c.method!=="HEAD")return R(405,"Method not allowed",{Allow:"GET, HEAD"});if(s===null)return R(404,"Attachment not found");if(d.token===void 0)throw new Error(Cu);let y=s.idCodec.decode(d.token);if(y===null||!Je(y))return R(400,"Invalid attachment token");let S=await r.getUserIdByExternalId(m.id);if(!S)return R(403,"Forbidden");let I={request:c,delivery:f,attachmentId:y,internalUserId:S,readAttachment:s.read,cookie:u,fail:R};return f.kind!=="thumbnail"?await s.serveOriginal(I):s.serveThumbnail===null?R(404,pt[404]):await s.serveThumbnail(I,f.variant)}catch(m){if(m instanceof Response)throw m;return a.error(`500 attachment=? viewer=? reason=unexpected message=${m instanceof Error?m.message:"unknown"}`),R(500,at)}}};var Pu=32*1024*1024,Lu=60,ku=4,Nu=120,vu=2,Ou=8*1024*1024,Lr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Fu=e=>{if(e===void 0)throw rt("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!Lr(e))throw J("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw rt("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw J("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw J("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},Hu=e=>{if(e===void 0)return null;if(!Lr(e))throw J("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:Fu(e.renderer),rateLimitPerMinute:xe("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,Nu),concurrency:xe("attachments.thumbnails.concurrency",e.concurrency,1,vu),cacheBytes:xe("attachments.thumbnails.cacheBytes",e.cacheBytes,0,Ou)})},pi=e=>{let t=e;if(t===void 0)return null;if(!Lr(t))throw J("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw rt("attachments.idCodec","injected when attachments is given");if(!Lr(r)||typeof r.encode!="function"||typeof r.decode!="function")throw J("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw rt("attachments.read","injected when attachments is given");if(typeof n!="function")throw J("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:xe("attachments.maxBytes",t.maxBytes,1,Pu),rateLimitPerMinute:xe("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,Lu),concurrency:xe("attachments.concurrency",t.concurrency,1,ku),thumbnails:Hu(t.thumbnails)})},Bu=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"]]),kr=e=>{for(let[t,r]of Bu)if(Object.hasOwn(e,t))throw rt(r,`given in place of the flat key ${t}`)};var yi=8,Uu=8*yi,$u=128,Vu=2,hi=Vu*$u,Yu=4*hi,qu=6e4,ju=6e4,Wu="Too many reads",mi=Object.freeze(Object.keys(_t).filter(e=>_t[e].admission.includes("miss-gate"))),fi=e=>{let t=Ze({limit:Uu,maxHeldPerOwner:yi,queue:{max:Yu,maxPerOwner:hi,maxWaitMs:qu}}),r=Fe({windowMs:ju,tallies:mi,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`cache_miss_admission_suppressed count=${o} since=${a} viewer=${n} endpoints=${mi.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}})}},Nr=(e,t,r)=>{let n=e(t,r,{error:{message:Wu}},503);for(let[o,a]of Object.entries(Ne(503)))n.headers.set(o,a);return n};var Ri=e=>{let t=e.get(ye.cursorReportHubId),r=e.get(ye.cursorBusinessDate),n=e.get(ye.cursorSnapshot),o=Go(n)?n:null,a=null;if(t!==null){let l=Ve(t);if(l===null)return{refused:"cursor"};let s={businessDate:r,reportHubId:l};if(!zo(s))return{refused:"cursor"};a=s}else if(r!==null)return{refused:"cursor"};let i=er(e.get(ye.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var vr=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,zu=2,Gu=16,Ku=zu*Gu,Ju=6e4,Si=()=>{},Qu=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},gi=e=>{let t=Ze({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:Ku,queue:null}),r=Fe({windowMs:Ju,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 Si;if(a.aborted){if(t.canAcquire(n))return Si}else{let i=await t.acquire(n,a);if(i!==null)return Qu(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var Or=30,Ei=4e3,Xu="stream interrupted by server error",Zu="Too many streams",ed=15e3,wi=Symbol("ids-stream-heartbeat"),bi=()=>{},Di=e=>e.return(void 0).then(bi,bi),td=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(wi),ed)}),stop:()=>clearTimeout(e)}};async function*Ti(e,t,r,n){let o=t?Qo(e,t):0,a=!0;for(;;){let i=Math.min(o+(a?r:Ei),e.length),l=Ft(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 Ii=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform",...Xe});return e&&t.append("Set-Cookie",e),t},Ai=(e,t,r,n,o)=>{let a=async(d,u)=>{o(),u&&await Di(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=td();try{s===null&&(s=t.next());let R=await Promise.race([s,u.fired]);if(u.stop(),R===wi){if(l||r.aborted){await a(d,!0);return}d.enqueue(i.encode(`
2
+ `));return}s=null;let{value:m,done:p}=R;if(p){await a(d,!1);return}if(l||r.aborted){await a(d,!0);return}d.enqueue(i.encode(`${JSON.stringify(m)}
3
+ `))}catch(R){if(u.stop(),s=null,o(),l||r.aborted)return;R instanceof $e||n.error(`ids-stream emission failed: ${R instanceof Error?R.message:String(R)}`);try{let m={kind:"error",error:Xu};d.enqueue(i.encode(`${JSON.stringify(m)}
4
+ `)),d.close()}catch{}}},cancel(){l=!0,o(),Di(t)}});return new Response(c,{status:200,headers:Ii(e)})},_i=e=>{let{service:t,logger:r,streamSlots:n,missGate:o,refuseForcedRead:a}=e,i=async(l,s,c,d,u,R,m)=>{let p=!1,f=null,y=null,S=new Promise((h,g)=>{f=h,y=g});S.catch(()=>{});let I=t.getDailyReportIdsByExternalId(c,s.id,{forceRefresh:l.forceRefresh,admission:m,onFetchStart:l.cursor?void 0:()=>{p=!0,t.readSseStreamAnchor().then(h=>t.getDailyReportIdsFirstPageByExternalId(c,s.id,Or).then(g=>({items:g,streamAnchor:h}))).then(h=>f?.(h),h=>y?.(h))}});if(I.catch(()=>{}),l.cursor){let{items:h,streamAnchor:g,snapshot:M}=await I,_=l.snapshot!==null&&l.snapshot===M;return Ai(d,Ti(h,_?l.cursor:null,Or,{snapshot:M,restarted:!_,streamAnchor:g}),u,r,R)}let D=(async function*(){let h=await Promise.race([I.then(_=>({kind:"full",source:_}),_=>({kind:"full-error",error:_})),S.then(_=>({kind:"page",page:_}),()=>({kind:"page-error"}))]),g=null,M=!1;if(h.kind==="full")g=h.source;else if(h.kind==="page"){let{items:_,streamAnchor:C}=h.page;if(_.length<Or){yield{kind:"chunk",...Ft(_,0,_.length),nextCursor:null,isLast:!0,total:_.length,streamAnchor:C};return}yield{kind:"chunk",...Ft(_,0,_.length),nextCursor:null,isLast:!1,provisional:!0},M=!0}else if(h.kind==="full-error"&&p){let _=await S.catch(()=>null);_&&_.items.length>0&&(yield{kind:"chunk",...Ft(_.items,0,_.items.length),nextCursor:null,isLast:!1,provisional:!0})}g===null&&(g=await I),yield*Ti(g.items,null,M?Ei:Or,{snapshot:g.snapshot,streamAnchor:g.streamAnchor})})();return Ai(d,D,u,r,R)};return async(l,s,c,d,u,R)=>{let m=Ri(l.searchParams);if("refused"in m)return R(c,s,{error:{message:m.refused==="cursor"?"Invalid cursor":"Invalid forceRefresh"}},400);let{query:p}=m;if(p.forceRefresh){let I=a(d,c,s,R);if(I!==null)return I}let f=vr(c),y=await t.getUserIdByExternalId(d.id),S=await n.admit(y,"ids-stream",f);if(S===null){let I=R(c,s,{error:{message:Zu}},503);for(let[D,h]of Object.entries(Ne(503)))I.headers.set(D,h);return I}if(f.aborted)return new Response(null,{status:200,headers:Ii(s)});try{return await i(p,d,u,s,f,S,y===null?void 0:o.admissionFor(y,oe.idsStream,f))}catch(I){if(S(),I instanceof $e)return Nr(R,c,s);throw I}}};import{inArray as rd,sql as xi}from"drizzle-orm";var nd="",od=64,ad=e=>e.toLowerCase(),id=e=>e.trim().toLowerCase();function Ci(e){if(e==null)return null;if(!Array.isArray(e))return new Set;let t=new Set;for(let r of e){if(typeof r!="string")continue;let n=id(r);n.length>0&&t.add(n)}return t}function Ee(e,t){return e===null?!0:t==null?!1:e.has(ad(t))}function Me(e){return e!==null&&e.size===0}function or(e,t){if(t!==null)return t.size===0?xi`1 = 0`:rd(xi`LOWER(${e})`,[...t])}var Ut,$t,nr=class nr{constructor(t,r){cn(this,Ut);cn(this,$t);un(this,Ut,t),un(this,$t,r)}get visible(){return Wt(this,Ut)===null?null:new Set(Wt(this,Ut))}get commentable(){return Wt(this,$t)===null?null:new Set(Wt(this,$t))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=Ci(r?t.read:t),o=r?t.comment:void 0;if(o===void 0)return new nr(n,n);let a=Ci(o),i=new Set;for(let l of a??[])n.has(l)&&i.add(l);return new nr(n,i)}static unrestricted(t){return new nr(null,null)}};Ut=new WeakMap,$t=new WeakMap;var He=nr;function ar(e){let t=Mi(e.visible),r=Mi(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function Mi(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(nd);if(t.length<=od)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 Pi=(e,t,r,n)=>Ee(n.commentable,t)||e.authorUserId!==null&&e.authorUserId===r;import{parseQuerySets as Yd}from"@aiquants/fuzzy-search";import{createHash as sd}from"crypto";import{setImmediate as Li}from"timers/promises";import{clusterCountOf as ld,DEFAULT_NORMALIZE_OPTIONS as Hr,InteriorPairs as cd,isAnswerTier as ud,normalizeText as dd,queryNeedles as pd,resolveNormalizeOptions as md,toMappedFormsInto as yd,trimmedRange as hd}from"@aiquants/fuzzy-search/normalize";var Br=`
5
+ `,Zn=4e3,fd=1,Oi=new Set([8203,8288,65279,173]),Rd=new RegExp(`[${String.fromCodePoint(...Oi)}]`,"gu"),Fi=new RegExp(`\\r\\n|[\\n\\r${String.fromCodePoint(133,8232,8233)}]`,"gu"),Hi=/(\s+)/u,Sd=/^\s+$/u,gd=new RegExp(Hi.source,"gu"),bd=/^(?:(?=\p{Lo})[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]|[A-Za-z0-9])$/u,Dd=new Set([8205,1536,1537,1538,1539,1540,1541,1757,1807,2192,2193,2274,69821,69837,70082,70083,71999,72001,72250,72324,72325,72326,72327,72328,72329,73030,73474]),Ur=e=>e.replace(Rd,"");var eo=e=>dd(e,Hr),Fr=e=>eo(Ur(e)),Td=md({...Hr,convertRomaji:!0},"[daily-report] search reading options"),Ad=3,Ed=/^[-ー]+/u,wd=/[^\p{L}\p{M}]/gu,Id=/ー{2,}/gu,_d=/\p{Script=Latin}/u,ki=/(?=\p{L})\p{Script=Latin}/u,xd=e=>ld(e.replace(Ed,"").replace(wd,"").replace(Id,"\u30FC")),Cd=(e,t)=>{for(let r of t)if(!ud(r.tier)||r.splitTier!==null)throw new Error(`[daily-report] search readings: queryNeedles gave an unfinished needle for the word ${JSON.stringify(e)} (text ${JSON.stringify(r.text)}, tier ${r.tier}, splitTier ${r.splitTier})`)},Bi=e=>{if(!ki.test(e))return[];let t=Fr(e);if(!ki.test(t))return[];let r=pd(t,Td,!1);Cd(t,r);let n=[];for(let o of r){if(o.tier===It.word)continue;let a=Fr(o.text);if(!(a.length===0||a.length>Ae.maxWordLength)&&!(a===t||_d.test(a))&&!(xd(a)<Ad||n.includes(a))&&(n.push(a),n.length===Mn))break}return n},to=(e,t)=>{let r=e.charCodeAt(t-1),n=e.charCodeAt(t);return r>=55296&&r<=56319&&n>=56320&&n<=57343},Ui=(e,t)=>{let r=e.codePointAt(t),n=t>=2&&to(e,t-1)?t-2:t-1;return bd.test(String.fromCodePoint(r))&&!Dd.has(e.codePointAt(n))},Md=(e,t,r)=>{let n=[],o=0,a=0;for(;e.length-a>r;){let i=a+r;for(;i>a&&!Ui(e,i);)i--;i===a&&(i=a+r,to(e,i)&&i--,o++),n.push({start:t+a,end:t+i}),a=i}return n.push({start:t+a,end:t+e.length}),{pieces:n,forcedCuts:o}},ro=(e,t)=>{if(e.length<=t)return{chunks:[[{start:0,end:e.length}]],forcedCuts:0};let r=[],n=0,o=0,a=0,i=0,l=()=>{i>0&&r.push([{start:a,end:a+i}]),i=0};for(let s of e.split(Hi)){let c=o;if(o+=s.length,i+s.length<=t){i===0&&(a=c),i+=s.length;continue}if(l(),Sd.test(s))continue;if(s.length<=t){a=c,i=s.length;continue}let d=Md(s,c,t);n+=d.forcedCuts,r.push(d.pieces)}return l(),{chunks:r,forcedCuts:n}},no=(e,t)=>{let r=ro(e,t),n=[];for(let o of r.chunks){let a=o.map(i=>eo(e.slice(i.start,i.end))).join("");a.length>0&&n.push(a)}return{text:n.join(" "),forcedCuts:r.forcedCuts}},Pd=(e,t)=>{let r=0;for(let n of e.matchAll(Fi))t(e.slice(r,n.index),r),r=n.index+n[0].length;t(e.slice(r),r)},Ld=(e,t)=>{if(e.partialReadings!==null)throw new Error(`[daily-report] search marks: the mapped forms of the piece ${JSON.stringify(t)} carry partial readings`);return e.canonical},$i=(e,t)=>{let r="",n=[],o=[];for(let a of t.chunks){let i="",l=[],s=[];for(let c of a){let d=e.slice(c.start,c.end),u=Ld(yd(d,Hr,new cd(0)),d),[R,m]=hd(u.text);i+=u.text.slice(R,m);for(let p=R;p<m;p++)l.push(c.start+u.start[p]),s.push(c.start+u.end[p])}if(i.length!==0){r.length>0&&(r+=" ",n.push(o[o.length-1]),o.push(l[0])),r+=i;for(let c=0;c<l.length;c++)n.push(l[c]),o.push(s[c])}}return{text:r,start:n,end:o}},$r=(e,t=Zn)=>{let r=[],n=0;return Pd(Ur(e),o=>{let a=no(o,t);n+=a.forcedCuts,a.text.length>0&&r.push(a.text)}),{text:r.join(Br),forcedCuts:n}},Vi=e=>e.filter(t=>t.length>0).join(Br),oo=(e,t)=>{let r=null;return{advance:n=>{if(r!==null)return 0;e.units=ue("search text steps: units",n,1);let o=t.next();return o.done===!0&&(r={result:o.value}),n-e.units},done:()=>r!==null,result:()=>{if(r===null)throw new Error("[daily-report] search text: the steps are not done (advance until done() is true)");return r.result}}},Ni=4096;function*kd(e,t){let r=[],n=new Uint32Array(e.length),o=0,a=!1;for(let i=0;i<e.length;){for(;t.units===0;)yield;let l=Math.min(e.length,i+t.units);t.units-=l-i;let s=o,c=new Uint16Array(l-i);for(let d=i;d<l;d++){let u=e.charCodeAt(d);Oi.has(u)||(c[o-s]=u,n[o++]=d)}if(o-s===l-i)a&&r.push(e.slice(i,l));else{a||r.push(e.slice(0,i)),a=!0;for(let d=s;d<o;d+=Ni)r.push(Reflect.apply(String.fromCharCode,null,c.subarray(d-s,Math.min(o,d+Ni)-s)))}i=l}return a?{text:r.join(""),rawIndex:n.subarray(0,o)}:{text:e,rawIndex:null}}var Yi=e=>{let t={units:0};return oo(t,kd(e,t))};function*Nd(e,t,r){let n=0;for(let o=0;o<e.length;){for(;r.units===0;)yield;let a=Math.min(e.length,o+r.units);r.units-=a-o;let i=a;for(let l of e.slice(o,Math.min(e.length,a+1)).matchAll(Fi)){let s=o+l.index;if(s>=a)break;t(e.slice(n,s),n),n=s+l[0].length,i=Math.max(i,n)}o=i}t(e.slice(n),n)}var qi=(e,t)=>{let r={units:0};return oo(r,Nd(e,t,r))};function*vi(e,t,r,n,o){let a=[],i=0,l=t;for(;r-l>n;){let s=l+n;for(;s>l;s--){for(;o.units===0;)yield;if(o.units-=1,Ui(e,s))break}s===l&&(s=l+n,to(e,s)&&s--,i++),a.push({start:l,end:s}),l=s}return a.push({start:l,end:r}),{pieces:a,forcedCuts:i}}function*vd(e,t,r){if(e.length<=t)return{chunks:[[{start:0,end:e.length}]],forcedCuts:0};let n=[],o=0,a=0,i=0,l=0,s=0,c=!1,d=(m,p,f)=>{let y=p-m;return i+y<=t?(i===0&&(a=m),i+=y,!1):(i>0&&n.push([{start:a,end:a+i}]),i=0,f?!1:y<=t?(a=m,i=y,!1):!0)},u=m=>{c&&(d(l,s,!0),l=s),c=!1,s=m},R=m=>{let p=-1;return!c&&s>l&&(d(l,s,!1)&&(p=l),l=s),c=!0,s=m,p};for(let m=0;m<e.length;){for(;r.units===0;)yield;let p=Math.min(e.length,m+r.units);r.units-=p-m;let f=m;for(let y of e.slice(m,p).matchAll(gd)){let S=m+y.index;S>f&&u(S),f=S+y[0].length;let I=R(f);if(I>=0){let D=yield*vi(e,I,S,t,r);o+=D.forcedCuts,n.push(D.pieces)}}p>f&&u(p),m=p}if(d(l,s,c)){let m=yield*vi(e,l,s,t,r);o+=m.forcedCuts,n.push(m.pieces)}return i>0&&n.push([{start:a,end:a+i}]),{chunks:n,forcedCuts:o}}var ji=(e,t)=>{let r={units:0};return oo(r,vd(e,t,r))},Od=e=>{let t=[];for(let r=0;r<=65535;r++)r>=55296&&r<=57343||t.push(e+String.fromCharCode(r));return t.join(`
6
+ `)},Fd=[`\u3067\u3093${String.fromCodePoint(8203)}\u3077\u3093 \uFF83\uFF9E\uFF9D\uFF8C\uFF9F\uFF9D\r
7
+ \u30C7\u30F3\u30D7\u30F3`,"\u30DD\u30C6\u30C8-25kg \u30A2--1 \u30FC\u30FC\u30E1\u30F3 \u4F50\u3005\u6728","\u6F22\u5B57\u304B\u306A\u30AB\u30CAABC123\u6F22\u5B57\u304B\u306A\u30AB\u30CAABC123\u6F22\u5B57\u304B\u306A\u30AB\u30CA",`\uFF71\uFF72\uFF73\uFF74\uFF75\uFF76\uFF9E\uFF77\uFF9E\uFF78\uFF9E\uFF79\uFF9E\uFF7A\uFF9E${String.fromCodePoint(8232)}\u6B21\u306E\u884C`],Hd=["","\u30A2","\u4F50"," "],Bd=()=>JSON.stringify(Fd.map(e=>$r(e,8))),Ud=e=>`dr-search-v${fd};fz=${e.slice(0,16)};u=${process.versions.unicode};icu=${process.versions.icu}`;var $d=async()=>{let e=sd("sha256");e.update(JSON.stringify(Hr));for(let t of Hd)await Li(),e.update("\0"),e.update(eo(Od(t)));return await Li(),e.update("\0"),e.update(Bd()),Ud(e.digest("hex"))},Vd=e=>{let t=null;return()=>{if(t===null){let r=e();t=r,r.catch(()=>{t=null})}return t}},ao=Vd($d);var qd=/^-+/u,jd=/\s+/u,Wi=e=>{let t=qd.exec(e);return t===null?[e]:[e,"\u30FC".repeat(t[0].length)+e.slice(t[0].length)]},Wd=(e,t)=>{let r=[...Wi(e).map(n=>({text:n,tier:It.word})),...t.flatMap(n=>Wi(n).map(o=>({text:o,tier:It.reading})))];return r.filter((n,o)=>r.findIndex(a=>a.text===n.text)===o)},zd=e=>JSON.stringify(e.map(({text:t,tier:r})=>JSON.stringify([r,t])).sort()),Vr=(e,t)=>{if(e.length>Ae.maxQueryLength)return{ok:!1,reason:"too-long"};let r=[],n=new Set,o=0;for(let{query:a}of Yd(Ur(e),t).sets){let i=[],l=new Set;for(let c of a.split(jd)){let d=Fr(c);if(d.length===0)return{ok:!1,reason:"blank-word"};if(d.length>Ae.maxWordLength)return{ok:!1,reason:"word-too-long"};let u=Wd(d,Bi(c)),R=zd(u);l.has(R)||(l.add(R),i.push({alternatives:u}))}if(i.length>Ae.maxWordsPerSet)return{ok:!1,reason:"too-many-words-in-set"};let s=JSON.stringify([...l].sort());n.has(s)||(n.add(s),o+=i.length,r.push({words:i}))}return r.length===0?{ok:!1,reason:"empty"}:r.length>Ae.maxSets?{ok:!1,reason:"too-many-sets"}:o>Ae.maxWords?{ok:!1,reason:"too-many-words"}:{ok:!0,plan:{combine:t,sets:r}}},ir=e=>e.sets.map(t=>t.words.map(r=>r.alternatives));var Wf=Object.freeze({sourceTypes:null,authors:null,customers:null}),Gd=e=>e.sourceTypes!==null||e.authors!==null||e.customers!==null,zi=(e,t,r)=>{if(oa(e)&&Gd(r))return{ok:!0,criteria:{plan:null,filters:r}};let n=Vr(e,t);return n.ok?{ok:!0,criteria:{plan:n.plan,filters:r}}:{ok:!1,reason:n.reason}};var Gi=6e4,Kd=1,Jd=3200,Ki=2e3,Qd=Object.freeze({search:Jd,reports:Ki,"search-marks":Ki,"search-facets":null}),Xd=(e,t)=>{let r=Qd[e];return r===null?null:{max:t,maxPerOwner:Er,maxWaitMs:r}},sr=e=>{let{concurrency:t,route:r,logger:n}=e,o=it({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:Gi,logger:n,windowFields:()=>`route=${r}`}),a=Ze({limit:t,maxHeldPerOwner:Math.max(1,Math.floor(t/2)),queue:Xd(r,t)}),i=Object.freeze({status:429,message:Wn,headers:Object.freeze({"Retry-After":String(Kd)})}),l=Fe({windowMs:Gi,tallies:["busy"],writeSuppressed:(s,{count:c,since:d})=>{n.warn(`busy_suppressed count=${c} since=${d} route=${r} concurrency=${t}`)}});return{admit:async(s,c)=>{let d=o.spend(s,r);if(d!==null)return{refusal:d};let u=await a.acquire(s,c);return u!==null?{release:u}:(o.refund(s,1),c.aborted||l.record(r,"busy",()=>n.warn(`429 ${r} reason=busy concurrency=${t}`)),{refusal:i})}}};import{systemSseRuntime as ip}from"@aiquants/sse";import{createSseResponse as sp,readLastEventId as lp,startSseHeartbeat as cp,terminalStreamResponse as up}from"@aiquants/sse/server";var lr=(e,t)=>{let r=e.message.data;if(!r)return{entry:{id:e.id,message:null},json:void 0};let n;try{n=JSON.parse(r)}catch(i){return t.error(`SSE message ${e.id} is not JSON:`,i),{entry:{id:e.id,message:null},json:void 0}}let o=jo.safeParse(n);if(!o.success)return t.error("SSE message validation failed:",o.error.format()),{entry:{id:e.id,message:null},json:n};let a=Object.freeze({parsed:o.data,published:n,text:r});return{entry:Object.freeze({id:e.id,message:a}),json:n}},Zd=["externalComments","postedComments"],Ji=new WeakMap,ep=e=>{let t=Ji.get(e);if(t!==void 0)return t;let r={recipientRemoved:null,commentsRedacted:null};return Ji.set(e,r),r},Qi=e=>{let{recipientRawUserId:t,...r}=e;return r},Xi=(e,t)=>{let{published:r}=e;if(!(t||Object.hasOwn(r,"recipientRawUserId")))return e.text;let n=ep(e);if(t){if(n.commentsRedacted===null){let o=Qi(r),a=o.report;n.commentsRedacted=JSON.stringify({...o,report:{...a,...Object.fromEntries(Zd.map(i=>[i,[]]))}})}return n.commentsRedacted}return n.recipientRemoved===null&&(n.recipientRemoved=JSON.stringify(Qi(r))),n.recipientRemoved};import{systemSseRuntime as rp}from"@aiquants/sse";import{createSharedSource as np}from"@aiquants/sse/shared-source";var mt="daily-report:ids:",yt="daily-report:business-date:",Yr=(e,t)=>`${e}st:${t}`,io=e=>`${mt}user:${e}:`,Zi=(e,t)=>Yr(io(e),t),tp=e=>`${yt}${e}:`,es=(e,t)=>Yr(tp(e),t),Vt=e=>`daily-report:date:${e}:user:`,xt=(e,t)=>`${Vt(e)}${t}:`,ts=(e,t,r)=>Yr(xt(e,t),r),Be=e=>`daily-report:detail:${e}:user:`,qr=(e,t)=>`${Be(e)}${t}:`,rs=(e,t,r)=>Yr(qr(e,t),r);var ht=(e,t)=>{let[r,n]=e.split("-").map(Number),[o,a]=t.split("-").map(Number);return r!==o?r<o:n<=a},op=5e3,ap=wr,cr=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=he(t.logger,1,"SseReader"),this._source=this._createSource()}ready(){return this._position().then(()=>{})}subscribe(t,r){return this._source.subscribe({next:n=>{this._lastId=n.id,t(n)},error:n=>r(n instanceof Error?n:new Error(String(n)))})}async destroy(){await this._source.dispose(),this._generation+=1,this._positioning=null,this._lastId=null,this._source=this._createSource()}_position(){if(this._lastId!==null)return Promise.resolve(this._lastId);if(this._positioning===null){let t=this._generation;this._positioning=this._readTail().then(r=>{if(t!==this._generation)throw new Error("SSE reader was destroyed while the stream tail was being read");return this._positioning=null,this._lastId=r,r},r=>{throw t===this._generation&&(this._positioning=null),r})}return this._positioning}async _readTail(){let t=await this.config.redis?.getClient();if(!t)throw new Error("Failed to get Redis client to read the SSE stream tail");let r=await t.xRevRange(this.config.streamKey,"+","-",{COUNT:1});return r.length>0?r[0].id:"0-0"}_createSource(){return np({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:rp,onListenerError:t=>this._logger.error("SSE reader subscriber threw:",t),onStopError:t=>this._logger.error("SSE reader failed to stop:",t)})}async _start(t){let r=await this._position(),n=await this.config.redis?.createClient();if(!n)throw new Error("Failed to create Redis client for SSE reader");n.on("error",i=>{this._logger.error("Redis client error:",i)});let o=!1,a=this._readLoop(n,t,r,()=>o);return async()=>{if(o=!0,n.isOpen)try{await n.quit()}catch{}await a}}async _readLoop(t,r,n,o){let a=n;try{for(;!o()&&t.isOpen;){let i=await t.xRead([{key:this.config.streamKey,id:a}],{BLOCK:op,COUNT:ap});if(i)for(let l of i)for(let s of l.messages){a=s.id;let{entry:c,json:d}=lr(s,this._logger);this._invalidateCaches(d),r.next(c)}}}catch(i){o()||(this._logger.error("xRead loop error:",i),r.fail(i instanceof Error?i:new Error(String(i))));return}o()||r.fail(new Error("Redis client for SSE reader closed unexpectedly"))}_invalidateCaches(t){if(t===null||typeof t!="object")return;let{type:r,reportHubId:n}=t;(r==="report-create"||r==="report-delete"||r==="report-publish")&&this.config.cache.invalidatePrefix(mt),(r==="comment-add"||r==="comment-delete"||r==="status-update")&&typeof n=="number"&&this.config.cache.invalidatePrefix(Be(n))}};var as=Object.freeze({...tr,route:"sse",frameworkDataRefusal:Ir}),ns=864e5,dp={baseMs:2e3,jitterMs:8e3},is=6e4,so=wr,ss=JSON.stringify({type:"connected"}),os="0-0",pp=(e,t,r)=>{if(t===null&&r===null)return!0;switch(e.type){case"connected":case"status-update":return!0;case"report-create":case"report-update":case"report-publish":return Ee(t,e.report.sourceType);case"comment-add":case"comment-delete":return Ee(r,e.sourceType);case"report-delete":return Ee(t,e.sourceType)}},mp=(e,t)=>t===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"?!1:!Ee(t,e.report.sourceType),yp=(e,t)=>{e.writeEvent({event:null,id:t,data:ss})},hp=(e,t,r)=>{let{message:n}=t;if(n===null)return;let{parsed:o,published:a}=n,i=typeof a.recipientRawUserId=="number"?a.recipientRawUserId:void 0;if((o.type==="status-update"||i!==void 0)&&i!==r.internalUserId||!pp(o,r.visibleSet,r.commentableSet)){yp(e,t.id);return}e.writeEvent({event:null,id:t.id,data:Xi(n,mp(o,r.commentableSet))})},ls=e=>{let{authenticate:t,service:r,resolveViewerScope:n,redis:o,sseReader:a,streamKey:i,streamSlots:l,logger:s}=e,c=async(d,u)=>{let{request:R,internalUserId:m,cursor:p}=u,f=u.initialScope.visible,y=u.initialScope.commentable,S=0,I=setInterval(()=>{let b=++S;n(R,"refresh").then(k=>{b===S&&(f=k.visible,y=k.commentable)})},is);d.onClose(()=>clearInterval(I));let D=p===null?os:p,h=p!==null&&o!==void 0,g=[],M=null,_=b=>{ht(b.id,D)||(D=b.id,hp(d,b,{internalUserId:m,visibleSet:f,commentableSet:y}))},C=async(b,k)=>{let[U]=await b.xRange(i,"-","+",{COUNT:1});return U!==void 0&&!ht(U.id,k)},Y=async(b,k)=>{if(await C(b,k))return!1;let U=k;for(;;){let O=await b.xRange(i,U,"+",{COUNT:so}),F=O[0];if(F!==void 0&&F.id!==U&&await C(b,U))return!1;for(let X of O){if(M!==null&&ht(M,X.id))return!0;ht(X.id,D)||_(lr(X,s).entry)}let z=O.at(-1);if(O.length<so||z===void 0||d.isClosed())return!0;U=z.id}},L=a.subscribe(b=>{if(!h){_(b);return}ht(b.id,D)||(M===null&&(M=b.id),g.push(b))},b=>{s.error(`[SSE:${m}] Fan-Out reader error:`,b),d.close()});if(d.onClose(L),p===null){await a.ready();try{let b=await o?.getClient();if(b){let k=await b.xRevRange(i,"+","-",{COUNT:1});k.length>0&&!ht(k[0].id,D)&&(D=k[0].id)}}catch{}}if(d.writeEvent({event:null,id:D===os?null:D,data:ss}),cp(d,{intervalMs:Vo,retry:dp,runtime:ip}),p===null||o===void 0)return;await a.ready();let N=await o.getClient();if(N===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await Y(N,p)){d.writeRetry(ns),d.writeEvent({event:"resync-required",id:null,data:""}),d.close();return}h=!1;for(let b of g.splice(0))_(b)};return async({request:d,params:u})=>{let R,m=()=>{let f=new Headers;R!==void 0&&f.append("Set-Cookie",R);for(let[y,S]of Object.entries(Xe))f.set(y,S);return f},p=f=>up(f,{data:"",retryMs:ns,headers:m()});try{let f=await t(d,{failureRedirect:null});R=f.cookie;let{user:y}=f;if(!y)return p("auth-required");let S=await r.getUserIdByExternalId(y.id);if(!S)return p("forbidden");if(u.endpoint!=="updates")return new Response("Not Found",{status:404,headers:m()});let I=lp(d,Yo);if(I!==null&&!qo(I))return s.warn(`[SSE:${S}] malformed resume cursor; asking the client to resync`),p("resync-required");let D=vr(d),h=await l.admit(S,"sse",D);if(h===null){let M=m();for(let[_,C]of Object.entries(Ne(503)))M.set(_,C);return new Response("Too many streams",{status:503,headers:M})}let g=!1;try{let M=await n(d,"initial");return sp({requestSignal:D,headers:m(),onError:(_,C)=>s.error(`[SSE:${S}] ${C} failed:`,_),produce:_=>(g=!0,_.onClose(h),c(_,{request:d,internalUserId:S,cursor:I,initialScope:M}))})}finally{g||h()}}catch(f){if(f instanceof Response)throw f;let y=f instanceof Error?f:new Error(String(f));return s.error(`500 sse name=${y.name} message=${y.message}`),new Response("Internal Server Error",{status:500,headers:m()})}}};var cs=(e,t)=>{let r=new Headers({...t?.headers,"Content-Type":"application/json",...Xe});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},fp=Object.freeze({...tr,route:"api",frameworkDataRefusal:({params:e})=>On(e.endpoint)&&_t[e.endpoint].body==="stream"?Ir():null}),Rp=Object.freeze({...tr,route:"action"}),Sp=(e,t,r)=>({...r,status:"OK",intent:e.intent,reportHubId:t,clientTempId:e.clientTempId}),ys=6e4,hs=5,gp=hs*Math.ceil(ys/500),bp=2,Dp=6,Tp=6e4,Ap=hs*bp*Dp,Ep=2,wp=10,Ip=2,_p=10,us=(e,t)=>Math.max(e,Er)*t,fs=(e,t)=>{for(let[r,n]of Object.entries(t))e.headers.set(r,n);return e},xp=Object.freeze({etag:(e,t,r)=>ga(e,t,r,200),"no-store":(e,t,r)=>$n(t,r,200)}),Cp=e=>Vn(e.body==="json"?xp[e.cache]:null),ds=Vn(null),ps=(e,t,r,n)=>fs(e(t,r,{error:{message:n.message}},n.status),n.headers),ms=(e,t,r)=>fs(e(t,r,null,503),Ne(503));function lo(e){kr(e);let{authenticate:t,service:r,encodeUserId:n,redis:o,sseReader:a,streamKey:i}=e,l={titleMaxLength:ue("service.titleMaxLength",r.titleMaxLength,1)},s=e.loginRedirectPath??"/auth/login",c=he(e.logger,3,"API"),d=he(e.logger,3,"Visibility"),u=he(e.logger,1,"SSE"),R=he(e.logger,1,"Attachment"),m=he(e.logger,2,"Isolation"),p=he(e.logger,2,"Action"),f=he(e.logger,2,"Search"),y=he(e.logger,2,"Refresh"),S=he(e.logger,2,"Streams"),I=he(e.logger,2,"Reads"),D=it({reason:"refresh_rate_limit",limitPerWindow:Ap,windowMs:Tp,logger:y,windowFields:()=>"route=api"}),h=gi(S),g=fi(I),M=async(E,T,A,w,x,v)=>{let V=await r.getUserIdByExternalId(T.id);try{return await v(V===null?void 0:g.admissionFor(V,E,A.signal))}catch(H){if(H instanceof $e)return Nr(x,A,w);throw H}},_=(E,T,A,w,x)=>{let v=D.spend(T.id,`endpoint=${E}`);return v===null?null:ps(x,A,w,v)},C=async(E,T="initial")=>{let A=e.resolveVisibleSourceTypes;if(!A)return He.unrestricted("no visibility port injected: this deployment does not restrict by source type");try{let w=await A(E,{reason:T});return w==null?He.unrestricted("visibility port returned null/undefined: this deployment opts out of source-type filtering"):He.restrictTo(w)}catch(w){return d.error("resolveVisibleSourceTypes threw; failing closed (deny all)",w),He.restrictTo([])}},Y=async({request:E})=>{let{user:T,cookie:A}=await t(E,{failureRedirect:s}),w=new Headers;A&&w.append("Set-Cookie",A);let x=await r.getUserIdByExternalId(T.id),v=x?n(x):null;return{data:{user:T,userId:v},headers:w}},L=E=>{let{limiter:T}=E;return async(A,w,x,v,V,H)=>{if(T===null)return H(x,w,{error:{message:"Unknown endpoint"}},404);let j=E.parse(A);if(!j.ok)return H(x,w,j.invalid,400);let P=await r.getUserIdByExternalId(v.id);if(!P)return H(x,w,E.emptyAnswer(j.parsed),200);let{signal:W}=x,Z=await T.admit(P,W);if("refusal"in Z)return W.aborted?ms(H,x,w):ps(H,x,w,Z.refusal);try{W.throwIfAborted();let Q=await E.read(j.parsed,{userId:P,user:v,scope:V},W);return W.throwIfAborted(),H(x,w,Q,200)}catch(Q){if(W.aborted&&Q===W.reason)return ms(H,x,w);throw Q}finally{Z.release()}}},N=r.searchLimits===null?null:sr({...r.searchLimits,route:oe.search,logger:f}),b=r.searchLimits===null?null:sr({concurrency:us(r.searchLimits.concurrency,Ep),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*wp,route:oe.reports,logger:f}),k=r.searchLimits===null?null:sr({concurrency:us(r.searchLimits.concurrency,Ip),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*_p,route:oe.searchMarks,logger:f}),U=r.searchLimits===null?null:sr({...r.searchLimits,route:oe.searchFacets,logger:f}),O={[oe.businessDate]:async(E,T,A,w,x,v)=>{let V=E.searchParams.get(ye.businessDate),H=V===null?null:vt(V);if(H===null)return v(A,T,{error:{message:"Invalid business date"}},400);let j=er(E.searchParams.get(ye.forceRefresh));if(j===null)return v(A,T,{error:{message:"Invalid forceRefresh"}},400);let P=j?_(oe.businessDate,w,A,T,v):null;return P!==null?P:M(oe.businessDate,w,A,T,v,async W=>{let Z=await r.getDailyReportsByBusinessDateByExternalId(x,H,w.id,{forceRefresh:j,admission:W});return v(A,T,{businessDate:H,reports:Z},200)})},[oe.idsStream]:_i({service:r,logger:c,streamSlots:h,missGate:g,refuseForcedRead:(E,T,A,w)=>_(oe.idsStream,E,T,A,w)}),[oe.report]:async(E,T,A,w,x,v)=>{let V=Ve(E.searchParams.get(ye.reportHubId));if(V===null)return v(A,T,{error:{message:"Invalid reportHubId"}},400);let H=er(E.searchParams.get(ye.forceRefresh));if(H===null)return v(A,T,{error:{message:"Invalid forceRefresh"}},400);let j=H?_(oe.report,w,A,T,v):null;return j!==null?j:M(oe.report,w,A,T,v,async P=>{let W=await r.getDailyReportDetailByIdByExternalId(x,V,w.id,{snapshot:!0,forceRefresh:H,admission:P});return W?v(A,T,{report:W},200):v(A,T,{error:{message:"Report not found"}},404)})},[oe.search]:L({limiter:N,parse:E=>{let T=E.searchParams.get(ye.searchQuery),A=Nn(E.searchParams.get(ye.searchCombine));if(T===null||A===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let w=ia(E.searchParams,r.searchFilterSourceTypes);if(!w.ok)return{ok:!1,invalid:{error:{message:"Invalid search filters",reason:w.reason}}};let x=zi(T,A,w.filters);if(!x.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:x.reason}}};let{criteria:v}=x;return{ok:!0,parsed:{criteria:v,words:v.plan===null?[]:ir(v.plan)}}},emptyAnswer:({words:E})=>Pn([],E),read:async({criteria:E,words:T},{userId:A,scope:w})=>Pn(await r.searchDailyReports(w,A,E),T)}),[oe.reports]:L({limiter:b,parse:E=>{let T=vn(E.searchParams.get(ye.reportIds));return T===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:T}},emptyAnswer:()=>({reports:[]}),read:async(E,{user:T,scope:A})=>({reports:await r.getDailyReportDetailsByIdsByExternalId(A,E,T.id)})}),[oe.searchMarks]:L({limiter:k,parse:E=>{let T=E.searchParams.get(ye.searchQuery),A=Nn(E.searchParams.get(ye.searchCombine));if(T===null||A===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let w=Vr(T,A);if(!w.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:w.reason}}};let x=vn(E.searchParams.get(ye.reportIds));return x===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:{plan:w.plan,ids:x}}},emptyAnswer:({plan:E})=>({wordsDigest:Ar(ir(E)),reports:[],deferred:[]}),read:({plan:E,ids:T},{userId:A,scope:w},x)=>r.markDailyReportSearchHits(w,A,E,T,{signal:x})}),[oe.searchFacets]:L({limiter:U,parse:()=>({ok:!0,parsed:null}),emptyAnswer:()=>({sourceTypes:[],authors:[],customers:[]}),read:(E,{userId:T,scope:A})=>r.listDailyReportSearchFacets(A,T)})},F=async({request:E,params:T})=>{let{user:A,cookie:w}=await t(E,{failureRedirect:null}),x=w??null;if(!A)return ds(E,x,{error:{message:"Unauthorized"}},401);let v=T.endpoint;if(!On(v))return ds(E,x,{error:{message:"Unknown endpoint"}},404);let V=_t[v],H=Cp(V),j=fa[V.body];if(!j.includes(E.method)){let W=H(E,x,{error:{message:"Method not allowed"}},405);return W.headers.set("Allow",j.join(", ")),W}let P=ae();try{let W=new URL(E.url),Z=await C(E),Q=await O[v](W,x,E,A,Z,H);return V.body==="json"&&c.debug(Q.headers.has("ETag")?`${Q.status} endpoint=${v} etag_match=${Q.status===304}`:`${Q.status} endpoint=${v}`),Q}catch(W){let Z=ae()-P,Q=W instanceof Error?W:new Error(String(W));return c.error(`500 endpoint=${v} elapsed=${Z}ms name=${Q.name} code=${"code"in Q?Q.code:"N/A"} message=${Q.message}`,Q),H(E,x,{error:{message:"Internal Server Error"}},500)}},z=ha(p),X=it({reason:"rate_limit",limitPerWindow:gp,windowMs:ys,logger:p,windowFields:()=>"route=action"}),q=async(E,T,A,w,x)=>{let{clientTempId:v}=E;if(E.intent==="create"){let P=await r.createDailyReport(T,E.businessDate,v);return x(E,P.reportHubId,{report:P})}let{reportHubId:V,businessDate:H}=E,j=async(P,W)=>{try{let Z=await W(P.value);return x(P,V,{updatedStatus:{isStarred:Z.isStarred,isRead:Z.isRead},operationTimestamp:P.operationTimestamp})}catch(Z){if(Z instanceof Error&&Z.message==="Not Found")return w({error:"Report not found"},{status:404});throw Z}};switch(E.intent){case"update":try{return await r.updateDailyReport(V,T,E.changes,v),x(E,V,{})}catch(P){if(P instanceof Error){if(P.message==="Unauthorized")return w({error:"Unauthorized"},{status:403});if(P.message==="Not Found")return w({error:"Report not found"},{status:404})}throw P}case"publish":try{let P=await r.publishDailyReport(V,T,v);return x(E,V,{report:P})}catch(P){if(P instanceof Error){if(P.message==="Unauthorized")return w({error:"Unauthorized"},{status:403});if(P.message==="Not Found")return w({error:"Report not found"},{status:404})}throw P}case"delete":try{return await r.deleteDailyReport(V,T,v),x(E,V,{})}catch(P){if(P instanceof Error){if(P.message==="Unauthorized")return w({error:"Unauthorized"},{status:403});if(P.message==="Not Found")return w({error:"Report not found"},{status:404})}throw P}case"toggleStar":return await j(E,P=>r.setStarStatus(A,T,V,H,P,v));case"toggleRead":return await j(E,P=>r.setReadStatus(A,T,V,H,P,v));case"addComment":try{let P=await r.addComment(A,T,V,E.content,H,v);return x(E,V,{newComment:P})}catch(P){if(P instanceof Error){if(P.message==="Not Found")return w({error:"Report not found"},{status:404});if(P.message.startsWith("Comments are restricted"))return w({error:"Comments are restricted for this report"},{status:403})}throw P}case"deleteComment":try{return await r.deleteComment(A,T,V,E.commentId,H,v),x(E,V,{deletedCommentId:E.commentId})}catch(P){if(P instanceof Error){if(P.message==="Unauthorized")return w({error:"Unauthorized"},{status:403});if(P.message==="Not Found")return w({error:"Comment not found"},{status:404})}throw P}}},ne=async({request:E,params:T})=>{let{user:A,cookie:w}=await t(E,{failureRedirect:null}),x=(H,j)=>cs(H,{...j,setCookie:w}),v=(H,j,P)=>cs(Sp(H,j,P),{setCookie:w});if(!A)return x({error:"Unauthorized"},{status:401});let V=ae();try{if(T.endpoint!==oe.action)return x({error:"Unknown endpoint"},{status:404});let H=X.spend(A.id,"action");if(H!==null)return x({error:H.message},{status:H.status,headers:H.headers});let j=await ya(E,l);if("refusal"in j){let{refusal:Q}=j;return Q.status===413&&z(Q.measuredBy),x({error:Q.error},{status:Q.status})}let{command:P}=j;if(P.intent==="clearCache"&&!e.enableDevCacheClear)return x({error:"Invalid intent"},{status:400});let W=await r.getUserIdByExternalId(A.id);if(!W)return x({error:"User not found"},{status:404});let Z=await C(E);return P.intent==="clearCache"?(await r.clearCache(),x({status:"OK",intent:"clearCache"})):await q(P,W,Z,x,v)}catch(H){if(H instanceof Response)throw H;let j=ae()-V,P=H instanceof Error?H:new Error(String(H));return c.error(`500 action elapsed=${j}ms name=${P.name} message=${P.message}`,P),x({error:"Internal Server Error"},{status:500})}},ge=ls({authenticate:t,service:r,resolveViewerScope:C,redis:o,sseReader:a,streamKey:i,streamSlots:h,logger:u}),Pe=di({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:C,logger:R}),me=Ea(m),G=(E,T)=>async A=>{let w=Ta(A.request)?E.frameworkDataRefusal(A):null;if(w!==null)throw w;return Aa(A.request,E)?(me(E.route,A.request),E.crossSiteRejection()):T(A)};return{index:{loader:Y},api:{loader:G(fp,F),action:G(Rp,ne)},sse:{loader:G(as,ge)},attachment:{loader:G(ui,Pe)}}}import{chunk as fm,MAX_IN_LIST as Rm,runWithTransactionRetry as Sm}from"@aiquants/mssql";import{asc as ct,eq as rn,inArray as Rr}from"drizzle-orm";var Mp=["tables","externalSourceTexts","concurrency","rateLimitPerMinute"],Pp=["document","comment"],Lp=["hubId","searchText","sourceDigest","normalizerVersion","indexedAt","rowVersion","authorName","customerName"],kp=["hubId","ordinal","authorUserId","commentText"],co=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Rs=(e,t,r)=>{for(let n of Object.keys(t))if(!r.includes(n))throw pn(e,n,r)},Ss=(e,t,r)=>{if(typeof t!="object"||t===null)throw J(e,"a table object",t);let n=t;for(let o of r)if(typeof n[o]!="object"||n[o]===null)throw J(`${e}.${o}`,"a column",n[o])},gs=(e,t)=>{if(!co(e))throw J("search","a plain object",e);Rs("search key",e,Mp);let{tables:r}=e;if(!co(r))throw J("search.tables","a plain object with document and comment",r);Rs("search.tables key",r,Pp),Ss("search.tables.document",r.document,Lp),Ss("search.tables.comment",r.comment,kp);let n=new Map;if(e.externalSourceTexts!==void 0){if(!co(e.externalSourceTexts))throw J("search.externalSourceTexts","a plain object",e.externalSourceTexts);for(let[o,a]of Object.entries(e.externalSourceTexts)){if(!t.includes(o))throw pn("search.externalSourceTexts key",o,t);if(typeof a!="function")throw J(`search.externalSourceTexts.${o}`,"a function",a);n.set(o,a)}}return{tables:r,externalSourceTexts:n,concurrency:ue("search.concurrency",e.concurrency,1),rateLimitPerMinute:ue("search.rateLimitPerMinute",e.rateLimitPerMinute,1)}};var ft=e=>{let t=typeof e=="object"&&e!==null?e.recordset:void 0;if(!Array.isArray(t))throw new Error("[daily-report] search: the database result has no recordset");return t},Ct=(e,t)=>{let r=typeof e=="string"?Ve(e):typeof e=="number"&&Je(e)?e:null;if(r===null)throw new Error(`[daily-report] search: column ${t} holds no positive id`);return r},Mt=(e,t)=>{if(e===null||typeof e=="string")return e;throw new Error(`[daily-report] search: column ${t} holds no string`)};import{sql as B}from"drizzle-orm";import{sql as Rt}from"drizzle-orm";var bs=e=>{if(e.length===0)throw new Error("[daily-report] draft rule: draftLabelNames must hold at least one name (a rule without names would show every draft to every viewer)");return Rt.join(e.map(t=>Rt`${t}`),Rt`, `)},Wr=(e,t)=>{let{hub:r,hubLabel:n,label:o}=e;return Rt`EXISTS (SELECT 1 FROM ${n} INNER JOIN ${o} ON ${o.id} = ${n.labelId} WHERE ${n.hubId} = ${r.id} AND ${o.name} IN (${bs(t)}))`},Ds=(e,t)=>{let{hubLabel:r,label:n}=e;return Rt`${r.labelId} IN (SELECT ${n.id} FROM ${n} WHERE ${n.name} IN (${bs(t)}))`},zr=(e,t,r,n)=>{let{hub:o}=e,a=n==="author-or-authorless"?Rt`${o.userId} = ${t} OR ${o.userId} IS NULL`:Rt`${o.userId} = ${t}`;return Rt`(${a} OR NOT ${Wr(e,r)})`};var Np=/[[%_]/gu,vp=e=>e.replace(Np,t=>`[${t}]`),Ts=e=>`%${vp(e)}%`;var qe=Object.freeze({reportHubId:"report_hub_id",businessDate:"business_date",sourceType:"source_type"}),Pt=Object.freeze({reportHubId:"report_hub_id",matchedSets:"matched_sets"}),dr=Object.freeze({value:"value"}),we=Object.freeze({hubId:"hub_id",sourceDigest:"source_digest",normalizerVersion:"normalizer_version"}),$=e=>B`${B.identifier(e.name)}`,ur=e=>B.join(e.map(t=>B`${t}`),B`, `),As=(e,t)=>B`SELECT ${$(e.id)} AS ${B.identifier(we.hubId)} FROM ${e} WITH (UPDLOCK, ROWLOCK) WHERE ${e.id} IN (${ur(t)}) ORDER BY ${e.id}`,Op=(e,t,r)=>{let{hub:n}=e,{document:o,comment:a}=e.search,i=t.alternatives.map(u=>Ts(u.text)),l=B.join(i.map(u=>B`${o.searchText} LIKE ${u}`),B` OR `),s=B.join(i.map(u=>B`${a.commentText} LIKE ${u}`),B` OR `),c=or(n.sourceType,r.scope.commentable),d=c===void 0?B``:B` AND (${c} OR ${a.authorUserId} = ${r.userId})`;return B`((${l}) OR EXISTS (SELECT 1 FROM ${a} WHERE ${a.hubId} = ${n.id} AND (${s})${d}))`},Es=(e,t,r)=>B`(${B.join(t.words.map(n=>Op(e,n,r)),B` AND `)})`,uo=(e,t,r,n)=>{let{hub:o}=e,a=[B`${o.deletedAt} IS NULL`,zr(e,t.userId,r,"author")],i=or(o.sourceType,t.scope.visible);return i!==void 0&&a.push(i),n!==void 0&&a.push(B`${o.id} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${JSON.stringify(n)}))`),a},Fp=(e,t)=>{let{hub:r}=e,{document:n}=e.search,o=[];if(t.sourceTypes!==null){if(t.sourceTypes.size===0)throw new Error("[daily-report] search: a source-type filter must hold at least one source type");o.push(B`LOWER(${r.sourceType}) IN (${ur([...t.sourceTypes])})`)}return t.authors!==null&&o.push(B`${n.authorName} IN (${ur(t.authors)})`),t.customers!==null&&o.push(B`${n.customerName} IN (${ur(t.customers)})`),o},ws=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,{plan:l}=t,s=[...uo(e,r,n,o),...Fp(e,t.filters)];if(l!==null){let c=l.combine==="intersection"?B` AND `:B` OR `;s.push(B`(${B.join(l.sets.map(d=>Es(e,d,r)),c)})`)}return B`SELECT ${$(a.id)} AS ${B.identifier(qe.reportHubId)}, CONVERT(char(10), ${$(a.businessDate)}, 23) AS ${B.identifier(qe.businessDate)}, ${$(a.sourceType)} AS ${B.identifier(qe.sourceType)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${B.join(s,B` AND `)} ORDER BY ${a.businessDate} DESC, ${a.id} DESC`},Is=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,l=B.join(t.sets.map((s,c)=>B`(CASE WHEN ${Es(e,s,r)} THEN ${2**c} ELSE 0 END)`),B` + `);return B`SELECT ${$(a.id)} AS ${B.identifier(Pt.reportHubId)}, ${l} AS ${B.identifier(Pt.matchedSets)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${B.join(uo(e,r,n,o),B` AND `)}`},_s=(e,t,r,n)=>{let{hub:o}=e,{document:a}=e.search,i=a[t],l=[...uo(e,r,n),B`${i} IS NOT NULL`];return B`SELECT ${i} AS ${B.identifier(dr.value)} FROM ${o} INNER JOIN ${a} ON ${a.hubId} = ${o.id} WHERE ${B.join(l,B` AND `)} GROUP BY ${i} ORDER BY ${i}`},xs=(e,t,r)=>{let{document:n,comment:o}=e,a=JSON.stringify(t.map(s=>({[n.hubId.name]:s.hubId,[n.searchText.name]:s.searchText,[n.sourceDigest.name]:s.sourceDigest,[n.normalizerVersion.name]:r,[n.authorName.name]:s.authorName,[n.customerName.name]:s.customerName}))),i=JSON.stringify(t.flatMap(s=>s.comments.map(c=>({[o.hubId.name]:s.hubId,[o.ordinal.name]:c.ordinal,[o.authorUserId.name]:c.authorUserId,[o.commentText.name]:c.commentText})))),l=JSON.stringify(t.map(s=>s.hubId));return B`MERGE ${n} WITH (HOLDLOCK) AS t USING (SELECT * FROM OPENJSON(${a}) WITH (${$(n.hubId)} bigint, ${$(n.searchText)} nvarchar(max), ${$(n.sourceDigest)} char(64), ${$(n.normalizerVersion)} varchar(64), ${$(n.authorName)} nvarchar(max), ${$(n.customerName)} nvarchar(max))) AS s ON t.${$(n.hubId)} = s.${$(n.hubId)}
8
+ WHEN MATCHED THEN UPDATE SET t.${$(n.searchText)} = s.${$(n.searchText)}, t.${$(n.sourceDigest)} = CONVERT(binary(32), s.${$(n.sourceDigest)}, 2), t.${$(n.normalizerVersion)} = s.${$(n.normalizerVersion)}, t.${$(n.authorName)} = s.${$(n.authorName)}, t.${$(n.customerName)} = s.${$(n.customerName)}, t.${$(n.indexedAt)} = SYSUTCDATETIME()
9
+ WHEN NOT MATCHED THEN INSERT (${$(n.hubId)}, ${$(n.searchText)}, ${$(n.sourceDigest)}, ${$(n.normalizerVersion)}, ${$(n.authorName)}, ${$(n.customerName)}) VALUES (s.${$(n.hubId)}, s.${$(n.searchText)}, CONVERT(binary(32), s.${$(n.sourceDigest)}, 2), s.${$(n.normalizerVersion)}, s.${$(n.authorName)}, s.${$(n.customerName)});
10
10
  DELETE FROM ${o} WHERE ${o.hubId} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${l}));
11
- INSERT INTO ${o} (${Y(o.hubId)}, ${Y(o.ordinal)}, ${Y(o.authorUserId)}, ${Y(o.commentText)}) SELECT ${Y(o.hubId)}, ${Y(o.ordinal)}, ${Y(o.authorUserId)}, ${Y(o.commentText)} FROM OPENJSON(${i}) WITH (${Y(o.hubId)} bigint, ${Y(o.ordinal)} int, ${Y(o.authorUserId)} bigint, ${Y(o.commentText)} nvarchar(max));`},qi=(e,t)=>B`SELECT ${Y(e.hubId)} AS ${B.identifier(we.hubId)}, LOWER(CONVERT(char(64), ${Y(e.sourceDigest)}, 2)) AS ${B.identifier(we.sourceDigest)}, ${Y(e.normalizerVersion)} AS ${B.identifier(we.normalizerVersion)} FROM ${e} WHERE ${e.hubId} IN (${Qt(t)})`,Yi=(e,t,r)=>B`SELECT TOP (${r}) ${Y(e.id)} AS ${B.identifier(we.hubId)} FROM ${e} WHERE ${e.id} > ${t} ORDER BY ${e.id}`;var ji=e=>({search:async(t,r)=>Ne(r.scope.visible)?[]:mt(await t.execute(Ui(e.tables,r.criteria,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=At(o[qe.sourceType],qe.sourceType);if(a===null)throw new Error(`[daily-report] search: column ${qe.sourceType} is null`);return{reportHubId:Dt(o[qe.reportHubId],qe.reportHubId),businessDate:At(o[qe.businessDate],qe.businessDate),sourceType:a}}),matchedSets:async(t,r)=>{if(Ne(r.scope.visible))return new Map;let n=mt(await t.execute($i(e.tables,r.plan,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames,r.ids))),o=2**r.plan.sets.length-1,a=new Map;for(let i of n){let l=i[Tt.matchedSets];if(!(typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&l<=o))throw new Error(`[daily-report] search: column ${Tt.matchedSets} holds no mask of ${r.plan.sets.length} keywords`);a.set(Dt(i[Tt.reportHubId],Tt.reportHubId),l)}return a},facetValues:async(t,r)=>Ne(r.scope.visible)?[]:mt(await t.execute(Bi(e.tables,r.column,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=At(o[Xt.value],Xt.value);if(a===null)throw new Error(`[daily-report] search: column ${Xt.value} is null`);return a})});import{chunk as Nr,MAX_IN_LIST as kr}from"@aiquants/mssql";import{sql as zi}from"drizzle-orm";import{createHash as Wd}from"crypto";var zd=Object.freeze({authorName:"author",customerName:"customer"}),Yn=e=>e===null?null:mn(e),Wi=(e,t,r)=>{let n=Yn(r);if(n!==null&&n.length>Ze.maxValueLength){let o=Ze.maxValueLength;throw new Error(`[daily-report] search index: report ${e}: the ${zd[t]} display value has ${n.length} UTF-16 units after trimming; the host must keep the author and customer display values at most ${o} UTF-16 units`)}return n},Zt=e=>e===null?"n;":`s${e.length}:${e}`,er="utf16le",Gd=e=>{let t=Wd("sha256");t.update(`F${e.fields.length};`,er);for(let[r,n]of e.fields)t.update(Zt(r)+Zt(n),er);return t.update(`C${e.comments.length};`,er),e.comments.forEach((r,n)=>{t.update(`${n};${r.authorUserId===null?"n":`i${r.authorUserId}`};${Zt(r.text)}`,er)}),t.update(`P;${Zt(Yn(e.filterValues.authorName))}${Zt(Yn(e.filterValues.customerName))}`,er),t.digest("hex")},jn=e=>{let t=0,r=[];for(let[,o]of e.fields){if(o===null)continue;let a=Ir(o);t+=a.forcedCuts,r.push(a.text)}let n=[];for(let o of e.comments){let a=Ir(o.text);t+=a.forcedCuts,a.text.length!==0&&n.push({ordinal:n.length,authorUserId:o.authorUserId,commentText:a.text})}return{hubId:e.hubId,searchText:ai(r),comments:n,sourceDigest:Gd(e),forcedCuts:t,authorName:Wi(e.hubId,"authorName",e.filterValues.authorName),customerName:Wi(e.hubId,"customerName",e.filterValues.customerName)}};var Gi=e=>{let t=async(c,s)=>{let m=[];for(let u of Nr(s,kr))for(let f of mt(await c.execute(Fi(e.hub,u))))m.push(Dt(f[we.hubId],we.hubId));return m},r=async(c,s)=>{for(let m of Nr(s,kr))await c.execute(Vi(e.tables,m,e.normalizerVersion))},n=async(c,s)=>{let m=new Map;for(let u of Nr(s,kr))for(let f of mt(await c.execute(qi(e.tables.document,u))))m.set(Dt(f[we.hubId],we.hubId),{sourceDigest:At(f[we.sourceDigest],we.sourceDigest),normalizerVersion:At(f[we.normalizerVersion],we.normalizerVersion)});return m},o=async(c,s,m)=>mt(await c.execute(Yi(e.hub,s,m))).map(u=>Dt(u[we.hubId],we.hubId)),a=async(c,s)=>{let m=await t(c,[...new Set(s)].sort((f,h)=>f-h));if(m.length===0)return;let u=(await e.loadSources(c,m)).map(jn);u.length>0&&await r(c,u)},i=c=>e.inTransaction(async s=>{await s.execute(zi`SET DEADLOCK_PRIORITY LOW`);let m=await t(s,c),u=await n(s,m),f=(await e.loadSources(s,m)).map(jn),h=f.filter(R=>{let b=u.get(R.hubId);return b===void 0||b.sourceDigest!==R.sourceDigest||b.normalizerVersion!==e.normalizerVersion});return h.length>0&&await r(s,h),await s.execute(zi`SET DEADLOCK_PRIORITY NORMAL`),{scanned:f.length,written:h.length,forcedCuts:f.reduce((R,b)=>R+b.forcedCuts,0)}});return{writeHubs:a,reconcile:async(c,s)=>{let{batchSize:m,hubIds:u,signal:f,onProgress:h}=s;te("reconcileSearchIndex: batchSize",m,1,kr);let R=ue(),b=u===void 0?null:Nr([...new Set(u)].sort((A,x)=>A-x),m),S={scanned:0,written:0,skipped:0,forcedCuts:0,lastHubId:null};for(let A=0;;A++){f?.throwIfAborted();let x=b===null?await o(c,S.lastHubId===null?0:S.lastHubId,m):b[A];if(x===void 0||x.length===0)break;let F=await i(x);S={scanned:S.scanned+F.scanned,written:S.written+F.written,skipped:S.skipped+F.scanned-F.written,forcedCuts:S.forcedCuts+F.forcedCuts,lastHubId:x[x.length-1]},h?.(S)}return{...S,elapsedMs:ue()-R}}}};import{holdsMultiUnitCluster as Kd}from"@aiquants/fuzzy-search/normalize";var Wn=255,vr=Object.values(ft).sort((e,t)=>e-t),Jd=new Intl.Segmenter("und",{granularity:"grapheme"}),De=Object.freeze({split:120,plan:200,normalize:900,map:2200,scan:2,run:700,segment:150,sweep:30,linear:6}),nt=5e5,Or=Math.floor(nt/De.linear),Qd=Math.floor(nt/De.segment),Ki=Math.floor(nt/De.sweep),Qi=Math.floor(nt/De.scan),Gn=Object.freeze({maxRanges:5e5,maxUnits:4e6,maxFieldRanges:1e4,sliceNs:8e6,sliceMs:5}),Xi=(e,t)=>{let r=0,n=t(),o=nt,a=!1;return{fits:i=>r===0?!0:r+i>e.sliceNs?!1:(r>=o&&(o=r+nt,a=t()-n>=e.sliceMs),!a),charge:i=>{r+=i},startSlice:()=>{r=0,n=t(),o=nt,a=!1}}},DR=Object.freeze({fits:()=>!0,charge:()=>{}}),Zi=e=>{let t=null;return{step:()=>{if(t!==null)return!0;let r=e.next();return r.done!==!0?!1:(t={result:r.value},!0)},result:()=>{if(t===null)throw new Error("[daily-report] search marks: the walk is not done (step until it returns true)");return t.result}}};var Xd=(e,t)=>{if(e.text!==t)throw new Error(`[daily-report] search marks: the position-mapped line (${e.text.length} units) differs from the index line (${t.length} units)`);return e},Zd=(e,t)=>e.chunks.length===1&&e.chunks[0].length===1&&e.chunks[0][0].start===0&&e.chunks[0][0].end===t.length;function*ep(e,t,r,n){let o=!1;for(let s=t;s<r&&!o;s+=Or){let m=Math.min(r,s+Or),u=(m-s)*De.linear;n.fits(u)||(yield),o=Kd(e.slice(s,m)),n.charge(u)}if(!o)return null;let a=new Int32Array(r-t),i=new Int32Array(r-t),l=Jd.segment(e.slice(t,r))[Symbol.iterator](),c=l.next();for(;!c.done;){let s=Math.max(Qd,c.value.segment.length);n.fits(s*De.segment)||(yield);let m=0;for(;!c.done&&m+c.value.segment.length<=s;){let{index:u,segment:f}=c.value;a.fill(t+u,u,u+f.length),i.fill(t+u+f.length,u,u+f.length),m+=f.length,c=l.next()}n.charge(m*De.segment)}return{start:t,clusterStarts:a,clusterEnds:i}}var tp=256,rp=e=>{let t=new Int32Array(e.length),r=0;for(let n=1;n<e.length;n++){for(;r>0&&e.charCodeAt(n)!==e.charCodeAt(r);)r=t[r-1];e.charCodeAt(n)===e.charCodeAt(r)&&r++,t[n]=r}return e.length-t[e.length-1]},np=e=>{let t=new Map;for(let r of e){if(r.text.length===0)throw new Error("[daily-report] search marks: an alternative has an empty text");let n=t.get(r.text);(n===void 0||r.tier<n)&&t.set(r.text,r.tier)}return[...t].map(([r,n])=>{let o=rp(r),a=Math.max(Qi-r.length+1,r.length);if(o===r.length)return{text:r,tier:n,periodic:null,windowStarts:a};let i=r.length%o,l=r.slice(i,o)+r.slice(0,i);return{text:r,tier:n,periodic:{period:o,continuation:l.repeat(Math.ceil(tp/o))},windowStarts:a}})},Fr=(e,t)=>{let{pieces:r}=e,n=r[e.lastPiece];if(n.plainStart<=t&&t<n.plainStart+n.text.length)return e.lastPiece;let o=0,a=r.length-1;for(;o<a;){let i=o+a+1>>1;r[i].plainStart<=t?o=i:a=i-1}return t>=r[o].plainStart+r[o].text.length?-1:(e.lastPiece=o,o)},Ji=(e,t,r)=>{let n=Fr(e,t);return e.pieces[n>=0?n:Fr(e,r==="start"?t-1:t+1)]},es=(e,t)=>{let r=Fr(e,t);if(r<0)return ts(e,t-1);let n=e.pieces[r];return n.start+n.mapped.start[t-n.plainStart]},ts=(e,t)=>{let r=Fr(e,t);if(r<0)return es(e,t+1);let n=e.pieces[r];return n.start+n.mapped.end[t-n.plainStart]},op=()=>({from:0,runStart:-1,last:0,periodicEnd:-1,window:"",windowStart:0,windowEnd:0,closedStart:0,closedEnd:-1}),ap=Object.freeze({kind:"done"}),zn=Object.freeze({kind:"slice"}),ip=Object.freeze({kind:"clusters"}),sp=(e,t,r,n,o,a)=>{let{plain:i}=e,{text:l,tier:c,periodic:s}=r;for(;;){if(n.closedEnd>=0){if(!o.fits(De.run))return zn;let h=Ji(e,n.closedStart,"start"),R=Ji(e,n.closedEnd-1,"end");if(h.mapped===null)return{kind:"map",piece:h};if(R.mapped===null)return{kind:"map",piece:R};if(e.isCut&&e.clusters===void 0)return ip;let b=t(e.offset+es(e,n.closedStart)),S=t(e.offset+ts(e,n.closedEnd-1)-1)+1;n.closedEnd=-1;let A=e.clusters;A==null?a(b,S,c):a(A.clusterStarts[b-A.start],A.clusterEnds[S-1-A.start],c),o.charge(De.run);continue}if(s!==null&&n.periodicEnd>=0){if(!o.fits(nt))return zn;let{period:h,continuation:R}=s,b=n.periodicEnd,S=Math.min(i.length,b+Math.max(Qi,R.length)),A=b;for(;A+R.length<=S&&i.startsWith(R,A);)A+=R.length;let x=A+R.length>S&&S<i.length;if(!x)for(;A<i.length&&i.charCodeAt(A)===i.charCodeAt(A-h);)A++;if(o.charge((A-b)*De.scan),x){n.periodicEnd=A;continue}n.periodicEnd=-1,n.last+=Math.floor((A-n.last-l.length)/h)*h,n.from=n.last+l.length-h+1;continue}if(n.from<0){if(n.runStart<0)return ap;n.closedStart=n.runStart,n.closedEnd=n.last+l.length,n.runStart=-1;continue}if(!o.fits(nt))return zn;n.from>=n.windowEnd&&(n.windowStart=n.from,n.windowEnd=n.from+r.windowStarts,n.window=i.slice(n.from,n.windowEnd+l.length-1));let m=n.from-n.windowStart,u=n.window.indexOf(l,m);if(u<0){o.charge((n.window.length-m)*De.scan),n.from=n.windowStart+n.window.length===i.length?-1:n.windowEnd;continue}o.charge((u+l.length-m)*De.scan);let f=n.windowStart+u;(n.runStart<0||f>=n.last+l.length)&&(n.runStart>=0&&(n.closedStart=n.runStart,n.closedEnd=n.last+l.length),n.runStart=f),n.last=f,s===null?n.from=f+1:n.periodicEnd=f+l.length}};function*lp(e,t,r,n,o){if(t.length===0)return;let a=e.length*De.split;n.fits(a)||(yield);let i=ti(e),l=[],c=[];Fn(i.text,(m,u)=>{l.push(u),c.push(u+m.length)}),n.charge(a);let s=m=>i.rawIndex===null?m:i.rawIndex[m];for(let m=0;m<l.length;m++){let u=l[m],f=i.text.slice(u,c[m]),h=f.length*De.plan;n.fits(h)||(yield);let R=wr(f,r);n.charge(h);let b=[],S="";for(let x of R.chunks){let F="",E=[];for(let D of x){let $=(D.end-D.start)*De.normalize;n.fits($)||(yield);let M=On(D.start===0&&D.end===f.length?f:f.slice(D.start,D.end),r).text;n.charge($),M.length>0&&E.push({start:D.start,end:D.end,text:M,chunkStart:F.length}),F+=M}if(F.length!==0){S.length>0&&(S+=" ");for(let D of E)b.push({start:D.start,end:D.end,text:D.text,plainStart:S.length+D.chunkStart,mapped:null});S+=F}}if(S.length===0)continue;let A={offset:u,plain:S,pieces:b,isCut:!Zd(R,f),lastPiece:0,clusters:void 0};for(let x of t){let F=op();for(;;){let E=sp(A,s,x,F,n,o);if(E.kind==="done")break;if(E.kind==="slice"){yield;continue}if(E.kind==="clusters"){A.clusters=yield*ep(e,s(u),s(u+f.length-1)+1,n);continue}let{piece:D}=E,$=(D.end-D.start)*De.map;n.fits($)||(yield);let M=f.slice(D.start,D.end);D.mapped=Xd(oi(M,wr(M,r)),D.text),n.charge($)}}}}function*cp(e,t,r,n){let o=new Int32Array(vr.length),a=0,i=Wn;for(let l=0;l<=e;l+=Ki){let c=Math.min(e+1,l+Ki),s=(c-l)*De.sweep;r.fits(s)||(yield);for(let m=l;m<c;m++){let u=Wn;for(let f=vr.length-1;f>=0;f--){let h=vr[f];o[h]+=t[h][m],o[h]>0&&(u=h)}if(u!==i){if(i!==Wn&&!n(a,m,i))return!1;a=m,i=u}}r.charge(s)}return!0}function*up(e,t,r,n,o){let a=null;return yield*lp(e,t,r,n,(l,c,s)=>{a===null&&(a=vr.map(()=>new Int32Array(e.length+1))),a[s][l]++,a[s][c]--}),a===null?!0:yield*cp(e.length,a,n,o)}var dp=(e,t,r,n)=>{let o=np(t),a=[],i=(c,s,m)=>(a.push(c,s,m),a.length<=3*r.maxRanges);return Zi(function*(){return(yield*up(e,o,r.maxLength,n,i))?{dense:!1,ranges:a}:{dense:!0}}())};var rs=(e,t)=>{if(e.combine==="intersection"||e.sets.length===1)return e.sets.flatMap(r=>r.words);if(t===null)throw new Error(`[daily-report] search marks: a union of ${e.sets.length} keywords needs the report's mask of matched keywords`);return e.sets.flatMap((r,n)=>(t&1<<n)===0?[]:r.words)},ns=e=>{let t=[],r=(n,o)=>{typeof o=="string"&&o.length>0&&t.push({key:n,value:o})};for(let n of ho)r(Xe.field(n),e[n]);e.interviewers.forEach((n,o)=>{r(Xe.interviewer(o,"name"),n.name),r(Xe.interviewer(o,"affiliation"),n.affiliation)}),e.attachments.forEach((n,o)=>{r(Xe.attachment(o),n.fileName)}),e.externalComments.forEach((n,o)=>{r(Xe.comment(Qr(o),"author"),n.name),r(Xe.comment(Qr(o),"content"),n.text)});for(let n of e.postedComments)r(Xe.comment(n.id,"author"),n.userName),r(Xe.comment(n.id,"content"),n.content);return t};function*pp(e,t){let r=en;for(let n=0;n<e.length;n+=Or){let o=Math.min(e.length,n+Or),a=(o-n)*De.linear;t.fits(a)||(yield),r=tn(r,e,n,o),t.charge(a)}return r}var os=async(e,t,r,n)=>{let o=0,a=0,i=async s=>{for(;!s.step();)await r(),n.startSlice();return s.result()},l=async(s,m)=>{if(!m&&a>t.maxRanges)return null;let u={};for(let{key:f,value:h}of s.fields){if(!m&&o+h.length>t.maxUnits)return null;let R=await i(Zi(pp(h,n))),b=await i(dp(h,s.alternatives,{maxLength:kn,maxRanges:t.maxFieldRanges},n));if(o+=h.length,b.dense){u[f]={fingerprint:R,dense:!0};continue}if(u[f]={fingerprint:R,ranges:b.ranges},a+=b.ranges.length/3,!m&&a>t.maxRanges)return null}return u},c=[];for(let s=0;s<e.length;s++){let m=e[s],u=await l(m,c.length===0);if(u===null)return{reports:c,deferred:e.slice(s).map(f=>f.reportHubId)};c.push({reportHubId:m.reportHubId,matchedSets:m.matchedSets,fields:u})}return{reports:c,deferred:[]}};var at=e=>Rp(e),as=ar([]),xe=(e,t)=>{if(!e)return null;let r=e instanceof Date?e:new Date(e);if(Number.isNaN(r.getTime()))return typeof e=="string"?e:null;let n=r.getFullYear(),o=n<0?`-${String(-n).padStart(4,"0")}`:String(n).padStart(4,"0"),a=String(r.getMonth()+1).padStart(2,"0"),i=String(r.getDate()).padStart(2,"0");if(t==="YYYY-MM-DD")return`${o}-${a}-${i}`;let l=String(r.getHours()).padStart(2,"0"),c=String(r.getMinutes()).padStart(2,"0"),s=String(r.getSeconds()).padStart(2,"0");return`${o}-${a}-${i} ${l}:${c}:${s}`},Sp=e=>{let{length:t}=e;if(t===void 0)throw ne("tables.hub.title","a character column with a declared length",t);return te("tables.hub.title.length",t,1)},is=e=>e===""?null:e,gp=Object.freeze([]),Jn=(e,t,r)=>{let n=e.get(t);n?n.push(r):e.set(t,[r])},Hr=(e,t)=>e.get(t)??gp,ss=(e,t)=>[e,t].filter(r=>typeof r=="string"&&r.length>0).join(Er),bp=e=>{if(!Array.isArray(e)||e.length===0||e.some(t=>typeof t!="string"||t.trim().length===0)||new Set(e).size!==e.length)throw ne("draftLabelNames","one or more non-blank label names",e);return Object.freeze([...e])},Dp=(e,t)=>{let r="the request's AbortSignal (new AbortController().signal for a call that is never aborted)";if(t===void 0)throw Qe(`${e}: options.signal`,r);if(typeof t!="object"||t===null)throw ne(`${e}: options`,"an object carrying the request's AbortSignal",t);let{signal:n}=t;if(n===void 0)throw Qe(`${e}: options.signal`,r);if(!(n instanceof AbortSignal))throw ne(`${e}: options.signal`,r,n);return n},Ap=e=>{let t=new Set;return e.filter(r=>{let n=r.toLowerCase();return t.has(n)?!1:(t.add(n),!0)})};function Qn(e){let{db:t,tables:r,userTable:n,resolveUserId:o,encodeUserId:a,redis:i,cache:l,epochs:c}=e,{hub:s,internal:m,comment:u,label:f,hubLabel:h,userStatus:R}=r,b=e.externalSources??[],S=bp(e.draftLabelNames),A=S[0],x=Se(e.logger,1,"Service");Sr(e);let F=La(e.attachments),E=Sp(s.title),D=d=>fp(p=>t.transaction(y=>p(()=>d(y))),e.transactionRetry),$=e.search===void 0?null:vi(e.search,b.map(d=>d.sourceType)),M={hub:s,hubLabel:h,label:f},H=$===null?null:ji({tables:{...M,search:$.tables},draftLabelNames:S});$!==null&&Hn();let de=null,pe=async()=>{if($===null)return null;if(de===null){let d=await Hn(),p=$.externalSourceTexts;de=Gi({hub:s,tables:$.tables,loadSources:(y,g)=>js(y,g,p),inTransaction:D,normalizerVersion:d})}return de},ge=e.idsTtlMs??18e4,G="daily-report:ids:epoch",se=e.businessDateTtlMs??3e5,re="daily-report:date-epoch:",ce="daily-report:detail-epoch:",he=`${e.streamKey??"daily-report:sse-stream"}:v3`,Ke=e.streamMaxLen??1e4,oe=d=>c.incrementEpoch(d),ke=d=>qt(s.sourceType,d),Ue=(d,p)=>Lr(M,d,S,p),it=Kn`CASE WHEN ${Pr(M,S)} THEN 1 ELSE 0 END`,st=async d=>{let[p]=await t.select({id:s.id}).top(1).from(s).where(Ae(V(s.id,d),Pr(M,S)));return p!==void 0},Ee=async(d,p)=>{let y=await i?.getClient();if(!y){x.warn(`[SSE] Redis client unavailable (${p})`);return}let g=JSON.stringify(d),w=Buffer.byteLength(g);if(w>6356992){x.warn(`[SSE] Event too large (${p}): ${w} bytes > ${6356992}; not published`);return}let _=ue();try{await y.xAdd(he,"*",{data:g},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:Ke}});let I=ue()-_;I>1e3&&x.warn(`[SSE] Slow publish (${p}): ${I}ms`)}catch(I){x.error(`[SSE] Redis publish failed (${p}):`,I)}},T=async()=>{try{let d=await i?.getClient();if(d===void 0)return null;let[p]=await d.xRevRange(he,"+","-",{COUNT:1});return p===void 0?null:p.id}catch(d){return x.error("SSE stream anchor read failed",d),null}},O=d=>d==null||d===""?null:/^\d+$/.test(d)?a(Number(d)):d,N=()=>{let d={};for(let p of b)d[`ext_${p.sourceType}`]=at(p.table);return d},P=d=>{let p=d;for(let y of b)p=p.leftJoin(y.table,Ae(V(s.sourceType,y.sourceType),V(s.sourceIdNum,y.idColumn)));return p},U=d=>{let{hub:p,internal:y}=d,g=p.summary,w=[],_=null,I=null,v=null,L=null,q=null,Q=null,J=[],j=b.find(ee=>ee.sourceType===p.sourceType),Z=j?d[`ext_${j.sourceType}`]:void 0;if(j&&Z){let ee=j.mapRow(Z);ee.content!==void 0&&(g=ee.content),ee.employeeName!==void 0&&(Q=ee.employeeName),ee.category!==void 0&&(_=ee.category),ee.creationCategory!==void 0&&(I=ee.creationCategory),ee.visitTimeFrom!==void 0&&(v=ee.visitTimeFrom),ee.visitTimeTo!==void 0&&(L=ee.visitTimeTo),ee.customerName!==void 0&&(q=ee.customerName),ee.interviewers!==void 0&&(w=ee.interviewers),ee.externalComments!==void 0&&(J=ee.externalComments)}else p.sourceType==="Internal"&&y&&(g=y.body);return{content:g,author:d.creatorName??O(p.createdBy)??"",employeeName:Q??d.creatorName??O(p.createdBy),updatedBy:O(p.updatedBy),category:_,creationCategory:I,visitTimeFrom:v,visitTimeTo:L,customerName:q,interviewers:w,externalComments:J}},W=d=>{if(d===1)return!0;if(d===0)return!1;throw new Error(`[daily-report] a detail row's hasDraftLabel must be 1 or 0 (the read must select draftLabelFlag); got ${zr(d)}`)},K=d=>d.creationCategory!==null&&S.includes(d.creationCategory),z=(d,p)=>W(d.hasDraftLabel)?!0:K(p),X=d=>d.some(K)?eo():Promise.resolve(null),k=(d,p,y,g,w)=>{let{hub:_}=p,I=(p.labels??[]).map(q=>({id:q.id,name:q.name,color:q.color})),v=p.postedCommentRows??[],L=Le(d.commentable,_.sourceType);return g!==null&&K(y)&&!I.some(q=>q.id===g)&&I.push({id:g,name:A,color:null}),{reportHubId:_.id,date:xe(_.businessDate,"YYYY-MM-DD"),author:y.author,userId:_.userId?a(_.userId):"",sourceType:_.sourceType??"Internal",createdAt:xe(_.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:xe(_.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:y.updatedBy,employeeName:y.employeeName,category:y.category,creationCategory:y.creationCategory,visitTimeFrom:y.visitTimeFrom,visitTimeTo:y.visitTimeTo,customerName:y.customerName,interviewers:y.interviewers,subject:_.title,content:y.content,externalComments:L?y.externalComments:[],isRead:p.isRead??!1,isStarred:p.isStarred??!1,isDraft:z(p,y),labels:I,postedComments:v.filter(q=>Qa({authorUserId:q.userId},_.sourceType,w??null,d)).map(q=>({...q,userId:a(q.userId),isMine:w?q.userId===w:!1})),attachments:p.attachments}},ae=async(d,p)=>(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).from(s).where(Ae(kt(s.deletedAt),Ue(p,"author-or-authorless"),ke(d.visible))).orderBy(Nt(s.businessDate),Nt(s.id))).map(g=>({...g,businessDate:xe(g.businessDate,"YYYY-MM-DD")})),fe=async(d,p,y)=>{let g=await wt(p);return g?Ne(d.visible)?[]:(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).top(y).from(s).where(Ae(kt(s.deletedAt),Ue(g,"author-or-authorless"),ke(d.visible))).orderBy(Nt(s.businessDate),Nt(s.id))).map(_=>({..._,businessDate:xe(_.businessDate,"YYYY-MM-DD")})):[]},ye=async(d,p)=>{let y=await P(t.select({hub:at(s),internal:at(m),creatorName:n.displayName,hasDraftLabel:it,...N()}).from(s)).leftJoin(m,V(s.id,m.hubId)).leftJoin(n,V(s.userId,n.id)).where(Ae(V(s.businessDate,Kn`${p}`),kt(s.deletedAt),ke(d.visible))).orderBy(Nt(s.id)),g=await rr(y.map(I=>I.hub.id)),w=y.map(U),_=await X(w);return y.map((I,v)=>k(d,{...I,attachments:g.get(I.hub.id)??[]},w[v],_))},tr=new Map,wt=async d=>{if(!e.disableUserIdCache&&tr.has(d))return tr.get(d)??null;let p=await o(d);return p!==null&&!e.disableUserIdCache&&tr.set(d,p),p},_s=async(d,p,{forceRefresh:y=!1,snapshot:g=!1,ttlMsOverride:w,onFetchStart:_,admission:I}={})=>{let v=await wt(p);if(!v)return{items:[],streamAnchor:null,snapshot:as};if(Ne(d.visible))return{items:[],streamAnchor:await T(),snapshot:as};let L=mi(v,Yt(d)),[q]=await l.getOrFetch({cacheKey:L,fetcher:async()=>{let Q=await T(),J=await ae(d,v);if(!uo(J)){x.warn("ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)");let j=[...J].sort(Jr);return[{items:j,streamAnchor:Q,snapshot:ar(j)}]}return[{items:J,streamAnchor:Q,snapshot:ar(J)}]},onFetchStart:_,forceRefresh:y,snapshot:g,admission:I,ttlMsOverride:w??ge,epochKey:G,refreshAheadRatio:.5});if(q===void 0)throw new Error("[daily-report] getDailyReportIdsByExternalId: the ids cache returned no record");return q},xs=(d,p,{forceRefresh:y=!1,snapshot:g=!1,ttlMsOverride:w}={})=>{let _=ve(p);return _?Ne(d.visible)?Promise.resolve([]):l.getOrFetch({cacheKey:yi(_,Yt(d)),fetcher:()=>ye(d,_),forceRefresh:y,snapshot:g,ttlMsOverride:w??se}):Promise.resolve([])},Zn=async d=>{let[p]=await d.select({id:f.id}).top(1).from(f).where(V(f.name,A)).orderBy(Ce(f.id));return p===void 0?null:p.id},eo=()=>Zn(t),Cs=(d,p)=>p!=null?"absent":d!=null?"present":"unknown",rr=async d=>{let p=new Map,y=r.attachment;if(d.length===0||!y||F===null)return p;let g=F.idCodec,w=F.thumbnails!==null,_=await t.select({id:y.id,hubId:y.hubId,fileName:y.fileName,fileType:y.fileType,fileSize:y.fileSize,createdAt:y.createdAt,objectCheckedAt:y.objectCheckedAt,objectMissingAt:y.objectMissingAt}).from(y).where(ot(y.hubId,d)).orderBy(Ce(y.createdAt),Ce(y.id));for(let I of _){let v=I.fileType?String(I.fileType):null,L=I.fileSize!=null?Number(I.fileSize):null,q=Cs(I.objectCheckedAt,I.objectMissingAt),Q={id:g.encode(Number(I.id)),fileName:String(I.fileName),fileType:v,fileSize:L,createdAt:xe(I.createdAt,"YYYY-MM-DD HH:mm:ss"),state:q,hasThumbnail:w&&q!=="absent"&&fr({fileType:v,fileSize:L},F.maxBytes)},J=p.get(Number(I.hubId));J?J.push(Q):p.set(Number(I.hubId),[Q])}return p},Ms=async(d,p,y)=>{let g=r.attachment;return!g||Ne(d.visible)?null:(await t.select({fileName:g.fileName,filePath:g.filePath,fileType:g.fileType,fileSize:g.fileSize}).top(1).from(g).innerJoin(s,V(s.id,g.hubId)).where(Ae(V(g.id,p),kt(s.deletedAt),Ue(y,"author"),ke(d.visible))))[0]??null},Ps=async d=>{let p=r.attachment;if(!p)return;let y=new Date;try{await t.update(p).set({objectCheckedAt:y,objectMissingAt:y,updatedAt:y}).where(V(p.id,d))}catch(g){x.error("markAttachmentMissing failed",g)}},Ls=async d=>{let p=r.attachment;if(!p)return;let y=new Date;try{await t.update(p).set({objectCheckedAt:y,objectMissingAt:null,updatedAt:y}).where(V(p.id,d))}catch(g){x.error("markAttachmentPresent failed",g)}},Br=async(d,p,y)=>{let g=await P(t.select({hub:at(s),internal:at(m),isRead:R.isRead,isStarred:R.isStarred,creatorName:n.displayName,hasDraftLabel:it,...N()}).from(s)).leftJoin(m,V(s.id,m.hubId)).leftJoin(R,Ae(V(s.id,R.hubId),V(R.userId,p))).leftJoin(n,V(s.userId,n.id)).where(Ae(y,kt(s.deletedAt),Ue(p,"author"),ke(d.visible))).orderBy(Nt(s.id));if(g.length===0)return[];let w=g.map(j=>j.hub.id),_=await t.select({hubId:h.hubId,id:f.id,name:f.name,color:f.color}).from(h).innerJoin(f,V(h.labelId,f.id)).where(ot(h.hubId,w)),I=await t.select({hubId:u.hubId,id:u.id,body:u.body,createdAt:u.createdAt,userId:u.userId,userName:n.displayName}).from(u).leftJoin(n,V(u.userId,n.id)).where(ot(u.hubId,w)).orderBy(Ce(u.createdAt)),v=await rr(w),L=new Map,q=new Map;for(let j of _){let Z=L.get(j.hubId);Z||(Z=[],L.set(j.hubId,Z)),Z.push({id:j.id,name:j.name,color:j.color})}for(let j of I){let Z=q.get(j.hubId);Z||(Z=[],q.set(j.hubId,Z)),Z.push({id:j.id,content:j.body,createdAt:xe(j.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:j.userId,userName:j.userName||""})}let Q=g.map(U),J=await X(Q);return g.map((j,Z)=>{let ee=j.hub.id;return k(d,{...j,attachments:v.get(ee)??[],labels:L.get(ee)||[],postedCommentRows:q.get(ee)||[]},Q[Z],J,p)})},Ns=async(d,p,y,{forceRefresh:g=!1,snapshot:w=!1,ttlMsOverride:_,admission:I}={})=>{let v=await wt(y);if(!v)return[];let L=ve(p);if(!L)return[];if(Ne(d.visible))return[];let q=hi(L,v,Yt(d));return l.getOrFetch({cacheKey:q,fetcher:()=>Br(d,v,V(s.businessDate,Kn`${L}`)),forceRefresh:g,snapshot:w,admission:I,ttlMsOverride:_??se,epochKey:`${re}${L}`})},vt=async(d,p,y,{forceRefresh:g=!1,snapshot:w=!1,ttlMsOverride:_,admission:I}={})=>{if(Ne(d.visible))return null;let v=fi(p,y,Yt(d));return(await l.getOrFetch({cacheKey:v,fetcher:async()=>{let q=await P(t.select({hub:at(s),internal:at(m),isRead:R.isRead,isStarred:R.isStarred,creatorName:n.displayName,hasDraftLabel:it,...N()}).from(s)).leftJoin(m,V(s.id,m.hubId)).leftJoin(R,Ae(V(s.id,R.hubId),V(R.userId,y))).leftJoin(n,V(s.userId,n.id)).where(Ae(V(s.id,p),kt(s.deletedAt),Ue(y,"author"),ke(d.visible)));if(q.length===0)return[];let Q=q[0].hub.id,J=await t.select({id:f.id,name:f.name,color:f.color}).from(h).innerJoin(f,V(h.labelId,f.id)).where(V(h.hubId,Q)),j=await t.select({id:u.id,body:u.body,createdAt:u.createdAt,userId:u.userId,userName:n.displayName}).from(u).leftJoin(n,V(u.userId,n.id)).where(V(u.hubId,Q)).orderBy(Ce(u.createdAt)),Z=await rr([Q]),ee=J.map(Je=>({id:Je.id,name:Je.name,color:Je.color})),Yr=j.map(Je=>({id:Je.id,content:Je.body,createdAt:xe(Je.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:Je.userId,userName:Je.userName||""})),oo=U(q[0]),nl=await X([oo]);return[k(d,{...q[0],attachments:Z.get(Q)??[],labels:ee,postedCommentRows:Yr},oo,nl,y)]},forceRefresh:g,snapshot:w,admission:I,ttlMsOverride:_??se,epochKey:`${ce}${p}`}))[0]??null},ks=async(d,p,y,g={})=>{let w=await wt(y);return w?vt(d,p,w,g):null},vs=async(d,p,y)=>{if(p.length>_e.maxDetailIds)throw ne("getDailyReportDetailsByIdsByExternalId: reportHubIds",`at most ${_e.maxDetailIds} ids`,p.length);let g=await wt(y);return!g||p.length===0?[]:Ne(d.visible)?[]:Br(d,g,ot(s.id,[...p]))},Os=async(d,p)=>{let[y]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt}).top(1).from(s).where(Ae(V(s.id,d),Ue(p,"author")));return y??null},Vr=async(d,p,y)=>{let g=await Os(p,y);if(!g||g.deletedAt||!Le(d.visible,g.sourceType))throw new Error("Not Found")},Fs=async(d,p,y,g,w,_)=>{await Vr(d,y,p);let I=await t.select().top(1).from(R).where(Ae(V(R.hubId,y),V(R.userId,p))),v;if(I.length>0?I[0].isStarred!==w?v=(await t.update(R).set({isStarred:w,updatedAt:new Date,updatedBy:String(p)}).output().where(Ae(V(R.hubId,y),V(R.userId,p))))[0]:v=I[0]:v=(await t.insert(R).output().values({hubId:y,userId:p,isStarred:w,isRead:!1,createdAt:new Date,createdBy:String(p),updatedAt:new Date,updatedBy:String(p)}))[0],g){let L=ve(g);L&&(l.invalidatePrefix(Lt(L,p)),await oe(`${re}${L}`))}return l.invalidatePrefix(Cr(y,p)),await oe(`${ce}${y}`),await Ee(cr.parse({type:"status-update",reportHubId:y,recipientRawUserId:p,statusType:"star",value:w,clientTempId:_}),"setStarStatus"),v},Hs=async(d,p,y,g,w,_)=>{await Vr(d,y,p);let I=await t.select().top(1).from(R).where(Ae(V(R.hubId,y),V(R.userId,p))),v;if(I.length>0?I[0].isRead!==w?v=(await t.update(R).set({isRead:w,updatedAt:new Date,updatedBy:String(p)}).output().where(Ae(V(R.hubId,y),V(R.userId,p))))[0]:v=I[0]:v=(await t.insert(R).output().values({hubId:y,userId:p,isRead:w,isStarred:!1,createdAt:new Date,createdBy:String(p),updatedAt:new Date,updatedBy:String(p)}))[0],g){let L=ve(g);L&&(l.invalidatePrefix(Lt(L,p)),await oe(`${re}${L}`))}return l.invalidatePrefix(Cr(y,p)),await oe(`${ce}${y}`),await Ee(cr.parse({type:"status-update",reportHubId:y,recipientRawUserId:p,statusType:"read",value:w,clientTempId:_}),"setReadStatus"),v},to=async(d,p)=>{if(p!==null)return await st(d)?p:void 0},Us=async(d,p,y,g,w,_)=>{let[I]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt,userId:s.userId}).top(1).from(s).where(V(s.id,y));if(!I||I.deletedAt)throw new Error("Not Found");if(await Vr(d,y,p),!Le(d.commentable,I.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(I.sourceType.toLowerCase()!=="internal")throw new Error("Comments are restricted for external daily report sources");let v=await to(y,I.userId),L=await pe(),q=await D(async Z=>{let[ee]=await Z.insert(u).output().values({hubId:y,userId:p,body:g,createdAt:new Date,createdBy:String(p),updatedAt:new Date,updatedBy:String(p)});return L!==null&&await L.writeHubs(Z,[y]),ee}),[Q]=await t.select({displayName:n.displayName}).top(1).from(n).where(V(n.id,p)),J=Q?.displayName??"";if(w){let Z=ve(w);Z&&(l.invalidatePrefix(Kt(Z)),await oe(`${re}${Z}`))}l.invalidatePrefix(Ge(y)),await oe(`${ce}${y}`);let j={id:q.id,userId:a(q.userId),userName:J,content:q.body,createdAt:xe(q.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await Ee(sn.parse({type:"comment-add",reportHubId:y,comment:j,clientTempId:_,recipientRawUserId:v,sourceType:I.sourceType}),"addComment"),j},$s=async(d,p)=>await d.select().top(1).from(u).where(V(u.id,p)),Bs=async(d,p,y,g,w,_)=>{let I=await $s(t,g);if(I.length===0)throw new Error("Not Found");if(I[0].hubId!==y)throw new Error("Not Found");let[v]=await t.select({userId:s.userId,sourceType:s.sourceType}).top(1).from(s).where(V(s.id,I[0].hubId));if(!(v&&Le(d.visible,v.sourceType)))throw new Error("Not Found");if(I[0].userId!==p)throw new Error("Unauthorized");let L=await to(y,v.userId),q=await pe();if(await D(async Q=>{await Q.delete(u).where(V(u.id,g)),q!==null&&await q.writeHubs(Q,[y])}),w){let Q=ve(w);Q&&(l.invalidatePrefix(Kt(Q)),await oe(`${re}${Q}`))}l.invalidatePrefix(Ge(y)),await oe(`${ce}${y}`),await Ee(ln.parse({type:"comment-delete",reportHubId:y,commentId:g,clientTempId:_,recipientRawUserId:L,sourceType:v?.sourceType}),"deleteComment")},Vs=async(d,p)=>{let y=new Map,g=r.attachment;if(!g||F===null)return y;let w=await d.select({hubId:g.hubId,fileName:g.fileName}).from(g).where(ot(g.hubId,[...p])).orderBy(Ce(g.hubId),Ce(g.createdAt),Ce(g.id));for(let _ of w)Jn(y,Number(_.hubId),String(_.fileName));return y},qs=async(d,p,y)=>{let g=new Map;for(let[w,_]of y){let I=new Map;for(let{hub:L}of p)L.sourceType===w&&L.sourceIdNum!==null&&I.set(L.sourceIdNum,L.id);if(I.size===0)continue;let v=await _(d,[...I.keys()]);for(let[L,q]of v){let Q=I.get(L);if(Q===void 0)throw ne(`search.externalSourceTexts.${w} answer key`,"a source id that was asked for",L);if(!(Array.isArray(q)&&q.every(J=>typeof J=="string")))throw ne(`search.externalSourceTexts.${w} answer for ${L}`,"an array of strings",q);g.set(Q,q)}}return g},Ys=(d,p)=>{let y=U(d),g=[["subject",d.hub.title],["content",y.content],["author",y.author],["employeeName",y.employeeName],["updatedBy",y.updatedBy],["category",y.category],["creationCategory",y.creationCategory],["customerName",y.customerName]];for(let _ of y.interviewers)g.push(["interviewerName",_.name??null],["interviewerAffiliation",_.affiliation??null]);for(let _ of p.labelNames)g.push(["label",_]);for(let _ of p.attachmentNames)g.push(["attachment",_]);for(let _ of p.extraTexts)g.push(["extra",_]);let w=[];for(let _ of y.externalComments)w.push({authorUserId:null,text:ss(_.name,_.text)});for(let _ of p.postedComments)w.push({authorUserId:_.userId,text:ss(_.userName,_.body)});return{hubId:d.hub.id,fields:g,comments:w,filterValues:{authorName:y.employeeName,customerName:y.customerName}}},js=async(d,p,y)=>{let g=[];for(let w of yp(p,hp)){let _=await P(d.select({hub:at(s),internal:at(m),creatorName:n.displayName,...N()}).from(s)).leftJoin(m,V(s.id,m.hubId)).leftJoin(n,V(s.userId,n.id)).where(ot(s.id,[...w])).orderBy(Ce(s.id)),I=new Map,v=await d.select({hubId:h.hubId,name:f.name}).from(h).innerJoin(f,V(h.labelId,f.id)).where(ot(h.hubId,[...w])).orderBy(Ce(h.hubId),Ce(f.id));for(let j of v)Jn(I,j.hubId,j.name);let L=new Map,q=await d.select({hubId:u.hubId,userId:u.userId,body:u.body,userName:n.displayName}).from(u).leftJoin(n,V(u.userId,n.id)).where(ot(u.hubId,[...w])).orderBy(Ce(u.hubId),Ce(u.createdAt),Ce(u.id));for(let j of q)Jn(L,j.hubId,j);let Q=await Vs(d,w),J=await qs(d,_,y);for(let j of _){let Z=j.hub.id;g.push(Ys(j,{labelNames:Hr(I,Z),postedComments:Hr(L,Z),attachmentNames:Hr(Q,Z),extraTexts:Hr(J,Z)}))}}return g},Ws=(d,p,y)=>H===null?Promise.reject(new Error("[daily-report] searchDailyReports: the search setting is not configured")):H.search(t,{criteria:y,viewerUserId:p,scope:d}),ro=Object.freeze(Ap(["Internal",...b.map(d=>d.sourceType)])),zs=async(d,p)=>{if(H===null)throw new Error("[daily-report] listDailyReportSearchFacets: the search setting is not configured");let y=ro.filter(_=>Le(d.visible,_)),g=await H.facetValues(t,{column:"authorName",viewerUserId:p,scope:d}),w=await H.facetValues(t,{column:"customerName",viewerUserId:p,scope:d});return{sourceTypes:y,authors:g,customers:w}},Gs=async(d,p,y,g,w)=>{let _=Dp("markDailyReportSearchHits",w);if(H===null)throw new Error("[daily-report] markDailyReportSearchHits: the search setting is not configured");if(g.length>_e.maxDetailIds)throw ne("markDailyReportSearchHits: reportHubIds",`at most ${_e.maxDetailIds} ids`,g.length);let I=ir(Wt(y));if(g.length===0||Ne(d.visible))return{wordsDigest:I,reports:[],deferred:[]};_.throwIfAborted();let v=await Br(d,p,ot(s.id,[...g]));_.throwIfAborted();let L=y.combine==="union"&&y.sets.length>=2&&v.length>0?await H.matchedSets(t,{plan:y,viewerUserId:p,scope:d,ids:v.map(j=>j.reportHubId)}):null,q=v.map(j=>{let Z=L===null?null:L.get(j.reportHubId),ee=Z===void 0?0:Z;return{reportHubId:j.reportHubId,matchedSets:ee,alternatives:rs(y,ee).flatMap(Yr=>Yr.alternatives),fields:ns(j)}}),J=await os(q,Gn,async()=>{await new Promise(j=>setImmediate(j)),_.throwIfAborted()},Xi(Gn,ue));return{wordsDigest:I,reports:J.reports,deferred:J.deferred}},Ks=async d=>{let p=await pe();if(p===null)throw new Error("[daily-report] reconcileSearchIndex: the search setting is not configured");return p.reconcile(t,d)},Js=async(d,p,y)=>{if(!or(p))throw ne("createDailyReport: businessDate","a business-date key in the canonical form YYYY-MM-DD naming a day from 0001-01-01 to 9999-12-31",p);x.info("createDailyReport called",{userId:d,businessDate:p});let[g]=await t.select({displayName:n.displayName}).from(n).where(V(n.id,d)),w=g?.displayName??a(d),_=await pe();try{let I=await D(async L=>{x.info("Starting transaction");let q=await Zn(L);if(q===null)throw new Error(`[daily-report] createDailyReport: the canonical draft label ${JSON.stringify(A)} (draftLabelNames[0]) does not exist; create that label before creating reports (a report without it would be visible to every viewer)`);let Q=`internal-temp-${Date.now()}-${Math.random()}`,[J]=await L.insert(s).output().values({sourceType:"Internal",sourceId:Q,businessDate:new Date(`${p}T00:00:00Z`),userId:d,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(d),updatedAt:new Date,updatedBy:String(d)});await L.update(s).set({sourceId:String(J.id)}).where(V(s.id,J.id)),x.info("Hub created",J),await L.insert(m).values({hubId:J.id,body:"",createdAt:new Date,createdBy:String(d),updatedAt:new Date,updatedBy:String(d)}),x.info("Internal created"),await L.insert(h).values({hubId:J.id,labelId:q,createdAt:new Date,createdBy:String(d)});let j=[{id:q,name:A,color:null}];return x.info("Label assigned"),_!==null&&await _.writeHubs(L,[J.id]),{reportHubId:J.id,date:p,createdAt:xe(J.createdAt,"YYYY-MM-DD HH:mm:ss"),author:w,userId:a(d),sourceType:"Internal",employeeName:w,updatedBy:a(d),updatedAt:xe(J.updatedAt,"YYYY-MM-DD HH:mm:ss"),category:null,creationCategory:null,visitTimeFrom:null,visitTimeTo:null,customerName:null,interviewers:[],subject:J.title,content:"",externalComments:[],isRead:!0,isStarred:!1,isDraft:!0,labels:j,postedComments:[],attachments:[]}});l.invalidatePrefix(Lt(p,d)),l.invalidatePrefix(bt),l.invalidatePrefix(Un(d)),await oe(G),await oe(`${re}${p}`);let v=await vt(He.unrestricted("post-write self read: the writer always sees the row they just wrote"),I.reportHubId,d,{forceRefresh:!0});if(v){let L=await st(v.reportHubId);await Ee(cn.parse({type:"report-create",reportHubId:v.reportHubId,report:v,clientTempId:y,recipientRawUserId:L?d:void 0}),"createDailyReport")}return v??I}catch(I){throw x.error("Error in createDailyReport",I),I}},nr=async(d,p)=>await d.select().top(1).from(s).where(V(s.id,p)),qr=async(d,p,y)=>{await d.update(s).set(y).where(V(s.id,p))},no=async(d,p,y)=>{await d.update(m).set(y).where(V(m.hubId,p))},Qs=async(d,p,y)=>{await d.delete(h).where(Ae(V(h.hubId,p),V(h.labelId,y)))},Xs=async(d,p,y)=>{let g=await nr(t,d);if(!g.length||g[0].deletedAt)throw new Error("Not Found");if(g[0].userId!==p)throw new Error("Unauthorized");if(await D(async w=>{await qr(w,d,{deletedAt:new Date,deletedBy:String(p),updatedAt:new Date,updatedBy:String(p)})}),l.invalidatePrefix(Ge(d)),l.invalidatePrefix(bt),l.invalidatePrefix(gt),await oe(G),g[0].businessDate){let w=ve(xe(g[0].businessDate,"YYYY-MM-DD"));w&&await oe(`${re}${w}`)}await Ee(pn.parse({type:"report-delete",reportHubId:d,clientTempId:y,sourceType:g[0].sourceType}),"deleteDailyReport")},Zs=async(d,p,y,g)=>{let w=await nr(t,d);if(!w.length||w[0].deletedAt)throw new Error("Not Found");if(w[0].userId!==p)throw new Error("Unauthorized");let _=await pe();await D(async L=>{y.title!==void 0&&await qr(L,d,{title:is(y.title),updatedAt:new Date,updatedBy:String(p)}),y.content!==void 0&&await no(L,d,{body:is(y.content),updatedAt:new Date,updatedBy:String(p)}),_!==null&&await _.writeHubs(L,[d])}),l.invalidatePrefix(Ge(d)),l.invalidatePrefix(bt),await oe(`${ce}${d}`);let I=ve(xe(w[0].businessDate,"YYYY-MM-DD"));I&&(l.invalidatePrefix(Kt(I)),await oe(`${re}${I}`));let v=await vt(He.unrestricted("post-write self read: the writer always sees the row they just wrote"),d,p,{forceRefresh:!0});if(v){let L=await st(d);await Ee(un.parse({type:"report-update",reportHubId:v.reportHubId,report:v,clientTempId:g,recipientRawUserId:L?p:void 0}),"updateDailyReport")}},el=async(d,p,y)=>{let g=await nr(t,d);if(!g.length)throw new Error("Not Found");if(g[0].userId!==p)throw new Error("Unauthorized");let w=await pe();if(await D(async v=>{await v.delete(h).where(Ae(V(h.hubId,d),Li(M,S))),w!==null&&await w.writeHubs(v,[d])}),l.invalidatePrefix(Ge(d)),l.invalidatePrefix(bt),l.invalidatePrefix(gt),await oe(G),g[0].businessDate){let v=ve(xe(g[0].businessDate,"YYYY-MM-DD"));v&&await oe(`${re}${v}`)}let _=ve(xe(g[0].businessDate,"YYYY-MM-DD"));_&&l.invalidatePrefix(Lt(_,p));let I=await vt(He.unrestricted("post-write self read: the writer always sees the row they just wrote"),d,p,{forceRefresh:!0});if(I){let v=await st(d);await Ee(dn.parse({type:"report-publish",reportHubId:I.reportHubId,report:I,clientTempId:y,recipientRawUserId:v?p:void 0}),"publishDailyReport")}return I??null},tl=async(d,p)=>{l.invalidatePrefix(bt),l.invalidatePrefix(gt),await oe(G);for(let y of new Set(d))l.invalidatePrefix(Ge(y)),await oe(`${ce}${y}`);for(let y of new Set(p)){let g=ve(y);g&&await oe(`${re}${g}`)}},rl=async()=>{l.clearAll(),tr.clear(),c&&await oe(G),x.info("Server-side DB/SQL caches cleared successfully.")};return{streamKey:he,streamMaxLen:Ke,attachmentDelivery:F,titleMaxLength:E,searchLimits:$===null?null:{concurrency:$.concurrency,rateLimitPerMinute:$.rateLimitPerMinute},searchFilterSourceTypes:ro,clearCache:rl,invalidateHubReadCaches:tl,getUserIdByExternalId:wt,getDailyReportIdsByExternalId:_s,getDailyReportIdsFirstPageByExternalId:fe,readSseStreamAnchor:T,getDailyReportsByBusinessDate:xs,getDailyReportsByBusinessDateByExternalId:Ns,getDailyReportDetailById:vt,getDailyReportDetailByIdByExternalId:ks,getDailyReportDetailsByIdsByExternalId:vs,getDraftLabelId:eo,searchDailyReports:Ws,markDailyReportSearchHits:Gs,listDailyReportSearchFacets:zs,reconcileSearchIndex:Ks,getAttachmentsByHubIds:rr,getAttachmentForUser:Ms,markAttachmentMissing:Ps,markAttachmentPresent:Ls,setStarStatus:Fs,setReadStatus:Hs,addComment:Us,deleteComment:Bs,createDailyReport:Js,updateDailyReport:Zs,publishDailyReport:el,deleteDailyReport:Xs,findDailyReportHubById:nr,updateDailyReportHub:qr,updateDailyReportInternal:no,deleteDailyReportLabel:Qs}}var Tp=(e,t,r,n)=>{if(!e)return[];try{let o=JSON.parse(e);return Array.isArray(o)?o.map(r).filter(a=>a!==null):(Se(n,1,"ExternalSource").warn(`Unexpected ${t} format: not an array`),[])}catch(o){return Se(n,1,"ExternalSource").warn(`Failed to parse ${t}:`,o),[]}};import{desc as ls,sql as Ep}from"drizzle-orm";import{bigint as Te,bit as cs,date as wp,datetime2 as Ie,foreignKey as Ye,index as yt,int as Ip,mssqlSchema as _p,nvarchar as le,primaryKey as Et,uniqueIndex as xp}from"drizzle-orm/mssql-core";function Cp(e,t){let r=_p(e),n=t.userTable,o=r.table("DailyReportHub",{id:Te("id",{mode:"number"}).identity().notNull(),sourceType:le("source_type",{length:20}).notNull(),sourceId:le("source_id",{length:100}).notNull(),sourceIdNum:Te("source_id_num",{mode:"number"}).generatedAlwaysAs(Ep`TRY_CAST(source_id AS BIGINT)`),businessDate:wp("business_date"),userId:Te("user_id",{mode:"number"}),title:le("title",{length:200}),summary:le("summary",{length:"max"}),createdAt:Ie("created_at").notNull(),createdBy:le("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:le("updated_by",{length:50}).notNull(),deletedAt:Ie("deleted_at"),deletedBy:le("deleted_by",{length:50})},u=>[Et({name:`${e}_DailyReportHub_pk`,columns:[u.id]}),Ye({name:`${e}_DailyReportHub_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),yt(`${e}_DailyReportHub_business_date_index`).on(u.businessDate),yt(`${e}_DailyReportHub_updated_at_index`).on(u.updatedAt),yt(`${e}_DailyReportHub_source_index`).on(u.sourceType,u.sourceId),yt(`${e}_DailyReportHub_user_id_index`).on(u.userId),yt(`${e}_DailyReportHub_business_date_id_index`).on(ls(u.businessDate),ls(u.id)),yt(`${e}_DailyReportHub_deleted_at_index`).on(u.deletedAt)]),a=r.table("DailyReportInternal",{hubId:Te("hub_id",{mode:"number"}).notNull(),body:le("body",{length:"max"}),metadata:le("metadata",{length:"max"}),createdAt:Ie("created_at").notNull(),createdBy:le("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:le("updated_by",{length:50}).notNull()},u=>[Et({name:`${e}_DailyReportInternal_pk`,columns:[u.hubId]}),Ye({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]})]),i=r.table("DailyReportComment",{id:Te("id",{mode:"number"}).identity().notNull(),hubId:Te("hub_id",{mode:"number"}).notNull(),userId:Te("user_id",{mode:"number"}).notNull(),body:le("body",{length:"max"}).notNull(),createdAt:Ie("created_at").notNull(),createdBy:le("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:le("updated_by",{length:50}).notNull()},u=>[Et({name:`${e}_DailyReportComment_pk`,columns:[u.id]}),Ye({name:`${e}_DailyReportComment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),Ye({name:`${e}_DailyReportComment_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),yt(`${e}_DailyReportComment_hub_id_index`).on(u.hubId)]),l=r.table("DailyReportLabel",{id:Te("id",{mode:"number"}).identity().notNull(),userId:Te("user_id",{mode:"number"}),name:le("name",{length:50}).notNull(),color:le("color",{length:20}),sortOrder:Ip("sort_order"),createdAt:Ie("created_at").notNull(),createdBy:le("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:le("updated_by",{length:50}).notNull()},u=>[Et({name:`${e}_DailyReportLabel_pk`,columns:[u.id]}),Ye({name:`${e}_DailyReportLabel_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),c=r.table("DailyReportHub_Label",{hubId:Te("hub_id",{mode:"number"}).notNull(),labelId:Te("label_id",{mode:"number"}).notNull(),createdAt:Ie("created_at").notNull(),createdBy:le("created_by",{length:50}).notNull()},u=>[Et({name:`${e}_DailyReportHub_Label_pk`,columns:[u.hubId,u.labelId]}),Ye({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),Ye({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[u.labelId],foreignColumns:[l.id]})]),s=r.table("DailyReportUserStatus",{hubId:Te("hub_id",{mode:"number"}).notNull(),userId:Te("user_id",{mode:"number"}).notNull(),isRead:cs("is_read").default(!1).notNull(),isStarred:cs("is_starred").default(!1).notNull(),createdAt:Ie("created_at").notNull(),createdBy:le("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:le("updated_by",{length:50}).notNull()},u=>[Et({name:`${e}_DailyReportUserStatus_pk`,columns:[u.hubId,u.userId]}),Ye({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),Ye({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),m=r.table("DailyReportAttachment",{id:Te("id",{mode:"number"}).identity().notNull(),hubId:Te("hub_id",{mode:"number"}).notNull(),uploadedBy:Te("uploaded_by",{mode:"number"}),sourceKey:le("source_key",{length:200}).notNull(),fileName:le("file_name",{length:255}).notNull(),filePath:le("file_path",{length:"max"}).notNull(),fileType:le("file_type",{length:100}),fileSize:Te("file_size",{mode:"number"}),objectCheckedAt:Ie("object_checked_at"),objectMissingAt:Ie("object_missing_at"),createdAt:Ie("created_at").notNull(),createdBy:le("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:le("updated_by",{length:50}).notNull()},u=>[Et({name:`${e}_DailyReportAttachment_pk`,columns:[u.id]}),Ye({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),Ye({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[u.uploadedBy],foreignColumns:[n.id]}),xp(`${e}_DailyReportAttachment_source_unique`).on(u.hubId,u.sourceKey),yt(`${e}_DailyReportAttachment_hub_id_index`).on(u.hubId,u.createdAt)]);return{hub:o,internal:a,comment:i,attachment:m,label:l,hubLabel:c,userStatus:s}}import{bigint as Xn,binary as us,datetime2 as Mp,int as Pp,mssqlSchema as Lp,nvarchar as Ur,primaryKey as ds,varchar as Np}from"drizzle-orm/mssql-core";function kp(e){let t=Lp(e),r=t.table("DailyReportSearchDocument",{hubId:Xn("hub_id",{mode:"number"}).notNull(),searchText:Ur("search_text",{length:"max"}).notNull(),sourceDigest:us("source_digest",{length:32}).notNull(),normalizerVersion:Np("normalizer_version",{length:64}).notNull(),indexedAt:Mp("indexed_at").notNull(),rowVersion:us("row_version",{length:8}).notNull(),authorName:Ur("author_name",{length:Ze.maxValueLength}),customerName:Ur("customer_name",{length:Ze.maxValueLength})},o=>[ds({name:`${e}_DailyReportSearchDocument_pk`,columns:[o.hubId]})]),n=t.table("DailyReportSearchComment",{hubId:Xn("hub_id",{mode:"number"}).notNull(),ordinal:Pp("ordinal").notNull(),authorUserId:Xn("author_user_id",{mode:"number"}),commentText:Ur("comment_text",{length:"max"}).notNull()},o=>[ds({name:`${e}_DailyReportSearchComment_pk`,columns:[o.hubId,o.ordinal]})]);return{document:r,comment:n}}var vp=5e7,As=2e8,Op=1,Ts=Object.freeze({fixedBytes:4*1024*1024,pipelineRows:2048,wholeImageBuffer:Object.freeze({"jpeg-single-scan":Object.freeze({kind:"none"}),"jpeg-multi-scan":Object.freeze({kind:"jpeg-coefficients"}),png:Object.freeze({kind:"none"}),"png-interlaced":Object.freeze({kind:"decoded-raster"}),gif:Object.freeze({kind:"canvas",bytesPerPixel:4}),"webp-lossy":Object.freeze({kind:"none"}),"webp-lossy-alpha":Object.freeze({kind:"canvas",bytesPerPixel:5}),"webp-lossless":Object.freeze({kind:"canvas",bytesPerPixel:4}),"webp-animated":Object.freeze({kind:"canvas",bytesPerPixel:9})})}),ps=125,ms=4,ys=16,hs=50,fs=2,$r=Object.freeze({renderMs:Pe.renderMs,nanosecondsPerBlockVisit:ps,margin:ms,maxBlockVisits:Math.floor(Pe.renderMs*1e6/(ps*ms)),walkBudgetMs:ys,nanosecondsPerWalkStep:hs,walkMargin:fs,maxWalkSteps:Math.floor(ys*1e6/(hs*fs))}),Fp=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),Rs=75,Ss=4,gs="#ffffff",Hp=1,Up={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},$p=[/out of memory/i,/insufficient memory/i,/memory allocation|allocation failed/i,/(?:cannot|could not|unable to|failed to) allocate/i,/picture memory error/i,/unable to create thread|error creating thread|resource temporarily unavailable/i,/too many open files|no space left on device/i,/\b(?:ENOMEM|EAGAIN|EMFILE|ENFILE|ENOSPC)\b/],bs=Object.freeze({ok:!1,reason:"failed"}),Ds=Object.freeze({ok:!1,reason:"unsupported"}),Es=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:ma(e)}),ws=(e,t)=>{switch(t){case"jpeg":{let r=Cn(e);return r===null?null:Es(r)}case"png":{let r=fa(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=Ra(e,$r.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},Is=(e,t)=>{let r=Fp.get(t.depth);if(r===void 0)return null;let n=t.channels*r,o=Ts,a=o.wholeImageBuffer[e.layout];return(a.kind==="none"?0:a.kind==="decoded-raster"?t.width*t.height*n:a.kind==="jpeg-coefficients"?e.coefficientBytes:t.width*t.height*a.bytesPerPixel)+o.pipelineRows*t.width*n+o.fixedBytes},Bp=(e,t,r)=>{let n=ws(e,t);return n===null?null:Is(n,r)},Vp=e=>e!==null&&e<=As,qp=(e,t)=>{if(t!=="jpeg")return ws(e,t);let r=ya(e,$r);return r===null||r.blockVisits>$r.maxBlockVisits?null:Es(r.header)},Yp=e=>{let t=e instanceof Error?e.message:"";return $p.some(r=>r.test(t))?"failed":"unsupported"},jp=e=>{e.cache(!1),e.concurrency(Op),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(Up)});let t=async(n,o,a,i,l)=>{let c=qp(n,o);if(c===null)return Ds;try{let s=e(n,{limitInputPixels:vp,animated:!1});if(!Vp(Is(c,await s.metadata())))return Ds;if(l.aborted)return bs;let m=await s.rotate().resize({width:a,height:i,fit:"inside",withoutEnlargement:!0}).flatten({background:gs}).webp({quality:Rs,effort:Ss}).toBuffer();return{ok:!0,bytes:new Uint8Array(m),contentType:"image/webp"}}catch(s){return{ok:!1,reason:Yp(s)}}},r=async(n,{format:o,maxWidth:a,maxHeight:i,signal:l})=>l.aborted?bs:t(n,o,a,i,l);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${Rs}-e${Ss}/flatten-${gs}/v${Hp}`,render:r}};var Wp=4096,zp=512*1024*1024,Gp=6e4;function cS(e){e.redis||Se(e.logger,2,"Server").warn("redis provider is not injected: cross-worker cache invalidation is disabled (staleness is bounded only by TTL) and SSE publishing is skipped.");let t=Kr(e.redis),r=new Ht({defaultTtlMs:te("cacheDefaultTtlMs",e.cacheDefaultTtlMs??Gp,1),maxBuckets:te("cacheMaxBuckets",e.cacheMaxBuckets??Wp,1),maxBytes:te("cacheMaxBytes",e.cacheMaxBytes??zp,1)},t),n=Qn({...e,cache:r,epochs:t}),o=new Jt({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),a=Bn({authenticate:e.authenticate,resolveVisibleSourceTypes:e.resolveVisibleSourceTypes,service:n,encodeUserId:e.encodeUserId,redis:e.redis,sseReader:o,streamKey:n.streamKey,loginRedirectPath:e.loginRedirectPath,enableDevCacheClear:e.enableDevCacheClear,logger:e.logger});return{service:n,cache:r,epochs:t,sseReader:o,streamKey:n.streamKey,knownSourceTypes:[...new Set(["Internal",...(e.externalSources??[]).map(i=>i.sourceType)])],...a}}export{Pn as DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,Mn as DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,As as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,$r as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL,Ts as DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,$n as DAILY_REPORT_SSE_CATCH_UP_BATCH,bi as DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,Jt as DailyReportSseReader,He as DailyReportViewerScope,Ht as SqlResultCache,Bn as createDailyReportHandlers,cS as createDailyReportServer,Qn as createDailyReportService,Kr as createEpochStore,jp as createSharpThumbnailRenderer,Cp as defineDailyReportSchema,kp as defineDailyReportSearchSchema,_t as encodeIdsStreamRows,dt as isStreamIdLte,yn as parseClientTempId,Bp as predictSharpThumbnailWorkingSetBytes,Gt as readDailyReportSseStreamEntry,Tp as transformJsonArray};
11
+ INSERT INTO ${o} (${$(o.hubId)}, ${$(o.ordinal)}, ${$(o.authorUserId)}, ${$(o.commentText)}) SELECT ${$(o.hubId)}, ${$(o.ordinal)}, ${$(o.authorUserId)}, ${$(o.commentText)} FROM OPENJSON(${i}) WITH (${$(o.hubId)} bigint, ${$(o.ordinal)} int, ${$(o.authorUserId)} bigint, ${$(o.commentText)} nvarchar(max));`},Cs=(e,t)=>B`SELECT ${$(e.hubId)} AS ${B.identifier(we.hubId)}, LOWER(CONVERT(char(64), ${$(e.sourceDigest)}, 2)) AS ${B.identifier(we.sourceDigest)}, ${$(e.normalizerVersion)} AS ${B.identifier(we.normalizerVersion)} FROM ${e} WHERE ${e.hubId} IN (${ur(t)})`,Ms=(e,t,r)=>B`SELECT TOP (${r}) ${$(e.id)} AS ${B.identifier(we.hubId)} FROM ${e} WHERE ${e.id} > ${t} ORDER BY ${e.id}`;var Ps=e=>({search:async(t,r)=>Me(r.scope.visible)?[]:ft(await t.execute(ws(e.tables,r.criteria,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=Mt(o[qe.sourceType],qe.sourceType);if(a===null)throw new Error(`[daily-report] search: column ${qe.sourceType} is null`);return{reportHubId:Ct(o[qe.reportHubId],qe.reportHubId),businessDate:Mt(o[qe.businessDate],qe.businessDate),sourceType:a}}),matchedSets:async(t,r)=>{if(Me(r.scope.visible))return new Map;let n=ft(await t.execute(Is(e.tables,r.plan,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames,r.ids))),o=2**r.plan.sets.length-1,a=new Map;for(let i of n){let l=i[Pt.matchedSets];if(!(typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&l<=o))throw new Error(`[daily-report] search: column ${Pt.matchedSets} holds no mask of ${r.plan.sets.length} keywords`);a.set(Ct(i[Pt.reportHubId],Pt.reportHubId),l)}return a},facetValues:async(t,r)=>Me(r.scope.visible)?[]:ft(await t.execute(_s(e.tables,r.column,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=Mt(o[dr.value],dr.value);if(a===null)throw new Error(`[daily-report] search: column ${dr.value} is null`);return a})});import{chunk as Gr,MAX_IN_LIST as Kr}from"@aiquants/mssql";import{sql as ks}from"drizzle-orm";import{createHash as Hp}from"crypto";var Bp=Object.freeze({authorName:"author",customerName:"customer"}),po=e=>e===null?null:Ln(e),Ls=(e,t,r)=>{let n=po(r);if(n!==null&&n.length>ot.maxValueLength){let o=ot.maxValueLength;throw new Error(`[daily-report] search index: report ${e}: the ${Bp[t]} display value has ${n.length} UTF-16 units after trimming; the host must keep the author and customer display values at most ${o} UTF-16 units`)}return n},pr=e=>e===null?"n;":`s${e.length}:${e}`,mr="utf16le",Up=e=>{let t=Hp("sha256");t.update(`F${e.fields.length};`,mr);for(let[r,n]of e.fields)t.update(pr(r)+pr(n),mr);return t.update(`C${e.comments.length};`,mr),e.comments.forEach((r,n)=>{t.update(`${n};${r.authorUserId===null?"n":`i${r.authorUserId}`};${pr(r.text)}`,mr)}),t.update(`P;${pr(po(e.filterValues.authorName))}${pr(po(e.filterValues.customerName))}`,mr),t.digest("hex")},mo=e=>{let t=0,r=[];for(let[,o]of e.fields){if(o===null)continue;let a=$r(o);t+=a.forcedCuts,r.push(a.text)}let n=[];for(let o of e.comments){let a=$r(o.text);t+=a.forcedCuts,a.text.length!==0&&n.push({ordinal:n.length,authorUserId:o.authorUserId,commentText:a.text})}return{hubId:e.hubId,searchText:Vi(r),comments:n,sourceDigest:Up(e),forcedCuts:t,authorName:Ls(e.hubId,"authorName",e.filterValues.authorName),customerName:Ls(e.hubId,"customerName",e.filterValues.customerName)}};var Ns=e=>{let t=async(s,c)=>{let d=[];for(let u of Gr(c,Kr))for(let R of ft(await s.execute(As(e.hub,u))))d.push(Ct(R[we.hubId],we.hubId));return d},r=async(s,c)=>{for(let d of Gr(c,Kr))await s.execute(xs(e.tables,d,e.normalizerVersion))},n=async(s,c)=>{let d=new Map;for(let u of Gr(c,Kr))for(let R of ft(await s.execute(Cs(e.tables.document,u))))d.set(Ct(R[we.hubId],we.hubId),{sourceDigest:Mt(R[we.sourceDigest],we.sourceDigest),normalizerVersion:Mt(R[we.normalizerVersion],we.normalizerVersion)});return d},o=async(s,c,d)=>ft(await s.execute(Ms(e.hub,c,d))).map(u=>Ct(u[we.hubId],we.hubId)),a=async(s,c)=>{let d=await t(s,[...new Set(c)].sort((R,m)=>R-m));if(d.length===0)return;let u=(await e.loadSources(s,d)).map(mo);u.length>0&&await r(s,u)},i=s=>e.inTransaction(async c=>{await c.execute(ks`SET DEADLOCK_PRIORITY LOW`);let d=await t(c,s),u=await n(c,d),R=(await e.loadSources(c,d)).map(mo),m=R.filter(p=>{let f=u.get(p.hubId);return f===void 0||f.sourceDigest!==p.sourceDigest||f.normalizerVersion!==e.normalizerVersion});return m.length>0&&await r(c,m),await c.execute(ks`SET DEADLOCK_PRIORITY NORMAL`),{scanned:R.length,written:m.length,forcedCuts:R.reduce((p,f)=>p+f.forcedCuts,0)}});return{writeHubs:a,reconcile:async(s,c)=>{let{batchSize:d,hubIds:u,signal:R,onProgress:m}=c;ue("reconcileSearchIndex: batchSize",d,1,Kr);let p=ae(),f=u===void 0?null:Gr([...new Set(u)].sort((S,I)=>S-I),d),y={scanned:0,written:0,skipped:0,forcedCuts:0,lastHubId:null};for(let S=0;;S++){R?.throwIfAborted();let I=f===null?await o(s,y.lastHubId===null?0:y.lastHubId,d):f[S];if(I===void 0||I.length===0)break;let D=await i(I);y={scanned:y.scanned+D.scanned,written:y.written+D.written,skipped:y.skipped+D.scanned-D.written,forcedCuts:y.forcedCuts+D.forcedCuts,lastHubId:I[I.length-1]},m?.(y)}return{...y,elapsedMs:ae()-p}}}};import{holdsMultiUnitCluster as $p}from"@aiquants/fuzzy-search/normalize";var yo=255,Jr=Object.values(It).sort((e,t)=>e-t),Vp=new Intl.Segmenter("und",{granularity:"grapheme"}),pe=Object.freeze({strip:30,split:200,line:2e3,plan:90,normalize:900,map:2200,scan:2,run:700,segment:150,sweep:30,linear:6}),tt=5e5,Qr=Math.floor(tt/pe.linear),Yp=Math.floor(tt/pe.segment),vs=Math.floor(tt/pe.sweep),Fs=Math.floor(tt/pe.scan),Ro=Object.freeze({maxRanges:5e5,maxUnits:4e6,maxFieldRanges:1e4,sliceNs:8e6,sliceMs:5}),Hs=(e,t)=>{let r=0,n=t(),o=tt,a=!1;return{fits:i=>r===0?!0:r+i>e.sliceNs?!1:(r>=o&&(o=r+tt,a=t()-n>=e.sliceMs),!a),charge:i=>{r+=i},startSlice:()=>{r=0,n=t(),o=tt,a=!1}}},_S=Object.freeze({fits:()=>!0,charge:()=>{}}),Bs=e=>{let t=null;return{step:()=>{if(t!==null)return!0;let r=e.next();return r.done!==!0?!1:(t={result:r.value},!0)},result:()=>{if(t===null)throw new Error("[daily-report] search marks: the walk is not done (step until it returns true)");return t.result}}};var qp=(e,t)=>{if(e.text!==t)throw new Error(`[daily-report] search marks: the position-mapped line (${e.text.length} units) differs from the index line (${t.length} units)`);return e},jp=(e,t)=>e.chunks.length===1&&e.chunks[0].length===1&&e.chunks[0][0].start===0&&e.chunks[0][0].end===t.length;function*Wp(e,t,r,n){let o=!1;for(let c=t;c<r&&!o;c+=Qr){let d=Math.min(r,c+Qr),u=(d-c)*pe.linear;n.fits(u)||(yield),o=$p(e.slice(c,d)),n.charge(u)}if(!o)return null;let a=new Int32Array(r-t),i=new Int32Array(r-t),l=Vp.segment(e.slice(t,r))[Symbol.iterator](),s=l.next();for(;!s.done;){let c=Math.max(Yp,s.value.segment.length);n.fits(c*pe.segment)||(yield);let d=0;for(;!s.done&&d+s.value.segment.length<=c;){let{index:u,segment:R}=s.value;a.fill(t+u,u,u+R.length),i.fill(t+u+R.length,u,u+R.length),d+=R.length,s=l.next()}n.charge(d*pe.segment)}return{start:t,clusterStarts:a,clusterEnds:i}}var zp=256,Gp=e=>{let t=new Int32Array(e.length),r=0;for(let n=1;n<e.length;n++){for(;r>0&&e.charCodeAt(n)!==e.charCodeAt(r);)r=t[r-1];e.charCodeAt(n)===e.charCodeAt(r)&&r++,t[n]=r}return e.length-t[e.length-1]},Kp=e=>{let t=new Map;for(let r of e){if(r.text.length===0)throw new Error("[daily-report] search marks: an alternative has an empty text");let n=t.get(r.text);(n===void 0||r.tier<n)&&t.set(r.text,r.tier)}return[...t].map(([r,n])=>{let o=Gp(r),a=Math.max(Fs-r.length+1,r.length);if(o===r.length)return{text:r,tier:n,periodic:null,windowStarts:a};let i=r.length%o,l=r.slice(i,o)+r.slice(0,i);return{text:r,tier:n,periodic:{period:o,continuation:l.repeat(Math.ceil(zp/o))},windowStarts:a}})},Xr=(e,t)=>{let{pieces:r}=e,n=r[e.lastPiece];if(n.plainStart<=t&&t<n.plainStart+n.text.length)return e.lastPiece;let o=0,a=r.length-1;for(;o<a;){let i=o+a+1>>1;r[i].plainStart<=t?o=i:a=i-1}return t>=r[o].plainStart+r[o].text.length?-1:(e.lastPiece=o,o)},Os=(e,t,r)=>{let n=Xr(e,t);return e.pieces[n>=0?n:Xr(e,r==="start"?t-1:t+1)]},Us=(e,t)=>{let r=Xr(e,t);if(r<0)return $s(e,t-1);let n=e.pieces[r];return n.start+n.mapped.start[t-n.plainStart]},$s=(e,t)=>{let r=Xr(e,t);if(r<0)return Us(e,t+1);let n=e.pieces[r];return n.start+n.mapped.end[t-n.plainStart]},Jp=()=>({from:0,runStart:-1,last:0,periodicEnd:-1,window:"",windowStart:0,windowEnd:0,closedStart:0,closedEnd:-1}),Qp=Object.freeze({kind:"done"}),ho=Object.freeze({kind:"slice"}),Xp=Object.freeze({kind:"clusters"}),Zp=(e,t,r,n,o,a)=>{let{plain:i}=e,{text:l,tier:s,periodic:c}=r;for(;;){if(n.closedEnd>=0){if(!o.fits(pe.run))return ho;let m=Os(e,n.closedStart,"start"),p=Os(e,n.closedEnd-1,"end");if(m.mapped===null)return{kind:"map",piece:m};if(p.mapped===null)return{kind:"map",piece:p};if(e.isCut&&e.clusters===void 0)return Xp;let f=t(e.offset+Us(e,n.closedStart)),y=t(e.offset+$s(e,n.closedEnd-1)-1)+1;n.closedEnd=-1;let S=e.clusters;S==null?a(f,y,s):a(S.clusterStarts[f-S.start],S.clusterEnds[y-1-S.start],s),o.charge(pe.run);continue}if(c!==null&&n.periodicEnd>=0){if(!o.fits(tt))return ho;let{period:m,continuation:p}=c,f=n.periodicEnd,y=Math.min(i.length,f+Math.max(Fs,p.length)),S=f;for(;S+p.length<=y&&i.startsWith(p,S);)S+=p.length;let I=S+p.length>y&&y<i.length;if(!I)for(;S<i.length&&i.charCodeAt(S)===i.charCodeAt(S-m);)S++;if(o.charge((S-f)*pe.scan),I){n.periodicEnd=S;continue}n.periodicEnd=-1,n.last+=Math.floor((S-n.last-l.length)/m)*m,n.from=n.last+l.length-m+1;continue}if(n.from<0){if(n.runStart<0)return Qp;n.closedStart=n.runStart,n.closedEnd=n.last+l.length,n.runStart=-1;continue}if(!o.fits(tt))return ho;n.from>=n.windowEnd&&(n.windowStart=n.from,n.windowEnd=n.from+r.windowStarts,n.window=i.slice(n.from,n.windowEnd+l.length-1));let d=n.from-n.windowStart,u=n.window.indexOf(l,d);if(u<0){o.charge((n.window.length-d)*pe.scan),n.from=n.windowStart+n.window.length===i.length?-1:n.windowEnd;continue}o.charge((u+l.length-d)*pe.scan);let R=n.windowStart+u;(n.runStart<0||R>=n.last+l.length)&&(n.runStart>=0&&(n.closedStart=n.runStart,n.closedEnd=n.last+l.length),n.runStart=R),n.last=R,c===null?n.from=R+1:n.periodicEnd=R+l.length}};function*fo(e,t,r){let n=Math.floor(tt/t);for(;!e.done();)r.fits(n*t)||(yield),r.charge(e.advance(n)*t);return e.result()}function*em(e,t,r,n,o){if(t.length===0)return;let a=yield*fo(Yi(e),pe.strip,n),i=[],l=[];yield*fo(qi(a.text,(c,d)=>{i.push(d),l.push(d+c.length)}),pe.split,n);let s=c=>a.rawIndex===null?c:a.rawIndex[c];for(let c=0;c<i.length;c++){n.fits(pe.line)||(yield),n.charge(pe.line);let d=i[c],u=a.text.slice(d,l[c]),R=yield*fo(ji(u,r),pe.plan,n),m=[],p="";for(let y of R.chunks){let S="",I=[];for(let D of y){let h=(D.end-D.start)*pe.normalize;n.fits(h)||(yield);let g=no(D.start===0&&D.end===u.length?u:u.slice(D.start,D.end),r).text;n.charge(h),g.length>0&&I.push({start:D.start,end:D.end,text:g,chunkStart:S.length}),S+=g}if(S.length!==0){p.length>0&&(p+=" ");for(let D of I)m.push({start:D.start,end:D.end,text:D.text,plainStart:p.length+D.chunkStart,mapped:null});p+=S}}if(p.length===0)continue;let f={offset:d,plain:p,pieces:m,isCut:!jp(R,u),lastPiece:0,clusters:void 0};for(let y of t){let S=Jp();for(;;){let I=Zp(f,s,y,S,n,o);if(I.kind==="done")break;if(I.kind==="slice"){yield;continue}if(I.kind==="clusters"){f.clusters=yield*Wp(e,s(d),s(d+u.length-1)+1,n);continue}let{piece:D}=I,h=(D.end-D.start)*pe.map;n.fits(h)||(yield);let g=u.slice(D.start,D.end);D.mapped=qp($i(g,ro(g,r)),D.text),n.charge(h)}}}}function*tm(e,t,r,n){let o=new Int32Array(Jr.length),a=0,i=yo;for(let l=0;l<=e;l+=vs){let s=Math.min(e+1,l+vs),c=(s-l)*pe.sweep;r.fits(c)||(yield);for(let d=l;d<s;d++){let u=yo;for(let R=Jr.length-1;R>=0;R--){let m=Jr[R];o[m]+=t[m][d],o[m]>0&&(u=m)}if(u!==i){if(i!==yo&&!n(a,d,i))return!1;a=d,i=u}}r.charge(c)}return!0}function*rm(e,t,r,n,o){let a=null;return yield*em(e,t,r,n,(l,s,c)=>{a===null&&(a=Jr.map(()=>new Int32Array(e.length+1))),a[c][l]++,a[c][s]--}),a===null?!0:yield*tm(e.length,a,n,o)}var nm=(e,t,r,n)=>{let o=Kp(t),a=[],i=(s,c,d)=>(a.push(s,c,d),a.length<=3*r.maxRanges);return Bs(function*(){return(yield*rm(e,o,r.maxLength,n,i))?{dense:!1,ranges:a}:{dense:!0}}())};var Vs=(e,t)=>{if(e.combine==="intersection"||e.sets.length===1)return e.sets.flatMap(r=>r.words);if(t===null)throw new Error(`[daily-report] search marks: a union of ${e.sets.length} keywords needs the report's mask of matched keywords`);return e.sets.flatMap((r,n)=>(t&1<<n)===0?[]:r.words)},Ys=e=>{let t=[],r=(n,o)=>{typeof o=="string"&&o.length>0&&t.push({key:n,value:o})};for(let n of ea)r(nt.field(n),e[n]);e.interviewers.forEach((n,o)=>{r(nt.interviewer(o,"name"),n.name),r(nt.interviewer(o,"affiliation"),n.affiliation)}),e.attachments.forEach((n,o)=>{r(nt.attachment(o),n.fileName)}),e.externalComments.forEach((n,o)=>{r(nt.comment(wn(o),"author"),n.name),r(nt.comment(wn(o),"content"),n.text)});for(let n of e.postedComments)r(nt.comment(n.id,"author"),n.userName),r(nt.comment(n.id,"content"),n.content);return t};function*om(e,t){let r=xn;for(let n=0;n<e.length;n+=Qr){let o=Math.min(e.length,n+Qr),a=(o-n)*pe.linear;t.fits(a)||(yield),r=Cn(r,e,n,o),t.charge(a)}return r}var qs=async(e,t,r,n)=>{let o=0,a=0,i=async c=>{for(;!c.step();)await r(),n.startSlice();return c.result()},l=async(c,d)=>{if(!d&&a>t.maxRanges)return null;let u={};for(let{key:R,value:m}of c.fields){if(!d&&o+m.length>t.maxUnits)return null;let p=await i(Bs(om(m,n))),f=await i(nm(m,c.alternatives,{maxLength:Zn,maxRanges:t.maxFieldRanges},n));if(o+=m.length,f.dense){u[R]={fingerprint:p,dense:!0};continue}if(u[R]={fingerprint:p,ranges:f.ranges},a+=f.ranges.length/3,!d&&a>t.maxRanges)return null}return u},s=[];for(let c=0;c<e.length;c++){let d=e[c],u=await l(d,s.length===0);if(u===null)return{reports:s,deferred:e.slice(c).map(R=>R.reportHubId)};s.push({reportHubId:d.reportHubId,matchedSets:d.matchedSets,fields:u})}return{reports:s,deferred:[]}};import{and as lm,asc as zs,eq as en,inArray as cm,isNull as um}from"drizzle-orm";import{and as js,asc as am,eq as Zr,getColumns as im,sql as sm}from"drizzle-orm";var je="Internal";var We=e=>im(e),fe=(e,t)=>{if(!e)return null;let r=e instanceof Date?e:new Date(e);if(Number.isNaN(r.getTime()))return typeof e=="string"?e:null;let n=r.getFullYear(),o=n<0?`-${String(-n).padStart(4,"0")}`:String(n).padStart(4,"0"),a=String(r.getMonth()+1).padStart(2,"0"),i=String(r.getDate()).padStart(2,"0");if(t==="YYYY-MM-DD")return`${o}-${a}-${i}`;let l=String(r.getHours()).padStart(2,"0"),s=String(r.getMinutes()).padStart(2,"0"),c=String(r.getSeconds()).padStart(2,"0");return`${o}-${a}-${i} ${l}:${s}:${c}`},Ws=e=>{let{db:t,tables:r,encodeUserId:n,settings:o,draftVisibilityTables:a}=e,{hub:i,label:l}=r,{externalSources:s,draftLabelNames:c,canonicalDraftLabelName:d}=o,u=L=>or(i.sourceType,L),R=(L,N)=>zr(a,L,c,N),m=sm`CASE WHEN ${Wr(a,c)} THEN 1 ELSE 0 END`,p=async L=>{let[N]=await t.select({id:i.id}).top(1).from(i).where(js(Zr(i.id,L),Wr(a,c)));return N!==void 0},f=L=>L==null||L===""?null:/^\d+$/.test(L)?n(Number(L)):L,y=()=>{let L={};for(let N of s)L[`ext_${N.sourceType}`]=We(N.table);return L},S=L=>{let N=L;for(let b of s)N=N.leftJoin(b.table,js(Zr(i.sourceType,b.sourceType),Zr(i.sourceIdNum,b.idColumn)));return N},I=L=>{let{hub:N,internal:b}=L,k=N.summary,U=[],O=null,F=null,z=null,X=null,q=null,ne=null,ge=[],Pe=s.find(G=>G.sourceType===N.sourceType),me=Pe?L[`ext_${Pe.sourceType}`]:void 0;if(Pe&&me){let G=Pe.mapRow(me);G.content!==void 0&&(k=G.content),G.employeeName!==void 0&&(ne=G.employeeName),G.category!==void 0&&(O=G.category),G.creationCategory!==void 0&&(F=G.creationCategory),G.visitTimeFrom!==void 0&&(z=G.visitTimeFrom),G.visitTimeTo!==void 0&&(X=G.visitTimeTo),G.customerName!==void 0&&(q=G.customerName),G.interviewers!==void 0&&(U=G.interviewers),G.externalComments!==void 0&&(ge=G.externalComments)}else N.sourceType===je&&b&&(k=b.body);return{content:k,author:L.creatorName??f(N.createdBy)??"",employeeName:ne??L.creatorName??f(N.createdBy),updatedBy:f(N.updatedBy),category:O,creationCategory:F,visitTimeFrom:z,visitTimeTo:X,customerName:q,interviewers:U,externalComments:ge}},D=L=>{if(L===1)return!0;if(L===0)return!1;throw new Error(`[daily-report] a detail row's hasDraftLabel must be 1 or 0 (the read must select draftLabelFlag); got ${dn(L)}`)},h=L=>L.creationCategory!==null&&c.includes(L.creationCategory),g=(L,N)=>D(L.hasDraftLabel)?!0:h(N),M=async L=>{let[N]=await L.select({id:l.id}).top(1).from(l).where(Zr(l.name,d)).orderBy(am(l.id));return N===void 0?null:N.id},_=()=>M(t);return{visibleSourceTypeCondition:u,draftVisibleTo:R,draftLabelFlag:m,isDraftReport:p,externalSelections:y,applyExternalJoins:S,resolveHubDisplayFields:I,readCanonicalDraftLabelId:M,getDraftLabelId:_,resolveCreationCategoryDraftLabelId:L=>L.some(h)?_():Promise.resolve(null),mapHubRecord:(L,N,b,k,U)=>{let{hub:O}=N,F=(N.labels??[]).map(q=>({id:q.id,name:q.name,color:q.color})),z=N.postedCommentRows??[],X=Ee(L.commentable,O.sourceType);return k!==null&&h(b)&&!F.some(q=>q.id===k)&&F.push({id:k,name:d,color:null}),{reportHubId:O.id,date:fe(O.businessDate,"YYYY-MM-DD"),author:b.author,userId:O.userId?n(O.userId):"",sourceType:O.sourceType,createdAt:fe(O.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:fe(O.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:b.updatedBy,employeeName:b.employeeName,category:b.category,creationCategory:b.creationCategory,visitTimeFrom:b.visitTimeFrom,visitTimeTo:b.visitTimeTo,customerName:b.customerName,interviewers:b.interviewers,subject:O.title,content:b.content,externalComments:X?b.externalComments:[],isRead:N.isRead??!1,isStarred:N.isStarred??!1,isDraft:g(N,b),labels:F,postedComments:z.filter(q=>Pi({authorUserId:q.userId},O.sourceType,U??null,L)).map(q=>({...q,userId:n(q.userId),isMine:U?q.userId===U:!1})),attachments:N.attachments}}}};var Gs=(e,{draftVisibleTo:t,visibleSourceTypeCondition:r})=>{let{db:n,tables:o,logger:a,settings:i}=e,{hub:l}=o,{attachmentDelivery:s}=i,c=(p,f)=>f!=null?"absent":p!=null?"present":"unknown";return{getAttachmentsByHubIds:async p=>{let f=new Map,y=o.attachment;if(p.length===0||!y||s===null)return f;let S=s.idCodec,I=s.thumbnails!==null,D=await n.select({id:y.id,hubId:y.hubId,fileName:y.fileName,fileType:y.fileType,fileSize:y.fileSize,createdAt:y.createdAt,objectCheckedAt:y.objectCheckedAt,objectMissingAt:y.objectMissingAt}).from(y).where(cm(y.hubId,p)).orderBy(zs(y.createdAt),zs(y.id));for(let h of D){let g=h.fileType?String(h.fileType):null,M=h.fileSize!=null?Number(h.fileSize):null,_=c(h.objectCheckedAt,h.objectMissingAt),C={id:S.encode(Number(h.id)),fileName:String(h.fileName),fileType:g,fileSize:M,createdAt:fe(h.createdAt,"YYYY-MM-DD HH:mm:ss"),state:_,hasThumbnail:I&&_!=="absent"&&Pr({fileType:g,fileSize:M},s.maxBytes)},Y=f.get(Number(h.hubId));Y?Y.push(C):f.set(Number(h.hubId),[C])}return f},getAttachmentForUser:async(p,f,y)=>{let S=o.attachment;return!S||Me(p.visible)?null:(await n.select({fileName:S.fileName,filePath:S.filePath,fileType:S.fileType,fileSize:S.fileSize}).top(1).from(S).innerJoin(l,en(l.id,S.hubId)).where(lm(en(S.id,f),um(l.deletedAt),t(y,"author"),r(p.visible))))[0]??null},markAttachmentMissing:async p=>{let f=o.attachment;if(!f)return;let y=new Date;try{await n.update(f).set({objectCheckedAt:y,objectMissingAt:y,updatedAt:y}).where(en(f.id,p))}catch(S){a.error("markAttachmentMissing failed",S)}},markAttachmentPresent:async p=>{let f=o.attachment;if(!f)return;let y=new Date;try{await n.update(f).set({objectCheckedAt:y,objectMissingAt:null,updatedAt:y}).where(en(f.id,p))}catch(S){a.error("markAttachmentPresent failed",S)}}}};import{eq as yr}from"drizzle-orm";var St="daily-report:ids:epoch",ke="daily-report:date-epoch:",ze="daily-report:detail-epoch:",Ks=({redis:e,logger:t,epochs:r,streamKey:n,streamMaxLen:o})=>({incrementRedisEpoch:s=>r.incrementEpoch(s),publishToSseStream:async(s,c)=>{let d=await e?.getClient();if(!d){t.warn(`[SSE] Redis client unavailable (${c})`);return}let u=JSON.stringify(s),R=Buffer.byteLength(u);if(R>6356992){t.warn(`[SSE] Event too large (${c}): ${R} bytes > ${6356992}; not published`);return}let m=ae();try{await d.xAdd(n,"*",{data:u},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:o}});let p=ae()-m;p>1e3&&t.warn(`[SSE] Slow publish (${c}): ${p}ms`)}catch(p){t.error(`[SSE] Redis publish failed (${c}):`,p)}},readSseStreamAnchor:async()=>{try{let s=await e?.getClient();if(s===void 0)return null;let[c]=await s.xRevRange(n,"+","-",{COUNT:1});return c===void 0?null:c.id}catch(s){return t.error("SSE stream anchor read failed",s),null}}});var Js=(e,{isDraftReport:t,assertHubMutable:r,incrementRedisEpoch:n})=>{let{db:o,tables:a,users:i,encodeUserId:l,cache:s,inTransaction:c,prepareSearchIndex:d,publishToSseStream:u}=e,{hub:R,comment:m}=a,p=async(I,D)=>{if(D!==null)return await t(I)?D:void 0},f=async(I,D,h,g,M,_)=>{let[C]=await o.select({sourceType:R.sourceType,deletedAt:R.deletedAt,userId:R.userId}).top(1).from(R).where(yr(R.id,h));if(!C||C.deletedAt)throw new Error("Not Found");if(await r(I,h,D),!Ee(I.commentable,C.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(C.sourceType.toLowerCase()!==je.toLowerCase())throw new Error("Comments are restricted for external daily report sources");let Y=await p(h,C.userId),L=await d(),N=await c(async O=>{let[F]=await O.insert(m).output().values({hubId:h,userId:D,body:g,createdAt:new Date,createdBy:String(D),updatedAt:new Date,updatedBy:String(D)});return L!==null&&await L.writeHubs(O,[h]),F}),[b]=await o.select({displayName:i.displayName}).top(1).from(i).where(yr(i.id,D)),k=b?.displayName??"";if(M){let O=Ce(M);O&&(s.invalidatePrefix(Vt(O)),await n(`${ke}${O}`))}s.invalidatePrefix(Be(h)),await n(`${ze}${h}`);let U={id:N.id,userId:l(N.userId),userName:k,content:N.body,createdAt:fe(N.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await u(Sn.parse({type:"comment-add",reportHubId:h,comment:U,clientTempId:_,recipientRawUserId:Y,sourceType:C.sourceType}),"addComment"),U},y=async(I,D)=>await I.select().top(1).from(m).where(yr(m.id,D));return{addComment:f,deleteComment:async(I,D,h,g,M,_)=>{let C=await y(o,g);if(C.length===0)throw new Error("Not Found");if(C[0].hubId!==h)throw new Error("Not Found");let[Y]=await o.select({userId:R.userId,sourceType:R.sourceType}).top(1).from(R).where(yr(R.id,C[0].hubId));if(!(Y&&Ee(I.visible,Y.sourceType)))throw new Error("Not Found");if(C[0].userId!==D)throw new Error("Unauthorized");let L=await p(h,Y.userId),N=await d();if(await c(async b=>{await b.delete(m).where(yr(m.id,g)),N!==null&&await N.writeHubs(b,[h])}),M){let b=Ce(M);b&&(s.invalidatePrefix(Vt(b)),await n(`${ke}${b}`))}s.invalidatePrefix(Be(h)),await n(`${ze}${h}`),await u(gn.parse({type:"comment-delete",reportHubId:h,commentId:g,clientTempId:_,recipientRawUserId:L,sourceType:Y.sourceType}),"deleteComment")}}};import{and as pm,eq as Yt}from"drizzle-orm";var Qs=e=>e===""?null:e,Xs=(e,{readCanonicalDraftLabelId:t,isDraftReport:r,getDailyReportDetailById:n,incrementRedisEpoch:o})=>{let{db:a,tables:i,users:l,encodeUserId:s,cache:c,logger:d,inTransaction:u,prepareSearchIndex:R,publishToSseStream:m,settings:p,draftVisibilityTables:f}=e,{hub:y,internal:S,hubLabel:I}=i,{canonicalDraftLabelName:D,draftLabelNames:h}=p,g=async(b,k,U)=>{if(!gr(k))throw J("createDailyReport: businessDate","a business-date key in the canonical form YYYY-MM-DD naming a day from 0001-01-01 to 9999-12-31",k);d.info("createDailyReport called",{userId:b,businessDate:k});let[O]=await a.select({displayName:l.displayName}).from(l).where(Yt(l.id,b)),F=O?.displayName??s(b),z=await R();try{let X=await u(async ne=>{d.info("Starting transaction");let ge=await t(ne);if(ge===null)throw new Error(`[daily-report] createDailyReport: the canonical draft label ${JSON.stringify(D)} (draftLabelNames[0]) does not exist; create that label before creating reports (a report without it would be visible to every viewer)`);let Pe=`internal-temp-${Date.now()}-${Math.random()}`,[me]=await ne.insert(y).output().values({sourceType:je,sourceId:Pe,businessDate:new Date(`${k}T00:00:00Z`),userId:b,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(b),updatedAt:new Date,updatedBy:String(b)});await ne.update(y).set({sourceId:String(me.id)}).where(Yt(y.id,me.id)),d.info("Hub created",me),await ne.insert(S).values({hubId:me.id,body:"",createdAt:new Date,createdBy:String(b),updatedAt:new Date,updatedBy:String(b)}),d.info("Internal created"),await ne.insert(I).values({hubId:me.id,labelId:ge,createdAt:new Date,createdBy:String(b)});let G=[{id:ge,name:D,color:null}];return d.info("Label assigned"),z!==null&&await z.writeHubs(ne,[me.id]),{reportHubId:me.id,date:k,createdAt:fe(me.createdAt,"YYYY-MM-DD HH:mm:ss"),author:F,userId:s(b),sourceType:je,employeeName:F,updatedBy:s(b),updatedAt:fe(me.updatedAt,"YYYY-MM-DD HH:mm:ss"),category:null,creationCategory:null,visitTimeFrom:null,visitTimeTo:null,customerName:null,interviewers:[],subject:me.title,content:"",externalComments:[],isRead:!0,isStarred:!1,isDraft:!0,labels:G,postedComments:[],attachments:[]}});c.invalidatePrefix(xt(k,b)),c.invalidatePrefix(yt),c.invalidatePrefix(io(b)),await o(St),await o(`${ke}${k}`);let q=await n(He.unrestricted("post-write self read: the writer always sees the row they just wrote"),X.reportHubId,b,{forceRefresh:!0});if(q){let ne=await r(q.reportHubId);await m(bn.parse({type:"report-create",reportHubId:q.reportHubId,report:q,clientTempId:U,recipientRawUserId:ne?b:void 0}),"createDailyReport")}return q??X}catch(X){throw d.error("Error in createDailyReport",X),X}},M=async(b,k)=>await b.select().top(1).from(y).where(Yt(y.id,k)),_=async(b,k,U)=>{await b.update(y).set(U).where(Yt(y.id,k))},C=async(b,k,U)=>{await b.update(S).set(U).where(Yt(S.hubId,k))};return{createDailyReport:g,updateDailyReport:async(b,k,U,O)=>{let F=await M(a,b);if(!F.length||F[0].deletedAt)throw new Error("Not Found");if(F[0].userId!==k)throw new Error("Unauthorized");let z=await R();await u(async ne=>{U.title!==void 0&&await _(ne,b,{title:Qs(U.title),updatedAt:new Date,updatedBy:String(k)}),U.content!==void 0&&await C(ne,b,{body:Qs(U.content),updatedAt:new Date,updatedBy:String(k)}),z!==null&&await z.writeHubs(ne,[b])}),c.invalidatePrefix(Be(b)),c.invalidatePrefix(yt),await o(`${ze}${b}`);let X=Ce(fe(F[0].businessDate,"YYYY-MM-DD"));X&&(c.invalidatePrefix(Vt(X)),await o(`${ke}${X}`));let q=await n(He.unrestricted("post-write self read: the writer always sees the row they just wrote"),b,k,{forceRefresh:!0});if(q){let ne=await r(b);await m(Dn.parse({type:"report-update",reportHubId:q.reportHubId,report:q,clientTempId:O,recipientRawUserId:ne?k:void 0}),"updateDailyReport")}},publishDailyReport:async(b,k,U)=>{let O=await M(a,b);if(!O.length)throw new Error("Not Found");if(O[0].userId!==k)throw new Error("Unauthorized");let F=await R();if(await u(async q=>{await q.delete(I).where(pm(Yt(I.hubId,b),Ds(f,h))),F!==null&&await F.writeHubs(q,[b])}),c.invalidatePrefix(Be(b)),c.invalidatePrefix(yt),c.invalidatePrefix(mt),await o(St),O[0].businessDate){let q=Ce(fe(O[0].businessDate,"YYYY-MM-DD"));q&&await o(`${ke}${q}`)}let z=Ce(fe(O[0].businessDate,"YYYY-MM-DD"));z&&c.invalidatePrefix(xt(z,k));let X=await n(He.unrestricted("post-write self read: the writer always sees the row they just wrote"),b,k,{forceRefresh:!0});if(X){let q=await r(b);await m(Tn.parse({type:"report-publish",reportHubId:X.reportHubId,report:X,clientTempId:U,recipientRawUserId:q?k:void 0}),"publishDailyReport")}return X??null},deleteDailyReport:async(b,k,U)=>{let O=await M(a,b);if(!O.length||O[0].deletedAt)throw new Error("Not Found");if(O[0].userId!==k)throw new Error("Unauthorized");if(await u(async F=>{await _(F,b,{deletedAt:new Date,deletedBy:String(k),updatedAt:new Date,updatedBy:String(k)})}),c.invalidatePrefix(Be(b)),c.invalidatePrefix(yt),c.invalidatePrefix(mt),await o(St),O[0].businessDate){let F=Ce(fe(O[0].businessDate,"YYYY-MM-DD"));F&&await o(`${ke}${F}`)}await m(An.parse({type:"report-delete",reportHubId:b,clientTempId:U,sourceType:O[0].sourceType}),"deleteDailyReport")}}};import{and as Lt,asc as Zs,desc as qt,eq as Re,inArray as So,isNull as hr,sql as el}from"drizzle-orm";var tl=Tr([]),rl=(e,{draftVisibleTo:t,visibleSourceTypeCondition:r,draftLabelFlag:n,externalSelections:o,applyExternalJoins:a,resolveHubDisplayFields:i,resolveCreationCategoryDraftLabelId:l,mapHubRecord:s,getAttachmentsByHubIds:c,readSseStreamAnchor:d,incrementRedisEpoch:u})=>{let{db:R,tables:m,users:p,resolveUserId:f,cache:y,epochs:S,logger:I,settings:D}=e,{hub:h,internal:g,comment:M,label:_,hubLabel:C,userStatus:Y}=m,L=D.idsTtlMs,N=D.businessDateTtlMs,b=async(T,A)=>(await R.select({reportHubId:h.id,businessDate:h.businessDate,sourceType:h.sourceType}).from(h).where(Lt(hr(h.deletedAt),t(A,"author-or-authorless"),r(T.visible))).orderBy(qt(h.businessDate),qt(h.id))).map(x=>({...x,businessDate:fe(x.businessDate,"YYYY-MM-DD")})),k=async(T,A,w)=>{let x=await F(A);return x?Me(T.visible)?[]:(await R.select({reportHubId:h.id,businessDate:h.businessDate,sourceType:h.sourceType}).top(w).from(h).where(Lt(hr(h.deletedAt),t(x,"author-or-authorless"),r(T.visible))).orderBy(qt(h.businessDate),qt(h.id))).map(V=>({...V,businessDate:fe(V.businessDate,"YYYY-MM-DD")})):[]},U=async(T,A)=>{let w=await a(R.select({hub:We(h),internal:We(g),creatorName:p.displayName,hasDraftLabel:n,...o()}).from(h)).leftJoin(g,Re(h.id,g.hubId)).leftJoin(p,Re(h.userId,p.id)).where(Lt(Re(h.businessDate,el`${A}`),hr(h.deletedAt),r(T.visible))).orderBy(qt(h.id)),x=await c(w.map(H=>H.hub.id)),v=w.map(i),V=await l(v);return w.map((H,j)=>s(T,{...H,attachments:x.get(H.hub.id)??[]},v[j],V))},O=new Map,F=async T=>{if(!D.disableUserIdCache&&O.has(T))return O.get(T)??null;let A=await f(T);return A!==null&&!D.disableUserIdCache&&O.set(T,A),A},z=async(T,A,{forceRefresh:w=!1,snapshot:x=!1,ttlMsOverride:v,onFetchStart:V,admission:H}={})=>{let j=await F(A);if(!j)return{items:[],streamAnchor:null,snapshot:tl};if(Me(T.visible))return{items:[],streamAnchor:await d(),snapshot:tl};let P=Zi(j,ar(T)),[W]=await y.getOrFetch({cacheKey:P,fetcher:async()=>{let Z=await d(),Q=await b(T,j);if(!Jo(Q)){I.warn("ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)");let le=[...Q].sort(En);return[{items:le,streamAnchor:Z,snapshot:Tr(le)}]}return[{items:Q,streamAnchor:Z,snapshot:Tr(Q)}]},onFetchStart:V,forceRefresh:w,snapshot:x,admission:H,ttlMsOverride:v??L,epochKey:St,refreshAheadRatio:.5});if(W===void 0)throw new Error("[daily-report] getDailyReportIdsByExternalId: the ids cache returned no record");return W},X=(T,A,{forceRefresh:w=!1,snapshot:x=!1,ttlMsOverride:v}={})=>{let V=Ce(A);return V?Me(T.visible)?Promise.resolve([]):y.getOrFetch({cacheKey:es(V,ar(T)),fetcher:()=>U(T,V),forceRefresh:w,snapshot:x,ttlMsOverride:v??N}):Promise.resolve([])},q=async(T,A,w)=>{let x=await a(R.select({hub:We(h),internal:We(g),isRead:Y.isRead,isStarred:Y.isStarred,creatorName:p.displayName,hasDraftLabel:n,...o()}).from(h)).leftJoin(g,Re(h.id,g.hubId)).leftJoin(Y,Lt(Re(h.id,Y.hubId),Re(Y.userId,A))).leftJoin(p,Re(h.userId,p.id)).where(Lt(w,hr(h.deletedAt),t(A,"author"),r(T.visible))).orderBy(qt(h.id));if(x.length===0)return[];let v=x.map(le=>le.hub.id),V=await R.select({hubId:C.hubId,id:_.id,name:_.name,color:_.color}).from(C).innerJoin(_,Re(C.labelId,_.id)).where(So(C.hubId,v)),H=await R.select({hubId:M.hubId,id:M.id,body:M.body,createdAt:M.createdAt,userId:M.userId,userName:p.displayName}).from(M).leftJoin(p,Re(M.userId,p.id)).where(So(M.hubId,v)).orderBy(Zs(M.createdAt)),j=await c(v),P=new Map,W=new Map;for(let le of V){let _e=P.get(le.hubId);_e||(_e=[],P.set(le.hubId,_e)),_e.push({id:le.id,name:le.name,color:le.color})}for(let le of H){let _e=W.get(le.hubId);_e||(_e=[],W.set(le.hubId,_e)),_e.push({id:le.id,content:le.body,createdAt:fe(le.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:le.userId,userName:le.userName||""})}let Z=x.map(i),Q=await l(Z);return x.map((le,_e)=>{let bt=le.hub.id;return s(T,{...le,attachments:j.get(bt)??[],labels:P.get(bt)||[],postedCommentRows:W.get(bt)||[]},Z[_e],Q,A)})},ne=async(T,A,w,{forceRefresh:x=!1,snapshot:v=!1,ttlMsOverride:V,admission:H}={})=>{let j=await F(w);if(!j)return[];let P=Ce(A);if(!P)return[];if(Me(T.visible))return[];let W=ts(P,j,ar(T));return y.getOrFetch({cacheKey:W,fetcher:()=>q(T,j,Re(h.businessDate,el`${P}`)),forceRefresh:x,snapshot:v,admission:H,ttlMsOverride:V??N,epochKey:`${ke}${P}`})},ge=async(T,A,w,{forceRefresh:x=!1,snapshot:v=!1,ttlMsOverride:V,admission:H}={})=>{if(Me(T.visible))return null;let j=rs(A,w,ar(T));return(await y.getOrFetch({cacheKey:j,fetcher:async()=>{let W=await a(R.select({hub:We(h),internal:We(g),isRead:Y.isRead,isStarred:Y.isStarred,creatorName:p.displayName,hasDraftLabel:n,...o()}).from(h)).leftJoin(g,Re(h.id,g.hubId)).leftJoin(Y,Lt(Re(h.id,Y.hubId),Re(Y.userId,w))).leftJoin(p,Re(h.userId,p.id)).where(Lt(Re(h.id,A),hr(h.deletedAt),t(w,"author"),r(T.visible)));if(W.length===0)return[];let Z=W[0].hub.id,Q=await R.select({id:_.id,name:_.name,color:_.color}).from(C).innerJoin(_,Re(C.labelId,_.id)).where(Re(C.hubId,Z)),le=await R.select({id:M.id,body:M.body,createdAt:M.createdAt,userId:M.userId,userName:p.displayName}).from(M).leftJoin(p,Re(M.userId,p.id)).where(Re(M.hubId,Z)).orderBy(Zs(M.createdAt)),_e=await c([Z]),bt=Q.map(Ue=>({id:Ue.id,name:Ue.name,color:Ue.color})),sn=le.map(Ue=>({id:Ue.id,content:Ue.body,createdAt:fe(Ue.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:Ue.userId,userName:Ue.userName||""})),Sr=i(W[0]),ln=await l([Sr]);return[s(T,{...W[0],attachments:_e.get(Z)??[],labels:bt,postedCommentRows:sn},Sr,ln,w)]},forceRefresh:x,snapshot:v,admission:H,ttlMsOverride:V??N,epochKey:`${ze}${A}`}))[0]??null};return{getUserIdByExternalId:F,getDailyReportIdsByExternalId:z,getDailyReportIdsFirstPageByExternalId:k,getDailyReportsByBusinessDate:X,getDailyReportsByBusinessDateByExternalId:ne,getDailyReportDetailById:ge,getDailyReportDetailByIdByExternalId:async(T,A,w,x={})=>{let v=await F(w);return v?ge(T,A,v,x):null},getDailyReportDetailsByIdsByExternalId:async(T,A,w)=>{if(A.length>Ae.maxDetailIds)throw J("getDailyReportDetailsByIdsByExternalId: reportHubIds",`at most ${Ae.maxDetailIds} ids`,A.length);let x=await F(w);return!x||A.length===0?[]:Me(T.visible)?[]:q(T,x,So(h.id,[...A]))},fetchVisibleHubDetails:q,invalidateHubReadCaches:async(T,A)=>{y.invalidatePrefix(yt),y.invalidatePrefix(mt),await u(St);for(let w of new Set(T))y.invalidatePrefix(Be(w)),await u(`${ze}${w}`);for(let w of new Set(A)){let x=Ce(w);x&&await u(`${ke}${x}`)}},clearCache:async()=>{y.clearAll(),O.clear(),S&&await u(St),I.info("Server-side DB/SQL caches cleared successfully.")}}};var tn=Object.freeze({idsTtlMs:18e4,businessDateTtlMs:3e5,streamKey:"daily-report:sse-stream",streamMaxLen:1e4}),mm=e=>{let{length:t}=e;if(t===void 0)throw J("tables.hub.title","a character column with a declared length",t);return ue("tables.hub.title.length",t,1)},ym=e=>{if(!Array.isArray(e)||e.length===0||e.some(t=>typeof t!="string"||t.trim().length===0)||new Set(e).size!==e.length)throw J("draftLabelNames","one or more non-blank label names",e);return Object.freeze([...e])},hm=e=>{let t=new Map([[je.toLowerCase(),`the internal source type ${JSON.stringify(je)}`]]);for(let[r,{sourceType:n}]of e.entries()){let o=`externalSources[${r}].sourceType`,a=t.get(n.toLowerCase());if(a!==void 0)throw J(o,`a source type that differs, ignoring case, from ${a}`,n);t.set(n.toLowerCase(),`${o} ${JSON.stringify(n)}`)}return Object.freeze([je,...e.map(r=>r.sourceType)])},nl=e=>{let t=e.externalSources??[],r=ym(e.draftLabelNames);kr(e);let n=pi(e.attachments),o=mm(e.tables.hub.title),a=xe("idsTtlMs",e.idsTtlMs,1,tn.idsTtlMs),i=xe("businessDateTtlMs",e.businessDateTtlMs,1,tn.businessDateTtlMs),l=xe("streamMaxLen",e.streamMaxLen,1,tn.streamMaxLen);return Object.freeze({externalSources:t,sourceTypes:hm(t),draftLabelNames:r,canonicalDraftLabelName:r[0],attachmentDelivery:n,titleMaxLength:o,idsTtlMs:a,businessDateTtlMs:i,streamKey:e.streamKey??tn.streamKey,streamMaxLen:l,disableUserIdCache:!!e.disableUserIdCache})};import{and as fr,eq as lt}from"drizzle-orm";var ol=(e,{draftVisibleTo:t,incrementRedisEpoch:r})=>{let{db:n,tables:o,cache:a,publishToSseStream:i}=e,{hub:l,userStatus:s}=o,c=async(m,p)=>{let[f]=await n.select({sourceType:l.sourceType,deletedAt:l.deletedAt}).top(1).from(l).where(fr(lt(l.id,m),t(p,"author")));return f??null},d=async(m,p,f)=>{let y=await c(p,f);if(!y||y.deletedAt||!Ee(m.visible,y.sourceType))throw new Error("Not Found")};return{assertHubMutable:d,setStarStatus:async(m,p,f,y,S,I)=>{await d(m,f,p);let D=await n.select().top(1).from(s).where(fr(lt(s.hubId,f),lt(s.userId,p))),h;if(D.length>0?D[0].isStarred!==S?h=(await n.update(s).set({isStarred:S,updatedAt:new Date,updatedBy:String(p)}).output().where(fr(lt(s.hubId,f),lt(s.userId,p))))[0]:h=D[0]:h=(await n.insert(s).output().values({hubId:f,userId:p,isStarred:S,isRead:!1,createdAt:new Date,createdBy:String(p),updatedAt:new Date,updatedBy:String(p)}))[0],y){let g=Ce(y);g&&(a.invalidatePrefix(xt(g,p)),await r(`${ke}${g}`))}return a.invalidatePrefix(qr(f,p)),await r(`${ze}${f}`),await i(Dr.parse({type:"status-update",reportHubId:f,recipientRawUserId:p,statusType:"star",value:S,clientTempId:I}),"setStarStatus"),h},setReadStatus:async(m,p,f,y,S,I)=>{await d(m,f,p);let D=await n.select().top(1).from(s).where(fr(lt(s.hubId,f),lt(s.userId,p))),h;if(D.length>0?D[0].isRead!==S?h=(await n.update(s).set({isRead:S,updatedAt:new Date,updatedBy:String(p)}).output().where(fr(lt(s.hubId,f),lt(s.userId,p))))[0]:h=D[0]:h=(await n.insert(s).output().values({hubId:f,userId:p,isRead:S,isStarred:!1,createdAt:new Date,createdBy:String(p),updatedAt:new Date,updatedBy:String(p)}))[0],y){let g=Ce(y);g&&(a.invalidatePrefix(xt(g,p)),await r(`${ke}${g}`))}return a.invalidatePrefix(qr(f,p)),await r(`${ze}${f}`),await i(Dr.parse({type:"status-update",reportHubId:f,recipientRawUserId:p,statusType:"read",value:S,clientTempId:I}),"setReadStatus"),h}}};var gm="v3",il=e=>`${e}:${gm}`,bm=Object.freeze([]),go=(e,t,r)=>{let n=e.get(t);n?n.push(r):e.set(t,[r])},nn=(e,t)=>e.get(t)??bm,al=(e,t)=>[e,t].filter(r=>typeof r=="string"&&r.length>0).join(Br),Dm=(e,t)=>{let r="the request's AbortSignal (new AbortController().signal for a call that is never aborted)";if(t===void 0)throw rt(`${e}: options.signal`,r);if(typeof t!="object"||t===null)throw J(`${e}: options`,"an object carrying the request's AbortSignal",t);let{signal:n}=t;if(n===void 0)throw rt(`${e}: options.signal`,r);if(!(n instanceof AbortSignal))throw J(`${e}: options.signal`,r,n);return n};function bo(e){let{db:t,tables:r,userTable:n,resolveUserId:o,encodeUserId:a,redis:i,cache:l,epochs:s}=e,{hub:c,internal:d,comment:u,label:R,hubLabel:m}=r,p=nl(e),{externalSources:f,draftLabelNames:y,attachmentDelivery:S,titleMaxLength:I}=p,D=he(e.logger,1,"Service"),h=ee=>Sm(ce=>t.transaction(K=>ce(()=>ee(K))),e.transactionRetry),g=e.search===void 0?null:gs(e.search,f.map(ee=>ee.sourceType)),M={hub:c,hubLabel:m,label:R},_=g===null?null:Ps({tables:{...M,search:g.tables},draftLabelNames:y});g!==null&&ao();let C=null,Y=async()=>{if(g===null)return null;if(C===null){let ee=await ao(),ce=g.externalSourceTexts;C=Ns({hub:c,tables:g.tables,loadSources:(K,te)=>Nl(K,te,ce),inTransaction:h,normalizerVersion:ee})}return C},L=il(p.streamKey),{incrementRedisEpoch:N,publishToSseStream:b,readSseStreamAnchor:k}=Ks({redis:i,logger:D,epochs:s,streamKey:L,streamMaxLen:p.streamMaxLen}),U={db:t,tables:r,users:n,resolveUserId:o,encodeUserId:a,cache:l,epochs:s,logger:D,settings:p,draftVisibilityTables:M,inTransaction:h,publishToSseStream:b,prepareSearchIndex:Y},{visibleSourceTypeCondition:O,draftVisibleTo:F,draftLabelFlag:z,isDraftReport:X,externalSelections:q,applyExternalJoins:ne,resolveHubDisplayFields:ge,readCanonicalDraftLabelId:Pe,getDraftLabelId:me,resolveCreationCategoryDraftLabelId:G,mapHubRecord:E}=Ws(U),{getAttachmentsByHubIds:T,getAttachmentForUser:A,markAttachmentMissing:w,markAttachmentPresent:x}=Gs(U,{draftVisibleTo:F,visibleSourceTypeCondition:O}),{getUserIdByExternalId:v,getDailyReportIdsByExternalId:V,getDailyReportIdsFirstPageByExternalId:H,getDailyReportsByBusinessDate:j,getDailyReportsByBusinessDateByExternalId:P,getDailyReportDetailById:W,getDailyReportDetailByIdByExternalId:Z,getDailyReportDetailsByIdsByExternalId:Q,fetchVisibleHubDetails:le,invalidateHubReadCaches:_e,clearCache:bt}=rl(U,{draftVisibleTo:F,visibleSourceTypeCondition:O,draftLabelFlag:z,externalSelections:q,applyExternalJoins:ne,resolveHubDisplayFields:ge,resolveCreationCategoryDraftLabelId:G,mapHubRecord:E,getAttachmentsByHubIds:T,readSseStreamAnchor:k,incrementRedisEpoch:N}),{assertHubMutable:sn,setStarStatus:Sr,setReadStatus:ln}=ol(U,{draftVisibleTo:F,incrementRedisEpoch:N}),{addComment:Ue,deleteComment:Il}=Js(U,{isDraftReport:X,assertHubMutable:sn,incrementRedisEpoch:N}),{createDailyReport:_l,updateDailyReport:xl,publishDailyReport:Cl,deleteDailyReport:Ml}=Xs(U,{readCanonicalDraftLabelId:Pe,isDraftReport:X,getDailyReportDetailById:W,incrementRedisEpoch:N}),Pl=async(ee,ce)=>{let K=new Map,te=r.attachment;if(!te||S===null)return K;let Se=await ee.select({hubId:te.hubId,fileName:te.fileName}).from(te).where(Rr(te.hubId,[...ce])).orderBy(ct(te.hubId),ct(te.createdAt),ct(te.id));for(let re of Se)go(K,Number(re.hubId),String(re.fileName));return K},Ll=async(ee,ce,K)=>{let te=new Map;for(let[Se,re]of K){let Ke=new Map;for(let{hub:Le}of ce)Le.sourceType===Se&&Le.sourceIdNum!==null&&Ke.set(Le.sourceIdNum,Le.id);if(Ke.size===0)continue;let Dt=await re(ee,[...Ke.keys()]);for(let[Le,ut]of Dt){let jt=Ke.get(Le);if(jt===void 0)throw J(`search.externalSourceTexts.${Se} answer key`,"a source id that was asked for",Le);if(!(Array.isArray(ut)&&ut.every(Nt=>typeof Nt=="string")))throw J(`search.externalSourceTexts.${Se} answer for ${Le}`,"an array of strings",ut);te.set(jt,ut)}}return te},kl=(ee,ce)=>{let K=ge(ee),te=[["subject",ee.hub.title],["content",K.content],["author",K.author],["employeeName",K.employeeName],["updatedBy",K.updatedBy],["category",K.category],["creationCategory",K.creationCategory],["customerName",K.customerName]];for(let re of K.interviewers)te.push(["interviewerName",re.name??null],["interviewerAffiliation",re.affiliation??null]);for(let re of ce.labelNames)te.push(["label",re]);for(let re of ce.attachmentNames)te.push(["attachment",re]);for(let re of ce.extraTexts)te.push(["extra",re]);let Se=[];for(let re of K.externalComments)Se.push({authorUserId:null,text:al(re.name,re.text)});for(let re of ce.postedComments)Se.push({authorUserId:re.userId,text:al(re.userName,re.body)});return{hubId:ee.hub.id,fields:te,comments:Se,filterValues:{authorName:K.employeeName,customerName:K.customerName}}},Nl=async(ee,ce,K)=>{let te=[];for(let Se of fm(ce,Rm)){let re=await ne(ee.select({hub:We(c),internal:We(d),creatorName:n.displayName,...q()}).from(c)).leftJoin(d,rn(c.id,d.hubId)).leftJoin(n,rn(c.userId,n.id)).where(Rr(c.id,[...Se])).orderBy(ct(c.id)),Ke=new Map,Dt=await ee.select({hubId:m.hubId,name:R.name}).from(m).innerJoin(R,rn(m.labelId,R.id)).where(Rr(m.hubId,[...Se])).orderBy(ct(m.hubId),ct(R.id));for(let Te of Dt)go(Ke,Te.hubId,Te.name);let Le=new Map,ut=await ee.select({hubId:u.hubId,userId:u.userId,body:u.body,userName:n.displayName}).from(u).leftJoin(n,rn(u.userId,n.id)).where(Rr(u.hubId,[...Se])).orderBy(ct(u.hubId),ct(u.createdAt),ct(u.id));for(let Te of ut)go(Le,Te.hubId,Te);let jt=await Pl(ee,Se),Nt=await Ll(ee,re,K);for(let Te of re){let Tt=Te.hub.id;te.push(kl(Te,{labelNames:nn(Ke,Tt),postedComments:nn(Le,Tt),attachmentNames:nn(jt,Tt),extraTexts:nn(Nt,Tt)}))}}return te},vl=(ee,ce,K)=>_===null?Promise.reject(new Error("[daily-report] searchDailyReports: the search setting is not configured")):_.search(t,{criteria:K,viewerUserId:ce,scope:ee}),To=p.sourceTypes,Ol=async(ee,ce)=>{if(_===null)throw new Error("[daily-report] listDailyReportSearchFacets: the search setting is not configured");let K=To.filter(re=>Ee(ee.visible,re)),te=await _.facetValues(t,{column:"authorName",viewerUserId:ce,scope:ee}),Se=await _.facetValues(t,{column:"customerName",viewerUserId:ce,scope:ee});return{sourceTypes:K,authors:te,customers:Se}},Fl=async(ee,ce,K,te,Se)=>{let re=Dm("markDailyReportSearchHits",Se);if(_===null)throw new Error("[daily-report] markDailyReportSearchHits: the search setting is not configured");if(te.length>Ae.maxDetailIds)throw J("markDailyReportSearchHits: reportHubIds",`at most ${Ae.maxDetailIds} ids`,te.length);let Ke=Ar(ir(K));if(te.length===0||Me(ee.visible))return{wordsDigest:Ke,reports:[],deferred:[]};re.throwIfAborted();let Dt=await le(ee,ce,Rr(c.id,[...te]));re.throwIfAborted();let Le=K.combine==="union"&&K.sets.length>=2&&Dt.length>0?await _.matchedSets(t,{plan:K,viewerUserId:ce,scope:ee,ids:Dt.map(Te=>Te.reportHubId)}):null,ut=Dt.map(Te=>{let Tt=Le===null?null:Le.get(Te.reportHubId),Ao=Tt===void 0?0:Tt;return{reportHubId:Te.reportHubId,matchedSets:Ao,alternatives:Vs(K,Ao).flatMap(Bl=>Bl.alternatives),fields:Ys(Te)}}),Nt=await qs(ut,Ro,async()=>{await new Promise(Te=>setImmediate(Te)),re.throwIfAborted()},Hs(Ro,ae));return{wordsDigest:Ke,reports:Nt.reports,deferred:Nt.deferred}},Hl=async ee=>{let ce=await Y();if(ce===null)throw new Error("[daily-report] reconcileSearchIndex: the search setting is not configured");return ce.reconcile(t,ee)};return{streamKey:L,attachmentDelivery:S,titleMaxLength:I,searchLimits:g===null?null:{concurrency:g.concurrency,rateLimitPerMinute:g.rateLimitPerMinute},searchFilterSourceTypes:To,clearCache:bt,invalidateHubReadCaches:_e,getUserIdByExternalId:v,getDailyReportIdsByExternalId:V,getDailyReportIdsFirstPageByExternalId:H,readSseStreamAnchor:k,getDailyReportsByBusinessDate:j,getDailyReportsByBusinessDateByExternalId:P,getDailyReportDetailById:W,getDailyReportDetailByIdByExternalId:Z,getDailyReportDetailsByIdsByExternalId:Q,getDraftLabelId:me,searchDailyReports:vl,markDailyReportSearchHits:Fl,listDailyReportSearchFacets:Ol,reconcileSearchIndex:Hl,getAttachmentsByHubIds:T,getAttachmentForUser:A,markAttachmentMissing:w,markAttachmentPresent:x,setStarStatus:Sr,setReadStatus:ln,addComment:Ue,deleteComment:Il,createDailyReport:_l,updateDailyReport:xl,publishDailyReport:Cl,deleteDailyReport:Ml}}var Tm=(e,t,r,n)=>{if(!e)return[];try{let o=JSON.parse(e);return Array.isArray(o)?o.map(r).filter(a=>a!==null):(he(n,1,"ExternalSource").warn(`Unexpected ${t} format: not an array`),[])}catch(o){return he(n,1,"ExternalSource").warn(`Failed to parse ${t}:`,o),[]}};import{desc as sl,sql as Am}from"drizzle-orm";import{bigint as De,bit as ll,date as Em,datetime2 as Ie,foreignKey as Ge,index as gt,int as wm,mssqlSchema as Im,nvarchar as ie,primaryKey as kt,uniqueIndex as _m}from"drizzle-orm/mssql-core";function xm(e,t){let r=Im(e),n=t.userTable,o=r.table("DailyReportHub",{id:De("id",{mode:"number"}).identity().notNull(),sourceType:ie("source_type",{length:20}).notNull(),sourceId:ie("source_id",{length:100}).notNull(),sourceIdNum:De("source_id_num",{mode:"number"}).generatedAlwaysAs(Am`TRY_CAST(source_id AS BIGINT)`),businessDate:Em("business_date"),userId:De("user_id",{mode:"number"}),title:ie("title",{length:200}),summary:ie("summary",{length:"max"}),createdAt:Ie("created_at").notNull(),createdBy:ie("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:ie("updated_by",{length:50}).notNull(),deletedAt:Ie("deleted_at"),deletedBy:ie("deleted_by",{length:50})},u=>[kt({name:`${e}_DailyReportHub_pk`,columns:[u.id]}),Ge({name:`${e}_DailyReportHub_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),gt(`${e}_DailyReportHub_business_date_index`).on(u.businessDate),gt(`${e}_DailyReportHub_updated_at_index`).on(u.updatedAt),gt(`${e}_DailyReportHub_source_index`).on(u.sourceType,u.sourceId),gt(`${e}_DailyReportHub_user_id_index`).on(u.userId),gt(`${e}_DailyReportHub_business_date_id_index`).on(sl(u.businessDate),sl(u.id)),gt(`${e}_DailyReportHub_deleted_at_index`).on(u.deletedAt)]),a=r.table("DailyReportInternal",{hubId:De("hub_id",{mode:"number"}).notNull(),body:ie("body",{length:"max"}),metadata:ie("metadata",{length:"max"}),createdAt:Ie("created_at").notNull(),createdBy:ie("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:ie("updated_by",{length:50}).notNull()},u=>[kt({name:`${e}_DailyReportInternal_pk`,columns:[u.hubId]}),Ge({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]})]),i=r.table("DailyReportComment",{id:De("id",{mode:"number"}).identity().notNull(),hubId:De("hub_id",{mode:"number"}).notNull(),userId:De("user_id",{mode:"number"}).notNull(),body:ie("body",{length:"max"}).notNull(),createdAt:Ie("created_at").notNull(),createdBy:ie("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:ie("updated_by",{length:50}).notNull()},u=>[kt({name:`${e}_DailyReportComment_pk`,columns:[u.id]}),Ge({name:`${e}_DailyReportComment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),Ge({name:`${e}_DailyReportComment_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),gt(`${e}_DailyReportComment_hub_id_index`).on(u.hubId)]),l=r.table("DailyReportLabel",{id:De("id",{mode:"number"}).identity().notNull(),userId:De("user_id",{mode:"number"}),name:ie("name",{length:50}).notNull(),color:ie("color",{length:20}),sortOrder:wm("sort_order"),createdAt:Ie("created_at").notNull(),createdBy:ie("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:ie("updated_by",{length:50}).notNull()},u=>[kt({name:`${e}_DailyReportLabel_pk`,columns:[u.id]}),Ge({name:`${e}_DailyReportLabel_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),s=r.table("DailyReportHub_Label",{hubId:De("hub_id",{mode:"number"}).notNull(),labelId:De("label_id",{mode:"number"}).notNull(),createdAt:Ie("created_at").notNull(),createdBy:ie("created_by",{length:50}).notNull()},u=>[kt({name:`${e}_DailyReportHub_Label_pk`,columns:[u.hubId,u.labelId]}),Ge({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),Ge({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[u.labelId],foreignColumns:[l.id]})]),c=r.table("DailyReportUserStatus",{hubId:De("hub_id",{mode:"number"}).notNull(),userId:De("user_id",{mode:"number"}).notNull(),isRead:ll("is_read").default(!1).notNull(),isStarred:ll("is_starred").default(!1).notNull(),createdAt:Ie("created_at").notNull(),createdBy:ie("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:ie("updated_by",{length:50}).notNull()},u=>[kt({name:`${e}_DailyReportUserStatus_pk`,columns:[u.hubId,u.userId]}),Ge({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),Ge({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),d=r.table("DailyReportAttachment",{id:De("id",{mode:"number"}).identity().notNull(),hubId:De("hub_id",{mode:"number"}).notNull(),uploadedBy:De("uploaded_by",{mode:"number"}),sourceKey:ie("source_key",{length:200}).notNull(),fileName:ie("file_name",{length:255}).notNull(),filePath:ie("file_path",{length:"max"}).notNull(),fileType:ie("file_type",{length:100}),fileSize:De("file_size",{mode:"number"}),objectCheckedAt:Ie("object_checked_at"),objectMissingAt:Ie("object_missing_at"),createdAt:Ie("created_at").notNull(),createdBy:ie("created_by",{length:50}).notNull(),updatedAt:Ie("updated_at").notNull(),updatedBy:ie("updated_by",{length:50}).notNull()},u=>[kt({name:`${e}_DailyReportAttachment_pk`,columns:[u.id]}),Ge({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),Ge({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[u.uploadedBy],foreignColumns:[n.id]}),_m(`${e}_DailyReportAttachment_source_unique`).on(u.hubId,u.sourceKey),gt(`${e}_DailyReportAttachment_hub_id_index`).on(u.hubId,u.createdAt)]);return{hub:o,internal:a,comment:i,attachment:d,label:l,hubLabel:s,userStatus:c}}import{bigint as Do,binary as cl,datetime2 as Cm,int as Mm,mssqlSchema as Pm,nvarchar as on,primaryKey as ul,varchar as Lm}from"drizzle-orm/mssql-core";function km(e){let t=Pm(e),r=t.table("DailyReportSearchDocument",{hubId:Do("hub_id",{mode:"number"}).notNull(),searchText:on("search_text",{length:"max"}).notNull(),sourceDigest:cl("source_digest",{length:32}).notNull(),normalizerVersion:Lm("normalizer_version",{length:64}).notNull(),indexedAt:Cm("indexed_at").notNull(),rowVersion:cl("row_version",{length:8}).notNull(),authorName:on("author_name",{length:ot.maxValueLength}),customerName:on("customer_name",{length:ot.maxValueLength})},o=>[ul({name:`${e}_DailyReportSearchDocument_pk`,columns:[o.hubId]})]),n=t.table("DailyReportSearchComment",{hubId:Do("hub_id",{mode:"number"}).notNull(),ordinal:Mm("ordinal").notNull(),authorUserId:Do("author_user_id",{mode:"number"}),commentText:on("comment_text",{length:"max"}).notNull()},o=>[ul({name:`${e}_DailyReportSearchComment_pk`,columns:[o.hubId,o.ordinal]})]);return{document:r,comment:n}}var Nm=5e7,Dl=2e8,vm=1,Tl=Object.freeze({fixedBytes:4*1024*1024,pipelineRows:2048,wholeImageBuffer:Object.freeze({"jpeg-single-scan":Object.freeze({kind:"none"}),"jpeg-multi-scan":Object.freeze({kind:"jpeg-coefficients"}),png:Object.freeze({kind:"none"}),"png-interlaced":Object.freeze({kind:"decoded-raster"}),gif:Object.freeze({kind:"canvas",bytesPerPixel:4}),"webp-lossy":Object.freeze({kind:"none"}),"webp-lossy-alpha":Object.freeze({kind:"canvas",bytesPerPixel:5}),"webp-lossless":Object.freeze({kind:"canvas",bytesPerPixel:4}),"webp-animated":Object.freeze({kind:"canvas",bytesPerPixel:9})})}),dl=125,pl=4,ml=16,yl=50,hl=2,an=Object.freeze({renderMs:ve.renderMs,nanosecondsPerBlockVisit:dl,margin:pl,maxBlockVisits:Math.floor(ve.renderMs*1e6/(dl*pl)),walkBudgetMs:ml,nanosecondsPerWalkStep:yl,walkMargin:hl,maxWalkSteps:Math.floor(ml*1e6/(yl*hl))}),Om=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),fl=75,Rl=4,Sl="#ffffff",Fm=1,Hm={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},Bm=[/out of memory/i,/insufficient memory/i,/memory allocation|allocation failed/i,/(?:cannot|could not|unable to|failed to) allocate/i,/picture memory error/i,/unable to create thread|error creating thread|resource temporarily unavailable/i,/too many open files|no space left on device/i,/\b(?:ENOMEM|EAGAIN|EMFILE|ENFILE|ENOSPC)\b/],gl=Object.freeze({ok:!1,reason:"failed"}),bl=Object.freeze({ok:!1,reason:"unsupported"}),Al=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:za(e)}),El=(e,t)=>{switch(t){case"jpeg":{let r=Gn(e);return r===null?null:Al(r)}case"png":{let r=Ja(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=Qa(e,an.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},wl=(e,t)=>{let r=Om.get(t.depth);if(r===void 0)return null;let n=t.channels*r,o=Tl,a=o.wholeImageBuffer[e.layout];return(a.kind==="none"?0:a.kind==="decoded-raster"?t.width*t.height*n:a.kind==="jpeg-coefficients"?e.coefficientBytes:t.width*t.height*a.bytesPerPixel)+o.pipelineRows*t.width*n+o.fixedBytes},Um=(e,t,r)=>{let n=El(e,t);return n===null?null:wl(n,r)},$m=e=>e!==null&&e<=Dl,Vm=(e,t)=>{if(t!=="jpeg")return El(e,t);let r=Ga(e,an);return r===null||r.blockVisits>an.maxBlockVisits?null:Al(r.header)},Ym=e=>{let t=e instanceof Error?e.message:"";return Bm.some(r=>r.test(t))?"failed":"unsupported"},qm=e=>{e.cache(!1),e.concurrency(vm),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(Hm)});let t=async(n,o,a,i,l)=>{let s=Vm(n,o);if(s===null)return bl;try{let c=e(n,{limitInputPixels:Nm,animated:!1});if(!$m(wl(s,await c.metadata())))return bl;if(l.aborted)return gl;let d=await c.rotate().resize({width:a,height:i,fit:"inside",withoutEnlargement:!0}).flatten({background:Sl}).webp({quality:fl,effort:Rl}).toBuffer();return{ok:!0,bytes:new Uint8Array(d),contentType:"image/webp"}}catch(c){return{ok:!1,reason:Ym(c)}}},r=async(n,{format:o,maxWidth:a,maxHeight:i,signal:l})=>l.aborted?gl:t(n,o,a,i,l);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${fl}-e${Rl}/flatten-${Sl}/v${Fm}`,render:r}};function fb(e){e.redis||he(e.logger,2,"Server").warn("redis provider is not injected: cross-worker cache invalidation is disabled (staleness is bounded only by TTL) and SSE publishing is skipped.");let t=yn(e.redis),r=new Gt({defaultTtlMs:e.cacheDefaultTtlMs,maxBuckets:e.cacheMaxBuckets,maxBytes:e.cacheMaxBytes},t),n=bo({...e,cache:r,epochs:t}),o=new cr({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),a=lo({authenticate:e.authenticate,resolveVisibleSourceTypes:e.resolveVisibleSourceTypes,service:n,encodeUserId:e.encodeUserId,redis:e.redis,sseReader:o,streamKey:n.streamKey,loginRedirectPath:e.loginRedirectPath,enableDevCacheClear:e.enableDevCacheClear,logger:e.logger});return{service:n,cache:r,epochs:t,sseReader:o,streamKey:n.streamKey,knownSourceTypes:n.searchFilterSourceTypes,...a}}export{Jn as DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,Kn as DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,Dl as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,an as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL,Tl as DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,so as DAILY_REPORT_SSE_CATCH_UP_BATCH,is as DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,cr as DailyReportSseReader,He as DailyReportViewerScope,Gt as SqlResultCache,il as buildDailyReportSseStreamKey,lo as createDailyReportHandlers,fb as createDailyReportServer,bo as createDailyReportService,yn as createEpochStore,qm as createSharpThumbnailRenderer,xm as defineDailyReportSchema,km as defineDailyReportSearchSchema,Ft as encodeIdsStreamRows,ht as isStreamIdLte,kn as parseClientTempId,Um as predictSharpThumbnailWorkingSetBytes,lr as readDailyReportSseStreamEntry,Tm as transformJsonArray};
12
12
  /* v8 ignore next -- @preserve 到達不能: 時間切れと中断の購読はどちらも cleanup で同時に外れ、枠を渡すときも先に cleanup するので、列にいない待機者でここへは来ない。それでも splice(-1) が別の待機者を消さないよう残す */