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