@aiquants/daily-report 0.24.0 → 0.25.0

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