@aiquants/daily-report 0.33.0 → 0.34.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,5 +1,5 @@
1
- var Lr=e=>{throw TypeError(e)};var Nr=(e,t,r)=>t.has(e)||Lr("Cannot "+r);var ut=(e,t,r)=>(Nr(e,t,"read from private field"),r?r.call(e):t.get(e)),Zt=(e,t,r)=>t.has(e)?Lr("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),er=(e,t,r,n)=>(Nr(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var te=()=>Math.floor(performance.now());var tr=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{}}}),ct=class{constructor(t,r){this.config=t;this.epochStore=r;this.buckets=new Map;this.inFlight=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.config.defaultTtlMs;if(a-(o.expireAt-te())<a*r||this.inFlight.has(n))return;let l;l=(async()=>{let y=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,i=await t.fetcher();return this.inFlight.get(n)===l&&this.buckets.set(n,{records:i,expireAt:te()+a,epoch:y}),i})(),this.inFlight.set(n,l),l.catch(()=>{}).finally(()=>{this.inFlight.get(n)===l&&this.inFlight.delete(n)})};this.getOrFetch=async t=>{let{cacheKey:r,forceRefresh:n,snapshot:o}=t,a=this.buckets.get(r);if(n&&(this.buckets.delete(r),this.inFlight.delete(r)),!n&&a&&a.expireAt>te())if(t.epochKey){let l=await this.epochStore.getEpoch(t.epochKey);if(l===null||a.epoch===l)return this.maybeRefreshAhead(t),o?a.records.map(y=>structuredClone(y)):a.records;this.buckets.delete(r)}else return this.maybeRefreshAhead(t),o?a.records.map(l=>structuredClone(l)):a.records;if(!n&&this.inFlight.has(r)){let l=await this.inFlight.get(r);return o?l.map(y=>structuredClone(y)):l}let s;s=(async()=>{let l=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null;t.onFetchStart?.();let y=await t.fetcher();if(n||this.inFlight.get(r)===s){let i=te()+(t.ttlMsOverride??this.config.defaultTtlMs);this.buckets.set(r,{records:y,expireAt:i,epoch:l}),this.buckets.size>500&&this.cleanExpired()}return y})(),n||this.inFlight.set(r,s);try{let l=await s;return o?l.map(y=>structuredClone(y)):l}finally{this.inFlight.get(r)===s&&this.inFlight.delete(r)}};this.clearAll=()=>{this.buckets.clear(),this.inFlight.clear()};this.invalidatePrefix=t=>{for(let r of this.buckets.keys())r.startsWith(t)&&this.buckets.delete(r);for(let r of this.inFlight.keys())r.startsWith(t)&&this.inFlight.delete(r)}}cleanExpired(){let t=te();for(let[r,n]of this.buckets.entries())n.expireAt<=t&&this.buckets.delete(r)}};var Or="ids-stream";var _t=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 s=0;s<a.length;s++){let l=a.charCodeAt(s);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+(?=.)/,"")},Et=(e,t)=>e.businessDate!==t.businessDate?e.businessDate===null?1:t.businessDate===null||e.businessDate>t.businessDate?-1:1:t.reportHubId-e.reportHubId,kr=e=>{for(let t=1;t<e.length;t++)if(Et(e[t-1],e[t])>0)return!1;return!0},Br=(e,t)=>{let r=e.findIndex(n=>Et({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var Ce=Object.freeze({businessDate:"business-date",idsStream:Or,report:"report",action:"action"}),_e=Object.freeze({businessDate:"businessDate",reportHubId:"reportHubId",forceRefresh:"forceRefresh",cursorReportHubId:"cursor_report_hub_id",cursorBusinessDate:"cursor_business_date",cursorSnapshot:"cursor_snapshot"});var ra=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var Ur=e=>e<10?`0${e}`:`${e}`,na=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=Ur(e.getMonth()+1),n=Ur(e.getDate());return`${t}-${r}-${n}`},Ke=e=>{let t=ra.exec(e);if(t===null)return null;let[,r,,n,o]=t,a=Number(r),s=Number(n),l=Number(o);if(a<1)return null;let y=new Date(0);return y.setUTCFullYear(a,s-1,l),y.getUTCFullYear()!==a||y.getUTCMonth()!==s-1||y.getUTCDate()!==l?null:`${r}-${n}-${o}`},It=e=>Ke(e)===e;var fe=e=>e==null?null:e instanceof Date?na(e):Ke(e);var ce=(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)}}};import{z as el}from"zod";var wt=/^(?:[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 g}from"zod";var Hr=15e3,Fr="lastEventId",oa=/^\d{1,15}-\d{1,15}$/,$r=e=>oa.test(e),aa=g.object({name:g.string().nullish(),affiliation:g.string().nullish()}),ia=g.object({name:g.string().nullish(),text:g.string().nullish(),color:g.string().nullish()}),sa=g.object({id:g.number(),name:g.string().nullish(),color:g.string().nullish()}),Yr=g.object({id:g.number(),userId:g.string().nullish(),userName:g.string().nullish(),content:g.string().nullish(),createdAt:g.string().nullish(),isMine:g.boolean()}),la=g.object({id:g.string(),fileName:g.string(),fileType:g.string().nullable(),fileSize:g.number().nullable(),createdAt:g.string().nullable(),state:g.enum(["present","absent","unknown"]),hasThumbnail:g.boolean().default(!1)}),rr=g.object({reportHubId:g.number(),date:g.string().nullish(),createdAt:g.string().nullish(),author:g.string().nullish(),userId:g.string().nullish(),sourceType:g.string().nullish(),employeeName:g.string().nullish(),updatedBy:g.string().nullish(),updatedAt:g.string().nullish(),category:g.string().nullish(),creationCategory:g.string().nullish(),visitTimeFrom:g.string().nullish(),visitTimeTo:g.string().nullish(),customerName:g.string().nullish(),interviewers:g.array(aa),subject:g.string().nullish(),content:g.string().nullish(),externalComments:g.array(ia),isRead:g.boolean(),isStarred:g.boolean(),labels:g.array(sa),postedComments:g.array(Yr),attachments:g.array(la).default([])}),Ue=g.string().regex(wt),ua=g.object({type:g.literal("connected")}),xt=g.object({type:g.literal("status-update"),reportHubId:g.number(),statusType:g.enum(["star","read"]),value:g.boolean(),clientTempId:Ue,recipientRawUserId:g.number().optional()}),nr=g.string().optional(),or=g.object({type:g.literal("comment-add"),reportHubId:g.number(),comment:Yr,clientTempId:Ue,recipientRawUserId:g.number().optional(),sourceType:nr}),ar=g.object({type:g.literal("comment-delete"),reportHubId:g.number(),commentId:g.number(),clientTempId:Ue,recipientRawUserId:g.number().optional(),sourceType:nr}),ir=g.object({type:g.literal("report-create"),reportHubId:g.number(),report:rr,clientTempId:Ue,recipientRawUserId:g.number().optional()}),sr=g.object({type:g.literal("report-update"),reportHubId:g.number(),report:rr,clientTempId:Ue,recipientRawUserId:g.number().optional()}),lr=g.object({type:g.literal("report-publish"),reportHubId:g.number(),report:rr,clientTempId:Ue,recipientRawUserId:g.number().optional()}),ur=g.object({type:g.literal("report-delete"),reportHubId:g.number(),clientTempId:Ue,sourceType:nr}),Vr=g.discriminatedUnion("type",[ua,xt,or,ar,ir,sr,lr,ur]);var Re=Object.freeze({intent:"intent",clientTempId:"clientTempId",businessDate:"businessDate",operationTimestamp:"operationTimestamp",reportHubId:"reportHubId",title:"title",content:"content",isStarred:"isStarred",isRead:"isRead",commentId:"commentId"});var Ct=Math.max(1,Math.floor(10.556701030927835));var Se=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var Je=e=>{let{windowMs:t,tallies:r,writeSuppressed:n}=e,o=new Map,a=s=>{let l={since:new Date().toISOString(),count:0,tallies:Object.fromEntries(r.map(i=>[i,0]))};o.set(s,l),Se(()=>{o.delete(s),l.count>0&&n(s,l)},t)};return{record:(s,l,y)=>{let i=o.get(s);if(i!==void 0){i.count+=1,i.tallies[l]+=1;return}y(),a(s)}}};var cr=e=>e!==null&&wt.test(e)?e:null,ca=/^[1-9][0-9]*$/,da=/^(?:0|[1-9][0-9]*)$/,dr=e=>Number.isSafeInteger(e)&&e>0,He=e=>{if(e===null||!ca.test(e))return null;let t=Number(e);return dr(t)?t:null},mr=e=>{if(e===null||!da.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},pr=e=>e==="true"?!0:e==="false"?!1:null,dt=e=>e===null?!1:pr(e),qr=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var zr=Object.freeze({status:400,error:"Invalid form"}),Wr=e=>({status:413,error:"Form too large",measuredBy:e}),ma=(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)}}))},pa=async e=>{let t=mr(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:Wr("declared")};let r=!1,n=e.body===null?null:ma(e.body,1048576,()=>{r=!0}),o=new Headers,a=e.headers.get("Content-Type");a!==null&&o.set("Content-Type",a);let s;try{s=await new Response(n,{headers:o}).formData()}catch{return{refusal:r?Wr("counted"):zr}}let l=qr(s);return l===null?{refusal:zr}:{fields:l}},Kr=(e,t)=>(r,n)=>{let o=r.get(t);if(o===null)return{error:`${t} required`};let a=pr(o);return a===null?{error:`Invalid ${t}`}:{command:{...n,intent:e,value:a}}},Gr=Object.freeze({update:(e,t,r)=>{let n=e.get(Re.title),o=e.get(Re.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:Kr("toggleStar",Re.isStarred),toggleRead:Kr("toggleRead",Re.isRead),addComment:(e,t)=>{let r=e.get(Re.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=He(e.get(Re.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),ya=e=>Object.hasOwn(Gr,e),ha=(e,t)=>{let r=e.get(Re.intent),n=e.get(Re.businessDate),o=n===null?null:Ke(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get(Re.operationTimestamp),s=mr(a);if(a!==null&&s===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get(Re.clientTempId);if(!l)return{error:"clientTempId required"};let y=cr(l);if(y===null)return{error:"Invalid clientTempId"};if(r==="create")return o===null?{error:"businessDate required"}:{command:{intent:r,clientTempId:y,businessDate:o,operationTimestamp:s}};let i=He(e.get(Re.reportHubId));return i===null?{error:"Invalid reportHubId"}:r===null||!ya(r)?{error:"Invalid intent"}:Gr[r](e,{clientTempId:y,businessDate:o,operationTimestamp:s,reportHubId:i},t)},Xr=async(e,t)=>{let r=await pa(e);if("refusal"in r)return r;let n=ha(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},fa=6e4,Ra="form_too_large",Jr=["declared","counted"],Qr=e=>{let t=Je({windowMs:fa,tallies:Jr,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${Jr.map(s=>`${s}:${a[s]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(Ra,r,n)}};var Pt=Object.freeze({[Ce.businessDate]:"json",[Ce.idsStream]:"stream",[Ce.report]:"json"}),Zr=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),yr=e=>e!==void 0&&Object.hasOwn(Pt,e);var hr=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),en=e=>Object.hasOwn(hr,e);var ga="download",ba="thumbnail",Sa="1";var fr=e=>{let t=e.getAll(ba),r=e.getAll(ga);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&en(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===Sa?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};var gr="Cross-site request rejected",Aa="Not Found",Ta=new Set(["same-origin","none"]),Da=new Set(["GET","HEAD","OPTIONS"]),tn=["api","action","sse","attachment"],rn=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}}),_a=()=>rn(403,gr),Mt=()=>rn(404,Aa),mt=Object.freeze({navigable:()=>!1,frameworkDataRefusal:()=>null,crossSiteRejection:_a}),nn=e=>new URL(e.url).pathname.endsWith(".data"),Ea=e=>{let t=e.headers.get("Origin");return t===null?!0:URL.canParse(t)&&new URL(t).host===new URL(e.url).host},on=(e,t)=>{let r=e.headers.get("Sec-Fetch-Site");return r===null?!(Da.has(e.method)||Ea(e)):Ta.has(r)?!1:!(e.method==="GET"&&e.headers.get("Sec-Fetch-Mode")==="navigate"&&e.headers.get("Sec-Fetch-Dest")==="document"&&t.navigable(e))},Ia=6e4,wa="refusals",xa=32,Ca=/^[a-z-]+$/,Rr=e=>{if(e===null)return"-";let t=e.slice(0,xa);return Ca.test(t)&&t===e?e:JSON.stringify(t)},an=e=>{let t=Je({windowMs:Ia,tallies:tn,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${tn.map(s=>`${s}:${a[s]}`).join(",")}`)}});return(r,n)=>{let o=()=>{let{headers:a}=n;e.warn(`cross_site_rejected route=${r} site=${Rr(a.get("Sec-Fetch-Site"))} mode=${Rr(a.get("Sec-Fetch-Mode"))} dest=${Rr(a.get("Sec-Fetch-Dest"))} method=${n.method}`)};t.record(wa,r,o)}};var sn=(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 Pa=5e3/1e3,Ma=new Map([[503,Pa]]),pt=e=>{let t=Ma.get(e);return t===void 0?{}:{"Retry-After":String(t)}},va="same-origin",La="SAMEORIGIN",Ge=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":va,"X-Frame-Options":La}),vt=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...Ge});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},ln=(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},un=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),Na=/^[\x20-\x7E]+$/,Oa=/^[\w.+-]+\/[\w.+-]+/,br=e=>e&&Na.test(e)&&Oa.test(e)?e:null,cn=e=>encodeURIComponent(e).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),dn=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),Lt={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},mn={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},Nt=e=>typeof e=="string"&&Object.hasOwn(mn,e),Ot=e=>mn[e],Pe="Attachment request failed";var ka=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,me=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${ka(r)}`),Xe=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`);var Ba=32*1024*1024,Ua=60,Ha=4,Fa=120,$a=2,Ya=8*1024*1024,oe=(e,t,r)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r)return t;throw me(e,`an integer >= ${r}`,t)},Qe=(e,t,r,n)=>t===void 0?n:oe(e,t,r),kt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Va=e=>{if(e===void 0)throw Xe("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!kt(e))throw me("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw Xe("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw me("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw me("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},qa=e=>{if(e===void 0)return null;if(!kt(e))throw me("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:Va(e.renderer),rateLimitPerMinute:Qe("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,Fa),concurrency:Qe("attachments.thumbnails.concurrency",e.concurrency,1,$a),cacheBytes:Qe("attachments.thumbnails.cacheBytes",e.cacheBytes,0,Ya)})},pn=e=>{let t=e;if(t===void 0)return null;if(!kt(t))throw me("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw Xe("attachments.idCodec","injected when attachments is given");if(!kt(r)||typeof r.encode!="function"||typeof r.decode!="function")throw me("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw Xe("attachments.read","injected when attachments is given");if(typeof n!="function")throw me("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:Qe("attachments.maxBytes",t.maxBytes,1,Ba),rateLimitPerMinute:Qe("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,Ua),concurrency:Qe("attachments.concurrency",t.concurrency,1,Ha),thumbnails:qa(t.thumbnails)})},ja=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"]]),Bt=e=>{for(let[t,r]of ja)if(Object.hasOwn(e,t))throw Xe(r,`given in place of the flat key ${t}`)};var za=1024,Wa="Too many requests",Ka=(e,t)=>{oe("limitPerWindow",e,1),oe("windowMs",t,1);let r=new Map,n=(a,s)=>{s<=a.lastRefillMs||(a.tokens=Math.min(e,a.tokens+(s-a.lastRefillMs)*e/t),a.lastRefillMs=s)},o=(a,s)=>{let l=r.get(a);l&&r.delete(a);let y=l??{tokens:e,lastRefillMs:s};n(y,s),r.set(a,y);for(let i of r.keys()){if(r.size<=za)break;r.delete(i)}return y};return{consume:(a,s)=>{let l=o(a,s);return l.tokens<1?!1:(l.tokens-=1,!0)},refund:(a,s,l)=>{let y=r.get(a);y&&(n(y,s),y.tokens=Math.min(e,y.tokens+l))}}},Ze=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(oe("windowMs",r,1e3)%1e3!==0)throw me("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=Ka(e.limitPerWindow,r),s=Object.freeze({status:429,message:Wa,headers:Object.freeze({"Retry-After":String(r/1e3)})}),l=Je({windowMs:r,tallies:[t],writeSuppressed:(y,{count:i,since:_})=>{n.warn(`${t}_suppressed count=${i} since=${_} ${o(y)}`)}});return{spend:(y,i)=>a.consume(y,te())?null:(l.record(y,t,()=>n.warn(`429 ${i} reason=${t}`)),s),refund:(y,i)=>{a.refund(y,te(),i)}}};var Ut=e=>{let t=oe("limit",e.limit,1),r=oe("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:oe("queue.max",e.queue.max,0),maxPerOwner:oe("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:oe("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],s=new Map,l=new Map,y=(d,R)=>d.get(R)??0,i=(d,R,x)=>{let P=y(d,R)+x;P<=0?d.delete(R):d.set(R,P)},_=d=>y(l,d)<r,m=d=>(o+=1,i(l,d,1),h(d)),A=()=>{for(;o<t;){let d=a.findIndex(x=>_(x.owner));if(d<0)return;let[R]=a.splice(d,1);i(s,R.owner,-1),R.grant(m(R.owner))}},h=d=>{let R=!1;return()=>{R||(R=!0,o-=1,i(l,d,-1),A())}};return{acquire:(d,R)=>{if(R.aborted)return Promise.resolve(null);if(o<t&&_(d))return Promise.resolve(m(d));if(n===null||a.length>=n.max||y(s,d)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:x}=n,P=C=>{let $=()=>{let V=a.indexOf(U);V<0||(a.splice(V,1),i(s,d,-1),I(),C(null))},T=Se($,x),I=()=>{clearTimeout(T),R.removeEventListener("abort",$)},U={owner:d,grant:V=>{I(),C(V)}};a.push(U),i(s,d,1),R.addEventListener("abort",$,{once:!0})};return new Promise(P)}}};var Ga=256*1024,yn=6e4,Xa=e=>Math.ceil(e/2),Qa=new Uint8Array(new ArrayBuffer(0)),Za=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=Qa,t()},s=l=>{clearTimeout(o),o=Se(()=>{l.error(new Error(`attachment body idle for ${yn} ms`)),a()},yn)};return new ReadableStream({start(l){s(l)},pull(l){let y=Math.min(n+Ga,r.byteLength);if(y>n&&l.enqueue(r.slice(n,y)),n=y,n>=r.byteLength){l.close(),a();return}s(l)},cancel(){a()}},{highWaterMark:0})},hn=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,s=Ze({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:y=>`viewer=${y}`}),l=Ut({limit:e.concurrency,maxHeldPerOwner:Xa(e.concurrency),queue:null});return async y=>{let{request:i,delivery:_,attachmentId:m,internalUserId:A,readAttachment:h,cookie:d,fail:R}=y,x=e.maxBytes,P=s.spend(A,`attachment=${m} viewer=${A}`);if(P)return R(P.status,P.message,P.headers);let C=await n(i),$=await t.getAttachmentForUser(C,m,A);if(!$)return o.warn(`404 attachment=${m} viewer=${A} reason=not_visible`),R(404,"Attachment not found");if($.fileSize!=null&&$.fileSize>x)return o.warn(`413 attachment=${m} viewer=${A} reason=db_size`),R(413,"Attachment too large");let T=await l.acquire(A,i.signal);if(!T)return i.signal.aborted?(o.info(`503 attachment=${m} viewer=${A} reason=aborted`),R(503,"Attachment request aborted")):(o.warn(`503 attachment=${m} viewer=${A} reason=concurrency`),R(503,"Too many concurrent downloads",pt(503)));let I=!1;try{let U=await h($.filePath,{maxBytes:x,head:i.method==="HEAD",principal:r(A),signal:i.signal});if(i.signal.aborted)return o.info(`503 attachment=${m} viewer=${A} reason=aborted`),R(503,"Attachment request aborted");if(!U.ok){if(!Nt(U.reason))return o.error(`500 attachment=${m} viewer=${A} reason=port_contract code=failure_reason`),R(500,Pe);let S=Ot(U.reason);return U.reason==="not_found"&&a(m,!1),o.warn(`${S} attachment=${m} viewer=${A} reason=${U.reason} code=${U.code??"-"}`),R(S,Lt[S],pt(S))}if(U.bytes.byteLength>x)return o.error(`500 attachment=${m} viewer=${A} reason=port_contract code=over_max_bytes`),R(500,Pe);let V=i.method==="HEAD";if(V&&U.size!==void 0&&U.size>x)return o.error(`500 attachment=${m} viewer=${A} reason=port_contract code=over_max_bytes`),R(500,Pe);if(!V&&U.size!==void 0&&U.size!==U.bytes.byteLength)return o.error(`500 attachment=${m} viewer=${A} reason=port_contract code=size_mismatch`),R(500,Pe);let z=br($.fileType)??br(U.contentType),G=z!==null&&un.has(z),K=G?z:"application/octet-stream",b=G&&_.kind!=="download"?"inline":"attachment",M=V?U.size:U.bytes.byteLength,L=new Headers({"Content-Type":K,"Content-Disposition":`${b}; filename="${dn($.fileName)}"; filename*=UTF-8''${cn($.fileName)}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...Ge});return M!==void 0&&L.set("Content-Length",String(M)),d&&L.append("Set-Cookie",d),a(m,!0),o.info(`200 attachment=${m} viewer=${A} type=${K} disposition=${b} bytes=${M??"-"}`),V?new Response(null,{status:200,headers:L}):(I=!0,new Response(Za(U.bytes,T),{status:200,headers:L}))}finally{I||T()}}};var ye=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),Hl=ye.queueWaitMs+ye.readMs+ye.renderMs+ye.transferMarginMs;import{createHash as ei}from"crypto";var yt=e=>{let t=JSON.stringify(e);return`"${ei("sha256").update(t).digest("hex")}"`};import{Buffer as ti}from"buffer";var gn=new Set([194,198,202,206]),ri=new Set([192,193,194,195]),bn=216,ni=217,Sn=218,oi=4,ai=64,ii=2,fn=8,Rn=28,Le=12,Sr=8,si=20,An=Le+Sr+10,li=2,Me=(e,t)=>e[t]<<8|e[t+1],et=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];return n},Ee=(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},Tn=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,Dn=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),_n=e=>(e.stepsLeft-=1,e.stepsLeft>=0),En=e=>e[0]===255&&e[1]===bn,In=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!_n(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===ni)return"eoi";if(o===0||o===bn)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=Me(e,n),s=n+a;return a<2||s>e.byteLength?null:(r.marker=o,r.body=n+2,r.length=a,r.end=s,"segment")}},ui=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!_n(r))return null;if(a+1>=n)return n;let s=e[a+1];if(s===255)a+=1;else if(s===0||s>=208&&s<=215){if(a+=2,a>=n||e[a]!==255)break}else return a}o=a}},wn=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=Me(e,r+1),a=Me(e,r+3),s=e[r+5];if(a===0||o===0||s===0||n!==8+3*s)return null;let l=[];for(let y=0;y<s;y+=1){let i=e[r+7+3*y],_=i>>4,m=i&15;if(_<1||_>4||m<1||m>4)return null;l.push({id:e[r+6+3*y],horizontal:_,vertical:m})}return{marker:t,width:a,height:o,components:l}},xn=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>oi||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},Cn=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:gn.has(e.marker)||t<e.components.length}),Ar=e=>{if(!En(e))return null;let t=Dn(e.byteLength),r=null;for(let n=2;;){if(In(e,n,t)!=="segment")return null;if(Tn(t.marker)){if(r!==null||(r=wn(e,t),r===null))return null}else if(t.marker===Sn){if(r===null)return null;let o=xn(e,t);return o===null?null:Cn(r,o.length)}n=t.end}},Pn=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*fn)),s=Math.ceil(e.height*o/(r*fn));return Math.ceil(a/n)*n*Math.ceil(s/o)*o})},Mn=e=>e.multiScan?Pn(e).reduce((r,n)=>r+n,0)*ai*ii:0,ci=896,vn=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!En(e))return null;let n=ti.from(e.buffer,e.byteOffset,e.byteLength),o=Dn(r),a=null,s=null,l=new Map,y=0,i=0,_=0;for(let m=2;;){let A=In(e,m,o);if(A===null)return null;if(A==="eoi")return s===null?null:{header:s,blockVisits:i};if(m=o.end,Tn(o.marker)){if(a!==null||!ri.has(o.marker)||(a=wn(e,o),a===null))return null;let h=Pn(a);l=new Map;for(let[d,R]of a.components.entries()){let x=l.get(R.id);l.set(R.id,x===void 0?h[d]:Math.max(x,h[d]))}y=a.components.length*(gn.has(a.marker)?ci:1)}else if(o.marker===Sn){if(a===null||_===y)return null;let h=xn(e,o);if(h===null)return null;for(let R of h){let x=l.get(R);if(x===void 0)return null;i+=x}if(_+=1,s===null&&(s=Cn(a,h.length)),i>t||!s.multiScan)return{header:s,blockVisits:i};let d=ui(n,o.end,o);if(d===null)return null;m=d}}},Ln=e=>{if(e.byteLength<24||Me(e,8)!==0||Me(e,10)!==13||!Ee(e,12,"IHDR"))return null;let t=Me(e,16)*65536+Me(e,18),r=Me(e,20)*65536+Me(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},di=e=>{if(Ee(e,Le,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=et(e,26,2)&16383,r=et(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(Ee(e,Le,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=et(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return Ee(e,Le,"VP8X")?e.byteLength<An?null:{width:et(e,24,3)+1,height:et(e,27,3)+1}:null},Nn=e=>{if(Ln(e)===null||e.byteLength<=Rn)return null;switch(e[Rn]){case 0:return!1;case 1:return!0;default:return null}},On=(e,t)=>{if(Ee(e,Le,"VP8 "))return"lossy";if(Ee(e,Le,"VP8L"))return"lossless";if(!Ee(e,Le,"VP8X")||e.byteLength<An)return null;if((e[si]&li)!==0)return"animated";let r=!1,n=t;for(let o=Le;o+Sr<=e.byteLength;){if(n-=1,n<0)return null;if(Ee(e,o,"VP8L"))return"lossless";if(Ee(e,o,"VP8 "))return r?"lossy-alpha":"lossy";Ee(e,o,"ALPH")&&(r=!0);let a=et(e,o+4,4);o+=Sr+a+a%2}return null},kn={png:Ln,jpeg:Ar,webp:di};var Tr=Object.freeze(["image/webp","image/jpeg","image/png"]),Dr=1024*1024;var mi=new Set(["image/png","image/jpeg","image/gif","image/webp"]),pi={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},yi=new Set(Tr),hi=e=>typeof e=="string"&&yi.has(e),fi=256,Ht=(e,t)=>e.fileType===null||!mi.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,Ri=[137,80,78,71,13,10,26,10],gi=[255,216,255],bi=[[71,73,70,56,55,97],[71,73,70,56,57,97]],Si=[82,73,70,70],Ai=[87,69,66,80],ht=(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},_r=e=>{if(ht(e,Ri,0))return"png";if(ht(e,gi,0))return"jpeg";for(let t of bi)if(ht(e,t,0))return"gif";return ht(e,Si,0)&&ht(e,Ai,8)?"webp":null},Bn=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:yt([t])}},Un=(e,t)=>{if(!hi(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>Dr)return"too_large";let r=pi[e.contentType];if(_r(e.bytes)!==r)return"signature";let n=kn[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},Hn=e=>{oe("maxBytes",e.maxBytes,0),oe("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 s=(a.kind==="thumbnail"?a.bytes.byteLength:0)+fi;if(s>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:s}),r+=s;for(let y of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(y)}}}};var Er=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,s=te(),l=new AbortController,y=!1,i,_,m=()=>{a(te()-s)},A=T=>{i=Se(()=>{y=!0,T({timedOut:!0}),_=Se(m,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},h=new Promise(A),d=AbortSignal.any([r,l.signal]),R=T=>{T(n(d))},x=new Promise(R),P=T=>(clearTimeout(i),clearTimeout(_),y&&o(te()-s,T.kind==="error"?{error:T.error}:null),T),C=x.then(T=>P({kind:"value",value:T}),T=>P({kind:"error",error:T}));return{outcome:Promise.race([x.then(T=>({timedOut:!1,value:T})),h]),settled:C}};var Ne={404:"Attachment not found",500:Pe,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},Fn=(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=Un(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},Ti=e=>{let t=new AbortController,r=()=>{t.abort()},n=Se(r,ye.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},$n=()=>{},Di=(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)}),Yn=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:s}=e,l=new Map,y=(h,d)=>{let R=d.then($n,$n);l.set(h,R);let x=()=>{l.get(h)===R&&l.delete(h)};R.then(x)},i=async(h,d)=>{let R=l.get(h.key);if(R===void 0)return t.acquire(h.owner,d);let x=Ti(d);try{if(await Di(R,x.signal),x.signal.aborted)return null;let P=r.get(h.key);return P!==void 0?{...P,identity:"verified"}:await t.acquire(h.owner,x.signal)}finally{x.end()}},_=(h,d)=>{if(h.fileSize===null)return d.kind==="exact"?"verified":"unrecorded";if(d.kind==="exact"?d.bytes===h.fileSize:h.fileSize>d.maxBytes)return"verified";let x=d.kind==="exact"?String(d.bytes):`>${d.maxBytes}`;return s.warn(`size_mismatch expected=${h.fileSize} got=${x} attachment=${h.attachmentId} viewer=${h.owner} variant=thumbnail`),"unverified"},m=(h,d)=>(R,x)=>{let P=x===null?"":` message=${x.error instanceof Error?x.error.message:"unknown"}`;s.warn(`${h}_overrun ms=${R} attachment=${d.attachmentId} viewer=${d.owner} variant=thumbnail${P}`)},A=(h,d)=>R=>{s.warn(`${h}_stuck ms=${R} attachment=${d.attachmentId} viewer=${d.owner} variant=thumbnail`)};return async(h,d)=>{let R=await i(h,d);if(R===null)return{kind:"failure",status:503,reason:d.aborted?"aborted":"queue"};if(typeof R!="function")return R;let x=R,P=null;try{if(d.aborted)return{kind:"failure",status:503,reason:"aborted"};let C=r.get(h.key);if(C!==void 0)return{...C,identity:"verified"};let $=Er({budgetMs:ye.readMs,flightSignal:d,call:H=>h.readAttachment(h.filePath,{maxBytes:n,head:!1,principal:o(h.owner),signal:H}),onOverrun:m("read",h),onStuck:A("read",h)}),T=await $.outcome;if(T.timedOut)return P=$.settled,d.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(d.aborted)return{kind:"failure",status:503,reason:"aborted"};let I=T.value;if(!I.ok&&I.reason!=="too_large")return Nt(I.reason)?(I.reason==="not_found"&&a(h.attachmentId,!1),{kind:"failure",status:Ot(I.reason),reason:I.reason,code:I.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(I.ok&&I.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let U=_(h,I.ok?{kind:"exact",bytes:I.bytes.byteLength}:{kind:"over",maxBytes:n}),V=H=>{U==="verified"&&r.set(h.key,H)},z=H=>(V(H),{...H,identity:U});if(!I.ok)return z({kind:"unrenderable",reason:"too_large"});let G=_r(I.bytes);if(G===null)return z({kind:"unrenderable",reason:"signature"});let K=Er({budgetMs:ye.renderMs,flightSignal:d,call:H=>h.renderer.render(I.bytes,{format:G,maxWidth:h.box.maxWidth,maxHeight:h.box.maxHeight,signal:H}),onOverrun:m("render",h),onStuck:A("render",h)}),b=H=>{if(H.kind==="error")return;let v=Fn(H.value,h.box);"entry"in v&&V(v.entry)},M=null,L=()=>(M===null&&(M=K.settled.then(b),y(h.key,M)),M);d.addEventListener("abort",L,{once:!0});let S=await K.outcome.finally(()=>d.removeEventListener("abort",L));if(S.timedOut||d.aborted)return P=L(),d.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let N=Fn(S.value,h.box);return"entry"in N?z(N.entry):N.failure}finally{P===null?x():P.then(x,x)}}};var Vn=()=>{let e=new Map;return{join:(t,r,n)=>{let o=()=>{let y=new AbortController,i=()=>{e.get(t)?.controller===y&&e.delete(t)},m={promise:n(y.signal).finally(i),controller:y,waiters:0};return e.set(t,m),m},a=e.get(t)??o();a.waiters+=1;let s=()=>{a.waiters-=1,!(a.waiters>0)&&(a.controller.abort(),e.get(t)===a&&e.delete(t))};r.aborted?s():r.addEventListener("abort",s,{once:!0});let l=()=>{r.removeEventListener("abort",s)};return a.promise.finally(l)}}};var zn=10,_i=1/zn,qn=1-_i,Ei=1024,Ii=64,wi=8,jn="private, no-cache",xi="no-store",Ci=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),Pi=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},Wn=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:s,thumbnails:l}=e,{renderer:y}=l,i=(T,I)=>Ze({reason:T,limitPerWindow:I,windowMs:6e4,logger:o,windowFields:U=>`viewer=${U} variant=thumbnail`}),_=i("rate_limit",l.rateLimitPerMinute),m=i("revalidation_rate_limit",l.rateLimitPerMinute*zn),A=Ut({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:Ii,maxPerOwner:wi,maxWaitMs:ye.queueWaitMs}}),h=Hn({maxBytes:l.cacheBytes,maxEntries:Ei}),d=Vn(),R=Yn({gate:A,cache:h,maxBytes:s,encodeUserId:r,recordObjectState:a,logger:o}),x=(T,I,U,V)=>{let z=`attachment=${T.attachmentId} viewer=${T.internalUserId} variant=thumbnail cache=${V}`;if(I.kind==="failure")return o[Pi(I)](`${I.status} ${z} reason=${I.reason} code=${I.code??"-"}`),T.fail(I.status,Ne[I.status],pt(I.status));let G=Ci[I.identity];if(I.kind==="unrenderable")return o.info(`404 ${z} reason=${I.reason}${G}`),T.fail(404,Ne[404]);let K=I.identity==="verified"?{"Cache-Control":jn,ETag:U}:{"Cache-Control":xi},b=new Headers({"Content-Type":I.contentType,"Content-Length":String(I.bytes.byteLength),...K,"Content-Security-Policy":"default-src 'none'; sandbox",...Ge});return T.cookie&&b.append("Set-Cookie",T.cookie),o.info(`200 ${z} type=${I.contentType} bytes=${I.bytes.byteLength}${G}`),new Response(I.bytes,{status:200,headers:b})},P=(T,I)=>{let U=T.spend(I.internalUserId,`attachment=${I.attachmentId} viewer=${I.internalUserId} variant=thumbnail`);return U===null?null:I.fail(U.status,U.message,U.headers)},C=T=>P(_,T),$=(T,I)=>I?P(m,T):C(T);return async(T,I)=>{let{request:U,attachmentId:V,internalUserId:z,readAttachment:G,cookie:K,fail:b}=T,M=hr[I],L=U.headers.get("If-None-Match"),S=L!==null,N=$(T,S);if(N)return N;let H=await n(U),v=await t.getAttachmentForUser(H,V,z),j=v!==null&&Ht(v,s)?Bn({rendererId:y.id,box:M,attachmentId:V,filePath:v.filePath,fileType:v.fileType,fileSize:v.fileSize}):null;if(j&&ln(L,j.etag)){let se=new Headers({"Cache-Control":jn,ETag:j.etag,...Ge});return K&&se.append("Set-Cookie",K),o.info(`304 attachment=${V} viewer=${z} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:se})}if(S){let se=C(T);if(se)return se}if(!v)return o.warn(`404 attachment=${V} viewer=${z} variant=thumbnail reason=not_visible`),b(404,Ne[404]);if(!j)return _.refund(z,qn),o.info(`404 attachment=${V} viewer=${z} variant=thumbnail reason=not_eligible`),b(404,Ne[404]);let{key:O,etag:re}=j,be=h.get(O);if(be)return _.refund(z,qn),x(T,{...be,identity:"verified"},re,"hit");let De=se=>R({key:O,attachmentId:V,filePath:v.filePath,fileSize:v.fileSize,box:M,owner:z,readAttachment:G,renderer:y},se),St;try{St=await d.join(O,U.signal,De)}catch(se){return o.error(`500 attachment=${V} viewer=${z} variant=thumbnail cache=miss reason=port_exception message=${se instanceof Error?se.message:"unknown"}`),b(500,Ne[500])}return x(T,St,re,"miss")}};var Mi='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',vi=()=>vt(403,gr,{cookie:null}),Kn=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=fr(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>vt(404,Lt[404],{cookie:null}),crossSiteRejection:vi}),Jn=e=>{let{authenticate:t,service:r,encodeUserId:n,resolveViewerScope:o,logger:a}=e,s=r.attachmentDelivery,l={service:r,encodeUserId:n,resolveViewerScope:o,logger:a,recordObjectState:sn(r,a)},y=s===null?null:{idCodec:s.idCodec,read:s.read,serveOriginal:hn({...l,maxBytes:s.maxBytes,rateLimitPerMinute:s.rateLimitPerMinute,concurrency:s.concurrency}),serveThumbnail:s.thumbnails===null?null:Wn({...l,maxBytes:s.maxBytes,thumbnails:s.thumbnails})};return async({request:i,params:_})=>{let m=null,A=(h,d,R={})=>vt(h,d,{cookie:m,extraHeaders:R});try{let{user:h,cookie:d}=await t(i,{failureRedirect:null});if(m=d??null,!h)return A(401,"Unauthorized");let R=fr(new URL(i.url).searchParams);if(R.kind==="invalid")return A(400,"Invalid attachment request");if(R.kind==="thumbnail"&&i.method!=="GET")return A(405,"Method not allowed",{Allow:"GET"});if(i.method!=="GET"&&i.method!=="HEAD")return A(405,"Method not allowed",{Allow:"GET, HEAD"});if(y===null)return A(404,"Attachment not found");if(_.token===void 0)throw new Error(Mi);let x=y.idCodec.decode(_.token);if(x===null||!dr(x))return A(400,"Invalid attachment token");let P=await r.getUserIdByExternalId(h.id);if(!P)return A(403,"Forbidden");let C={request:i,delivery:R,attachmentId:x,internalUserId:P,readAttachment:y.read,cookie:m,fail:A};return R.kind!=="thumbnail"?await y.serveOriginal(C):y.serveThumbnail===null?A(404,Ne[404]):await y.serveThumbnail(C,R.variant)}catch(h){if(h instanceof Response)throw h;return a.error(`500 attachment=? viewer=? reason=unexpected message=${h instanceof Error?h.message:"unknown"}`),A(500,Pe)}}};var Li=ce(1,"[Response]"),ae=(e,t,r,n=200,o=Li)=>{let a=yt(r),s=e.headers.get("If-None-Match");o.info(`[jsonResponseWithETag] ETag: ${a}, If-None-Match: ${s}`);let l=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate","X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'",ETag:a});return t&&l.append("Set-Cookie",t),e.method==="GET"&&n===200&&s===a?new Response(null,{status:304,headers:l}):new Response(JSON.stringify(r),{status:n,headers:l})};var $t=e=>e.method==="HEAD"?AbortSignal.abort():e.signal;var Yt=30,Zn=4e3,Ni="stream interrupted by server error",Oi=15e3,eo=Symbol("ids-stream-heartbeat"),Gn=()=>{},Vt=e=>e.return(void 0).then(Gn,Gn),ki=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(eo),Oi)}),stop:()=>clearTimeout(e)}},Bi=/^[0-9a-f]{1,16}$/,Ui=e=>{let t=e.searchParams.get(_e.cursorReportHubId),r=e.searchParams.get(_e.cursorBusinessDate),n=e.searchParams.get(_e.cursorSnapshot),o=n!==null&&Bi.test(n)?n:null;if(t===null)return r===null?{cursor:null,snapshot:o}:{invalid:!0};let a=He(t);return a===null?{invalid:!0}:r===null?{cursor:{businessDate:null,reportHubId:a},snapshot:o}:It(r)?{cursor:{businessDate:r,reportHubId:a},snapshot:o}:{invalid:!0}};async function*Xn(e,t,r,n){let o=t?Br(e,t):0,a=!0;for(;;){let s=e.slice(o,o+(a?r:Zn));o+=s.length;let l=o>=e.length,y=s[s.length-1];if(yield{kind:"chunk",items:s,nextCursor:l||!y?null:{businessDate:y.businessDate,reportHubId:y.reportHubId},isLast:l,...a?{total:e.length}:{},...a?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...a&&n.restarted?{restarted:!0}:{}},a=!1,l)return}}var to=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform","X-Content-Type-Options":"nosniff"});return e&&t.append("Set-Cookie",e),t},Qn=(e,t,r,n)=>{let o=new TextEncoder,a=!1,s=null,l=new ReadableStream({async pull(y){if(a||r.aborted){await Vt(t);try{y.close()}catch{}return}let i=ki();try{s===null&&(s=t.next());let _=await Promise.race([s,i.fired]);if(i.stop(),_===eo){if(a||r.aborted){await Vt(t);try{y.close()}catch{}return}y.enqueue(o.encode(`
2
- `));return}s=null;let{value:m,done:A}=_;if(A){y.close();return}if(a||r.aborted){await Vt(t);try{y.close()}catch{}return}y.enqueue(o.encode(`${JSON.stringify(m)}
3
- `))}catch(_){if(i.stop(),s=null,a||r.aborted)return;n.error(`ids-stream emission failed: ${_ instanceof Error?_.message:String(_)}`);try{let m={kind:"error",error:Ni};y.enqueue(o.encode(`${JSON.stringify(m)}
4
- `)),y.close()}catch{}}},cancel(){a=!0,Vt(t)}});return new Response(l,{status:200,headers:to(e)})},ro=e=>{let{service:t,logger:r}=e;return async(n,o,a,s,l)=>{let y=Ui(n);if("invalid"in y)return ae(a,o,{error:{message:"Invalid cursor"}},400);let i=dt(n.searchParams.get(_e.forceRefresh));if(i===null)return ae(a,o,{error:{message:"Invalid forceRefresh"}},400);let _=$t(a);if(_.aborted)return new Response(null,{status:200,headers:to(o)});let m=!1,A=null,h=null,d=new Promise((P,C)=>{A=P,h=C});d.catch(()=>{});let R=t.getDailyReportIdsByExternalId(l,s.id,{forceRefresh:i,onFetchStart:y.cursor?void 0:()=>{m=!0,t.readSseStreamAnchor().then(P=>t.getDailyReportIdsFirstPageByExternalId(l,s.id,Yt).then(C=>({items:C,streamAnchor:P}))).then(P=>A?.(P),P=>h?.(P))}});if(R.catch(()=>{}),y.cursor){let{items:P,streamAnchor:C,snapshot:$}=await R,T=y.snapshot!==null&&y.snapshot===$;return Qn(o,Xn(P,T?y.cursor:null,Yt,{snapshot:$,restarted:!T,streamAnchor:C}),_,r)}let x=(async function*(){let P=await Promise.race([R.then(T=>({kind:"full",source:T}),T=>({kind:"full-error",error:T})),d.then(T=>({kind:"page",page:T}),()=>({kind:"page-error"}))]),C=null,$=!1;if(P.kind==="full")C=P.source;else if(P.kind==="page"){let{items:T,streamAnchor:I}=P.page;if(T.length<Yt){yield{kind:"chunk",items:T,nextCursor:null,isLast:!0,total:T.length,streamAnchor:I};return}yield{kind:"chunk",items:T,nextCursor:null,isLast:!1,provisional:!0},$=!0}else if(P.kind==="full-error"&&m){let T=await d.catch(()=>null);T&&T.items.length>0&&(yield{kind:"chunk",items:T.items,nextCursor:null,isLast:!1,provisional:!0})}C===null&&(C=await R),yield*Xn(C.items,null,$?Zn:Yt,{snapshot:C.snapshot,streamAnchor:C.streamAnchor})})();return Qn(o,x,_,r)}};import{systemSseRuntime as Xi}from"@aiquants/sse";import{createSseResponse as Qi,readLastEventId as Zi,startSseHeartbeat as es,terminalStreamResponse as ts}from"@aiquants/sse/server";var qt=(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(s){return t.error(`SSE message ${e.id} is not JSON:`,s),{entry:{id:e.id,message:null},json:void 0}}let o=Vr.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}},Hi=["externalComments","postedComments"],no=new WeakMap,Fi=e=>{let t=no.get(e);if(t!==void 0)return t;let r={recipientRemoved:null,commentsRedacted:null};return no.set(e,r),r},oo=e=>{let{recipientRawUserId:t,...r}=e;return r},ao=(e,t)=>{let{published:r}=e;if(!(t||Object.hasOwn(r,"recipientRawUserId")))return e.text;let n=Fi(e);if(t){if(n.commentsRedacted===null){let o=oo(r),a=o.report;n.commentsRedacted=JSON.stringify({...o,report:{...a,...Object.fromEntries(Hi.map(s=>[s,[]]))}})}return n.commentsRedacted}return n.recipientRemoved===null&&(n.recipientRemoved=JSON.stringify(oo(r))),n.recipientRemoved};import{systemSseRuntime as Yi}from"@aiquants/sse";import{createSharedSource as Vi}from"@aiquants/sse/shared-source";var Fe="daily-report:ids:",$e="daily-report:business-date:",jt=(e,t)=>`${e}st:${t}`,Ir=e=>`${Fe}user:${e}:`,io=(e,t)=>jt(Ir(e),t),$i=e=>`${$e}${e}:`,so=(e,t)=>jt($i(e),t),ft=e=>`daily-report:date:${e}:user:`,tt=(e,t)=>`${ft(e)}${t}:`,lo=(e,t,r)=>jt(tt(e,t),r),Ie=e=>`daily-report:detail:${e}:user:`,zt=(e,t)=>`${Ie(e)}${t}:`,uo=(e,t,r)=>jt(zt(e,t),r);var Oe=(e,t)=>{let[r,n]=e.split("-").map(Number),[o,a]=t.split("-").map(Number);return r!==o?r<o:n<=a},qi=5e3,ji=Ct,Rt=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=t.logger??ce(1,"[SSE Reader]"),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 Vi({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:Yi,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",s=>{this._logger.error("Redis client error:",s)});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 s=await t.xRead([{key:this.config.streamKey,id:a}],{BLOCK:qi,COUNT:ji});if(s)for(let l of s)for(let y of l.messages){a=y.id;let{entry:i,json:_}=qt(y,this._logger);this._invalidateCaches(_),r.next(i)}}}catch(s){o()||(this._logger.error("xRead loop error:",s),r.fail(s instanceof Error?s:new Error(String(s))));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(Fe),(r==="comment-add"||r==="comment-delete"||r==="status-update")&&typeof n=="number"&&this.config.cache.invalidatePrefix(Ie(n))}};import{inArray as zi,sql as co}from"drizzle-orm";var Wi="",Ki=64,Ji=e=>e.toLowerCase(),Gi=e=>e.trim().toLowerCase();function mo(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=Gi(r);n.length>0&&t.add(n)}return t}function we(e,t){return e===null?!0:t==null?!1:e.has(Ji(t))}function Ye(e){return e!==null&&e.size===0}function yo(e,t){if(t!==null)return t.size===0?co`1 = 0`:zi(co`LOWER(${e})`,[...t])}var rt,nt,gt=class gt{constructor(t,r){Zt(this,rt);Zt(this,nt);er(this,rt,t),er(this,nt,r)}get visible(){return ut(this,rt)===null?null:new Set(ut(this,rt))}get commentable(){return ut(this,nt)===null?null:new Set(ut(this,nt))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=mo(r?t.read:t),o=r?t.comment:void 0;if(o===void 0)return new gt(n,n);let a=mo(o),s=new Set;for(let l of a??[])n.has(l)&&s.add(l);return new gt(n,s)}static unrestricted(t){return new gt(null,null)}};rt=new WeakMap,nt=new WeakMap;var ge=gt;function bt(e){let t=po(e.visible),r=po(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function po(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(Wi);if(t.length<=Ki)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 Ro=Object.freeze({...mt,route:"sse",frameworkDataRefusal:Mt}),ho=864e5,rs={baseMs:2e3,jitterMs:8e3},go=6e4,wr=Ct,bo=JSON.stringify({type:"connected"}),fo="0-0",ns=(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 we(r,e.report.sourceType);case"comment-add":case"comment-delete":return we(n,o??"Internal");case"report-delete":return we(r,o)}},os=(e,t)=>t===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"?!1:!we(t,e.report.sourceType),as=(e,t)=>{e.writeEvent({event:null,id:t,data:bo})},is=(e,t,r)=>{let{message:n}=t;if(n===null)return;let{parsed:o,published:a}=n,s=typeof a.recipientRawUserId=="number"?a.recipientRawUserId:void 0;if((o.type==="status-update"||s!==void 0)&&s!==r.internalUserId||!ns(o,a,r.visibleSet,r.commentableSet)){as(e,t.id);return}e.writeEvent({event:null,id:t.id,data:ao(n,os(o,r.commentableSet))})},So=e=>{let{authenticate:t,service:r,resolveViewerScope:n,redis:o,sseReader:a,streamKey:s,logger:l}=e,y=async(i,_)=>{let{request:m,internalUserId:A,cursor:h}=_,d=_.initialScope.visible,R=_.initialScope.commentable,x=0,P=setInterval(()=>{let b=++x;n(m,"refresh").then(M=>{b===x&&(d=M.visible,R=M.commentable)})},go);i.onClose(()=>clearInterval(P));let C=h===null?fo:h,$=h!==null&&o!==void 0,T=[],I=null,U=b=>{Oe(b.id,C)||(C=b.id,is(i,b,{internalUserId:A,visibleSet:d,commentableSet:R}))},V=async(b,M)=>{let[L]=await b.xRange(s,"-","+",{COUNT:1});return L!==void 0&&!Oe(L.id,M)},z=async(b,M)=>{if(await V(b,M))return!1;let L=M;for(;;){let S=await b.xRange(s,L,"+",{COUNT:wr}),N=S[0];if(N!==void 0&&N.id!==L&&await V(b,L))return!1;for(let v of S){if(I!==null&&Oe(I,v.id))return!0;Oe(v.id,C)||U(qt(v,l).entry)}let H=S.at(-1);if(S.length<wr||H===void 0||i.isClosed())return!0;L=H.id}},G=a.subscribe(b=>{if(!$){U(b);return}Oe(b.id,C)||(I===null&&(I=b.id),T.push(b))},b=>{l.error(`[SSE:${A}] Fan-Out reader error:`,b),i.close()});if(i.onClose(G),h===null){await a.ready();try{let b=await o?.getClient();if(b){let M=await b.xRevRange(s,"+","-",{COUNT:1});M.length>0&&!Oe(M[0].id,C)&&(C=M[0].id)}}catch{}}if(i.writeEvent({event:null,id:C===fo?null:C,data:bo}),es(i,{intervalMs:Hr,retry:rs,runtime:Xi}),h===null||o===void 0)return;await a.ready();let K=await o.getClient();if(K===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await z(K,h)){i.writeRetry(ho),i.writeEvent({event:"resync-required",id:null,data:""}),i.close();return}$=!1;for(let b of T.splice(0))U(b)};return async({request:i,params:_})=>{let m,A=()=>{let d=new Headers;return m!==void 0&&d.append("Set-Cookie",m),d},h=d=>ts(d,{data:"",retryMs:ho,headers:A()});try{let d=await t(i,{failureRedirect:null});m=d.cookie;let{user:R}=d;if(!R)return h("auth-required");let x=await r.getUserIdByExternalId(R.id);if(!x)return h("forbidden");if(_.endpoint!=="updates")return new Response("Not Found",{status:404,headers:A()});let P=Zi(i,Fr);if(P!==null&&!$r(P))return l.warn(`[SSE:${x}] malformed resume cursor; asking the client to resync`),h("resync-required");let C=await n(i,"initial");return Qi({requestSignal:$t(i),headers:A(),onError:($,T)=>l.error(`[SSE:${x}] ${T} failed:`,$),produce:$=>y($,{request:i,internalUserId:x,cursor:P,initialScope:C})})}catch(d){if(d instanceof Response)throw d;let R=d instanceof Error?d:new Error(String(d));return l.error(`500 sse name=${R.name} message=${R.message}`),new Response("Internal Server Error",{status:500,headers:A()})}}};var ss=(e,t)=>{let r=new Headers({...t?.headers,"Content-Type":"application/json"});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},ls=Object.freeze({...mt,route:"api",frameworkDataRefusal:({params:e})=>yr(e.endpoint)&&Pt[e.endpoint]==="stream"?Mt():null}),us=Object.freeze({...mt,route:"action"}),cs=600,ds=6e4;function xr(e){Bt(e);let{authenticate:t,service:r,encodeUserId:n,redis:o,sseReader:a,streamKey:s}=e,l={titleMaxLength:oe("service.titleMaxLength",r.titleMaxLength,1)},y=e.loginRedirectPath??"/auth/login",i=e.logger??ce(3,"[DailyReportAPI]"),_=e.logger??ce(3,"[DailyReportVisibility]"),m=e.logger??ce(1,"[DailyReportSSE]"),A=e.logger??ce(1,"[DailyReportAttachment]"),h=e.logger??ce(2,"[DailyReportIsolation]"),d=e.logger??ce(2,"[DailyReportAction]"),R=async(b,M="initial")=>{let L=e.resolveVisibleSourceTypes;if(!L)return ge.unrestricted("no visibility port injected: this deployment does not restrict by source type");try{let S=await L(b,{reason:M});return S==null?ge.unrestricted("visibility port returned null/undefined: this deployment opts out of source-type filtering"):ge.restrictTo(S)}catch(S){return _.error("resolveVisibleSourceTypes threw; failing closed (deny all)",S),ge.restrictTo([])}},x=async({request:b})=>{let{user:M,cookie:L}=await t(b,{failureRedirect:y}),S=new Headers;L&&S.append("Set-Cookie",L);let N=await r.getUserIdByExternalId(M.id),H=N?n(N):null;return{data:{user:M,userId:H},headers:S}},P={[Ce.businessDate]:async(b,M,L,S,N)=>{let H=b.searchParams.get(_e.businessDate),v=H===null?null:Ke(H);if(v===null)return ae(L,M,{error:{message:"Invalid business date"}},400);let X=dt(b.searchParams.get(_e.forceRefresh));if(X===null)return ae(L,M,{error:{message:"Invalid forceRefresh"}},400);let j=await r.getDailyReportsByBusinessDateByExternalId(N,v,S.id,{forceRefresh:X});return ae(L,M,{businessDate:v,reports:j},200)},[Ce.idsStream]:ro({service:r,logger:i}),[Ce.report]:async(b,M,L,S,N)=>{let H=He(b.searchParams.get(_e.reportHubId));if(H===null)return ae(L,M,{error:{message:"Invalid reportHubId"}},400);let v=dt(b.searchParams.get(_e.forceRefresh));if(v===null)return ae(L,M,{error:{message:"Invalid forceRefresh"}},400);let X=await r.getDailyReportDetailByIdByExternalId(N,H,S.id,{snapshot:!0,forceRefresh:v});return X?ae(L,M,{report:X},200):ae(L,M,{error:{message:"Report not found"}},404)}},C=async({request:b,params:M})=>{let{user:L,cookie:S}=await t(b,{failureRedirect:null}),N=S??null;if(!L)return ae(b,N,{error:{message:"Unauthorized"}},401);let H=M.endpoint;if(!yr(H))return ae(b,N,{error:{message:"Unknown endpoint"}},404);let v=Zr[Pt[H]];if(!v.includes(b.method)){let j=ae(b,N,{error:{message:"Method not allowed"}},405);return j.headers.set("Allow",v.join(", ")),j}let X=te();try{let j=new URL(b.url),O=await R(b);return await P[H](j,N,b,L,O)}catch(j){let O=te()-X,re=j instanceof Error?j:new Error(String(j));return i.error(`500 endpoint=${H} elapsed=${O}ms name=${re.name} code=${"code"in re?re.code:"N/A"} message=${re.message}`),i.error("Stack:",re.stack),ae(b,N,{error:{message:"Internal Server Error"}},500)}},$=Qr(d),T=Ze({reason:"rate_limit",limitPerWindow:cs,windowMs:ds,logger:d,windowFields:()=>"route=action"}),I=async(b,M,L,S)=>{let{clientTempId:N,operationTimestamp:H}=b;if(b.intent==="create"){let O=await r.createDailyReport(M,b.businessDate,N);return S({status:"OK",intent:"create",report:O,reportHubId:String(O.reportHubId),clientTempId:N})}let{reportHubId:v,businessDate:X}=b,j=async(O,re,be)=>{try{let De=await be(re);return S({status:"OK",intent:O,updatedStatus:{isStarred:De.isStarred,isRead:De.isRead},operationTimestamp:H,reportHubId:String(v),clientTempId:N})}catch(De){if(De instanceof Error&&De.message==="Not Found")return S({error:"Report not found"},{status:404});throw De}};switch(b.intent){case"update":try{return await r.updateDailyReport(v,M,b.changes,N),S({status:"OK",intent:"update",reportHubId:String(v),clientTempId:N})}catch(O){if(O instanceof Error){if(O.message==="Unauthorized")return S({error:"Unauthorized"},{status:403});if(O.message==="Not Found")return S({error:"Report not found"},{status:404})}throw O}case"publish":try{let O=await r.publishDailyReport(v,M,N);return S({status:"OK",intent:"publish",reportHubId:String(v),clientTempId:N,report:O})}catch(O){if(O instanceof Error){if(O.message==="Unauthorized")return S({error:"Unauthorized"},{status:403});if(O.message==="Not Found")return S({error:"Report not found"},{status:404})}throw O}case"delete":try{return await r.deleteDailyReport(v,M,N),S({status:"OK",intent:"delete",reportHubId:String(v),clientTempId:N})}catch(O){if(O instanceof Error){if(O.message==="Unauthorized")return S({error:"Unauthorized"},{status:403});if(O.message==="Not Found")return S({error:"Report not found"},{status:404})}throw O}case"toggleStar":return await j("toggleStar",b.value,O=>r.setStarStatus(L,M,v,X,O,N));case"toggleRead":return await j("toggleRead",b.value,O=>r.setReadStatus(L,M,v,X,O,N));case"addComment":try{let O=await r.addComment(L,M,v,b.content,X,N),re={...O,userId:O.userId};return S({status:"OK",intent:"addComment",newComment:re,reportHubId:String(v),clientTempId:N})}catch(O){if(O instanceof Error){if(O.message==="Not Found")return S({error:"Report not found"},{status:404});if(O.message.startsWith("Comments are restricted"))return S({error:"Comments are restricted for this report"},{status:403})}throw O}case"deleteComment":try{return await r.deleteComment(L,M,v,b.commentId,X,N),S({status:"OK",intent:"deleteComment",reportHubId:String(v),deletedCommentId:String(b.commentId),clientTempId:N})}catch(O){if(O instanceof Error){if(O.message==="Unauthorized")return S({error:"Unauthorized"},{status:403});if(O.message==="Not Found")return S({error:"Comment not found"},{status:404})}throw O}}},U=async({request:b,params:M})=>{let{user:L,cookie:S}=await t(b,{failureRedirect:null}),N=(v,X)=>ss(v,{...X,setCookie:S});if(!L)return N({error:"Unauthorized"},{status:401});let H=te();try{if(M.endpoint!==Ce.action)return N({error:"Unknown endpoint"},{status:404});let v=T.spend(L.id,"action");if(v!==null)return N({error:v.message},{status:v.status,headers:v.headers});let X=await Xr(b,l);if("refusal"in X){let{refusal:be}=X;return be.status===413&&$(be.measuredBy),N({error:be.error},{status:be.status})}let{command:j}=X;if(j.intent==="clearCache"&&!e.enableDevCacheClear)return N({error:"Invalid intent"},{status:400});let O=await r.getUserIdByExternalId(L.id);if(!O)return N({error:"User not found"},{status:404});let re=await R(b);return j.intent==="clearCache"?(await r.clearCache(),N({status:"OK",intent:"clearCache"})):await I(j,O,re,N)}catch(v){if(v instanceof Response)throw v;let X=te()-H,j=v instanceof Error?v:new Error(String(v));return i.error(`500 action elapsed=${X}ms name=${j.name} message=${j.message}`),i.error("Stack:",j.stack),N({error:"Internal Server Error"},{status:500})}},V=So({authenticate:t,service:r,resolveViewerScope:R,redis:o,sseReader:a,streamKey:s,logger:m}),z=Jn({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:R,logger:A}),G=an(h),K=(b,M)=>async L=>{let S=nn(L.request)?b.frameworkDataRefusal(L):null;if(S!==null)throw S;return on(L.request,b)?(G(b.route,L.request),b.crossSiteRejection()):M(L)};return{index:{loader:x},api:{loader:K(ls,C),action:K(us,U)},sse:{loader:K(Ro,V)},attachment:{loader:K(Kn,z)}}}import{runWithTransactionRetry as ps}from"@aiquants/mssql";import{aliasedTable as ot,and as Z,asc as Wt,desc as at,eq as w,getColumns as ys,inArray as Ae,isNull as pe,or as it,sql as Ao}from"drizzle-orm";var Ve=e=>ys(e),To=_t([]),de=(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"),s=String(r.getDate()).padStart(2,"0");if(t==="YYYY-MM-DD")return`${o}-${a}-${s}`;let l=String(r.getHours()).padStart(2,"0"),y=String(r.getMinutes()).padStart(2,"0"),i=String(r.getSeconds()).padStart(2,"0");return`${o}-${a}-${s} ${l}:${y}:${i}`},hs=e=>{let{length:t}=e;if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=1)return t;throw me("tables.hub.title","a character column with a declared length",t)},Do=e=>e===""?null:e;function Cr(e){let{db:t,tables:r,userTable:n,resolveUserId:o,encodeUserId:a,redis:s,cache:l,epochs:y}=e,{hub:i,internal:_,comment:m,label:A,hubLabel:h,userStatus:d}=r,R=e.externalSources??[],x=e.draftLabelNames&&e.draftLabelNames.length>0?e.draftLabelNames:[e.draftLabelName??"\u4E0B\u66F8\u304D"],P=x[0]??"\u4E0B\u66F8\u304D",C=e.logger??ce(1,"[DailyReportService]");Bt(e);let $=pn(e.attachments),T=hs(i.title),I=c=>ps(u=>t.transaction(p=>u(()=>c(p))),e.transactionRetry),U=e.idsTtlMs??18e4,V="daily-report:ids:epoch",z=e.businessDateTtlMs??3e5,G="daily-report:date-epoch:",K="daily-report:detail-epoch:",M=`${e.streamKey??"daily-report:sse-stream"}:v2`,L=e.streamMaxLen??1e4,S=c=>y.incrementEpoch(c),N=c=>yo(i.sourceType,c),H=async(c,u)=>{let p=await s?.getClient();if(!p){C.warn(`[SSE] Redis client unavailable (${u})`);return}let f=JSON.stringify(c),E=Buffer.byteLength(f);if(E>6356992){C.warn(`[SSE] Event too large (${u}): ${E} bytes > ${6356992}; not published`);return}let k=te();try{await p.xAdd(M,"*",{data:f},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:L}});let D=te()-k;D>1e3&&C.warn(`[SSE] Slow publish (${u}): ${D}ms`)}catch(D){C.error(`[SSE] Redis publish failed (${u}):`,D)}},v=async()=>{try{let c=await s?.getClient();if(c===void 0)return null;let[u]=await c.xRevRange(M,"+","-",{COUNT:1});return u===void 0?null:u.id}catch(c){return C.error("[DailyReportService] SSE stream anchor read failed",c),null}},X=c=>c==null||c===""?null:/^\d+$/.test(c)?a(Number(c)):c,j=()=>{let c={};for(let u of R)c[`ext_${u.sourceType}`]=Ve(u.table);return c},O=c=>{let u=c;for(let p of R)u=u.leftJoin(p.table,Z(w(i.sourceType,p.sourceType),w(i.sourceIdNum,p.idColumn)));return u},re=(c,u,p)=>{let{hub:f,internal:E}=u,k=f.summary,D=[],B=null,F=null,Y=null,J=null,Q=null,he=null,ze=[],ve=R.find(q=>q.sourceType===f.sourceType),We=ve?u[`ext_${ve.sourceType}`]:void 0;if(ve&&We){let q=ve.mapRow(We);q.content!==void 0&&(k=q.content),q.employeeName!==void 0&&(he=q.employeeName),q.category!==void 0&&(B=q.category),q.creationCategory!==void 0&&(F=q.creationCategory),q.visitTimeFrom!==void 0&&(Y=q.visitTimeFrom),q.visitTimeTo!==void 0&&(J=q.visitTimeTo),q.customerName!==void 0&&(Q=q.customerName),q.interviewers!==void 0&&(D=q.interviewers),q.externalComments!==void 0&&(ze=q.externalComments)}else f.sourceType==="Internal"&&E&&(k=E.body);let xe=(u.labels??[]).map(q=>({id:q.id,name:q.name,color:q.color})),le=u.postedCommentRows??[],ee=we(c.commentable,f.sourceType),ue=F?x.includes(F):!1,Qt=je?.[0]??null;return ue&&Qt&&!xe.some(q=>q.id===Qt)&&xe.push({id:Qt,name:P,color:null}),{reportHubId:f.id,date:de(f.businessDate,"YYYY-MM-DD"),author:u.creatorName??X(f.createdBy)??"",userId:f.userId?a(f.userId):"",sourceType:f.sourceType??"Internal",createdAt:de(f.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:de(f.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:X(f.updatedBy),employeeName:he??u.creatorName??X(f.createdBy),category:B,creationCategory:F,visitTimeFrom:Y,visitTimeTo:J,customerName:Q,interviewers:D,subject:f.title,content:k,externalComments:ee?ze:[],isRead:u.isRead??!1,isStarred:u.isStarred??!1,labels:xe,postedComments:le.filter(q=>ee||p!==void 0&&q.userId===p).map(q=>({...q,userId:a(q.userId),isMine:p?q.userId===p:!1})),attachments:u.attachments}},be=async(c,u)=>{let p=ot(h,"draft_label"),f=await Be();return(await t.select({reportHubId:i.id,businessDate:i.businessDate,sourceType:i.sourceType}).from(i).leftJoin(p,Z(w(p.hubId,i.id),Ae(p.labelId,f))).where(Z(pe(i.deletedAt),it(w(i.userId,u),pe(i.userId),pe(p.hubId)),N(c.visible))).orderBy(at(i.businessDate),at(i.id))).map(k=>({...k,businessDate:de(k.businessDate,"YYYY-MM-DD")}))},De=async(c,u,p)=>{let f=await st(u);if(!f)return[];if(Ye(c.visible))return[];let E=ot(h,"draft_label"),k=await Be();return(await t.select({reportHubId:i.id,businessDate:i.businessDate,sourceType:i.sourceType}).top(p).from(i).leftJoin(E,Z(w(E.hubId,i.id),Ae(E.labelId,k))).where(Z(pe(i.deletedAt),it(w(i.userId,f),pe(i.userId),pe(E.hubId)),N(c.visible))).orderBy(at(i.businessDate),at(i.id))).map(B=>({...B,businessDate:de(B.businessDate,"YYYY-MM-DD")}))},St=async(c,u)=>{let p=await O(t.select({hub:Ve(i),internal:Ve(_),creatorName:n.displayName,...j()}).from(i)).leftJoin(_,w(i.id,_.hubId)).leftJoin(n,w(i.userId,n.id)).where(Z(w(i.businessDate,Ao`${u}`),pe(i.deletedAt),N(c.visible))).orderBy(at(i.id)),f=await Tt(p.map(E=>E.hub.id));return p.map(E=>re(c,{...E,attachments:f.get(E.hub.id)??[]}))},se=new Map,st=async c=>{if(!e.disableUserIdCache&&se.has(c))return se.get(c)??null;let u=await o(c);return u!==null&&!e.disableUserIdCache&&se.set(c,u),u},$o=async(c,u,{forceRefresh:p=!1,snapshot:f=!1,ttlMsOverride:E,onFetchStart:k}={})=>{let D=await st(u);if(!D)return{items:[],streamAnchor:null,snapshot:To};if(Ye(c.visible))return{items:[],streamAnchor:await v(),snapshot:To};let B=io(D,bt(c)),[F]=await l.getOrFetch({cacheKey:B,fetcher:async()=>{let Y=await v(),J=await be(c,D);if(!kr(J)){C.warn("[DailyReportService] ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)");let Q=[...J].sort(Et);return[{items:Q,streamAnchor:Y,snapshot:_t(Q)}]}return[{items:J,streamAnchor:Y,snapshot:_t(J)}]},onFetchStart:k,forceRefresh:p,snapshot:f,ttlMsOverride:E??U,epochKey:V,refreshAheadRatio:.5});if(F===void 0)throw new Error("[DailyReportService] ids cache returned no record");return F},Yo=(c,u,{forceRefresh:p=!1,snapshot:f=!1,ttlMsOverride:E}={})=>{let k=fe(u);return k?Ye(c.visible)?Promise.resolve([]):l.getOrFetch({cacheKey:so(k,bt(c)),fetcher:()=>St(c,k),forceRefresh:p,snapshot:f,ttlMsOverride:E??z}):Promise.resolve([])},je=null,At=async()=>(je!==null||(je=(await t.select({id:A.id}).from(A).where(Ae(A.name,x)).orderBy(A.id)).map(u=>u.id)),je),Be=async()=>{let c=await At();return c.length>0?c:[-1]},Jt=async()=>{let c=await At();if(c.length===0)return null;let[u]=await t.select({id:A.id}).top(1).from(A).where(w(A.name,P));return u?.id??c[0]},Vo=(c,u)=>u!=null?"absent":c!=null?"present":"unknown",Tt=async c=>{let u=new Map,p=r.attachment;if(c.length===0||!p||$===null)return u;let f=$.idCodec,E=$.thumbnails!==null,k=await t.select({id:p.id,hubId:p.hubId,fileName:p.fileName,fileType:p.fileType,fileSize:p.fileSize,createdAt:p.createdAt,objectCheckedAt:p.objectCheckedAt,objectMissingAt:p.objectMissingAt}).from(p).where(Ae(p.hubId,c)).orderBy(Wt(p.createdAt),Wt(p.id));for(let D of k){let B=D.fileType?String(D.fileType):null,F=D.fileSize!=null?Number(D.fileSize):null,Y=Vo(D.objectCheckedAt,D.objectMissingAt),J={id:f.encode(Number(D.id)),fileName:String(D.fileName),fileType:B,fileSize:F,createdAt:de(D.createdAt,"YYYY-MM-DD HH:mm:ss"),state:Y,hasThumbnail:E&&Y!=="absent"&&Ht({fileType:B,fileSize:F},$.maxBytes)},Q=u.get(Number(D.hubId));Q?Q.push(J):u.set(Number(D.hubId),[J])}return u},qo=async(c,u,p)=>{let f=r.attachment;if(!f||Ye(c.visible))return null;let E=await Be(),k=ot(h,"draft_label");return(await t.select({fileName:f.fileName,filePath:f.filePath,fileType:f.fileType,fileSize:f.fileSize}).top(1).from(f).innerJoin(i,w(i.id,f.hubId)).leftJoin(k,Z(w(k.hubId,i.id),Ae(k.labelId,E))).where(Z(w(f.id,u),pe(i.deletedAt),it(w(i.userId,p),pe(k.hubId)),N(c.visible))))[0]??null},jo=async c=>{let u=r.attachment;if(!u)return;let p=new Date;try{await t.update(u).set({objectCheckedAt:p,objectMissingAt:p,updatedAt:p}).where(w(u.id,c))}catch(f){C.error("markAttachmentMissing failed",f)}},zo=async c=>{let u=r.attachment;if(!u)return;let p=new Date;try{await t.update(u).set({objectCheckedAt:p,objectMissingAt:null,updatedAt:p}).where(w(u.id,c))}catch(f){C.error("markAttachmentPresent failed",f)}},Wo=async(c,u,p,{forceRefresh:f=!1,snapshot:E=!1,ttlMsOverride:k}={})=>{let D=await st(p);if(!D)return[];let B=fe(u);if(!B)return[];if(Ye(c.visible))return[];let F=lo(B,D,bt(c));return l.getOrFetch({cacheKey:F,fetcher:async()=>{let Y=await Be(),J=ot(h,"draft_label"),Q=await O(t.select({hub:Ve(i),internal:Ve(_),isRead:d.isRead,isStarred:d.isStarred,creatorName:n.displayName,...j()}).from(i)).leftJoin(_,w(i.id,_.hubId)).leftJoin(d,Z(w(i.id,d.hubId),w(d.userId,D))).leftJoin(J,Z(w(J.hubId,i.id),Ae(J.labelId,Y))).leftJoin(n,w(i.userId,n.id)).where(Z(w(i.businessDate,Ao`${B}`),pe(i.deletedAt),it(w(i.userId,D),pe(J.hubId)),N(c.visible))).orderBy(at(i.id));if(Q.length===0)return[];let he=Q.map(ee=>ee.hub.id),ze=await t.select({hubId:h.hubId,id:A.id,name:A.name,color:A.color}).from(h).innerJoin(A,w(h.labelId,A.id)).where(Ae(h.hubId,he)),ve=await t.select({hubId:m.hubId,id:m.id,body:m.body,createdAt:m.createdAt,userId:m.userId,userName:n.displayName}).from(m).leftJoin(n,w(m.userId,n.id)).where(Ae(m.hubId,he)).orderBy(Wt(m.createdAt)),We=await Tt(he),xe=new Map,le=new Map;for(let ee of ze){let ue=xe.get(ee.hubId);ue||(ue=[],xe.set(ee.hubId,ue)),ue.push({id:ee.id,name:ee.name,color:ee.color})}for(let ee of ve){let ue=le.get(ee.hubId);ue||(ue=[],le.set(ee.hubId,ue)),ue.push({id:ee.id,content:ee.body,createdAt:de(ee.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:ee.userId,userName:ee.userName||""})}return Q.map(ee=>{let ue=ee.hub.id;return re(c,{...ee,attachments:We.get(ue)??[],labels:xe.get(ue)||[],postedCommentRows:le.get(ue)||[]},D)})},forceRefresh:f,snapshot:E,ttlMsOverride:k??z,epochKey:`${G}${B}`})},lt=async(c,u,p,{forceRefresh:f=!1,snapshot:E=!1,ttlMsOverride:k}={})=>{if(Ye(c.visible))return null;let D=uo(u,p,bt(c));return(await l.getOrFetch({cacheKey:D,fetcher:async()=>{let F=await Be(),Y=ot(h,"draft_label"),J=await O(t.select({hub:Ve(i),internal:Ve(_),isRead:d.isRead,isStarred:d.isStarred,creatorName:n.displayName,...j()}).from(i)).leftJoin(_,w(i.id,_.hubId)).leftJoin(d,Z(w(i.id,d.hubId),w(d.userId,p))).leftJoin(Y,Z(w(Y.hubId,i.id),Ae(Y.labelId,F))).leftJoin(n,w(i.userId,n.id)).where(Z(w(i.id,u),pe(i.deletedAt),it(w(i.userId,p),pe(Y.hubId)),N(c.visible)));if(J.length===0)return[];let Q=J[0].hub.id,he=await t.select({id:A.id,name:A.name,color:A.color}).from(h).innerJoin(A,w(h.labelId,A.id)).where(w(h.hubId,Q)),ze=await t.select({id:m.id,body:m.body,createdAt:m.createdAt,userId:m.userId,userName:n.displayName}).from(m).leftJoin(n,w(m.userId,n.id)).where(w(m.hubId,Q)).orderBy(Wt(m.createdAt)),ve=await Tt([Q]),We=he.map(le=>({id:le.id,name:le.name,color:le.color})),xe=ze.map(le=>({id:le.id,content:le.body,createdAt:de(le.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:le.userId,userName:le.userName||""}));return[re(c,{...J[0],attachments:ve.get(Q)??[],labels:We,postedCommentRows:xe},p)]},forceRefresh:f,snapshot:E,ttlMsOverride:k??z,epochKey:`${K}${u}`}))[0]??null},Ko=async(c,u,p,f={})=>{let E=await st(p);return E?lt(c,u,E,f):null},Jo=async(c,u)=>{let p=await Be(),f=ot(h,"draft_label"),[E]=await t.select({sourceType:i.sourceType,deletedAt:i.deletedAt}).top(1).from(i).leftJoin(f,Z(w(f.hubId,i.id),Ae(f.labelId,p))).where(Z(w(i.id,c),it(w(i.userId,u),pe(f.hubId))));return E??null},Gt=async(c,u,p)=>{let f=await Jo(u,p);if(!f||f.deletedAt||!we(c.visible,f.sourceType))throw new Error("Not Found")},Go=async(c,u,p,f,E,k)=>{await Gt(c,p,u);let D=await t.select().top(1).from(d).where(Z(w(d.hubId,p),w(d.userId,u))),B;if(D.length>0?D[0].isStarred!==E?B=(await t.update(d).set({isStarred:E,updatedAt:new Date,updatedBy:String(u)}).output().where(Z(w(d.hubId,p),w(d.userId,u))))[0]:B=D[0]:B=(await t.insert(d).output().values({hubId:p,userId:u,isStarred:E,isRead:!1,createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)}))[0],f){let F=fe(f);F&&(l.invalidatePrefix(tt(F,u)),await S(`${G}${F}`))}return l.invalidatePrefix(zt(p,u)),await S(`${K}${p}`),await H(xt.parse({type:"status-update",reportHubId:p,recipientRawUserId:u,statusType:"star",value:E,clientTempId:k}),"setStarStatus"),B},Xo=async(c,u,p,f,E,k)=>{await Gt(c,p,u);let D=await t.select().top(1).from(d).where(Z(w(d.hubId,p),w(d.userId,u))),B;if(D.length>0?D[0].isRead!==E?B=(await t.update(d).set({isRead:E,updatedAt:new Date,updatedBy:String(u)}).output().where(Z(w(d.hubId,p),w(d.userId,u))))[0]:B=D[0]:B=(await t.insert(d).output().values({hubId:p,userId:u,isRead:E,isStarred:!1,createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)}))[0],f){let F=fe(f);F&&(l.invalidatePrefix(tt(F,u)),await S(`${G}${F}`))}return l.invalidatePrefix(zt(p,u)),await S(`${K}${p}`),await H(xt.parse({type:"status-update",reportHubId:p,recipientRawUserId:u,statusType:"read",value:E,clientTempId:k}),"setReadStatus"),B},Pr=async(c,u)=>{if(u===null)return;let p=await Be(),[f]=await t.select({hubId:h.hubId}).top(1).from(h).where(Z(w(h.hubId,c),Ae(h.labelId,p)));return f?u:void 0},Qo=async(c,u,p,f,E,k)=>{let[D]=await t.select({sourceType:i.sourceType,deletedAt:i.deletedAt,userId:i.userId}).top(1).from(i).where(w(i.id,p));if(!D||D.deletedAt)throw new Error("Not Found");if(await Gt(c,p,u),!we(c.commentable,D.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(D.sourceType.toLowerCase()!=="internal")throw new Error("Comments are restricted for external daily report sources");let B=await Pr(p,D.userId),[F]=await t.insert(m).output().values({hubId:p,userId:u,body:f,createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)}),[Y]=await t.select({displayName:n.displayName}).top(1).from(n).where(w(n.id,u)),J=Y?.displayName??"";if(E){let he=fe(E);he&&(l.invalidatePrefix(ft(he)),await S(`${G}${he}`))}l.invalidatePrefix(Ie(p)),await S(`${K}${p}`);let Q={id:F.id,userId:a(F.userId),userName:J,content:F.body,createdAt:de(F.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await H(or.parse({type:"comment-add",reportHubId:p,comment:Q,clientTempId:k,recipientRawUserId:B,sourceType:D.sourceType}),"addComment"),Q},Zo=async(c,u)=>await c.select().top(1).from(m).where(w(m.id,u)),ea=async(c,u,p,f,E,k)=>{let D=await Zo(t,f);if(D.length===0)throw new Error("Not Found");if(D[0].hubId!==p)throw new Error("Not Found");let[B]=await t.select({userId:i.userId,sourceType:i.sourceType}).top(1).from(i).where(w(i.id,D[0].hubId));if(!(B&&we(c.visible,B.sourceType)))throw new Error("Not Found");if(D[0].userId!==u)throw new Error("Unauthorized");let F=await Pr(p,B.userId);if(await t.delete(m).where(w(m.id,f)),E){let Y=fe(E);Y&&(l.invalidatePrefix(ft(Y)),await S(`${G}${Y}`))}l.invalidatePrefix(Ie(p)),await S(`${K}${p}`),await H(ar.parse({type:"comment-delete",reportHubId:p,commentId:f,clientTempId:k,recipientRawUserId:F,sourceType:B?.sourceType}),"deleteComment")},ta=async(c,u,p)=>{if(!It(u))throw me("createDailyReport: businessDate","a business-date key in the canonical form YYYY-MM-DD naming a day from 0001-01-01 to 9999-12-31",u);C.info("createDailyReport called",{userId:c,businessDate:u});let[f]=await t.select({displayName:n.displayName}).from(n).where(w(n.id,c)),E=f?.displayName??a(c);try{let k=await I(async B=>{C.info("Starting transaction");let F=`internal-temp-${Date.now()}-${Math.random()}`,[Y]=await B.insert(i).output().values({sourceType:"Internal",sourceId:F,businessDate:new Date(`${u}T00:00:00Z`),userId:c,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(c),updatedAt:new Date,updatedBy:String(c)});await B.update(i).set({sourceId:String(Y.id)}).where(w(i.id,Y.id)),C.info("Hub created",Y),await B.insert(_).values({hubId:Y.id,body:"",createdAt:new Date,createdBy:String(c),updatedAt:new Date,updatedBy:String(c)}),C.info("Internal created"),C.info("Calling getDraftLabelId");let J=await Jt();C.info("draftLabelId",J);let Q=[];return J&&(await B.insert(h).values({hubId:Y.id,labelId:J,createdAt:new Date,createdBy:String(c)}),Q.push({id:J,name:P,color:null})),C.info("Label assigned"),{reportHubId:Y.id,date:u,createdAt:de(Y.createdAt,"YYYY-MM-DD HH:mm:ss"),author:E,userId:a(c),sourceType:"Internal",employeeName:E,updatedBy:a(c),updatedAt:de(Y.updatedAt,"YYYY-MM-DD HH:mm:ss"),category:null,creationCategory:null,visitTimeFrom:null,visitTimeTo:null,customerName:null,interviewers:[],subject:Y.title,content:"",externalComments:[],isRead:!0,isStarred:!1,labels:Q,postedComments:[],attachments:[]}});l.invalidatePrefix(tt(u,c)),l.invalidatePrefix($e),l.invalidatePrefix(Ir(c)),await S(V),await S(`${G}${u}`);let D=await lt(ge.unrestricted("post-write self read: the writer always sees the row they just wrote"),k.reportHubId,c,{forceRefresh:!0});if(D){let B=await At(),F=D.labels.some(Y=>B.includes(Y.id));await H(ir.parse({type:"report-create",reportHubId:D.reportHubId,report:D,clientTempId:p,recipientRawUserId:F?c:void 0}),"createDailyReport")}return D??k}catch(k){throw C.error("Error in createDailyReport",k),k}},Dt=async(c,u)=>await c.select().top(1).from(i).where(w(i.id,u)),Xt=async(c,u,p)=>{await c.update(i).set(p).where(w(i.id,u))},Mr=async(c,u,p)=>{await c.update(_).set(p).where(w(_.hubId,u))},vr=async(c,u,p)=>{await c.delete(h).where(Z(w(h.hubId,u),w(h.labelId,p)))};return{streamKey:M,streamMaxLen:L,attachmentDelivery:$,titleMaxLength:T,clearCache:async()=>{l.clearAll(),se.clear(),je=null,y&&await S(V),C.info("[DailyReportService] Server-side DB/SQL caches cleared successfully.")},invalidateHubReadCaches:async(c,u)=>{l.invalidatePrefix($e),l.invalidatePrefix(Fe),await S(V);for(let p of new Set(c))l.invalidatePrefix(Ie(p)),await S(`${K}${p}`);for(let p of new Set(u)){let f=fe(p);f&&await S(`${G}${f}`)}},getUserIdByExternalId:st,getDailyReportIdsByExternalId:$o,getDailyReportIdsFirstPageByExternalId:De,readSseStreamAnchor:v,getDailyReportsByBusinessDate:Yo,getDailyReportsByBusinessDateByExternalId:Wo,getDailyReportDetailById:lt,getDailyReportDetailByIdByExternalId:Ko,getDraftLabelId:Jt,getAttachmentsByHubIds:Tt,getAttachmentForUser:qo,markAttachmentMissing:jo,markAttachmentPresent:zo,setStarStatus:Go,setReadStatus:Xo,addComment:Qo,deleteComment:ea,createDailyReport:ta,updateDailyReport:async(c,u,p,f)=>{let E=await Dt(t,c);if(!E.length||E[0].deletedAt)throw new Error("Not Found");if(E[0].userId!==u)throw new Error("Unauthorized");await I(async B=>{p.title!==void 0&&await Xt(B,c,{title:Do(p.title),updatedAt:new Date,updatedBy:String(u)}),p.content!==void 0&&await Mr(B,c,{body:Do(p.content),updatedAt:new Date,updatedBy:String(u)})}),l.invalidatePrefix(Ie(c)),l.invalidatePrefix($e),await S(`${K}${c}`);let k=fe(de(E[0].businessDate,"YYYY-MM-DD"));k&&(l.invalidatePrefix(ft(k)),await S(`${G}${k}`));let D=await lt(ge.unrestricted("post-write self read: the writer always sees the row they just wrote"),c,u,{forceRefresh:!0});if(D){let B=await At(),F=D.labels.some(Y=>B.includes(Y.id));await H(sr.parse({type:"report-update",reportHubId:D.reportHubId,report:D,clientTempId:f,recipientRawUserId:F?u:void 0}),"updateDailyReport")}},publishDailyReport:async(c,u,p)=>{let f=await Dt(t,c);if(!f.length)throw new Error("Not Found");if(f[0].userId!==u)throw new Error("Unauthorized");let E=await Jt();if(!E)return null;if(await vr(t,c,E),l.invalidatePrefix(Ie(c)),l.invalidatePrefix($e),l.invalidatePrefix(Fe),await S(V),f[0].businessDate){let B=fe(de(f[0].businessDate,"YYYY-MM-DD"));B&&await S(`${G}${B}`)}let k=fe(de(f[0].businessDate,"YYYY-MM-DD"));k&&l.invalidatePrefix(tt(k,u));let D=await lt(ge.unrestricted("post-write self read: the writer always sees the row they just wrote"),c,u,{forceRefresh:!0});return D&&await H(lr.parse({type:"report-publish",reportHubId:D.reportHubId,report:D,clientTempId:p}),"publishDailyReport"),D??null},deleteDailyReport:async(c,u,p)=>{let f=await Dt(t,c);if(!f.length||f[0].deletedAt)throw new Error("Not Found");if(f[0].userId!==u)throw new Error("Unauthorized");if(await Xt(t,c,{deletedAt:new Date,deletedBy:String(u),updatedAt:new Date,updatedBy:String(u)}),l.invalidatePrefix(Ie(c)),l.invalidatePrefix($e),l.invalidatePrefix(Fe),await S(V),f[0].businessDate){let E=fe(de(f[0].businessDate,"YYYY-MM-DD"));E&&await S(`${G}${E}`)}await H(ur.parse({type:"report-delete",reportHubId:c,clientTempId:p,sourceType:f[0].sourceType}),"deleteDailyReport")},findDailyReportHubById:Dt,updateDailyReportHub:Xt,updateDailyReportInternal:Mr,deleteDailyReportLabel:vr}}var fs=ce(1,"[DailyReportExternalSource]"),Rs=(e,t,r,n=fs)=>{if(!e)return[];try{let o=JSON.parse(e);return Array.isArray(o)?o.map(r).filter(a=>a!==null):(n.warn(`Unexpected ${t} format: not an array`),[])}catch(o){return n.warn(`Failed to parse ${t}:`,o),[]}};import{desc as _o,sql as gs}from"drizzle-orm";import{bigint as ne,bit as Eo,date as bs,datetime2 as ie,foreignKey as Te,index as ke,int as Ss,mssqlSchema as As,nvarchar as W,primaryKey as qe,uniqueIndex as Ts}from"drizzle-orm/mssql-core";function Ds(e,t){let r=As(e),n=t.userTable,o=r.table("DailyReportHub",{id:ne("id",{mode:"number"}).identity().notNull(),sourceType:W("source_type",{length:20}).notNull(),sourceId:W("source_id",{length:100}).notNull(),sourceIdNum:ne("source_id_num",{mode:"number"}).generatedAlwaysAs(gs`TRY_CAST(source_id AS BIGINT)`),businessDate:bs("business_date"),userId:ne("user_id",{mode:"number"}),title:W("title",{length:200}),summary:W("summary",{length:"max"}),createdAt:ie("created_at").notNull(),createdBy:W("created_by",{length:50}).notNull(),updatedAt:ie("updated_at").notNull(),updatedBy:W("updated_by",{length:50}).notNull(),deletedAt:ie("deleted_at"),deletedBy:W("deleted_by",{length:50})},m=>[qe({name:`${e}_DailyReportHub_pk`,columns:[m.id]}),Te({name:`${e}_DailyReportHub_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]}),ke(`${e}_DailyReportHub_business_date_index`).on(m.businessDate),ke(`${e}_DailyReportHub_updated_at_index`).on(m.updatedAt),ke(`${e}_DailyReportHub_source_index`).on(m.sourceType,m.sourceId),ke(`${e}_DailyReportHub_user_id_index`).on(m.userId),ke(`${e}_DailyReportHub_business_date_id_index`).on(_o(m.businessDate),_o(m.id)),ke(`${e}_DailyReportHub_deleted_at_index`).on(m.deletedAt)]),a=r.table("DailyReportInternal",{hubId:ne("hub_id",{mode:"number"}).notNull(),body:W("body",{length:"max"}),metadata:W("metadata",{length:"max"}),createdAt:ie("created_at").notNull(),createdBy:W("created_by",{length:50}).notNull(),updatedAt:ie("updated_at").notNull(),updatedBy:W("updated_by",{length:50}).notNull()},m=>[qe({name:`${e}_DailyReportInternal_pk`,columns:[m.hubId]}),Te({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]})]),s=r.table("DailyReportComment",{id:ne("id",{mode:"number"}).identity().notNull(),hubId:ne("hub_id",{mode:"number"}).notNull(),userId:ne("user_id",{mode:"number"}).notNull(),body:W("body",{length:"max"}).notNull(),createdAt:ie("created_at").notNull(),createdBy:W("created_by",{length:50}).notNull(),updatedAt:ie("updated_at").notNull(),updatedBy:W("updated_by",{length:50}).notNull()},m=>[qe({name:`${e}_DailyReportComment_pk`,columns:[m.id]}),Te({name:`${e}_DailyReportComment_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),Te({name:`${e}_DailyReportComment_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]}),ke(`${e}_DailyReportComment_hub_id_index`).on(m.hubId)]),l=r.table("DailyReportLabel",{id:ne("id",{mode:"number"}).identity().notNull(),userId:ne("user_id",{mode:"number"}),name:W("name",{length:50}).notNull(),color:W("color",{length:20}),sortOrder:Ss("sort_order"),createdAt:ie("created_at").notNull(),createdBy:W("created_by",{length:50}).notNull(),updatedAt:ie("updated_at").notNull(),updatedBy:W("updated_by",{length:50}).notNull()},m=>[qe({name:`${e}_DailyReportLabel_pk`,columns:[m.id]}),Te({name:`${e}_DailyReportLabel_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]})]),y=r.table("DailyReportHub_Label",{hubId:ne("hub_id",{mode:"number"}).notNull(),labelId:ne("label_id",{mode:"number"}).notNull(),createdAt:ie("created_at").notNull(),createdBy:W("created_by",{length:50}).notNull()},m=>[qe({name:`${e}_DailyReportHub_Label_pk`,columns:[m.hubId,m.labelId]}),Te({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),Te({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[m.labelId],foreignColumns:[l.id]})]),i=r.table("DailyReportUserStatus",{hubId:ne("hub_id",{mode:"number"}).notNull(),userId:ne("user_id",{mode:"number"}).notNull(),isRead:Eo("is_read").default(!1).notNull(),isStarred:Eo("is_starred").default(!1).notNull(),createdAt:ie("created_at").notNull(),createdBy:W("created_by",{length:50}).notNull(),updatedAt:ie("updated_at").notNull(),updatedBy:W("updated_by",{length:50}).notNull()},m=>[qe({name:`${e}_DailyReportUserStatus_pk`,columns:[m.hubId,m.userId]}),Te({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),Te({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]})]),_=r.table("DailyReportAttachment",{id:ne("id",{mode:"number"}).identity().notNull(),hubId:ne("hub_id",{mode:"number"}).notNull(),uploadedBy:ne("uploaded_by",{mode:"number"}),sourceKey:W("source_key",{length:200}).notNull(),fileName:W("file_name",{length:255}).notNull(),filePath:W("file_path",{length:"max"}).notNull(),fileType:W("file_type",{length:100}),fileSize:ne("file_size",{mode:"number"}),objectCheckedAt:ie("object_checked_at"),objectMissingAt:ie("object_missing_at"),createdAt:ie("created_at").notNull(),createdBy:W("created_by",{length:50}).notNull(),updatedAt:ie("updated_at").notNull(),updatedBy:W("updated_by",{length:50}).notNull()},m=>[qe({name:`${e}_DailyReportAttachment_pk`,columns:[m.id]}),Te({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),Te({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[m.uploadedBy],foreignColumns:[n.id]}),Ts(`${e}_DailyReportAttachment_source_unique`).on(m.hubId,m.sourceKey),ke(`${e}_DailyReportAttachment_hub_id_index`).on(m.hubId,m.createdAt)]);return{hub:o,internal:a,comment:s,attachment:_,label:l,hubLabel:y,userStatus:i}}var _s=5e7,ko=2e8,Es=1,Bo=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})})}),Io=125,wo=4,xo=16,Co=50,Po=2,Kt=Object.freeze({renderMs:ye.renderMs,nanosecondsPerBlockVisit:Io,margin:wo,maxBlockVisits:Math.floor(ye.renderMs*1e6/(Io*wo)),walkBudgetMs:xo,nanosecondsPerWalkStep:Co,walkMargin:Po,maxWalkSteps:Math.floor(xo*1e6/(Co*Po))}),Is=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),Mo=75,vo=4,Lo="#ffffff",ws=1,xs={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},Cs=[/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/],No=Object.freeze({ok:!1,reason:"failed"}),Oo=Object.freeze({ok:!1,reason:"unsupported"}),Uo=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:Mn(e)}),Ho=(e,t)=>{switch(t){case"jpeg":{let r=Ar(e);return r===null?null:Uo(r)}case"png":{let r=Nn(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=On(e,Kt.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},Fo=(e,t)=>{let r=Is.get(t.depth);if(r===void 0)return null;let n=t.channels*r,o=Bo,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},Ps=(e,t,r)=>{let n=Ho(e,t);return n===null?null:Fo(n,r)},Ms=e=>e!==null&&e<=ko,vs=(e,t)=>{if(t!=="jpeg")return Ho(e,t);let r=vn(e,Kt);return r===null||r.blockVisits>Kt.maxBlockVisits?null:Uo(r.header)},Ls=e=>{let t=e instanceof Error?e.message:"";return Cs.some(r=>r.test(t))?"failed":"unsupported"},Ns=e=>{e.cache(!1),e.concurrency(Es),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(xs)});let t=async(n,o,a,s,l)=>{let y=vs(n,o);if(y===null)return Oo;try{let i=e(n,{limitInputPixels:_s,animated:!1});if(!Ms(Fo(y,await i.metadata())))return Oo;if(l.aborted)return No;let _=await i.rotate().resize({width:a,height:s,fit:"inside",withoutEnlargement:!0}).flatten({background:Lo}).webp({quality:Mo,effort:vo}).toBuffer();return{ok:!0,bytes:new Uint8Array(_),contentType:"image/webp"}}catch(i){return{ok:!1,reason:Ls(i)}}},r=async(n,{format:o,maxWidth:a,maxHeight:s,signal:l})=>l.aborted?No:t(n,o,a,s,l);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${Mo}-e${vo}/flatten-${Lo}/v${ws}`,render:r}};function zc(e){e.redis||(e.logger??console).warn("[DailyReport] redis provider is not injected: cross-worker cache invalidation is disabled (staleness is bounded only by TTL) and SSE publishing is skipped.");let t=tr(e.redis),r=new ct({defaultTtlMs:e.cacheDefaultTtlMs??6e4},t),n=Cr({...e,cache:r,epochs:t}),o=new Rt({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),a=xr({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(s=>s.sourceType)])],...a}}export{Dr as DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,Tr as DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,ko as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,Kt as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL,Bo as DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,wr as DAILY_REPORT_SSE_CATCH_UP_BATCH,go as DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,Rt as DailyReportSseReader,ge as DailyReportViewerScope,ct as SqlResultCache,xr as createDailyReportHandlers,zc as createDailyReportServer,Cr as createDailyReportService,tr as createEpochStore,Ns as createSharpThumbnailRenderer,Ds as defineDailyReportSchema,yt as generateETag,Oe as isStreamIdLte,ae as jsonResponseWithETag,cr as parseClientTempId,Ps as predictSharpThumbnailWorkingSetBytes,Rs as transformJsonArray};
1
+ var kr=e=>{throw TypeError(e)};var Br=(e,t,r)=>t.has(e)||kr("Cannot "+r);var ft=(e,t,r)=>(Br(e,t,"read from private field"),r?r.call(e):t.get(e)),rr=(e,t,r)=>t.has(e)?kr("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),nr=(e,t,r,n)=>(Br(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var ae=()=>Math.floor(performance.now());var or=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{}}}),ht=(e,t)=>t?e.map(r=>structuredClone(r)):e,Rt=class{constructor(t,r){this.config=t;this.epochStore=r;this.buckets=new Map;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.config.defaultTtlMs;if(a-(o.expireAt-ae())<a*r||this.inFlight.has(n))return;let l;l=(async()=>{let p=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,s=await t.fetcher();return this.inFlight.get(n)===l&&this.buckets.set(n,{records:s,expireAt:ae()+a,epoch:p}),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}=t,o;o=(async()=>{let i=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null;for(let p of r)p();let l=await t.fetcher();if(this.inFlight.get(n)===o){let p=ae()+(t.ttlMsOverride??this.config.defaultTtlMs);this.buckets.set(n,{records:l,expireAt:p,epoch:i}),this.buckets.size>500&&this.cleanExpired()}return l})(),this.inFlight.set(n,o);let a=()=>{this.inFlight.get(n)===o&&this.inFlight.delete(n)};return o.then(a,a),o};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}=t;if(n)return this.buckets.delete(r),ht(await this.forcedFetch(t),o);let a=this.buckets.get(r);if(a&&a.expireAt>ae())if(t.epochKey){let l=await this.epochStore.getEpoch(t.epochKey);if(l===null||a.epoch===l)return this.maybeRefreshAhead(t),ht(a.records,o);this.buckets.delete(r)}else return this.maybeRefreshAhead(t),ht(a.records,o);let i=this.inFlight.get(r);return ht(i!==void 0?await i:await this.startFetch(t,t.onFetchStart===void 0?[]:[t.onFetchStart]),o)};this.clearAll=()=>{this.buckets.clear(),this.inFlight.clear()};this.invalidatePrefix=t=>{for(let r of this.buckets.keys())r.startsWith(t)&&this.buckets.delete(r);for(let r of this.inFlight.keys())r.startsWith(t)&&this.inFlight.delete(r)}}cleanExpired(){let t=ae();for(let[r,n]of this.buckets.entries())n.expireAt<=t&&this.buckets.delete(r)}};var Ur="ids-stream";var Mt=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+(?=.)/,"")},vt=(e,t)=>e.businessDate!==t.businessDate?e.businessDate===null?1:t.businessDate===null||e.businessDate>t.businessDate?-1:1:t.reportHubId-e.reportHubId,Fr=e=>{for(let t=1;t<e.length;t++)if(vt(e[t-1],e[t])>0)return!1;return!0},Hr=(e,t)=>{let r=e.findIndex(n=>vt({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var Ae=Object.freeze({businessDate:"business-date",idsStream:Ur,report:"report",action:"action"}),Ce=Object.freeze({businessDate:"businessDate",reportHubId:"reportHubId",forceRefresh:"forceRefresh",cursorReportHubId:"cursor_report_hub_id",cursorBusinessDate:"cursor_business_date",cursorSnapshot:"cursor_snapshot"});var ca=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var $r=e=>e<10?`0${e}`:`${e}`,da=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=$r(e.getMonth()+1),n=$r(e.getDate());return`${t}-${r}-${n}`},nt=e=>{let t=ca.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 p=new Date(0);return p.setUTCFullYear(a,i-1,l),p.getUTCFullYear()!==a||p.getUTCMonth()!==i-1||p.getUTCDate()!==l?null:`${r}-${n}-${o}`},Lt=e=>nt(e)===e;var Te=e=>e==null?null:e instanceof Date?da(e):nt(e);var ma=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,Re=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${ma(r)}`),ot=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`);var de=(e,t,r)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r)return t;throw Re(e,`an integer >= ${r}`,t)},qe=(e,t,r,n)=>t===void 0?n:de(e,t,r);var fe=(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)}}};import{z as pa}from"zod";var Ot=e=>Number.isSafeInteger(e)&&e>0,se=pa.number().int().positive().max(Number.MAX_SAFE_INTEGER);var ya=/^[1-9][0-9]*$/,fa=/^(?:0|[1-9][0-9]*)$/,je=e=>{if(e===null||!ya.test(e))return null;let t=Number(e);return Ot(t)?t:null},ar=e=>{if(e===null||!fa.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},ir=e=>e==="true"?!0:e==="false"?!1:null,gt=e=>e===null?!1:ir(e);import{z as Tl}from"zod";var Nt=/^(?:[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 E}from"zod";var Yr=15e3,Vr="lastEventId",ha=/^\d{1,15}-\d{1,15}$/,qr=e=>ha.test(e),Ra=E.object({name:E.string().nullish(),affiliation:E.string().nullish()}),ga=E.object({name:E.string().nullish(),text:E.string().nullish(),color:E.string().nullish()}),ba=E.object({id:se,name:E.string().nullish(),color:E.string().nullish()}),jr=E.object({id:se,userId:E.string().nullish(),userName:E.string().nullish(),content:E.string().nullish(),createdAt:E.string().nullish(),isMine:E.boolean()}),Sa=E.object({id:E.string(),fileName:E.string(),fileType:E.string().nullable(),fileSize:E.number().nullable(),createdAt:E.string().nullable(),state:E.enum(["present","absent","unknown"]),hasThumbnail:E.boolean().default(!1)}),sr=E.object({reportHubId:se,date:E.string().nullish(),createdAt:E.string().nullish(),author:E.string().nullish(),userId:E.string().nullish(),sourceType:E.string().nullish(),employeeName:E.string().nullish(),updatedBy:E.string().nullish(),updatedAt:E.string().nullish(),category:E.string().nullish(),creationCategory:E.string().nullish(),visitTimeFrom:E.string().nullish(),visitTimeTo:E.string().nullish(),customerName:E.string().nullish(),interviewers:E.array(Ra),subject:E.string().nullish(),content:E.string().nullish(),externalComments:E.array(ga),isRead:E.boolean(),isStarred:E.boolean(),labels:E.array(ba),postedComments:E.array(jr),attachments:E.array(Sa).default([])}),ze=E.string().regex(Nt),Aa=E.object({type:E.literal("connected")}),kt=E.object({type:E.literal("status-update"),reportHubId:se,statusType:E.enum(["star","read"]),value:E.boolean(),clientTempId:ze,recipientRawUserId:se.optional()}),lr=E.string().optional(),ur=E.object({type:E.literal("comment-add"),reportHubId:se,comment:jr,clientTempId:ze,recipientRawUserId:se.optional(),sourceType:lr}),cr=E.object({type:E.literal("comment-delete"),reportHubId:se,commentId:se,clientTempId:ze,recipientRawUserId:se.optional(),sourceType:lr}),dr=E.object({type:E.literal("report-create"),reportHubId:se,report:sr,clientTempId:ze,recipientRawUserId:se.optional()}),mr=E.object({type:E.literal("report-update"),reportHubId:se,report:sr,clientTempId:ze,recipientRawUserId:se.optional()}),pr=E.object({type:E.literal("report-publish"),reportHubId:se,report:sr,clientTempId:ze,recipientRawUserId:se.optional()}),yr=E.object({type:E.literal("report-delete"),reportHubId:se,clientTempId:ze,sourceType:lr}),zr=E.discriminatedUnion("type",[Aa,kt,ur,cr,dr,mr,pr,yr]);var De=Object.freeze({intent:"intent",clientTempId:"clientTempId",businessDate:"businessDate",operationTimestamp:"operationTimestamp",reportHubId:"reportHubId",title:"title",content:"content",isStarred:"isStarred",isRead:"isRead",commentId:"commentId"});var Bt=Math.max(1,Math.floor(10.556701030927835));var Ee=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var Ue=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),Ee(()=>{o.delete(i),l.count>0&&n(i,l)},t)};return{record:(i,l,p)=>{let s=o.get(i);if(s!==void 0){s.count+=1,s.tallies[l]+=1;return}p(),a(i)}}};var fr=e=>e!==null&&Nt.test(e)?e:null,Wr=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var Kr=Object.freeze({status:400,error:"Invalid form"}),Jr=e=>({status:413,error:"Form too large",measuredBy:e}),Ta=(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)}}))},Da=async e=>{let t=ar(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:Jr("declared")};let r=!1,n=e.body===null?null:Ta(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?Jr("counted"):Kr}}let l=Wr(i);return l===null?{refusal:Kr}:{fields:l}},Qr=(e,t)=>(r,n)=>{let o=r.get(t);if(o===null)return{error:`${t} required`};let a=ir(o);return a===null?{error:`Invalid ${t}`}:{command:{...n,intent:e,value:a}}},Zr=Object.freeze({update:(e,t,r)=>{let n=e.get(De.title),o=e.get(De.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:Qr("toggleStar",De.isStarred),toggleRead:Qr("toggleRead",De.isRead),addComment:(e,t)=>{let r=e.get(De.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=je(e.get(De.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),_a=e=>Object.hasOwn(Zr,e),Ea=(e,t)=>{let r=e.get(De.intent),n=e.get(De.businessDate),o=n===null?null:nt(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get(De.operationTimestamp),i=ar(a);if(a!==null&&i===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get(De.clientTempId);if(!l)return{error:"clientTempId required"};let p=fr(l);if(p===null)return{error:"Invalid clientTempId"};if(r==="create")return o===null?{error:"businessDate required"}:{command:{intent:r,clientTempId:p,businessDate:o,operationTimestamp:i}};let s=je(e.get(De.reportHubId));return s===null?{error:"Invalid reportHubId"}:r===null||!_a(r)?{error:"Invalid intent"}:Zr[r](e,{clientTempId:p,businessDate:o,operationTimestamp:i,reportHubId:s},t)},en=async(e,t)=>{let r=await Da(e);if("refusal"in r)return r;let n=Ea(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},Ia=6e4,wa="form_too_large",Xr=["declared","counted"],tn=e=>{let t=Ue({windowMs:Ia,tallies:Xr,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${Xr.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(wa,r,n)}};var bt=Object.freeze({[Ae.businessDate]:"json",[Ae.idsStream]:"stream",[Ae.report]:"json"}),rn=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),hr=e=>e!==void 0&&Object.hasOwn(bt,e);var Rr=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),nn=e=>Object.hasOwn(Rr,e);var xa="download",Ca="thumbnail",Pa="1";var gr=e=>{let t=e.getAll(Ca),r=e.getAll(xa);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&nn(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===Pa?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};var Sr="Cross-site request rejected",Ma="Not Found",va=new Set(["same-origin","none"]),La=new Set(["GET","HEAD","OPTIONS"]),on=["api","action","sse","attachment"],an=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}}),Oa=()=>an(403,Sr),Ut=()=>an(404,Ma),St=Object.freeze({navigable:()=>!1,frameworkDataRefusal:()=>null,crossSiteRejection:Oa}),sn=e=>new URL(e.url).pathname.endsWith(".data"),Na=e=>{let t=e.headers.get("Origin");return t===null?!0:URL.canParse(t)&&new URL(t).host===new URL(e.url).host},ln=(e,t)=>{let r=e.headers.get("Sec-Fetch-Site");return r===null?!(La.has(e.method)||Na(e)):va.has(r)?!1:!(e.method==="GET"&&e.headers.get("Sec-Fetch-Mode")==="navigate"&&e.headers.get("Sec-Fetch-Dest")==="document"&&t.navigable(e))},ka=6e4,Ba="refusals",Ua=32,Fa=/^[a-z-]+$/,br=e=>{if(e===null)return"-";let t=e.slice(0,Ua);return Fa.test(t)&&t===e?e:JSON.stringify(t)},un=e=>{let t=Ue({windowMs:ka,tallies:on,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${on.map(i=>`${i}:${a[i]}`).join(",")}`)}});return(r,n)=>{let o=()=>{let{headers:a}=n;e.warn(`cross_site_rejected route=${r} site=${br(a.get("Sec-Fetch-Site"))} mode=${br(a.get("Sec-Fetch-Mode"))} dest=${br(a.get("Sec-Fetch-Dest"))} method=${n.method}`)};t.record(Ba,r,o)}};var cn=(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 Ha="same-origin",$a="SAMEORIGIN",at=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":Ha,"X-Frame-Options":$a}),Ft=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...at});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},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},mn=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),Ya=/^[\x20-\x7E]+$/,Va=/^[\w.+-]+\/[\w.+-]+/,Ar=e=>e&&Ya.test(e)&&Va.test(e)?e:null,qa=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,pn=e=>encodeURIComponent(e.replace(qa,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),yn=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),Ht={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},fn={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},$t=e=>typeof e=="string"&&Object.hasOwn(fn,e),Yt=e=>fn[e],Oe="Attachment request failed";var it=e=>{let t=de("limit",e.limit,1),r=de("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:de("queue.max",e.queue.max,0),maxPerOwner:de("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:de("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],i=new Map,l=new Map,p=(f,T)=>f.get(T)??0,s=(f,T,L)=>{let x=p(f,T)+L;x<=0?f.delete(T):f.set(T,x)},b=f=>p(l,f)<r,d=f=>o<t&&b(f),S=f=>(o+=1,s(l,f,1),h(f)),y=()=>{for(;o<t;){let f=a.findIndex(L=>b(L.owner));if(f<0)return;let[T]=a.splice(f,1);s(i,T.owner,-1),T.grant(S(T.owner))}},h=f=>{let T=!1;return()=>{T||(T=!0,o-=1,s(l,f,-1),y())}};return{canAcquire:d,acquire:(f,T)=>{if(T.aborted)return Promise.resolve(null);if(d(f))return Promise.resolve(S(f));if(n===null||a.length>=n.max||p(i,f)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:L}=n,x=M=>{let I=()=>{let v=a.indexOf(V);v<0||(a.splice(v,1),s(i,f,-1),Y(),M(null))},A=Ee(I,L),Y=()=>{clearTimeout(A),T.removeEventListener("abort",I)},V={owner:f,grant:v=>{Y(),M(v)}};a.push(V),s(i,f,1),T.addEventListener("abort",I,{once:!0})};return new Promise(x)}}};var ja=1024,za="Too many requests",Wa=(e,t)=>{de("limitPerWindow",e,1),de("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 p=l??{tokens:e,lastRefillMs:i};n(p,i),r.set(a,p);for(let s of r.keys()){if(r.size<=ja)break;r.delete(s)}return p};return{consume:(a,i)=>{let l=o(a,i);return l.tokens<1?!1:(l.tokens-=1,!0)},refund:(a,i,l)=>{let p=r.get(a);p&&(n(p,i),p.tokens=Math.min(e,p.tokens+l))}}},We=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(de("windowMs",r,1e3)%1e3!==0)throw Re("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=Wa(e.limitPerWindow,r),i=Object.freeze({status:429,message:za,headers:Object.freeze({"Retry-After":String(r/1e3)})}),l=Ue({windowMs:r,tallies:[t],writeSuppressed:(p,{count:s,since:b})=>{n.warn(`${t}_suppressed count=${s} since=${b} ${o(p)}`)}});return{spend:(p,s)=>a.consume(p,ae())?null:(l.record(p,t,()=>n.warn(`429 ${s} reason=${t}`)),i),refund:(p,s)=>{a.refund(p,ae(),s)}}};import{createHash as Ga}from"crypto";var At=e=>{let t=JSON.stringify(e);return`"${Ga("sha256").update(t).digest("hex")}"`};var ue=(e,t,r,n=200)=>{let o=At(r),a=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate","X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'",ETag:o});return t&&a.append("Set-Cookie",t),e.method==="GET"&&n===200&&e.headers.get("If-None-Match")===o?new Response(null,{status:304,headers:a}):new Response(JSON.stringify(r),{status:n,headers:a})},Ka=5e3/1e3,Ja=new Map([[503,Ka]]),Ne=e=>{let t=Ja.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var Xa=256*1024,hn=6e4,Za=e=>Math.ceil(e/2),ei=new Uint8Array(new ArrayBuffer(0)),ti=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=ei,t()},i=l=>{clearTimeout(o),o=Ee(()=>{l.error(new Error(`attachment body idle for ${hn} ms`)),a()},hn)};return new ReadableStream({start(l){i(l)},pull(l){let p=Math.min(n+Xa,r.byteLength);if(p>n&&l.enqueue(r.slice(n,p)),n=p,n>=r.byteLength){l.close(),a();return}i(l)},cancel(){a()}},{highWaterMark:0})},Rn=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=We({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:p=>`viewer=${p}`}),l=it({limit:e.concurrency,maxHeldPerOwner:Za(e.concurrency),queue:null});return async p=>{let{request:s,delivery:b,attachmentId:d,internalUserId:S,readAttachment:y,cookie:h,fail:f}=p,T=e.maxBytes,L=i.spend(S,`attachment=${d} viewer=${S}`);if(L)return f(L.status,L.message,L.headers);let x=await n(s),M=await t.getAttachmentForUser(x,d,S);if(!M)return o.warn(`404 attachment=${d} viewer=${S} reason=not_visible`),f(404,"Attachment not found");if(M.fileSize!=null&&M.fileSize>T)return o.warn(`413 attachment=${d} viewer=${S} reason=db_size`),f(413,"Attachment too large");let I=Ar(M.fileType),A=`filename="${yn(M.fileName)}"; filename*=UTF-8''${pn(M.fileName)}`,Y=await l.acquire(S,s.signal);if(!Y)return s.signal.aborted?(o.info(`503 attachment=${d} viewer=${S} reason=aborted`),f(503,"Attachment request aborted")):(o.warn(`503 attachment=${d} viewer=${S} reason=concurrency`),f(503,"Too many concurrent downloads",Ne(503)));let V=!1;try{let v=await y(M.filePath,{maxBytes:T,head:s.method==="HEAD",principal:r(S),signal:s.signal});if(s.signal.aborted)return o.info(`503 attachment=${d} viewer=${S} reason=aborted`),f(503,"Attachment request aborted");if(!v.ok){if(!$t(v.reason))return o.error(`500 attachment=${d} viewer=${S} reason=port_contract code=failure_reason`),f(500,Oe);let g=Yt(v.reason);return v.reason==="not_found"&&a(d,!1),o.warn(`${g} attachment=${d} viewer=${S} reason=${v.reason} code=${v.code??"-"}`),f(g,Ht[g],Ne(g))}if(v.bytes.byteLength>T)return o.error(`500 attachment=${d} viewer=${S} reason=port_contract code=over_max_bytes`),f(500,Oe);let Q=s.method==="HEAD";if(Q&&v.size!==void 0&&v.size>T)return o.error(`500 attachment=${d} viewer=${S} reason=port_contract code=over_max_bytes`),f(500,Oe);if(!Q&&v.size!==void 0&&v.size!==v.bytes.byteLength)return o.error(`500 attachment=${d} viewer=${S} reason=port_contract code=size_mismatch`),f(500,Oe);let te=I??Ar(v.contentType),le=te!==null&&mn.has(te),F=le?te:"application/octet-stream",Z=le&&b.kind!=="download"?"inline":"attachment",H=Q?v.size:v.bytes.byteLength,J=new Headers({"Content-Type":F,"Content-Disposition":`${Z}; ${A}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...at});return H!==void 0&&J.set("Content-Length",String(H)),h&&J.append("Set-Cookie",h),a(d,!0),o.info(`200 attachment=${d} viewer=${S} type=${F} disposition=${Z} bytes=${H??"-"}`),Q?new Response(null,{status:200,headers:J}):(V=!0,new Response(ti(v.bytes,Y),{status:200,headers:J}))}finally{V||Y()}}};var be=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),uu=be.queueWaitMs+be.readMs+be.renderMs+be.transferMarginMs;import{Buffer as ri}from"buffer";var Sn=new Set([194,198,202,206]),ni=new Set([192,193,194,195]),An=216,oi=217,Tn=218,ai=4,ii=64,si=2,gn=8,bn=28,Fe=12,Tr=8,li=20,Dn=Fe+Tr+10,ui=2,ke=(e,t)=>e[t]<<8|e[t+1],st=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];return n},Pe=(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},_n=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,En=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),In=e=>(e.stepsLeft-=1,e.stepsLeft>=0),wn=e=>e[0]===255&&e[1]===An,xn=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!In(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===oi)return"eoi";if(o===0||o===An)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=ke(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")}},ci=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!In(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}},Cn=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=ke(e,r+1),a=ke(e,r+3),i=e[r+5];if(a===0||o===0||i===0||n!==8+3*i)return null;let l=[];for(let p=0;p<i;p+=1){let s=e[r+7+3*p],b=s>>4,d=s&15;if(b<1||b>4||d<1||d>4)return null;l.push({id:e[r+6+3*p],horizontal:b,vertical:d})}return{marker:t,width:a,height:o,components:l}},Pn=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>ai||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},Mn=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:Sn.has(e.marker)||t<e.components.length}),Dr=e=>{if(!wn(e))return null;let t=En(e.byteLength),r=null;for(let n=2;;){if(xn(e,n,t)!=="segment")return null;if(_n(t.marker)){if(r!==null||(r=Cn(e,t),r===null))return null}else if(t.marker===Tn){if(r===null)return null;let o=Pn(e,t);return o===null?null:Mn(r,o.length)}n=t.end}},vn=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*gn)),i=Math.ceil(e.height*o/(r*gn));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},Ln=e=>e.multiScan?vn(e).reduce((r,n)=>r+n,0)*ii*si:0,di=896,On=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!wn(e))return null;let n=ri.from(e.buffer,e.byteOffset,e.byteLength),o=En(r),a=null,i=null,l=new Map,p=0,s=0,b=0;for(let d=2;;){let S=xn(e,d,o);if(S===null)return null;if(S==="eoi")return i===null?null:{header:i,blockVisits:s};if(d=o.end,_n(o.marker)){if(a!==null||!ni.has(o.marker)||(a=Cn(e,o),a===null))return null;let y=vn(a);l=new Map;for(let[h,f]of a.components.entries()){let T=l.get(f.id);l.set(f.id,T===void 0?y[h]:Math.max(T,y[h]))}p=a.components.length*(Sn.has(a.marker)?di:1)}else if(o.marker===Tn){if(a===null||b===p)return null;let y=Pn(e,o);if(y===null)return null;for(let f of y){let T=l.get(f);if(T===void 0)return null;s+=T}if(b+=1,i===null&&(i=Mn(a,y.length)),s>t||!i.multiScan)return{header:i,blockVisits:s};let h=ci(n,o.end,o);if(h===null)return null;d=h}}},Nn=e=>{if(e.byteLength<24||ke(e,8)!==0||ke(e,10)!==13||!Pe(e,12,"IHDR"))return null;let t=ke(e,16)*65536+ke(e,18),r=ke(e,20)*65536+ke(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},mi=e=>{if(Pe(e,Fe,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=st(e,26,2)&16383,r=st(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(Pe(e,Fe,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=st(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return Pe(e,Fe,"VP8X")?e.byteLength<Dn?null:{width:st(e,24,3)+1,height:st(e,27,3)+1}:null},kn=e=>{if(Nn(e)===null||e.byteLength<=bn)return null;switch(e[bn]){case 0:return!1;case 1:return!0;default:return null}},Bn=(e,t)=>{if(Pe(e,Fe,"VP8 "))return"lossy";if(Pe(e,Fe,"VP8L"))return"lossless";if(!Pe(e,Fe,"VP8X")||e.byteLength<Dn)return null;if((e[li]&ui)!==0)return"animated";let r=!1,n=t;for(let o=Fe;o+Tr<=e.byteLength;){if(n-=1,n<0)return null;if(Pe(e,o,"VP8L"))return"lossless";if(Pe(e,o,"VP8 "))return r?"lossy-alpha":"lossy";Pe(e,o,"ALPH")&&(r=!0);let a=st(e,o+4,4);o+=Tr+a+a%2}return null},Un={png:Nn,jpeg:Dr,webp:mi};var _r=Object.freeze(["image/webp","image/jpeg","image/png"]),Er=1024*1024;var pi=new Set(["image/png","image/jpeg","image/gif","image/webp"]),yi={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},fi=new Set(_r),hi=e=>typeof e=="string"&&fi.has(e),Ri=256,Vt=(e,t)=>e.fileType===null||!pi.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,gi=[137,80,78,71,13,10,26,10],bi=[255,216,255],Si=[[71,73,70,56,55,97],[71,73,70,56,57,97]],Ai=[82,73,70,70],Ti=[87,69,66,80],Tt=(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},Ir=e=>{if(Tt(e,gi,0))return"png";if(Tt(e,bi,0))return"jpeg";for(let t of Si)if(Tt(e,t,0))return"gif";return Tt(e,Ai,0)&&Tt(e,Ti,8)?"webp":null},Fn=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:At([t])}},Hn=(e,t)=>{if(!hi(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>Er)return"too_large";let r=yi[e.contentType];if(Ir(e.bytes)!==r)return"signature";let n=Un[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},$n=e=>{de("maxBytes",e.maxBytes,0),de("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)+Ri;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 p of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(p)}}}};var wr=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,i=ae(),l=new AbortController,p=!1,s,b,d=()=>{a(ae()-i)},S=I=>{s=Ee(()=>{p=!0,I({timedOut:!0}),b=Ee(d,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},y=new Promise(S),h=AbortSignal.any([r,l.signal]),f=I=>{I(n(h))},T=new Promise(f),L=I=>(clearTimeout(s),clearTimeout(b),p&&o(ae()-i,I.kind==="error"?{error:I.error}:null),I),x=T.then(I=>L({kind:"value",value:I}),I=>L({kind:"error",error:I}));return{outcome:Promise.race([T.then(I=>({timedOut:!1,value:I})),y]),settled:x}};var He={404:"Attachment not found",500:Oe,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},Yn=(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=Hn(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},Di=e=>{let t=new AbortController,r=()=>{t.abort()},n=Ee(r,be.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},Vn=()=>{},_i=(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)}),qn=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:i}=e,l=new Map,p=(y,h)=>{let f=h.then(Vn,Vn);l.set(y,f);let T=()=>{l.get(y)===f&&l.delete(y)};f.then(T)},s=async(y,h)=>{let f=l.get(y.key);if(f===void 0)return t.acquire(y.owner,h);let T=Di(h);try{if(await _i(f,T.signal),T.signal.aborted)return null;let L=r.get(y.key);return L!==void 0?{...L,identity:"verified"}:await t.acquire(y.owner,T.signal)}finally{T.end()}},b=(y,h)=>{if(y.fileSize===null)return h.kind==="exact"?"verified":"unrecorded";if(h.kind==="exact"?h.bytes===y.fileSize:y.fileSize>h.maxBytes)return"verified";let T=h.kind==="exact"?String(h.bytes):`>${h.maxBytes}`;return i.warn(`size_mismatch expected=${y.fileSize} got=${T} attachment=${y.attachmentId} viewer=${y.owner} variant=thumbnail`),"unverified"},d=(y,h)=>(f,T)=>{let L=T===null?"":` message=${T.error instanceof Error?T.error.message:"unknown"}`;i.warn(`${y}_overrun ms=${f} attachment=${h.attachmentId} viewer=${h.owner} variant=thumbnail${L}`)},S=(y,h)=>f=>{i.warn(`${y}_stuck ms=${f} attachment=${h.attachmentId} viewer=${h.owner} variant=thumbnail`)};return async(y,h)=>{let f=await s(y,h);if(f===null)return{kind:"failure",status:503,reason:h.aborted?"aborted":"queue"};if(typeof f!="function")return f;let T=f,L=null;try{if(h.aborted)return{kind:"failure",status:503,reason:"aborted"};let x=r.get(y.key);if(x!==void 0)return{...x,identity:"verified"};let M=wr({budgetMs:be.readMs,flightSignal:h,call:g=>y.readAttachment(y.filePath,{maxBytes:n,head:!1,principal:o(y.owner),signal:g}),onOverrun:d("read",y),onStuck:S("read",y)}),I=await M.outcome;if(I.timedOut)return L=M.settled,h.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(h.aborted)return{kind:"failure",status:503,reason:"aborted"};let A=I.value;if(!A.ok&&A.reason!=="too_large")return $t(A.reason)?(A.reason==="not_found"&&a(y.attachmentId,!1),{kind:"failure",status:Yt(A.reason),reason:A.reason,code:A.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(A.ok&&A.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let Y=b(y,A.ok?{kind:"exact",bytes:A.bytes.byteLength}:{kind:"over",maxBytes:n}),V=g=>{Y==="verified"&&r.set(y.key,g)},v=g=>(V(g),{...g,identity:Y});if(!A.ok)return v({kind:"unrenderable",reason:"too_large"});let Q=Ir(A.bytes);if(Q===null)return v({kind:"unrenderable",reason:"signature"});let te=wr({budgetMs:be.renderMs,flightSignal:h,call:g=>y.renderer.render(A.bytes,{format:Q,maxWidth:y.box.maxWidth,maxHeight:y.box.maxHeight,signal:g}),onOverrun:d("render",y),onStuck:S("render",y)}),le=g=>{if(g.kind==="error")return;let P=Yn(g.value,y.box);"entry"in P&&V(P.entry)},F=null,Z=()=>(F===null&&(F=te.settled.then(le),p(y.key,F)),F);h.addEventListener("abort",Z,{once:!0});let H=await te.outcome.finally(()=>h.removeEventListener("abort",Z));if(H.timedOut||h.aborted)return L=Z(),h.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let J=Yn(H.value,y.box);return"entry"in J?v(J.entry):J.failure}finally{L===null?T():L.then(T,T)}}};var jn=()=>{let e=new Map;return{join:(t,r,n)=>{let o=()=>{let p=new AbortController,s=()=>{e.get(t)?.controller===p&&e.delete(t)},d={promise:n(p.signal).finally(s),controller:p,waiters:0};return e.set(t,d),d},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 Gn=10,Ei=1/Gn,zn=1-Ei,Ii=1024,wi=64,xi=8,Wn="private, no-cache",Ci="no-store",Pi=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),Mi=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},Kn=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:p}=l,s=(I,A)=>We({reason:I,limitPerWindow:A,windowMs:6e4,logger:o,windowFields:Y=>`viewer=${Y} variant=thumbnail`}),b=s("rate_limit",l.rateLimitPerMinute),d=s("revalidation_rate_limit",l.rateLimitPerMinute*Gn),S=it({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:wi,maxPerOwner:xi,maxWaitMs:be.queueWaitMs}}),y=$n({maxBytes:l.cacheBytes,maxEntries:Ii}),h=jn(),f=qn({gate:S,cache:y,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),T=(I,A,Y,V)=>{let v=`attachment=${I.attachmentId} viewer=${I.internalUserId} variant=thumbnail cache=${V}`;if(A.kind==="failure")return o[Mi(A)](`${A.status} ${v} reason=${A.reason} code=${A.code??"-"}`),I.fail(A.status,He[A.status],Ne(A.status));let Q=Pi[A.identity];if(A.kind==="unrenderable")return o.info(`404 ${v} reason=${A.reason}${Q}`),I.fail(404,He[404]);let te=A.identity==="verified"?{"Cache-Control":Wn,ETag:Y}:{"Cache-Control":Ci},le=new Headers({"Content-Type":A.contentType,"Content-Length":String(A.bytes.byteLength),...te,"Content-Security-Policy":"default-src 'none'; sandbox",...at});return I.cookie&&le.append("Set-Cookie",I.cookie),o.info(`200 ${v} type=${A.contentType} bytes=${A.bytes.byteLength}${Q}`),new Response(A.bytes,{status:200,headers:le})},L=(I,A)=>{let Y=I.spend(A.internalUserId,`attachment=${A.attachmentId} viewer=${A.internalUserId} variant=thumbnail`);return Y===null?null:A.fail(Y.status,Y.message,Y.headers)},x=I=>L(b,I),M=(I,A)=>A?L(d,I):x(I);return async(I,A)=>{let{request:Y,attachmentId:V,internalUserId:v,readAttachment:Q,cookie:te,fail:le}=I,F=Rr[A],Z=Y.headers.get("If-None-Match"),H=Z!==null,J=M(I,H);if(J)return J;let g=await n(Y),P=await t.getAttachmentForUser(g,V,v),B=P!==null&&Vt(P,i)?Fn({rendererId:p.id,box:F,attachmentId:V,filePath:P.filePath,fileType:P.fileType,fileSize:P.fileSize}):null;if(B&&dn(Z,B.etag)){let D=new Headers({"Cache-Control":Wn,ETag:B.etag,...at});return te&&D.append("Set-Cookie",te),o.info(`304 attachment=${V} viewer=${v} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:D})}if(H){let D=x(I);if(D)return D}if(!P)return o.warn(`404 attachment=${V} viewer=${v} variant=thumbnail reason=not_visible`),le(404,He[404]);if(!B)return b.refund(v,zn),o.info(`404 attachment=${V} viewer=${v} variant=thumbnail reason=not_eligible`),le(404,He[404]);let{key:U,etag:q}=B,W=y.get(U);if(W)return b.refund(v,zn),T(I,{...W,identity:"verified"},q,"hit");let z=D=>f({key:U,attachmentId:V,filePath:P.filePath,fileSize:P.fileSize,box:F,owner:v,readAttachment:Q,renderer:p},D),G;try{G=await h.join(U,Y.signal,z)}catch(D){return o.error(`500 attachment=${V} viewer=${v} variant=thumbnail cache=miss reason=port_exception message=${D instanceof Error?D.message:"unknown"}`),le(500,He[500])}return T(I,G,q,"miss")}};var vi='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',Li=()=>Ft(403,Sr,{cookie:null}),Jn=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=gr(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>Ft(404,Ht[404],{cookie:null}),crossSiteRejection:Li}),Qn=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:cn(r,a)},p=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:Rn({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:Kn({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:s,params:b})=>{let d=null,S=(y,h,f={})=>Ft(y,h,{cookie:d,extraHeaders:f});try{let{user:y,cookie:h}=await t(s,{failureRedirect:null});if(d=h??null,!y)return S(401,"Unauthorized");let f=gr(new URL(s.url).searchParams);if(f.kind==="invalid")return S(400,"Invalid attachment request");if(f.kind==="thumbnail"&&s.method!=="GET")return S(405,"Method not allowed",{Allow:"GET"});if(s.method!=="GET"&&s.method!=="HEAD")return S(405,"Method not allowed",{Allow:"GET, HEAD"});if(p===null)return S(404,"Attachment not found");if(b.token===void 0)throw new Error(vi);let T=p.idCodec.decode(b.token);if(T===null||!Ot(T))return S(400,"Invalid attachment token");let L=await r.getUserIdByExternalId(y.id);if(!L)return S(403,"Forbidden");let x={request:s,delivery:f,attachmentId:T,internalUserId:L,readAttachment:p.read,cookie:d,fail:S};return f.kind!=="thumbnail"?await p.serveOriginal(x):p.serveThumbnail===null?S(404,He[404]):await p.serveThumbnail(x,f.variant)}catch(y){if(y instanceof Response)throw y;return a.error(`500 attachment=? viewer=? reason=unexpected message=${y instanceof Error?y.message:"unknown"}`),S(500,Oe)}}};var Oi=32*1024*1024,Ni=60,ki=4,Bi=120,Ui=2,Fi=8*1024*1024,qt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Hi=e=>{if(e===void 0)throw ot("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!qt(e))throw Re("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw ot("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw Re("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw Re("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},$i=e=>{if(e===void 0)return null;if(!qt(e))throw Re("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:Hi(e.renderer),rateLimitPerMinute:qe("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,Bi),concurrency:qe("attachments.thumbnails.concurrency",e.concurrency,1,Ui),cacheBytes:qe("attachments.thumbnails.cacheBytes",e.cacheBytes,0,Fi)})},Xn=e=>{let t=e;if(t===void 0)return null;if(!qt(t))throw Re("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw ot("attachments.idCodec","injected when attachments is given");if(!qt(r)||typeof r.encode!="function"||typeof r.decode!="function")throw Re("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw ot("attachments.read","injected when attachments is given");if(typeof n!="function")throw Re("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:qe("attachments.maxBytes",t.maxBytes,1,Oi),rateLimitPerMinute:qe("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,Ni),concurrency:qe("attachments.concurrency",t.concurrency,1,ki),thumbnails:$i(t.thumbnails)})},Yi=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"]]),jt=e=>{for(let[t,r]of Yi)if(Object.hasOwn(e,t))throw ot(r,`given in place of the flat key ${t}`)};var Vi=/^[0-9a-f]{1,16}$/;var Zn=e=>{let t=e.get(Ce.cursorReportHubId),r=e.get(Ce.cursorBusinessDate),n=e.get(Ce.cursorSnapshot),o=n!==null&&Vi.test(n)?n:null,a=null;if(t!==null){let l=je(t);if(l===null)return{refused:"cursor"};if(r!==null&&!Lt(r))return{refused:"cursor"};a={businessDate:r,reportHubId:l}}else if(r!==null)return{refused:"cursor"};let i=gt(e.get(Ce.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var zt=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,qi=2,ji=16,zi=qi*ji,Wi=6e4,eo=()=>{},to=e=>{let t=it({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:zi,queue:null}),r=Ue({windowMs:Wi,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 eo;let i=a.aborted?t.canAcquire(n)?eo:null:await t.acquire(n,a);return i===null&&r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),i}}};var Wt=30,io=4e3,Gi="stream interrupted by server error",Ki="Too many streams",Ji=15e3,so=Symbol("ids-stream-heartbeat"),ro=()=>{},no=e=>e.return(void 0).then(ro,ro),Qi=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(so),Ji)}),stop:()=>clearTimeout(e)}};async function*oo(e,t,r,n){let o=t?Hr(e,t):0,a=!0;for(;;){let i=e.slice(o,o+(a?r:io));o+=i.length;let l=o>=e.length,p=i[i.length-1];if(yield{kind:"chunk",items:i,nextCursor:l||!p?null:{businessDate:p.businessDate,reportHubId:p.reportHubId},isLast:l,...a?{total:e.length}:{},...a?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...a&&n.restarted?{restarted:!0}:{}},a=!1,l)return}}var lo=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform","X-Content-Type-Options":"nosniff"});return e&&t.append("Set-Cookie",e),t},ao=(e,t,r,n,o)=>{r.addEventListener("abort",o,{once:!0});let a=async(b,d)=>{o(),d&&await no(t);try{b.close()}catch{}},i=new TextEncoder,l=!1,p=null,s=new ReadableStream({async pull(b){if(l||r.aborted){await a(b,!0);return}let d=Qi();try{p===null&&(p=t.next());let S=await Promise.race([p,d.fired]);if(d.stop(),S===so){if(l||r.aborted){await a(b,!0);return}b.enqueue(i.encode(`
2
+ `));return}p=null;let{value:y,done:h}=S;if(h){await a(b,!1);return}if(l||r.aborted){await a(b,!0);return}b.enqueue(i.encode(`${JSON.stringify(y)}
3
+ `))}catch(S){if(d.stop(),p=null,o(),l||r.aborted)return;n.error(`ids-stream emission failed: ${S instanceof Error?S.message:String(S)}`);try{let y={kind:"error",error:Gi};b.enqueue(i.encode(`${JSON.stringify(y)}
4
+ `)),b.close()}catch{}}},cancel(){l=!0,o(),no(t)}});return new Response(s,{status:200,headers:lo(e)})},uo=e=>{let{service:t,logger:r,streamSlots:n,refuseForcedRead:o}=e,a=async(i,l,p,s,b,d)=>{let S=!1,y=null,h=null,f=new Promise((x,M)=>{y=x,h=M});f.catch(()=>{});let T=t.getDailyReportIdsByExternalId(p,l.id,{forceRefresh:i.forceRefresh,onFetchStart:i.cursor?void 0:()=>{S=!0,t.readSseStreamAnchor().then(x=>t.getDailyReportIdsFirstPageByExternalId(p,l.id,Wt).then(M=>({items:M,streamAnchor:x}))).then(x=>y?.(x),x=>h?.(x))}});if(T.catch(()=>{}),i.cursor){let{items:x,streamAnchor:M,snapshot:I}=await T,A=i.snapshot!==null&&i.snapshot===I;return ao(s,oo(x,A?i.cursor:null,Wt,{snapshot:I,restarted:!A,streamAnchor:M}),b,r,d)}let L=(async function*(){let x=await Promise.race([T.then(A=>({kind:"full",source:A}),A=>({kind:"full-error",error:A})),f.then(A=>({kind:"page",page:A}),()=>({kind:"page-error"}))]),M=null,I=!1;if(x.kind==="full")M=x.source;else if(x.kind==="page"){let{items:A,streamAnchor:Y}=x.page;if(A.length<Wt){yield{kind:"chunk",items:A,nextCursor:null,isLast:!0,total:A.length,streamAnchor:Y};return}yield{kind:"chunk",items:A,nextCursor:null,isLast:!1,provisional:!0},I=!0}else if(x.kind==="full-error"&&S){let A=await f.catch(()=>null);A&&A.items.length>0&&(yield{kind:"chunk",items:A.items,nextCursor:null,isLast:!1,provisional:!0})}M===null&&(M=await T),yield*oo(M.items,null,I?io:Wt,{snapshot:M.snapshot,streamAnchor:M.streamAnchor})})();return ao(s,L,b,r,d)};return async(i,l,p,s,b)=>{let d=Zn(i.searchParams);if("refused"in d)return ue(p,l,{error:{message:d.refused==="cursor"?"Invalid cursor":"Invalid forceRefresh"}},400);let{query:S}=d;if(S.forceRefresh){let f=o(s,p,l);if(f!==null)return f}let y=zt(p),h=await n.admit(await t.getUserIdByExternalId(s.id),"ids-stream",y);if(h===null){let f=ue(p,l,{error:{message:Ki}},503);for(let[T,L]of Object.entries(Ne(503)))f.headers.set(T,L);return f}if(y.aborted)return new Response(null,{status:200,headers:lo(l)});try{return await a(S,s,b,l,y,h)}catch(f){throw h(),f}}};import{systemSseRuntime as cs}from"@aiquants/sse";import{createSseResponse as ds,readLastEventId as ms,startSseHeartbeat as ps,terminalStreamResponse as ys}from"@aiquants/sse/server";var Dt=(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=zr.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}},Xi=["externalComments","postedComments"],co=new WeakMap,Zi=e=>{let t=co.get(e);if(t!==void 0)return t;let r={recipientRemoved:null,commentsRedacted:null};return co.set(e,r),r},mo=e=>{let{recipientRawUserId:t,...r}=e;return r},po=(e,t)=>{let{published:r}=e;if(!(t||Object.hasOwn(r,"recipientRawUserId")))return e.text;let n=Zi(e);if(t){if(n.commentsRedacted===null){let o=mo(r),a=o.report;n.commentsRedacted=JSON.stringify({...o,report:{...a,...Object.fromEntries(Xi.map(i=>[i,[]]))}})}return n.commentsRedacted}return n.recipientRemoved===null&&(n.recipientRemoved=JSON.stringify(mo(r))),n.recipientRemoved};import{systemSseRuntime as ts}from"@aiquants/sse";import{createSharedSource as rs}from"@aiquants/sse/shared-source";var Ge="daily-report:ids:",Ke="daily-report:business-date:",Gt=(e,t)=>`${e}st:${t}`,xr=e=>`${Ge}user:${e}:`,yo=(e,t)=>Gt(xr(e),t),es=e=>`${Ke}${e}:`,fo=(e,t)=>Gt(es(e),t),_t=e=>`daily-report:date:${e}:user:`,lt=(e,t)=>`${_t(e)}${t}:`,ho=(e,t,r)=>Gt(lt(e,t),r),Me=e=>`daily-report:detail:${e}:user:`,Kt=(e,t)=>`${Me(e)}${t}:`,Ro=(e,t,r)=>Gt(Kt(e,t),r);var $e=(e,t)=>{let[r,n]=e.split("-").map(Number),[o,a]=t.split("-").map(Number);return r!==o?r<o:n<=a},ns=5e3,os=Bt,Et=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=t.logger??fe(1,"[SSE Reader]"),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 rs({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:ts,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:ns,COUNT:os});if(i)for(let l of i)for(let p of l.messages){a=p.id;let{entry:s,json:b}=Dt(p,this._logger);this._invalidateCaches(b),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(Ge),(r==="comment-add"||r==="comment-delete"||r==="status-update")&&typeof n=="number"&&this.config.cache.invalidatePrefix(Me(n))}};import{inArray as as,sql as go}from"drizzle-orm";var is="",ss=64,ls=e=>e.toLowerCase(),us=e=>e.trim().toLowerCase();function bo(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=us(r);n.length>0&&t.add(n)}return t}function ve(e,t){return e===null?!0:t==null?!1:e.has(ls(t))}function Je(e){return e!==null&&e.size===0}function Ao(e,t){if(t!==null)return t.size===0?go`1 = 0`:as(go`LOWER(${e})`,[...t])}var ut,ct,It=class It{constructor(t,r){rr(this,ut);rr(this,ct);nr(this,ut,t),nr(this,ct,r)}get visible(){return ft(this,ut)===null?null:new Set(ft(this,ut))}get commentable(){return ft(this,ct)===null?null:new Set(ft(this,ct))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=bo(r?t.read:t),o=r?t.comment:void 0;if(o===void 0)return new It(n,n);let a=bo(o),i=new Set;for(let l of a??[])n.has(l)&&i.add(l);return new It(n,i)}static unrestricted(t){return new It(null,null)}};ut=new WeakMap,ct=new WeakMap;var _e=It;function wt(e){let t=So(e.visible),r=So(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function So(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(is);if(t.length<=ss)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 _o=Object.freeze({...St,route:"sse",frameworkDataRefusal:Ut}),To=864e5,fs={baseMs:2e3,jitterMs:8e3},Eo=6e4,Pr=Bt,Io=JSON.stringify({type:"connected"}),Do="0-0",hs=(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 ve(r,e.report.sourceType);case"comment-add":case"comment-delete":return ve(n,o??"Internal");case"report-delete":return ve(r,o)}},Rs=(e,t)=>t===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"?!1:!ve(t,e.report.sourceType),gs=(e,t)=>{e.writeEvent({event:null,id:t,data:Io})},bs=(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||!hs(o,a,r.visibleSet,r.commentableSet)){gs(e,t.id);return}e.writeEvent({event:null,id:t.id,data:po(n,Rs(o,r.commentableSet))})},wo=e=>{let{authenticate:t,service:r,resolveViewerScope:n,redis:o,sseReader:a,streamKey:i,streamSlots:l,logger:p}=e,s=async(b,d)=>{let{request:S,internalUserId:y,cursor:h}=d,f=d.initialScope.visible,T=d.initialScope.commentable,L=0,x=setInterval(()=>{let F=++L;n(S,"refresh").then(Z=>{F===L&&(f=Z.visible,T=Z.commentable)})},Eo);b.onClose(()=>clearInterval(x));let M=h===null?Do:h,I=h!==null&&o!==void 0,A=[],Y=null,V=F=>{$e(F.id,M)||(M=F.id,bs(b,F,{internalUserId:y,visibleSet:f,commentableSet:T}))},v=async(F,Z)=>{let[H]=await F.xRange(i,"-","+",{COUNT:1});return H!==void 0&&!$e(H.id,Z)},Q=async(F,Z)=>{if(await v(F,Z))return!1;let H=Z;for(;;){let J=await F.xRange(i,H,"+",{COUNT:Pr}),g=J[0];if(g!==void 0&&g.id!==H&&await v(F,H))return!1;for(let k of J){if(Y!==null&&$e(Y,k.id))return!0;$e(k.id,M)||V(Dt(k,p).entry)}let P=J.at(-1);if(J.length<Pr||P===void 0||b.isClosed())return!0;H=P.id}},te=a.subscribe(F=>{if(!I){V(F);return}$e(F.id,M)||(Y===null&&(Y=F.id),A.push(F))},F=>{p.error(`[SSE:${y}] Fan-Out reader error:`,F),b.close()});if(b.onClose(te),h===null){await a.ready();try{let F=await o?.getClient();if(F){let Z=await F.xRevRange(i,"+","-",{COUNT:1});Z.length>0&&!$e(Z[0].id,M)&&(M=Z[0].id)}}catch{}}if(b.writeEvent({event:null,id:M===Do?null:M,data:Io}),ps(b,{intervalMs:Yr,retry:fs,runtime:cs}),h===null||o===void 0)return;await a.ready();let le=await o.getClient();if(le===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await Q(le,h)){b.writeRetry(To),b.writeEvent({event:"resync-required",id:null,data:""}),b.close();return}I=!1;for(let F of A.splice(0))V(F)};return async({request:b,params:d})=>{let S,y=()=>{let f=new Headers;return S!==void 0&&f.append("Set-Cookie",S),f},h=f=>ys(f,{data:"",retryMs:To,headers:y()});try{let f=await t(b,{failureRedirect:null});S=f.cookie;let{user:T}=f;if(!T)return h("auth-required");let L=await r.getUserIdByExternalId(T.id);if(!L)return h("forbidden");if(d.endpoint!=="updates")return new Response("Not Found",{status:404,headers:y()});let x=ms(b,Vr);if(x!==null&&!qr(x))return p.warn(`[SSE:${L}] malformed resume cursor; asking the client to resync`),h("resync-required");let M=zt(b),I=await l.admit(L,"sse",M);if(I===null){let Y=y();for(let[V,v]of Object.entries(Ne(503)))Y.set(V,v);return new Response("Too many streams",{status:503,headers:Y})}let A=!1;try{let Y=await n(b,"initial");return ds({requestSignal:M,headers:y(),onError:(V,v)=>p.error(`[SSE:${L}] ${v} failed:`,V),produce:V=>(A=!0,V.onClose(I),s(V,{request:b,internalUserId:L,cursor:x,initialScope:Y}))})}finally{A||I()}}catch(f){if(f instanceof Response)throw f;let T=f instanceof Error?f:new Error(String(f));return p.error(`500 sse name=${T.name} message=${T.message}`),new Response("Internal Server Error",{status:500,headers:y()})}}};var xo=(e,t)=>{let r=new Headers({...t?.headers,"Content-Type":"application/json"});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},Ss=Object.freeze({...St,route:"api",frameworkDataRefusal:({params:e})=>hr(e.endpoint)&&bt[e.endpoint]==="stream"?Ut():null}),As=Object.freeze({...St,route:"action"}),Ts=(e,t,r)=>({...r,status:"OK",intent:e.intent,reportHubId:t,clientTempId:e.clientTempId}),Co=6e4,Po=5,Ds=Po*Math.ceil(Co/500),_s=2,Es=6,Is=6e4,ws=Po*_s*Es;function Mr(e){jt(e);let{authenticate:t,service:r,encodeUserId:n,redis:o,sseReader:a,streamKey:i}=e,l={titleMaxLength:de("service.titleMaxLength",r.titleMaxLength,1)},p=e.loginRedirectPath??"/auth/login",s=e.logger??fe(3,"[DailyReportAPI]"),b=e.logger??fe(3,"[DailyReportVisibility]"),d=e.logger??fe(1,"[DailyReportSSE]"),S=e.logger??fe(1,"[DailyReportAttachment]"),y=e.logger??fe(2,"[DailyReportIsolation]"),h=e.logger??fe(2,"[DailyReportAction]"),f=e.logger??fe(2,"[DailyReportAPI]"),T=e.logger??fe(2,"[DailyReportStreams]"),L=We({reason:"refresh_rate_limit",limitPerWindow:ws,windowMs:Is,logger:f,windowFields:()=>"route=api"}),x=to(T),M=(g,P,k,B)=>{let U=L.spend(P.id,`endpoint=${g}`);if(U===null)return null;let q=ue(k,B,{error:{message:U.message}},U.status);for(let[W,z]of Object.entries(U.headers))q.headers.set(W,z);return q},I=async(g,P="initial")=>{let k=e.resolveVisibleSourceTypes;if(!k)return _e.unrestricted("no visibility port injected: this deployment does not restrict by source type");try{let B=await k(g,{reason:P});return B==null?_e.unrestricted("visibility port returned null/undefined: this deployment opts out of source-type filtering"):_e.restrictTo(B)}catch(B){return b.error("resolveVisibleSourceTypes threw; failing closed (deny all)",B),_e.restrictTo([])}},A=async({request:g})=>{let{user:P,cookie:k}=await t(g,{failureRedirect:p}),B=new Headers;k&&B.append("Set-Cookie",k);let U=await r.getUserIdByExternalId(P.id),q=U?n(U):null;return{data:{user:P,userId:q},headers:B}},Y={[Ae.businessDate]:async(g,P,k,B,U)=>{let q=g.searchParams.get(Ce.businessDate),W=q===null?null:nt(q);if(W===null)return ue(k,P,{error:{message:"Invalid business date"}},400);let z=gt(g.searchParams.get(Ce.forceRefresh));if(z===null)return ue(k,P,{error:{message:"Invalid forceRefresh"}},400);let G=z?M(Ae.businessDate,B,k,P):null;if(G!==null)return G;let D=await r.getDailyReportsByBusinessDateByExternalId(U,W,B.id,{forceRefresh:z});return ue(k,P,{businessDate:W,reports:D},200)},[Ae.idsStream]:uo({service:r,logger:s,streamSlots:x,refuseForcedRead:(g,P,k)=>M(Ae.idsStream,g,P,k)}),[Ae.report]:async(g,P,k,B,U)=>{let q=je(g.searchParams.get(Ce.reportHubId));if(q===null)return ue(k,P,{error:{message:"Invalid reportHubId"}},400);let W=gt(g.searchParams.get(Ce.forceRefresh));if(W===null)return ue(k,P,{error:{message:"Invalid forceRefresh"}},400);let z=W?M(Ae.report,B,k,P):null;if(z!==null)return z;let G=await r.getDailyReportDetailByIdByExternalId(U,q,B.id,{snapshot:!0,forceRefresh:W});return G?ue(k,P,{report:G},200):ue(k,P,{error:{message:"Report not found"}},404)}},V=async({request:g,params:P})=>{let{user:k,cookie:B}=await t(g,{failureRedirect:null}),U=B??null;if(!k)return ue(g,U,{error:{message:"Unauthorized"}},401);let q=P.endpoint;if(!hr(q))return ue(g,U,{error:{message:"Unknown endpoint"}},404);let W=rn[bt[q]];if(!W.includes(g.method)){let G=ue(g,U,{error:{message:"Method not allowed"}},405);return G.headers.set("Allow",W.join(", ")),G}let z=ae();try{let G=new URL(g.url),D=await I(g),ie=await Y[q](G,U,g,k,D);return bt[q]==="json"&&s.debug(`${ie.status} endpoint=${q} etag_match=${ie.status===304}`),ie}catch(G){let D=ae()-z,ie=G instanceof Error?G:new Error(String(G));return s.error(`500 endpoint=${q} elapsed=${D}ms name=${ie.name} code=${"code"in ie?ie.code:"N/A"} message=${ie.message}`),s.error("Stack:",ie.stack),ue(g,U,{error:{message:"Internal Server Error"}},500)}},v=tn(h),Q=We({reason:"rate_limit",limitPerWindow:Ds,windowMs:Co,logger:h,windowFields:()=>"route=action"}),te=async(g,P,k,B,U)=>{let{clientTempId:q}=g;if(g.intent==="create"){let D=await r.createDailyReport(P,g.businessDate,q);return U(g,D.reportHubId,{report:D})}let{reportHubId:W,businessDate:z}=g,G=async(D,ie)=>{try{let xe=await ie(D.value);return U(D,W,{updatedStatus:{isStarred:xe.isStarred,isRead:xe.isRead},operationTimestamp:D.operationTimestamp})}catch(xe){if(xe instanceof Error&&xe.message==="Not Found")return B({error:"Report not found"},{status:404});throw xe}};switch(g.intent){case"update":try{return await r.updateDailyReport(W,P,g.changes,q),U(g,W,{})}catch(D){if(D instanceof Error){if(D.message==="Unauthorized")return B({error:"Unauthorized"},{status:403});if(D.message==="Not Found")return B({error:"Report not found"},{status:404})}throw D}case"publish":try{let D=await r.publishDailyReport(W,P,q);return U(g,W,{report:D})}catch(D){if(D instanceof Error){if(D.message==="Unauthorized")return B({error:"Unauthorized"},{status:403});if(D.message==="Not Found")return B({error:"Report not found"},{status:404})}throw D}case"delete":try{return await r.deleteDailyReport(W,P,q),U(g,W,{})}catch(D){if(D instanceof Error){if(D.message==="Unauthorized")return B({error:"Unauthorized"},{status:403});if(D.message==="Not Found")return B({error:"Report not found"},{status:404})}throw D}case"toggleStar":return await G(g,D=>r.setStarStatus(k,P,W,z,D,q));case"toggleRead":return await G(g,D=>r.setReadStatus(k,P,W,z,D,q));case"addComment":try{let D=await r.addComment(k,P,W,g.content,z,q);return U(g,W,{newComment:D})}catch(D){if(D instanceof Error){if(D.message==="Not Found")return B({error:"Report not found"},{status:404});if(D.message.startsWith("Comments are restricted"))return B({error:"Comments are restricted for this report"},{status:403})}throw D}case"deleteComment":try{return await r.deleteComment(k,P,W,g.commentId,z,q),U(g,W,{deletedCommentId:g.commentId})}catch(D){if(D instanceof Error){if(D.message==="Unauthorized")return B({error:"Unauthorized"},{status:403});if(D.message==="Not Found")return B({error:"Comment not found"},{status:404})}throw D}}},le=async({request:g,params:P})=>{let{user:k,cookie:B}=await t(g,{failureRedirect:null}),U=(z,G)=>xo(z,{...G,setCookie:B}),q=(z,G,D)=>xo(Ts(z,G,D),{setCookie:B});if(!k)return U({error:"Unauthorized"},{status:401});let W=ae();try{if(P.endpoint!==Ae.action)return U({error:"Unknown endpoint"},{status:404});let z=Q.spend(k.id,"action");if(z!==null)return U({error:z.message},{status:z.status,headers:z.headers});let G=await en(g,l);if("refusal"in G){let{refusal:Ze}=G;return Ze.status===413&&v(Ze.measuredBy),U({error:Ze.error},{status:Ze.status})}let{command:D}=G;if(D.intent==="clearCache"&&!e.enableDevCacheClear)return U({error:"Invalid intent"},{status:400});let ie=await r.getUserIdByExternalId(k.id);if(!ie)return U({error:"User not found"},{status:404});let xe=await I(g);return D.intent==="clearCache"?(await r.clearCache(),U({status:"OK",intent:"clearCache"})):await te(D,ie,xe,U,q)}catch(z){if(z instanceof Response)throw z;let G=ae()-W,D=z instanceof Error?z:new Error(String(z));return s.error(`500 action elapsed=${G}ms name=${D.name} message=${D.message}`),s.error("Stack:",D.stack),U({error:"Internal Server Error"},{status:500})}},F=wo({authenticate:t,service:r,resolveViewerScope:I,redis:o,sseReader:a,streamKey:i,streamSlots:x,logger:d}),Z=Qn({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:I,logger:S}),H=un(y),J=(g,P)=>async k=>{let B=sn(k.request)?g.frameworkDataRefusal(k):null;if(B!==null)throw B;return ln(k.request,g)?(H(g.route,k.request),g.crossSiteRejection()):P(k)};return{index:{loader:A},api:{loader:J(Ss,V),action:J(As,le)},sse:{loader:J(_o,F)},attachment:{loader:J(Jn,Z)}}}import{runWithTransactionRetry as Cs}from"@aiquants/mssql";import{aliasedTable as dt,and as ne,asc as Jt,desc as mt,eq as C,getColumns as Ps,inArray as Ie,isNull as ge,or as pt,sql as Mo}from"drizzle-orm";var Qe=e=>Ps(e),vo=Mt([]),he=(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"),p=String(r.getMinutes()).padStart(2,"0"),s=String(r.getSeconds()).padStart(2,"0");return`${o}-${a}-${i} ${l}:${p}:${s}`},Ms=e=>{let{length:t}=e;if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=1)return t;throw Re("tables.hub.title","a character column with a declared length",t)},Lo=e=>e===""?null:e;function vr(e){let{db:t,tables:r,userTable:n,resolveUserId:o,encodeUserId:a,redis:i,cache:l,epochs:p}=e,{hub:s,internal:b,comment:d,label:S,hubLabel:y,userStatus:h}=r,f=e.externalSources??[],T=e.draftLabelNames&&e.draftLabelNames.length>0?e.draftLabelNames:[e.draftLabelName??"\u4E0B\u66F8\u304D"],L=T[0]??"\u4E0B\u66F8\u304D",x=e.logger??fe(1,"[DailyReportService]");jt(e);let M=Xn(e.attachments),I=Ms(s.title),A=c=>Cs(u=>t.transaction(m=>u(()=>c(m))),e.transactionRetry),Y=e.idsTtlMs??18e4,V="daily-report:ids:epoch",v=e.businessDateTtlMs??3e5,Q="daily-report:date-epoch:",te="daily-report:detail-epoch:",F=`${e.streamKey??"daily-report:sse-stream"}:v2`,Z=e.streamMaxLen??1e4,H=c=>p.incrementEpoch(c),J=c=>Ao(s.sourceType,c),g=async(c,u)=>{let m=await i?.getClient();if(!m){x.warn(`[SSE] Redis client unavailable (${u})`);return}let R=JSON.stringify(c),w=Buffer.byteLength(R);if(w>6356992){x.warn(`[SSE] Event too large (${u}): ${w} bytes > ${6356992}; not published`);return}let O=ae();try{await m.xAdd(F,"*",{data:R},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:Z}});let _=ae()-O;_>1e3&&x.warn(`[SSE] Slow publish (${u}): ${_}ms`)}catch(_){x.error(`[SSE] Redis publish failed (${u}):`,_)}},P=async()=>{try{let c=await i?.getClient();if(c===void 0)return null;let[u]=await c.xRevRange(F,"+","-",{COUNT:1});return u===void 0?null:u.id}catch(c){return x.error("[DailyReportService] SSE stream anchor read failed",c),null}},k=c=>c==null||c===""?null:/^\d+$/.test(c)?a(Number(c)):c,B=()=>{let c={};for(let u of f)c[`ext_${u.sourceType}`]=Qe(u.table);return c},U=c=>{let u=c;for(let m of f)u=u.leftJoin(m.table,ne(C(s.sourceType,m.sourceType),C(s.sourceIdNum,m.idColumn)));return u},q=(c,u,m)=>{let{hub:R,internal:w}=u,O=R.summary,_=[],N=null,$=null,j=null,ee=null,re=null,Se=null,tt=[],Be=f.find(K=>K.sourceType===R.sourceType),rt=Be?u[`ext_${Be.sourceType}`]:void 0;if(Be&&rt){let K=Be.mapRow(rt);K.content!==void 0&&(O=K.content),K.employeeName!==void 0&&(Se=K.employeeName),K.category!==void 0&&(N=K.category),K.creationCategory!==void 0&&($=K.creationCategory),K.visitTimeFrom!==void 0&&(j=K.visitTimeFrom),K.visitTimeTo!==void 0&&(ee=K.visitTimeTo),K.customerName!==void 0&&(re=K.customerName),K.interviewers!==void 0&&(_=K.interviewers),K.externalComments!==void 0&&(tt=K.externalComments)}else R.sourceType==="Internal"&&w&&(O=w.body);let Le=(u.labels??[]).map(K=>({id:K.id,name:K.name,color:K.color})),pe=u.postedCommentRows??[],oe=ve(c.commentable,R.sourceType),ye=$?T.includes($):!1,tr=et?.[0]??null;return ye&&tr&&!Le.some(K=>K.id===tr)&&Le.push({id:tr,name:L,color:null}),{reportHubId:R.id,date:he(R.businessDate,"YYYY-MM-DD"),author:u.creatorName??k(R.createdBy)??"",userId:R.userId?a(R.userId):"",sourceType:R.sourceType??"Internal",createdAt:he(R.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:he(R.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:k(R.updatedBy),employeeName:Se??u.creatorName??k(R.createdBy),category:N,creationCategory:$,visitTimeFrom:j,visitTimeTo:ee,customerName:re,interviewers:_,subject:R.title,content:O,externalComments:oe?tt:[],isRead:u.isRead??!1,isStarred:u.isStarred??!1,labels:Le,postedComments:pe.filter(K=>oe||m!==void 0&&K.userId===m).map(K=>({...K,userId:a(K.userId),isMine:m?K.userId===m:!1})),attachments:u.attachments}},W=async(c,u)=>{let m=dt(y,"draft_label"),R=await Ve();return(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).from(s).leftJoin(m,ne(C(m.hubId,s.id),Ie(m.labelId,R))).where(ne(ge(s.deletedAt),pt(C(s.userId,u),ge(s.userId),ge(m.hubId)),J(c.visible))).orderBy(mt(s.businessDate),mt(s.id))).map(O=>({...O,businessDate:he(O.businessDate,"YYYY-MM-DD")}))},z=async(c,u,m)=>{let R=await ie(u);if(!R)return[];if(Je(c.visible))return[];let w=dt(y,"draft_label"),O=await Ve();return(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).top(m).from(s).leftJoin(w,ne(C(w.hubId,s.id),Ie(w.labelId,O))).where(ne(ge(s.deletedAt),pt(C(s.userId,R),ge(s.userId),ge(w.hubId)),J(c.visible))).orderBy(mt(s.businessDate),mt(s.id))).map(N=>({...N,businessDate:he(N.businessDate,"YYYY-MM-DD")}))},G=async(c,u)=>{let m=await U(t.select({hub:Qe(s),internal:Qe(b),creatorName:n.displayName,...B()}).from(s)).leftJoin(b,C(s.id,b.hubId)).leftJoin(n,C(s.userId,n.id)).where(ne(C(s.businessDate,Mo`${u}`),ge(s.deletedAt),J(c.visible))).orderBy(mt(s.id)),R=await Ct(m.map(w=>w.hub.id));return m.map(w=>q(c,{...w,attachments:R.get(w.hub.id)??[]}))},D=new Map,ie=async c=>{if(!e.disableUserIdCache&&D.has(c))return D.get(c)??null;let u=await o(c);return u!==null&&!e.disableUserIdCache&&D.set(c,u),u},xe=async(c,u,{forceRefresh:m=!1,snapshot:R=!1,ttlMsOverride:w,onFetchStart:O}={})=>{let _=await ie(u);if(!_)return{items:[],streamAnchor:null,snapshot:vo};if(Je(c.visible))return{items:[],streamAnchor:await P(),snapshot:vo};let N=yo(_,wt(c)),[$]=await l.getOrFetch({cacheKey:N,fetcher:async()=>{let j=await P(),ee=await W(c,_);if(!Fr(ee)){x.warn("[DailyReportService] ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)");let re=[...ee].sort(vt);return[{items:re,streamAnchor:j,snapshot:Mt(re)}]}return[{items:ee,streamAnchor:j,snapshot:Mt(ee)}]},onFetchStart:O,forceRefresh:m,snapshot:R,ttlMsOverride:w??Y,epochKey:V,refreshAheadRatio:.5});if($===void 0)throw new Error("[DailyReportService] ids cache returned no record");return $},Ze=(c,u,{forceRefresh:m=!1,snapshot:R=!1,ttlMsOverride:w}={})=>{let O=Te(u);return O?Je(c.visible)?Promise.resolve([]):l.getOrFetch({cacheKey:fo(O,wt(c)),fetcher:()=>G(c,O),forceRefresh:m,snapshot:R,ttlMsOverride:w??v}):Promise.resolve([])},et=null,xt=async()=>(et!==null||(et=(await t.select({id:S.id}).from(S).where(Ie(S.name,T)).orderBy(S.id)).map(u=>u.id)),et),Ve=async()=>{let c=await xt();return c.length>0?c:[-1]},Xt=async()=>{let c=await xt();if(c.length===0)return null;let[u]=await t.select({id:S.id}).top(1).from(S).where(C(S.name,L));return u?.id??c[0]},Qo=(c,u)=>u!=null?"absent":c!=null?"present":"unknown",Ct=async c=>{let u=new Map,m=r.attachment;if(c.length===0||!m||M===null)return u;let R=M.idCodec,w=M.thumbnails!==null,O=await t.select({id:m.id,hubId:m.hubId,fileName:m.fileName,fileType:m.fileType,fileSize:m.fileSize,createdAt:m.createdAt,objectCheckedAt:m.objectCheckedAt,objectMissingAt:m.objectMissingAt}).from(m).where(Ie(m.hubId,c)).orderBy(Jt(m.createdAt),Jt(m.id));for(let _ of O){let N=_.fileType?String(_.fileType):null,$=_.fileSize!=null?Number(_.fileSize):null,j=Qo(_.objectCheckedAt,_.objectMissingAt),ee={id:R.encode(Number(_.id)),fileName:String(_.fileName),fileType:N,fileSize:$,createdAt:he(_.createdAt,"YYYY-MM-DD HH:mm:ss"),state:j,hasThumbnail:w&&j!=="absent"&&Vt({fileType:N,fileSize:$},M.maxBytes)},re=u.get(Number(_.hubId));re?re.push(ee):u.set(Number(_.hubId),[ee])}return u},Xo=async(c,u,m)=>{let R=r.attachment;if(!R||Je(c.visible))return null;let w=await Ve(),O=dt(y,"draft_label");return(await t.select({fileName:R.fileName,filePath:R.filePath,fileType:R.fileType,fileSize:R.fileSize}).top(1).from(R).innerJoin(s,C(s.id,R.hubId)).leftJoin(O,ne(C(O.hubId,s.id),Ie(O.labelId,w))).where(ne(C(R.id,u),ge(s.deletedAt),pt(C(s.userId,m),ge(O.hubId)),J(c.visible))))[0]??null},Zo=async c=>{let u=r.attachment;if(!u)return;let m=new Date;try{await t.update(u).set({objectCheckedAt:m,objectMissingAt:m,updatedAt:m}).where(C(u.id,c))}catch(R){x.error("markAttachmentMissing failed",R)}},ea=async c=>{let u=r.attachment;if(!u)return;let m=new Date;try{await t.update(u).set({objectCheckedAt:m,objectMissingAt:null,updatedAt:m}).where(C(u.id,c))}catch(R){x.error("markAttachmentPresent failed",R)}},ta=async(c,u,m,{forceRefresh:R=!1,snapshot:w=!1,ttlMsOverride:O}={})=>{let _=await ie(m);if(!_)return[];let N=Te(u);if(!N)return[];if(Je(c.visible))return[];let $=ho(N,_,wt(c));return l.getOrFetch({cacheKey:$,fetcher:async()=>{let j=await Ve(),ee=dt(y,"draft_label"),re=await U(t.select({hub:Qe(s),internal:Qe(b),isRead:h.isRead,isStarred:h.isStarred,creatorName:n.displayName,...B()}).from(s)).leftJoin(b,C(s.id,b.hubId)).leftJoin(h,ne(C(s.id,h.hubId),C(h.userId,_))).leftJoin(ee,ne(C(ee.hubId,s.id),Ie(ee.labelId,j))).leftJoin(n,C(s.userId,n.id)).where(ne(C(s.businessDate,Mo`${N}`),ge(s.deletedAt),pt(C(s.userId,_),ge(ee.hubId)),J(c.visible))).orderBy(mt(s.id));if(re.length===0)return[];let Se=re.map(oe=>oe.hub.id),tt=await t.select({hubId:y.hubId,id:S.id,name:S.name,color:S.color}).from(y).innerJoin(S,C(y.labelId,S.id)).where(Ie(y.hubId,Se)),Be=await t.select({hubId:d.hubId,id:d.id,body:d.body,createdAt:d.createdAt,userId:d.userId,userName:n.displayName}).from(d).leftJoin(n,C(d.userId,n.id)).where(Ie(d.hubId,Se)).orderBy(Jt(d.createdAt)),rt=await Ct(Se),Le=new Map,pe=new Map;for(let oe of tt){let ye=Le.get(oe.hubId);ye||(ye=[],Le.set(oe.hubId,ye)),ye.push({id:oe.id,name:oe.name,color:oe.color})}for(let oe of Be){let ye=pe.get(oe.hubId);ye||(ye=[],pe.set(oe.hubId,ye)),ye.push({id:oe.id,content:oe.body,createdAt:he(oe.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:oe.userId,userName:oe.userName||""})}return re.map(oe=>{let ye=oe.hub.id;return q(c,{...oe,attachments:rt.get(ye)??[],labels:Le.get(ye)||[],postedCommentRows:pe.get(ye)||[]},_)})},forceRefresh:R,snapshot:w,ttlMsOverride:O??v,epochKey:`${Q}${N}`})},yt=async(c,u,m,{forceRefresh:R=!1,snapshot:w=!1,ttlMsOverride:O}={})=>{if(Je(c.visible))return null;let _=Ro(u,m,wt(c));return(await l.getOrFetch({cacheKey:_,fetcher:async()=>{let $=await Ve(),j=dt(y,"draft_label"),ee=await U(t.select({hub:Qe(s),internal:Qe(b),isRead:h.isRead,isStarred:h.isStarred,creatorName:n.displayName,...B()}).from(s)).leftJoin(b,C(s.id,b.hubId)).leftJoin(h,ne(C(s.id,h.hubId),C(h.userId,m))).leftJoin(j,ne(C(j.hubId,s.id),Ie(j.labelId,$))).leftJoin(n,C(s.userId,n.id)).where(ne(C(s.id,u),ge(s.deletedAt),pt(C(s.userId,m),ge(j.hubId)),J(c.visible)));if(ee.length===0)return[];let re=ee[0].hub.id,Se=await t.select({id:S.id,name:S.name,color:S.color}).from(y).innerJoin(S,C(y.labelId,S.id)).where(C(y.hubId,re)),tt=await t.select({id:d.id,body:d.body,createdAt:d.createdAt,userId:d.userId,userName:n.displayName}).from(d).leftJoin(n,C(d.userId,n.id)).where(C(d.hubId,re)).orderBy(Jt(d.createdAt)),Be=await Ct([re]),rt=Se.map(pe=>({id:pe.id,name:pe.name,color:pe.color})),Le=tt.map(pe=>({id:pe.id,content:pe.body,createdAt:he(pe.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:pe.userId,userName:pe.userName||""}));return[q(c,{...ee[0],attachments:Be.get(re)??[],labels:rt,postedCommentRows:Le},m)]},forceRefresh:R,snapshot:w,ttlMsOverride:O??v,epochKey:`${te}${u}`}))[0]??null},ra=async(c,u,m,R={})=>{let w=await ie(m);return w?yt(c,u,w,R):null},na=async(c,u)=>{let m=await Ve(),R=dt(y,"draft_label"),[w]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt}).top(1).from(s).leftJoin(R,ne(C(R.hubId,s.id),Ie(R.labelId,m))).where(ne(C(s.id,c),pt(C(s.userId,u),ge(R.hubId))));return w??null},Zt=async(c,u,m)=>{let R=await na(u,m);if(!R||R.deletedAt||!ve(c.visible,R.sourceType))throw new Error("Not Found")},oa=async(c,u,m,R,w,O)=>{await Zt(c,m,u);let _=await t.select().top(1).from(h).where(ne(C(h.hubId,m),C(h.userId,u))),N;if(_.length>0?_[0].isStarred!==w?N=(await t.update(h).set({isStarred:w,updatedAt:new Date,updatedBy:String(u)}).output().where(ne(C(h.hubId,m),C(h.userId,u))))[0]:N=_[0]:N=(await t.insert(h).output().values({hubId:m,userId:u,isStarred:w,isRead:!1,createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)}))[0],R){let $=Te(R);$&&(l.invalidatePrefix(lt($,u)),await H(`${Q}${$}`))}return l.invalidatePrefix(Kt(m,u)),await H(`${te}${m}`),await g(kt.parse({type:"status-update",reportHubId:m,recipientRawUserId:u,statusType:"star",value:w,clientTempId:O}),"setStarStatus"),N},aa=async(c,u,m,R,w,O)=>{await Zt(c,m,u);let _=await t.select().top(1).from(h).where(ne(C(h.hubId,m),C(h.userId,u))),N;if(_.length>0?_[0].isRead!==w?N=(await t.update(h).set({isRead:w,updatedAt:new Date,updatedBy:String(u)}).output().where(ne(C(h.hubId,m),C(h.userId,u))))[0]:N=_[0]:N=(await t.insert(h).output().values({hubId:m,userId:u,isRead:w,isStarred:!1,createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)}))[0],R){let $=Te(R);$&&(l.invalidatePrefix(lt($,u)),await H(`${Q}${$}`))}return l.invalidatePrefix(Kt(m,u)),await H(`${te}${m}`),await g(kt.parse({type:"status-update",reportHubId:m,recipientRawUserId:u,statusType:"read",value:w,clientTempId:O}),"setReadStatus"),N},Lr=async(c,u)=>{if(u===null)return;let m=await Ve(),[R]=await t.select({hubId:y.hubId}).top(1).from(y).where(ne(C(y.hubId,c),Ie(y.labelId,m)));return R?u:void 0},ia=async(c,u,m,R,w,O)=>{let[_]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt,userId:s.userId}).top(1).from(s).where(C(s.id,m));if(!_||_.deletedAt)throw new Error("Not Found");if(await Zt(c,m,u),!ve(c.commentable,_.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(_.sourceType.toLowerCase()!=="internal")throw new Error("Comments are restricted for external daily report sources");let N=await Lr(m,_.userId),[$]=await t.insert(d).output().values({hubId:m,userId:u,body:R,createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)}),[j]=await t.select({displayName:n.displayName}).top(1).from(n).where(C(n.id,u)),ee=j?.displayName??"";if(w){let Se=Te(w);Se&&(l.invalidatePrefix(_t(Se)),await H(`${Q}${Se}`))}l.invalidatePrefix(Me(m)),await H(`${te}${m}`);let re={id:$.id,userId:a($.userId),userName:ee,content:$.body,createdAt:he($.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await g(ur.parse({type:"comment-add",reportHubId:m,comment:re,clientTempId:O,recipientRawUserId:N,sourceType:_.sourceType}),"addComment"),re},sa=async(c,u)=>await c.select().top(1).from(d).where(C(d.id,u)),la=async(c,u,m,R,w,O)=>{let _=await sa(t,R);if(_.length===0)throw new Error("Not Found");if(_[0].hubId!==m)throw new Error("Not Found");let[N]=await t.select({userId:s.userId,sourceType:s.sourceType}).top(1).from(s).where(C(s.id,_[0].hubId));if(!(N&&ve(c.visible,N.sourceType)))throw new Error("Not Found");if(_[0].userId!==u)throw new Error("Unauthorized");let $=await Lr(m,N.userId);if(await t.delete(d).where(C(d.id,R)),w){let j=Te(w);j&&(l.invalidatePrefix(_t(j)),await H(`${Q}${j}`))}l.invalidatePrefix(Me(m)),await H(`${te}${m}`),await g(cr.parse({type:"comment-delete",reportHubId:m,commentId:R,clientTempId:O,recipientRawUserId:$,sourceType:N?.sourceType}),"deleteComment")},ua=async(c,u,m)=>{if(!Lt(u))throw Re("createDailyReport: businessDate","a business-date key in the canonical form YYYY-MM-DD naming a day from 0001-01-01 to 9999-12-31",u);x.info("createDailyReport called",{userId:c,businessDate:u});let[R]=await t.select({displayName:n.displayName}).from(n).where(C(n.id,c)),w=R?.displayName??a(c);try{let O=await A(async N=>{x.info("Starting transaction");let $=`internal-temp-${Date.now()}-${Math.random()}`,[j]=await N.insert(s).output().values({sourceType:"Internal",sourceId:$,businessDate:new Date(`${u}T00:00:00Z`),userId:c,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(c),updatedAt:new Date,updatedBy:String(c)});await N.update(s).set({sourceId:String(j.id)}).where(C(s.id,j.id)),x.info("Hub created",j),await N.insert(b).values({hubId:j.id,body:"",createdAt:new Date,createdBy:String(c),updatedAt:new Date,updatedBy:String(c)}),x.info("Internal created"),x.info("Calling getDraftLabelId");let ee=await Xt();x.info("draftLabelId",ee);let re=[];return ee&&(await N.insert(y).values({hubId:j.id,labelId:ee,createdAt:new Date,createdBy:String(c)}),re.push({id:ee,name:L,color:null})),x.info("Label assigned"),{reportHubId:j.id,date:u,createdAt:he(j.createdAt,"YYYY-MM-DD HH:mm:ss"),author:w,userId:a(c),sourceType:"Internal",employeeName:w,updatedBy:a(c),updatedAt:he(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,labels:re,postedComments:[],attachments:[]}});l.invalidatePrefix(lt(u,c)),l.invalidatePrefix(Ke),l.invalidatePrefix(xr(c)),await H(V),await H(`${Q}${u}`);let _=await yt(_e.unrestricted("post-write self read: the writer always sees the row they just wrote"),O.reportHubId,c,{forceRefresh:!0});if(_){let N=await xt(),$=_.labels.some(j=>N.includes(j.id));await g(dr.parse({type:"report-create",reportHubId:_.reportHubId,report:_,clientTempId:m,recipientRawUserId:$?c:void 0}),"createDailyReport")}return _??O}catch(O){throw x.error("Error in createDailyReport",O),O}},Pt=async(c,u)=>await c.select().top(1).from(s).where(C(s.id,u)),er=async(c,u,m)=>{await c.update(s).set(m).where(C(s.id,u))},Or=async(c,u,m)=>{await c.update(b).set(m).where(C(b.hubId,u))},Nr=async(c,u,m)=>{await c.delete(y).where(ne(C(y.hubId,u),C(y.labelId,m)))};return{streamKey:F,streamMaxLen:Z,attachmentDelivery:M,titleMaxLength:I,clearCache:async()=>{l.clearAll(),D.clear(),et=null,p&&await H(V),x.info("[DailyReportService] Server-side DB/SQL caches cleared successfully.")},invalidateHubReadCaches:async(c,u)=>{l.invalidatePrefix(Ke),l.invalidatePrefix(Ge),await H(V);for(let m of new Set(c))l.invalidatePrefix(Me(m)),await H(`${te}${m}`);for(let m of new Set(u)){let R=Te(m);R&&await H(`${Q}${R}`)}},getUserIdByExternalId:ie,getDailyReportIdsByExternalId:xe,getDailyReportIdsFirstPageByExternalId:z,readSseStreamAnchor:P,getDailyReportsByBusinessDate:Ze,getDailyReportsByBusinessDateByExternalId:ta,getDailyReportDetailById:yt,getDailyReportDetailByIdByExternalId:ra,getDraftLabelId:Xt,getAttachmentsByHubIds:Ct,getAttachmentForUser:Xo,markAttachmentMissing:Zo,markAttachmentPresent:ea,setStarStatus:oa,setReadStatus:aa,addComment:ia,deleteComment:la,createDailyReport:ua,updateDailyReport:async(c,u,m,R)=>{let w=await Pt(t,c);if(!w.length||w[0].deletedAt)throw new Error("Not Found");if(w[0].userId!==u)throw new Error("Unauthorized");await A(async N=>{m.title!==void 0&&await er(N,c,{title:Lo(m.title),updatedAt:new Date,updatedBy:String(u)}),m.content!==void 0&&await Or(N,c,{body:Lo(m.content),updatedAt:new Date,updatedBy:String(u)})}),l.invalidatePrefix(Me(c)),l.invalidatePrefix(Ke),await H(`${te}${c}`);let O=Te(he(w[0].businessDate,"YYYY-MM-DD"));O&&(l.invalidatePrefix(_t(O)),await H(`${Q}${O}`));let _=await yt(_e.unrestricted("post-write self read: the writer always sees the row they just wrote"),c,u,{forceRefresh:!0});if(_){let N=await xt(),$=_.labels.some(j=>N.includes(j.id));await g(mr.parse({type:"report-update",reportHubId:_.reportHubId,report:_,clientTempId:R,recipientRawUserId:$?u:void 0}),"updateDailyReport")}},publishDailyReport:async(c,u,m)=>{let R=await Pt(t,c);if(!R.length)throw new Error("Not Found");if(R[0].userId!==u)throw new Error("Unauthorized");let w=await Xt();if(!w)return null;if(await Nr(t,c,w),l.invalidatePrefix(Me(c)),l.invalidatePrefix(Ke),l.invalidatePrefix(Ge),await H(V),R[0].businessDate){let N=Te(he(R[0].businessDate,"YYYY-MM-DD"));N&&await H(`${Q}${N}`)}let O=Te(he(R[0].businessDate,"YYYY-MM-DD"));O&&l.invalidatePrefix(lt(O,u));let _=await yt(_e.unrestricted("post-write self read: the writer always sees the row they just wrote"),c,u,{forceRefresh:!0});return _&&await g(pr.parse({type:"report-publish",reportHubId:_.reportHubId,report:_,clientTempId:m}),"publishDailyReport"),_??null},deleteDailyReport:async(c,u,m)=>{let R=await Pt(t,c);if(!R.length||R[0].deletedAt)throw new Error("Not Found");if(R[0].userId!==u)throw new Error("Unauthorized");if(await er(t,c,{deletedAt:new Date,deletedBy:String(u),updatedAt:new Date,updatedBy:String(u)}),l.invalidatePrefix(Me(c)),l.invalidatePrefix(Ke),l.invalidatePrefix(Ge),await H(V),R[0].businessDate){let w=Te(he(R[0].businessDate,"YYYY-MM-DD"));w&&await H(`${Q}${w}`)}await g(yr.parse({type:"report-delete",reportHubId:c,clientTempId:m,sourceType:R[0].sourceType}),"deleteDailyReport")},findDailyReportHubById:Pt,updateDailyReportHub:er,updateDailyReportInternal:Or,deleteDailyReportLabel:Nr}}var vs=fe(1,"[DailyReportExternalSource]"),Ls=(e,t,r,n=vs)=>{if(!e)return[];try{let o=JSON.parse(e);return Array.isArray(o)?o.map(r).filter(a=>a!==null):(n.warn(`Unexpected ${t} format: not an array`),[])}catch(o){return n.warn(`Failed to parse ${t}:`,o),[]}};import{desc as Oo,sql as Os}from"drizzle-orm";import{bigint as ce,bit as No,date as Ns,datetime2 as me,foreignKey as we,index as Ye,int as ks,mssqlSchema as Bs,nvarchar as X,primaryKey as Xe,uniqueIndex as Us}from"drizzle-orm/mssql-core";function Fs(e,t){let r=Bs(e),n=t.userTable,o=r.table("DailyReportHub",{id:ce("id",{mode:"number"}).identity().notNull(),sourceType:X("source_type",{length:20}).notNull(),sourceId:X("source_id",{length:100}).notNull(),sourceIdNum:ce("source_id_num",{mode:"number"}).generatedAlwaysAs(Os`TRY_CAST(source_id AS BIGINT)`),businessDate:Ns("business_date"),userId:ce("user_id",{mode:"number"}),title:X("title",{length:200}),summary:X("summary",{length:"max"}),createdAt:me("created_at").notNull(),createdBy:X("created_by",{length:50}).notNull(),updatedAt:me("updated_at").notNull(),updatedBy:X("updated_by",{length:50}).notNull(),deletedAt:me("deleted_at"),deletedBy:X("deleted_by",{length:50})},d=>[Xe({name:`${e}_DailyReportHub_pk`,columns:[d.id]}),we({name:`${e}_DailyReportHub_user_id_fk`,columns:[d.userId],foreignColumns:[n.id]}),Ye(`${e}_DailyReportHub_business_date_index`).on(d.businessDate),Ye(`${e}_DailyReportHub_updated_at_index`).on(d.updatedAt),Ye(`${e}_DailyReportHub_source_index`).on(d.sourceType,d.sourceId),Ye(`${e}_DailyReportHub_user_id_index`).on(d.userId),Ye(`${e}_DailyReportHub_business_date_id_index`).on(Oo(d.businessDate),Oo(d.id)),Ye(`${e}_DailyReportHub_deleted_at_index`).on(d.deletedAt)]),a=r.table("DailyReportInternal",{hubId:ce("hub_id",{mode:"number"}).notNull(),body:X("body",{length:"max"}),metadata:X("metadata",{length:"max"}),createdAt:me("created_at").notNull(),createdBy:X("created_by",{length:50}).notNull(),updatedAt:me("updated_at").notNull(),updatedBy:X("updated_by",{length:50}).notNull()},d=>[Xe({name:`${e}_DailyReportInternal_pk`,columns:[d.hubId]}),we({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[d.hubId],foreignColumns:[o.id]})]),i=r.table("DailyReportComment",{id:ce("id",{mode:"number"}).identity().notNull(),hubId:ce("hub_id",{mode:"number"}).notNull(),userId:ce("user_id",{mode:"number"}).notNull(),body:X("body",{length:"max"}).notNull(),createdAt:me("created_at").notNull(),createdBy:X("created_by",{length:50}).notNull(),updatedAt:me("updated_at").notNull(),updatedBy:X("updated_by",{length:50}).notNull()},d=>[Xe({name:`${e}_DailyReportComment_pk`,columns:[d.id]}),we({name:`${e}_DailyReportComment_hub_id_fk`,columns:[d.hubId],foreignColumns:[o.id]}),we({name:`${e}_DailyReportComment_user_id_fk`,columns:[d.userId],foreignColumns:[n.id]}),Ye(`${e}_DailyReportComment_hub_id_index`).on(d.hubId)]),l=r.table("DailyReportLabel",{id:ce("id",{mode:"number"}).identity().notNull(),userId:ce("user_id",{mode:"number"}),name:X("name",{length:50}).notNull(),color:X("color",{length:20}),sortOrder:ks("sort_order"),createdAt:me("created_at").notNull(),createdBy:X("created_by",{length:50}).notNull(),updatedAt:me("updated_at").notNull(),updatedBy:X("updated_by",{length:50}).notNull()},d=>[Xe({name:`${e}_DailyReportLabel_pk`,columns:[d.id]}),we({name:`${e}_DailyReportLabel_user_id_fk`,columns:[d.userId],foreignColumns:[n.id]})]),p=r.table("DailyReportHub_Label",{hubId:ce("hub_id",{mode:"number"}).notNull(),labelId:ce("label_id",{mode:"number"}).notNull(),createdAt:me("created_at").notNull(),createdBy:X("created_by",{length:50}).notNull()},d=>[Xe({name:`${e}_DailyReportHub_Label_pk`,columns:[d.hubId,d.labelId]}),we({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[d.hubId],foreignColumns:[o.id]}),we({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[d.labelId],foreignColumns:[l.id]})]),s=r.table("DailyReportUserStatus",{hubId:ce("hub_id",{mode:"number"}).notNull(),userId:ce("user_id",{mode:"number"}).notNull(),isRead:No("is_read").default(!1).notNull(),isStarred:No("is_starred").default(!1).notNull(),createdAt:me("created_at").notNull(),createdBy:X("created_by",{length:50}).notNull(),updatedAt:me("updated_at").notNull(),updatedBy:X("updated_by",{length:50}).notNull()},d=>[Xe({name:`${e}_DailyReportUserStatus_pk`,columns:[d.hubId,d.userId]}),we({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[d.hubId],foreignColumns:[o.id]}),we({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[d.userId],foreignColumns:[n.id]})]),b=r.table("DailyReportAttachment",{id:ce("id",{mode:"number"}).identity().notNull(),hubId:ce("hub_id",{mode:"number"}).notNull(),uploadedBy:ce("uploaded_by",{mode:"number"}),sourceKey:X("source_key",{length:200}).notNull(),fileName:X("file_name",{length:255}).notNull(),filePath:X("file_path",{length:"max"}).notNull(),fileType:X("file_type",{length:100}),fileSize:ce("file_size",{mode:"number"}),objectCheckedAt:me("object_checked_at"),objectMissingAt:me("object_missing_at"),createdAt:me("created_at").notNull(),createdBy:X("created_by",{length:50}).notNull(),updatedAt:me("updated_at").notNull(),updatedBy:X("updated_by",{length:50}).notNull()},d=>[Xe({name:`${e}_DailyReportAttachment_pk`,columns:[d.id]}),we({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[d.hubId],foreignColumns:[o.id]}),we({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[d.uploadedBy],foreignColumns:[n.id]}),Us(`${e}_DailyReportAttachment_source_unique`).on(d.hubId,d.sourceKey),Ye(`${e}_DailyReportAttachment_hub_id_index`).on(d.hubId,d.createdAt)]);return{hub:o,internal:a,comment:i,attachment:b,label:l,hubLabel:p,userStatus:s}}var Hs=5e7,zo=2e8,$s=1,Wo=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})})}),ko=125,Bo=4,Uo=16,Fo=50,Ho=2,Qt=Object.freeze({renderMs:be.renderMs,nanosecondsPerBlockVisit:ko,margin:Bo,maxBlockVisits:Math.floor(be.renderMs*1e6/(ko*Bo)),walkBudgetMs:Uo,nanosecondsPerWalkStep:Fo,walkMargin:Ho,maxWalkSteps:Math.floor(Uo*1e6/(Fo*Ho))}),Ys=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),$o=75,Yo=4,Vo="#ffffff",Vs=1,qs={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},js=[/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/],qo=Object.freeze({ok:!1,reason:"failed"}),jo=Object.freeze({ok:!1,reason:"unsupported"}),Go=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:Ln(e)}),Ko=(e,t)=>{switch(t){case"jpeg":{let r=Dr(e);return r===null?null:Go(r)}case"png":{let r=kn(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=Bn(e,Qt.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},Jo=(e,t)=>{let r=Ys.get(t.depth);if(r===void 0)return null;let n=t.channels*r,o=Wo,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},zs=(e,t,r)=>{let n=Ko(e,t);return n===null?null:Jo(n,r)},Ws=e=>e!==null&&e<=zo,Gs=(e,t)=>{if(t!=="jpeg")return Ko(e,t);let r=On(e,Qt);return r===null||r.blockVisits>Qt.maxBlockVisits?null:Go(r.header)},Ks=e=>{let t=e instanceof Error?e.message:"";return js.some(r=>r.test(t))?"failed":"unsupported"},Js=e=>{e.cache(!1),e.concurrency($s),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(qs)});let t=async(n,o,a,i,l)=>{let p=Gs(n,o);if(p===null)return jo;try{let s=e(n,{limitInputPixels:Hs,animated:!1});if(!Ws(Jo(p,await s.metadata())))return jo;if(l.aborted)return qo;let b=await s.rotate().resize({width:a,height:i,fit:"inside",withoutEnlargement:!0}).flatten({background:Vo}).webp({quality:$o,effort:Yo}).toBuffer();return{ok:!0,bytes:new Uint8Array(b),contentType:"image/webp"}}catch(s){return{ok:!1,reason:Ks(s)}}},r=async(n,{format:o,maxWidth:a,maxHeight:i,signal:l})=>l.aborted?qo:t(n,o,a,i,l);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${$o}-e${Yo}/flatten-${Vo}/v${Vs}`,render:r}};function Td(e){e.redis||(e.logger??console).warn("[DailyReport] redis provider is not injected: cross-worker cache invalidation is disabled (staleness is bounded only by TTL) and SSE publishing is skipped.");let t=or(e.redis),r=new Rt({defaultTtlMs:e.cacheDefaultTtlMs??6e4},t),n=vr({...e,cache:r,epochs:t}),o=new Et({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),a=Mr({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{Er as DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,_r as DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,zo as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,Qt as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL,Wo as DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,Pr as DAILY_REPORT_SSE_CATCH_UP_BATCH,Eo as DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,Et as DailyReportSseReader,_e as DailyReportViewerScope,Rt as SqlResultCache,Mr as createDailyReportHandlers,Td as createDailyReportServer,vr as createDailyReportService,or as createEpochStore,Js as createSharpThumbnailRenderer,Fs as defineDailyReportSchema,At as generateETag,$e as isStreamIdLte,ue as jsonResponseWithETag,fr as parseClientTempId,zs as predictSharpThumbnailWorkingSetBytes,Dt as readDailyReportSseStreamEntry,Ls as transformJsonArray};
5
5
  /* v8 ignore next -- @preserve 到達不能: 時間切れと中断の購読はどちらも cleanup で同時に外れ、枠を渡すときも先に cleanup するので、列にいない待機者でここへは来ない。それでも splice(-1) が別の待機者を消さないよう残す */