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