@aiquants/daily-report 0.40.0 → 0.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -1,12 +1,12 @@
1
- "use strict";var jr=Object.defineProperty;var il=Object.getOwnPropertyDescriptor;var sl=Object.getOwnPropertyNames;var ll=Object.prototype.hasOwnProperty;var ro=e=>{throw TypeError(e)};var cl=(e,t)=>{for(var r in t)jr(e,r,{get:t[r],enumerable:!0})},ul=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of sl(t))!ll.call(e,o)&&o!==r&&jr(e,o,{get:()=>t[o],enumerable:!(n=il(t,o))||n.enumerable});return e};var dl=e=>ul(jr({},"__esModule",{value:!0}),e);var no=(e,t,r)=>t.has(e)||ro("Cannot "+r);var kt=(e,t,r)=>(no(e,t,"read from private field"),r?r.call(e):t.get(e)),Wr=(e,t,r)=>t.has(e)?ro("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),zr=(e,t,r,n)=>(no(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var Sp={};cl(Sp,{DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES:()=>Rr,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES:()=>fr,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES:()=>Gn,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL:()=>Xt,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL:()=>Kn,DAILY_REPORT_SSE_CATCH_UP_BATCH:()=>Lr,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS:()=>Hn,DailyReportSseReader:()=>Pt,DailyReportViewerScope:()=>Me,SqlResultCache:()=>Tt,createDailyReportHandlers:()=>Nr,createDailyReportServer:()=>Rp,createDailyReportService:()=>$r,createEpochStore:()=>rr,createSharpThumbnailRenderer:()=>xs,defineDailyReportSchema:()=>ps,defineDailyReportSearchSchema:()=>ms,encodeIdsStreamRows:()=>mt,isStreamIdLte:()=>tt,parseClientTempId:()=>ur,predictSharpThumbnailWorkingSetBytes:()=>_s,readDailyReportSseStreamEntry:()=>Ct,transformJsonArray:()=>ds});module.exports=dl(Sp);var Gr=e=>typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"||e===null||e===void 0?String(e):Array.isArray(e)?"array":typeof e,oe=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${Gr(r)}`),Ke=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),Kr=(e,t,r)=>oe(e,`one of ${r.map(n=>JSON.stringify(n)).join(", ")}`,t),re=(e,t,r,n)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r&&(n===void 0||t<=n))return t;throw oe(e,n===void 0?`an integer >= ${r}`:`an integer from ${r} to ${n}`,t)},pt=(e,t,r,n)=>t===void 0?n:re(e,t,r);var ue=()=>Math.floor(performance.now());var He=class extends Error{constructor(t){super(`cache miss refused (${t})`),this.name="SqlResultCacheMissRefusal",this.reason=t}},rr=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{}}}),vt=(e,t)=>t?e.map(r=>structuredClone(r)):e,pl=8,ml=(e,t)=>{let r=0,n=[e];for(;n.length>0&&r<=t;){let o=n.pop();if(ArrayBuffer.isView(o)){r+=o.byteLength;continue}let a=Array.isArray(o)?o:Object.keys(o).map(i=>o[i]);r+=pl*a.length;for(let i of a)typeof i=="string"?r+=2*i.length:typeof i=="object"&&i!==null&&n.push(i)}return r},Tt=class{constructor(t,r){this.epochStore=r;this.buckets=new Map;this.totalBytes=0;this.inFlight=new Map;this.forcedFetches=new Map;this.maybeRefreshAhead=t=>{let r=t.refreshAheadRatio;if(r===void 0)return;let{cacheKey:n}=t,o=this.buckets.get(n);if(!o)return;let a=t.ttlMsOverride??this.defaultTtlMs;if(a-(o.expireAt-ue())<a*r||this.inFlight.has(n))return;let l;l=(async()=>{let c=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,s=await t.fetcher();return this.inFlight.get(n)===l&&this.writeBucket(n,{records:s,expireAt:ue()+a,epoch:c}),s})(),this.inFlight.set(n,l),l.catch(()=>{}).finally(()=>{this.inFlight.get(n)===l&&this.inFlight.delete(n)})};this.startFetch=(t,r)=>{let{cacheKey:n,admission:o}=t,a;a=(async()=>{let l=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,c=o===void 0?null:await o.acquire(o.signal);if(o!==void 0&&c===null)throw new He(o.signal.aborted?"aborted":"busy");try{for(let m of r)m();let s=await t.fetcher();return this.inFlight.get(n)===a&&this.writeBucket(n,{records:s,expireAt:ue()+(t.ttlMsOverride??this.defaultTtlMs),epoch:l}),s}finally{c?.()}})(),this.inFlight.set(n,a);let i=()=>{this.inFlight.get(n)===a&&this.inFlight.delete(n)};return a.then(i,i),a};this.forcedFetch=t=>{let{cacheKey:r}=t,n=t.onFetchStart===void 0?[]:[t.onFetchStart],o=this.forcedFetches.get(r);if(o===void 0)return this.runForcedFetch(t,n);if(o.pending===null){let a=[],i=()=>this.runForcedFetch(t,a);o.pending={promise:o.running.then(i,i),onFetchStarts:a}}return o.pending.onFetchStarts.push(...n),o.pending.promise};this.runForcedFetch=(t,r)=>{let{cacheKey:n}=t,o=this.startFetch(t,r);this.forcedFetches.set(n,{running:o,pending:null});let a=()=>{let i=this.forcedFetches.get(n);i?.running===o&&i.pending===null&&this.forcedFetches.delete(n)};return o.then(a,a),o};this.getOrFetch=async t=>{let{cacheKey:r,forceRefresh:n,snapshot:o,admission:a}=t;if(n){if(a?.signal.aborted)throw new He("aborted");return this.dropBucket(r),vt(await this.readOwnOrRetry(this.forcedFetch(t),t),o)}let i=this.buckets.get(r);if(i&&i.expireAt>ue())if(t.epochKey){let c=await this.epochStore.getEpoch(t.epochKey);if(c===null||i.epoch===c)return this.maybeRefreshAhead(t),vt(i.records,o);this.dropBucket(r)}else return this.maybeRefreshAhead(t),vt(i.records,o);let l=this.inFlight.get(r);if(l!==void 0)return vt(await this.readOwnOrRetry(l,t),o);if(a?.signal.aborted)throw new He("aborted");return vt(await this.startFetch(t,t.onFetchStart===void 0?[]:[t.onFetchStart]),o)};this.readOwnOrRetry=async(t,r)=>{try{return await t}catch(n){let{admission:o}=r;if(!(n instanceof He&&(o===void 0||n.reason==="aborted"&&!o.signal.aborted)))throw n;return this.getOrFetch({...r,snapshot:!1})}};this.clearAll=()=>{this.buckets.clear(),this.totalBytes=0,this.inFlight.clear()};this.invalidatePrefix=t=>{for(let r of this.buckets.keys())r.startsWith(t)&&this.dropBucket(r);for(let r of this.inFlight.keys())r.startsWith(t)&&this.inFlight.delete(r)};this.defaultTtlMs=re("defaultTtlMs",t.defaultTtlMs,1),this.maxBuckets=re("maxBuckets",t.maxBuckets,1),this.maxBytes=re("maxBytes",t.maxBytes,1),this.lastSweepAt=ue()}dropBucket(t){let r=this.buckets.get(t);r!==void 0&&(this.buckets.delete(t),this.totalBytes-=r.bytes)}writeBucket(t,r){this.dropBucket(t);let n=ml(r.records,this.maxBytes);if(n>this.maxBytes)return;this.buckets.set(t,{...r,bytes:n}),this.totalBytes+=n;let o=ue();o-this.lastSweepAt>=this.defaultTtlMs&&this.sweepExpired(o);for(let a of this.buckets.keys()){if(this.buckets.size<=this.maxBuckets&&this.totalBytes<=this.maxBytes)break;this.dropBucket(a)}}sweepExpired(t){this.lastSweepAt=t;for(let[r,n]of this.buckets)n.expireAt<=t&&this.dropBucket(r)}};var yl=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var oo=e=>e<10?`0${e}`:`${e}`,hl=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=oo(e.getMonth()+1),n=oo(e.getDate());return`${t}-${r}-${n}`},Et=e=>{let t=yl.exec(e);if(t===null)return null;let[,r,,n,o]=t,a=Number(r),i=Number(n),l=Number(o);if(a<1)return null;let c=new Date(0);return c.setUTCFullYear(a,i-1,l),c.getUTCFullYear()!==a||c.getUTCMonth()!==i-1||c.getUTCDate()!==l?null:`${r}-${n}-${o}`},nr=e=>Et(e)===e;var ke=e=>e==null?null:e instanceof Date?hl(e):Et(e);var ao=require("zod"),st=e=>Number.isSafeInteger(e)&&e>0,Ae=ao.z.number().int().positive().max(Number.MAX_SAFE_INTEGER);var io="ids-columns";var mt=(e,t,r)=>{let n=[],o=[],a=[],i=[],l=[],c=new Map;for(let s=t;s<r;s++){let{reportHubId:m,businessDate:u,sourceType:f}=e[s];n.push(m),o.length>0&&o[o.length-1]===u?a[a.length-1]+=1:(o.push(u),a.push(1));let h=f===void 0?null:f,R=c.get(h);R===void 0&&(R=i.length,i.push(h),c.set(h,R)),l.push(R)}return{ids:n,dates:o,counts:a,sourceTypes:i,sources:l}},or=e=>{let t=2166136261,r=-624069552;for(let n of e){let o=n.reportHubId;t^=o&255,t=Math.imul(t,16777619),t^=o>>>8&255,t=Math.imul(t,16777619),t^=o>>>16&255,t=Math.imul(t,16777619),t^=o>>>24&255,t=Math.imul(t,16777619),r^=o>>>24&255,r=Math.imul(r,16777619),r^=o>>>16&255,r=Math.imul(r,16777619),r^=o>>>8&255,r=Math.imul(r,16777619),r^=o&255,r=Math.imul(r,16777619);let a=n.businessDate;if(a===null)t^=1,t=Math.imul(t,16777619),r^=1,r=Math.imul(r,16777619);else for(let i=0;i<a.length;i++){let l=a.charCodeAt(i);t^=l&255,t=Math.imul(t,16777619),r^=l&255,r=Math.imul(r,16777619)}}return t^=e.length,t=Math.imul(t,16777619),r^=e.length,r=Math.imul(r,16777619),((t>>>0).toString(16).padStart(8,"0")+(r>>>0).toString(16).padStart(8,"0")).replace(/^0+(?=.)/,"")},so=(e,t,r,n)=>e!==r?e===null?1:r===null||e>r?-1:1:n-t,fl=(e,t,r,n)=>so(e,t,r,n)<0,Jr=(e,t)=>so(e.businessDate,e.reportHubId,t.businessDate,t.reportHubId),lo=e=>{for(let t=1;t<e.length;t++)if(!fl(e[t-1].businessDate,e[t-1].reportHubId,e[t].businessDate,e[t].reportHubId))return!1;return!0},co=(e,t)=>{let r=e.findIndex(n=>Jr({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var se=Object.freeze({businessDate:"business-date",idsStream:io,report:"report",search:"search",reports:"reports",searchMarks:"search-marks",searchFacets:"search-facets",action:"action"}),ge=Object.freeze({businessDate:"businessDate",reportHubId:"reportHubId",searchQuery:"q",searchCombine:"combine",searchAuthor:"author",searchSourceType:"sourceType",searchCustomer:"customer",reportIds:"ids",forceRefresh:"forceRefresh",cursorReportHubId:"cursor_report_hub_id",cursorBusinessDate:"cursor_business_date",cursorSnapshot:"cursor_snapshot"});var uo=(e,t,r=console)=>{let n=o=>typeof o=="string"?[`${t} ${o}`]:[t,o];return{debug:(o,...a)=>{e<=0&&r.debug(...n(o),...a)},info:(o,...a)=>{e<=1&&r.info(...n(o),...a)},warn:(o,...a)=>{e<=2&&r.warn(...n(o),...a)},error:(o,...a)=>{e<=3&&r.error(...n(o),...a)}}},Mp=Object.freeze(["API","Action","Attachment","ExternalSource","Isolation","Reads","Refresh","Search","SSE","SseReader","Server","Service","Streams","Visibility","ActionProvider","DetailLoader","IdsStream","SseConnection"]),po=e=>`[DailyReport${e}]`,be=(e,t,r)=>e===void 0?uo(t,po(r)):uo(0,po(r),e);var Rl="legacy-",Qr=e=>`${Rl}${e}`;var Sl=/^[1-9][0-9]*$/,gl=/^(?:0|[1-9][0-9]*)$/,Ue=e=>{if(e===null||!Sl.test(e))return null;let t=Number(e);return st(t)?t:null},Xr=e=>{if(e===null||!gl.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},Zr=e=>e==="true"?!0:e==="false"?!1:null,Ot=e=>e===null?!1:Zr(e);var mo=Object.freeze(["subject","content","author","employeeName","updatedBy","category","creationCategory","customerName"]),Je=Object.freeze({field:e=>e,interviewer:(e,t)=>`interviewer:${e}:${t}`,attachment:e=>`attachment:${e}`,comment:(e,t)=>`comment:${e}:${t}`});var bl=16777619,en=2166136261,tn=(e,t,r,n)=>{let o=e;for(let a=r;a<n;a++)o^=t.charCodeAt(a),o=Math.imul(o,bl);return o>>>0},yo=e=>tn(en,e,0,e.length),Dl=String.fromCodePoint(3),Al=String.fromCodePoint(2),Tl=String.fromCodePoint(1),ar=e=>yo(e.map(t=>t.map(r=>r.map(n=>`${n.tier}${n.text}`).join(Dl)).join(Al)).join(Tl));var ho=e=>e==="intersection"||e==="union",Ie=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),rn=2,ir=2,yt=Object.freeze({word:0,reading:1});var nn=(e,t)=>({ids:e.map(r=>r.reportHubId),businessDates:e.map(r=>r.businessDate),sourceTypes:e.map(r=>r.sourceType),words:t});var Op=2*(1+rn);var Ml=require("zod");var sr=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|-[1-9][0-9]{0,15})$/;var P=require("zod");var fo=15e3,Ro="lastEventId",El=/^\d{1,15}-\d{1,15}$/,So=e=>El.test(e),wl=P.z.object({name:P.z.string().nullish(),affiliation:P.z.string().nullish()}),Il=P.z.object({name:P.z.string().nullish(),text:P.z.string().nullish(),color:P.z.string().nullish()}),_l=P.z.object({id:Ae,name:P.z.string().nullish(),color:P.z.string().nullish()}),go=P.z.object({id:Ae,userId:P.z.string().nullish(),userName:P.z.string().nullish(),content:P.z.string().nullish(),createdAt:P.z.string().nullish(),isMine:P.z.boolean()}),xl=P.z.object({id:P.z.string(),fileName:P.z.string(),fileType:P.z.string().nullable(),fileSize:P.z.number().nullable(),createdAt:P.z.string().nullable(),state:P.z.enum(["present","absent","unknown"]),hasThumbnail:P.z.boolean().default(!1)}),on=P.z.object({reportHubId:Ae,date:P.z.string().nullish(),createdAt:P.z.string().nullish(),author:P.z.string().nullish(),userId:P.z.string().nullish(),sourceType:P.z.string().nullish(),employeeName:P.z.string().nullish(),updatedBy:P.z.string().nullish(),updatedAt:P.z.string().nullish(),category:P.z.string().nullish(),creationCategory:P.z.string().nullish(),visitTimeFrom:P.z.string().nullish(),visitTimeTo:P.z.string().nullish(),customerName:P.z.string().nullish(),interviewers:P.z.array(wl),subject:P.z.string().nullish(),content:P.z.string().nullish(),externalComments:P.z.array(Il),isRead:P.z.boolean(),isStarred:P.z.boolean(),isDraft:P.z.boolean(),labels:P.z.array(_l),postedComments:P.z.array(go),attachments:P.z.array(xl).default([])}),ht=P.z.string().regex(sr),Cl=P.z.object({type:P.z.literal("connected")}),lr=P.z.object({type:P.z.literal("status-update"),reportHubId:Ae,statusType:P.z.enum(["star","read"]),value:P.z.boolean(),clientTempId:ht,recipientRawUserId:Ae.optional()}),an=P.z.string().optional(),sn=P.z.object({type:P.z.literal("comment-add"),reportHubId:Ae,comment:go,clientTempId:ht,recipientRawUserId:Ae.optional(),sourceType:an}),ln=P.z.object({type:P.z.literal("comment-delete"),reportHubId:Ae,commentId:Ae,clientTempId:ht,recipientRawUserId:Ae.optional(),sourceType:an}),cn=P.z.object({type:P.z.literal("report-create"),reportHubId:Ae,report:on,clientTempId:ht,recipientRawUserId:Ae.optional()}),un=P.z.object({type:P.z.literal("report-update"),reportHubId:Ae,report:on,clientTempId:ht,recipientRawUserId:Ae.optional()}),dn=P.z.object({type:P.z.literal("report-publish"),reportHubId:Ae,report:on,clientTempId:ht,recipientRawUserId:Ae.optional()}),pn=P.z.object({type:P.z.literal("report-delete"),reportHubId:Ae,clientTempId:ht,sourceType:an}),bo=P.z.discriminatedUnion("type",[Cl,lr,sn,ln,cn,un,dn,pn]);var ve=Object.freeze({intent:"intent",clientTempId:"clientTempId",businessDate:"businessDate",operationTimestamp:"operationTimestamp",reportHubId:"reportHubId",title:"title",content:"content",isStarred:"isStarred",isRead:"isRead",commentId:"commentId"});var cr=Math.max(1,Math.floor(10.556701030927835));var $e=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var Oe=e=>{let{windowMs:t,tallies:r,writeSuppressed:n}=e,o=new Map,a=i=>{let l={since:new Date().toISOString(),count:0,tallies:Object.fromEntries(r.map(s=>[s,0]))};o.set(i,l),$e(()=>{o.delete(i),l.count>0&&n(i,l)},t)};return{record:(i,l,c)=>{let s=o.get(i);if(s!==void 0){s.count+=1,s.tallies[l]+=1;return}c(),a(i)}}};var Qe=Object.freeze({maxValuesPerFacet:16,maxValueLength:200,maxTotalValueLength:300});var zp=Object.freeze({authors:Object.freeze([]),sourceTypes:Object.freeze([]),customers:Object.freeze([])}),Pl=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,mn=e=>{let t=e.trim();return t.length===0?null:t.replace(Pl,"\uFFFD")},Ll=e=>{let t=mn(e);return t===null?"filter-blank-value":t!==e?"filter-value-not-canonical":e.length>Qe.maxValueLength?"filter-value-too-long":null},Nl=e=>{if(e.length>Qe.maxValuesPerFacet)return"filter-too-many-values";let t=new Set;for(let r of e){let n=Ll(r);if(n!==null)return n;if(t.has(r))return"filter-duplicate-value";t.add(r)}return null},kl=e=>{let t=0;for(let r of e.authors)t+=r.length;for(let r of e.customers)t+=r.length;return t},Do=e=>{for(let t of[e.authors,e.sourceTypes,e.customers]){let r=Nl(t);if(r!==null)return r}return kl(e)>Qe.maxTotalValueLength?"filters-too-long":null};var Ao=e=>e.trim().length===0;var ur=e=>e!==null&&sr.test(e)?e:null,yn=e=>ho(e)?e:null,hn=e=>{if(e===null)return null;let t=e.split(",");if(t.length>Ie.maxDetailIds)return null;let r=[];for(let n of t){let o=Ue(n);if(o===null||r.includes(o))return null;r.push(o)}return r},To=e=>{let[t,...r]=e;return t===void 0?null:[t,...r]},Eo=(e,t)=>{let r={authors:e.getAll(ge.searchAuthor),sourceTypes:e.getAll(ge.searchSourceType),customers:e.getAll(ge.searchCustomer)},n=Do(r);if(n!==null)return{ok:!1,reason:n};let o=new Set(t.map(i=>i.toLowerCase())),a=new Set;for(let i of r.sourceTypes){let l=i.toLowerCase();if(!o.has(l))return{ok:!1,reason:"filter-unknown-source-type"};if(a.has(l))return{ok:!1,reason:"filter-duplicate-value"};a.add(l)}return{ok:!0,filters:{sourceTypes:a.size===0?null:a,authors:To(r.authors),customers:To(r.customers)}}},wo=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var _o=Object.freeze({status:400,error:"Invalid form"}),xo=e=>({status:413,error:"Form too large",measuredBy:e}),vl=(e,t,r)=>{let n=0;return e.pipeThrough(new TransformStream({transform(o,a){if(n+=o.byteLength,n>t){r(),a.error(new Error(`action form body exceeds ${t} bytes`));return}a.enqueue(o)}}))},Ol=async e=>{let t=Xr(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:xo("declared")};let r=!1,n=e.body===null?null:vl(e.body,1048576,()=>{r=!0}),o=new Headers,a=e.headers.get("Content-Type");a!==null&&o.set("Content-Type",a);let i;try{i=await new Response(n,{headers:o}).formData()}catch{return{refusal:r?xo("counted"):_o}}let l=wo(i);return l===null?{refusal:_o}:{fields:l}},Co=(e,t)=>(r,n)=>{let o=r.get(t);if(o===null)return{error:`${t} required`};let a=Zr(o);return a===null?{error:`Invalid ${t}`}:{command:{...n,intent:e,value:a}}},Po=Object.freeze({update:(e,t,r)=>{let n=e.get(ve.title),o=e.get(ve.content);if(n!==null&&n.length>r.titleMaxLength)return{error:"Invalid title"};let a={};return n!==null&&(a.title=n),o!==null&&(a.content=o),{command:{...t,intent:"update",changes:a}}},publish:(e,t)=>({command:{...t,intent:"publish"}}),delete:(e,t)=>({command:{...t,intent:"delete"}}),toggleStar:Co("toggleStar",ve.isStarred),toggleRead:Co("toggleRead",ve.isRead),addComment:(e,t)=>{let r=e.get(ve.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=Ue(e.get(ve.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),Fl=e=>Object.hasOwn(Po,e),Hl=(e,t)=>{let r=e.get(ve.intent),n=e.get(ve.businessDate),o=n===null?null:Et(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get(ve.operationTimestamp),i=Xr(a);if(a!==null&&i===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get(ve.clientTempId);if(!l)return{error:"clientTempId required"};let c=ur(l);if(c===null)return{error:"Invalid clientTempId"};if(r==="create")return o===null?{error:"businessDate required"}:{command:{intent:r,clientTempId:c,businessDate:o,operationTimestamp:i}};let s=Ue(e.get(ve.reportHubId));return s===null?{error:"Invalid reportHubId"}:r===null||!Fl(r)?{error:"Invalid intent"}:Po[r](e,{clientTempId:c,businessDate:o,operationTimestamp:i,reportHubId:s},t)},Lo=async(e,t)=>{let r=await Ol(e);if("refusal"in r)return r;let n=Hl(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},Ul=6e4,$l="form_too_large",Mo=["declared","counted"],No=e=>{let t=Oe({windowMs:Ul,tallies:Mo,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${Mo.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record($l,r,n)}};var ft=Object.freeze({[se.businessDate]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[se.idsStream]:{body:"stream",admission:["refresh-bucket","stream-slots","cache","miss-gate"]},[se.report]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[se.search]:{body:"json",cache:"etag",admission:["search-limiter"]},[se.reports]:{body:"json",cache:"etag",admission:["search-limiter"]},[se.searchMarks]:{body:"json",cache:"no-store",admission:["search-limiter"]},[se.searchFacets]:{body:"json",cache:"etag",admission:["search-limiter"]}}),ko=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),fn=e=>e!==void 0&&Object.hasOwn(ft,e);var Rn=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),vo=e=>Object.hasOwn(Rn,e);var Bl="download",Vl="thumbnail",ql="1";var Sn=e=>{let t=e.getAll(Vl),r=e.getAll(Bl);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&vo(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===ql?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};var Oo=require("crypto"),gn=e=>`"${(0,Oo.createHash)("sha256").update(e).digest("hex")}"`,Fo=e=>gn(JSON.stringify(e));var Ve=Object.freeze({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'"}),bn=(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},Ho=(e,t,r,n=200)=>{let o=JSON.stringify(r),a=gn(o),i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate",ETag:a,...Ve});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&bn(e.headers.get("If-None-Match"),a)?new Response(null,{status:304,headers:i}):new Response(o,{status:n,headers:i})},Dn=(e,t,r)=>{let n=new Headers({...t===null?{}:{"Content-Type":"application/json"},"Cache-Control":"no-store",...Ve});return e&&n.append("Set-Cookie",e),new Response(t===null?null:JSON.stringify(t),{status:r,headers:n})},An=e=>(t,r,n,o)=>{if(o!==200)return Dn(r,n,o);if(e===null||n===null)throw new Error(`[daily-report] API route: a 200 JSON answer needs an answer of a JSON 200 and a body; got ${e===null?"a responder without one":"an answer"} and ${n===null?"no body":"a body"}`);return e(t,r,n)},Yl=5e3/1e3,jl=new Map([[503,Yl]]),xe=e=>{let t=jl.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var En="Cross-site request rejected",Wl="Not Found",zl=new Set(["same-origin","none"]),Gl=new Set(["GET","HEAD","OPTIONS"]),Uo=["api","action","sse","attachment"],$o=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...Ve}}),Kl=()=>$o(403,En),dr=()=>$o(404,Wl),Ft=Object.freeze({navigable:()=>!1,frameworkDataRefusal:()=>null,crossSiteRejection:Kl}),Bo=e=>new URL(e.url).pathname.endsWith(".data"),Jl=e=>{let t=e.headers.get("Origin");return t===null?!0:URL.canParse(t)&&new URL(t).host===new URL(e.url).host},Vo=(e,t)=>{let r=e.headers.get("Sec-Fetch-Site");return r===null?!(Gl.has(e.method)||Jl(e)):zl.has(r)?!1:!(e.method==="GET"&&e.headers.get("Sec-Fetch-Mode")==="navigate"&&e.headers.get("Sec-Fetch-Dest")==="document"&&t.navigable(e))},Ql=6e4,Xl="refusals",Zl=32,ec=/^[a-z-]+$/,Tn=e=>{if(e===null)return"-";let t=e.slice(0,Zl);return ec.test(t)&&t===e?e:JSON.stringify(t)},qo=e=>{let t=Oe({windowMs:Ql,tallies:Uo,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${Uo.map(i=>`${i}:${a[i]}`).join(",")}`)}});return(r,n)=>{let o=()=>{let{headers:a}=n;e.warn(`cross_site_rejected route=${r} site=${Tn(a.get("Sec-Fetch-Site"))} mode=${Tn(a.get("Sec-Fetch-Mode"))} dest=${Tn(a.get("Sec-Fetch-Dest"))} method=${n.method}`)};t.record(Xl,r,o)}};var Yo=(e,t)=>(r,n)=>{let o=n?"markAttachmentPresent":"markAttachmentMissing";e[o](r).catch(a=>{t.error(`${o} failed attachment=${r} message=${a instanceof Error?a.message:"unknown"}`)})};var tc="same-origin",rc="SAMEORIGIN",wt=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":tc,"X-Frame-Options":rc}),pr=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...wt});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},jo=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),nc=/^[\x20-\x7E]+$/,oc=/^[\w.+-]+\/[\w.+-]+/,wn=e=>e&&nc.test(e)&&oc.test(e)?e:null,ac=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Wo=e=>encodeURIComponent(e.replace(ac,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),zo=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),mr={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},Go={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},yr=e=>typeof e=="string"&&Object.hasOwn(Go,e),hr=e=>Go[e],Xe="Attachment request failed";var qe=e=>{let t=re("limit",e.limit,1),r=re("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:re("queue.max",e.queue.max,0),maxPerOwner:re("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:re("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],i=new Map,l=new Map,c=(S,E)=>S.get(E)??0,s=(S,E,M)=>{let U=c(S,E)+M;U<=0?S.delete(E):S.set(E,U)},m=S=>c(l,S)<r,u=S=>o<t&&m(S),f=S=>(o+=1,s(l,S,1),D(S)),h=()=>{let S=-1,E=r;for(let[M,U]of a.entries()){let I=c(l,U.owner);if(I<E&&(S=M,E=I,I===0))break}return S},R=()=>{for(;o<t;){let S=h();if(S<0)return;let[E]=a.splice(S,1);s(i,E.owner,-1),E.grant(f(E.owner))}},D=S=>{let E=!1;return()=>{E||(E=!0,o-=1,s(l,S,-1),R())}};return{canAcquire:u,acquire:(S,E)=>{if(E.aborted)return Promise.resolve(null);if(u(S))return Promise.resolve(f(S));if(n===null||a.length>=n.max||c(i,S)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:M}=n,U=I=>{let T=()=>{let de=a.indexOf($);de<0||(a.splice(de,1),s(i,S,-1),L(),I(null))},V=$e(T,M),L=()=>{clearTimeout(V),E.removeEventListener("abort",T)},$={owner:S,grant:de=>{L(),I(de)}};a.push($),s(i,S,1),E.addEventListener("abort",T,{once:!0})};return new Promise(U)}}};var ic=1024,In="Too many requests",sc=(e,t)=>{re("limitPerWindow",e,1),re("windowMs",t,1);let r=new Map,n=(a,i)=>{i<=a.lastRefillMs||(a.tokens=Math.min(e,a.tokens+(i-a.lastRefillMs)*e/t),a.lastRefillMs=i)},o=(a,i)=>{let l=r.get(a);l&&r.delete(a);let c=l??{tokens:e,lastRefillMs:i};n(c,i),r.set(a,c);for(let s of r.keys()){if(r.size<=ic)break;r.delete(s)}return c};return{consume:(a,i)=>{let l=o(a,i);return l.tokens<1?!1:(l.tokens-=1,!0)},refund:(a,i,l)=>{let c=r.get(a);c&&(n(c,i),c.tokens=Math.min(e,c.tokens+l))}}},Ze=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(re("windowMs",r,1e3)%1e3!==0)throw oe("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=sc(e.limitPerWindow,r),i=Object.freeze({status:429,message:In,headers:Object.freeze({"Retry-After":String(r/1e3)})}),l=Oe({windowMs:r,tallies:[t],writeSuppressed:(c,{count:s,since:m})=>{n.warn(`${t}_suppressed count=${s} since=${m} ${o(c)}`)}});return{spend:(c,s)=>a.consume(c,ue())?null:(l.record(c,t,()=>n.warn(`429 ${s} reason=${t}`)),i),refund:(c,s)=>{a.refund(c,ue(),s)}}};var cc=256*1024,Ko=6e4,uc=e=>Math.ceil(e/2),dc=new Uint8Array(new ArrayBuffer(0)),pc=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=dc,t()},i=l=>{clearTimeout(o),o=$e(()=>{l.error(new Error(`attachment body idle for ${Ko} ms`)),a()},Ko)};return new ReadableStream({start(l){i(l)},pull(l){let c=Math.min(n+cc,r.byteLength);if(c>n&&l.enqueue(r.slice(n,c)),n=c,n>=r.byteLength){l.close(),a();return}i(l)},cancel(){a()}},{highWaterMark:0})},Jo=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=Ze({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:c=>`viewer=${c}`}),l=qe({limit:e.concurrency,maxHeldPerOwner:uc(e.concurrency),queue:null});return async c=>{let{request:s,delivery:m,attachmentId:u,internalUserId:f,readAttachment:h,cookie:R,fail:D}=c,S=e.maxBytes,E=i.spend(f,`attachment=${u} viewer=${f}`);if(E)return D(E.status,E.message,E.headers);let M=await n(s),U=await t.getAttachmentForUser(M,u,f);if(!U)return o.warn(`404 attachment=${u} viewer=${f} reason=not_visible`),D(404,"Attachment not found");if(U.fileSize!=null&&U.fileSize>S)return o.warn(`413 attachment=${u} viewer=${f} reason=db_size`),D(413,"Attachment too large");let I=wn(U.fileType),T=`filename="${zo(U.fileName)}"; filename*=UTF-8''${Wo(U.fileName)}`,V=await l.acquire(f,s.signal);if(!V)return s.signal.aborted?(o.info(`503 attachment=${u} viewer=${f} reason=aborted`),D(503,"Attachment request aborted")):(o.warn(`503 attachment=${u} viewer=${f} reason=concurrency`),D(503,"Too many concurrent downloads",xe(503)));let L=!1;try{let $=await h(U.filePath,{maxBytes:S,head:s.method==="HEAD",principal:r(f),signal:s.signal});if(s.signal.aborted)return o.info(`503 attachment=${u} viewer=${f} reason=aborted`),D(503,"Attachment request aborted");if(!$.ok){if(!yr($.reason))return o.error(`500 attachment=${u} viewer=${f} reason=port_contract code=failure_reason`),D(500,Xe);let me=hr($.reason);return $.reason==="not_found"&&a(u,!1),o.warn(`${me} attachment=${u} viewer=${f} reason=${$.reason} code=${$.code??"-"}`),D(me,mr[me],xe(me))}if($.bytes.byteLength>S)return o.error(`500 attachment=${u} viewer=${f} reason=port_contract code=over_max_bytes`),D(500,Xe);let de=s.method==="HEAD";if(de&&$.size!==void 0&&$.size>S)return o.error(`500 attachment=${u} viewer=${f} reason=port_contract code=over_max_bytes`),D(500,Xe);if(!de&&$.size!==void 0&&$.size!==$.bytes.byteLength)return o.error(`500 attachment=${u} viewer=${f} reason=port_contract code=size_mismatch`),D(500,Xe);let pe=I??wn($.contentType),De=pe!==null&&jo.has(pe),K=De?pe:"application/octet-stream",le=De&&m.kind!=="download"?"inline":"attachment",ne=de?$.size:$.bytes.byteLength,ce=new Headers({"Content-Type":K,"Content-Disposition":`${le}; ${T}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...wt});return ne!==void 0&&ce.set("Content-Length",String(ne)),R&&ce.append("Set-Cookie",R),a(u,!0),o.info(`200 attachment=${u} viewer=${f} type=${K} disposition=${le} bytes=${ne??"-"}`),de?new Response(null,{status:200,headers:ce}):(L=!0,new Response(pc($.bytes,V),{status:200,headers:ce}))}finally{L||V()}}};var Ce=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),km=Ce.queueWaitMs+Ce.readMs+Ce.renderMs+Ce.transferMarginMs;var Zo=require("buffer"),ea=new Set([194,198,202,206]),mc=new Set([192,193,194,195]),ta=216,yc=217,ra=218,hc=4,fc=64,Rc=2,Qo=8,Xo=28,lt=12,_n=8,Sc=20,na=lt+_n+10,gc=2,et=(e,t)=>e[t]<<8|e[t+1],It=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];return n},Ye=(e,t,r)=>{if(e.byteLength<t+r.length)return!1;for(let n=0;n<r.length;n+=1)if(e[t+n]!==r.charCodeAt(n))return!1;return!0},oa=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,aa=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),ia=e=>(e.stepsLeft-=1,e.stepsLeft>=0),sa=e=>e[0]===255&&e[1]===ta,la=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!ia(r))return null;n+=1}while(n<e.byteLength&&e[n]===255);if(n>=e.byteLength)return null;let o=e[n];if(n+=1,o===yc)return"eoi";if(o===0||o===ta)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=et(e,n),i=n+a;return a<2||i>e.byteLength?null:(r.marker=o,r.body=n+2,r.length=a,r.end=i,"segment")}},bc=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!ia(r))return null;if(a+1>=n)return n;let i=e[a+1];if(i===255)a+=1;else if(i===0||i>=208&&i<=215){if(a+=2,a>=n||e[a]!==255)break}else return a}o=a}},ca=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=et(e,r+1),a=et(e,r+3),i=e[r+5];if(a===0||o===0||i===0||n!==8+3*i)return null;let l=[];for(let c=0;c<i;c+=1){let s=e[r+7+3*c],m=s>>4,u=s&15;if(m<1||m>4||u<1||u>4)return null;l.push({id:e[r+6+3*c],horizontal:m,vertical:u})}return{marker:t,width:a,height:o,components:l}},ua=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>hc||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},da=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:ea.has(e.marker)||t<e.components.length}),xn=e=>{if(!sa(e))return null;let t=aa(e.byteLength),r=null;for(let n=2;;){if(la(e,n,t)!=="segment")return null;if(oa(t.marker)){if(r!==null||(r=ca(e,t),r===null))return null}else if(t.marker===ra){if(r===null)return null;let o=ua(e,t);return o===null?null:da(r,o.length)}n=t.end}},pa=e=>{let t=Math.max(...e.components.map(n=>n.horizontal)),r=Math.max(...e.components.map(n=>n.vertical));return e.components.map(({horizontal:n,vertical:o})=>{let a=Math.ceil(e.width*n/(t*Qo)),i=Math.ceil(e.height*o/(r*Qo));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},ma=e=>e.multiScan?pa(e).reduce((r,n)=>r+n,0)*fc*Rc:0,Dc=896,ya=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!sa(e))return null;let n=Zo.Buffer.from(e.buffer,e.byteOffset,e.byteLength),o=aa(r),a=null,i=null,l=new Map,c=0,s=0,m=0;for(let u=2;;){let f=la(e,u,o);if(f===null)return null;if(f==="eoi")return i===null?null:{header:i,blockVisits:s};if(u=o.end,oa(o.marker)){if(a!==null||!mc.has(o.marker)||(a=ca(e,o),a===null))return null;let h=pa(a);l=new Map;for(let[R,D]of a.components.entries()){let S=l.get(D.id);l.set(D.id,S===void 0?h[R]:Math.max(S,h[R]))}c=a.components.length*(ea.has(a.marker)?Dc:1)}else if(o.marker===ra){if(a===null||m===c)return null;let h=ua(e,o);if(h===null)return null;for(let D of h){let S=l.get(D);if(S===void 0)return null;s+=S}if(m+=1,i===null&&(i=da(a,h.length)),s>t||!i.multiScan)return{header:i,blockVisits:s};let R=bc(n,o.end,o);if(R===null)return null;u=R}}},ha=e=>{if(e.byteLength<24||et(e,8)!==0||et(e,10)!==13||!Ye(e,12,"IHDR"))return null;let t=et(e,16)*65536+et(e,18),r=et(e,20)*65536+et(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},Ac=e=>{if(Ye(e,lt,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=It(e,26,2)&16383,r=It(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(Ye(e,lt,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=It(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return Ye(e,lt,"VP8X")?e.byteLength<na?null:{width:It(e,24,3)+1,height:It(e,27,3)+1}:null},fa=e=>{if(ha(e)===null||e.byteLength<=Xo)return null;switch(e[Xo]){case 0:return!1;case 1:return!0;default:return null}},Ra=(e,t)=>{if(Ye(e,lt,"VP8 "))return"lossy";if(Ye(e,lt,"VP8L"))return"lossless";if(!Ye(e,lt,"VP8X")||e.byteLength<na)return null;if((e[Sc]&gc)!==0)return"animated";let r=!1,n=t;for(let o=lt;o+_n<=e.byteLength;){if(n-=1,n<0)return null;if(Ye(e,o,"VP8L"))return"lossless";if(Ye(e,o,"VP8 "))return r?"lossy-alpha":"lossy";Ye(e,o,"ALPH")&&(r=!0);let a=It(e,o+4,4);o+=_n+a+a%2}return null},Sa={png:ha,jpeg:xn,webp:Ac};var fr=Object.freeze(["image/webp","image/jpeg","image/png"]),Rr=1024*1024;var Tc=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Ec={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},wc=new Set(fr),Ic=e=>typeof e=="string"&&wc.has(e),_c=256,Sr=(e,t)=>e.fileType===null||!Tc.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,xc=[137,80,78,71,13,10,26,10],Cc=[255,216,255],Mc=[[71,73,70,56,55,97],[71,73,70,56,57,97]],Pc=[82,73,70,70],Lc=[87,69,66,80],Ht=(e,t,r)=>{if(e.byteLength<r+t.length)return!1;for(let[n,o]of t.entries())if(e[r+n]!==o)return!1;return!0},Cn=e=>{if(Ht(e,xc,0))return"png";if(Ht(e,Cc,0))return"jpeg";for(let t of Mc)if(Ht(e,t,0))return"gif";return Ht(e,Pc,0)&&Ht(e,Lc,8)?"webp":null},ga=e=>{let t=JSON.stringify([e.rendererId,e.box.maxWidth,e.box.maxHeight,e.attachmentId,e.filePath,e.fileType,e.fileSize]);return{key:t,etag:Fo([t])}},ba=(e,t)=>{if(!Ic(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>Rr)return"too_large";let r=Ec[e.contentType];if(Cn(e.bytes)!==r)return"signature";let n=Sa[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},Da=e=>{re("maxBytes",e.maxBytes,0),re("maxEntries",e.maxEntries,0);let t=new Map,r=0,n=o=>{let a=t.get(o);a&&(t.delete(o),r-=a.weight)};return{get:o=>{let a=t.get(o);if(a)return t.delete(o),t.set(o,a),a.entry},set:(o,a)=>{n(o);let i=(a.kind==="thumbnail"?a.bytes.byteLength:0)+_c;if(i>e.maxBytes||e.maxEntries===0)return;let l=a.kind==="thumbnail"?{kind:"thumbnail",bytes:a.bytes.slice(),contentType:a.contentType}:a;t.set(o,{entry:l,weight:i}),r+=i;for(let c of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(c)}}}};var Mn=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,i=ue(),l=new AbortController,c=!1,s,m,u=()=>{a(ue()-i)},f=I=>{s=$e(()=>{c=!0,I({timedOut:!0}),m=$e(u,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},h=new Promise(f),R=AbortSignal.any([r,l.signal]),D=I=>{I(n(R))},S=new Promise(D),E=I=>(clearTimeout(s),clearTimeout(m),c&&o(ue()-i,I.kind==="error"?{error:I.error}:null),I),M=S.then(I=>E({kind:"value",value:I}),I=>E({kind:"error",error:I}));return{outcome:Promise.race([S.then(I=>({timedOut:!1,value:I})),h]),settled:M}};var ct={404:"Attachment not found",500:Xe,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},Aa=(e,t)=>{if(typeof e!="object"||e===null)return{failure:{kind:"failure",status:500,reason:"port_contract",code:"result"}};let r=e;if(!r.ok)return r.reason==="unsupported"?{entry:{kind:"unrenderable",reason:"unsupported"}}:r.reason==="failed"?{failure:{kind:"failure",status:502,reason:"render_failed"}}:{failure:{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"}};let n=ba(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},Nc=e=>{let t=new AbortController,r=()=>{t.abort()},n=$e(r,Ce.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},Ta=()=>{},kc=(e,t)=>t.aborted?Promise.resolve():new Promise(r=>{let n=()=>{t.removeEventListener("abort",n),r()};t.addEventListener("abort",n,{once:!0}),e.then(n)}),Ea=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:i}=e,l=new Map,c=(h,R)=>{let D=R.then(Ta,Ta);l.set(h,D);let S=()=>{l.get(h)===D&&l.delete(h)};D.then(S)},s=async(h,R)=>{let D=l.get(h.key);if(D===void 0)return t.acquire(h.owner,R);let S=Nc(R);try{if(await kc(D,S.signal),S.signal.aborted)return null;let E=r.get(h.key);return E!==void 0?{...E,identity:"verified"}:await t.acquire(h.owner,S.signal)}finally{S.end()}},m=(h,R)=>{if(h.fileSize===null)return R.kind==="exact"?"verified":"unrecorded";if(R.kind==="exact"?R.bytes===h.fileSize:h.fileSize>R.maxBytes)return"verified";let S=R.kind==="exact"?String(R.bytes):`>${R.maxBytes}`;return i.warn(`size_mismatch expected=${h.fileSize} got=${S} attachment=${h.attachmentId} viewer=${h.owner} variant=thumbnail`),"unverified"},u=(h,R)=>(D,S)=>{let E=S===null?"":` message=${S.error instanceof Error?S.error.message:"unknown"}`;i.warn(`${h}_overrun ms=${D} attachment=${R.attachmentId} viewer=${R.owner} variant=thumbnail${E}`)},f=(h,R)=>D=>{i.warn(`${h}_stuck ms=${D} attachment=${R.attachmentId} viewer=${R.owner} variant=thumbnail`)};return async(h,R)=>{let D=await s(h,R);if(D===null)return{kind:"failure",status:503,reason:R.aborted?"aborted":"queue"};if(typeof D!="function")return D;let S=D,E=null;try{if(R.aborted)return{kind:"failure",status:503,reason:"aborted"};let M=r.get(h.key);if(M!==void 0)return{...M,identity:"verified"};let U=Mn({budgetMs:Ce.readMs,flightSignal:R,call:me=>h.readAttachment(h.filePath,{maxBytes:n,head:!1,principal:o(h.owner),signal:me}),onOverrun:u("read",h),onStuck:f("read",h)}),I=await U.outcome;if(I.timedOut)return E=U.settled,R.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(R.aborted)return{kind:"failure",status:503,reason:"aborted"};let T=I.value;if(!T.ok&&T.reason!=="too_large")return yr(T.reason)?(T.reason==="not_found"&&a(h.attachmentId,!1),{kind:"failure",status:hr(T.reason),reason:T.reason,code:T.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(T.ok&&T.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let V=m(h,T.ok?{kind:"exact",bytes:T.bytes.byteLength}:{kind:"over",maxBytes:n}),L=me=>{V==="verified"&&r.set(h.key,me)},$=me=>(L(me),{...me,identity:V});if(!T.ok)return $({kind:"unrenderable",reason:"too_large"});let de=Cn(T.bytes);if(de===null)return $({kind:"unrenderable",reason:"signature"});let pe=Mn({budgetMs:Ce.renderMs,flightSignal:R,call:me=>h.renderer.render(T.bytes,{format:de,maxWidth:h.box.maxWidth,maxHeight:h.box.maxHeight,signal:me}),onOverrun:u("render",h),onStuck:f("render",h)}),De=me=>{if(me.kind==="error")return;let Re=Aa(me.value,h.box);"entry"in Re&&L(Re.entry)},K=null,le=()=>(K===null&&(K=pe.settled.then(De),c(h.key,K)),K);R.addEventListener("abort",le,{once:!0});let ne=await pe.outcome.finally(()=>R.removeEventListener("abort",le));if(ne.timedOut||R.aborted)return E=le(),R.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let ce=Aa(ne.value,h.box);return"entry"in ce?$(ce.entry):ce.failure}finally{E===null?S():E.then(S,S)}}};var wa=()=>{let e=new Map;return{join:(t,r,n)=>{let o=()=>{let c=new AbortController,s=()=>{e.get(t)?.controller===c&&e.delete(t)},u={promise:n(c.signal).finally(s),controller:c,waiters:0};return e.set(t,u),u},a=e.get(t)??o();a.waiters+=1;let i=()=>{a.waiters-=1,!(a.waiters>0)&&(a.controller.abort(),e.get(t)===a&&e.delete(t))};r.aborted?i():r.addEventListener("abort",i,{once:!0});let l=()=>{r.removeEventListener("abort",i)};return a.promise.finally(l)}}};var xa=10,vc=1/xa,Ia=1-vc,Oc=1024,Fc=64,Hc=8,_a="private, no-cache",Uc="no-store",$c=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),Bc=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},Ca=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:c}=l,s=(I,T)=>Ze({reason:I,limitPerWindow:T,windowMs:6e4,logger:o,windowFields:V=>`viewer=${V} variant=thumbnail`}),m=s("rate_limit",l.rateLimitPerMinute),u=s("revalidation_rate_limit",l.rateLimitPerMinute*xa),f=qe({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:Fc,maxPerOwner:Hc,maxWaitMs:Ce.queueWaitMs}}),h=Da({maxBytes:l.cacheBytes,maxEntries:Oc}),R=wa(),D=Ea({gate:f,cache:h,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),S=(I,T,V,L)=>{let $=`attachment=${I.attachmentId} viewer=${I.internalUserId} variant=thumbnail cache=${L}`;if(T.kind==="failure")return o[Bc(T)](`${T.status} ${$} reason=${T.reason} code=${T.code??"-"}`),I.fail(T.status,ct[T.status],xe(T.status));let de=$c[T.identity];if(T.kind==="unrenderable")return o.info(`404 ${$} reason=${T.reason}${de}`),I.fail(404,ct[404]);let pe=T.identity==="verified"?{"Cache-Control":_a,ETag:V}:{"Cache-Control":Uc},De=new Headers({"Content-Type":T.contentType,"Content-Length":String(T.bytes.byteLength),...pe,"Content-Security-Policy":"default-src 'none'; sandbox",...wt});return I.cookie&&De.append("Set-Cookie",I.cookie),o.info(`200 ${$} type=${T.contentType} bytes=${T.bytes.byteLength}${de}`),new Response(T.bytes,{status:200,headers:De})},E=(I,T)=>{let V=I.spend(T.internalUserId,`attachment=${T.attachmentId} viewer=${T.internalUserId} variant=thumbnail`);return V===null?null:T.fail(V.status,V.message,V.headers)},M=I=>E(m,I),U=(I,T)=>T?E(u,I):M(I);return async(I,T)=>{let{request:V,attachmentId:L,internalUserId:$,readAttachment:de,cookie:pe,fail:De}=I,K=Rn[T],le=V.headers.get("If-None-Match"),ne=le!==null,ce=U(I,ne);if(ce)return ce;let me=await n(V),Re=await t.getAttachmentForUser(me,L,$),ae=Re!==null&&Sr(Re,i)?ga({rendererId:c.id,box:K,attachmentId:L,filePath:Re.filePath,fileType:Re.fileType,fileSize:Re.fileSize}):null;if(ae&&bn(le,ae.etag)){let w=new Headers({"Cache-Control":_a,ETag:ae.etag,...wt});return pe&&w.append("Set-Cookie",pe),o.info(`304 attachment=${L} viewer=${$} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:w})}if(ne){let w=M(I);if(w)return w}if(!Re)return o.warn(`404 attachment=${L} viewer=${$} variant=thumbnail reason=not_visible`),De(404,ct[404]);if(!ae)return m.refund($,Ia),o.info(`404 attachment=${L} viewer=${$} variant=thumbnail reason=not_eligible`),De(404,ct[404]);let{key:Ne,etag:Fe}=ae,at=h.get(Ne);if(at)return m.refund($,Ia),S(I,{...at,identity:"verified"},Fe,"hit");let it=w=>D({key:Ne,attachmentId:L,filePath:Re.filePath,fileSize:Re.fileSize,box:K,owner:$,readAttachment:de,renderer:c},w),Ee;try{Ee=await R.join(Ne,V.signal,it)}catch(w){return o.error(`500 attachment=${L} viewer=${$} variant=thumbnail cache=miss reason=port_exception message=${w instanceof Error?w.message:"unknown"}`),De(500,ct[500])}return S(I,Ee,Fe,"miss")}};var Vc='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',qc=()=>pr(403,En,{cookie:null}),Ma=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=Sn(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>pr(404,mr[404],{cookie:null}),crossSiteRejection:qc}),Pa=e=>{let{authenticate:t,service:r,encodeUserId:n,resolveViewerScope:o,logger:a}=e,i=r.attachmentDelivery,l={service:r,encodeUserId:n,resolveViewerScope:o,logger:a,recordObjectState:Yo(r,a)},c=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:Jo({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:Ca({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:s,params:m})=>{let u=null,f=(h,R,D={})=>pr(h,R,{cookie:u,extraHeaders:D});try{let{user:h,cookie:R}=await t(s,{failureRedirect:null});if(u=R??null,!h)return f(401,"Unauthorized");let D=Sn(new URL(s.url).searchParams);if(D.kind==="invalid")return f(400,"Invalid attachment request");if(D.kind==="thumbnail"&&s.method!=="GET")return f(405,"Method not allowed",{Allow:"GET"});if(s.method!=="GET"&&s.method!=="HEAD")return f(405,"Method not allowed",{Allow:"GET, HEAD"});if(c===null)return f(404,"Attachment not found");if(m.token===void 0)throw new Error(Vc);let S=c.idCodec.decode(m.token);if(S===null||!st(S))return f(400,"Invalid attachment token");let E=await r.getUserIdByExternalId(h.id);if(!E)return f(403,"Forbidden");let M={request:s,delivery:D,attachmentId:S,internalUserId:E,readAttachment:c.read,cookie:u,fail:f};return D.kind!=="thumbnail"?await c.serveOriginal(M):c.serveThumbnail===null?f(404,ct[404]):await c.serveThumbnail(M,D.variant)}catch(h){if(h instanceof Response)throw h;return a.error(`500 attachment=? viewer=? reason=unexpected message=${h instanceof Error?h.message:"unknown"}`),f(500,Xe)}}};var Yc=32*1024*1024,jc=60,Wc=4,zc=120,Gc=2,Kc=8*1024*1024,gr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Jc=e=>{if(e===void 0)throw Ke("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!gr(e))throw oe("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw Ke("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw oe("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw oe("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},Qc=e=>{if(e===void 0)return null;if(!gr(e))throw oe("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:Jc(e.renderer),rateLimitPerMinute:pt("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,zc),concurrency:pt("attachments.thumbnails.concurrency",e.concurrency,1,Gc),cacheBytes:pt("attachments.thumbnails.cacheBytes",e.cacheBytes,0,Kc)})},La=e=>{let t=e;if(t===void 0)return null;if(!gr(t))throw oe("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw Ke("attachments.idCodec","injected when attachments is given");if(!gr(r)||typeof r.encode!="function"||typeof r.decode!="function")throw oe("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw Ke("attachments.read","injected when attachments is given");if(typeof n!="function")throw oe("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:pt("attachments.maxBytes",t.maxBytes,1,Yc),rateLimitPerMinute:pt("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,jc),concurrency:pt("attachments.concurrency",t.concurrency,1,Wc),thumbnails:Qc(t.thumbnails)})},Xc=Object.freeze([["attachmentIdCodec","attachments.idCodec"],["readAttachment","attachments.read"],["attachmentMaxBytes","attachments.maxBytes"],["attachmentRateLimitPerMinute","attachments.rateLimitPerMinute"],["attachmentConcurrency","attachments.concurrency"],["attachmentThumbnailRenderer","attachments.thumbnails.renderer"],["attachmentThumbnailRateLimitPerMinute","attachments.thumbnails.rateLimitPerMinute"],["attachmentThumbnailConcurrency","attachments.thumbnails.concurrency"],["attachmentThumbnailCacheBytes","attachments.thumbnails.cacheBytes"]]),br=e=>{for(let[t,r]of Xc)if(Object.hasOwn(e,t))throw Ke(r,`given in place of the flat key ${t}`)};var ka=8,Zc=8*ka,eu=128,tu=2,va=tu*eu,ru=4*va,nu=6e4,ou=6e4,au="Too many reads",Na=Object.freeze(Object.keys(ft).filter(e=>ft[e].admission.includes("miss-gate"))),Oa=e=>{let t=qe({limit:Zc,maxHeldPerOwner:ka,queue:{max:ru,maxPerOwner:va,maxWaitMs:nu}}),r=Oe({windowMs:ou,tallies:Na,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`cache_miss_admission_suppressed count=${o} since=${a} viewer=${n} endpoints=${Na.map(l=>`${l}:${i[l]}`).join(",")}`)}});return{admissionFor:(n,o,a)=>({signal:a,acquire:async i=>{let l=await t.acquire(n,i);return l===null&&!i.aborted&&r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=cache_miss_admission`)),l}})}},Dr=(e,t,r)=>{let n=e(t,r,{error:{message:au}},503);for(let[o,a]of Object.entries(xe(503)))n.headers.set(o,a);return n};var iu=/^[0-9a-f]{1,16}$/,su=e=>st(e.reportHubId)&&(e.businessDate===null||nr(e.businessDate)),lu=e=>typeof e=="string"&&iu.test(e);var Fa=e=>{let t=e.get(ge.cursorReportHubId),r=e.get(ge.cursorBusinessDate),n=e.get(ge.cursorSnapshot),o=lu(n)?n:null,a=null;if(t!==null){let l=Ue(t);if(l===null)return{refused:"cursor"};let c={businessDate:r,reportHubId:l};if(!su(c))return{refused:"cursor"};a=c}else if(r!==null)return{refused:"cursor"};let i=Ot(e.get(ge.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var Ar=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,cu=2,uu=16,du=cu*uu,pu=6e4,Ha=()=>{},mu=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},Ua=e=>{let t=qe({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:du,queue:null}),r=Oe({windowMs:pu,tallies:["sse","ids-stream"],writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`streams_per_viewer_suppressed count=${o} since=${a} viewer=${n} routes=sse:${i.sse},ids-stream:${i["ids-stream"]}`)}});return{admit:async(n,o,a)=>{if(n===null)return Ha;if(a.aborted){if(t.canAcquire(n))return Ha}else{let i=await t.acquire(n,a);if(i!==null)return mu(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var Tr=30,Ya=4e3,yu="stream interrupted by server error",hu="Too many streams",fu=15e3,ja=Symbol("ids-stream-heartbeat"),$a=()=>{},Ba=e=>e.return(void 0).then($a,$a),Ru=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(ja),fu)}),stop:()=>clearTimeout(e)}};async function*Va(e,t,r,n){let o=t?co(e,t):0,a=!0;for(;;){let i=Math.min(o+(a?r:Ya),e.length),l=mt(e,o,i),c=i>o?e[i-1]:void 0;o=i;let s=o>=e.length;if(yield{kind:"chunk",...l,nextCursor:s||c===void 0?null:{businessDate:c.businessDate,reportHubId:c.reportHubId},isLast:s,...a?{total:e.length}:{},...a?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...a&&n.restarted?{restarted:!0}:{}},a=!1,s)return}}var Wa=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform",...Ve});return e&&t.append("Set-Cookie",e),t},qa=(e,t,r,n,o)=>{let a=async(m,u)=>{o(),u&&await Ba(t);try{m.close()}catch{}},i=new TextEncoder,l=!1,c=null,s=new ReadableStream({async pull(m){if(l||r.aborted){await a(m,!0);return}let u=Ru();try{c===null&&(c=t.next());let f=await Promise.race([c,u.fired]);if(u.stop(),f===ja){if(l||r.aborted){await a(m,!0);return}m.enqueue(i.encode(`
2
- `));return}c=null;let{value:h,done:R}=f;if(R){await a(m,!1);return}if(l||r.aborted){await a(m,!0);return}m.enqueue(i.encode(`${JSON.stringify(h)}
3
- `))}catch(f){if(u.stop(),c=null,o(),l||r.aborted)return;f instanceof He||n.error(`ids-stream emission failed: ${f instanceof Error?f.message:String(f)}`);try{let h={kind:"error",error:yu};m.enqueue(i.encode(`${JSON.stringify(h)}
4
- `)),m.close()}catch{}}},cancel(){l=!0,o(),Ba(t)}});return new Response(s,{status:200,headers:Wa(e)})},za=e=>{let{service:t,logger:r,streamSlots:n,missGate:o,refuseForcedRead:a}=e,i=async(l,c,s,m,u,f,h)=>{let R=!1,D=null,S=null,E=new Promise((I,T)=>{D=I,S=T});E.catch(()=>{});let M=t.getDailyReportIdsByExternalId(s,c.id,{forceRefresh:l.forceRefresh,admission:h,onFetchStart:l.cursor?void 0:()=>{R=!0,t.readSseStreamAnchor().then(I=>t.getDailyReportIdsFirstPageByExternalId(s,c.id,Tr).then(T=>({items:T,streamAnchor:I}))).then(I=>D?.(I),I=>S?.(I))}});if(M.catch(()=>{}),l.cursor){let{items:I,streamAnchor:T,snapshot:V}=await M,L=l.snapshot!==null&&l.snapshot===V;return qa(m,Va(I,L?l.cursor:null,Tr,{snapshot:V,restarted:!L,streamAnchor:T}),u,r,f)}let U=(async function*(){let I=await Promise.race([M.then(L=>({kind:"full",source:L}),L=>({kind:"full-error",error:L})),E.then(L=>({kind:"page",page:L}),()=>({kind:"page-error"}))]),T=null,V=!1;if(I.kind==="full")T=I.source;else if(I.kind==="page"){let{items:L,streamAnchor:$}=I.page;if(L.length<Tr){yield{kind:"chunk",...mt(L,0,L.length),nextCursor:null,isLast:!0,total:L.length,streamAnchor:$};return}yield{kind:"chunk",...mt(L,0,L.length),nextCursor:null,isLast:!1,provisional:!0},V=!0}else if(I.kind==="full-error"&&R){let L=await E.catch(()=>null);L&&L.items.length>0&&(yield{kind:"chunk",...mt(L.items,0,L.items.length),nextCursor:null,isLast:!1,provisional:!0})}T===null&&(T=await M),yield*Va(T.items,null,V?Ya:Tr,{snapshot:T.snapshot,streamAnchor:T.streamAnchor})})();return qa(m,U,u,r,f)};return async(l,c,s,m,u,f)=>{let h=Fa(l.searchParams);if("refused"in h)return f(s,c,{error:{message:h.refused==="cursor"?"Invalid cursor":"Invalid forceRefresh"}},400);let{query:R}=h;if(R.forceRefresh){let M=a(m,s,c,f);if(M!==null)return M}let D=Ar(s),S=await t.getUserIdByExternalId(m.id),E=await n.admit(S,"ids-stream",D);if(E===null){let M=f(s,c,{error:{message:hu}},503);for(let[U,I]of Object.entries(xe(503)))M.headers.set(U,I);return M}if(D.aborted)return new Response(null,{status:200,headers:Wa(c)});try{return await i(R,m,u,c,D,E,S===null?void 0:o.admissionFor(S,se.idsStream,D))}catch(M){if(E(),M instanceof He)return Dr(f,s,c);throw M}}};var $t=require("drizzle-orm");var Su="",gu=64,bu=e=>e.toLowerCase(),Du=e=>e.trim().toLowerCase();function Ga(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=Du(r);n.length>0&&t.add(n)}return t}function Pe(e,t){return e===null?!0:t==null?!1:e.has(bu(t))}function Le(e){return e!==null&&e.size===0}function Bt(e,t){if(t!==null)return t.size===0?$t.sql`1 = 0`:(0,$t.inArray)($t.sql`LOWER(${e})`,[...t])}var _t,xt,Ut=class Ut{constructor(t,r){Wr(this,_t);Wr(this,xt);zr(this,_t,t),zr(this,xt,r)}get visible(){return kt(this,_t)===null?null:new Set(kt(this,_t))}get commentable(){return kt(this,xt)===null?null:new Set(kt(this,xt))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=Ga(r?t.read:t),o=r?t.comment:void 0;if(o===void 0)return new Ut(n,n);let a=Ga(o),i=new Set;for(let l of a??[])n.has(l)&&i.add(l);return new Ut(n,i)}static unrestricted(t){return new Ut(null,null)}};_t=new WeakMap,xt=new WeakMap;var Me=Ut;function Vt(e){let t=Ka(e.visible),r=Ka(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function Ka(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(Su);if(t.length<=gu)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 Ja=(e,t,r,n)=>Pe(n.commentable,t)||e.authorUserId!==null&&e.authorUserId===r;var ii=require("@aiquants/fuzzy-search");var Xa=require("crypto"),Pn=require("timers/promises"),fe=require("@aiquants/fuzzy-search/normalize");var wr=`
5
- `,Ln=4e3,Au=1,Za=new Set([8203,8288,65279,173]),Tu=new RegExp(`[${String.fromCodePoint(...Za)}]`,"gu"),Eu=new RegExp(`\\r\\n|[\\n\\r${String.fromCodePoint(133,8232,8233)}]`,"gu"),wu=/(\s+)/u,Iu=/^\s+$/u,_u=/^(?:(?=\p{Lo})[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]|[A-Za-z0-9])$/u,xu=new Set([8205,1536,1537,1538,1539,1540,1541,1757,1807,2192,2193,2274,69821,69837,70082,70083,71999,72001,72250,72324,72325,72326,72327,72328,72329,73030,73474]),qt=e=>e.replace(Tu,""),ei=e=>{let t=qt(e);if(t.length===e.length)return{text:t,rawIndex:null};let r=new Uint32Array(t.length),n=0;for(let o=0;o<e.length;o++)Za.has(e.charCodeAt(o))||(r[n++]=o);return{text:t,rawIndex:r}},Nn=e=>(0,fe.normalizeText)(e,fe.DEFAULT_NORMALIZE_OPTIONS),Er=e=>Nn(qt(e)),Cu=(0,fe.resolveNormalizeOptions)({...fe.DEFAULT_NORMALIZE_OPTIONS,convertRomaji:!0},"[daily-report] search reading options"),Mu=3,Pu=/^[-ー]+/u,Lu=/[^\p{L}\p{M}]/gu,Nu=/ー{2,}/gu,ku=/\p{Script=Latin}/u,Qa=/(?=\p{L})\p{Script=Latin}/u,vu=e=>(0,fe.clusterCountOf)(e.replace(Pu,"").replace(Lu,"").replace(Nu,"\u30FC")),Ou=(e,t)=>{for(let r of t)if(!(0,fe.isAnswerTier)(r.tier)||r.splitTier!==null)throw new Error(`[daily-report] search readings: queryNeedles gave an unfinished needle for the word ${JSON.stringify(e)} (text ${JSON.stringify(r.text)}, tier ${r.tier}, splitTier ${r.splitTier})`)},ti=e=>{if(!Qa.test(e))return[];let t=Er(e);if(!Qa.test(t))return[];let r=(0,fe.queryNeedles)(t,Cu,!1);Ou(t,r);let n=[];for(let o of r){if(o.tier===yt.word)continue;let a=Er(o.text);if(!(a.length===0||a.length>Ie.maxWordLength)&&!(a===t||ku.test(a))&&!(vu(a)<Mu||n.includes(a))&&(n.push(a),n.length===rn))break}return n},ri=(e,t)=>{let r=e.charCodeAt(t-1),n=e.charCodeAt(t);return r>=55296&&r<=56319&&n>=56320&&n<=57343},Fu=(e,t)=>{let r=e.codePointAt(t),n=t>=2&&ri(e,t-1)?t-2:t-1;return _u.test(String.fromCodePoint(r))&&!xu.has(e.codePointAt(n))},Hu=(e,t,r)=>{let n=[],o=0,a=0;for(;e.length-a>r;){let i=a+r;for(;i>a&&!Fu(e,i);)i--;i===a&&(i=a+r,ri(e,i)&&i--,o++),n.push({start:t+a,end:t+i}),a=i}return n.push({start:t+a,end:t+e.length}),{pieces:n,forcedCuts:o}},Ir=(e,t)=>{if(e.length<=t)return{chunks:[[{start:0,end:e.length}]],forcedCuts:0};let r=[],n=0,o=0,a=0,i=0,l=()=>{i>0&&r.push([{start:a,end:a+i}]),i=0};for(let c of e.split(wu)){let s=o;if(o+=c.length,i+c.length<=t){i===0&&(a=s),i+=c.length;continue}if(l(),Iu.test(c))continue;if(c.length<=t){a=s,i=c.length;continue}let m=Hu(c,s,t);n+=m.forcedCuts,r.push(m.pieces)}return l(),{chunks:r,forcedCuts:n}},kn=(e,t)=>{let r=Ir(e,t),n=[];for(let o of r.chunks){let a=o.map(i=>Nn(e.slice(i.start,i.end))).join("");a.length>0&&n.push(a)}return{text:n.join(" "),forcedCuts:r.forcedCuts}},vn=(e,t)=>{let r=0;for(let n of e.matchAll(Eu))t(e.slice(r,n.index),r),r=n.index+n[0].length;t(e.slice(r),r)},Uu=(e,t)=>{if(e.partialReadings!==null)throw new Error(`[daily-report] search marks: the mapped forms of the piece ${JSON.stringify(t)} carry partial readings`);return e.canonical},ni=(e,t)=>{let r="",n=[],o=[];for(let a of t.chunks){let i="",l=[],c=[];for(let s of a){let m=e.slice(s.start,s.end),u=Uu((0,fe.toMappedFormsInto)(m,fe.DEFAULT_NORMALIZE_OPTIONS,new fe.InteriorPairs(0)),m),[f,h]=(0,fe.trimmedRange)(u.text);i+=u.text.slice(f,h);for(let R=f;R<h;R++)l.push(s.start+u.start[R]),c.push(s.start+u.end[R])}if(i.length!==0){r.length>0&&(r+=" ",n.push(o[o.length-1]),o.push(l[0])),r+=i;for(let s=0;s<l.length;s++)n.push(l[s]),o.push(c[s])}}return{text:r,start:n,end:o}},_r=(e,t=Ln)=>{let r=[],n=0;return vn(qt(e),o=>{let a=kn(o,t);n+=a.forcedCuts,a.text.length>0&&r.push(a.text)}),{text:r.join(wr),forcedCuts:n}},oi=e=>e.filter(t=>t.length>0).join(wr),$u=e=>{let t=[];for(let r=0;r<=65535;r++)r>=55296&&r<=57343||t.push(e+String.fromCharCode(r));return t.join(`
6
- `)},Bu=[`\u3067\u3093${String.fromCodePoint(8203)}\u3077\u3093 \uFF83\uFF9E\uFF9D\uFF8C\uFF9F\uFF9D\r
7
- \u30C7\u30F3\u30D7\u30F3`,"\u30DD\u30C6\u30C8-25kg \u30A2--1 \u30FC\u30FC\u30E1\u30F3 \u4F50\u3005\u6728","\u6F22\u5B57\u304B\u306A\u30AB\u30CAABC123\u6F22\u5B57\u304B\u306A\u30AB\u30CAABC123\u6F22\u5B57\u304B\u306A\u30AB\u30CA",`\uFF71\uFF72\uFF73\uFF74\uFF75\uFF76\uFF9E\uFF77\uFF9E\uFF78\uFF9E\uFF79\uFF9E\uFF7A\uFF9E${String.fromCodePoint(8232)}\u6B21\u306E\u884C`],Vu=["","\u30A2","\u4F50"," "],qu=()=>JSON.stringify(Bu.map(e=>_r(e,8))),Yu=e=>`dr-search-v${Au};fz=${e.slice(0,16)};u=${process.versions.unicode};icu=${process.versions.icu}`;var ju=async()=>{let e=(0,Xa.createHash)("sha256");e.update(JSON.stringify(fe.DEFAULT_NORMALIZE_OPTIONS));for(let t of Vu)await(0,Pn.setImmediate)(),e.update("\0"),e.update(Nn($u(t)));return await(0,Pn.setImmediate)(),e.update("\0"),e.update(qu()),Yu(e.digest("hex"))},Wu=e=>{let t=null;return()=>{if(t===null){let r=e();t=r,r.catch(()=>{t=null})}return t}},On=Wu(ju);var zu=/^-+/u,Gu=/\s+/u,ai=e=>{let t=zu.exec(e);return t===null?[e]:[e,"\u30FC".repeat(t[0].length)+e.slice(t[0].length)]},Ku=(e,t)=>{let r=[...ai(e).map(n=>({text:n,tier:yt.word})),...t.flatMap(n=>ai(n).map(o=>({text:o,tier:yt.reading})))];return r.filter((n,o)=>r.findIndex(a=>a.text===n.text)===o)},Ju=e=>JSON.stringify(e.map(({text:t,tier:r})=>JSON.stringify([r,t])).sort()),xr=(e,t)=>{if(e.length>Ie.maxQueryLength)return{ok:!1,reason:"too-long"};let r=[],n=new Set,o=0;for(let{query:a}of(0,ii.parseQuerySets)(qt(e),t).sets){let i=[],l=new Set;for(let s of a.split(Gu)){let m=Er(s);if(m.length===0)return{ok:!1,reason:"blank-word"};if(m.length>Ie.maxWordLength)return{ok:!1,reason:"word-too-long"};let u=Ku(m,ti(s)),f=Ju(u);l.has(f)||(l.add(f),i.push({alternatives:u}))}if(i.length>Ie.maxWordsPerSet)return{ok:!1,reason:"too-many-words-in-set"};let c=JSON.stringify([...l].sort());n.has(c)||(n.add(c),o+=i.length,r.push({words:i}))}return r.length===0?{ok:!1,reason:"empty"}:r.length>Ie.maxSets?{ok:!1,reason:"too-many-sets"}:o>Ie.maxWords?{ok:!1,reason:"too-many-words"}:{ok:!0,plan:{combine:t,sets:r}}},Yt=e=>e.sets.map(t=>t.words.map(r=>r.alternatives));var Xy=Object.freeze({sourceTypes:null,authors:null,customers:null}),Qu=e=>e.sourceTypes!==null||e.authors!==null||e.customers!==null,si=(e,t,r)=>{if(Ao(e)&&Qu(r))return{ok:!0,criteria:{plan:null,filters:r}};let n=xr(e,t);return n.ok?{ok:!0,criteria:{plan:n.plan,filters:r}}:{ok:!1,reason:n.reason}};var li=6e4,Xu=1,Zu=3200,ci=2e3,ed=Object.freeze({search:Zu,reports:ci,"search-marks":ci,"search-facets":null}),td=(e,t)=>{let r=ed[e];return r===null?null:{max:t,maxPerOwner:ir,maxWaitMs:r}},jt=e=>{let{concurrency:t,route:r,logger:n}=e,o=Ze({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:li,logger:n,windowFields:()=>`route=${r}`}),a=qe({limit:t,maxHeldPerOwner:Math.max(1,Math.floor(t/2)),queue:td(r,t)}),i=Object.freeze({status:429,message:In,headers:Object.freeze({"Retry-After":String(Xu)})}),l=Oe({windowMs:li,tallies:["busy"],writeSuppressed:(c,{count:s,since:m})=>{n.warn(`busy_suppressed count=${s} since=${m} route=${r} concurrency=${t}`)}});return{admit:async(c,s)=>{let m=o.spend(c,r);if(m!==null)return{refusal:m};let u=await a.acquire(c,s);return u!==null?{release:u}:(o.refund(c,1),s.aborted||l.record(r,"busy",()=>n.warn(`429 ${r} reason=busy concurrency=${t}`)),{refusal:i})}}};var Di=require("@aiquants/sse"),ut=require("@aiquants/sse/server");var Ct=(e,t)=>{let r=e.message.data;if(!r)return{entry:{id:e.id,message:null},json:void 0};let n;try{n=JSON.parse(r)}catch(i){return t.error(`SSE message ${e.id} is not JSON:`,i),{entry:{id:e.id,message:null},json:void 0}}let o=bo.safeParse(n);if(!o.success)return t.error("SSE message validation failed:",o.error.format()),{entry:{id:e.id,message:null},json:n};let a=Object.freeze({parsed:o.data,published:n,text:r});return{entry:Object.freeze({id:e.id,message:a}),json:n}},rd=["externalComments","postedComments"],ui=new WeakMap,nd=e=>{let t=ui.get(e);if(t!==void 0)return t;let r={recipientRemoved:null,commentsRedacted:null};return ui.set(e,r),r},di=e=>{let{recipientRawUserId:t,...r}=e;return r},pi=(e,t)=>{let{published:r}=e;if(!(t||Object.hasOwn(r,"recipientRawUserId")))return e.text;let n=nd(e);if(t){if(n.commentsRedacted===null){let o=di(r),a=o.report;n.commentsRedacted=JSON.stringify({...o,report:{...a,...Object.fromEntries(rd.map(i=>[i,[]]))}})}return n.commentsRedacted}return n.recipientRemoved===null&&(n.recipientRemoved=JSON.stringify(di(r))),n.recipientRemoved};var Ri=require("@aiquants/sse"),Si=require("@aiquants/sse/shared-source");var Rt="daily-report:ids:",St="daily-report:business-date:",Cr=(e,t)=>`${e}st:${t}`,Fn=e=>`${Rt}user:${e}:`,mi=(e,t)=>Cr(Fn(e),t),od=e=>`${St}${e}:`,yi=(e,t)=>Cr(od(e),t),Wt=e=>`daily-report:date:${e}:user:`,Mt=(e,t)=>`${Wt(e)}${t}:`,hi=(e,t,r)=>Cr(Mt(e,t),r),je=e=>`daily-report:detail:${e}:user:`,Mr=(e,t)=>`${je(e)}${t}:`,fi=(e,t,r)=>Cr(Mr(e,t),r);var tt=(e,t)=>{let[r,n]=e.split("-").map(Number),[o,a]=t.split("-").map(Number);return r!==o?r<o:n<=a},ad=5e3,id=cr,Pt=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=be(t.logger,1,"SseReader"),this._source=this._createSource()}ready(){return this._position().then(()=>{})}subscribe(t,r){return this._source.subscribe({next:n=>{this._lastId=n.id,t(n)},error:n=>r(n instanceof Error?n:new Error(String(n)))})}async destroy(){await this._source.dispose(),this._generation+=1,this._positioning=null,this._lastId=null,this._source=this._createSource()}_position(){if(this._lastId!==null)return Promise.resolve(this._lastId);if(this._positioning===null){let t=this._generation;this._positioning=this._readTail().then(r=>{if(t!==this._generation)throw new Error("SSE reader was destroyed while the stream tail was being read");return this._positioning=null,this._lastId=r,r},r=>{throw t===this._generation&&(this._positioning=null),r})}return this._positioning}async _readTail(){let t=await this.config.redis?.getClient();if(!t)throw new Error("Failed to get Redis client to read the SSE stream tail");let r=await t.xRevRange(this.config.streamKey,"+","-",{COUNT:1});return r.length>0?r[0].id:"0-0"}_createSource(){return(0,Si.createSharedSource)({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:Ri.systemSseRuntime,onListenerError:t=>this._logger.error("SSE reader subscriber threw:",t),onStopError:t=>this._logger.error("SSE reader failed to stop:",t)})}async _start(t){let r=await this._position(),n=await this.config.redis?.createClient();if(!n)throw new Error("Failed to create Redis client for SSE reader");n.on("error",i=>{this._logger.error("Redis client error:",i)});let o=!1,a=this._readLoop(n,t,r,()=>o);return async()=>{if(o=!0,n.isOpen)try{await n.quit()}catch{}await a}}async _readLoop(t,r,n,o){let a=n;try{for(;!o()&&t.isOpen;){let i=await t.xRead([{key:this.config.streamKey,id:a}],{BLOCK:ad,COUNT:id});if(i)for(let l of i)for(let c of l.messages){a=c.id;let{entry:s,json:m}=Ct(c,this._logger);this._invalidateCaches(m),r.next(s)}}}catch(i){o()||(this._logger.error("xRead loop error:",i),r.fail(i instanceof Error?i:new Error(String(i))));return}o()||r.fail(new Error("Redis client for SSE reader closed unexpectedly"))}_invalidateCaches(t){if(t===null||typeof t!="object")return;let{type:r,reportHubId:n}=t;(r==="report-create"||r==="report-delete"||r==="report-publish")&&this.config.cache.invalidatePrefix(Rt),(r==="comment-add"||r==="comment-delete"||r==="status-update")&&typeof n=="number"&&this.config.cache.invalidatePrefix(je(n))}};var Ai=Object.freeze({...Ft,route:"sse",frameworkDataRefusal:dr}),gi=864e5,sd={baseMs:2e3,jitterMs:8e3},Hn=6e4,Lr=cr,Ti=JSON.stringify({type:"connected"}),bi="0-0",ld=(e,t,r,n)=>{if(r===null&&n===null)return!0;let o=typeof t.sourceType=="string"?t.sourceType:void 0;switch(e.type){case"connected":case"status-update":return!0;case"report-create":case"report-update":case"report-publish":return Pe(r,e.report.sourceType);case"comment-add":case"comment-delete":return Pe(n,o??"Internal");case"report-delete":return Pe(r,o)}},cd=(e,t)=>t===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"?!1:!Pe(t,e.report.sourceType),ud=(e,t)=>{e.writeEvent({event:null,id:t,data:Ti})},dd=(e,t,r)=>{let{message:n}=t;if(n===null)return;let{parsed:o,published:a}=n,i=typeof a.recipientRawUserId=="number"?a.recipientRawUserId:void 0;if((o.type==="status-update"||i!==void 0)&&i!==r.internalUserId||!ld(o,a,r.visibleSet,r.commentableSet)){ud(e,t.id);return}e.writeEvent({event:null,id:t.id,data:pi(n,cd(o,r.commentableSet))})},Ei=e=>{let{authenticate:t,service:r,resolveViewerScope:n,redis:o,sseReader:a,streamKey:i,streamSlots:l,logger:c}=e,s=async(m,u)=>{let{request:f,internalUserId:h,cursor:R}=u,D=u.initialScope.visible,S=u.initialScope.commentable,E=0,M=setInterval(()=>{let K=++E;n(f,"refresh").then(le=>{K===E&&(D=le.visible,S=le.commentable)})},Hn);m.onClose(()=>clearInterval(M));let U=R===null?bi:R,I=R!==null&&o!==void 0,T=[],V=null,L=K=>{tt(K.id,U)||(U=K.id,dd(m,K,{internalUserId:h,visibleSet:D,commentableSet:S}))},$=async(K,le)=>{let[ne]=await K.xRange(i,"-","+",{COUNT:1});return ne!==void 0&&!tt(ne.id,le)},de=async(K,le)=>{if(await $(K,le))return!1;let ne=le;for(;;){let ce=await K.xRange(i,ne,"+",{COUNT:Lr}),me=ce[0];if(me!==void 0&&me.id!==ne&&await $(K,ne))return!1;for(let ze of ce){if(V!==null&&tt(V,ze.id))return!0;tt(ze.id,U)||L(Ct(ze,c).entry)}let Re=ce.at(-1);if(ce.length<Lr||Re===void 0||m.isClosed())return!0;ne=Re.id}},pe=a.subscribe(K=>{if(!I){L(K);return}tt(K.id,U)||(V===null&&(V=K.id),T.push(K))},K=>{c.error(`[SSE:${h}] Fan-Out reader error:`,K),m.close()});if(m.onClose(pe),R===null){await a.ready();try{let K=await o?.getClient();if(K){let le=await K.xRevRange(i,"+","-",{COUNT:1});le.length>0&&!tt(le[0].id,U)&&(U=le[0].id)}}catch{}}if(m.writeEvent({event:null,id:U===bi?null:U,data:Ti}),(0,ut.startSseHeartbeat)(m,{intervalMs:fo,retry:sd,runtime:Di.systemSseRuntime}),R===null||o===void 0)return;await a.ready();let De=await o.getClient();if(De===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await de(De,R)){m.writeRetry(gi),m.writeEvent({event:"resync-required",id:null,data:""}),m.close();return}I=!1;for(let K of T.splice(0))L(K)};return async({request:m,params:u})=>{let f,h=()=>{let D=new Headers;f!==void 0&&D.append("Set-Cookie",f);for(let[S,E]of Object.entries(Ve))D.set(S,E);return D},R=D=>(0,ut.terminalStreamResponse)(D,{data:"",retryMs:gi,headers:h()});try{let D=await t(m,{failureRedirect:null});f=D.cookie;let{user:S}=D;if(!S)return R("auth-required");let E=await r.getUserIdByExternalId(S.id);if(!E)return R("forbidden");if(u.endpoint!=="updates")return new Response("Not Found",{status:404,headers:h()});let M=(0,ut.readLastEventId)(m,Ro);if(M!==null&&!So(M))return c.warn(`[SSE:${E}] malformed resume cursor; asking the client to resync`),R("resync-required");let U=Ar(m),I=await l.admit(E,"sse",U);if(I===null){let V=h();for(let[L,$]of Object.entries(xe(503)))V.set(L,$);return new Response("Too many streams",{status:503,headers:V})}let T=!1;try{let V=await n(m,"initial");return(0,ut.createSseResponse)({requestSignal:U,headers:h(),onError:(L,$)=>c.error(`[SSE:${E}] ${$} failed:`,L),produce:L=>(T=!0,L.onClose(I),s(L,{request:m,internalUserId:E,cursor:M,initialScope:V}))})}finally{T||I()}}catch(D){if(D instanceof Response)throw D;let S=D instanceof Error?D:new Error(String(D));return c.error(`500 sse name=${S.name} message=${S.message}`),new Response("Internal Server Error",{status:500,headers:h()})}}};var wi=(e,t)=>{let r=new Headers({...t?.headers,"Content-Type":"application/json",...Ve});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},pd=Object.freeze({...Ft,route:"api",frameworkDataRefusal:({params:e})=>fn(e.endpoint)&&ft[e.endpoint].body==="stream"?dr():null}),md=Object.freeze({...Ft,route:"action"}),yd=(e,t,r)=>({...r,status:"OK",intent:e.intent,reportHubId:t,clientTempId:e.clientTempId}),Mi=6e4,Pi=5,hd=Pi*Math.ceil(Mi/500),fd=2,Rd=6,Sd=6e4,gd=Pi*fd*Rd,bd=2,Dd=10,Ad=2,Td=10,Ii=(e,t)=>Math.max(e,ir)*t,Li=(e,t)=>{for(let[r,n]of Object.entries(t))e.headers.set(r,n);return e},Ed=Object.freeze({etag:(e,t,r)=>Ho(e,t,r,200),"no-store":(e,t,r)=>Dn(t,r,200)}),wd=e=>An(e.body==="json"?Ed[e.cache]:null),_i=An(null),xi=(e,t,r,n)=>Li(e(t,r,{error:{message:n.message}},n.status),n.headers),Ci=(e,t,r)=>Li(e(t,r,null,503),xe(503));function Nr(e){br(e);let{authenticate:t,service:r,encodeUserId:n,redis:o,sseReader:a,streamKey:i}=e,l={titleMaxLength:re("service.titleMaxLength",r.titleMaxLength,1)},c=e.loginRedirectPath??"/auth/login",s=be(e.logger,3,"API"),m=be(e.logger,3,"Visibility"),u=be(e.logger,1,"SSE"),f=be(e.logger,1,"Attachment"),h=be(e.logger,2,"Isolation"),R=be(e.logger,2,"Action"),D=be(e.logger,2,"Search"),S=be(e.logger,2,"Refresh"),E=be(e.logger,2,"Streams"),M=be(e.logger,2,"Reads"),U=Ze({reason:"refresh_rate_limit",limitPerWindow:gd,windowMs:Sd,logger:S,windowFields:()=>"route=api"}),I=Ua(E),T=Oa(M),V=async(w,H,v,N,B,z)=>{let J=await r.getUserIdByExternalId(H.id);try{return await z(J===null?void 0:T.admissionFor(J,w,v.signal))}catch(G){if(G instanceof He)return Dr(B,v,N);throw G}},L=(w,H,v,N,B)=>{let z=U.spend(H.id,`endpoint=${w}`);return z===null?null:xi(B,v,N,z)},$=async(w,H="initial")=>{let v=e.resolveVisibleSourceTypes;if(!v)return Me.unrestricted("no visibility port injected: this deployment does not restrict by source type");try{let N=await v(w,{reason:H});return N==null?Me.unrestricted("visibility port returned null/undefined: this deployment opts out of source-type filtering"):Me.restrictTo(N)}catch(N){return m.error("resolveVisibleSourceTypes threw; failing closed (deny all)",N),Me.restrictTo([])}},de=async({request:w})=>{let{user:H,cookie:v}=await t(w,{failureRedirect:c}),N=new Headers;v&&N.append("Set-Cookie",v);let B=await r.getUserIdByExternalId(H.id),z=B?n(B):null;return{data:{user:H,userId:z},headers:N}},pe=w=>{let{limiter:H}=w;return async(v,N,B,z,J,G)=>{if(H===null)return G(B,N,{error:{message:"Unknown endpoint"}},404);let Z=w.parse(v);if(!Z.ok)return G(B,N,Z.invalid,400);let O=await r.getUserIdByExternalId(z.id);if(!O)return G(B,N,w.emptyAnswer(Z.parsed),200);let{signal:ie}=B,Se=await H.admit(O,ie);if("refusal"in Se)return ie.aborted?Ci(G,B,N):xi(G,B,N,Se.refusal);try{ie.throwIfAborted();let ye=await w.read(Z.parsed,{userId:O,user:z,scope:J},ie);return ie.throwIfAborted(),G(B,N,ye,200)}catch(ye){if(ie.aborted&&ye===ie.reason)return Ci(G,B,N);throw ye}finally{Se.release()}}},De=r.searchLimits===null?null:jt({...r.searchLimits,route:se.search,logger:D}),K=r.searchLimits===null?null:jt({concurrency:Ii(r.searchLimits.concurrency,bd),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*Dd,route:se.reports,logger:D}),le=r.searchLimits===null?null:jt({concurrency:Ii(r.searchLimits.concurrency,Ad),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*Td,route:se.searchMarks,logger:D}),ne=r.searchLimits===null?null:jt({...r.searchLimits,route:se.searchFacets,logger:D}),ce={[se.businessDate]:async(w,H,v,N,B,z)=>{let J=w.searchParams.get(ge.businessDate),G=J===null?null:Et(J);if(G===null)return z(v,H,{error:{message:"Invalid business date"}},400);let Z=Ot(w.searchParams.get(ge.forceRefresh));if(Z===null)return z(v,H,{error:{message:"Invalid forceRefresh"}},400);let O=Z?L(se.businessDate,N,v,H,z):null;return O!==null?O:V(se.businessDate,N,v,H,z,async ie=>{let Se=await r.getDailyReportsByBusinessDateByExternalId(B,G,N.id,{forceRefresh:Z,admission:ie});return z(v,H,{businessDate:G,reports:Se},200)})},[se.idsStream]:za({service:r,logger:s,streamSlots:I,missGate:T,refuseForcedRead:(w,H,v,N)=>L(se.idsStream,w,H,v,N)}),[se.report]:async(w,H,v,N,B,z)=>{let J=Ue(w.searchParams.get(ge.reportHubId));if(J===null)return z(v,H,{error:{message:"Invalid reportHubId"}},400);let G=Ot(w.searchParams.get(ge.forceRefresh));if(G===null)return z(v,H,{error:{message:"Invalid forceRefresh"}},400);let Z=G?L(se.report,N,v,H,z):null;return Z!==null?Z:V(se.report,N,v,H,z,async O=>{let ie=await r.getDailyReportDetailByIdByExternalId(B,J,N.id,{snapshot:!0,forceRefresh:G,admission:O});return ie?z(v,H,{report:ie},200):z(v,H,{error:{message:"Report not found"}},404)})},[se.search]:pe({limiter:De,parse:w=>{let H=w.searchParams.get(ge.searchQuery),v=yn(w.searchParams.get(ge.searchCombine));if(H===null||v===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let N=Eo(w.searchParams,r.searchFilterSourceTypes);if(!N.ok)return{ok:!1,invalid:{error:{message:"Invalid search filters",reason:N.reason}}};let B=si(H,v,N.filters);if(!B.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:B.reason}}};let{criteria:z}=B;return{ok:!0,parsed:{criteria:z,words:z.plan===null?[]:Yt(z.plan)}}},emptyAnswer:({words:w})=>nn([],w),read:async({criteria:w,words:H},{userId:v,scope:N})=>nn(await r.searchDailyReports(N,v,w),H)}),[se.reports]:pe({limiter:K,parse:w=>{let H=hn(w.searchParams.get(ge.reportIds));return H===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:H}},emptyAnswer:()=>({reports:[]}),read:async(w,{user:H,scope:v})=>({reports:await r.getDailyReportDetailsByIdsByExternalId(v,w,H.id)})}),[se.searchMarks]:pe({limiter:le,parse:w=>{let H=w.searchParams.get(ge.searchQuery),v=yn(w.searchParams.get(ge.searchCombine));if(H===null||v===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let N=xr(H,v);if(!N.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:N.reason}}};let B=hn(w.searchParams.get(ge.reportIds));return B===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:{plan:N.plan,ids:B}}},emptyAnswer:({plan:w})=>({wordsDigest:ar(Yt(w)),reports:[],deferred:[]}),read:({plan:w,ids:H},{userId:v,scope:N},B)=>r.markDailyReportSearchHits(N,v,w,H,{signal:B})}),[se.searchFacets]:pe({limiter:ne,parse:()=>({ok:!0,parsed:null}),emptyAnswer:()=>({sourceTypes:[],authors:[],customers:[]}),read:(w,{userId:H,scope:v})=>r.listDailyReportSearchFacets(v,H)})},me=async({request:w,params:H})=>{let{user:v,cookie:N}=await t(w,{failureRedirect:null}),B=N??null;if(!v)return _i(w,B,{error:{message:"Unauthorized"}},401);let z=H.endpoint;if(!fn(z))return _i(w,B,{error:{message:"Unknown endpoint"}},404);let J=ft[z],G=wd(J),Z=ko[J.body];if(!Z.includes(w.method)){let ie=G(w,B,{error:{message:"Method not allowed"}},405);return ie.headers.set("Allow",Z.join(", ")),ie}let O=ue();try{let ie=new URL(w.url),Se=await $(w),ye=await ce[z](ie,B,w,v,Se,G);return J.body==="json"&&s.debug(ye.headers.has("ETag")?`${ye.status} endpoint=${z} etag_match=${ye.status===304}`:`${ye.status} endpoint=${z}`),ye}catch(ie){let Se=ue()-O,ye=ie instanceof Error?ie:new Error(String(ie));return s.error(`500 endpoint=${z} elapsed=${Se}ms name=${ye.name} code=${"code"in ye?ye.code:"N/A"} message=${ye.message}`,ye),G(w,B,{error:{message:"Internal Server Error"}},500)}},Re=No(R),ze=Ze({reason:"rate_limit",limitPerWindow:hd,windowMs:Mi,logger:R,windowFields:()=>"route=action"}),ae=async(w,H,v,N,B)=>{let{clientTempId:z}=w;if(w.intent==="create"){let O=await r.createDailyReport(H,w.businessDate,z);return B(w,O.reportHubId,{report:O})}let{reportHubId:J,businessDate:G}=w,Z=async(O,ie)=>{try{let Se=await ie(O.value);return B(O,J,{updatedStatus:{isStarred:Se.isStarred,isRead:Se.isRead},operationTimestamp:O.operationTimestamp})}catch(Se){if(Se instanceof Error&&Se.message==="Not Found")return N({error:"Report not found"},{status:404});throw Se}};switch(w.intent){case"update":try{return await r.updateDailyReport(J,H,w.changes,z),B(w,J,{})}catch(O){if(O instanceof Error){if(O.message==="Unauthorized")return N({error:"Unauthorized"},{status:403});if(O.message==="Not Found")return N({error:"Report not found"},{status:404})}throw O}case"publish":try{let O=await r.publishDailyReport(J,H,z);return B(w,J,{report:O})}catch(O){if(O instanceof Error){if(O.message==="Unauthorized")return N({error:"Unauthorized"},{status:403});if(O.message==="Not Found")return N({error:"Report not found"},{status:404})}throw O}case"delete":try{return await r.deleteDailyReport(J,H,z),B(w,J,{})}catch(O){if(O instanceof Error){if(O.message==="Unauthorized")return N({error:"Unauthorized"},{status:403});if(O.message==="Not Found")return N({error:"Report not found"},{status:404})}throw O}case"toggleStar":return await Z(w,O=>r.setStarStatus(v,H,J,G,O,z));case"toggleRead":return await Z(w,O=>r.setReadStatus(v,H,J,G,O,z));case"addComment":try{let O=await r.addComment(v,H,J,w.content,G,z);return B(w,J,{newComment:O})}catch(O){if(O instanceof Error){if(O.message==="Not Found")return N({error:"Report not found"},{status:404});if(O.message.startsWith("Comments are restricted"))return N({error:"Comments are restricted for this report"},{status:403})}throw O}case"deleteComment":try{return await r.deleteComment(v,H,J,w.commentId,G,z),B(w,J,{deletedCommentId:w.commentId})}catch(O){if(O instanceof Error){if(O.message==="Unauthorized")return N({error:"Unauthorized"},{status:403});if(O.message==="Not Found")return N({error:"Comment not found"},{status:404})}throw O}}},Ne=async({request:w,params:H})=>{let{user:v,cookie:N}=await t(w,{failureRedirect:null}),B=(G,Z)=>wi(G,{...Z,setCookie:N}),z=(G,Z,O)=>wi(yd(G,Z,O),{setCookie:N});if(!v)return B({error:"Unauthorized"},{status:401});let J=ue();try{if(H.endpoint!==se.action)return B({error:"Unknown endpoint"},{status:404});let G=ze.spend(v.id,"action");if(G!==null)return B({error:G.message},{status:G.status,headers:G.headers});let Z=await Lo(w,l);if("refusal"in Z){let{refusal:ye}=Z;return ye.status===413&&Re(ye.measuredBy),B({error:ye.error},{status:ye.status})}let{command:O}=Z;if(O.intent==="clearCache"&&!e.enableDevCacheClear)return B({error:"Invalid intent"},{status:400});let ie=await r.getUserIdByExternalId(v.id);if(!ie)return B({error:"User not found"},{status:404});let Se=await $(w);return O.intent==="clearCache"?(await r.clearCache(),B({status:"OK",intent:"clearCache"})):await ae(O,ie,Se,B,z)}catch(G){if(G instanceof Response)throw G;let Z=ue()-J,O=G instanceof Error?G:new Error(String(G));return s.error(`500 action elapsed=${Z}ms name=${O.name} message=${O.message}`,O),B({error:"Internal Server Error"},{status:500})}},Fe=Ei({authenticate:t,service:r,resolveViewerScope:$,redis:o,sseReader:a,streamKey:i,streamSlots:I,logger:u}),at=Pa({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:$,logger:f}),it=qo(h),Ee=(w,H)=>async v=>{let N=Bo(v.request)?w.frameworkDataRefusal(v):null;if(N!==null)throw N;return Vo(v.request,w)?(it(w.route,v.request),w.crossSiteRejection()):H(v)};return{index:{loader:de},api:{loader:Ee(pd,me),action:Ee(md,Ne)},sse:{loader:Ee(Ai,Fe)},attachment:{loader:Ee(Ma,at)}}}var Lt=require("@aiquants/mssql"),b=require("drizzle-orm");var rt=require("drizzle-orm"),Ni=e=>{if(e.length===0)throw new Error("[daily-report] draft rule: draftLabelNames must hold at least one name (a rule without names would show every draft to every viewer)");return rt.sql.join(e.map(t=>rt.sql`${t}`),rt.sql`, `)},kr=(e,t)=>{let{hub:r,hubLabel:n,label:o}=e;return rt.sql`EXISTS (SELECT 1 FROM ${n} INNER JOIN ${o} ON ${o.id} = ${n.labelId} WHERE ${n.hubId} = ${r.id} AND ${o.name} IN (${Ni(t)}))`},ki=(e,t)=>{let{hubLabel:r,label:n}=e;return rt.sql`${r.labelId} IN (SELECT ${n.id} FROM ${n} WHERE ${n.name} IN (${Ni(t)}))`},vr=(e,t,r,n)=>{let{hub:o}=e,a=n==="author-or-authorless"?rt.sql`${o.userId} = ${t} OR ${o.userId} IS NULL`:rt.sql`${o.userId} = ${t}`;return rt.sql`(${a} OR NOT ${kr(e,r)})`};var Id=["tables","externalSourceTexts","concurrency","rateLimitPerMinute"],_d=["document","comment"],xd=["hubId","searchText","sourceDigest","normalizerVersion","indexedAt","rowVersion","authorName","customerName"],Cd=["hubId","ordinal","authorUserId","commentText"],Un=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},vi=(e,t,r)=>{for(let n of Object.keys(t))if(!r.includes(n))throw Kr(e,n,r)},Oi=(e,t,r)=>{if(typeof t!="object"||t===null)throw oe(e,"a table object",t);let n=t;for(let o of r)if(typeof n[o]!="object"||n[o]===null)throw oe(`${e}.${o}`,"a column",n[o])},Fi=(e,t)=>{if(!Un(e))throw oe("search","a plain object",e);vi("search key",e,Id);let{tables:r}=e;if(!Un(r))throw oe("search.tables","a plain object with document and comment",r);vi("search.tables key",r,_d),Oi("search.tables.document",r.document,xd),Oi("search.tables.comment",r.comment,Cd);let n=new Map;if(e.externalSourceTexts!==void 0){if(!Un(e.externalSourceTexts))throw oe("search.externalSourceTexts","a plain object",e.externalSourceTexts);for(let[o,a]of Object.entries(e.externalSourceTexts)){if(!t.includes(o))throw Kr("search.externalSourceTexts key",o,t);if(typeof a!="function")throw oe(`search.externalSourceTexts.${o}`,"a function",a);n.set(o,a)}}return{tables:r,externalSourceTexts:n,concurrency:re("search.concurrency",e.concurrency,1),rateLimitPerMinute:re("search.rateLimitPerMinute",e.rateLimitPerMinute,1)}};var dt=e=>{let t=typeof e=="object"&&e!==null?e.recordset:void 0;if(!Array.isArray(t))throw new Error("[daily-report] search: the database result has no recordset");return t},gt=(e,t)=>{let r=typeof e=="string"?Ue(e):typeof e=="number"&&st(e)?e:null;if(r===null)throw new Error(`[daily-report] search: column ${t} holds no positive id`);return r},bt=(e,t)=>{if(e===null||typeof e=="string")return e;throw new Error(`[daily-report] search: column ${t} holds no string`)};var q=require("drizzle-orm");var Md=/[[%_]/gu,Pd=e=>e.replace(Md,t=>`[${t}]`),Hi=e=>`%${Pd(e)}%`;var Be=Object.freeze({reportHubId:"report_hub_id",businessDate:"business_date",sourceType:"source_type"}),Dt=Object.freeze({reportHubId:"report_hub_id",matchedSets:"matched_sets"}),Gt=Object.freeze({value:"value"}),we=Object.freeze({hubId:"hub_id",sourceDigest:"source_digest",normalizerVersion:"normalizer_version"}),j=e=>q.sql`${q.sql.identifier(e.name)}`,zt=e=>q.sql.join(e.map(t=>q.sql`${t}`),q.sql`, `),Ui=(e,t)=>q.sql`SELECT ${j(e.id)} AS ${q.sql.identifier(we.hubId)} FROM ${e} WITH (UPDLOCK, ROWLOCK) WHERE ${e.id} IN (${zt(t)}) ORDER BY ${e.id}`,Ld=(e,t,r)=>{let{hub:n}=e,{document:o,comment:a}=e.search,i=t.alternatives.map(u=>Hi(u.text)),l=q.sql.join(i.map(u=>q.sql`${o.searchText} LIKE ${u}`),q.sql` OR `),c=q.sql.join(i.map(u=>q.sql`${a.commentText} LIKE ${u}`),q.sql` OR `),s=Bt(n.sourceType,r.scope.commentable),m=s===void 0?q.sql``:q.sql` AND (${s} OR ${a.authorUserId} = ${r.userId})`;return q.sql`((${l}) OR EXISTS (SELECT 1 FROM ${a} WHERE ${a.hubId} = ${n.id} AND (${c})${m}))`},$i=(e,t,r)=>q.sql`(${q.sql.join(t.words.map(n=>Ld(e,n,r)),q.sql` AND `)})`,$n=(e,t,r,n)=>{let{hub:o}=e,a=[q.sql`${o.deletedAt} IS NULL`,vr(e,t.userId,r,"author")],i=Bt(o.sourceType,t.scope.visible);return i!==void 0&&a.push(i),n!==void 0&&a.push(q.sql`${o.id} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${JSON.stringify(n)}))`),a},Nd=(e,t)=>{let{hub:r}=e,{document:n}=e.search,o=[];if(t.sourceTypes!==null){if(t.sourceTypes.size===0)throw new Error("[daily-report] search: a source-type filter must hold at least one source type");o.push(q.sql`LOWER(${r.sourceType}) IN (${zt([...t.sourceTypes])})`)}return t.authors!==null&&o.push(q.sql`${n.authorName} IN (${zt(t.authors)})`),t.customers!==null&&o.push(q.sql`${n.customerName} IN (${zt(t.customers)})`),o},Bi=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,{plan:l}=t,c=[...$n(e,r,n,o),...Nd(e,t.filters)];if(l!==null){let s=l.combine==="intersection"?q.sql` AND `:q.sql` OR `;c.push(q.sql`(${q.sql.join(l.sets.map(m=>$i(e,m,r)),s)})`)}return q.sql`SELECT ${j(a.id)} AS ${q.sql.identifier(Be.reportHubId)}, CONVERT(char(10), ${j(a.businessDate)}, 23) AS ${q.sql.identifier(Be.businessDate)}, ${j(a.sourceType)} AS ${q.sql.identifier(Be.sourceType)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${q.sql.join(c,q.sql` AND `)} ORDER BY ${a.businessDate} DESC, ${a.id} DESC`},Vi=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,l=q.sql.join(t.sets.map((c,s)=>q.sql`(CASE WHEN ${$i(e,c,r)} THEN ${2**s} ELSE 0 END)`),q.sql` + `);return q.sql`SELECT ${j(a.id)} AS ${q.sql.identifier(Dt.reportHubId)}, ${l} AS ${q.sql.identifier(Dt.matchedSets)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${q.sql.join($n(e,r,n,o),q.sql` AND `)}`},qi=(e,t,r,n)=>{let{hub:o}=e,{document:a}=e.search,i=a[t],l=[...$n(e,r,n),q.sql`${i} IS NOT NULL`];return q.sql`SELECT ${i} AS ${q.sql.identifier(Gt.value)} FROM ${o} INNER JOIN ${a} ON ${a.hubId} = ${o.id} WHERE ${q.sql.join(l,q.sql` AND `)} GROUP BY ${i} ORDER BY ${i}`},Yi=(e,t,r)=>{let{document:n,comment:o}=e,a=JSON.stringify(t.map(c=>({[n.hubId.name]:c.hubId,[n.searchText.name]:c.searchText,[n.sourceDigest.name]:c.sourceDigest,[n.normalizerVersion.name]:r,[n.authorName.name]:c.authorName,[n.customerName.name]:c.customerName}))),i=JSON.stringify(t.flatMap(c=>c.comments.map(s=>({[o.hubId.name]:c.hubId,[o.ordinal.name]:s.ordinal,[o.authorUserId.name]:s.authorUserId,[o.commentText.name]:s.commentText})))),l=JSON.stringify(t.map(c=>c.hubId));return q.sql`MERGE ${n} WITH (HOLDLOCK) AS t USING (SELECT * FROM OPENJSON(${a}) WITH (${j(n.hubId)} bigint, ${j(n.searchText)} nvarchar(max), ${j(n.sourceDigest)} char(64), ${j(n.normalizerVersion)} varchar(64), ${j(n.authorName)} nvarchar(max), ${j(n.customerName)} nvarchar(max))) AS s ON t.${j(n.hubId)} = s.${j(n.hubId)}
8
- WHEN MATCHED THEN UPDATE SET t.${j(n.searchText)} = s.${j(n.searchText)}, t.${j(n.sourceDigest)} = CONVERT(binary(32), s.${j(n.sourceDigest)}, 2), t.${j(n.normalizerVersion)} = s.${j(n.normalizerVersion)}, t.${j(n.authorName)} = s.${j(n.authorName)}, t.${j(n.customerName)} = s.${j(n.customerName)}, t.${j(n.indexedAt)} = SYSUTCDATETIME()
9
- WHEN NOT MATCHED THEN INSERT (${j(n.hubId)}, ${j(n.searchText)}, ${j(n.sourceDigest)}, ${j(n.normalizerVersion)}, ${j(n.authorName)}, ${j(n.customerName)}) VALUES (s.${j(n.hubId)}, s.${j(n.searchText)}, CONVERT(binary(32), s.${j(n.sourceDigest)}, 2), s.${j(n.normalizerVersion)}, s.${j(n.authorName)}, s.${j(n.customerName)});
1
+ "use strict";var ln=Object.defineProperty;var Fl=Object.getOwnPropertyDescriptor;var Hl=Object.getOwnPropertyNames;var Bl=Object.prototype.hasOwnProperty;var Do=e=>{throw TypeError(e)};var Ul=(e,t)=>{for(var r in t)ln(e,r,{get:t[r],enumerable:!0})},$l=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Hl(t))!Bl.call(e,o)&&o!==r&&ln(e,o,{get:()=>t[o],enumerable:!(n=Fl(t,o))||n.enumerable});return e};var Vl=e=>$l(ln({},"__esModule",{value:!0}),e);var To=(e,t,r)=>t.has(e)||Do("Cannot "+r);var Jt=(e,t,r)=>(To(e,t,"read from private field"),r?r.call(e):t.get(e)),cn=(e,t,r)=>t.has(e)?Do("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),un=(e,t,r,n)=>(To(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var nm={};Ul(nm,{DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES:()=>Nr,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES:()=>kr,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES:()=>Ro,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL:()=>Rr,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL:()=>So,DAILY_REPORT_SSE_CATCH_UP_BATCH:()=>Kr,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS:()=>oo,DailyReportSseReader:()=>Wt,DailyReportViewerScope:()=>Ue,SqlResultCache:()=>Ft,buildDailyReportSseStreamKey:()=>fo,createDailyReportHandlers:()=>Jr,createDailyReportServer:()=>rm,createDailyReportService:()=>on,createEpochStore:()=>gr,createSharpThumbnailRenderer:()=>Tl,defineDailyReportSchema:()=>il,defineDailyReportSearchSchema:()=>sl,encodeIdsStreamRows:()=>Ct,isStreamIdLte:()=>pt,parseClientTempId:()=>_r,predictSharpThumbnailWorkingSetBytes:()=>Dl,readDailyReportSseStreamEntry:()=>qt,transformJsonArray:()=>al});module.exports=Vl(nm);var dn=e=>typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"||e===null||e===void 0?String(e):Array.isArray(e)?"array":typeof e,X=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${dn(r)}`),it=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),pn=(e,t,r)=>X(e,`one of ${r.map(n=>JSON.stringify(n)).join(", ")}`,t),de=(e,t,r,n)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r&&(n===void 0||t<=n))return t;throw X(e,n===void 0?`an integer >= ${r}`:`an integer from ${r} to ${n}`,t)},Me=(e,t,r,n)=>t===void 0?n:de(e,t,r);var se=()=>Math.floor(performance.now());var mn=Object.freeze({defaultTtlMs:6e4,maxBuckets:4096,maxBytes:512*1024*1024}),je=class extends Error{constructor(t){super(`cache miss refused (${t})`),this.name="SqlResultCacheMissRefusal",this.reason=t}},gr=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{}}}),Qt=(e,t)=>t?e.map(r=>structuredClone(r)):e,Yl=8,ql=32,jl=24,Wl=16,zl=-(2**30),Gl=2**30-1,Kl=e=>Number.isInteger(e)&&e>=zl&&e<=Gl&&!Object.is(e,-0),Jl=(e,t)=>{let r=0,n=[e];for(;n.length>0&&r<=t;){let o=n.pop();if(r+=ql,ArrayBuffer.isView(o)){r+=o.byteLength;continue}let a=Array.isArray(o)?o:Object.keys(o).map(i=>o[i]);r+=Yl*a.length;for(let i of a)typeof i=="string"?r+=jl+2*i.length:typeof i=="number"&&!Kl(i)?r+=Wl:typeof i=="object"&&i!==null&&n.push(i)}return r},Ft=class{constructor(t,r){this.epochStore=r;this.buckets=new Map;this.totalBytes=0;this.inFlight=new Map;this.forcedFetches=new Map;this.maybeRefreshAhead=t=>{let r=t.refreshAheadRatio;if(r===void 0)return;let{cacheKey:n}=t,o=this.buckets.get(n);if(!o)return;let a=t.ttlMsOverride??this.defaultTtlMs;if(a-(o.expireAt-se())<a*r||this.inFlight.has(n))return;let l;l=(async()=>{let s=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,c=await t.fetcher();return this.inFlight.get(n)===l&&this.writeBucket(n,{records:c,expireAt:se()+a,epoch:s}),c})(),this.inFlight.set(n,l),l.catch(()=>{}).finally(()=>{this.inFlight.get(n)===l&&this.inFlight.delete(n)})};this.startFetch=(t,r)=>{let{cacheKey:n,admission:o}=t,a;a=(async()=>{let l=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,s=o===void 0?null:await o.acquire(o.signal);if(o!==void 0&&s===null)throw new je(o.signal.aborted?"aborted":"busy");try{for(let d of r)d();let c=await t.fetcher();return this.inFlight.get(n)===a&&this.writeBucket(n,{records:c,expireAt:se()+(t.ttlMsOverride??this.defaultTtlMs),epoch:l}),c}finally{s?.()}})(),this.inFlight.set(n,a);let i=()=>{this.inFlight.get(n)===a&&this.inFlight.delete(n)};return a.then(i,i),a};this.forcedFetch=t=>{let{cacheKey:r}=t,n=t.onFetchStart===void 0?[]:[t.onFetchStart],o=this.forcedFetches.get(r);if(o===void 0)return this.runForcedFetch(t,n);if(o.pending===null){let a=[],i=()=>this.runForcedFetch(t,a);o.pending={promise:o.running.then(i,i),onFetchStarts:a}}return o.pending.onFetchStarts.push(...n),o.pending.promise};this.runForcedFetch=(t,r)=>{let{cacheKey:n}=t,o=this.startFetch(t,r);this.forcedFetches.set(n,{running:o,pending:null});let a=()=>{let i=this.forcedFetches.get(n);i?.running===o&&i.pending===null&&this.forcedFetches.delete(n)};return o.then(a,a),o};this.getOrFetch=async t=>{let{cacheKey:r,forceRefresh:n,snapshot:o,admission:a}=t;if(n){if(a?.signal.aborted)throw new je("aborted");return this.dropBucket(r),Qt(await this.readOwnOrRetry(this.forcedFetch(t),t),o)}let i=this.buckets.get(r);if(i&&i.expireAt>se())if(t.epochKey){let s=await this.epochStore.getEpoch(t.epochKey);if(s===null||i.epoch===s)return this.maybeRefreshAhead(t),Qt(i.records,o);this.dropBucket(r)}else return this.maybeRefreshAhead(t),Qt(i.records,o);let l=this.inFlight.get(r);if(l!==void 0)return Qt(await this.readOwnOrRetry(l,t),o);if(a?.signal.aborted)throw new je("aborted");return Qt(await this.startFetch(t,t.onFetchStart===void 0?[]:[t.onFetchStart]),o)};this.readOwnOrRetry=async(t,r)=>{try{return await t}catch(n){let{admission:o}=r;if(!(n instanceof je&&(o===void 0||n.reason==="aborted"&&!o.signal.aborted)))throw n;return this.getOrFetch({...r,snapshot:!1})}};this.clearAll=()=>{this.buckets.clear(),this.totalBytes=0,this.inFlight.clear()};this.invalidatePrefix=t=>{for(let r of this.buckets.keys())r.startsWith(t)&&this.dropBucket(r);for(let r of this.inFlight.keys())r.startsWith(t)&&this.inFlight.delete(r)};this.defaultTtlMs=Me("cacheDefaultTtlMs",t.defaultTtlMs,1,mn.defaultTtlMs),this.maxBuckets=Me("cacheMaxBuckets",t.maxBuckets,1,mn.maxBuckets),this.maxBytes=Me("cacheMaxBytes",t.maxBytes,1,mn.maxBytes),this.lastSweepAt=se()}dropBucket(t){let r=this.buckets.get(t);r!==void 0&&(this.buckets.delete(t),this.totalBytes-=r.bytes)}writeBucket(t,r){this.dropBucket(t);let n=Jl(r.records,this.maxBytes);if(n>this.maxBytes)return;this.buckets.set(t,{...r,bytes:n}),this.totalBytes+=n;let o=se();o-this.lastSweepAt>=this.defaultTtlMs&&this.sweepExpired(o);for(let a of this.buckets.keys()){if(this.buckets.size<=this.maxBuckets&&this.totalBytes<=this.maxBytes)break;this.dropBucket(a)}}sweepExpired(t){this.lastSweepAt=t;for(let[r,n]of this.buckets)n.expireAt<=t&&this.dropBucket(r)}};var Ql=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var Ao=e=>e<10?`0${e}`:`${e}`,Xl=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=Ao(e.getMonth()+1),n=Ao(e.getDate());return`${t}-${r}-${n}`},Ht=e=>{let t=Ql.exec(e);if(t===null)return null;let[,r,,n,o]=t,a=Number(r),i=Number(n),l=Number(o);if(a<1)return null;let s=new Date(0);return s.setUTCFullYear(a,i-1,l),s.getUTCFullYear()!==a||s.getUTCMonth()!==i-1||s.getUTCDate()!==l?null:`${r}-${n}-${o}`},br=e=>Ht(e)===e;var Pe=e=>e==null?null:e instanceof Date?Xl(e):Ht(e);var Eo=require("zod/v3"),Ze=e=>Number.isSafeInteger(e)&&e>0,Ae=Eo.z.number().int().positive().max(Number.MAX_SAFE_INTEGER);var pe=require("zod/v3");var Dr=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|-[1-9][0-9]{0,15})$/;var It=Symbol("daily-report wire mismatch"),et=(e,t,r)=>(e.issues.push({...r,path:t===null?[...e.path]:[...e.path,t]}),It),xo=e=>e===null?"null":Array.isArray(e)?"array":Number.isNaN(e)?"nan":typeof e,_t=(e,t)=>({code:"invalid_type",expected:e,received:xo(t)}),Zl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ec=e=>{let t=0;for(let r in e)t+=1;return t},wo=(e,t,r)=>{let n={};for(let o=0;o<r;o+=1){let a=t[o];a in e&&(n[a]=e[a])}return n},Bt=e=>{let t=Object.keys(e),r=Object.values(e);return(n,o)=>{if(!Zl(n))return et(o,null,_t("object",n));let a=null,i=!1,l=0;for(let s=0;s<t.length;s+=1){let c=t[s],d=n[c];d!==void 0&&(l+=1);let u=r[s](d,o,c);if(u===It){i=!0;continue}a===null&&u!==d&&(a=wo(n,t,s)),a!==null&&(u!==void 0||c in n)&&(a[c]=u)}return i?It:a!==null?a:ec(n)===l?n:wo(n,t,t.length)}},Xt=e=>(t,r,n)=>{r.path.push(n);let o=e(t,r);return r.path.pop(),o},Zt=e=>(t,r,n)=>{if(!Array.isArray(t))return et(r,n,_t("array",t));r.path.push(n);let o=t,a=!1;for(let i=0;i<t.length;i+=1){let l=t[i],s=e(l,r,i);s===It?a=!0:s!==l&&(o===t&&(o=t.slice()),o[i]=s)}return r.path.pop(),a?It:o},le=(e,t,r)=>e==null||typeof e=="string"?e:et(t,r,_t("string",e)),Io=(e,t,r)=>e===null||typeof e=="string"?e:et(t,r,_t("string",e)),_o=(e,t,r)=>typeof e=="string"?e:et(t,r,_t("string",e)),tc=(e,t,r)=>e===null||typeof e=="number"&&!Number.isNaN(e)?e:et(t,r,_t("number",e)),er=(e,t,r)=>typeof e=="boolean"?e:et(t,r,_t("boolean",e)),yn=(e,t,r)=>{if(typeof e=="number"&&Ze(e))return e;for(let{message:n,path:o,...a}of Ae.safeParse(e).error.issues)et(t,r,a);return It},Co={present:!0,absent:!0,unknown:!0},Mo=Object.keys(Co),rc=Mo.map(e=>`'${e}'`).join(" | "),nc=(e,t,r)=>typeof e!="string"?et(t,r,{code:"invalid_type",expected:rc,received:xo(e)}):Object.hasOwn(Co,e)?e:et(t,r,{code:"invalid_enum_value",received:e,options:[...Mo]}),Po=Bt({name:le,affiliation:le}),Lo=Bt({name:le,text:le,color:le}),ko=Bt({id:yn,name:le,color:le}),No=Bt({id:yn,userId:le,userName:le,content:le,createdAt:le,isMine:er}),oc=Bt({id:_o,fileName:_o,fileType:Io,fileSize:tc,createdAt:Io,state:nc,hasThumbnail:er}),ac=Bt({reportHubId:yn,date:le,createdAt:le,author:le,userId:le,sourceType:le,employeeName:le,updatedBy:le,updatedAt:le,category:le,creationCategory:le,visitTimeFrom:le,visitTimeTo:le,customerName:le,interviewers:Zt(Xt(Po)),subject:le,content:le,externalComments:Zt(Xt(Lo)),isRead:er,isStarred:er,isDraft:er,labels:Zt(Xt(ko)),postedComments:Zt(Xt(No)),attachments:Zt(Xt(oc))}),tr=(e,t)=>{let r={path:[],issues:[]},n=e(t,r);return n===It?{ok:!1,issues:r.issues}:{ok:!0,value:n}},vo=e=>tr(ac,e),Oo=e=>tr(Po,e),Fo=e=>tr(Lo,e),Ho=e=>tr(ko,e),Bo=e=>tr(No,e);var Uo=15e3,$o="lastEventId",ic=/^\d{1,15}-\d{1,15}$/,Vo=e=>ic.test(e),rr=e=>pe.z.unknown().transform((t,r)=>{let n=e(t);if(n.ok)return n.value;for(let o of n.issues)r.addIssue({...o,fatal:!0});return pe.z.NEVER}),Sm=rr(Oo),gm=rr(Fo),bm=rr(Ho),sc=rr(Bo),hn=rr(vo),xt=pe.z.string().regex(Dr),lc=pe.z.object({type:pe.z.literal("connected")}),Tr=pe.z.object({type:pe.z.literal("status-update"),reportHubId:Ae,statusType:pe.z.enum(["star","read"]),value:pe.z.boolean(),clientTempId:xt,recipientRawUserId:Ae.optional()}),fn=pe.z.string(),Rn=pe.z.object({type:pe.z.literal("comment-add"),reportHubId:Ae,comment:sc,clientTempId:xt,recipientRawUserId:Ae.optional(),sourceType:fn}),Sn=pe.z.object({type:pe.z.literal("comment-delete"),reportHubId:Ae,commentId:Ae,clientTempId:xt,recipientRawUserId:Ae.optional(),sourceType:fn}),gn=pe.z.object({type:pe.z.literal("report-create"),reportHubId:Ae,report:hn,clientTempId:xt,recipientRawUserId:Ae.optional()}),bn=pe.z.object({type:pe.z.literal("report-update"),reportHubId:Ae,report:hn,clientTempId:xt,recipientRawUserId:Ae.optional()}),Dn=pe.z.object({type:pe.z.literal("report-publish"),reportHubId:Ae,report:hn,clientTempId:xt,recipientRawUserId:Ae.optional()}),Tn=pe.z.object({type:pe.z.literal("report-delete"),reportHubId:Ae,clientTempId:xt,sourceType:fn}),Yo=pe.z.discriminatedUnion("type",[lc,Tr,Rn,Sn,gn,bn,Dn,Tn]);var qo="ids-columns";var cc=/^[0-9a-f]{1,16}$/,jo=e=>Ze(e.reportHubId)&&(e.businessDate===null||br(e.businessDate)),Wo=e=>typeof e=="string"&&cc.test(e),Em=Object.freeze({kind:"absent"}),wm=Object.freeze({kind:"value",value:null});var Ct=(e,t,r)=>{let n=[],o=[],a=[],i=[],l=[],s=new Map;for(let c=t;c<r;c++){let{reportHubId:d,businessDate:u,sourceType:R}=e[c];n.push(d),o.length>0&&o[o.length-1]===u?a[a.length-1]+=1:(o.push(u),a.push(1));let m=R===void 0?null:R,p=s.get(m);p===void 0&&(p=i.length,i.push(m),s.set(m,p)),l.push(p)}return{ids:n,dates:o,counts:a,sourceTypes:i,sources:l}},Ar=e=>{let t=2166136261,r=-624069552;for(let n of e){let o=n.reportHubId;t^=o&255,t=Math.imul(t,16777619),t^=o>>>8&255,t=Math.imul(t,16777619),t^=o>>>16&255,t=Math.imul(t,16777619),t^=o>>>24&255,t=Math.imul(t,16777619),r^=o>>>24&255,r=Math.imul(r,16777619),r^=o>>>16&255,r=Math.imul(r,16777619),r^=o>>>8&255,r=Math.imul(r,16777619),r^=o&255,r=Math.imul(r,16777619);let a=n.businessDate;if(a===null)t^=1,t=Math.imul(t,16777619),r^=1,r=Math.imul(r,16777619);else for(let i=0;i<a.length;i++){let l=a.charCodeAt(i);t^=l&255,t=Math.imul(t,16777619),r^=l&255,r=Math.imul(r,16777619)}}return t^=e.length,t=Math.imul(t,16777619),r^=e.length,r=Math.imul(r,16777619),((t>>>0).toString(16).padStart(8,"0")+(r>>>0).toString(16).padStart(8,"0")).replace(/^0+(?=.)/,"")},zo=(e,t,r,n)=>e!==r?e===null?1:r===null||e>r?-1:1:n-t,uc=(e,t,r,n)=>zo(e,t,r,n)<0,An=(e,t)=>zo(e.businessDate,e.reportHubId,t.businessDate,t.reportHubId),Go=e=>{for(let t=1;t<e.length;t++)if(!uc(e[t-1].businessDate,e[t-1].reportHubId,e[t].businessDate,e[t].reportHubId))return!1;return!0},Ko=(e,t)=>{let r=e.findIndex(n=>An({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var ie=Object.freeze({businessDate:"business-date",idsStream:qo,report:"report",search:"search",reports:"reports",searchMarks:"search-marks",searchFacets:"search-facets",action:"action"}),Se=Object.freeze({businessDate:"businessDate",reportHubId:"reportHubId",searchQuery:"q",searchCombine:"combine",searchAuthor:"author",searchSourceType:"sourceType",searchCustomer:"customer",reportIds:"ids",forceRefresh:"forceRefresh",cursorReportHubId:"cursor_report_hub_id",cursorBusinessDate:"cursor_business_date",cursorSnapshot:"cursor_snapshot"});var Jo=(e,t,r=console)=>{let n=o=>typeof o=="string"?[`${t} ${o}`]:[t,o];return{debug:(o,...a)=>{e<=0&&r.debug(...n(o),...a)},info:(o,...a)=>{e<=1&&r.info(...n(o),...a)},warn:(o,...a)=>{e<=2&&r.warn(...n(o),...a)},error:(o,...a)=>{e<=3&&r.error(...n(o),...a)}}},Cm=Object.freeze(["API","Action","Attachment","ExternalSource","Isolation","Reads","Refresh","Search","SSE","SseReader","Server","Service","Streams","Visibility","ActionProvider","DetailLoader","IdsStream","SseConnection"]),Qo=e=>`[DailyReport${e}]`,ge=(e,t,r)=>e===void 0?Jo(t,Qo(r)):Jo(0,Qo(r),e);var dc="legacy-",En=e=>`${dc}${e}`;var pc=/^[1-9][0-9]*$/,mc=/^(?:0|[1-9][0-9]*)$/,We=e=>{if(e===null||!pc.test(e))return null;let t=Number(e);return Ze(t)?t:null},wn=e=>{if(e===null||!mc.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},In=e=>e==="true"?!0:e==="false"?!1:null,nr=e=>e===null?!1:In(e);var Xo=Object.freeze(["subject","content","author","employeeName","updatedBy","category","creationCategory","customerName"]),st=Object.freeze({field:e=>e,interviewer:(e,t)=>`interviewer:${e}:${t}`,attachment:e=>`attachment:${e}`,comment:(e,t)=>`comment:${e}:${t}`});var yc=16777619,_n=2166136261,xn=(e,t,r,n)=>{let o=e;for(let a=r;a<n;a++)o^=t.charCodeAt(a),o=Math.imul(o,yc);return o>>>0},Zo=e=>xn(_n,e,0,e.length),hc=String.fromCodePoint(3),fc=String.fromCodePoint(2),Rc=String.fromCodePoint(1),Er=e=>Zo(e.map(t=>t.map(r=>r.map(n=>`${n.tier}${n.text}`).join(hc)).join(fc)).join(Rc));var ea=e=>e==="intersection"||e==="union",we=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),Cn=2,wr=2,Mt=Object.freeze({word:0,reading:1});var Mn=(e,t)=>({ids:e.map(r=>r.reportHubId),businessDates:e.map(r=>r.businessDate),sourceTypes:e.map(r=>r.sourceType),words:t});var vm=2*(1+Cn);var Sc=require("zod/v3");var $e=Object.freeze({intent:"intent",clientTempId:"clientTempId",businessDate:"businessDate",operationTimestamp:"operationTimestamp",reportHubId:"reportHubId",title:"title",content:"content",isStarred:"isStarred",isRead:"isRead",commentId:"commentId"});var Ir=Math.max(1,Math.floor(10.556701030927835));var ze=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var Ve=e=>{let{windowMs:t,tallies:r,writeSuppressed:n}=e,o=new Map,a=i=>{let l={since:new Date().toISOString(),count:0,tallies:Object.fromEntries(r.map(c=>[c,0]))};o.set(i,l),ze(()=>{o.delete(i),l.count>0&&n(i,l)},t)};return{record:(i,l,s)=>{let c=o.get(i);if(c!==void 0){c.count+=1,c.tallies[l]+=1;return}s(),a(i)}}};var lt=Object.freeze({maxValuesPerFacet:16,maxValueLength:200,maxTotalValueLength:300});var Vm=Object.freeze({authors:Object.freeze([]),sourceTypes:Object.freeze([]),customers:Object.freeze([])}),gc=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Pn=e=>{let t=e.trim();return t.length===0?null:t.replace(gc,"\uFFFD")},bc=e=>{let t=Pn(e);return t===null?"filter-blank-value":t!==e?"filter-value-not-canonical":e.length>lt.maxValueLength?"filter-value-too-long":null},Dc=e=>{if(e.length>lt.maxValuesPerFacet)return"filter-too-many-values";let t=new Set;for(let r of e){let n=bc(r);if(n!==null)return n;if(t.has(r))return"filter-duplicate-value";t.add(r)}return null},Tc=e=>{let t=0;for(let r of e.authors)t+=r.length;for(let r of e.customers)t+=r.length;return t},ta=e=>{for(let t of[e.authors,e.sourceTypes,e.customers]){let r=Dc(t);if(r!==null)return r}return Tc(e)>lt.maxTotalValueLength?"filters-too-long":null};var ra=e=>e.trim().length===0;var _r=e=>e!==null&&Dr.test(e)?e:null,Ln=e=>ea(e)?e:null,kn=e=>{if(e===null)return null;let t=e.split(",");if(t.length>we.maxDetailIds)return null;let r=[];for(let n of t){let o=We(n);if(o===null||r.includes(o))return null;r.push(o)}return r},na=e=>{let[t,...r]=e;return t===void 0?null:[t,...r]},oa=(e,t)=>{let r={authors:e.getAll(Se.searchAuthor),sourceTypes:e.getAll(Se.searchSourceType),customers:e.getAll(Se.searchCustomer)},n=ta(r);if(n!==null)return{ok:!1,reason:n};let o=new Set(t.map(i=>i.toLowerCase())),a=new Set;for(let i of r.sourceTypes){let l=i.toLowerCase();if(!o.has(l))return{ok:!1,reason:"filter-unknown-source-type"};if(a.has(l))return{ok:!1,reason:"filter-duplicate-value"};a.add(l)}return{ok:!0,filters:{sourceTypes:a.size===0?null:a,authors:na(r.authors),customers:na(r.customers)}}},aa=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var sa=Object.freeze({status:400,error:"Invalid form"}),la=e=>({status:413,error:"Form too large",measuredBy:e}),Ac=(e,t,r)=>{let n=0;return e.pipeThrough(new TransformStream({transform(o,a){if(n+=o.byteLength,n>t){r(),a.error(new Error(`action form body exceeds ${t} bytes`));return}a.enqueue(o)}}))},Ec=async e=>{let t=wn(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:la("declared")};let r=!1,n=e.body===null?null:Ac(e.body,1048576,()=>{r=!0}),o=new Headers,a=e.headers.get("Content-Type");a!==null&&o.set("Content-Type",a);let i;try{i=await new Response(n,{headers:o}).formData()}catch{return{refusal:r?la("counted"):sa}}let l=aa(i);return l===null?{refusal:sa}:{fields:l}},ca=(e,t)=>(r,n)=>{let o=r.get(t);if(o===null)return{error:`${t} required`};let a=In(o);return a===null?{error:`Invalid ${t}`}:{command:{...n,intent:e,value:a}}},da=Object.freeze({update:(e,t,r)=>{let n=e.get($e.title),o=e.get($e.content);if(n!==null&&n.length>r.titleMaxLength)return{error:"Invalid title"};let a={};return n!==null&&(a.title=n),o!==null&&(a.content=o),{command:{...t,intent:"update",changes:a}}},publish:(e,t)=>({command:{...t,intent:"publish"}}),delete:(e,t)=>({command:{...t,intent:"delete"}}),toggleStar:ca("toggleStar",$e.isStarred),toggleRead:ca("toggleRead",$e.isRead),addComment:(e,t)=>{let r=e.get($e.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=We(e.get($e.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),wc=e=>Object.hasOwn(da,e),Ic=(e,t)=>{let r=e.get($e.intent),n=e.get($e.businessDate),o=n===null?null:Ht(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get($e.operationTimestamp),i=wn(a);if(a!==null&&i===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get($e.clientTempId);if(!l)return{error:"clientTempId required"};let s=_r(l);if(s===null)return{error:"Invalid clientTempId"};if(r==="create")return o===null?{error:"businessDate required"}:{command:{intent:r,clientTempId:s,businessDate:o,operationTimestamp:i}};let c=We(e.get($e.reportHubId));return c===null?{error:"Invalid reportHubId"}:r===null||!wc(r)?{error:"Invalid intent"}:da[r](e,{clientTempId:s,businessDate:o,operationTimestamp:i,reportHubId:c},t)},pa=async(e,t)=>{let r=await Ec(e);if("refusal"in r)return r;let n=Ic(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},_c=6e4,xc="form_too_large",ua=["declared","counted"],ma=e=>{let t=Ve({windowMs:_c,tallies:ua,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${ua.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(xc,r,n)}};var Pt=Object.freeze({[ie.businessDate]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[ie.idsStream]:{body:"stream",admission:["refresh-bucket","stream-slots","cache","miss-gate"]},[ie.report]:{body:"json",cache:"etag",admission:["refresh-bucket","cache","miss-gate"]},[ie.search]:{body:"json",cache:"etag",admission:["search-limiter"]},[ie.reports]:{body:"json",cache:"etag",admission:["search-limiter"]},[ie.searchMarks]:{body:"json",cache:"no-store",admission:["search-limiter"]},[ie.searchFacets]:{body:"json",cache:"etag",admission:["search-limiter"]}}),ya=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),Nn=e=>e!==void 0&&Object.hasOwn(Pt,e);var vn=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),ha=e=>Object.hasOwn(vn,e);var Cc="download",Mc="thumbnail",Pc="1";var On=e=>{let t=e.getAll(Mc),r=e.getAll(Cc);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&ha(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===Pc?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};var fa=require("crypto"),Fn=e=>`"${(0,fa.createHash)("sha256").update(e).digest("hex")}"`,Ra=e=>Fn(JSON.stringify(e));var tt=Object.freeze({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'"}),Hn=(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},Sa=(e,t,r,n=200)=>{let o=JSON.stringify(r),a=Fn(o),i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate",ETag:a,...tt});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&Hn(e.headers.get("If-None-Match"),a)?new Response(null,{status:304,headers:i}):new Response(o,{status:n,headers:i})},Bn=(e,t,r)=>{let n=new Headers({...t===null?{}:{"Content-Type":"application/json"},"Cache-Control":"no-store",...tt});return e&&n.append("Set-Cookie",e),new Response(t===null?null:JSON.stringify(t),{status:r,headers:n})},Un=e=>(t,r,n,o)=>{if(o!==200)return Bn(r,n,o);if(e===null||n===null)throw new Error(`[daily-report] API route: a 200 JSON answer needs an answer of a JSON 200 and a body; got ${e===null?"a responder without one":"an answer"} and ${n===null?"no body":"a body"}`);return e(t,r,n)},Lc=5e3/1e3,kc=new Map([[503,Lc]]),He=e=>{let t=kc.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var Vn="Cross-site request rejected",Nc="Not Found",vc=new Set(["same-origin","none"]),Oc=new Set(["GET","HEAD","OPTIONS"]),ga=["api","action","sse","attachment"],ba=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...tt}}),Fc=()=>ba(403,Vn),xr=()=>ba(404,Nc),or=Object.freeze({navigable:()=>!1,frameworkDataRefusal:()=>null,crossSiteRejection:Fc}),Da=e=>new URL(e.url).pathname.endsWith(".data"),Hc=e=>{let t=e.headers.get("Origin");return t===null?!0:URL.canParse(t)&&new URL(t).host===new URL(e.url).host},Ta=(e,t)=>{let r=e.headers.get("Sec-Fetch-Site");return r===null?!(Oc.has(e.method)||Hc(e)):vc.has(r)?!1:!(e.method==="GET"&&e.headers.get("Sec-Fetch-Mode")==="navigate"&&e.headers.get("Sec-Fetch-Dest")==="document"&&t.navigable(e))},Bc=6e4,Uc="refusals",$c=32,Vc=/^[a-z-]+$/,$n=e=>{if(e===null)return"-";let t=e.slice(0,$c);return Vc.test(t)&&t===e?e:JSON.stringify(t)},Aa=e=>{let t=Ve({windowMs:Bc,tallies:ga,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${ga.map(i=>`${i}:${a[i]}`).join(",")}`)}});return(r,n)=>{let o=()=>{let{headers:a}=n;e.warn(`cross_site_rejected route=${r} site=${$n(a.get("Sec-Fetch-Site"))} mode=${$n(a.get("Sec-Fetch-Mode"))} dest=${$n(a.get("Sec-Fetch-Dest"))} method=${n.method}`)};t.record(Uc,r,o)}};var Ea=(e,t)=>(r,n)=>{let o=n?"markAttachmentPresent":"markAttachmentMissing";e[o](r).catch(a=>{t.error(`${o} failed attachment=${r} message=${a instanceof Error?a.message:"unknown"}`)})};var Yc="same-origin",qc="SAMEORIGIN",Ut=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":Yc,"X-Frame-Options":qc}),Cr=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...Ut});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},wa=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),jc=/^[\x20-\x7E]+$/,Wc=/^[\w.+-]+\/[\w.+-]+/,Yn=e=>e&&jc.test(e)&&Wc.test(e)?e:null,zc=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Ia=e=>encodeURIComponent(e.replace(zc,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),_a=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),Mr={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},xa={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},Pr=e=>typeof e=="string"&&Object.hasOwn(xa,e),Lr=e=>xa[e],ct="Attachment request failed";var rt=e=>{let t=de("limit",e.limit,1),r=de("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:de("queue.max",e.queue.max,0),maxPerOwner:de("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:de("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],i=new Map,l=new Map,s=(y,S)=>y.get(S)??0,c=(y,S,_)=>{let D=s(y,S)+_;D<=0?y.delete(S):y.set(S,D)},d=y=>s(l,y)<r,u=y=>o<t&&d(y),R=y=>(o+=1,c(l,y,1),f(y)),m=()=>{let y=-1,S=r;for(let[_,D]of a.entries()){let h=s(l,D.owner);if(h<S&&(y=_,S=h,h===0))break}return y},p=()=>{for(;o<t;){let y=m();if(y<0)return;let[S]=a.splice(y,1);c(i,S.owner,-1),S.grant(R(S.owner))}},f=y=>{let S=!1;return()=>{S||(S=!0,o-=1,c(l,y,-1),p())}};return{canAcquire:u,acquire:(y,S)=>{if(S.aborted)return Promise.resolve(null);if(u(y))return Promise.resolve(R(y));if(n===null||a.length>=n.max||s(i,y)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:_}=n,D=h=>{let g=()=>{let j=a.indexOf(M);j<0||(a.splice(j,1),c(i,y,-1),x(),h(null))},P=ze(g,_),x=()=>{clearTimeout(P),S.removeEventListener("abort",g)},M={owner:y,grant:j=>{x(),h(j)}};a.push(M),c(i,y,1),S.addEventListener("abort",g,{once:!0})};return new Promise(D)}}};var Gc=1024,qn="Too many requests",Kc=(e,t)=>{de("limitPerWindow",e,1),de("windowMs",t,1);let r=new Map,n=(a,i)=>{i<=a.lastRefillMs||(a.tokens=Math.min(e,a.tokens+(i-a.lastRefillMs)*e/t),a.lastRefillMs=i)},o=(a,i)=>{let l=r.get(a);l&&r.delete(a);let s=l??{tokens:e,lastRefillMs:i};n(s,i),r.set(a,s);for(let c of r.keys()){if(r.size<=Gc)break;r.delete(c)}return s};return{consume:(a,i)=>{let l=o(a,i);return l.tokens<1?!1:(l.tokens-=1,!0)},refund:(a,i,l)=>{let s=r.get(a);s&&(n(s,i),s.tokens=Math.min(e,s.tokens+l))}}},ut=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(de("windowMs",r,1e3)%1e3!==0)throw X("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=Kc(e.limitPerWindow,r),i=Object.freeze({status:429,message:qn,headers:Object.freeze({"Retry-After":String(r/1e3)})}),l=Ve({windowMs:r,tallies:[t],writeSuppressed:(s,{count:c,since:d})=>{n.warn(`${t}_suppressed count=${c} since=${d} ${o(s)}`)}});return{spend:(s,c)=>a.consume(s,se())?null:(l.record(s,t,()=>n.warn(`429 ${c} reason=${t}`)),i),refund:(s,c)=>{a.refund(s,se(),c)}}};var Qc=256*1024,Ca=6e4,Xc=e=>Math.ceil(e/2),Zc=new Uint8Array(new ArrayBuffer(0)),eu=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=Zc,t()},i=l=>{clearTimeout(o),o=ze(()=>{l.error(new Error(`attachment body idle for ${Ca} ms`)),a()},Ca)};return new ReadableStream({start(l){i(l)},pull(l){let s=Math.min(n+Qc,r.byteLength);if(s>n&&l.enqueue(r.slice(n,s)),n=s,n>=r.byteLength){l.close(),a();return}i(l)},cancel(){a()}},{highWaterMark:0})},Ma=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=ut({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:s=>`viewer=${s}`}),l=rt({limit:e.concurrency,maxHeldPerOwner:Xc(e.concurrency),queue:null});return async s=>{let{request:c,delivery:d,attachmentId:u,internalUserId:R,readAttachment:m,cookie:p,fail:f}=s,y=e.maxBytes,S=i.spend(R,`attachment=${u} viewer=${R}`);if(S)return f(S.status,S.message,S.headers);let _=await n(c),D=await t.getAttachmentForUser(_,u,R);if(!D)return o.warn(`404 attachment=${u} viewer=${R} reason=not_visible`),f(404,"Attachment not found");if(D.fileSize!=null&&D.fileSize>y)return o.warn(`413 attachment=${u} viewer=${R} reason=db_size`),f(413,"Attachment too large");let h=Yn(D.fileType),g=`filename="${_a(D.fileName)}"; filename*=UTF-8''${Ia(D.fileName)}`,P=await l.acquire(R,c.signal);if(!P)return c.signal.aborted?(o.info(`503 attachment=${u} viewer=${R} reason=aborted`),f(503,"Attachment request aborted")):(o.warn(`503 attachment=${u} viewer=${R} reason=concurrency`),f(503,"Too many concurrent downloads",He(503)));let x=!1;try{let M=await m(D.filePath,{maxBytes:y,head:c.method==="HEAD",principal:r(R),signal:c.signal});if(c.signal.aborted)return o.info(`503 attachment=${u} viewer=${R} reason=aborted`),f(503,"Attachment request aborted");if(!M.ok){if(!Pr(M.reason))return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=failure_reason`),f(500,ct);let H=Lr(M.reason);return M.reason==="not_found"&&a(u,!1),o.warn(`${H} attachment=${u} viewer=${R} reason=${M.reason} code=${M.code??"-"}`),f(H,Mr[H],He(H))}if(M.bytes.byteLength>y)return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=over_max_bytes`),f(500,ct);let j=c.method==="HEAD";if(j&&M.size!==void 0&&M.size>y)return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=over_max_bytes`),f(500,ct);if(!j&&M.size!==void 0&&M.size!==M.bytes.byteLength)return o.error(`500 attachment=${u} viewer=${R} reason=port_contract code=size_mismatch`),f(500,ct);let k=h??Yn(M.contentType),v=k!==null&&wa.has(k),b=v?k:"application/octet-stream",N=v&&d.kind!=="download"?"inline":"attachment",$=j?M.size:M.bytes.byteLength,F=new Headers({"Content-Type":b,"Content-Disposition":`${N}; ${g}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...Ut});return $!==void 0&&F.set("Content-Length",String($)),p&&F.append("Set-Cookie",p),a(u,!0),o.info(`200 attachment=${u} viewer=${R} type=${b} disposition=${N} bytes=${$??"-"}`),j?new Response(null,{status:200,headers:F}):(x=!0,new Response(eu(M.bytes,P),{status:200,headers:F}))}finally{x||P()}}};var Be=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),Cy=Be.queueWaitMs+Be.readMs+Be.renderMs+Be.transferMarginMs;var ka=require("buffer"),Na=new Set([194,198,202,206]),tu=new Set([192,193,194,195]),va=216,ru=217,Oa=218,nu=4,ou=64,au=2,Pa=8,La=28,ft=12,jn=8,iu=20,Fa=ft+jn+10,su=2,dt=(e,t)=>e[t]<<8|e[t+1],$t=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];return n},nt=(e,t,r)=>{if(e.byteLength<t+r.length)return!1;for(let n=0;n<r.length;n+=1)if(e[t+n]!==r.charCodeAt(n))return!1;return!0},Ha=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,Ba=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),Ua=e=>(e.stepsLeft-=1,e.stepsLeft>=0),$a=e=>e[0]===255&&e[1]===va,Va=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!Ua(r))return null;n+=1}while(n<e.byteLength&&e[n]===255);if(n>=e.byteLength)return null;let o=e[n];if(n+=1,o===ru)return"eoi";if(o===0||o===va)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=dt(e,n),i=n+a;return a<2||i>e.byteLength?null:(r.marker=o,r.body=n+2,r.length=a,r.end=i,"segment")}},lu=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!Ua(r))return null;if(a+1>=n)return n;let i=e[a+1];if(i===255)a+=1;else if(i===0||i>=208&&i<=215){if(a+=2,a>=n||e[a]!==255)break}else return a}o=a}},Ya=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=dt(e,r+1),a=dt(e,r+3),i=e[r+5];if(a===0||o===0||i===0||n!==8+3*i)return null;let l=[];for(let s=0;s<i;s+=1){let c=e[r+7+3*s],d=c>>4,u=c&15;if(d<1||d>4||u<1||u>4)return null;l.push({id:e[r+6+3*s],horizontal:d,vertical:u})}return{marker:t,width:a,height:o,components:l}},qa=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>nu||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},ja=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:Na.has(e.marker)||t<e.components.length}),Wn=e=>{if(!$a(e))return null;let t=Ba(e.byteLength),r=null;for(let n=2;;){if(Va(e,n,t)!=="segment")return null;if(Ha(t.marker)){if(r!==null||(r=Ya(e,t),r===null))return null}else if(t.marker===Oa){if(r===null)return null;let o=qa(e,t);return o===null?null:ja(r,o.length)}n=t.end}},Wa=e=>{let t=Math.max(...e.components.map(n=>n.horizontal)),r=Math.max(...e.components.map(n=>n.vertical));return e.components.map(({horizontal:n,vertical:o})=>{let a=Math.ceil(e.width*n/(t*Pa)),i=Math.ceil(e.height*o/(r*Pa));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},za=e=>e.multiScan?Wa(e).reduce((r,n)=>r+n,0)*ou*au:0,cu=896,Ga=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!$a(e))return null;let n=ka.Buffer.from(e.buffer,e.byteOffset,e.byteLength),o=Ba(r),a=null,i=null,l=new Map,s=0,c=0,d=0;for(let u=2;;){let R=Va(e,u,o);if(R===null)return null;if(R==="eoi")return i===null?null:{header:i,blockVisits:c};if(u=o.end,Ha(o.marker)){if(a!==null||!tu.has(o.marker)||(a=Ya(e,o),a===null))return null;let m=Wa(a);l=new Map;for(let[p,f]of a.components.entries()){let y=l.get(f.id);l.set(f.id,y===void 0?m[p]:Math.max(y,m[p]))}s=a.components.length*(Na.has(a.marker)?cu:1)}else if(o.marker===Oa){if(a===null||d===s)return null;let m=qa(e,o);if(m===null)return null;for(let f of m){let y=l.get(f);if(y===void 0)return null;c+=y}if(d+=1,i===null&&(i=ja(a,m.length)),c>t||!i.multiScan)return{header:i,blockVisits:c};let p=lu(n,o.end,o);if(p===null)return null;u=p}}},Ka=e=>{if(e.byteLength<24||dt(e,8)!==0||dt(e,10)!==13||!nt(e,12,"IHDR"))return null;let t=dt(e,16)*65536+dt(e,18),r=dt(e,20)*65536+dt(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},uu=e=>{if(nt(e,ft,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=$t(e,26,2)&16383,r=$t(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(nt(e,ft,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=$t(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return nt(e,ft,"VP8X")?e.byteLength<Fa?null:{width:$t(e,24,3)+1,height:$t(e,27,3)+1}:null},Ja=e=>{if(Ka(e)===null||e.byteLength<=La)return null;switch(e[La]){case 0:return!1;case 1:return!0;default:return null}},Qa=(e,t)=>{if(nt(e,ft,"VP8 "))return"lossy";if(nt(e,ft,"VP8L"))return"lossless";if(!nt(e,ft,"VP8X")||e.byteLength<Fa)return null;if((e[iu]&su)!==0)return"animated";let r=!1,n=t;for(let o=ft;o+jn<=e.byteLength;){if(n-=1,n<0)return null;if(nt(e,o,"VP8L"))return"lossless";if(nt(e,o,"VP8 "))return r?"lossy-alpha":"lossy";nt(e,o,"ALPH")&&(r=!0);let a=$t(e,o+4,4);o+=jn+a+a%2}return null},Xa={png:Ka,jpeg:Wn,webp:uu};var kr=Object.freeze(["image/webp","image/jpeg","image/png"]),Nr=1024*1024;var du=new Set(["image/png","image/jpeg","image/gif","image/webp"]),pu={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},mu=new Set(kr),yu=e=>typeof e=="string"&&mu.has(e),hu=256,vr=(e,t)=>e.fileType===null||!du.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,fu=[137,80,78,71,13,10,26,10],Ru=[255,216,255],Su=[[71,73,70,56,55,97],[71,73,70,56,57,97]],gu=[82,73,70,70],bu=[87,69,66,80],ar=(e,t,r)=>{if(e.byteLength<r+t.length)return!1;for(let[n,o]of t.entries())if(e[r+n]!==o)return!1;return!0},zn=e=>{if(ar(e,fu,0))return"png";if(ar(e,Ru,0))return"jpeg";for(let t of Su)if(ar(e,t,0))return"gif";return ar(e,gu,0)&&ar(e,bu,8)?"webp":null},Za=e=>{let t=JSON.stringify([e.rendererId,e.box.maxWidth,e.box.maxHeight,e.attachmentId,e.filePath,e.fileType,e.fileSize]);return{key:t,etag:Ra([t])}},ei=(e,t)=>{if(!yu(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=pu[e.contentType];if(zn(e.bytes)!==r)return"signature";let n=Xa[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},ti=e=>{de("maxBytes",e.maxBytes,0),de("maxEntries",e.maxEntries,0);let t=new Map,r=0,n=o=>{let a=t.get(o);a&&(t.delete(o),r-=a.weight)};return{get:o=>{let a=t.get(o);if(a)return t.delete(o),t.set(o,a),a.entry},set:(o,a)=>{n(o);let i=(a.kind==="thumbnail"?a.bytes.byteLength:0)+hu;if(i>e.maxBytes||e.maxEntries===0)return;let l=a.kind==="thumbnail"?{kind:"thumbnail",bytes:a.bytes.slice(),contentType:a.contentType}:a;t.set(o,{entry:l,weight:i}),r+=i;for(let s of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(s)}}}};var Gn=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,i=se(),l=new AbortController,s=!1,c,d,u=()=>{a(se()-i)},R=h=>{c=ze(()=>{s=!0,h({timedOut:!0}),d=ze(u,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},m=new Promise(R),p=AbortSignal.any([r,l.signal]),f=h=>{h(n(p))},y=new Promise(f),S=h=>(clearTimeout(c),clearTimeout(d),s&&o(se()-i,h.kind==="error"?{error:h.error}:null),h),_=y.then(h=>S({kind:"value",value:h}),h=>S({kind:"error",error:h}));return{outcome:Promise.race([y.then(h=>({timedOut:!1,value:h})),m]),settled:_}};var Rt={404:"Attachment not found",500:ct,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},ri=(e,t)=>{if(typeof e!="object"||e===null)return{failure:{kind:"failure",status:500,reason:"port_contract",code:"result"}};let r=e;if(!r.ok)return r.reason==="unsupported"?{entry:{kind:"unrenderable",reason:"unsupported"}}:r.reason==="failed"?{failure:{kind:"failure",status:502,reason:"render_failed"}}:{failure:{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"}};let n=ei(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},Du=e=>{let t=new AbortController,r=()=>{t.abort()},n=ze(r,Be.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},ni=()=>{},Tu=(e,t)=>t.aborted?Promise.resolve():new Promise(r=>{let n=()=>{t.removeEventListener("abort",n),r()};t.addEventListener("abort",n,{once:!0}),e.then(n)}),oi=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:i}=e,l=new Map,s=(m,p)=>{let f=p.then(ni,ni);l.set(m,f);let y=()=>{l.get(m)===f&&l.delete(m)};f.then(y)},c=async(m,p)=>{let f=l.get(m.key);if(f===void 0)return t.acquire(m.owner,p);let y=Du(p);try{if(await Tu(f,y.signal),y.signal.aborted)return null;let S=r.get(m.key);return S!==void 0?{...S,identity:"verified"}:await t.acquire(m.owner,y.signal)}finally{y.end()}},d=(m,p)=>{if(m.fileSize===null)return p.kind==="exact"?"verified":"unrecorded";if(p.kind==="exact"?p.bytes===m.fileSize:m.fileSize>p.maxBytes)return"verified";let y=p.kind==="exact"?String(p.bytes):`>${p.maxBytes}`;return i.warn(`size_mismatch expected=${m.fileSize} got=${y} attachment=${m.attachmentId} viewer=${m.owner} variant=thumbnail`),"unverified"},u=(m,p)=>(f,y)=>{let S=y===null?"":` message=${y.error instanceof Error?y.error.message:"unknown"}`;i.warn(`${m}_overrun ms=${f} attachment=${p.attachmentId} viewer=${p.owner} variant=thumbnail${S}`)},R=(m,p)=>f=>{i.warn(`${m}_stuck ms=${f} attachment=${p.attachmentId} viewer=${p.owner} variant=thumbnail`)};return async(m,p)=>{let f=await c(m,p);if(f===null)return{kind:"failure",status:503,reason:p.aborted?"aborted":"queue"};if(typeof f!="function")return f;let y=f,S=null;try{if(p.aborted)return{kind:"failure",status:503,reason:"aborted"};let _=r.get(m.key);if(_!==void 0)return{..._,identity:"verified"};let D=Gn({budgetMs:Be.readMs,flightSignal:p,call:H=>m.readAttachment(m.filePath,{maxBytes:n,head:!1,principal:o(m.owner),signal:H}),onOverrun:u("read",m),onStuck:R("read",m)}),h=await D.outcome;if(h.timedOut)return S=D.settled,p.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(p.aborted)return{kind:"failure",status:503,reason:"aborted"};let g=h.value;if(!g.ok&&g.reason!=="too_large")return Pr(g.reason)?(g.reason==="not_found"&&a(m.attachmentId,!1),{kind:"failure",status:Lr(g.reason),reason:g.reason,code:g.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(g.ok&&g.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let P=d(m,g.ok?{kind:"exact",bytes:g.bytes.byteLength}:{kind:"over",maxBytes:n}),x=H=>{P==="verified"&&r.set(m.key,H)},M=H=>(x(H),{...H,identity:P});if(!g.ok)return M({kind:"unrenderable",reason:"too_large"});let j=zn(g.bytes);if(j===null)return M({kind:"unrenderable",reason:"signature"});let k=Gn({budgetMs:Be.renderMs,flightSignal:p,call:H=>m.renderer.render(g.bytes,{format:j,maxWidth:m.box.maxWidth,maxHeight:m.box.maxHeight,signal:H}),onOverrun:u("render",m),onStuck:R("render",m)}),v=H=>{if(H.kind==="error")return;let K=ri(H.value,m.box);"entry"in K&&x(K.entry)},b=null,N=()=>(b===null&&(b=k.settled.then(v),s(m.key,b)),b);p.addEventListener("abort",N,{once:!0});let $=await k.outcome.finally(()=>p.removeEventListener("abort",N));if($.timedOut||p.aborted)return S=N(),p.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let F=ri($.value,m.box);return"entry"in F?M(F.entry):F.failure}finally{S===null?y():S.then(y,y)}}};var ai=()=>{let e=new Map;return{join:(t,r,n)=>{let o=()=>{let s=new AbortController,c=()=>{e.get(t)?.controller===s&&e.delete(t)},u={promise:n(s.signal).finally(c),controller:s,waiters:0};return e.set(t,u),u},a=e.get(t)??o();a.waiters+=1;let i=()=>{a.waiters-=1,!(a.waiters>0)&&(a.controller.abort(),e.get(t)===a&&e.delete(t))};r.aborted?i():r.addEventListener("abort",i,{once:!0});let l=()=>{r.removeEventListener("abort",i)};return a.promise.finally(l)}}};var li=10,Au=1/li,ii=1-Au,Eu=1024,wu=64,Iu=8,si="private, no-cache",_u="no-store",xu=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),Cu=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},ci=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:s}=l,c=(h,g)=>ut({reason:h,limitPerWindow:g,windowMs:6e4,logger:o,windowFields:P=>`viewer=${P} variant=thumbnail`}),d=c("rate_limit",l.rateLimitPerMinute),u=c("revalidation_rate_limit",l.rateLimitPerMinute*li),R=rt({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:wu,maxPerOwner:Iu,maxWaitMs:Be.queueWaitMs}}),m=ti({maxBytes:l.cacheBytes,maxEntries:Eu}),p=ai(),f=oi({gate:R,cache:m,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),y=(h,g,P,x)=>{let M=`attachment=${h.attachmentId} viewer=${h.internalUserId} variant=thumbnail cache=${x}`;if(g.kind==="failure")return o[Cu(g)](`${g.status} ${M} reason=${g.reason} code=${g.code??"-"}`),h.fail(g.status,Rt[g.status],He(g.status));let j=xu[g.identity];if(g.kind==="unrenderable")return o.info(`404 ${M} reason=${g.reason}${j}`),h.fail(404,Rt[404]);let k=g.identity==="verified"?{"Cache-Control":si,ETag:P}:{"Cache-Control":_u},v=new Headers({"Content-Type":g.contentType,"Content-Length":String(g.bytes.byteLength),...k,"Content-Security-Policy":"default-src 'none'; sandbox",...Ut});return h.cookie&&v.append("Set-Cookie",h.cookie),o.info(`200 ${M} type=${g.contentType} bytes=${g.bytes.byteLength}${j}`),new Response(g.bytes,{status:200,headers:v})},S=(h,g)=>{let P=h.spend(g.internalUserId,`attachment=${g.attachmentId} viewer=${g.internalUserId} variant=thumbnail`);return P===null?null:g.fail(P.status,P.message,P.headers)},_=h=>S(d,h),D=(h,g)=>g?S(u,h):_(h);return async(h,g)=>{let{request:P,attachmentId:x,internalUserId:M,readAttachment:j,cookie:k,fail:v}=h,b=vn[g],N=P.headers.get("If-None-Match"),$=N!==null,F=D(h,$);if(F)return F;let H=await n(P),K=await t.getAttachmentForUser(H,x,M),W=K!==null&&vr(K,i)?Za({rendererId:s.id,box:b,attachmentId:x,filePath:K.filePath,fileType:K.fileType,fileSize:K.fileSize}):null;if(W&&Hn(N,W.etag)){let w=new Headers({"Cache-Control":si,ETag:W.etag,...Ut});return k&&w.append("Set-Cookie",k),o.info(`304 attachment=${x} viewer=${M} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:w})}if($){let w=_(h);if(w)return w}if(!K)return o.warn(`404 attachment=${x} viewer=${M} variant=thumbnail reason=not_visible`),v(404,Rt[404]);if(!W)return d.refund(M,ii),o.info(`404 attachment=${x} viewer=${M} variant=thumbnail reason=not_eligible`),v(404,Rt[404]);let{key:ae,etag:Te}=W,ke=m.get(ae);if(ke)return d.refund(M,ii),y(h,{...ke,identity:"verified"},Te,"hit");let Re=w=>f({key:ae,attachmentId:x,filePath:K.filePath,fileSize:K.fileSize,box:b,owner:M,readAttachment:j,renderer:s},w),J;try{J=await p.join(ae,P.signal,Re)}catch(w){return o.error(`500 attachment=${x} viewer=${M} variant=thumbnail cache=miss reason=port_exception message=${w instanceof Error?w.message:"unknown"}`),v(500,Rt[500])}return y(h,J,Te,"miss")}};var Mu='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',Pu=()=>Cr(403,Vn,{cookie:null}),ui=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=On(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>Cr(404,Mr[404],{cookie:null}),crossSiteRejection:Pu}),di=e=>{let{authenticate:t,service:r,encodeUserId:n,resolveViewerScope:o,logger:a}=e,i=r.attachmentDelivery,l={service:r,encodeUserId:n,resolveViewerScope:o,logger:a,recordObjectState:Ea(r,a)},s=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:Ma({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:ci({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:c,params:d})=>{let u=null,R=(m,p,f={})=>Cr(m,p,{cookie:u,extraHeaders:f});try{let{user:m,cookie:p}=await t(c,{failureRedirect:null});if(u=p??null,!m)return R(401,"Unauthorized");let f=On(new URL(c.url).searchParams);if(f.kind==="invalid")return R(400,"Invalid attachment request");if(f.kind==="thumbnail"&&c.method!=="GET")return R(405,"Method not allowed",{Allow:"GET"});if(c.method!=="GET"&&c.method!=="HEAD")return R(405,"Method not allowed",{Allow:"GET, HEAD"});if(s===null)return R(404,"Attachment not found");if(d.token===void 0)throw new Error(Mu);let y=s.idCodec.decode(d.token);if(y===null||!Ze(y))return R(400,"Invalid attachment token");let S=await r.getUserIdByExternalId(m.id);if(!S)return R(403,"Forbidden");let _={request:c,delivery:f,attachmentId:y,internalUserId:S,readAttachment:s.read,cookie:u,fail:R};return f.kind!=="thumbnail"?await s.serveOriginal(_):s.serveThumbnail===null?R(404,Rt[404]):await s.serveThumbnail(_,f.variant)}catch(m){if(m instanceof Response)throw m;return a.error(`500 attachment=? viewer=? reason=unexpected message=${m instanceof Error?m.message:"unknown"}`),R(500,ct)}}};var Lu=32*1024*1024,ku=60,Nu=4,vu=120,Ou=2,Fu=8*1024*1024,Or=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Hu=e=>{if(e===void 0)throw it("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!Or(e))throw X("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw it("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw X("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw X("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},Bu=e=>{if(e===void 0)return null;if(!Or(e))throw X("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:Hu(e.renderer),rateLimitPerMinute:Me("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,vu),concurrency:Me("attachments.thumbnails.concurrency",e.concurrency,1,Ou),cacheBytes:Me("attachments.thumbnails.cacheBytes",e.cacheBytes,0,Fu)})},pi=e=>{let t=e;if(t===void 0)return null;if(!Or(t))throw X("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw it("attachments.idCodec","injected when attachments is given");if(!Or(r)||typeof r.encode!="function"||typeof r.decode!="function")throw X("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw it("attachments.read","injected when attachments is given");if(typeof n!="function")throw X("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:Me("attachments.maxBytes",t.maxBytes,1,Lu),rateLimitPerMinute:Me("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,ku),concurrency:Me("attachments.concurrency",t.concurrency,1,Nu),thumbnails:Bu(t.thumbnails)})},Uu=Object.freeze([["attachmentIdCodec","attachments.idCodec"],["readAttachment","attachments.read"],["attachmentMaxBytes","attachments.maxBytes"],["attachmentRateLimitPerMinute","attachments.rateLimitPerMinute"],["attachmentConcurrency","attachments.concurrency"],["attachmentThumbnailRenderer","attachments.thumbnails.renderer"],["attachmentThumbnailRateLimitPerMinute","attachments.thumbnails.rateLimitPerMinute"],["attachmentThumbnailConcurrency","attachments.thumbnails.concurrency"],["attachmentThumbnailCacheBytes","attachments.thumbnails.cacheBytes"]]),Fr=e=>{for(let[t,r]of Uu)if(Object.hasOwn(e,t))throw it(r,`given in place of the flat key ${t}`)};var yi=8,$u=8*yi,Vu=128,Yu=2,hi=Yu*Vu,qu=4*hi,ju=6e4,Wu=6e4,zu="Too many reads",mi=Object.freeze(Object.keys(Pt).filter(e=>Pt[e].admission.includes("miss-gate"))),fi=e=>{let t=rt({limit:$u,maxHeldPerOwner:yi,queue:{max:qu,maxPerOwner:hi,maxWaitMs:ju}}),r=Ve({windowMs:Wu,tallies:mi,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`cache_miss_admission_suppressed count=${o} since=${a} viewer=${n} endpoints=${mi.map(l=>`${l}:${i[l]}`).join(",")}`)}});return{admissionFor:(n,o,a)=>({signal:a,acquire:async i=>{let l=await t.acquire(n,i);return l===null&&!i.aborted&&r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=cache_miss_admission`)),l}})}},Hr=(e,t,r)=>{let n=e(t,r,{error:{message:zu}},503);for(let[o,a]of Object.entries(He(503)))n.headers.set(o,a);return n};var Ri=e=>{let t=e.get(Se.cursorReportHubId),r=e.get(Se.cursorBusinessDate),n=e.get(Se.cursorSnapshot),o=Wo(n)?n:null,a=null;if(t!==null){let l=We(t);if(l===null)return{refused:"cursor"};let s={businessDate:r,reportHubId:l};if(!jo(s))return{refused:"cursor"};a=s}else if(r!==null)return{refused:"cursor"};let i=nr(e.get(Se.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var Br=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,Gu=2,Ku=16,Ju=Gu*Ku,Qu=6e4,Si=()=>{},Xu=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},gi=e=>{let t=rt({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:Ju,queue:null}),r=Ve({windowMs:Qu,tallies:["sse","ids-stream"],writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`streams_per_viewer_suppressed count=${o} since=${a} viewer=${n} routes=sse:${i.sse},ids-stream:${i["ids-stream"]}`)}});return{admit:async(n,o,a)=>{if(n===null)return Si;if(a.aborted){if(t.canAcquire(n))return Si}else{let i=await t.acquire(n,a);if(i!==null)return Xu(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var Ur=30,Ei=4e3,Zu="stream interrupted by server error",ed="Too many streams",td=15e3,wi=Symbol("ids-stream-heartbeat"),bi=()=>{},Di=e=>e.return(void 0).then(bi,bi),rd=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(wi),td)}),stop:()=>clearTimeout(e)}};async function*Ti(e,t,r,n){let o=t?Ko(e,t):0,a=!0;for(;;){let i=Math.min(o+(a?r:Ei),e.length),l=Ct(e,o,i),s=i>o?e[i-1]:void 0;o=i;let c=o>=e.length;if(yield{kind:"chunk",...l,nextCursor:c||s===void 0?null:{businessDate:s.businessDate,reportHubId:s.reportHubId},isLast:c,...a?{total:e.length}:{},...a?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...a&&n.restarted?{restarted:!0}:{}},a=!1,c)return}}var Ii=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform",...tt});return e&&t.append("Set-Cookie",e),t},Ai=(e,t,r,n,o)=>{let a=async(d,u)=>{o(),u&&await Di(t);try{d.close()}catch{}},i=new TextEncoder,l=!1,s=null,c=new ReadableStream({async pull(d){if(l||r.aborted){await a(d,!0);return}let u=rd();try{s===null&&(s=t.next());let R=await Promise.race([s,u.fired]);if(u.stop(),R===wi){if(l||r.aborted){await a(d,!0);return}d.enqueue(i.encode(`
2
+ `));return}s=null;let{value:m,done:p}=R;if(p){await a(d,!1);return}if(l||r.aborted){await a(d,!0);return}d.enqueue(i.encode(`${JSON.stringify(m)}
3
+ `))}catch(R){if(u.stop(),s=null,o(),l||r.aborted)return;R instanceof je||n.error(`ids-stream emission failed: ${R instanceof Error?R.message:String(R)}`);try{let m={kind:"error",error:Zu};d.enqueue(i.encode(`${JSON.stringify(m)}
4
+ `)),d.close()}catch{}}},cancel(){l=!0,o(),Di(t)}});return new Response(c,{status:200,headers:Ii(e)})},_i=e=>{let{service:t,logger:r,streamSlots:n,missGate:o,refuseForcedRead:a}=e,i=async(l,s,c,d,u,R,m)=>{let p=!1,f=null,y=null,S=new Promise((h,g)=>{f=h,y=g});S.catch(()=>{});let _=t.getDailyReportIdsByExternalId(c,s.id,{forceRefresh:l.forceRefresh,admission:m,onFetchStart:l.cursor?void 0:()=>{p=!0,t.readSseStreamAnchor().then(h=>t.getDailyReportIdsFirstPageByExternalId(c,s.id,Ur).then(g=>({items:g,streamAnchor:h}))).then(h=>f?.(h),h=>y?.(h))}});if(_.catch(()=>{}),l.cursor){let{items:h,streamAnchor:g,snapshot:P}=await _,x=l.snapshot!==null&&l.snapshot===P;return Ai(d,Ti(h,x?l.cursor:null,Ur,{snapshot:P,restarted:!x,streamAnchor:g}),u,r,R)}let D=(async function*(){let h=await Promise.race([_.then(x=>({kind:"full",source:x}),x=>({kind:"full-error",error:x})),S.then(x=>({kind:"page",page:x}),()=>({kind:"page-error"}))]),g=null,P=!1;if(h.kind==="full")g=h.source;else if(h.kind==="page"){let{items:x,streamAnchor:M}=h.page;if(x.length<Ur){yield{kind:"chunk",...Ct(x,0,x.length),nextCursor:null,isLast:!0,total:x.length,streamAnchor:M};return}yield{kind:"chunk",...Ct(x,0,x.length),nextCursor:null,isLast:!1,provisional:!0},P=!0}else if(h.kind==="full-error"&&p){let x=await S.catch(()=>null);x&&x.items.length>0&&(yield{kind:"chunk",...Ct(x.items,0,x.items.length),nextCursor:null,isLast:!1,provisional:!0})}g===null&&(g=await _),yield*Ti(g.items,null,P?Ei:Ur,{snapshot:g.snapshot,streamAnchor:g.streamAnchor})})();return Ai(d,D,u,r,R)};return async(l,s,c,d,u,R)=>{let m=Ri(l.searchParams);if("refused"in m)return R(c,s,{error:{message:m.refused==="cursor"?"Invalid cursor":"Invalid forceRefresh"}},400);let{query:p}=m;if(p.forceRefresh){let _=a(d,c,s,R);if(_!==null)return _}let f=Br(c),y=await t.getUserIdByExternalId(d.id),S=await n.admit(y,"ids-stream",f);if(S===null){let _=R(c,s,{error:{message:ed}},503);for(let[D,h]of Object.entries(He(503)))_.headers.set(D,h);return _}if(f.aborted)return new Response(null,{status:200,headers:Ii(s)});try{return await i(p,d,u,s,f,S,y===null?void 0:o.admissionFor(y,ie.idsStream,f))}catch(_){if(S(),_ instanceof je)return Hr(R,c,s);throw _}}};var sr=require("drizzle-orm");var nd="",od=64,ad=e=>e.toLowerCase(),id=e=>e.trim().toLowerCase();function xi(e){if(e==null)return null;if(!Array.isArray(e))return new Set;let t=new Set;for(let r of e){if(typeof r!="string")continue;let n=id(r);n.length>0&&t.add(n)}return t}function Ie(e,t){return e===null?!0:t==null?!1:e.has(ad(t))}function Le(e){return e!==null&&e.size===0}function lr(e,t){if(t!==null)return t.size===0?sr.sql`1 = 0`:(0,sr.inArray)(sr.sql`LOWER(${e})`,[...t])}var Vt,Yt,ir=class ir{constructor(t,r){cn(this,Vt);cn(this,Yt);un(this,Vt,t),un(this,Yt,r)}get visible(){return Jt(this,Vt)===null?null:new Set(Jt(this,Vt))}get commentable(){return Jt(this,Yt)===null?null:new Set(Jt(this,Yt))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=xi(r?t.read:t),o=r?t.comment:void 0;if(o===void 0)return new ir(n,n);let a=xi(o),i=new Set;for(let l of a??[])n.has(l)&&i.add(l);return new ir(n,i)}static unrestricted(t){return new ir(null,null)}};Vt=new WeakMap,Yt=new WeakMap;var Ue=ir;function cr(e){let t=Ci(e.visible),r=Ci(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function Ci(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(nd);if(t.length<=od)return`s:${t}`;let r=2166136261;for(let n=0;n<t.length;n++)r^=t.charCodeAt(n),r=Math.imul(r,16777619);return`sh:${(r>>>0).toString(16)}`}var Mi=(e,t,r,n)=>Ie(n.commentable,t)||e.authorUserId!==null&&e.authorUserId===r;var Wi=require("@aiquants/fuzzy-search");var Ni=require("crypto"),Kn=require("timers/promises"),ye=require("@aiquants/fuzzy-search/normalize");var Vr=`
5
+ `,Jn=4e3,sd=1,vi=new Set([8203,8288,65279,173]),ld=new RegExp(`[${String.fromCodePoint(...vi)}]`,"gu"),Oi=new RegExp(`\\r\\n|[\\n\\r${String.fromCodePoint(133,8232,8233)}]`,"gu"),Fi=/(\s+)/u,cd=/^\s+$/u,ud=new RegExp(Fi.source,"gu"),dd=/^(?:(?=\p{Lo})[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]|[A-Za-z0-9])$/u,pd=new Set([8205,1536,1537,1538,1539,1540,1541,1757,1807,2192,2193,2274,69821,69837,70082,70083,71999,72001,72250,72324,72325,72326,72327,72328,72329,73030,73474]),Yr=e=>e.replace(ld,"");var Qn=e=>(0,ye.normalizeText)(e,ye.DEFAULT_NORMALIZE_OPTIONS),$r=e=>Qn(Yr(e)),md=(0,ye.resolveNormalizeOptions)({...ye.DEFAULT_NORMALIZE_OPTIONS,convertRomaji:!0},"[daily-report] search reading options"),yd=3,hd=/^[-ー]+/u,fd=/[^\p{L}\p{M}]/gu,Rd=/ー{2,}/gu,Sd=/\p{Script=Latin}/u,Pi=/(?=\p{L})\p{Script=Latin}/u,gd=e=>(0,ye.clusterCountOf)(e.replace(hd,"").replace(fd,"").replace(Rd,"\u30FC")),bd=(e,t)=>{for(let r of t)if(!(0,ye.isAnswerTier)(r.tier)||r.splitTier!==null)throw new Error(`[daily-report] search readings: queryNeedles gave an unfinished needle for the word ${JSON.stringify(e)} (text ${JSON.stringify(r.text)}, tier ${r.tier}, splitTier ${r.splitTier})`)},Hi=e=>{if(!Pi.test(e))return[];let t=$r(e);if(!Pi.test(t))return[];let r=(0,ye.queryNeedles)(t,md,!1);bd(t,r);let n=[];for(let o of r){if(o.tier===Mt.word)continue;let a=$r(o.text);if(!(a.length===0||a.length>we.maxWordLength)&&!(a===t||Sd.test(a))&&!(gd(a)<yd||n.includes(a))&&(n.push(a),n.length===Cn))break}return n},Xn=(e,t)=>{let r=e.charCodeAt(t-1),n=e.charCodeAt(t);return r>=55296&&r<=56319&&n>=56320&&n<=57343},Bi=(e,t)=>{let r=e.codePointAt(t),n=t>=2&&Xn(e,t-1)?t-2:t-1;return dd.test(String.fromCodePoint(r))&&!pd.has(e.codePointAt(n))},Dd=(e,t,r)=>{let n=[],o=0,a=0;for(;e.length-a>r;){let i=a+r;for(;i>a&&!Bi(e,i);)i--;i===a&&(i=a+r,Xn(e,i)&&i--,o++),n.push({start:t+a,end:t+i}),a=i}return n.push({start:t+a,end:t+e.length}),{pieces:n,forcedCuts:o}},Zn=(e,t)=>{if(e.length<=t)return{chunks:[[{start:0,end:e.length}]],forcedCuts:0};let r=[],n=0,o=0,a=0,i=0,l=()=>{i>0&&r.push([{start:a,end:a+i}]),i=0};for(let s of e.split(Fi)){let c=o;if(o+=s.length,i+s.length<=t){i===0&&(a=c),i+=s.length;continue}if(l(),cd.test(s))continue;if(s.length<=t){a=c,i=s.length;continue}let d=Dd(s,c,t);n+=d.forcedCuts,r.push(d.pieces)}return l(),{chunks:r,forcedCuts:n}},eo=(e,t)=>{let r=Zn(e,t),n=[];for(let o of r.chunks){let a=o.map(i=>Qn(e.slice(i.start,i.end))).join("");a.length>0&&n.push(a)}return{text:n.join(" "),forcedCuts:r.forcedCuts}},Td=(e,t)=>{let r=0;for(let n of e.matchAll(Oi))t(e.slice(r,n.index),r),r=n.index+n[0].length;t(e.slice(r),r)},Ad=(e,t)=>{if(e.partialReadings!==null)throw new Error(`[daily-report] search marks: the mapped forms of the piece ${JSON.stringify(t)} carry partial readings`);return e.canonical},Ui=(e,t)=>{let r="",n=[],o=[];for(let a of t.chunks){let i="",l=[],s=[];for(let c of a){let d=e.slice(c.start,c.end),u=Ad((0,ye.toMappedFormsInto)(d,ye.DEFAULT_NORMALIZE_OPTIONS,new ye.InteriorPairs(0)),d),[R,m]=(0,ye.trimmedRange)(u.text);i+=u.text.slice(R,m);for(let p=R;p<m;p++)l.push(c.start+u.start[p]),s.push(c.start+u.end[p])}if(i.length!==0){r.length>0&&(r+=" ",n.push(o[o.length-1]),o.push(l[0])),r+=i;for(let c=0;c<l.length;c++)n.push(l[c]),o.push(s[c])}}return{text:r,start:n,end:o}},qr=(e,t=Jn)=>{let r=[],n=0;return Td(Yr(e),o=>{let a=eo(o,t);n+=a.forcedCuts,a.text.length>0&&r.push(a.text)}),{text:r.join(Vr),forcedCuts:n}},$i=e=>e.filter(t=>t.length>0).join(Vr),to=(e,t)=>{let r=null;return{advance:n=>{if(r!==null)return 0;e.units=de("search text steps: units",n,1);let o=t.next();return o.done===!0&&(r={result:o.value}),n-e.units},done:()=>r!==null,result:()=>{if(r===null)throw new Error("[daily-report] search text: the steps are not done (advance until done() is true)");return r.result}}},Li=4096;function*Ed(e,t){let r=[],n=new Uint32Array(e.length),o=0,a=!1;for(let i=0;i<e.length;){for(;t.units===0;)yield;let l=Math.min(e.length,i+t.units);t.units-=l-i;let s=o,c=new Uint16Array(l-i);for(let d=i;d<l;d++){let u=e.charCodeAt(d);vi.has(u)||(c[o-s]=u,n[o++]=d)}if(o-s===l-i)a&&r.push(e.slice(i,l));else{a||r.push(e.slice(0,i)),a=!0;for(let d=s;d<o;d+=Li)r.push(Reflect.apply(String.fromCharCode,null,c.subarray(d-s,Math.min(o,d+Li)-s)))}i=l}return a?{text:r.join(""),rawIndex:n.subarray(0,o)}:{text:e,rawIndex:null}}var Vi=e=>{let t={units:0};return to(t,Ed(e,t))};function*wd(e,t,r){let n=0;for(let o=0;o<e.length;){for(;r.units===0;)yield;let a=Math.min(e.length,o+r.units);r.units-=a-o;let i=a;for(let l of e.slice(o,Math.min(e.length,a+1)).matchAll(Oi)){let s=o+l.index;if(s>=a)break;t(e.slice(n,s),n),n=s+l[0].length,i=Math.max(i,n)}o=i}t(e.slice(n),n)}var Yi=(e,t)=>{let r={units:0};return to(r,wd(e,t,r))};function*ki(e,t,r,n,o){let a=[],i=0,l=t;for(;r-l>n;){let s=l+n;for(;s>l;s--){for(;o.units===0;)yield;if(o.units-=1,Bi(e,s))break}s===l&&(s=l+n,Xn(e,s)&&s--,i++),a.push({start:l,end:s}),l=s}return a.push({start:l,end:r}),{pieces:a,forcedCuts:i}}function*Id(e,t,r){if(e.length<=t)return{chunks:[[{start:0,end:e.length}]],forcedCuts:0};let n=[],o=0,a=0,i=0,l=0,s=0,c=!1,d=(m,p,f)=>{let y=p-m;return i+y<=t?(i===0&&(a=m),i+=y,!1):(i>0&&n.push([{start:a,end:a+i}]),i=0,f?!1:y<=t?(a=m,i=y,!1):!0)},u=m=>{c&&(d(l,s,!0),l=s),c=!1,s=m},R=m=>{let p=-1;return!c&&s>l&&(d(l,s,!1)&&(p=l),l=s),c=!0,s=m,p};for(let m=0;m<e.length;){for(;r.units===0;)yield;let p=Math.min(e.length,m+r.units);r.units-=p-m;let f=m;for(let y of e.slice(m,p).matchAll(ud)){let S=m+y.index;S>f&&u(S),f=S+y[0].length;let _=R(f);if(_>=0){let D=yield*ki(e,_,S,t,r);o+=D.forcedCuts,n.push(D.pieces)}}p>f&&u(p),m=p}if(d(l,s,c)){let m=yield*ki(e,l,s,t,r);o+=m.forcedCuts,n.push(m.pieces)}return i>0&&n.push([{start:a,end:a+i}]),{chunks:n,forcedCuts:o}}var qi=(e,t)=>{let r={units:0};return to(r,Id(e,t,r))},_d=e=>{let t=[];for(let r=0;r<=65535;r++)r>=55296&&r<=57343||t.push(e+String.fromCharCode(r));return t.join(`
6
+ `)},xd=[`\u3067\u3093${String.fromCodePoint(8203)}\u3077\u3093 \uFF83\uFF9E\uFF9D\uFF8C\uFF9F\uFF9D\r
7
+ \u30C7\u30F3\u30D7\u30F3`,"\u30DD\u30C6\u30C8-25kg \u30A2--1 \u30FC\u30FC\u30E1\u30F3 \u4F50\u3005\u6728","\u6F22\u5B57\u304B\u306A\u30AB\u30CAABC123\u6F22\u5B57\u304B\u306A\u30AB\u30CAABC123\u6F22\u5B57\u304B\u306A\u30AB\u30CA",`\uFF71\uFF72\uFF73\uFF74\uFF75\uFF76\uFF9E\uFF77\uFF9E\uFF78\uFF9E\uFF79\uFF9E\uFF7A\uFF9E${String.fromCodePoint(8232)}\u6B21\u306E\u884C`],Cd=["","\u30A2","\u4F50"," "],Md=()=>JSON.stringify(xd.map(e=>qr(e,8))),Pd=e=>`dr-search-v${sd};fz=${e.slice(0,16)};u=${process.versions.unicode};icu=${process.versions.icu}`;var Ld=async()=>{let e=(0,Ni.createHash)("sha256");e.update(JSON.stringify(ye.DEFAULT_NORMALIZE_OPTIONS));for(let t of Cd)await(0,Kn.setImmediate)(),e.update("\0"),e.update(Qn(_d(t)));return await(0,Kn.setImmediate)(),e.update("\0"),e.update(Md()),Pd(e.digest("hex"))},kd=e=>{let t=null;return()=>{if(t===null){let r=e();t=r,r.catch(()=>{t=null})}return t}},ro=kd(Ld);var Nd=/^-+/u,vd=/\s+/u,ji=e=>{let t=Nd.exec(e);return t===null?[e]:[e,"\u30FC".repeat(t[0].length)+e.slice(t[0].length)]},Od=(e,t)=>{let r=[...ji(e).map(n=>({text:n,tier:Mt.word})),...t.flatMap(n=>ji(n).map(o=>({text:o,tier:Mt.reading})))];return r.filter((n,o)=>r.findIndex(a=>a.text===n.text)===o)},Fd=e=>JSON.stringify(e.map(({text:t,tier:r})=>JSON.stringify([r,t])).sort()),jr=(e,t)=>{if(e.length>we.maxQueryLength)return{ok:!1,reason:"too-long"};let r=[],n=new Set,o=0;for(let{query:a}of(0,Wi.parseQuerySets)(Yr(e),t).sets){let i=[],l=new Set;for(let c of a.split(vd)){let d=$r(c);if(d.length===0)return{ok:!1,reason:"blank-word"};if(d.length>we.maxWordLength)return{ok:!1,reason:"word-too-long"};let u=Od(d,Hi(c)),R=Fd(u);l.has(R)||(l.add(R),i.push({alternatives:u}))}if(i.length>we.maxWordsPerSet)return{ok:!1,reason:"too-many-words-in-set"};let s=JSON.stringify([...l].sort());n.has(s)||(n.add(s),o+=i.length,r.push({words:i}))}return r.length===0?{ok:!1,reason:"empty"}:r.length>we.maxSets?{ok:!1,reason:"too-many-sets"}:o>we.maxWords?{ok:!1,reason:"too-many-words"}:{ok:!0,plan:{combine:t,sets:r}}},ur=e=>e.sets.map(t=>t.words.map(r=>r.alternatives));var zh=Object.freeze({sourceTypes:null,authors:null,customers:null}),Hd=e=>e.sourceTypes!==null||e.authors!==null||e.customers!==null,zi=(e,t,r)=>{if(ra(e)&&Hd(r))return{ok:!0,criteria:{plan:null,filters:r}};let n=jr(e,t);return n.ok?{ok:!0,criteria:{plan:n.plan,filters:r}}:{ok:!1,reason:n.reason}};var Gi=6e4,Bd=1,Ud=3200,Ki=2e3,$d=Object.freeze({search:Ud,reports:Ki,"search-marks":Ki,"search-facets":null}),Vd=(e,t)=>{let r=$d[e];return r===null?null:{max:t,maxPerOwner:wr,maxWaitMs:r}},dr=e=>{let{concurrency:t,route:r,logger:n}=e,o=ut({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:Gi,logger:n,windowFields:()=>`route=${r}`}),a=rt({limit:t,maxHeldPerOwner:Math.max(1,Math.floor(t/2)),queue:Vd(r,t)}),i=Object.freeze({status:429,message:qn,headers:Object.freeze({"Retry-After":String(Bd)})}),l=Ve({windowMs:Gi,tallies:["busy"],writeSuppressed:(s,{count:c,since:d})=>{n.warn(`busy_suppressed count=${c} since=${d} route=${r} concurrency=${t}`)}});return{admit:async(s,c)=>{let d=o.spend(s,r);if(d!==null)return{refusal:d};let u=await a.acquire(s,c);return u!==null?{release:u}:(o.refund(s,1),c.aborted||l.record(r,"busy",()=>n.warn(`429 ${r} reason=busy concurrency=${t}`)),{refusal:i})}}};var ss=require("@aiquants/sse"),bt=require("@aiquants/sse/server");var qt=(e,t)=>{let r=e.message.data;if(!r)return{entry:{id:e.id,message:null},json:void 0};let n;try{n=JSON.parse(r)}catch(i){return t.error(`SSE message ${e.id} is not JSON:`,i),{entry:{id:e.id,message:null},json:void 0}}let o=Yo.safeParse(n);if(!o.success)return t.error("SSE message validation failed:",o.error.format()),{entry:{id:e.id,message:null},json:n};let a=Object.freeze({parsed:o.data,published:n,text:r});return{entry:Object.freeze({id:e.id,message:a}),json:n}},Yd=["externalComments","postedComments"],Ji=new WeakMap,qd=e=>{let t=Ji.get(e);if(t!==void 0)return t;let r={recipientRemoved:null,commentsRedacted:null};return Ji.set(e,r),r},Qi=e=>{let{recipientRawUserId:t,...r}=e;return r},Xi=(e,t)=>{let{published:r}=e;if(!(t||Object.hasOwn(r,"recipientRawUserId")))return e.text;let n=qd(e);if(t){if(n.commentsRedacted===null){let o=Qi(r),a=o.report;n.commentsRedacted=JSON.stringify({...o,report:{...a,...Object.fromEntries(Yd.map(i=>[i,[]]))}})}return n.commentsRedacted}return n.recipientRemoved===null&&(n.recipientRemoved=JSON.stringify(Qi(r))),n.recipientRemoved};var ns=require("@aiquants/sse"),os=require("@aiquants/sse/shared-source");var St="daily-report:ids:",gt="daily-report:business-date:",Wr=(e,t)=>`${e}st:${t}`,no=e=>`${St}user:${e}:`,Zi=(e,t)=>Wr(no(e),t),jd=e=>`${gt}${e}:`,es=(e,t)=>Wr(jd(e),t),jt=e=>`daily-report:date:${e}:user:`,Lt=(e,t)=>`${jt(e)}${t}:`,ts=(e,t,r)=>Wr(Lt(e,t),r),Ye=e=>`daily-report:detail:${e}:user:`,zr=(e,t)=>`${Ye(e)}${t}:`,rs=(e,t,r)=>Wr(zr(e,t),r);var pt=(e,t)=>{let[r,n]=e.split("-").map(Number),[o,a]=t.split("-").map(Number);return r!==o?r<o:n<=a},Wd=5e3,zd=Ir,Wt=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=ge(t.logger,1,"SseReader"),this._source=this._createSource()}ready(){return this._position().then(()=>{})}subscribe(t,r){return this._source.subscribe({next:n=>{this._lastId=n.id,t(n)},error:n=>r(n instanceof Error?n:new Error(String(n)))})}async destroy(){await this._source.dispose(),this._generation+=1,this._positioning=null,this._lastId=null,this._source=this._createSource()}_position(){if(this._lastId!==null)return Promise.resolve(this._lastId);if(this._positioning===null){let t=this._generation;this._positioning=this._readTail().then(r=>{if(t!==this._generation)throw new Error("SSE reader was destroyed while the stream tail was being read");return this._positioning=null,this._lastId=r,r},r=>{throw t===this._generation&&(this._positioning=null),r})}return this._positioning}async _readTail(){let t=await this.config.redis?.getClient();if(!t)throw new Error("Failed to get Redis client to read the SSE stream tail");let r=await t.xRevRange(this.config.streamKey,"+","-",{COUNT:1});return r.length>0?r[0].id:"0-0"}_createSource(){return(0,os.createSharedSource)({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:ns.systemSseRuntime,onListenerError:t=>this._logger.error("SSE reader subscriber threw:",t),onStopError:t=>this._logger.error("SSE reader failed to stop:",t)})}async _start(t){let r=await this._position(),n=await this.config.redis?.createClient();if(!n)throw new Error("Failed to create Redis client for SSE reader");n.on("error",i=>{this._logger.error("Redis client error:",i)});let o=!1,a=this._readLoop(n,t,r,()=>o);return async()=>{if(o=!0,n.isOpen)try{await n.quit()}catch{}await a}}async _readLoop(t,r,n,o){let a=n;try{for(;!o()&&t.isOpen;){let i=await t.xRead([{key:this.config.streamKey,id:a}],{BLOCK:Wd,COUNT:zd});if(i)for(let l of i)for(let s of l.messages){a=s.id;let{entry:c,json:d}=qt(s,this._logger);this._invalidateCaches(d),r.next(c)}}}catch(i){o()||(this._logger.error("xRead loop error:",i),r.fail(i instanceof Error?i:new Error(String(i))));return}o()||r.fail(new Error("Redis client for SSE reader closed unexpectedly"))}_invalidateCaches(t){if(t===null||typeof t!="object")return;let{type:r,reportHubId:n}=t;(r==="report-create"||r==="report-delete"||r==="report-publish")&&this.config.cache.invalidatePrefix(St),(r==="comment-add"||r==="comment-delete"||r==="status-update")&&typeof n=="number"&&this.config.cache.invalidatePrefix(Ye(n))}};var ls=Object.freeze({...or,route:"sse",frameworkDataRefusal:xr}),as=864e5,Gd={baseMs:2e3,jitterMs:8e3},oo=6e4,Kr=Ir,cs=JSON.stringify({type:"connected"}),is="0-0",Kd=(e,t,r)=>{if(t===null&&r===null)return!0;switch(e.type){case"connected":case"status-update":return!0;case"report-create":case"report-update":case"report-publish":return Ie(t,e.report.sourceType);case"comment-add":case"comment-delete":return Ie(r,e.sourceType);case"report-delete":return Ie(t,e.sourceType)}},Jd=(e,t)=>t===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"?!1:!Ie(t,e.report.sourceType),Qd=(e,t)=>{e.writeEvent({event:null,id:t,data:cs})},Xd=(e,t,r)=>{let{message:n}=t;if(n===null)return;let{parsed:o,published:a}=n,i=typeof a.recipientRawUserId=="number"?a.recipientRawUserId:void 0;if((o.type==="status-update"||i!==void 0)&&i!==r.internalUserId||!Kd(o,r.visibleSet,r.commentableSet)){Qd(e,t.id);return}e.writeEvent({event:null,id:t.id,data:Xi(n,Jd(o,r.commentableSet))})},us=e=>{let{authenticate:t,service:r,resolveViewerScope:n,redis:o,sseReader:a,streamKey:i,streamSlots:l,logger:s}=e,c=async(d,u)=>{let{request:R,internalUserId:m,cursor:p}=u,f=u.initialScope.visible,y=u.initialScope.commentable,S=0,_=setInterval(()=>{let b=++S;n(R,"refresh").then(N=>{b===S&&(f=N.visible,y=N.commentable)})},oo);d.onClose(()=>clearInterval(_));let D=p===null?is:p,h=p!==null&&o!==void 0,g=[],P=null,x=b=>{pt(b.id,D)||(D=b.id,Xd(d,b,{internalUserId:m,visibleSet:f,commentableSet:y}))},M=async(b,N)=>{let[$]=await b.xRange(i,"-","+",{COUNT:1});return $!==void 0&&!pt($.id,N)},j=async(b,N)=>{if(await M(b,N))return!1;let $=N;for(;;){let F=await b.xRange(i,$,"+",{COUNT:Kr}),H=F[0];if(H!==void 0&&H.id!==$&&await M(b,$))return!1;for(let ee of F){if(P!==null&&pt(P,ee.id))return!0;pt(ee.id,D)||x(qt(ee,s).entry)}let K=F.at(-1);if(F.length<Kr||K===void 0||d.isClosed())return!0;$=K.id}},k=a.subscribe(b=>{if(!h){x(b);return}pt(b.id,D)||(P===null&&(P=b.id),g.push(b))},b=>{s.error(`[SSE:${m}] Fan-Out reader error:`,b),d.close()});if(d.onClose(k),p===null){await a.ready();try{let b=await o?.getClient();if(b){let N=await b.xRevRange(i,"+","-",{COUNT:1});N.length>0&&!pt(N[0].id,D)&&(D=N[0].id)}}catch{}}if(d.writeEvent({event:null,id:D===is?null:D,data:cs}),(0,bt.startSseHeartbeat)(d,{intervalMs:Uo,retry:Gd,runtime:ss.systemSseRuntime}),p===null||o===void 0)return;await a.ready();let v=await o.getClient();if(v===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await j(v,p)){d.writeRetry(as),d.writeEvent({event:"resync-required",id:null,data:""}),d.close();return}h=!1;for(let b of g.splice(0))x(b)};return async({request:d,params:u})=>{let R,m=()=>{let f=new Headers;R!==void 0&&f.append("Set-Cookie",R);for(let[y,S]of Object.entries(tt))f.set(y,S);return f},p=f=>(0,bt.terminalStreamResponse)(f,{data:"",retryMs:as,headers:m()});try{let f=await t(d,{failureRedirect:null});R=f.cookie;let{user:y}=f;if(!y)return p("auth-required");let S=await r.getUserIdByExternalId(y.id);if(!S)return p("forbidden");if(u.endpoint!=="updates")return new Response("Not Found",{status:404,headers:m()});let _=(0,bt.readLastEventId)(d,$o);if(_!==null&&!Vo(_))return s.warn(`[SSE:${S}] malformed resume cursor; asking the client to resync`),p("resync-required");let D=Br(d),h=await l.admit(S,"sse",D);if(h===null){let P=m();for(let[x,M]of Object.entries(He(503)))P.set(x,M);return new Response("Too many streams",{status:503,headers:P})}let g=!1;try{let P=await n(d,"initial");return(0,bt.createSseResponse)({requestSignal:D,headers:m(),onError:(x,M)=>s.error(`[SSE:${S}] ${M} failed:`,x),produce:x=>(g=!0,x.onClose(h),c(x,{request:d,internalUserId:S,cursor:_,initialScope:P}))})}finally{g||h()}}catch(f){if(f instanceof Response)throw f;let y=f instanceof Error?f:new Error(String(f));return s.error(`500 sse name=${y.name} message=${y.message}`),new Response("Internal Server Error",{status:500,headers:m()})}}};var ds=(e,t)=>{let r=new Headers({...t?.headers,"Content-Type":"application/json",...tt});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},Zd=Object.freeze({...or,route:"api",frameworkDataRefusal:({params:e})=>Nn(e.endpoint)&&Pt[e.endpoint].body==="stream"?xr():null}),ep=Object.freeze({...or,route:"action"}),tp=(e,t,r)=>({...r,status:"OK",intent:e.intent,reportHubId:t,clientTempId:e.clientTempId}),fs=6e4,Rs=5,rp=Rs*Math.ceil(fs/500),np=2,op=6,ap=6e4,ip=Rs*np*op,sp=2,lp=10,cp=2,up=10,ps=(e,t)=>Math.max(e,wr)*t,Ss=(e,t)=>{for(let[r,n]of Object.entries(t))e.headers.set(r,n);return e},dp=Object.freeze({etag:(e,t,r)=>Sa(e,t,r,200),"no-store":(e,t,r)=>Bn(t,r,200)}),pp=e=>Un(e.body==="json"?dp[e.cache]:null),ms=Un(null),ys=(e,t,r,n)=>Ss(e(t,r,{error:{message:n.message}},n.status),n.headers),hs=(e,t,r)=>Ss(e(t,r,null,503),He(503));function Jr(e){Fr(e);let{authenticate:t,service:r,encodeUserId:n,redis:o,sseReader:a,streamKey:i}=e,l={titleMaxLength:de("service.titleMaxLength",r.titleMaxLength,1)},s=e.loginRedirectPath??"/auth/login",c=ge(e.logger,3,"API"),d=ge(e.logger,3,"Visibility"),u=ge(e.logger,1,"SSE"),R=ge(e.logger,1,"Attachment"),m=ge(e.logger,2,"Isolation"),p=ge(e.logger,2,"Action"),f=ge(e.logger,2,"Search"),y=ge(e.logger,2,"Refresh"),S=ge(e.logger,2,"Streams"),_=ge(e.logger,2,"Reads"),D=ut({reason:"refresh_rate_limit",limitPerWindow:ip,windowMs:ap,logger:y,windowFields:()=>"route=api"}),h=gi(S),g=fi(_),P=async(w,A,E,I,C,O)=>{let q=await r.getUserIdByExternalId(A.id);try{return await O(q===null?void 0:g.admissionFor(q,w,E.signal))}catch(B){if(B instanceof je)return Hr(C,E,I);throw B}},x=(w,A,E,I,C)=>{let O=D.spend(A.id,`endpoint=${w}`);return O===null?null:ys(C,E,I,O)},M=async(w,A="initial")=>{let E=e.resolveVisibleSourceTypes;if(!E)return Ue.unrestricted("no visibility port injected: this deployment does not restrict by source type");try{let I=await E(w,{reason:A});return I==null?Ue.unrestricted("visibility port returned null/undefined: this deployment opts out of source-type filtering"):Ue.restrictTo(I)}catch(I){return d.error("resolveVisibleSourceTypes threw; failing closed (deny all)",I),Ue.restrictTo([])}},j=async({request:w})=>{let{user:A,cookie:E}=await t(w,{failureRedirect:s}),I=new Headers;E&&I.append("Set-Cookie",E);let C=await r.getUserIdByExternalId(A.id),O=C?n(C):null;return{data:{user:A,userId:O},headers:I}},k=w=>{let{limiter:A}=w;return async(E,I,C,O,q,B)=>{if(A===null)return B(C,I,{error:{message:"Unknown endpoint"}},404);let z=w.parse(E);if(!z.ok)return B(C,I,z.invalid,400);let L=await r.getUserIdByExternalId(O.id);if(!L)return B(C,I,w.emptyAnswer(z.parsed),200);let{signal:G}=C,te=await A.admit(L,G);if("refusal"in te)return G.aborted?hs(B,C,I):ys(B,C,I,te.refusal);try{G.throwIfAborted();let Z=await w.read(z.parsed,{userId:L,user:O,scope:q},G);return G.throwIfAborted(),B(C,I,Z,200)}catch(Z){if(G.aborted&&Z===G.reason)return hs(B,C,I);throw Z}finally{te.release()}}},v=r.searchLimits===null?null:dr({...r.searchLimits,route:ie.search,logger:f}),b=r.searchLimits===null?null:dr({concurrency:ps(r.searchLimits.concurrency,sp),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*lp,route:ie.reports,logger:f}),N=r.searchLimits===null?null:dr({concurrency:ps(r.searchLimits.concurrency,cp),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*up,route:ie.searchMarks,logger:f}),$=r.searchLimits===null?null:dr({...r.searchLimits,route:ie.searchFacets,logger:f}),F={[ie.businessDate]:async(w,A,E,I,C,O)=>{let q=w.searchParams.get(Se.businessDate),B=q===null?null:Ht(q);if(B===null)return O(E,A,{error:{message:"Invalid business date"}},400);let z=nr(w.searchParams.get(Se.forceRefresh));if(z===null)return O(E,A,{error:{message:"Invalid forceRefresh"}},400);let L=z?x(ie.businessDate,I,E,A,O):null;return L!==null?L:P(ie.businessDate,I,E,A,O,async G=>{let te=await r.getDailyReportsByBusinessDateByExternalId(C,B,I.id,{forceRefresh:z,admission:G});return O(E,A,{businessDate:B,reports:te},200)})},[ie.idsStream]:_i({service:r,logger:c,streamSlots:h,missGate:g,refuseForcedRead:(w,A,E,I)=>x(ie.idsStream,w,A,E,I)}),[ie.report]:async(w,A,E,I,C,O)=>{let q=We(w.searchParams.get(Se.reportHubId));if(q===null)return O(E,A,{error:{message:"Invalid reportHubId"}},400);let B=nr(w.searchParams.get(Se.forceRefresh));if(B===null)return O(E,A,{error:{message:"Invalid forceRefresh"}},400);let z=B?x(ie.report,I,E,A,O):null;return z!==null?z:P(ie.report,I,E,A,O,async L=>{let G=await r.getDailyReportDetailByIdByExternalId(C,q,I.id,{snapshot:!0,forceRefresh:B,admission:L});return G?O(E,A,{report:G},200):O(E,A,{error:{message:"Report not found"}},404)})},[ie.search]:k({limiter:v,parse:w=>{let A=w.searchParams.get(Se.searchQuery),E=Ln(w.searchParams.get(Se.searchCombine));if(A===null||E===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let I=oa(w.searchParams,r.searchFilterSourceTypes);if(!I.ok)return{ok:!1,invalid:{error:{message:"Invalid search filters",reason:I.reason}}};let C=zi(A,E,I.filters);if(!C.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:C.reason}}};let{criteria:O}=C;return{ok:!0,parsed:{criteria:O,words:O.plan===null?[]:ur(O.plan)}}},emptyAnswer:({words:w})=>Mn([],w),read:async({criteria:w,words:A},{userId:E,scope:I})=>Mn(await r.searchDailyReports(I,E,w),A)}),[ie.reports]:k({limiter:b,parse:w=>{let A=kn(w.searchParams.get(Se.reportIds));return A===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:A}},emptyAnswer:()=>({reports:[]}),read:async(w,{user:A,scope:E})=>({reports:await r.getDailyReportDetailsByIdsByExternalId(E,w,A.id)})}),[ie.searchMarks]:k({limiter:N,parse:w=>{let A=w.searchParams.get(Se.searchQuery),E=Ln(w.searchParams.get(Se.searchCombine));if(A===null||E===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let I=jr(A,E);if(!I.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:I.reason}}};let C=kn(w.searchParams.get(Se.reportIds));return C===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:{plan:I.plan,ids:C}}},emptyAnswer:({plan:w})=>({wordsDigest:Er(ur(w)),reports:[],deferred:[]}),read:({plan:w,ids:A},{userId:E,scope:I},C)=>r.markDailyReportSearchHits(I,E,w,A,{signal:C})}),[ie.searchFacets]:k({limiter:$,parse:()=>({ok:!0,parsed:null}),emptyAnswer:()=>({sourceTypes:[],authors:[],customers:[]}),read:(w,{userId:A,scope:E})=>r.listDailyReportSearchFacets(E,A)})},H=async({request:w,params:A})=>{let{user:E,cookie:I}=await t(w,{failureRedirect:null}),C=I??null;if(!E)return ms(w,C,{error:{message:"Unauthorized"}},401);let O=A.endpoint;if(!Nn(O))return ms(w,C,{error:{message:"Unknown endpoint"}},404);let q=Pt[O],B=pp(q),z=ya[q.body];if(!z.includes(w.method)){let G=B(w,C,{error:{message:"Method not allowed"}},405);return G.headers.set("Allow",z.join(", ")),G}let L=se();try{let G=new URL(w.url),te=await M(w),Z=await F[O](G,C,w,E,te,B);return q.body==="json"&&c.debug(Z.headers.has("ETag")?`${Z.status} endpoint=${O} etag_match=${Z.status===304}`:`${Z.status} endpoint=${O}`),Z}catch(G){let te=se()-L,Z=G instanceof Error?G:new Error(String(G));return c.error(`500 endpoint=${O} elapsed=${te}ms name=${Z.name} code=${"code"in Z?Z.code:"N/A"} message=${Z.message}`,Z),B(w,C,{error:{message:"Internal Server Error"}},500)}},K=ma(p),ee=ut({reason:"rate_limit",limitPerWindow:rp,windowMs:fs,logger:p,windowFields:()=>"route=action"}),W=async(w,A,E,I,C)=>{let{clientTempId:O}=w;if(w.intent==="create"){let L=await r.createDailyReport(A,w.businessDate,O);return C(w,L.reportHubId,{report:L})}let{reportHubId:q,businessDate:B}=w,z=async(L,G)=>{try{let te=await G(L.value);return C(L,q,{updatedStatus:{isStarred:te.isStarred,isRead:te.isRead},operationTimestamp:L.operationTimestamp})}catch(te){if(te instanceof Error&&te.message==="Not Found")return I({error:"Report not found"},{status:404});throw te}};switch(w.intent){case"update":try{return await r.updateDailyReport(q,A,w.changes,O),C(w,q,{})}catch(L){if(L instanceof Error){if(L.message==="Unauthorized")return I({error:"Unauthorized"},{status:403});if(L.message==="Not Found")return I({error:"Report not found"},{status:404})}throw L}case"publish":try{let L=await r.publishDailyReport(q,A,O);return C(w,q,{report:L})}catch(L){if(L instanceof Error){if(L.message==="Unauthorized")return I({error:"Unauthorized"},{status:403});if(L.message==="Not Found")return I({error:"Report not found"},{status:404})}throw L}case"delete":try{return await r.deleteDailyReport(q,A,O),C(w,q,{})}catch(L){if(L instanceof Error){if(L.message==="Unauthorized")return I({error:"Unauthorized"},{status:403});if(L.message==="Not Found")return I({error:"Report not found"},{status:404})}throw L}case"toggleStar":return await z(w,L=>r.setStarStatus(E,A,q,B,L,O));case"toggleRead":return await z(w,L=>r.setReadStatus(E,A,q,B,L,O));case"addComment":try{let L=await r.addComment(E,A,q,w.content,B,O);return C(w,q,{newComment:L})}catch(L){if(L instanceof Error){if(L.message==="Not Found")return I({error:"Report not found"},{status:404});if(L.message.startsWith("Comments are restricted"))return I({error:"Comments are restricted for this report"},{status:403})}throw L}case"deleteComment":try{return await r.deleteComment(E,A,q,w.commentId,B,O),C(w,q,{deletedCommentId:w.commentId})}catch(L){if(L instanceof Error){if(L.message==="Unauthorized")return I({error:"Unauthorized"},{status:403});if(L.message==="Not Found")return I({error:"Comment not found"},{status:404})}throw L}}},ae=async({request:w,params:A})=>{let{user:E,cookie:I}=await t(w,{failureRedirect:null}),C=(B,z)=>ds(B,{...z,setCookie:I}),O=(B,z,L)=>ds(tp(B,z,L),{setCookie:I});if(!E)return C({error:"Unauthorized"},{status:401});let q=se();try{if(A.endpoint!==ie.action)return C({error:"Unknown endpoint"},{status:404});let B=ee.spend(E.id,"action");if(B!==null)return C({error:B.message},{status:B.status,headers:B.headers});let z=await pa(w,l);if("refusal"in z){let{refusal:Z}=z;return Z.status===413&&K(Z.measuredBy),C({error:Z.error},{status:Z.status})}let{command:L}=z;if(L.intent==="clearCache"&&!e.enableDevCacheClear)return C({error:"Invalid intent"},{status:400});let G=await r.getUserIdByExternalId(E.id);if(!G)return C({error:"User not found"},{status:404});let te=await M(w);return L.intent==="clearCache"?(await r.clearCache(),C({status:"OK",intent:"clearCache"})):await W(L,G,te,C,O)}catch(B){if(B instanceof Response)throw B;let z=se()-q,L=B instanceof Error?B:new Error(String(B));return c.error(`500 action elapsed=${z}ms name=${L.name} message=${L.message}`,L),C({error:"Internal Server Error"},{status:500})}},Te=us({authenticate:t,service:r,resolveViewerScope:M,redis:o,sseReader:a,streamKey:i,streamSlots:h,logger:u}),ke=di({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:M,logger:R}),Re=Aa(m),J=(w,A)=>async E=>{let I=Da(E.request)?w.frameworkDataRefusal(E):null;if(I!==null)throw I;return Ta(E.request,w)?(Re(w.route,E.request),w.crossSiteRejection()):A(E)};return{index:{loader:j},api:{loader:J(Zd,H),action:J(ep,ae)},sse:{loader:J(ls,Te)},attachment:{loader:J(ui,ke)}}}var Gt=require("@aiquants/mssql"),fe=require("drizzle-orm");var mp=["tables","externalSourceTexts","concurrency","rateLimitPerMinute"],yp=["document","comment"],hp=["hubId","searchText","sourceDigest","normalizerVersion","indexedAt","rowVersion","authorName","customerName"],fp=["hubId","ordinal","authorUserId","commentText"],ao=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},gs=(e,t,r)=>{for(let n of Object.keys(t))if(!r.includes(n))throw pn(e,n,r)},bs=(e,t,r)=>{if(typeof t!="object"||t===null)throw X(e,"a table object",t);let n=t;for(let o of r)if(typeof n[o]!="object"||n[o]===null)throw X(`${e}.${o}`,"a column",n[o])},Ds=(e,t)=>{if(!ao(e))throw X("search","a plain object",e);gs("search key",e,mp);let{tables:r}=e;if(!ao(r))throw X("search.tables","a plain object with document and comment",r);gs("search.tables key",r,yp),bs("search.tables.document",r.document,hp),bs("search.tables.comment",r.comment,fp);let n=new Map;if(e.externalSourceTexts!==void 0){if(!ao(e.externalSourceTexts))throw X("search.externalSourceTexts","a plain object",e.externalSourceTexts);for(let[o,a]of Object.entries(e.externalSourceTexts)){if(!t.includes(o))throw pn("search.externalSourceTexts key",o,t);if(typeof a!="function")throw X(`search.externalSourceTexts.${o}`,"a function",a);n.set(o,a)}}return{tables:r,externalSourceTexts:n,concurrency:de("search.concurrency",e.concurrency,1),rateLimitPerMinute:de("search.rateLimitPerMinute",e.rateLimitPerMinute,1)}};var Dt=e=>{let t=typeof e=="object"&&e!==null?e.recordset:void 0;if(!Array.isArray(t))throw new Error("[daily-report] search: the database result has no recordset");return t},kt=(e,t)=>{let r=typeof e=="string"?We(e):typeof e=="number"&&Ze(e)?e:null;if(r===null)throw new Error(`[daily-report] search: column ${t} holds no positive id`);return r},Nt=(e,t)=>{if(e===null||typeof e=="string")return e;throw new Error(`[daily-report] search: column ${t} holds no string`)};var U=require("drizzle-orm");var mt=require("drizzle-orm"),Ts=e=>{if(e.length===0)throw new Error("[daily-report] draft rule: draftLabelNames must hold at least one name (a rule without names would show every draft to every viewer)");return mt.sql.join(e.map(t=>mt.sql`${t}`),mt.sql`, `)},Qr=(e,t)=>{let{hub:r,hubLabel:n,label:o}=e;return mt.sql`EXISTS (SELECT 1 FROM ${n} INNER JOIN ${o} ON ${o.id} = ${n.labelId} WHERE ${n.hubId} = ${r.id} AND ${o.name} IN (${Ts(t)}))`},As=(e,t)=>{let{hubLabel:r,label:n}=e;return mt.sql`${r.labelId} IN (SELECT ${n.id} FROM ${n} WHERE ${n.name} IN (${Ts(t)}))`},Xr=(e,t,r,n)=>{let{hub:o}=e,a=n==="author-or-authorless"?mt.sql`${o.userId} = ${t} OR ${o.userId} IS NULL`:mt.sql`${o.userId} = ${t}`;return mt.sql`(${a} OR NOT ${Qr(e,r)})`};var Rp=/[[%_]/gu,Sp=e=>e.replace(Rp,t=>`[${t}]`),Es=e=>`%${Sp(e)}%`;var Ge=Object.freeze({reportHubId:"report_hub_id",businessDate:"business_date",sourceType:"source_type"}),vt=Object.freeze({reportHubId:"report_hub_id",matchedSets:"matched_sets"}),mr=Object.freeze({value:"value"}),_e=Object.freeze({hubId:"hub_id",sourceDigest:"source_digest",normalizerVersion:"normalizer_version"}),V=e=>U.sql`${U.sql.identifier(e.name)}`,pr=e=>U.sql.join(e.map(t=>U.sql`${t}`),U.sql`, `),ws=(e,t)=>U.sql`SELECT ${V(e.id)} AS ${U.sql.identifier(_e.hubId)} FROM ${e} WITH (UPDLOCK, ROWLOCK) WHERE ${e.id} IN (${pr(t)}) ORDER BY ${e.id}`,gp=(e,t,r)=>{let{hub:n}=e,{document:o,comment:a}=e.search,i=t.alternatives.map(u=>Es(u.text)),l=U.sql.join(i.map(u=>U.sql`${o.searchText} LIKE ${u}`),U.sql` OR `),s=U.sql.join(i.map(u=>U.sql`${a.commentText} LIKE ${u}`),U.sql` OR `),c=lr(n.sourceType,r.scope.commentable),d=c===void 0?U.sql``:U.sql` AND (${c} OR ${a.authorUserId} = ${r.userId})`;return U.sql`((${l}) OR EXISTS (SELECT 1 FROM ${a} WHERE ${a.hubId} = ${n.id} AND (${s})${d}))`},Is=(e,t,r)=>U.sql`(${U.sql.join(t.words.map(n=>gp(e,n,r)),U.sql` AND `)})`,io=(e,t,r,n)=>{let{hub:o}=e,a=[U.sql`${o.deletedAt} IS NULL`,Xr(e,t.userId,r,"author")],i=lr(o.sourceType,t.scope.visible);return i!==void 0&&a.push(i),n!==void 0&&a.push(U.sql`${o.id} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${JSON.stringify(n)}))`),a},bp=(e,t)=>{let{hub:r}=e,{document:n}=e.search,o=[];if(t.sourceTypes!==null){if(t.sourceTypes.size===0)throw new Error("[daily-report] search: a source-type filter must hold at least one source type");o.push(U.sql`LOWER(${r.sourceType}) IN (${pr([...t.sourceTypes])})`)}return t.authors!==null&&o.push(U.sql`${n.authorName} IN (${pr(t.authors)})`),t.customers!==null&&o.push(U.sql`${n.customerName} IN (${pr(t.customers)})`),o},_s=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,{plan:l}=t,s=[...io(e,r,n,o),...bp(e,t.filters)];if(l!==null){let c=l.combine==="intersection"?U.sql` AND `:U.sql` OR `;s.push(U.sql`(${U.sql.join(l.sets.map(d=>Is(e,d,r)),c)})`)}return U.sql`SELECT ${V(a.id)} AS ${U.sql.identifier(Ge.reportHubId)}, CONVERT(char(10), ${V(a.businessDate)}, 23) AS ${U.sql.identifier(Ge.businessDate)}, ${V(a.sourceType)} AS ${U.sql.identifier(Ge.sourceType)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${U.sql.join(s,U.sql` AND `)} ORDER BY ${a.businessDate} DESC, ${a.id} DESC`},xs=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,l=U.sql.join(t.sets.map((s,c)=>U.sql`(CASE WHEN ${Is(e,s,r)} THEN ${2**c} ELSE 0 END)`),U.sql` + `);return U.sql`SELECT ${V(a.id)} AS ${U.sql.identifier(vt.reportHubId)}, ${l} AS ${U.sql.identifier(vt.matchedSets)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${U.sql.join(io(e,r,n,o),U.sql` AND `)}`},Cs=(e,t,r,n)=>{let{hub:o}=e,{document:a}=e.search,i=a[t],l=[...io(e,r,n),U.sql`${i} IS NOT NULL`];return U.sql`SELECT ${i} AS ${U.sql.identifier(mr.value)} FROM ${o} INNER JOIN ${a} ON ${a.hubId} = ${o.id} WHERE ${U.sql.join(l,U.sql` AND `)} GROUP BY ${i} ORDER BY ${i}`},Ms=(e,t,r)=>{let{document:n,comment:o}=e,a=JSON.stringify(t.map(s=>({[n.hubId.name]:s.hubId,[n.searchText.name]:s.searchText,[n.sourceDigest.name]:s.sourceDigest,[n.normalizerVersion.name]:r,[n.authorName.name]:s.authorName,[n.customerName.name]:s.customerName}))),i=JSON.stringify(t.flatMap(s=>s.comments.map(c=>({[o.hubId.name]:s.hubId,[o.ordinal.name]:c.ordinal,[o.authorUserId.name]:c.authorUserId,[o.commentText.name]:c.commentText})))),l=JSON.stringify(t.map(s=>s.hubId));return U.sql`MERGE ${n} WITH (HOLDLOCK) AS t USING (SELECT * FROM OPENJSON(${a}) WITH (${V(n.hubId)} bigint, ${V(n.searchText)} nvarchar(max), ${V(n.sourceDigest)} char(64), ${V(n.normalizerVersion)} varchar(64), ${V(n.authorName)} nvarchar(max), ${V(n.customerName)} nvarchar(max))) AS s ON t.${V(n.hubId)} = s.${V(n.hubId)}
8
+ WHEN MATCHED THEN UPDATE SET t.${V(n.searchText)} = s.${V(n.searchText)}, t.${V(n.sourceDigest)} = CONVERT(binary(32), s.${V(n.sourceDigest)}, 2), t.${V(n.normalizerVersion)} = s.${V(n.normalizerVersion)}, t.${V(n.authorName)} = s.${V(n.authorName)}, t.${V(n.customerName)} = s.${V(n.customerName)}, t.${V(n.indexedAt)} = SYSUTCDATETIME()
9
+ WHEN NOT MATCHED THEN INSERT (${V(n.hubId)}, ${V(n.searchText)}, ${V(n.sourceDigest)}, ${V(n.normalizerVersion)}, ${V(n.authorName)}, ${V(n.customerName)}) VALUES (s.${V(n.hubId)}, s.${V(n.searchText)}, CONVERT(binary(32), s.${V(n.sourceDigest)}, 2), s.${V(n.normalizerVersion)}, s.${V(n.authorName)}, s.${V(n.customerName)});
10
10
  DELETE FROM ${o} WHERE ${o.hubId} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${l}));
11
- INSERT INTO ${o} (${j(o.hubId)}, ${j(o.ordinal)}, ${j(o.authorUserId)}, ${j(o.commentText)}) SELECT ${j(o.hubId)}, ${j(o.ordinal)}, ${j(o.authorUserId)}, ${j(o.commentText)} FROM OPENJSON(${i}) WITH (${j(o.hubId)} bigint, ${j(o.ordinal)} int, ${j(o.authorUserId)} bigint, ${j(o.commentText)} nvarchar(max));`},ji=(e,t)=>q.sql`SELECT ${j(e.hubId)} AS ${q.sql.identifier(we.hubId)}, LOWER(CONVERT(char(64), ${j(e.sourceDigest)}, 2)) AS ${q.sql.identifier(we.sourceDigest)}, ${j(e.normalizerVersion)} AS ${q.sql.identifier(we.normalizerVersion)} FROM ${e} WHERE ${e.hubId} IN (${zt(t)})`,Wi=(e,t,r)=>q.sql`SELECT TOP (${r}) ${j(e.id)} AS ${q.sql.identifier(we.hubId)} FROM ${e} WHERE ${e.id} > ${t} ORDER BY ${e.id}`;var zi=e=>({search:async(t,r)=>Le(r.scope.visible)?[]:dt(await t.execute(Bi(e.tables,r.criteria,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=bt(o[Be.sourceType],Be.sourceType);if(a===null)throw new Error(`[daily-report] search: column ${Be.sourceType} is null`);return{reportHubId:gt(o[Be.reportHubId],Be.reportHubId),businessDate:bt(o[Be.businessDate],Be.businessDate),sourceType:a}}),matchedSets:async(t,r)=>{if(Le(r.scope.visible))return new Map;let n=dt(await t.execute(Vi(e.tables,r.plan,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames,r.ids))),o=2**r.plan.sets.length-1,a=new Map;for(let i of n){let l=i[Dt.matchedSets];if(!(typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&l<=o))throw new Error(`[daily-report] search: column ${Dt.matchedSets} holds no mask of ${r.plan.sets.length} keywords`);a.set(gt(i[Dt.reportHubId],Dt.reportHubId),l)}return a},facetValues:async(t,r)=>Le(r.scope.visible)?[]:dt(await t.execute(qi(e.tables,r.column,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=bt(o[Gt.value],Gt.value);if(a===null)throw new Error(`[daily-report] search: column ${Gt.value} is null`);return a})});var We=require("@aiquants/mssql"),qn=require("drizzle-orm");var Ki=require("crypto");var kd=Object.freeze({authorName:"author",customerName:"customer"}),Bn=e=>e===null?null:mn(e),Gi=(e,t,r)=>{let n=Bn(r);if(n!==null&&n.length>Qe.maxValueLength){let o=Qe.maxValueLength;throw new Error(`[daily-report] search index: report ${e}: the ${kd[t]} display value has ${n.length} UTF-16 units after trimming; the host must keep the author and customer display values at most ${o} UTF-16 units`)}return n},Kt=e=>e===null?"n;":`s${e.length}:${e}`,Jt="utf16le",vd=e=>{let t=(0,Ki.createHash)("sha256");t.update(`F${e.fields.length};`,Jt);for(let[r,n]of e.fields)t.update(Kt(r)+Kt(n),Jt);return t.update(`C${e.comments.length};`,Jt),e.comments.forEach((r,n)=>{t.update(`${n};${r.authorUserId===null?"n":`i${r.authorUserId}`};${Kt(r.text)}`,Jt)}),t.update(`P;${Kt(Bn(e.filterValues.authorName))}${Kt(Bn(e.filterValues.customerName))}`,Jt),t.digest("hex")},Vn=e=>{let t=0,r=[];for(let[,o]of e.fields){if(o===null)continue;let a=_r(o);t+=a.forcedCuts,r.push(a.text)}let n=[];for(let o of e.comments){let a=_r(o.text);t+=a.forcedCuts,a.text.length!==0&&n.push({ordinal:n.length,authorUserId:o.authorUserId,commentText:a.text})}return{hubId:e.hubId,searchText:oi(r),comments:n,sourceDigest:vd(e),forcedCuts:t,authorName:Gi(e.hubId,"authorName",e.filterValues.authorName),customerName:Gi(e.hubId,"customerName",e.filterValues.customerName)}};var Ji=e=>{let t=async(c,s)=>{let m=[];for(let u of(0,We.chunk)(s,We.MAX_IN_LIST))for(let f of dt(await c.execute(Ui(e.hub,u))))m.push(gt(f[we.hubId],we.hubId));return m},r=async(c,s)=>{for(let m of(0,We.chunk)(s,We.MAX_IN_LIST))await c.execute(Yi(e.tables,m,e.normalizerVersion))},n=async(c,s)=>{let m=new Map;for(let u of(0,We.chunk)(s,We.MAX_IN_LIST))for(let f of dt(await c.execute(ji(e.tables.document,u))))m.set(gt(f[we.hubId],we.hubId),{sourceDigest:bt(f[we.sourceDigest],we.sourceDigest),normalizerVersion:bt(f[we.normalizerVersion],we.normalizerVersion)});return m},o=async(c,s,m)=>dt(await c.execute(Wi(e.hub,s,m))).map(u=>gt(u[we.hubId],we.hubId)),a=async(c,s)=>{let m=await t(c,[...new Set(s)].sort((f,h)=>f-h));if(m.length===0)return;let u=(await e.loadSources(c,m)).map(Vn);u.length>0&&await r(c,u)},i=c=>e.inTransaction(async s=>{await s.execute(qn.sql`SET DEADLOCK_PRIORITY LOW`);let m=await t(s,c),u=await n(s,m),f=(await e.loadSources(s,m)).map(Vn),h=f.filter(R=>{let D=u.get(R.hubId);return D===void 0||D.sourceDigest!==R.sourceDigest||D.normalizerVersion!==e.normalizerVersion});return h.length>0&&await r(s,h),await s.execute(qn.sql`SET DEADLOCK_PRIORITY NORMAL`),{scanned:f.length,written:h.length,forcedCuts:f.reduce((R,D)=>R+D.forcedCuts,0)}});return{writeHubs:a,reconcile:async(c,s)=>{let{batchSize:m,hubIds:u,signal:f,onProgress:h}=s;re("reconcileSearchIndex: batchSize",m,1,We.MAX_IN_LIST);let R=ue(),D=u===void 0?null:(0,We.chunk)([...new Set(u)].sort((E,M)=>E-M),m),S={scanned:0,written:0,skipped:0,forcedCuts:0,lastHubId:null};for(let E=0;;E++){f?.throwIfAborted();let M=D===null?await o(c,S.lastHubId===null?0:S.lastHubId,m):D[E];if(M===void 0||M.length===0)break;let U=await i(M);S={scanned:S.scanned+U.scanned,written:S.written+U.written,skipped:S.skipped+U.scanned-U.written,forcedCuts:S.forcedCuts+U.forcedCuts,lastHubId:M[M.length-1]},h?.(S)}return{...S,elapsedMs:ue()-R}}}};var Zi=require("@aiquants/fuzzy-search/normalize");var Yn=255,Or=Object.values(yt).sort((e,t)=>e-t),Od=new Intl.Segmenter("und",{granularity:"grapheme"}),Te=Object.freeze({split:120,plan:200,normalize:900,map:2200,scan:2,run:700,segment:150,sweep:30,linear:6}),nt=5e5,Fr=Math.floor(nt/Te.linear),Fd=Math.floor(nt/Te.segment),Qi=Math.floor(nt/Te.sweep),es=Math.floor(nt/Te.scan),Wn=Object.freeze({maxRanges:5e5,maxUnits:4e6,maxFieldRanges:1e4,sliceNs:8e6,sliceMs:5}),ts=(e,t)=>{let r=0,n=t(),o=nt,a=!1;return{fits:i=>r===0?!0:r+i>e.sliceNs?!1:(r>=o&&(o=r+nt,a=t()-n>=e.sliceMs),!a),charge:i=>{r+=i},startSlice:()=>{r=0,n=t(),o=nt,a=!1}}},Ef=Object.freeze({fits:()=>!0,charge:()=>{}}),rs=e=>{let t=null;return{step:()=>{if(t!==null)return!0;let r=e.next();return r.done!==!0?!1:(t={result:r.value},!0)},result:()=>{if(t===null)throw new Error("[daily-report] search marks: the walk is not done (step until it returns true)");return t.result}}};var Hd=(e,t)=>{if(e.text!==t)throw new Error(`[daily-report] search marks: the position-mapped line (${e.text.length} units) differs from the index line (${t.length} units)`);return e},Ud=(e,t)=>e.chunks.length===1&&e.chunks[0].length===1&&e.chunks[0][0].start===0&&e.chunks[0][0].end===t.length;function*$d(e,t,r,n){let o=!1;for(let s=t;s<r&&!o;s+=Fr){let m=Math.min(r,s+Fr),u=(m-s)*Te.linear;n.fits(u)||(yield),o=(0,Zi.holdsMultiUnitCluster)(e.slice(s,m)),n.charge(u)}if(!o)return null;let a=new Int32Array(r-t),i=new Int32Array(r-t),l=Od.segment(e.slice(t,r))[Symbol.iterator](),c=l.next();for(;!c.done;){let s=Math.max(Fd,c.value.segment.length);n.fits(s*Te.segment)||(yield);let m=0;for(;!c.done&&m+c.value.segment.length<=s;){let{index:u,segment:f}=c.value;a.fill(t+u,u,u+f.length),i.fill(t+u+f.length,u,u+f.length),m+=f.length,c=l.next()}n.charge(m*Te.segment)}return{start:t,clusterStarts:a,clusterEnds:i}}var Bd=256,Vd=e=>{let t=new Int32Array(e.length),r=0;for(let n=1;n<e.length;n++){for(;r>0&&e.charCodeAt(n)!==e.charCodeAt(r);)r=t[r-1];e.charCodeAt(n)===e.charCodeAt(r)&&r++,t[n]=r}return e.length-t[e.length-1]},qd=e=>{let t=new Map;for(let r of e){if(r.text.length===0)throw new Error("[daily-report] search marks: an alternative has an empty text");let n=t.get(r.text);(n===void 0||r.tier<n)&&t.set(r.text,r.tier)}return[...t].map(([r,n])=>{let o=Vd(r),a=Math.max(es-r.length+1,r.length);if(o===r.length)return{text:r,tier:n,periodic:null,windowStarts:a};let i=r.length%o,l=r.slice(i,o)+r.slice(0,i);return{text:r,tier:n,periodic:{period:o,continuation:l.repeat(Math.ceil(Bd/o))},windowStarts:a}})},Hr=(e,t)=>{let{pieces:r}=e,n=r[e.lastPiece];if(n.plainStart<=t&&t<n.plainStart+n.text.length)return e.lastPiece;let o=0,a=r.length-1;for(;o<a;){let i=o+a+1>>1;r[i].plainStart<=t?o=i:a=i-1}return t>=r[o].plainStart+r[o].text.length?-1:(e.lastPiece=o,o)},Xi=(e,t,r)=>{let n=Hr(e,t);return e.pieces[n>=0?n:Hr(e,r==="start"?t-1:t+1)]},ns=(e,t)=>{let r=Hr(e,t);if(r<0)return os(e,t-1);let n=e.pieces[r];return n.start+n.mapped.start[t-n.plainStart]},os=(e,t)=>{let r=Hr(e,t);if(r<0)return ns(e,t+1);let n=e.pieces[r];return n.start+n.mapped.end[t-n.plainStart]},Yd=()=>({from:0,runStart:-1,last:0,periodicEnd:-1,window:"",windowStart:0,windowEnd:0,closedStart:0,closedEnd:-1}),jd=Object.freeze({kind:"done"}),jn=Object.freeze({kind:"slice"}),Wd=Object.freeze({kind:"clusters"}),zd=(e,t,r,n,o,a)=>{let{plain:i}=e,{text:l,tier:c,periodic:s}=r;for(;;){if(n.closedEnd>=0){if(!o.fits(Te.run))return jn;let h=Xi(e,n.closedStart,"start"),R=Xi(e,n.closedEnd-1,"end");if(h.mapped===null)return{kind:"map",piece:h};if(R.mapped===null)return{kind:"map",piece:R};if(e.isCut&&e.clusters===void 0)return Wd;let D=t(e.offset+ns(e,n.closedStart)),S=t(e.offset+os(e,n.closedEnd-1)-1)+1;n.closedEnd=-1;let E=e.clusters;E==null?a(D,S,c):a(E.clusterStarts[D-E.start],E.clusterEnds[S-1-E.start],c),o.charge(Te.run);continue}if(s!==null&&n.periodicEnd>=0){if(!o.fits(nt))return jn;let{period:h,continuation:R}=s,D=n.periodicEnd,S=Math.min(i.length,D+Math.max(es,R.length)),E=D;for(;E+R.length<=S&&i.startsWith(R,E);)E+=R.length;let M=E+R.length>S&&S<i.length;if(!M)for(;E<i.length&&i.charCodeAt(E)===i.charCodeAt(E-h);)E++;if(o.charge((E-D)*Te.scan),M){n.periodicEnd=E;continue}n.periodicEnd=-1,n.last+=Math.floor((E-n.last-l.length)/h)*h,n.from=n.last+l.length-h+1;continue}if(n.from<0){if(n.runStart<0)return jd;n.closedStart=n.runStart,n.closedEnd=n.last+l.length,n.runStart=-1;continue}if(!o.fits(nt))return jn;n.from>=n.windowEnd&&(n.windowStart=n.from,n.windowEnd=n.from+r.windowStarts,n.window=i.slice(n.from,n.windowEnd+l.length-1));let m=n.from-n.windowStart,u=n.window.indexOf(l,m);if(u<0){o.charge((n.window.length-m)*Te.scan),n.from=n.windowStart+n.window.length===i.length?-1:n.windowEnd;continue}o.charge((u+l.length-m)*Te.scan);let f=n.windowStart+u;(n.runStart<0||f>=n.last+l.length)&&(n.runStart>=0&&(n.closedStart=n.runStart,n.closedEnd=n.last+l.length),n.runStart=f),n.last=f,s===null?n.from=f+1:n.periodicEnd=f+l.length}};function*Gd(e,t,r,n,o){if(t.length===0)return;let a=e.length*Te.split;n.fits(a)||(yield);let i=ei(e),l=[],c=[];vn(i.text,(m,u)=>{l.push(u),c.push(u+m.length)}),n.charge(a);let s=m=>i.rawIndex===null?m:i.rawIndex[m];for(let m=0;m<l.length;m++){let u=l[m],f=i.text.slice(u,c[m]),h=f.length*Te.plan;n.fits(h)||(yield);let R=Ir(f,r);n.charge(h);let D=[],S="";for(let M of R.chunks){let U="",I=[];for(let T of M){let V=(T.end-T.start)*Te.normalize;n.fits(V)||(yield);let L=kn(T.start===0&&T.end===f.length?f:f.slice(T.start,T.end),r).text;n.charge(V),L.length>0&&I.push({start:T.start,end:T.end,text:L,chunkStart:U.length}),U+=L}if(U.length!==0){S.length>0&&(S+=" ");for(let T of I)D.push({start:T.start,end:T.end,text:T.text,plainStart:S.length+T.chunkStart,mapped:null});S+=U}}if(S.length===0)continue;let E={offset:u,plain:S,pieces:D,isCut:!Ud(R,f),lastPiece:0,clusters:void 0};for(let M of t){let U=Yd();for(;;){let I=zd(E,s,M,U,n,o);if(I.kind==="done")break;if(I.kind==="slice"){yield;continue}if(I.kind==="clusters"){E.clusters=yield*$d(e,s(u),s(u+f.length-1)+1,n);continue}let{piece:T}=I,V=(T.end-T.start)*Te.map;n.fits(V)||(yield);let L=f.slice(T.start,T.end);T.mapped=Hd(ni(L,Ir(L,r)),T.text),n.charge(V)}}}}function*Kd(e,t,r,n){let o=new Int32Array(Or.length),a=0,i=Yn;for(let l=0;l<=e;l+=Qi){let c=Math.min(e+1,l+Qi),s=(c-l)*Te.sweep;r.fits(s)||(yield);for(let m=l;m<c;m++){let u=Yn;for(let f=Or.length-1;f>=0;f--){let h=Or[f];o[h]+=t[h][m],o[h]>0&&(u=h)}if(u!==i){if(i!==Yn&&!n(a,m,i))return!1;a=m,i=u}}r.charge(s)}return!0}function*Jd(e,t,r,n,o){let a=null;return yield*Gd(e,t,r,n,(l,c,s)=>{a===null&&(a=Or.map(()=>new Int32Array(e.length+1))),a[s][l]++,a[s][c]--}),a===null?!0:yield*Kd(e.length,a,n,o)}var Qd=(e,t,r,n)=>{let o=qd(t),a=[],i=(c,s,m)=>(a.push(c,s,m),a.length<=3*r.maxRanges);return rs(function*(){return(yield*Jd(e,o,r.maxLength,n,i))?{dense:!1,ranges:a}:{dense:!0}}())};var as=(e,t)=>{if(e.combine==="intersection"||e.sets.length===1)return e.sets.flatMap(r=>r.words);if(t===null)throw new Error(`[daily-report] search marks: a union of ${e.sets.length} keywords needs the report's mask of matched keywords`);return e.sets.flatMap((r,n)=>(t&1<<n)===0?[]:r.words)},is=e=>{let t=[],r=(n,o)=>{typeof o=="string"&&o.length>0&&t.push({key:n,value:o})};for(let n of mo)r(Je.field(n),e[n]);e.interviewers.forEach((n,o)=>{r(Je.interviewer(o,"name"),n.name),r(Je.interviewer(o,"affiliation"),n.affiliation)}),e.attachments.forEach((n,o)=>{r(Je.attachment(o),n.fileName)}),e.externalComments.forEach((n,o)=>{r(Je.comment(Qr(o),"author"),n.name),r(Je.comment(Qr(o),"content"),n.text)});for(let n of e.postedComments)r(Je.comment(n.id,"author"),n.userName),r(Je.comment(n.id,"content"),n.content);return t};function*Xd(e,t){let r=en;for(let n=0;n<e.length;n+=Fr){let o=Math.min(e.length,n+Fr),a=(o-n)*Te.linear;t.fits(a)||(yield),r=tn(r,e,n,o),t.charge(a)}return r}var ss=async(e,t,r,n)=>{let o=0,a=0,i=async s=>{for(;!s.step();)await r(),n.startSlice();return s.result()},l=async(s,m)=>{if(!m&&a>t.maxRanges)return null;let u={};for(let{key:f,value:h}of s.fields){if(!m&&o+h.length>t.maxUnits)return null;let R=await i(rs(Xd(h,n))),D=await i(Qd(h,s.alternatives,{maxLength:Ln,maxRanges:t.maxFieldRanges},n));if(o+=h.length,D.dense){u[f]={fingerprint:R,dense:!0};continue}if(u[f]={fingerprint:R,ranges:D.ranges},a+=D.ranges.length/3,!m&&a>t.maxRanges)return null}return u},c=[];for(let s=0;s<e.length;s++){let m=e[s],u=await l(m,c.length===0);if(u===null)return{reports:c,deferred:e.slice(s).map(f=>f.reportHubId)};c.push({reportHubId:m.reportHubId,matchedSets:m.matchedSets,fields:u})}return{reports:c,deferred:[]}};var ot=e=>(0,b.getColumns)(e),ls=or([]),_e=(e,t)=>{if(!e)return null;let r=e instanceof Date?e:new Date(e);if(Number.isNaN(r.getTime()))return typeof e=="string"?e:null;let n=r.getFullYear(),o=n<0?`-${String(-n).padStart(4,"0")}`:String(n).padStart(4,"0"),a=String(r.getMonth()+1).padStart(2,"0"),i=String(r.getDate()).padStart(2,"0");if(t==="YYYY-MM-DD")return`${o}-${a}-${i}`;let l=String(r.getHours()).padStart(2,"0"),c=String(r.getMinutes()).padStart(2,"0"),s=String(r.getSeconds()).padStart(2,"0");return`${o}-${a}-${i} ${l}:${c}:${s}`},ep=e=>{let{length:t}=e;if(t===void 0)throw oe("tables.hub.title","a character column with a declared length",t);return re("tables.hub.title.length",t,1)},cs=e=>e===""?null:e,tp=Object.freeze([]),zn=(e,t,r)=>{let n=e.get(t);n?n.push(r):e.set(t,[r])},Ur=(e,t)=>e.get(t)??tp,us=(e,t)=>[e,t].filter(r=>typeof r=="string"&&r.length>0).join(wr),rp=e=>{if(!Array.isArray(e)||e.length===0||e.some(t=>typeof t!="string"||t.trim().length===0)||new Set(e).size!==e.length)throw oe("draftLabelNames","one or more non-blank label names",e);return Object.freeze([...e])},np=(e,t)=>{let r="the request's AbortSignal (new AbortController().signal for a call that is never aborted)";if(t===void 0)throw Ke(`${e}: options.signal`,r);if(typeof t!="object"||t===null)throw oe(`${e}: options`,"an object carrying the request's AbortSignal",t);let{signal:n}=t;if(n===void 0)throw Ke(`${e}: options.signal`,r);if(!(n instanceof AbortSignal))throw oe(`${e}: options.signal`,r,n);return n},op=e=>{let t=new Set;return e.filter(r=>{let n=r.toLowerCase();return t.has(n)?!1:(t.add(n),!0)})};function $r(e){let{db:t,tables:r,userTable:n,resolveUserId:o,encodeUserId:a,redis:i,cache:l,epochs:c}=e,{hub:s,internal:m,comment:u,label:f,hubLabel:h,userStatus:R}=r,D=e.externalSources??[],S=rp(e.draftLabelNames),E=S[0],M=be(e.logger,1,"Service");br(e);let U=La(e.attachments),I=ep(s.title),T=d=>(0,Lt.runWithTransactionRetry)(p=>t.transaction(y=>p(()=>d(y))),e.transactionRetry),V=e.search===void 0?null:Fi(e.search,D.map(d=>d.sourceType)),L={hub:s,hubLabel:h,label:f},$=V===null?null:zi({tables:{...L,search:V.tables},draftLabelNames:S});V!==null&&On();let de=null,pe=async()=>{if(V===null)return null;if(de===null){let d=await On(),p=V.externalSourceTexts;de=Ji({hub:s,tables:V.tables,loadSources:(y,g)=>zs(y,g,p),inTransaction:T,normalizerVersion:d})}return de},De=e.idsTtlMs??18e4,K="daily-report:ids:epoch",le=e.businessDateTtlMs??3e5,ne="daily-report:date-epoch:",ce="daily-report:detail-epoch:",Re=`${e.streamKey??"daily-report:sse-stream"}:v3`,ze=e.streamMaxLen??1e4,ae=d=>c.incrementEpoch(d),Ne=d=>Bt(s.sourceType,d),Fe=(d,p)=>vr(L,d,S,p),at=b.sql`CASE WHEN ${kr(L,S)} THEN 1 ELSE 0 END`,it=async d=>{let[p]=await t.select({id:s.id}).top(1).from(s).where((0,b.and)((0,b.eq)(s.id,d),kr(L,S)));return p!==void 0},Ee=async(d,p)=>{let y=await i?.getClient();if(!y){M.warn(`[SSE] Redis client unavailable (${p})`);return}let g=JSON.stringify(d),_=Buffer.byteLength(g);if(_>6356992){M.warn(`[SSE] Event too large (${p}): ${_} bytes > ${6356992}; not published`);return}let C=ue();try{await y.xAdd(Re,"*",{data:g},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:ze}});let x=ue()-C;x>1e3&&M.warn(`[SSE] Slow publish (${p}): ${x}ms`)}catch(x){M.error(`[SSE] Redis publish failed (${p}):`,x)}},w=async()=>{try{let d=await i?.getClient();if(d===void 0)return null;let[p]=await d.xRevRange(Re,"+","-",{COUNT:1});return p===void 0?null:p.id}catch(d){return M.error("SSE stream anchor read failed",d),null}},H=d=>d==null||d===""?null:/^\d+$/.test(d)?a(Number(d)):d,v=()=>{let d={};for(let p of D)d[`ext_${p.sourceType}`]=ot(p.table);return d},N=d=>{let p=d;for(let y of D)p=p.leftJoin(y.table,(0,b.and)((0,b.eq)(s.sourceType,y.sourceType),(0,b.eq)(s.sourceIdNum,y.idColumn)));return p},B=d=>{let{hub:p,internal:y}=d,g=p.summary,_=[],C=null,x=null,F=null,k=null,Y=null,X=null,Q=[],W=D.find(te=>te.sourceType===p.sourceType),ee=W?d[`ext_${W.sourceType}`]:void 0;if(W&&ee){let te=W.mapRow(ee);te.content!==void 0&&(g=te.content),te.employeeName!==void 0&&(X=te.employeeName),te.category!==void 0&&(C=te.category),te.creationCategory!==void 0&&(x=te.creationCategory),te.visitTimeFrom!==void 0&&(F=te.visitTimeFrom),te.visitTimeTo!==void 0&&(k=te.visitTimeTo),te.customerName!==void 0&&(Y=te.customerName),te.interviewers!==void 0&&(_=te.interviewers),te.externalComments!==void 0&&(Q=te.externalComments)}else p.sourceType==="Internal"&&y&&(g=y.body);return{content:g,author:d.creatorName??H(p.createdBy)??"",employeeName:X??d.creatorName??H(p.createdBy),updatedBy:H(p.updatedBy),category:C,creationCategory:x,visitTimeFrom:F,visitTimeTo:k,customerName:Y,interviewers:_,externalComments:Q}},z=d=>{if(d===1)return!0;if(d===0)return!1;throw new Error(`[daily-report] a detail row's hasDraftLabel must be 1 or 0 (the read must select draftLabelFlag); got ${Gr(d)}`)},J=d=>d.creationCategory!==null&&S.includes(d.creationCategory),G=(d,p)=>z(d.hasDraftLabel)?!0:J(p),Z=d=>d.some(J)?Qn():Promise.resolve(null),O=(d,p,y,g,_)=>{let{hub:C}=p,x=(p.labels??[]).map(Y=>({id:Y.id,name:Y.name,color:Y.color})),F=p.postedCommentRows??[],k=Pe(d.commentable,C.sourceType);return g!==null&&J(y)&&!x.some(Y=>Y.id===g)&&x.push({id:g,name:E,color:null}),{reportHubId:C.id,date:_e(C.businessDate,"YYYY-MM-DD"),author:y.author,userId:C.userId?a(C.userId):"",sourceType:C.sourceType??"Internal",createdAt:_e(C.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:_e(C.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:y.updatedBy,employeeName:y.employeeName,category:y.category,creationCategory:y.creationCategory,visitTimeFrom:y.visitTimeFrom,visitTimeTo:y.visitTimeTo,customerName:y.customerName,interviewers:y.interviewers,subject:C.title,content:y.content,externalComments:k?y.externalComments:[],isRead:p.isRead??!1,isStarred:p.isStarred??!1,isDraft:G(p,y),labels:x,postedComments:F.filter(Y=>Ja({authorUserId:Y.userId},C.sourceType,_??null,d)).map(Y=>({...Y,userId:a(Y.userId),isMine:_?Y.userId===_:!1})),attachments:p.attachments}},ie=async(d,p)=>(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).from(s).where((0,b.and)((0,b.isNull)(s.deletedAt),Fe(p,"author-or-authorless"),Ne(d.visible))).orderBy((0,b.desc)(s.businessDate),(0,b.desc)(s.id))).map(g=>({...g,businessDate:_e(g.businessDate,"YYYY-MM-DD")})),Se=async(d,p,y)=>{let g=await At(p);return g?Le(d.visible)?[]:(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).top(y).from(s).where((0,b.and)((0,b.isNull)(s.deletedAt),Fe(g,"author-or-authorless"),Ne(d.visible))).orderBy((0,b.desc)(s.businessDate),(0,b.desc)(s.id))).map(C=>({...C,businessDate:_e(C.businessDate,"YYYY-MM-DD")})):[]},ye=async(d,p)=>{let y=await N(t.select({hub:ot(s),internal:ot(m),creatorName:n.displayName,hasDraftLabel:at,...v()}).from(s)).leftJoin(m,(0,b.eq)(s.id,m.hubId)).leftJoin(n,(0,b.eq)(s.userId,n.id)).where((0,b.and)((0,b.eq)(s.businessDate,b.sql`${p}`),(0,b.isNull)(s.deletedAt),Ne(d.visible))).orderBy((0,b.desc)(s.id)),g=await er(y.map(x=>x.hub.id)),_=y.map(B),C=await Z(_);return y.map((x,F)=>O(d,{...x,attachments:g.get(x.hub.id)??[]},_[F],C))},Zt=new Map,At=async d=>{if(!e.disableUserIdCache&&Zt.has(d))return Zt.get(d)??null;let p=await o(d);return p!==null&&!e.disableUserIdCache&&Zt.set(d,p),p},Cs=async(d,p,{forceRefresh:y=!1,snapshot:g=!1,ttlMsOverride:_,onFetchStart:C,admission:x}={})=>{let F=await At(p);if(!F)return{items:[],streamAnchor:null,snapshot:ls};if(Le(d.visible))return{items:[],streamAnchor:await w(),snapshot:ls};let k=mi(F,Vt(d)),[Y]=await l.getOrFetch({cacheKey:k,fetcher:async()=>{let X=await w(),Q=await ie(d,F);if(!lo(Q)){M.warn("ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)");let W=[...Q].sort(Jr);return[{items:W,streamAnchor:X,snapshot:or(W)}]}return[{items:Q,streamAnchor:X,snapshot:or(Q)}]},onFetchStart:C,forceRefresh:y,snapshot:g,admission:x,ttlMsOverride:_??De,epochKey:K,refreshAheadRatio:.5});if(Y===void 0)throw new Error("[daily-report] getDailyReportIdsByExternalId: the ids cache returned no record");return Y},Ms=(d,p,{forceRefresh:y=!1,snapshot:g=!1,ttlMsOverride:_}={})=>{let C=ke(p);return C?Le(d.visible)?Promise.resolve([]):l.getOrFetch({cacheKey:yi(C,Vt(d)),fetcher:()=>ye(d,C),forceRefresh:y,snapshot:g,ttlMsOverride:_??le}):Promise.resolve([])},Jn=async d=>{let[p]=await d.select({id:f.id}).top(1).from(f).where((0,b.eq)(f.name,E)).orderBy((0,b.asc)(f.id));return p===void 0?null:p.id},Qn=()=>Jn(t),Ps=(d,p)=>p!=null?"absent":d!=null?"present":"unknown",er=async d=>{let p=new Map,y=r.attachment;if(d.length===0||!y||U===null)return p;let g=U.idCodec,_=U.thumbnails!==null,C=await t.select({id:y.id,hubId:y.hubId,fileName:y.fileName,fileType:y.fileType,fileSize:y.fileSize,createdAt:y.createdAt,objectCheckedAt:y.objectCheckedAt,objectMissingAt:y.objectMissingAt}).from(y).where((0,b.inArray)(y.hubId,d)).orderBy((0,b.asc)(y.createdAt),(0,b.asc)(y.id));for(let x of C){let F=x.fileType?String(x.fileType):null,k=x.fileSize!=null?Number(x.fileSize):null,Y=Ps(x.objectCheckedAt,x.objectMissingAt),X={id:g.encode(Number(x.id)),fileName:String(x.fileName),fileType:F,fileSize:k,createdAt:_e(x.createdAt,"YYYY-MM-DD HH:mm:ss"),state:Y,hasThumbnail:_&&Y!=="absent"&&Sr({fileType:F,fileSize:k},U.maxBytes)},Q=p.get(Number(x.hubId));Q?Q.push(X):p.set(Number(x.hubId),[X])}return p},Ls=async(d,p,y)=>{let g=r.attachment;return!g||Le(d.visible)?null:(await t.select({fileName:g.fileName,filePath:g.filePath,fileType:g.fileType,fileSize:g.fileSize}).top(1).from(g).innerJoin(s,(0,b.eq)(s.id,g.hubId)).where((0,b.and)((0,b.eq)(g.id,p),(0,b.isNull)(s.deletedAt),Fe(y,"author"),Ne(d.visible))))[0]??null},Ns=async d=>{let p=r.attachment;if(!p)return;let y=new Date;try{await t.update(p).set({objectCheckedAt:y,objectMissingAt:y,updatedAt:y}).where((0,b.eq)(p.id,d))}catch(g){M.error("markAttachmentMissing failed",g)}},ks=async d=>{let p=r.attachment;if(!p)return;let y=new Date;try{await t.update(p).set({objectCheckedAt:y,objectMissingAt:null,updatedAt:y}).where((0,b.eq)(p.id,d))}catch(g){M.error("markAttachmentPresent failed",g)}},Br=async(d,p,y)=>{let g=await N(t.select({hub:ot(s),internal:ot(m),isRead:R.isRead,isStarred:R.isStarred,creatorName:n.displayName,hasDraftLabel:at,...v()}).from(s)).leftJoin(m,(0,b.eq)(s.id,m.hubId)).leftJoin(R,(0,b.and)((0,b.eq)(s.id,R.hubId),(0,b.eq)(R.userId,p))).leftJoin(n,(0,b.eq)(s.userId,n.id)).where((0,b.and)(y,(0,b.isNull)(s.deletedAt),Fe(p,"author"),Ne(d.visible))).orderBy((0,b.desc)(s.id));if(g.length===0)return[];let _=g.map(W=>W.hub.id),C=await t.select({hubId:h.hubId,id:f.id,name:f.name,color:f.color}).from(h).innerJoin(f,(0,b.eq)(h.labelId,f.id)).where((0,b.inArray)(h.hubId,_)),x=await t.select({hubId:u.hubId,id:u.id,body:u.body,createdAt:u.createdAt,userId:u.userId,userName:n.displayName}).from(u).leftJoin(n,(0,b.eq)(u.userId,n.id)).where((0,b.inArray)(u.hubId,_)).orderBy((0,b.asc)(u.createdAt)),F=await er(_),k=new Map,Y=new Map;for(let W of C){let ee=k.get(W.hubId);ee||(ee=[],k.set(W.hubId,ee)),ee.push({id:W.id,name:W.name,color:W.color})}for(let W of x){let ee=Y.get(W.hubId);ee||(ee=[],Y.set(W.hubId,ee)),ee.push({id:W.id,content:W.body,createdAt:_e(W.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:W.userId,userName:W.userName||""})}let X=g.map(B),Q=await Z(X);return g.map((W,ee)=>{let te=W.hub.id;return O(d,{...W,attachments:F.get(te)??[],labels:k.get(te)||[],postedCommentRows:Y.get(te)||[]},X[ee],Q,p)})},vs=async(d,p,y,{forceRefresh:g=!1,snapshot:_=!1,ttlMsOverride:C,admission:x}={})=>{let F=await At(y);if(!F)return[];let k=ke(p);if(!k)return[];if(Le(d.visible))return[];let Y=hi(k,F,Vt(d));return l.getOrFetch({cacheKey:Y,fetcher:()=>Br(d,F,(0,b.eq)(s.businessDate,b.sql`${k}`)),forceRefresh:g,snapshot:_,admission:x,ttlMsOverride:C??le,epochKey:`${ne}${k}`})},Nt=async(d,p,y,{forceRefresh:g=!1,snapshot:_=!1,ttlMsOverride:C,admission:x}={})=>{if(Le(d.visible))return null;let F=fi(p,y,Vt(d));return(await l.getOrFetch({cacheKey:F,fetcher:async()=>{let Y=await N(t.select({hub:ot(s),internal:ot(m),isRead:R.isRead,isStarred:R.isStarred,creatorName:n.displayName,hasDraftLabel:at,...v()}).from(s)).leftJoin(m,(0,b.eq)(s.id,m.hubId)).leftJoin(R,(0,b.and)((0,b.eq)(s.id,R.hubId),(0,b.eq)(R.userId,y))).leftJoin(n,(0,b.eq)(s.userId,n.id)).where((0,b.and)((0,b.eq)(s.id,p),(0,b.isNull)(s.deletedAt),Fe(y,"author"),Ne(d.visible)));if(Y.length===0)return[];let X=Y[0].hub.id,Q=await t.select({id:f.id,name:f.name,color:f.color}).from(h).innerJoin(f,(0,b.eq)(h.labelId,f.id)).where((0,b.eq)(h.hubId,X)),W=await t.select({id:u.id,body:u.body,createdAt:u.createdAt,userId:u.userId,userName:n.displayName}).from(u).leftJoin(n,(0,b.eq)(u.userId,n.id)).where((0,b.eq)(u.hubId,X)).orderBy((0,b.asc)(u.createdAt)),ee=await er([X]),te=Q.map(Ge=>({id:Ge.id,name:Ge.name,color:Ge.color})),Yr=W.map(Ge=>({id:Ge.id,content:Ge.body,createdAt:_e(Ge.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:Ge.userId,userName:Ge.userName||""})),to=B(Y[0]),al=await Z([to]);return[O(d,{...Y[0],attachments:ee.get(X)??[],labels:te,postedCommentRows:Yr},to,al,y)]},forceRefresh:g,snapshot:_,admission:x,ttlMsOverride:C??le,epochKey:`${ce}${p}`}))[0]??null},Os=async(d,p,y,g={})=>{let _=await At(y);return _?Nt(d,p,_,g):null},Fs=async(d,p,y)=>{if(p.length>Ie.maxDetailIds)throw oe("getDailyReportDetailsByIdsByExternalId: reportHubIds",`at most ${Ie.maxDetailIds} ids`,p.length);let g=await At(y);return!g||p.length===0?[]:Le(d.visible)?[]:Br(d,g,(0,b.inArray)(s.id,[...p]))},Hs=async(d,p)=>{let[y]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt}).top(1).from(s).where((0,b.and)((0,b.eq)(s.id,d),Fe(p,"author")));return y??null},Vr=async(d,p,y)=>{let g=await Hs(p,y);if(!g||g.deletedAt||!Pe(d.visible,g.sourceType))throw new Error("Not Found")},Us=async(d,p,y,g,_,C)=>{await Vr(d,y,p);let x=await t.select().top(1).from(R).where((0,b.and)((0,b.eq)(R.hubId,y),(0,b.eq)(R.userId,p))),F;if(x.length>0?x[0].isStarred!==_?F=(await t.update(R).set({isStarred:_,updatedAt:new Date,updatedBy:String(p)}).output().where((0,b.and)((0,b.eq)(R.hubId,y),(0,b.eq)(R.userId,p))))[0]:F=x[0]:F=(await t.insert(R).output().values({hubId:y,userId:p,isStarred:_,isRead:!1,createdAt:new Date,createdBy:String(p),updatedAt:new Date,updatedBy:String(p)}))[0],g){let k=ke(g);k&&(l.invalidatePrefix(Mt(k,p)),await ae(`${ne}${k}`))}return l.invalidatePrefix(Mr(y,p)),await ae(`${ce}${y}`),await Ee(lr.parse({type:"status-update",reportHubId:y,recipientRawUserId:p,statusType:"star",value:_,clientTempId:C}),"setStarStatus"),F},$s=async(d,p,y,g,_,C)=>{await Vr(d,y,p);let x=await t.select().top(1).from(R).where((0,b.and)((0,b.eq)(R.hubId,y),(0,b.eq)(R.userId,p))),F;if(x.length>0?x[0].isRead!==_?F=(await t.update(R).set({isRead:_,updatedAt:new Date,updatedBy:String(p)}).output().where((0,b.and)((0,b.eq)(R.hubId,y),(0,b.eq)(R.userId,p))))[0]:F=x[0]:F=(await t.insert(R).output().values({hubId:y,userId:p,isRead:_,isStarred:!1,createdAt:new Date,createdBy:String(p),updatedAt:new Date,updatedBy:String(p)}))[0],g){let k=ke(g);k&&(l.invalidatePrefix(Mt(k,p)),await ae(`${ne}${k}`))}return l.invalidatePrefix(Mr(y,p)),await ae(`${ce}${y}`),await Ee(lr.parse({type:"status-update",reportHubId:y,recipientRawUserId:p,statusType:"read",value:_,clientTempId:C}),"setReadStatus"),F},Xn=async(d,p)=>{if(p!==null)return await it(d)?p:void 0},Bs=async(d,p,y,g,_,C)=>{let[x]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt,userId:s.userId}).top(1).from(s).where((0,b.eq)(s.id,y));if(!x||x.deletedAt)throw new Error("Not Found");if(await Vr(d,y,p),!Pe(d.commentable,x.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(x.sourceType.toLowerCase()!=="internal")throw new Error("Comments are restricted for external daily report sources");let F=await Xn(y,x.userId),k=await pe(),Y=await T(async ee=>{let[te]=await ee.insert(u).output().values({hubId:y,userId:p,body:g,createdAt:new Date,createdBy:String(p),updatedAt:new Date,updatedBy:String(p)});return k!==null&&await k.writeHubs(ee,[y]),te}),[X]=await t.select({displayName:n.displayName}).top(1).from(n).where((0,b.eq)(n.id,p)),Q=X?.displayName??"";if(_){let ee=ke(_);ee&&(l.invalidatePrefix(Wt(ee)),await ae(`${ne}${ee}`))}l.invalidatePrefix(je(y)),await ae(`${ce}${y}`);let W={id:Y.id,userId:a(Y.userId),userName:Q,content:Y.body,createdAt:_e(Y.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await Ee(sn.parse({type:"comment-add",reportHubId:y,comment:W,clientTempId:C,recipientRawUserId:F,sourceType:x.sourceType}),"addComment"),W},Vs=async(d,p)=>await d.select().top(1).from(u).where((0,b.eq)(u.id,p)),qs=async(d,p,y,g,_,C)=>{let x=await Vs(t,g);if(x.length===0)throw new Error("Not Found");if(x[0].hubId!==y)throw new Error("Not Found");let[F]=await t.select({userId:s.userId,sourceType:s.sourceType}).top(1).from(s).where((0,b.eq)(s.id,x[0].hubId));if(!(F&&Pe(d.visible,F.sourceType)))throw new Error("Not Found");if(x[0].userId!==p)throw new Error("Unauthorized");let k=await Xn(y,F.userId),Y=await pe();if(await T(async X=>{await X.delete(u).where((0,b.eq)(u.id,g)),Y!==null&&await Y.writeHubs(X,[y])}),_){let X=ke(_);X&&(l.invalidatePrefix(Wt(X)),await ae(`${ne}${X}`))}l.invalidatePrefix(je(y)),await ae(`${ce}${y}`),await Ee(ln.parse({type:"comment-delete",reportHubId:y,commentId:g,clientTempId:C,recipientRawUserId:k,sourceType:F?.sourceType}),"deleteComment")},Ys=async(d,p)=>{let y=new Map,g=r.attachment;if(!g||U===null)return y;let _=await d.select({hubId:g.hubId,fileName:g.fileName}).from(g).where((0,b.inArray)(g.hubId,[...p])).orderBy((0,b.asc)(g.hubId),(0,b.asc)(g.createdAt),(0,b.asc)(g.id));for(let C of _)zn(y,Number(C.hubId),String(C.fileName));return y},js=async(d,p,y)=>{let g=new Map;for(let[_,C]of y){let x=new Map;for(let{hub:k}of p)k.sourceType===_&&k.sourceIdNum!==null&&x.set(k.sourceIdNum,k.id);if(x.size===0)continue;let F=await C(d,[...x.keys()]);for(let[k,Y]of F){let X=x.get(k);if(X===void 0)throw oe(`search.externalSourceTexts.${_} answer key`,"a source id that was asked for",k);if(!(Array.isArray(Y)&&Y.every(Q=>typeof Q=="string")))throw oe(`search.externalSourceTexts.${_} answer for ${k}`,"an array of strings",Y);g.set(X,Y)}}return g},Ws=(d,p)=>{let y=B(d),g=[["subject",d.hub.title],["content",y.content],["author",y.author],["employeeName",y.employeeName],["updatedBy",y.updatedBy],["category",y.category],["creationCategory",y.creationCategory],["customerName",y.customerName]];for(let C of y.interviewers)g.push(["interviewerName",C.name??null],["interviewerAffiliation",C.affiliation??null]);for(let C of p.labelNames)g.push(["label",C]);for(let C of p.attachmentNames)g.push(["attachment",C]);for(let C of p.extraTexts)g.push(["extra",C]);let _=[];for(let C of y.externalComments)_.push({authorUserId:null,text:us(C.name,C.text)});for(let C of p.postedComments)_.push({authorUserId:C.userId,text:us(C.userName,C.body)});return{hubId:d.hub.id,fields:g,comments:_,filterValues:{authorName:y.employeeName,customerName:y.customerName}}},zs=async(d,p,y)=>{let g=[];for(let _ of(0,Lt.chunk)(p,Lt.MAX_IN_LIST)){let C=await N(d.select({hub:ot(s),internal:ot(m),creatorName:n.displayName,...v()}).from(s)).leftJoin(m,(0,b.eq)(s.id,m.hubId)).leftJoin(n,(0,b.eq)(s.userId,n.id)).where((0,b.inArray)(s.id,[..._])).orderBy((0,b.asc)(s.id)),x=new Map,F=await d.select({hubId:h.hubId,name:f.name}).from(h).innerJoin(f,(0,b.eq)(h.labelId,f.id)).where((0,b.inArray)(h.hubId,[..._])).orderBy((0,b.asc)(h.hubId),(0,b.asc)(f.id));for(let W of F)zn(x,W.hubId,W.name);let k=new Map,Y=await d.select({hubId:u.hubId,userId:u.userId,body:u.body,userName:n.displayName}).from(u).leftJoin(n,(0,b.eq)(u.userId,n.id)).where((0,b.inArray)(u.hubId,[..._])).orderBy((0,b.asc)(u.hubId),(0,b.asc)(u.createdAt),(0,b.asc)(u.id));for(let W of Y)zn(k,W.hubId,W);let X=await Ys(d,_),Q=await js(d,C,y);for(let W of C){let ee=W.hub.id;g.push(Ws(W,{labelNames:Ur(x,ee),postedComments:Ur(k,ee),attachmentNames:Ur(X,ee),extraTexts:Ur(Q,ee)}))}}return g},Gs=(d,p,y)=>$===null?Promise.reject(new Error("[daily-report] searchDailyReports: the search setting is not configured")):$.search(t,{criteria:y,viewerUserId:p,scope:d}),Zn=Object.freeze(op(["Internal",...D.map(d=>d.sourceType)])),Ks=async(d,p)=>{if($===null)throw new Error("[daily-report] listDailyReportSearchFacets: the search setting is not configured");let y=Zn.filter(C=>Pe(d.visible,C)),g=await $.facetValues(t,{column:"authorName",viewerUserId:p,scope:d}),_=await $.facetValues(t,{column:"customerName",viewerUserId:p,scope:d});return{sourceTypes:y,authors:g,customers:_}},Js=async(d,p,y,g,_)=>{let C=np("markDailyReportSearchHits",_);if($===null)throw new Error("[daily-report] markDailyReportSearchHits: the search setting is not configured");if(g.length>Ie.maxDetailIds)throw oe("markDailyReportSearchHits: reportHubIds",`at most ${Ie.maxDetailIds} ids`,g.length);let x=ar(Yt(y));if(g.length===0||Le(d.visible))return{wordsDigest:x,reports:[],deferred:[]};C.throwIfAborted();let F=await Br(d,p,(0,b.inArray)(s.id,[...g]));C.throwIfAborted();let k=y.combine==="union"&&y.sets.length>=2&&F.length>0?await $.matchedSets(t,{plan:y,viewerUserId:p,scope:d,ids:F.map(W=>W.reportHubId)}):null,Y=F.map(W=>{let ee=k===null?null:k.get(W.reportHubId),te=ee===void 0?0:ee;return{reportHubId:W.reportHubId,matchedSets:te,alternatives:as(y,te).flatMap(Yr=>Yr.alternatives),fields:is(W)}}),Q=await ss(Y,Wn,async()=>{await new Promise(W=>setImmediate(W)),C.throwIfAborted()},ts(Wn,ue));return{wordsDigest:x,reports:Q.reports,deferred:Q.deferred}},Qs=async d=>{let p=await pe();if(p===null)throw new Error("[daily-report] reconcileSearchIndex: the search setting is not configured");return p.reconcile(t,d)},Xs=async(d,p,y)=>{if(!nr(p))throw oe("createDailyReport: businessDate","a business-date key in the canonical form YYYY-MM-DD naming a day from 0001-01-01 to 9999-12-31",p);M.info("createDailyReport called",{userId:d,businessDate:p});let[g]=await t.select({displayName:n.displayName}).from(n).where((0,b.eq)(n.id,d)),_=g?.displayName??a(d),C=await pe();try{let x=await T(async k=>{M.info("Starting transaction");let Y=await Jn(k);if(Y===null)throw new Error(`[daily-report] createDailyReport: the canonical draft label ${JSON.stringify(E)} (draftLabelNames[0]) does not exist; create that label before creating reports (a report without it would be visible to every viewer)`);let X=`internal-temp-${Date.now()}-${Math.random()}`,[Q]=await k.insert(s).output().values({sourceType:"Internal",sourceId:X,businessDate:new Date(`${p}T00:00:00Z`),userId:d,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(d),updatedAt:new Date,updatedBy:String(d)});await k.update(s).set({sourceId:String(Q.id)}).where((0,b.eq)(s.id,Q.id)),M.info("Hub created",Q),await k.insert(m).values({hubId:Q.id,body:"",createdAt:new Date,createdBy:String(d),updatedAt:new Date,updatedBy:String(d)}),M.info("Internal created"),await k.insert(h).values({hubId:Q.id,labelId:Y,createdAt:new Date,createdBy:String(d)});let W=[{id:Y,name:E,color:null}];return M.info("Label assigned"),C!==null&&await C.writeHubs(k,[Q.id]),{reportHubId:Q.id,date:p,createdAt:_e(Q.createdAt,"YYYY-MM-DD HH:mm:ss"),author:_,userId:a(d),sourceType:"Internal",employeeName:_,updatedBy:a(d),updatedAt:_e(Q.updatedAt,"YYYY-MM-DD HH:mm:ss"),category:null,creationCategory:null,visitTimeFrom:null,visitTimeTo:null,customerName:null,interviewers:[],subject:Q.title,content:"",externalComments:[],isRead:!0,isStarred:!1,isDraft:!0,labels:W,postedComments:[],attachments:[]}});l.invalidatePrefix(Mt(p,d)),l.invalidatePrefix(St),l.invalidatePrefix(Fn(d)),await ae(K),await ae(`${ne}${p}`);let F=await Nt(Me.unrestricted("post-write self read: the writer always sees the row they just wrote"),x.reportHubId,d,{forceRefresh:!0});if(F){let k=await it(F.reportHubId);await Ee(cn.parse({type:"report-create",reportHubId:F.reportHubId,report:F,clientTempId:y,recipientRawUserId:k?d:void 0}),"createDailyReport")}return F??x}catch(x){throw M.error("Error in createDailyReport",x),x}},tr=async(d,p)=>await d.select().top(1).from(s).where((0,b.eq)(s.id,p)),qr=async(d,p,y)=>{await d.update(s).set(y).where((0,b.eq)(s.id,p))},eo=async(d,p,y)=>{await d.update(m).set(y).where((0,b.eq)(m.hubId,p))},Zs=async(d,p,y)=>{await d.delete(h).where((0,b.and)((0,b.eq)(h.hubId,p),(0,b.eq)(h.labelId,y)))},el=async(d,p,y)=>{let g=await tr(t,d);if(!g.length||g[0].deletedAt)throw new Error("Not Found");if(g[0].userId!==p)throw new Error("Unauthorized");if(await T(async _=>{await qr(_,d,{deletedAt:new Date,deletedBy:String(p),updatedAt:new Date,updatedBy:String(p)})}),l.invalidatePrefix(je(d)),l.invalidatePrefix(St),l.invalidatePrefix(Rt),await ae(K),g[0].businessDate){let _=ke(_e(g[0].businessDate,"YYYY-MM-DD"));_&&await ae(`${ne}${_}`)}await Ee(pn.parse({type:"report-delete",reportHubId:d,clientTempId:y,sourceType:g[0].sourceType}),"deleteDailyReport")},tl=async(d,p,y,g)=>{let _=await tr(t,d);if(!_.length||_[0].deletedAt)throw new Error("Not Found");if(_[0].userId!==p)throw new Error("Unauthorized");let C=await pe();await T(async k=>{y.title!==void 0&&await qr(k,d,{title:cs(y.title),updatedAt:new Date,updatedBy:String(p)}),y.content!==void 0&&await eo(k,d,{body:cs(y.content),updatedAt:new Date,updatedBy:String(p)}),C!==null&&await C.writeHubs(k,[d])}),l.invalidatePrefix(je(d)),l.invalidatePrefix(St),await ae(`${ce}${d}`);let x=ke(_e(_[0].businessDate,"YYYY-MM-DD"));x&&(l.invalidatePrefix(Wt(x)),await ae(`${ne}${x}`));let F=await Nt(Me.unrestricted("post-write self read: the writer always sees the row they just wrote"),d,p,{forceRefresh:!0});if(F){let k=await it(d);await Ee(un.parse({type:"report-update",reportHubId:F.reportHubId,report:F,clientTempId:g,recipientRawUserId:k?p:void 0}),"updateDailyReport")}},rl=async(d,p,y)=>{let g=await tr(t,d);if(!g.length)throw new Error("Not Found");if(g[0].userId!==p)throw new Error("Unauthorized");let _=await pe();if(await T(async F=>{await F.delete(h).where((0,b.and)((0,b.eq)(h.hubId,d),ki(L,S))),_!==null&&await _.writeHubs(F,[d])}),l.invalidatePrefix(je(d)),l.invalidatePrefix(St),l.invalidatePrefix(Rt),await ae(K),g[0].businessDate){let F=ke(_e(g[0].businessDate,"YYYY-MM-DD"));F&&await ae(`${ne}${F}`)}let C=ke(_e(g[0].businessDate,"YYYY-MM-DD"));C&&l.invalidatePrefix(Mt(C,p));let x=await Nt(Me.unrestricted("post-write self read: the writer always sees the row they just wrote"),d,p,{forceRefresh:!0});if(x){let F=await it(d);await Ee(dn.parse({type:"report-publish",reportHubId:x.reportHubId,report:x,clientTempId:y,recipientRawUserId:F?p:void 0}),"publishDailyReport")}return x??null},nl=async(d,p)=>{l.invalidatePrefix(St),l.invalidatePrefix(Rt),await ae(K);for(let y of new Set(d))l.invalidatePrefix(je(y)),await ae(`${ce}${y}`);for(let y of new Set(p)){let g=ke(y);g&&await ae(`${ne}${g}`)}},ol=async()=>{l.clearAll(),Zt.clear(),c&&await ae(K),M.info("Server-side DB/SQL caches cleared successfully.")};return{streamKey:Re,streamMaxLen:ze,attachmentDelivery:U,titleMaxLength:I,searchLimits:V===null?null:{concurrency:V.concurrency,rateLimitPerMinute:V.rateLimitPerMinute},searchFilterSourceTypes:Zn,clearCache:ol,invalidateHubReadCaches:nl,getUserIdByExternalId:At,getDailyReportIdsByExternalId:Cs,getDailyReportIdsFirstPageByExternalId:Se,readSseStreamAnchor:w,getDailyReportsByBusinessDate:Ms,getDailyReportsByBusinessDateByExternalId:vs,getDailyReportDetailById:Nt,getDailyReportDetailByIdByExternalId:Os,getDailyReportDetailsByIdsByExternalId:Fs,getDraftLabelId:Qn,searchDailyReports:Gs,markDailyReportSearchHits:Js,listDailyReportSearchFacets:Ks,reconcileSearchIndex:Qs,getAttachmentsByHubIds:er,getAttachmentForUser:Ls,markAttachmentMissing:Ns,markAttachmentPresent:ks,setStarStatus:Us,setReadStatus:$s,addComment:Bs,deleteComment:qs,createDailyReport:Xs,updateDailyReport:tl,publishDailyReport:rl,deleteDailyReport:el,findDailyReportHubById:tr,updateDailyReportHub:qr,updateDailyReportInternal:eo,deleteDailyReportLabel:Zs}}var ds=(e,t,r,n)=>{if(!e)return[];try{let o=JSON.parse(e);return Array.isArray(o)?o.map(r).filter(a=>a!==null):(be(n,1,"ExternalSource").warn(`Unexpected ${t} format: not an array`),[])}catch(o){return be(n,1,"ExternalSource").warn(`Failed to parse ${t}:`,o),[]}};var Qt=require("drizzle-orm"),A=require("drizzle-orm/mssql-core");function ps(e,t){let r=(0,A.mssqlSchema)(e),n=t.userTable,o=r.table("DailyReportHub",{id:(0,A.bigint)("id",{mode:"number"}).identity().notNull(),sourceType:(0,A.nvarchar)("source_type",{length:20}).notNull(),sourceId:(0,A.nvarchar)("source_id",{length:100}).notNull(),sourceIdNum:(0,A.bigint)("source_id_num",{mode:"number"}).generatedAlwaysAs(Qt.sql`TRY_CAST(source_id AS BIGINT)`),businessDate:(0,A.date)("business_date"),userId:(0,A.bigint)("user_id",{mode:"number"}),title:(0,A.nvarchar)("title",{length:200}),summary:(0,A.nvarchar)("summary",{length:"max"}),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull(),deletedAt:(0,A.datetime2)("deleted_at"),deletedBy:(0,A.nvarchar)("deleted_by",{length:50})},u=>[(0,A.primaryKey)({name:`${e}_DailyReportHub_pk`,columns:[u.id]}),(0,A.foreignKey)({name:`${e}_DailyReportHub_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),(0,A.index)(`${e}_DailyReportHub_business_date_index`).on(u.businessDate),(0,A.index)(`${e}_DailyReportHub_updated_at_index`).on(u.updatedAt),(0,A.index)(`${e}_DailyReportHub_source_index`).on(u.sourceType,u.sourceId),(0,A.index)(`${e}_DailyReportHub_user_id_index`).on(u.userId),(0,A.index)(`${e}_DailyReportHub_business_date_id_index`).on((0,Qt.desc)(u.businessDate),(0,Qt.desc)(u.id)),(0,A.index)(`${e}_DailyReportHub_deleted_at_index`).on(u.deletedAt)]),a=r.table("DailyReportInternal",{hubId:(0,A.bigint)("hub_id",{mode:"number"}).notNull(),body:(0,A.nvarchar)("body",{length:"max"}),metadata:(0,A.nvarchar)("metadata",{length:"max"}),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportInternal_pk`,columns:[u.hubId]}),(0,A.foreignKey)({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]})]),i=r.table("DailyReportComment",{id:(0,A.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,A.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,A.bigint)("user_id",{mode:"number"}).notNull(),body:(0,A.nvarchar)("body",{length:"max"}).notNull(),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportComment_pk`,columns:[u.id]}),(0,A.foreignKey)({name:`${e}_DailyReportComment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,A.foreignKey)({name:`${e}_DailyReportComment_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),(0,A.index)(`${e}_DailyReportComment_hub_id_index`).on(u.hubId)]),l=r.table("DailyReportLabel",{id:(0,A.bigint)("id",{mode:"number"}).identity().notNull(),userId:(0,A.bigint)("user_id",{mode:"number"}),name:(0,A.nvarchar)("name",{length:50}).notNull(),color:(0,A.nvarchar)("color",{length:20}),sortOrder:(0,A.int)("sort_order"),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportLabel_pk`,columns:[u.id]}),(0,A.foreignKey)({name:`${e}_DailyReportLabel_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),c=r.table("DailyReportHub_Label",{hubId:(0,A.bigint)("hub_id",{mode:"number"}).notNull(),labelId:(0,A.bigint)("label_id",{mode:"number"}).notNull(),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportHub_Label_pk`,columns:[u.hubId,u.labelId]}),(0,A.foreignKey)({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,A.foreignKey)({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[u.labelId],foreignColumns:[l.id]})]),s=r.table("DailyReportUserStatus",{hubId:(0,A.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,A.bigint)("user_id",{mode:"number"}).notNull(),isRead:(0,A.bit)("is_read").default(!1).notNull(),isStarred:(0,A.bit)("is_starred").default(!1).notNull(),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportUserStatus_pk`,columns:[u.hubId,u.userId]}),(0,A.foreignKey)({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,A.foreignKey)({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),m=r.table("DailyReportAttachment",{id:(0,A.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,A.bigint)("hub_id",{mode:"number"}).notNull(),uploadedBy:(0,A.bigint)("uploaded_by",{mode:"number"}),sourceKey:(0,A.nvarchar)("source_key",{length:200}).notNull(),fileName:(0,A.nvarchar)("file_name",{length:255}).notNull(),filePath:(0,A.nvarchar)("file_path",{length:"max"}).notNull(),fileType:(0,A.nvarchar)("file_type",{length:100}),fileSize:(0,A.bigint)("file_size",{mode:"number"}),objectCheckedAt:(0,A.datetime2)("object_checked_at"),objectMissingAt:(0,A.datetime2)("object_missing_at"),createdAt:(0,A.datetime2)("created_at").notNull(),createdBy:(0,A.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,A.datetime2)("updated_at").notNull(),updatedBy:(0,A.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,A.primaryKey)({name:`${e}_DailyReportAttachment_pk`,columns:[u.id]}),(0,A.foreignKey)({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,A.foreignKey)({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[u.uploadedBy],foreignColumns:[n.id]}),(0,A.uniqueIndex)(`${e}_DailyReportAttachment_source_unique`).on(u.hubId,u.sourceKey),(0,A.index)(`${e}_DailyReportAttachment_hub_id_index`).on(u.hubId,u.createdAt)]);return{hub:o,internal:a,comment:i,attachment:m,label:l,hubLabel:c,userStatus:s}}var he=require("drizzle-orm/mssql-core");function ms(e){let t=(0,he.mssqlSchema)(e),r=t.table("DailyReportSearchDocument",{hubId:(0,he.bigint)("hub_id",{mode:"number"}).notNull(),searchText:(0,he.nvarchar)("search_text",{length:"max"}).notNull(),sourceDigest:(0,he.binary)("source_digest",{length:32}).notNull(),normalizerVersion:(0,he.varchar)("normalizer_version",{length:64}).notNull(),indexedAt:(0,he.datetime2)("indexed_at").notNull(),rowVersion:(0,he.binary)("row_version",{length:8}).notNull(),authorName:(0,he.nvarchar)("author_name",{length:Qe.maxValueLength}),customerName:(0,he.nvarchar)("customer_name",{length:Qe.maxValueLength})},o=>[(0,he.primaryKey)({name:`${e}_DailyReportSearchDocument_pk`,columns:[o.hubId]})]),n=t.table("DailyReportSearchComment",{hubId:(0,he.bigint)("hub_id",{mode:"number"}).notNull(),ordinal:(0,he.int)("ordinal").notNull(),authorUserId:(0,he.bigint)("author_user_id",{mode:"number"}),commentText:(0,he.nvarchar)("comment_text",{length:"max"}).notNull()},o=>[(0,he.primaryKey)({name:`${e}_DailyReportSearchComment_pk`,columns:[o.hubId,o.ordinal]})]);return{document:r,comment:n}}var ap=5e7,Gn=2e8,ip=1,Kn=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})})}),ys=125,hs=4,fs=16,Rs=50,Ss=2,Xt=Object.freeze({renderMs:Ce.renderMs,nanosecondsPerBlockVisit:ys,margin:hs,maxBlockVisits:Math.floor(Ce.renderMs*1e6/(ys*hs)),walkBudgetMs:fs,nanosecondsPerWalkStep:Rs,walkMargin:Ss,maxWalkSteps:Math.floor(fs*1e6/(Rs*Ss))}),sp=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),gs=75,bs=4,Ds="#ffffff",lp=1,cp={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},up=[/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/],As=Object.freeze({ok:!1,reason:"failed"}),Ts=Object.freeze({ok:!1,reason:"unsupported"}),Es=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:ma(e)}),ws=(e,t)=>{switch(t){case"jpeg":{let r=xn(e);return r===null?null:Es(r)}case"png":{let r=fa(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=Ra(e,Xt.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},Is=(e,t)=>{let r=sp.get(t.depth);if(r===void 0)return null;let n=t.channels*r,o=Kn,a=o.wholeImageBuffer[e.layout];return(a.kind==="none"?0:a.kind==="decoded-raster"?t.width*t.height*n:a.kind==="jpeg-coefficients"?e.coefficientBytes:t.width*t.height*a.bytesPerPixel)+o.pipelineRows*t.width*n+o.fixedBytes},_s=(e,t,r)=>{let n=ws(e,t);return n===null?null:Is(n,r)},dp=e=>e!==null&&e<=Gn,pp=(e,t)=>{if(t!=="jpeg")return ws(e,t);let r=ya(e,Xt);return r===null||r.blockVisits>Xt.maxBlockVisits?null:Es(r.header)},mp=e=>{let t=e instanceof Error?e.message:"";return up.some(r=>r.test(t))?"failed":"unsupported"},xs=e=>{e.cache(!1),e.concurrency(ip),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(cp)});let t=async(n,o,a,i,l)=>{let c=pp(n,o);if(c===null)return Ts;try{let s=e(n,{limitInputPixels:ap,animated:!1});if(!dp(Is(c,await s.metadata())))return Ts;if(l.aborted)return As;let m=await s.rotate().resize({width:a,height:i,fit:"inside",withoutEnlargement:!0}).flatten({background:Ds}).webp({quality:gs,effort:bs}).toBuffer();return{ok:!0,bytes:new Uint8Array(m),contentType:"image/webp"}}catch(s){return{ok:!1,reason:mp(s)}}},r=async(n,{format:o,maxWidth:a,maxHeight:i,signal:l})=>l.aborted?As:t(n,o,a,i,l);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${gs}-e${bs}/flatten-${Ds}/v${lp}`,render:r}};var yp=4096,hp=512*1024*1024,fp=6e4;function Rp(e){e.redis||be(e.logger,2,"Server").warn("redis provider is not injected: cross-worker cache invalidation is disabled (staleness is bounded only by TTL) and SSE publishing is skipped.");let t=rr(e.redis),r=new Tt({defaultTtlMs:re("cacheDefaultTtlMs",e.cacheDefaultTtlMs??fp,1),maxBuckets:re("cacheMaxBuckets",e.cacheMaxBuckets??yp,1),maxBytes:re("cacheMaxBytes",e.cacheMaxBytes??hp,1)},t),n=$r({...e,cache:r,epochs:t}),o=new Pt({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),a=Nr({authenticate:e.authenticate,resolveVisibleSourceTypes:e.resolveVisibleSourceTypes,service:n,encodeUserId:e.encodeUserId,redis:e.redis,sseReader:o,streamKey:n.streamKey,loginRedirectPath:e.loginRedirectPath,enableDevCacheClear:e.enableDevCacheClear,logger:e.logger});return{service:n,cache:r,epochs:t,sseReader:o,streamKey:n.streamKey,knownSourceTypes:[...new Set(["Internal",...(e.externalSources??[]).map(i=>i.sourceType)])],...a}}0&&(module.exports={DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,DAILY_REPORT_SSE_CATCH_UP_BATCH,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,DailyReportSseReader,DailyReportViewerScope,SqlResultCache,createDailyReportHandlers,createDailyReportServer,createDailyReportService,createEpochStore,createSharpThumbnailRenderer,defineDailyReportSchema,defineDailyReportSearchSchema,encodeIdsStreamRows,isStreamIdLte,parseClientTempId,predictSharpThumbnailWorkingSetBytes,readDailyReportSseStreamEntry,transformJsonArray});
11
+ INSERT INTO ${o} (${V(o.hubId)}, ${V(o.ordinal)}, ${V(o.authorUserId)}, ${V(o.commentText)}) SELECT ${V(o.hubId)}, ${V(o.ordinal)}, ${V(o.authorUserId)}, ${V(o.commentText)} FROM OPENJSON(${i}) WITH (${V(o.hubId)} bigint, ${V(o.ordinal)} int, ${V(o.authorUserId)} bigint, ${V(o.commentText)} nvarchar(max));`},Ps=(e,t)=>U.sql`SELECT ${V(e.hubId)} AS ${U.sql.identifier(_e.hubId)}, LOWER(CONVERT(char(64), ${V(e.sourceDigest)}, 2)) AS ${U.sql.identifier(_e.sourceDigest)}, ${V(e.normalizerVersion)} AS ${U.sql.identifier(_e.normalizerVersion)} FROM ${e} WHERE ${e.hubId} IN (${pr(t)})`,Ls=(e,t,r)=>U.sql`SELECT TOP (${r}) ${V(e.id)} AS ${U.sql.identifier(_e.hubId)} FROM ${e} WHERE ${e.id} > ${t} ORDER BY ${e.id}`;var ks=e=>({search:async(t,r)=>Le(r.scope.visible)?[]:Dt(await t.execute(_s(e.tables,r.criteria,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=Nt(o[Ge.sourceType],Ge.sourceType);if(a===null)throw new Error(`[daily-report] search: column ${Ge.sourceType} is null`);return{reportHubId:kt(o[Ge.reportHubId],Ge.reportHubId),businessDate:Nt(o[Ge.businessDate],Ge.businessDate),sourceType:a}}),matchedSets:async(t,r)=>{if(Le(r.scope.visible))return new Map;let n=Dt(await t.execute(xs(e.tables,r.plan,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames,r.ids))),o=2**r.plan.sets.length-1,a=new Map;for(let i of n){let l=i[vt.matchedSets];if(!(typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&l<=o))throw new Error(`[daily-report] search: column ${vt.matchedSets} holds no mask of ${r.plan.sets.length} keywords`);a.set(kt(i[vt.reportHubId],vt.reportHubId),l)}return a},facetValues:async(t,r)=>Le(r.scope.visible)?[]:Dt(await t.execute(Cs(e.tables,r.column,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=Nt(o[mr.value],mr.value);if(a===null)throw new Error(`[daily-report] search: column ${mr.value} is null`);return a})});var ot=require("@aiquants/mssql"),co=require("drizzle-orm");var vs=require("crypto");var Dp=Object.freeze({authorName:"author",customerName:"customer"}),so=e=>e===null?null:Pn(e),Ns=(e,t,r)=>{let n=so(r);if(n!==null&&n.length>lt.maxValueLength){let o=lt.maxValueLength;throw new Error(`[daily-report] search index: report ${e}: the ${Dp[t]} display value has ${n.length} UTF-16 units after trimming; the host must keep the author and customer display values at most ${o} UTF-16 units`)}return n},yr=e=>e===null?"n;":`s${e.length}:${e}`,hr="utf16le",Tp=e=>{let t=(0,vs.createHash)("sha256");t.update(`F${e.fields.length};`,hr);for(let[r,n]of e.fields)t.update(yr(r)+yr(n),hr);return t.update(`C${e.comments.length};`,hr),e.comments.forEach((r,n)=>{t.update(`${n};${r.authorUserId===null?"n":`i${r.authorUserId}`};${yr(r.text)}`,hr)}),t.update(`P;${yr(so(e.filterValues.authorName))}${yr(so(e.filterValues.customerName))}`,hr),t.digest("hex")},lo=e=>{let t=0,r=[];for(let[,o]of e.fields){if(o===null)continue;let a=qr(o);t+=a.forcedCuts,r.push(a.text)}let n=[];for(let o of e.comments){let a=qr(o.text);t+=a.forcedCuts,a.text.length!==0&&n.push({ordinal:n.length,authorUserId:o.authorUserId,commentText:a.text})}return{hubId:e.hubId,searchText:$i(r),comments:n,sourceDigest:Tp(e),forcedCuts:t,authorName:Ns(e.hubId,"authorName",e.filterValues.authorName),customerName:Ns(e.hubId,"customerName",e.filterValues.customerName)}};var Os=e=>{let t=async(s,c)=>{let d=[];for(let u of(0,ot.chunk)(c,ot.MAX_IN_LIST))for(let R of Dt(await s.execute(ws(e.hub,u))))d.push(kt(R[_e.hubId],_e.hubId));return d},r=async(s,c)=>{for(let d of(0,ot.chunk)(c,ot.MAX_IN_LIST))await s.execute(Ms(e.tables,d,e.normalizerVersion))},n=async(s,c)=>{let d=new Map;for(let u of(0,ot.chunk)(c,ot.MAX_IN_LIST))for(let R of Dt(await s.execute(Ps(e.tables.document,u))))d.set(kt(R[_e.hubId],_e.hubId),{sourceDigest:Nt(R[_e.sourceDigest],_e.sourceDigest),normalizerVersion:Nt(R[_e.normalizerVersion],_e.normalizerVersion)});return d},o=async(s,c,d)=>Dt(await s.execute(Ls(e.hub,c,d))).map(u=>kt(u[_e.hubId],_e.hubId)),a=async(s,c)=>{let d=await t(s,[...new Set(c)].sort((R,m)=>R-m));if(d.length===0)return;let u=(await e.loadSources(s,d)).map(lo);u.length>0&&await r(s,u)},i=s=>e.inTransaction(async c=>{await c.execute(co.sql`SET DEADLOCK_PRIORITY LOW`);let d=await t(c,s),u=await n(c,d),R=(await e.loadSources(c,d)).map(lo),m=R.filter(p=>{let f=u.get(p.hubId);return f===void 0||f.sourceDigest!==p.sourceDigest||f.normalizerVersion!==e.normalizerVersion});return m.length>0&&await r(c,m),await c.execute(co.sql`SET DEADLOCK_PRIORITY NORMAL`),{scanned:R.length,written:m.length,forcedCuts:R.reduce((p,f)=>p+f.forcedCuts,0)}});return{writeHubs:a,reconcile:async(s,c)=>{let{batchSize:d,hubIds:u,signal:R,onProgress:m}=c;de("reconcileSearchIndex: batchSize",d,1,ot.MAX_IN_LIST);let p=se(),f=u===void 0?null:(0,ot.chunk)([...new Set(u)].sort((S,_)=>S-_),d),y={scanned:0,written:0,skipped:0,forcedCuts:0,lastHubId:null};for(let S=0;;S++){R?.throwIfAborted();let _=f===null?await o(s,y.lastHubId===null?0:y.lastHubId,d):f[S];if(_===void 0||_.length===0)break;let D=await i(_);y={scanned:y.scanned+D.scanned,written:y.written+D.written,skipped:y.skipped+D.scanned-D.written,forcedCuts:y.forcedCuts+D.forcedCuts,lastHubId:_[_.length-1]},m?.(y)}return{...y,elapsedMs:se()-p}}}};var Bs=require("@aiquants/fuzzy-search/normalize");var uo=255,Zr=Object.values(Mt).sort((e,t)=>e-t),Ap=new Intl.Segmenter("und",{granularity:"grapheme"}),he=Object.freeze({strip:30,split:200,line:2e3,plan:90,normalize:900,map:2200,scan:2,run:700,segment:150,sweep:30,linear:6}),at=5e5,en=Math.floor(at/he.linear),Ep=Math.floor(at/he.segment),Fs=Math.floor(at/he.sweep),Us=Math.floor(at/he.scan),yo=Object.freeze({maxRanges:5e5,maxUnits:4e6,maxFieldRanges:1e4,sliceNs:8e6,sliceMs:5}),$s=(e,t)=>{let r=0,n=t(),o=at,a=!1;return{fits:i=>r===0?!0:r+i>e.sliceNs?!1:(r>=o&&(o=r+at,a=t()-n>=e.sliceMs),!a),charge:i=>{r+=i},startSlice:()=>{r=0,n=t(),o=at,a=!1}}},gR=Object.freeze({fits:()=>!0,charge:()=>{}}),Vs=e=>{let t=null;return{step:()=>{if(t!==null)return!0;let r=e.next();return r.done!==!0?!1:(t={result:r.value},!0)},result:()=>{if(t===null)throw new Error("[daily-report] search marks: the walk is not done (step until it returns true)");return t.result}}};var wp=(e,t)=>{if(e.text!==t)throw new Error(`[daily-report] search marks: the position-mapped line (${e.text.length} units) differs from the index line (${t.length} units)`);return e},Ip=(e,t)=>e.chunks.length===1&&e.chunks[0].length===1&&e.chunks[0][0].start===0&&e.chunks[0][0].end===t.length;function*_p(e,t,r,n){let o=!1;for(let c=t;c<r&&!o;c+=en){let d=Math.min(r,c+en),u=(d-c)*he.linear;n.fits(u)||(yield),o=(0,Bs.holdsMultiUnitCluster)(e.slice(c,d)),n.charge(u)}if(!o)return null;let a=new Int32Array(r-t),i=new Int32Array(r-t),l=Ap.segment(e.slice(t,r))[Symbol.iterator](),s=l.next();for(;!s.done;){let c=Math.max(Ep,s.value.segment.length);n.fits(c*he.segment)||(yield);let d=0;for(;!s.done&&d+s.value.segment.length<=c;){let{index:u,segment:R}=s.value;a.fill(t+u,u,u+R.length),i.fill(t+u+R.length,u,u+R.length),d+=R.length,s=l.next()}n.charge(d*he.segment)}return{start:t,clusterStarts:a,clusterEnds:i}}var xp=256,Cp=e=>{let t=new Int32Array(e.length),r=0;for(let n=1;n<e.length;n++){for(;r>0&&e.charCodeAt(n)!==e.charCodeAt(r);)r=t[r-1];e.charCodeAt(n)===e.charCodeAt(r)&&r++,t[n]=r}return e.length-t[e.length-1]},Mp=e=>{let t=new Map;for(let r of e){if(r.text.length===0)throw new Error("[daily-report] search marks: an alternative has an empty text");let n=t.get(r.text);(n===void 0||r.tier<n)&&t.set(r.text,r.tier)}return[...t].map(([r,n])=>{let o=Cp(r),a=Math.max(Us-r.length+1,r.length);if(o===r.length)return{text:r,tier:n,periodic:null,windowStarts:a};let i=r.length%o,l=r.slice(i,o)+r.slice(0,i);return{text:r,tier:n,periodic:{period:o,continuation:l.repeat(Math.ceil(xp/o))},windowStarts:a}})},tn=(e,t)=>{let{pieces:r}=e,n=r[e.lastPiece];if(n.plainStart<=t&&t<n.plainStart+n.text.length)return e.lastPiece;let o=0,a=r.length-1;for(;o<a;){let i=o+a+1>>1;r[i].plainStart<=t?o=i:a=i-1}return t>=r[o].plainStart+r[o].text.length?-1:(e.lastPiece=o,o)},Hs=(e,t,r)=>{let n=tn(e,t);return e.pieces[n>=0?n:tn(e,r==="start"?t-1:t+1)]},Ys=(e,t)=>{let r=tn(e,t);if(r<0)return qs(e,t-1);let n=e.pieces[r];return n.start+n.mapped.start[t-n.plainStart]},qs=(e,t)=>{let r=tn(e,t);if(r<0)return Ys(e,t+1);let n=e.pieces[r];return n.start+n.mapped.end[t-n.plainStart]},Pp=()=>({from:0,runStart:-1,last:0,periodicEnd:-1,window:"",windowStart:0,windowEnd:0,closedStart:0,closedEnd:-1}),Lp=Object.freeze({kind:"done"}),po=Object.freeze({kind:"slice"}),kp=Object.freeze({kind:"clusters"}),Np=(e,t,r,n,o,a)=>{let{plain:i}=e,{text:l,tier:s,periodic:c}=r;for(;;){if(n.closedEnd>=0){if(!o.fits(he.run))return po;let m=Hs(e,n.closedStart,"start"),p=Hs(e,n.closedEnd-1,"end");if(m.mapped===null)return{kind:"map",piece:m};if(p.mapped===null)return{kind:"map",piece:p};if(e.isCut&&e.clusters===void 0)return kp;let f=t(e.offset+Ys(e,n.closedStart)),y=t(e.offset+qs(e,n.closedEnd-1)-1)+1;n.closedEnd=-1;let S=e.clusters;S==null?a(f,y,s):a(S.clusterStarts[f-S.start],S.clusterEnds[y-1-S.start],s),o.charge(he.run);continue}if(c!==null&&n.periodicEnd>=0){if(!o.fits(at))return po;let{period:m,continuation:p}=c,f=n.periodicEnd,y=Math.min(i.length,f+Math.max(Us,p.length)),S=f;for(;S+p.length<=y&&i.startsWith(p,S);)S+=p.length;let _=S+p.length>y&&y<i.length;if(!_)for(;S<i.length&&i.charCodeAt(S)===i.charCodeAt(S-m);)S++;if(o.charge((S-f)*he.scan),_){n.periodicEnd=S;continue}n.periodicEnd=-1,n.last+=Math.floor((S-n.last-l.length)/m)*m,n.from=n.last+l.length-m+1;continue}if(n.from<0){if(n.runStart<0)return Lp;n.closedStart=n.runStart,n.closedEnd=n.last+l.length,n.runStart=-1;continue}if(!o.fits(at))return po;n.from>=n.windowEnd&&(n.windowStart=n.from,n.windowEnd=n.from+r.windowStarts,n.window=i.slice(n.from,n.windowEnd+l.length-1));let d=n.from-n.windowStart,u=n.window.indexOf(l,d);if(u<0){o.charge((n.window.length-d)*he.scan),n.from=n.windowStart+n.window.length===i.length?-1:n.windowEnd;continue}o.charge((u+l.length-d)*he.scan);let R=n.windowStart+u;(n.runStart<0||R>=n.last+l.length)&&(n.runStart>=0&&(n.closedStart=n.runStart,n.closedEnd=n.last+l.length),n.runStart=R),n.last=R,c===null?n.from=R+1:n.periodicEnd=R+l.length}};function*mo(e,t,r){let n=Math.floor(at/t);for(;!e.done();)r.fits(n*t)||(yield),r.charge(e.advance(n)*t);return e.result()}function*vp(e,t,r,n,o){if(t.length===0)return;let a=yield*mo(Vi(e),he.strip,n),i=[],l=[];yield*mo(Yi(a.text,(c,d)=>{i.push(d),l.push(d+c.length)}),he.split,n);let s=c=>a.rawIndex===null?c:a.rawIndex[c];for(let c=0;c<i.length;c++){n.fits(he.line)||(yield),n.charge(he.line);let d=i[c],u=a.text.slice(d,l[c]),R=yield*mo(qi(u,r),he.plan,n),m=[],p="";for(let y of R.chunks){let S="",_=[];for(let D of y){let h=(D.end-D.start)*he.normalize;n.fits(h)||(yield);let g=eo(D.start===0&&D.end===u.length?u:u.slice(D.start,D.end),r).text;n.charge(h),g.length>0&&_.push({start:D.start,end:D.end,text:g,chunkStart:S.length}),S+=g}if(S.length!==0){p.length>0&&(p+=" ");for(let D of _)m.push({start:D.start,end:D.end,text:D.text,plainStart:p.length+D.chunkStart,mapped:null});p+=S}}if(p.length===0)continue;let f={offset:d,plain:p,pieces:m,isCut:!Ip(R,u),lastPiece:0,clusters:void 0};for(let y of t){let S=Pp();for(;;){let _=Np(f,s,y,S,n,o);if(_.kind==="done")break;if(_.kind==="slice"){yield;continue}if(_.kind==="clusters"){f.clusters=yield*_p(e,s(d),s(d+u.length-1)+1,n);continue}let{piece:D}=_,h=(D.end-D.start)*he.map;n.fits(h)||(yield);let g=u.slice(D.start,D.end);D.mapped=wp(Ui(g,Zn(g,r)),D.text),n.charge(h)}}}}function*Op(e,t,r,n){let o=new Int32Array(Zr.length),a=0,i=uo;for(let l=0;l<=e;l+=Fs){let s=Math.min(e+1,l+Fs),c=(s-l)*he.sweep;r.fits(c)||(yield);for(let d=l;d<s;d++){let u=uo;for(let R=Zr.length-1;R>=0;R--){let m=Zr[R];o[m]+=t[m][d],o[m]>0&&(u=m)}if(u!==i){if(i!==uo&&!n(a,d,i))return!1;a=d,i=u}}r.charge(c)}return!0}function*Fp(e,t,r,n,o){let a=null;return yield*vp(e,t,r,n,(l,s,c)=>{a===null&&(a=Zr.map(()=>new Int32Array(e.length+1))),a[c][l]++,a[c][s]--}),a===null?!0:yield*Op(e.length,a,n,o)}var Hp=(e,t,r,n)=>{let o=Mp(t),a=[],i=(s,c,d)=>(a.push(s,c,d),a.length<=3*r.maxRanges);return Vs(function*(){return(yield*Fp(e,o,r.maxLength,n,i))?{dense:!1,ranges:a}:{dense:!0}}())};var js=(e,t)=>{if(e.combine==="intersection"||e.sets.length===1)return e.sets.flatMap(r=>r.words);if(t===null)throw new Error(`[daily-report] search marks: a union of ${e.sets.length} keywords needs the report's mask of matched keywords`);return e.sets.flatMap((r,n)=>(t&1<<n)===0?[]:r.words)},Ws=e=>{let t=[],r=(n,o)=>{typeof o=="string"&&o.length>0&&t.push({key:n,value:o})};for(let n of Xo)r(st.field(n),e[n]);e.interviewers.forEach((n,o)=>{r(st.interviewer(o,"name"),n.name),r(st.interviewer(o,"affiliation"),n.affiliation)}),e.attachments.forEach((n,o)=>{r(st.attachment(o),n.fileName)}),e.externalComments.forEach((n,o)=>{r(st.comment(En(o),"author"),n.name),r(st.comment(En(o),"content"),n.text)});for(let n of e.postedComments)r(st.comment(n.id,"author"),n.userName),r(st.comment(n.id,"content"),n.content);return t};function*Bp(e,t){let r=_n;for(let n=0;n<e.length;n+=en){let o=Math.min(e.length,n+en),a=(o-n)*he.linear;t.fits(a)||(yield),r=xn(r,e,n,o),t.charge(a)}return r}var zs=async(e,t,r,n)=>{let o=0,a=0,i=async c=>{for(;!c.step();)await r(),n.startSlice();return c.result()},l=async(c,d)=>{if(!d&&a>t.maxRanges)return null;let u={};for(let{key:R,value:m}of c.fields){if(!d&&o+m.length>t.maxUnits)return null;let p=await i(Vs(Bp(m,n))),f=await i(Hp(m,c.alternatives,{maxLength:Jn,maxRanges:t.maxFieldRanges},n));if(o+=m.length,f.dense){u[R]={fingerprint:p,dense:!0};continue}if(u[R]={fingerprint:p,ranges:f.ranges},a+=f.ranges.length/3,!d&&a>t.maxRanges)return null}return u},s=[];for(let c=0;c<e.length;c++){let d=e[c],u=await l(d,s.length===0);if(u===null)return{reports:s,deferred:e.slice(c).map(R=>R.reportHubId)};s.push({reportHubId:d.reportHubId,matchedSets:d.matchedSets,fields:u})}return{reports:s,deferred:[]}};var Oe=require("drizzle-orm");var ve=require("drizzle-orm");var Ke="Internal";var Je=e=>(0,ve.getColumns)(e),be=(e,t)=>{if(!e)return null;let r=e instanceof Date?e:new Date(e);if(Number.isNaN(r.getTime()))return typeof e=="string"?e:null;let n=r.getFullYear(),o=n<0?`-${String(-n).padStart(4,"0")}`:String(n).padStart(4,"0"),a=String(r.getMonth()+1).padStart(2,"0"),i=String(r.getDate()).padStart(2,"0");if(t==="YYYY-MM-DD")return`${o}-${a}-${i}`;let l=String(r.getHours()).padStart(2,"0"),s=String(r.getMinutes()).padStart(2,"0"),c=String(r.getSeconds()).padStart(2,"0");return`${o}-${a}-${i} ${l}:${s}:${c}`},Gs=e=>{let{db:t,tables:r,encodeUserId:n,settings:o,draftVisibilityTables:a}=e,{hub:i,label:l}=r,{externalSources:s,draftLabelNames:c,canonicalDraftLabelName:d}=o,u=k=>lr(i.sourceType,k),R=(k,v)=>Xr(a,k,c,v),m=ve.sql`CASE WHEN ${Qr(a,c)} THEN 1 ELSE 0 END`,p=async k=>{let[v]=await t.select({id:i.id}).top(1).from(i).where((0,ve.and)((0,ve.eq)(i.id,k),Qr(a,c)));return v!==void 0},f=k=>k==null||k===""?null:/^\d+$/.test(k)?n(Number(k)):k,y=()=>{let k={};for(let v of s)k[`ext_${v.sourceType}`]=Je(v.table);return k},S=k=>{let v=k;for(let b of s)v=v.leftJoin(b.table,(0,ve.and)((0,ve.eq)(i.sourceType,b.sourceType),(0,ve.eq)(i.sourceIdNum,b.idColumn)));return v},_=k=>{let{hub:v,internal:b}=k,N=v.summary,$=[],F=null,H=null,K=null,ee=null,W=null,ae=null,Te=[],ke=s.find(J=>J.sourceType===v.sourceType),Re=ke?k[`ext_${ke.sourceType}`]:void 0;if(ke&&Re){let J=ke.mapRow(Re);J.content!==void 0&&(N=J.content),J.employeeName!==void 0&&(ae=J.employeeName),J.category!==void 0&&(F=J.category),J.creationCategory!==void 0&&(H=J.creationCategory),J.visitTimeFrom!==void 0&&(K=J.visitTimeFrom),J.visitTimeTo!==void 0&&(ee=J.visitTimeTo),J.customerName!==void 0&&(W=J.customerName),J.interviewers!==void 0&&($=J.interviewers),J.externalComments!==void 0&&(Te=J.externalComments)}else v.sourceType===Ke&&b&&(N=b.body);return{content:N,author:k.creatorName??f(v.createdBy)??"",employeeName:ae??k.creatorName??f(v.createdBy),updatedBy:f(v.updatedBy),category:F,creationCategory:H,visitTimeFrom:K,visitTimeTo:ee,customerName:W,interviewers:$,externalComments:Te}},D=k=>{if(k===1)return!0;if(k===0)return!1;throw new Error(`[daily-report] a detail row's hasDraftLabel must be 1 or 0 (the read must select draftLabelFlag); got ${dn(k)}`)},h=k=>k.creationCategory!==null&&c.includes(k.creationCategory),g=(k,v)=>D(k.hasDraftLabel)?!0:h(v),P=async k=>{let[v]=await k.select({id:l.id}).top(1).from(l).where((0,ve.eq)(l.name,d)).orderBy((0,ve.asc)(l.id));return v===void 0?null:v.id},x=()=>P(t);return{visibleSourceTypeCondition:u,draftVisibleTo:R,draftLabelFlag:m,isDraftReport:p,externalSelections:y,applyExternalJoins:S,resolveHubDisplayFields:_,readCanonicalDraftLabelId:P,getDraftLabelId:x,resolveCreationCategoryDraftLabelId:k=>k.some(h)?x():Promise.resolve(null),mapHubRecord:(k,v,b,N,$)=>{let{hub:F}=v,H=(v.labels??[]).map(W=>({id:W.id,name:W.name,color:W.color})),K=v.postedCommentRows??[],ee=Ie(k.commentable,F.sourceType);return N!==null&&h(b)&&!H.some(W=>W.id===N)&&H.push({id:N,name:d,color:null}),{reportHubId:F.id,date:be(F.businessDate,"YYYY-MM-DD"),author:b.author,userId:F.userId?n(F.userId):"",sourceType:F.sourceType,createdAt:be(F.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:be(F.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:b.updatedBy,employeeName:b.employeeName,category:b.category,creationCategory:b.creationCategory,visitTimeFrom:b.visitTimeFrom,visitTimeTo:b.visitTimeTo,customerName:b.customerName,interviewers:b.interviewers,subject:F.title,content:b.content,externalComments:ee?b.externalComments:[],isRead:v.isRead??!1,isStarred:v.isStarred??!1,isDraft:g(v,b),labels:H,postedComments:K.filter(W=>Mi({authorUserId:W.userId},F.sourceType,$??null,k)).map(W=>({...W,userId:n(W.userId),isMine:$?W.userId===$:!1})),attachments:v.attachments}}}};var Ks=(e,{draftVisibleTo:t,visibleSourceTypeCondition:r})=>{let{db:n,tables:o,logger:a,settings:i}=e,{hub:l}=o,{attachmentDelivery:s}=i,c=(p,f)=>f!=null?"absent":p!=null?"present":"unknown";return{getAttachmentsByHubIds:async p=>{let f=new Map,y=o.attachment;if(p.length===0||!y||s===null)return f;let S=s.idCodec,_=s.thumbnails!==null,D=await n.select({id:y.id,hubId:y.hubId,fileName:y.fileName,fileType:y.fileType,fileSize:y.fileSize,createdAt:y.createdAt,objectCheckedAt:y.objectCheckedAt,objectMissingAt:y.objectMissingAt}).from(y).where((0,Oe.inArray)(y.hubId,p)).orderBy((0,Oe.asc)(y.createdAt),(0,Oe.asc)(y.id));for(let h of D){let g=h.fileType?String(h.fileType):null,P=h.fileSize!=null?Number(h.fileSize):null,x=c(h.objectCheckedAt,h.objectMissingAt),M={id:S.encode(Number(h.id)),fileName:String(h.fileName),fileType:g,fileSize:P,createdAt:be(h.createdAt,"YYYY-MM-DD HH:mm:ss"),state:x,hasThumbnail:_&&x!=="absent"&&vr({fileType:g,fileSize:P},s.maxBytes)},j=f.get(Number(h.hubId));j?j.push(M):f.set(Number(h.hubId),[M])}return f},getAttachmentForUser:async(p,f,y)=>{let S=o.attachment;return!S||Le(p.visible)?null:(await n.select({fileName:S.fileName,filePath:S.filePath,fileType:S.fileType,fileSize:S.fileSize}).top(1).from(S).innerJoin(l,(0,Oe.eq)(l.id,S.hubId)).where((0,Oe.and)((0,Oe.eq)(S.id,f),(0,Oe.isNull)(l.deletedAt),t(y,"author"),r(p.visible))))[0]??null},markAttachmentMissing:async p=>{let f=o.attachment;if(!f)return;let y=new Date;try{await n.update(f).set({objectCheckedAt:y,objectMissingAt:y,updatedAt:y}).where((0,Oe.eq)(f.id,p))}catch(S){a.error("markAttachmentMissing failed",S)}},markAttachmentPresent:async p=>{let f=o.attachment;if(!f)return;let y=new Date;try{await n.update(f).set({objectCheckedAt:y,objectMissingAt:null,updatedAt:y}).where((0,Oe.eq)(f.id,p))}catch(S){a.error("markAttachmentPresent failed",S)}}}};var zt=require("drizzle-orm");var Tt="daily-report:ids:epoch",Fe="daily-report:date-epoch:",Qe="daily-report:detail-epoch:",Js=({redis:e,logger:t,epochs:r,streamKey:n,streamMaxLen:o})=>({incrementRedisEpoch:s=>r.incrementEpoch(s),publishToSseStream:async(s,c)=>{let d=await e?.getClient();if(!d){t.warn(`[SSE] Redis client unavailable (${c})`);return}let u=JSON.stringify(s),R=Buffer.byteLength(u);if(R>6356992){t.warn(`[SSE] Event too large (${c}): ${R} bytes > ${6356992}; not published`);return}let m=se();try{await d.xAdd(n,"*",{data:u},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:o}});let p=se()-m;p>1e3&&t.warn(`[SSE] Slow publish (${c}): ${p}ms`)}catch(p){t.error(`[SSE] Redis publish failed (${c}):`,p)}},readSseStreamAnchor:async()=>{try{let s=await e?.getClient();if(s===void 0)return null;let[c]=await s.xRevRange(n,"+","-",{COUNT:1});return c===void 0?null:c.id}catch(s){return t.error("SSE stream anchor read failed",s),null}}});var Qs=(e,{isDraftReport:t,assertHubMutable:r,incrementRedisEpoch:n})=>{let{db:o,tables:a,users:i,encodeUserId:l,cache:s,inTransaction:c,prepareSearchIndex:d,publishToSseStream:u}=e,{hub:R,comment:m}=a,p=async(_,D)=>{if(D!==null)return await t(_)?D:void 0},f=async(_,D,h,g,P,x)=>{let[M]=await o.select({sourceType:R.sourceType,deletedAt:R.deletedAt,userId:R.userId}).top(1).from(R).where((0,zt.eq)(R.id,h));if(!M||M.deletedAt)throw new Error("Not Found");if(await r(_,h,D),!Ie(_.commentable,M.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(M.sourceType.toLowerCase()!==Ke.toLowerCase())throw new Error("Comments are restricted for external daily report sources");let j=await p(h,M.userId),k=await d(),v=await c(async F=>{let[H]=await F.insert(m).output().values({hubId:h,userId:D,body:g,createdAt:new Date,createdBy:String(D),updatedAt:new Date,updatedBy:String(D)});return k!==null&&await k.writeHubs(F,[h]),H}),[b]=await o.select({displayName:i.displayName}).top(1).from(i).where((0,zt.eq)(i.id,D)),N=b?.displayName??"";if(P){let F=Pe(P);F&&(s.invalidatePrefix(jt(F)),await n(`${Fe}${F}`))}s.invalidatePrefix(Ye(h)),await n(`${Qe}${h}`);let $={id:v.id,userId:l(v.userId),userName:N,content:v.body,createdAt:be(v.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await u(Rn.parse({type:"comment-add",reportHubId:h,comment:$,clientTempId:x,recipientRawUserId:j,sourceType:M.sourceType}),"addComment"),$},y=async(_,D)=>await _.select().top(1).from(m).where((0,zt.eq)(m.id,D));return{addComment:f,deleteComment:async(_,D,h,g,P,x)=>{let M=await y(o,g);if(M.length===0)throw new Error("Not Found");if(M[0].hubId!==h)throw new Error("Not Found");let[j]=await o.select({userId:R.userId,sourceType:R.sourceType}).top(1).from(R).where((0,zt.eq)(R.id,M[0].hubId));if(!(j&&Ie(_.visible,j.sourceType)))throw new Error("Not Found");if(M[0].userId!==D)throw new Error("Unauthorized");let k=await p(h,j.userId),v=await d();if(await c(async b=>{await b.delete(m).where((0,zt.eq)(m.id,g)),v!==null&&await v.writeHubs(b,[h])}),P){let b=Pe(P);b&&(s.invalidatePrefix(jt(b)),await n(`${Fe}${b}`))}s.invalidatePrefix(Ye(h)),await n(`${Qe}${h}`),await u(Sn.parse({type:"comment-delete",reportHubId:h,commentId:g,clientTempId:x,recipientRawUserId:k,sourceType:j.sourceType}),"deleteComment")}}};var yt=require("drizzle-orm");var Xs=e=>e===""?null:e,Zs=(e,{readCanonicalDraftLabelId:t,isDraftReport:r,getDailyReportDetailById:n,incrementRedisEpoch:o})=>{let{db:a,tables:i,users:l,encodeUserId:s,cache:c,logger:d,inTransaction:u,prepareSearchIndex:R,publishToSseStream:m,settings:p,draftVisibilityTables:f}=e,{hub:y,internal:S,hubLabel:_}=i,{canonicalDraftLabelName:D,draftLabelNames:h}=p,g=async(b,N,$)=>{if(!br(N))throw X("createDailyReport: businessDate","a business-date key in the canonical form YYYY-MM-DD naming a day from 0001-01-01 to 9999-12-31",N);d.info("createDailyReport called",{userId:b,businessDate:N});let[F]=await a.select({displayName:l.displayName}).from(l).where((0,yt.eq)(l.id,b)),H=F?.displayName??s(b),K=await R();try{let ee=await u(async ae=>{d.info("Starting transaction");let Te=await t(ae);if(Te===null)throw new Error(`[daily-report] createDailyReport: the canonical draft label ${JSON.stringify(D)} (draftLabelNames[0]) does not exist; create that label before creating reports (a report without it would be visible to every viewer)`);let ke=`internal-temp-${Date.now()}-${Math.random()}`,[Re]=await ae.insert(y).output().values({sourceType:Ke,sourceId:ke,businessDate:new Date(`${N}T00:00:00Z`),userId:b,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(b),updatedAt:new Date,updatedBy:String(b)});await ae.update(y).set({sourceId:String(Re.id)}).where((0,yt.eq)(y.id,Re.id)),d.info("Hub created",Re),await ae.insert(S).values({hubId:Re.id,body:"",createdAt:new Date,createdBy:String(b),updatedAt:new Date,updatedBy:String(b)}),d.info("Internal created"),await ae.insert(_).values({hubId:Re.id,labelId:Te,createdAt:new Date,createdBy:String(b)});let J=[{id:Te,name:D,color:null}];return d.info("Label assigned"),K!==null&&await K.writeHubs(ae,[Re.id]),{reportHubId:Re.id,date:N,createdAt:be(Re.createdAt,"YYYY-MM-DD HH:mm:ss"),author:H,userId:s(b),sourceType:Ke,employeeName:H,updatedBy:s(b),updatedAt:be(Re.updatedAt,"YYYY-MM-DD HH:mm:ss"),category:null,creationCategory:null,visitTimeFrom:null,visitTimeTo:null,customerName:null,interviewers:[],subject:Re.title,content:"",externalComments:[],isRead:!0,isStarred:!1,isDraft:!0,labels:J,postedComments:[],attachments:[]}});c.invalidatePrefix(Lt(N,b)),c.invalidatePrefix(gt),c.invalidatePrefix(no(b)),await o(Tt),await o(`${Fe}${N}`);let W=await n(Ue.unrestricted("post-write self read: the writer always sees the row they just wrote"),ee.reportHubId,b,{forceRefresh:!0});if(W){let ae=await r(W.reportHubId);await m(gn.parse({type:"report-create",reportHubId:W.reportHubId,report:W,clientTempId:$,recipientRawUserId:ae?b:void 0}),"createDailyReport")}return W??ee}catch(ee){throw d.error("Error in createDailyReport",ee),ee}},P=async(b,N)=>await b.select().top(1).from(y).where((0,yt.eq)(y.id,N)),x=async(b,N,$)=>{await b.update(y).set($).where((0,yt.eq)(y.id,N))},M=async(b,N,$)=>{await b.update(S).set($).where((0,yt.eq)(S.hubId,N))};return{createDailyReport:g,updateDailyReport:async(b,N,$,F)=>{let H=await P(a,b);if(!H.length||H[0].deletedAt)throw new Error("Not Found");if(H[0].userId!==N)throw new Error("Unauthorized");let K=await R();await u(async ae=>{$.title!==void 0&&await x(ae,b,{title:Xs($.title),updatedAt:new Date,updatedBy:String(N)}),$.content!==void 0&&await M(ae,b,{body:Xs($.content),updatedAt:new Date,updatedBy:String(N)}),K!==null&&await K.writeHubs(ae,[b])}),c.invalidatePrefix(Ye(b)),c.invalidatePrefix(gt),await o(`${Qe}${b}`);let ee=Pe(be(H[0].businessDate,"YYYY-MM-DD"));ee&&(c.invalidatePrefix(jt(ee)),await o(`${Fe}${ee}`));let W=await n(Ue.unrestricted("post-write self read: the writer always sees the row they just wrote"),b,N,{forceRefresh:!0});if(W){let ae=await r(b);await m(bn.parse({type:"report-update",reportHubId:W.reportHubId,report:W,clientTempId:F,recipientRawUserId:ae?N:void 0}),"updateDailyReport")}},publishDailyReport:async(b,N,$)=>{let F=await P(a,b);if(!F.length)throw new Error("Not Found");if(F[0].userId!==N)throw new Error("Unauthorized");let H=await R();if(await u(async W=>{await W.delete(_).where((0,yt.and)((0,yt.eq)(_.hubId,b),As(f,h))),H!==null&&await H.writeHubs(W,[b])}),c.invalidatePrefix(Ye(b)),c.invalidatePrefix(gt),c.invalidatePrefix(St),await o(Tt),F[0].businessDate){let W=Pe(be(F[0].businessDate,"YYYY-MM-DD"));W&&await o(`${Fe}${W}`)}let K=Pe(be(F[0].businessDate,"YYYY-MM-DD"));K&&c.invalidatePrefix(Lt(K,N));let ee=await n(Ue.unrestricted("post-write self read: the writer always sees the row they just wrote"),b,N,{forceRefresh:!0});if(ee){let W=await r(b);await m(Dn.parse({type:"report-publish",reportHubId:ee.reportHubId,report:ee,clientTempId:$,recipientRawUserId:W?N:void 0}),"publishDailyReport")}return ee??null},deleteDailyReport:async(b,N,$)=>{let F=await P(a,b);if(!F.length||F[0].deletedAt)throw new Error("Not Found");if(F[0].userId!==N)throw new Error("Unauthorized");if(await u(async H=>{await x(H,b,{deletedAt:new Date,deletedBy:String(N),updatedAt:new Date,updatedBy:String(N)})}),c.invalidatePrefix(Ye(b)),c.invalidatePrefix(gt),c.invalidatePrefix(St),await o(Tt),F[0].businessDate){let H=Pe(be(F[0].businessDate,"YYYY-MM-DD"));H&&await o(`${Fe}${H}`)}await m(Tn.parse({type:"report-delete",reportHubId:b,clientTempId:$,sourceType:F[0].sourceType}),"deleteDailyReport")}}};var Y=require("drizzle-orm");var el=Ar([]),tl=(e,{draftVisibleTo:t,visibleSourceTypeCondition:r,draftLabelFlag:n,externalSelections:o,applyExternalJoins:a,resolveHubDisplayFields:i,resolveCreationCategoryDraftLabelId:l,mapHubRecord:s,getAttachmentsByHubIds:c,readSseStreamAnchor:d,incrementRedisEpoch:u})=>{let{db:R,tables:m,users:p,resolveUserId:f,cache:y,epochs:S,logger:_,settings:D}=e,{hub:h,internal:g,comment:P,label:x,hubLabel:M,userStatus:j}=m,k=D.idsTtlMs,v=D.businessDateTtlMs,b=async(A,E)=>(await R.select({reportHubId:h.id,businessDate:h.businessDate,sourceType:h.sourceType}).from(h).where((0,Y.and)((0,Y.isNull)(h.deletedAt),t(E,"author-or-authorless"),r(A.visible))).orderBy((0,Y.desc)(h.businessDate),(0,Y.desc)(h.id))).map(C=>({...C,businessDate:be(C.businessDate,"YYYY-MM-DD")})),N=async(A,E,I)=>{let C=await H(E);return C?Le(A.visible)?[]:(await R.select({reportHubId:h.id,businessDate:h.businessDate,sourceType:h.sourceType}).top(I).from(h).where((0,Y.and)((0,Y.isNull)(h.deletedAt),t(C,"author-or-authorless"),r(A.visible))).orderBy((0,Y.desc)(h.businessDate),(0,Y.desc)(h.id))).map(q=>({...q,businessDate:be(q.businessDate,"YYYY-MM-DD")})):[]},$=async(A,E)=>{let I=await a(R.select({hub:Je(h),internal:Je(g),creatorName:p.displayName,hasDraftLabel:n,...o()}).from(h)).leftJoin(g,(0,Y.eq)(h.id,g.hubId)).leftJoin(p,(0,Y.eq)(h.userId,p.id)).where((0,Y.and)((0,Y.eq)(h.businessDate,Y.sql`${E}`),(0,Y.isNull)(h.deletedAt),r(A.visible))).orderBy((0,Y.desc)(h.id)),C=await c(I.map(B=>B.hub.id)),O=I.map(i),q=await l(O);return I.map((B,z)=>s(A,{...B,attachments:C.get(B.hub.id)??[]},O[z],q))},F=new Map,H=async A=>{if(!D.disableUserIdCache&&F.has(A))return F.get(A)??null;let E=await f(A);return E!==null&&!D.disableUserIdCache&&F.set(A,E),E},K=async(A,E,{forceRefresh:I=!1,snapshot:C=!1,ttlMsOverride:O,onFetchStart:q,admission:B}={})=>{let z=await H(E);if(!z)return{items:[],streamAnchor:null,snapshot:el};if(Le(A.visible))return{items:[],streamAnchor:await d(),snapshot:el};let L=Zi(z,cr(A)),[G]=await y.getOrFetch({cacheKey:L,fetcher:async()=>{let te=await d(),Z=await b(A,z);if(!Go(Z)){_.warn("ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)");let ce=[...Z].sort(An);return[{items:ce,streamAnchor:te,snapshot:Ar(ce)}]}return[{items:Z,streamAnchor:te,snapshot:Ar(Z)}]},onFetchStart:q,forceRefresh:I,snapshot:C,admission:B,ttlMsOverride:O??k,epochKey:Tt,refreshAheadRatio:.5});if(G===void 0)throw new Error("[daily-report] getDailyReportIdsByExternalId: the ids cache returned no record");return G},ee=(A,E,{forceRefresh:I=!1,snapshot:C=!1,ttlMsOverride:O}={})=>{let q=Pe(E);return q?Le(A.visible)?Promise.resolve([]):y.getOrFetch({cacheKey:es(q,cr(A)),fetcher:()=>$(A,q),forceRefresh:I,snapshot:C,ttlMsOverride:O??v}):Promise.resolve([])},W=async(A,E,I)=>{let C=await a(R.select({hub:Je(h),internal:Je(g),isRead:j.isRead,isStarred:j.isStarred,creatorName:p.displayName,hasDraftLabel:n,...o()}).from(h)).leftJoin(g,(0,Y.eq)(h.id,g.hubId)).leftJoin(j,(0,Y.and)((0,Y.eq)(h.id,j.hubId),(0,Y.eq)(j.userId,E))).leftJoin(p,(0,Y.eq)(h.userId,p.id)).where((0,Y.and)(I,(0,Y.isNull)(h.deletedAt),t(E,"author"),r(A.visible))).orderBy((0,Y.desc)(h.id));if(C.length===0)return[];let O=C.map(ce=>ce.hub.id),q=await R.select({hubId:M.hubId,id:x.id,name:x.name,color:x.color}).from(M).innerJoin(x,(0,Y.eq)(M.labelId,x.id)).where((0,Y.inArray)(M.hubId,O)),B=await R.select({hubId:P.hubId,id:P.id,body:P.body,createdAt:P.createdAt,userId:P.userId,userName:p.displayName}).from(P).leftJoin(p,(0,Y.eq)(P.userId,p.id)).where((0,Y.inArray)(P.hubId,O)).orderBy((0,Y.asc)(P.createdAt)),z=await c(O),L=new Map,G=new Map;for(let ce of q){let Ce=L.get(ce.hubId);Ce||(Ce=[],L.set(ce.hubId,Ce)),Ce.push({id:ce.id,name:ce.name,color:ce.color})}for(let ce of B){let Ce=G.get(ce.hubId);Ce||(Ce=[],G.set(ce.hubId,Ce)),Ce.push({id:ce.id,content:ce.body,createdAt:be(ce.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:ce.userId,userName:ce.userName||""})}let te=C.map(i),Z=await l(te);return C.map((ce,Ce)=>{let At=ce.hub.id;return s(A,{...ce,attachments:z.get(At)??[],labels:L.get(At)||[],postedCommentRows:G.get(At)||[]},te[Ce],Z,E)})},ae=async(A,E,I,{forceRefresh:C=!1,snapshot:O=!1,ttlMsOverride:q,admission:B}={})=>{let z=await H(I);if(!z)return[];let L=Pe(E);if(!L)return[];if(Le(A.visible))return[];let G=ts(L,z,cr(A));return y.getOrFetch({cacheKey:G,fetcher:()=>W(A,z,(0,Y.eq)(h.businessDate,Y.sql`${L}`)),forceRefresh:C,snapshot:O,admission:B,ttlMsOverride:q??v,epochKey:`${Fe}${L}`})},Te=async(A,E,I,{forceRefresh:C=!1,snapshot:O=!1,ttlMsOverride:q,admission:B}={})=>{if(Le(A.visible))return null;let z=rs(E,I,cr(A));return(await y.getOrFetch({cacheKey:z,fetcher:async()=>{let G=await a(R.select({hub:Je(h),internal:Je(g),isRead:j.isRead,isStarred:j.isStarred,creatorName:p.displayName,hasDraftLabel:n,...o()}).from(h)).leftJoin(g,(0,Y.eq)(h.id,g.hubId)).leftJoin(j,(0,Y.and)((0,Y.eq)(h.id,j.hubId),(0,Y.eq)(j.userId,I))).leftJoin(p,(0,Y.eq)(h.userId,p.id)).where((0,Y.and)((0,Y.eq)(h.id,E),(0,Y.isNull)(h.deletedAt),t(I,"author"),r(A.visible)));if(G.length===0)return[];let te=G[0].hub.id,Z=await R.select({id:x.id,name:x.name,color:x.color}).from(M).innerJoin(x,(0,Y.eq)(M.labelId,x.id)).where((0,Y.eq)(M.hubId,te)),ce=await R.select({id:P.id,body:P.body,createdAt:P.createdAt,userId:P.userId,userName:p.displayName}).from(P).leftJoin(p,(0,Y.eq)(P.userId,p.id)).where((0,Y.eq)(P.hubId,te)).orderBy((0,Y.asc)(P.createdAt)),Ce=await c([te]),At=Z.map(qe=>({id:qe.id,name:qe.name,color:qe.color})),an=ce.map(qe=>({id:qe.id,content:qe.body,createdAt:be(qe.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:qe.userId,userName:qe.userName||""})),Sr=i(G[0]),sn=await l([Sr]);return[s(A,{...G[0],attachments:Ce.get(te)??[],labels:At,postedCommentRows:an},Sr,sn,I)]},forceRefresh:C,snapshot:O,admission:B,ttlMsOverride:q??v,epochKey:`${Qe}${E}`}))[0]??null};return{getUserIdByExternalId:H,getDailyReportIdsByExternalId:K,getDailyReportIdsFirstPageByExternalId:N,getDailyReportsByBusinessDate:ee,getDailyReportsByBusinessDateByExternalId:ae,getDailyReportDetailById:Te,getDailyReportDetailByIdByExternalId:async(A,E,I,C={})=>{let O=await H(I);return O?Te(A,E,O,C):null},getDailyReportDetailsByIdsByExternalId:async(A,E,I)=>{if(E.length>we.maxDetailIds)throw X("getDailyReportDetailsByIdsByExternalId: reportHubIds",`at most ${we.maxDetailIds} ids`,E.length);let C=await H(I);return!C||E.length===0?[]:Le(A.visible)?[]:W(A,C,(0,Y.inArray)(h.id,[...E]))},fetchVisibleHubDetails:W,invalidateHubReadCaches:async(A,E)=>{y.invalidatePrefix(gt),y.invalidatePrefix(St),await u(Tt);for(let I of new Set(A))y.invalidatePrefix(Ye(I)),await u(`${Qe}${I}`);for(let I of new Set(E)){let C=Pe(I);C&&await u(`${Fe}${C}`)}},clearCache:async()=>{y.clearAll(),F.clear(),S&&await u(Tt),_.info("Server-side DB/SQL caches cleared successfully.")}}};var rn=Object.freeze({idsTtlMs:18e4,businessDateTtlMs:3e5,streamKey:"daily-report:sse-stream",streamMaxLen:1e4}),$p=e=>{let{length:t}=e;if(t===void 0)throw X("tables.hub.title","a character column with a declared length",t);return de("tables.hub.title.length",t,1)},Vp=e=>{if(!Array.isArray(e)||e.length===0||e.some(t=>typeof t!="string"||t.trim().length===0)||new Set(e).size!==e.length)throw X("draftLabelNames","one or more non-blank label names",e);return Object.freeze([...e])},Yp=e=>{let t=new Map([[Ke.toLowerCase(),`the internal source type ${JSON.stringify(Ke)}`]]);for(let[r,{sourceType:n}]of e.entries()){let o=`externalSources[${r}].sourceType`,a=t.get(n.toLowerCase());if(a!==void 0)throw X(o,`a source type that differs, ignoring case, from ${a}`,n);t.set(n.toLowerCase(),`${o} ${JSON.stringify(n)}`)}return Object.freeze([Ke,...e.map(r=>r.sourceType)])},rl=e=>{let t=e.externalSources??[],r=Vp(e.draftLabelNames);Fr(e);let n=pi(e.attachments),o=$p(e.tables.hub.title),a=Me("idsTtlMs",e.idsTtlMs,1,rn.idsTtlMs),i=Me("businessDateTtlMs",e.businessDateTtlMs,1,rn.businessDateTtlMs),l=Me("streamMaxLen",e.streamMaxLen,1,rn.streamMaxLen);return Object.freeze({externalSources:t,sourceTypes:Yp(t),draftLabelNames:r,canonicalDraftLabelName:r[0],attachmentDelivery:n,titleMaxLength:o,idsTtlMs:a,businessDateTtlMs:i,streamKey:e.streamKey??rn.streamKey,streamMaxLen:l,disableUserIdCache:!!e.disableUserIdCache})};var xe=require("drizzle-orm");var nl=(e,{draftVisibleTo:t,incrementRedisEpoch:r})=>{let{db:n,tables:o,cache:a,publishToSseStream:i}=e,{hub:l,userStatus:s}=o,c=async(m,p)=>{let[f]=await n.select({sourceType:l.sourceType,deletedAt:l.deletedAt}).top(1).from(l).where((0,xe.and)((0,xe.eq)(l.id,m),t(p,"author")));return f??null},d=async(m,p,f)=>{let y=await c(p,f);if(!y||y.deletedAt||!Ie(m.visible,y.sourceType))throw new Error("Not Found")};return{assertHubMutable:d,setStarStatus:async(m,p,f,y,S,_)=>{await d(m,f,p);let D=await n.select().top(1).from(s).where((0,xe.and)((0,xe.eq)(s.hubId,f),(0,xe.eq)(s.userId,p))),h;if(D.length>0?D[0].isStarred!==S?h=(await n.update(s).set({isStarred:S,updatedAt:new Date,updatedBy:String(p)}).output().where((0,xe.and)((0,xe.eq)(s.hubId,f),(0,xe.eq)(s.userId,p))))[0]:h=D[0]:h=(await n.insert(s).output().values({hubId:f,userId:p,isStarred:S,isRead:!1,createdAt:new Date,createdBy:String(p),updatedAt:new Date,updatedBy:String(p)}))[0],y){let g=Pe(y);g&&(a.invalidatePrefix(Lt(g,p)),await r(`${Fe}${g}`))}return a.invalidatePrefix(zr(f,p)),await r(`${Qe}${f}`),await i(Tr.parse({type:"status-update",reportHubId:f,recipientRawUserId:p,statusType:"star",value:S,clientTempId:_}),"setStarStatus"),h},setReadStatus:async(m,p,f,y,S,_)=>{await d(m,f,p);let D=await n.select().top(1).from(s).where((0,xe.and)((0,xe.eq)(s.hubId,f),(0,xe.eq)(s.userId,p))),h;if(D.length>0?D[0].isRead!==S?h=(await n.update(s).set({isRead:S,updatedAt:new Date,updatedBy:String(p)}).output().where((0,xe.and)((0,xe.eq)(s.hubId,f),(0,xe.eq)(s.userId,p))))[0]:h=D[0]:h=(await n.insert(s).output().values({hubId:f,userId:p,isRead:S,isStarred:!1,createdAt:new Date,createdBy:String(p),updatedAt:new Date,updatedBy:String(p)}))[0],y){let g=Pe(y);g&&(a.invalidatePrefix(Lt(g,p)),await r(`${Fe}${g}`))}return a.invalidatePrefix(zr(f,p)),await r(`${Qe}${f}`),await i(Tr.parse({type:"status-update",reportHubId:f,recipientRawUserId:p,statusType:"read",value:S,clientTempId:_}),"setReadStatus"),h}}};var qp="v3",fo=e=>`${e}:${qp}`,jp=Object.freeze([]),ho=(e,t,r)=>{let n=e.get(t);n?n.push(r):e.set(t,[r])},nn=(e,t)=>e.get(t)??jp,ol=(e,t)=>[e,t].filter(r=>typeof r=="string"&&r.length>0).join(Vr),Wp=(e,t)=>{let r="the request's AbortSignal (new AbortController().signal for a call that is never aborted)";if(t===void 0)throw it(`${e}: options.signal`,r);if(typeof t!="object"||t===null)throw X(`${e}: options`,"an object carrying the request's AbortSignal",t);let{signal:n}=t;if(n===void 0)throw it(`${e}: options.signal`,r);if(!(n instanceof AbortSignal))throw X(`${e}: options.signal`,r,n);return n};function on(e){let{db:t,tables:r,userTable:n,resolveUserId:o,encodeUserId:a,redis:i,cache:l,epochs:s}=e,{hub:c,internal:d,comment:u,label:R,hubLabel:m}=r,p=rl(e),{externalSources:f,draftLabelNames:y,attachmentDelivery:S,titleMaxLength:_}=p,D=ge(e.logger,1,"Service"),h=re=>(0,Gt.runWithTransactionRetry)(ue=>t.transaction(Q=>ue(()=>re(Q))),e.transactionRetry),g=e.search===void 0?null:Ds(e.search,f.map(re=>re.sourceType)),P={hub:c,hubLabel:m,label:R},x=g===null?null:ks({tables:{...P,search:g.tables},draftLabelNames:y});g!==null&&ro();let M=null,j=async()=>{if(g===null)return null;if(M===null){let re=await ro(),ue=g.externalSourceTexts;M=Os({hub:c,tables:g.tables,loadSources:(Q,ne)=>Pl(Q,ne,ue),inTransaction:h,normalizerVersion:re})}return M},k=fo(p.streamKey),{incrementRedisEpoch:v,publishToSseStream:b,readSseStreamAnchor:N}=Js({redis:i,logger:D,epochs:s,streamKey:k,streamMaxLen:p.streamMaxLen}),$={db:t,tables:r,users:n,resolveUserId:o,encodeUserId:a,cache:l,epochs:s,logger:D,settings:p,draftVisibilityTables:P,inTransaction:h,publishToSseStream:b,prepareSearchIndex:j},{visibleSourceTypeCondition:F,draftVisibleTo:H,draftLabelFlag:K,isDraftReport:ee,externalSelections:W,applyExternalJoins:ae,resolveHubDisplayFields:Te,readCanonicalDraftLabelId:ke,getDraftLabelId:Re,resolveCreationCategoryDraftLabelId:J,mapHubRecord:w}=Gs($),{getAttachmentsByHubIds:A,getAttachmentForUser:E,markAttachmentMissing:I,markAttachmentPresent:C}=Ks($,{draftVisibleTo:H,visibleSourceTypeCondition:F}),{getUserIdByExternalId:O,getDailyReportIdsByExternalId:q,getDailyReportIdsFirstPageByExternalId:B,getDailyReportsByBusinessDate:z,getDailyReportsByBusinessDateByExternalId:L,getDailyReportDetailById:G,getDailyReportDetailByIdByExternalId:te,getDailyReportDetailsByIdsByExternalId:Z,fetchVisibleHubDetails:ce,invalidateHubReadCaches:Ce,clearCache:At}=tl($,{draftVisibleTo:H,visibleSourceTypeCondition:F,draftLabelFlag:K,externalSelections:W,applyExternalJoins:ae,resolveHubDisplayFields:Te,resolveCreationCategoryDraftLabelId:J,mapHubRecord:w,getAttachmentsByHubIds:A,readSseStreamAnchor:N,incrementRedisEpoch:v}),{assertHubMutable:an,setStarStatus:Sr,setReadStatus:sn}=nl($,{draftVisibleTo:H,incrementRedisEpoch:v}),{addComment:qe,deleteComment:Al}=Qs($,{isDraftReport:ee,assertHubMutable:an,incrementRedisEpoch:v}),{createDailyReport:El,updateDailyReport:wl,publishDailyReport:Il,deleteDailyReport:_l}=Zs($,{readCanonicalDraftLabelId:ke,isDraftReport:ee,getDailyReportDetailById:G,incrementRedisEpoch:v}),xl=async(re,ue)=>{let Q=new Map,ne=r.attachment;if(!ne||S===null)return Q;let De=await re.select({hubId:ne.hubId,fileName:ne.fileName}).from(ne).where((0,fe.inArray)(ne.hubId,[...ue])).orderBy((0,fe.asc)(ne.hubId),(0,fe.asc)(ne.createdAt),(0,fe.asc)(ne.id));for(let oe of De)ho(Q,Number(oe.hubId),String(oe.fileName));return Q},Cl=async(re,ue,Q)=>{let ne=new Map;for(let[De,oe]of Q){let Xe=new Map;for(let{hub:Ne}of ue)Ne.sourceType===De&&Ne.sourceIdNum!==null&&Xe.set(Ne.sourceIdNum,Ne.id);if(Xe.size===0)continue;let Et=await oe(re,[...Xe.keys()]);for(let[Ne,ht]of Et){let Kt=Xe.get(Ne);if(Kt===void 0)throw X(`search.externalSourceTexts.${De} answer key`,"a source id that was asked for",Ne);if(!(Array.isArray(ht)&&ht.every(Ot=>typeof Ot=="string")))throw X(`search.externalSourceTexts.${De} answer for ${Ne}`,"an array of strings",ht);ne.set(Kt,ht)}}return ne},Ml=(re,ue)=>{let Q=Te(re),ne=[["subject",re.hub.title],["content",Q.content],["author",Q.author],["employeeName",Q.employeeName],["updatedBy",Q.updatedBy],["category",Q.category],["creationCategory",Q.creationCategory],["customerName",Q.customerName]];for(let oe of Q.interviewers)ne.push(["interviewerName",oe.name??null],["interviewerAffiliation",oe.affiliation??null]);for(let oe of ue.labelNames)ne.push(["label",oe]);for(let oe of ue.attachmentNames)ne.push(["attachment",oe]);for(let oe of ue.extraTexts)ne.push(["extra",oe]);let De=[];for(let oe of Q.externalComments)De.push({authorUserId:null,text:ol(oe.name,oe.text)});for(let oe of ue.postedComments)De.push({authorUserId:oe.userId,text:ol(oe.userName,oe.body)});return{hubId:re.hub.id,fields:ne,comments:De,filterValues:{authorName:Q.employeeName,customerName:Q.customerName}}},Pl=async(re,ue,Q)=>{let ne=[];for(let De of(0,Gt.chunk)(ue,Gt.MAX_IN_LIST)){let oe=await ae(re.select({hub:Je(c),internal:Je(d),creatorName:n.displayName,...W()}).from(c)).leftJoin(d,(0,fe.eq)(c.id,d.hubId)).leftJoin(n,(0,fe.eq)(c.userId,n.id)).where((0,fe.inArray)(c.id,[...De])).orderBy((0,fe.asc)(c.id)),Xe=new Map,Et=await re.select({hubId:m.hubId,name:R.name}).from(m).innerJoin(R,(0,fe.eq)(m.labelId,R.id)).where((0,fe.inArray)(m.hubId,[...De])).orderBy((0,fe.asc)(m.hubId),(0,fe.asc)(R.id));for(let Ee of Et)ho(Xe,Ee.hubId,Ee.name);let Ne=new Map,ht=await re.select({hubId:u.hubId,userId:u.userId,body:u.body,userName:n.displayName}).from(u).leftJoin(n,(0,fe.eq)(u.userId,n.id)).where((0,fe.inArray)(u.hubId,[...De])).orderBy((0,fe.asc)(u.hubId),(0,fe.asc)(u.createdAt),(0,fe.asc)(u.id));for(let Ee of ht)ho(Ne,Ee.hubId,Ee);let Kt=await xl(re,De),Ot=await Cl(re,oe,Q);for(let Ee of oe){let wt=Ee.hub.id;ne.push(Ml(Ee,{labelNames:nn(Xe,wt),postedComments:nn(Ne,wt),attachmentNames:nn(Kt,wt),extraTexts:nn(Ot,wt)}))}}return ne},Ll=(re,ue,Q)=>x===null?Promise.reject(new Error("[daily-report] searchDailyReports: the search setting is not configured")):x.search(t,{criteria:Q,viewerUserId:ue,scope:re}),go=p.sourceTypes,kl=async(re,ue)=>{if(x===null)throw new Error("[daily-report] listDailyReportSearchFacets: the search setting is not configured");let Q=go.filter(oe=>Ie(re.visible,oe)),ne=await x.facetValues(t,{column:"authorName",viewerUserId:ue,scope:re}),De=await x.facetValues(t,{column:"customerName",viewerUserId:ue,scope:re});return{sourceTypes:Q,authors:ne,customers:De}},Nl=async(re,ue,Q,ne,De)=>{let oe=Wp("markDailyReportSearchHits",De);if(x===null)throw new Error("[daily-report] markDailyReportSearchHits: the search setting is not configured");if(ne.length>we.maxDetailIds)throw X("markDailyReportSearchHits: reportHubIds",`at most ${we.maxDetailIds} ids`,ne.length);let Xe=Er(ur(Q));if(ne.length===0||Le(re.visible))return{wordsDigest:Xe,reports:[],deferred:[]};oe.throwIfAborted();let Et=await ce(re,ue,(0,fe.inArray)(c.id,[...ne]));oe.throwIfAborted();let Ne=Q.combine==="union"&&Q.sets.length>=2&&Et.length>0?await x.matchedSets(t,{plan:Q,viewerUserId:ue,scope:re,ids:Et.map(Ee=>Ee.reportHubId)}):null,ht=Et.map(Ee=>{let wt=Ne===null?null:Ne.get(Ee.reportHubId),bo=wt===void 0?0:wt;return{reportHubId:Ee.reportHubId,matchedSets:bo,alternatives:js(Q,bo).flatMap(Ol=>Ol.alternatives),fields:Ws(Ee)}}),Ot=await zs(ht,yo,async()=>{await new Promise(Ee=>setImmediate(Ee)),oe.throwIfAborted()},$s(yo,se));return{wordsDigest:Xe,reports:Ot.reports,deferred:Ot.deferred}},vl=async re=>{let ue=await j();if(ue===null)throw new Error("[daily-report] reconcileSearchIndex: the search setting is not configured");return ue.reconcile(t,re)};return{streamKey:k,attachmentDelivery:S,titleMaxLength:_,searchLimits:g===null?null:{concurrency:g.concurrency,rateLimitPerMinute:g.rateLimitPerMinute},searchFilterSourceTypes:go,clearCache:At,invalidateHubReadCaches:Ce,getUserIdByExternalId:O,getDailyReportIdsByExternalId:q,getDailyReportIdsFirstPageByExternalId:B,readSseStreamAnchor:N,getDailyReportsByBusinessDate:z,getDailyReportsByBusinessDateByExternalId:L,getDailyReportDetailById:G,getDailyReportDetailByIdByExternalId:te,getDailyReportDetailsByIdsByExternalId:Z,getDraftLabelId:Re,searchDailyReports:Ll,markDailyReportSearchHits:Nl,listDailyReportSearchFacets:kl,reconcileSearchIndex:vl,getAttachmentsByHubIds:A,getAttachmentForUser:E,markAttachmentMissing:I,markAttachmentPresent:C,setStarStatus:Sr,setReadStatus:sn,addComment:qe,deleteComment:Al,createDailyReport:El,updateDailyReport:wl,publishDailyReport:Il,deleteDailyReport:_l}}var al=(e,t,r,n)=>{if(!e)return[];try{let o=JSON.parse(e);return Array.isArray(o)?o.map(r).filter(a=>a!==null):(ge(n,1,"ExternalSource").warn(`Unexpected ${t} format: not an array`),[])}catch(o){return ge(n,1,"ExternalSource").warn(`Failed to parse ${t}:`,o),[]}};var fr=require("drizzle-orm"),T=require("drizzle-orm/mssql-core");function il(e,t){let r=(0,T.mssqlSchema)(e),n=t.userTable,o=r.table("DailyReportHub",{id:(0,T.bigint)("id",{mode:"number"}).identity().notNull(),sourceType:(0,T.nvarchar)("source_type",{length:20}).notNull(),sourceId:(0,T.nvarchar)("source_id",{length:100}).notNull(),sourceIdNum:(0,T.bigint)("source_id_num",{mode:"number"}).generatedAlwaysAs(fr.sql`TRY_CAST(source_id AS BIGINT)`),businessDate:(0,T.date)("business_date"),userId:(0,T.bigint)("user_id",{mode:"number"}),title:(0,T.nvarchar)("title",{length:200}),summary:(0,T.nvarchar)("summary",{length:"max"}),createdAt:(0,T.datetime2)("created_at").notNull(),createdBy:(0,T.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,T.datetime2)("updated_at").notNull(),updatedBy:(0,T.nvarchar)("updated_by",{length:50}).notNull(),deletedAt:(0,T.datetime2)("deleted_at"),deletedBy:(0,T.nvarchar)("deleted_by",{length:50})},u=>[(0,T.primaryKey)({name:`${e}_DailyReportHub_pk`,columns:[u.id]}),(0,T.foreignKey)({name:`${e}_DailyReportHub_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),(0,T.index)(`${e}_DailyReportHub_business_date_index`).on(u.businessDate),(0,T.index)(`${e}_DailyReportHub_updated_at_index`).on(u.updatedAt),(0,T.index)(`${e}_DailyReportHub_source_index`).on(u.sourceType,u.sourceId),(0,T.index)(`${e}_DailyReportHub_user_id_index`).on(u.userId),(0,T.index)(`${e}_DailyReportHub_business_date_id_index`).on((0,fr.desc)(u.businessDate),(0,fr.desc)(u.id)),(0,T.index)(`${e}_DailyReportHub_deleted_at_index`).on(u.deletedAt)]),a=r.table("DailyReportInternal",{hubId:(0,T.bigint)("hub_id",{mode:"number"}).notNull(),body:(0,T.nvarchar)("body",{length:"max"}),metadata:(0,T.nvarchar)("metadata",{length:"max"}),createdAt:(0,T.datetime2)("created_at").notNull(),createdBy:(0,T.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,T.datetime2)("updated_at").notNull(),updatedBy:(0,T.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,T.primaryKey)({name:`${e}_DailyReportInternal_pk`,columns:[u.hubId]}),(0,T.foreignKey)({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]})]),i=r.table("DailyReportComment",{id:(0,T.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,T.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,T.bigint)("user_id",{mode:"number"}).notNull(),body:(0,T.nvarchar)("body",{length:"max"}).notNull(),createdAt:(0,T.datetime2)("created_at").notNull(),createdBy:(0,T.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,T.datetime2)("updated_at").notNull(),updatedBy:(0,T.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,T.primaryKey)({name:`${e}_DailyReportComment_pk`,columns:[u.id]}),(0,T.foreignKey)({name:`${e}_DailyReportComment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,T.foreignKey)({name:`${e}_DailyReportComment_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]}),(0,T.index)(`${e}_DailyReportComment_hub_id_index`).on(u.hubId)]),l=r.table("DailyReportLabel",{id:(0,T.bigint)("id",{mode:"number"}).identity().notNull(),userId:(0,T.bigint)("user_id",{mode:"number"}),name:(0,T.nvarchar)("name",{length:50}).notNull(),color:(0,T.nvarchar)("color",{length:20}),sortOrder:(0,T.int)("sort_order"),createdAt:(0,T.datetime2)("created_at").notNull(),createdBy:(0,T.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,T.datetime2)("updated_at").notNull(),updatedBy:(0,T.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,T.primaryKey)({name:`${e}_DailyReportLabel_pk`,columns:[u.id]}),(0,T.foreignKey)({name:`${e}_DailyReportLabel_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),s=r.table("DailyReportHub_Label",{hubId:(0,T.bigint)("hub_id",{mode:"number"}).notNull(),labelId:(0,T.bigint)("label_id",{mode:"number"}).notNull(),createdAt:(0,T.datetime2)("created_at").notNull(),createdBy:(0,T.nvarchar)("created_by",{length:50}).notNull()},u=>[(0,T.primaryKey)({name:`${e}_DailyReportHub_Label_pk`,columns:[u.hubId,u.labelId]}),(0,T.foreignKey)({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,T.foreignKey)({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[u.labelId],foreignColumns:[l.id]})]),c=r.table("DailyReportUserStatus",{hubId:(0,T.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,T.bigint)("user_id",{mode:"number"}).notNull(),isRead:(0,T.bit)("is_read").default(!1).notNull(),isStarred:(0,T.bit)("is_starred").default(!1).notNull(),createdAt:(0,T.datetime2)("created_at").notNull(),createdBy:(0,T.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,T.datetime2)("updated_at").notNull(),updatedBy:(0,T.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,T.primaryKey)({name:`${e}_DailyReportUserStatus_pk`,columns:[u.hubId,u.userId]}),(0,T.foreignKey)({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,T.foreignKey)({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),d=r.table("DailyReportAttachment",{id:(0,T.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,T.bigint)("hub_id",{mode:"number"}).notNull(),uploadedBy:(0,T.bigint)("uploaded_by",{mode:"number"}),sourceKey:(0,T.nvarchar)("source_key",{length:200}).notNull(),fileName:(0,T.nvarchar)("file_name",{length:255}).notNull(),filePath:(0,T.nvarchar)("file_path",{length:"max"}).notNull(),fileType:(0,T.nvarchar)("file_type",{length:100}),fileSize:(0,T.bigint)("file_size",{mode:"number"}),objectCheckedAt:(0,T.datetime2)("object_checked_at"),objectMissingAt:(0,T.datetime2)("object_missing_at"),createdAt:(0,T.datetime2)("created_at").notNull(),createdBy:(0,T.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,T.datetime2)("updated_at").notNull(),updatedBy:(0,T.nvarchar)("updated_by",{length:50}).notNull()},u=>[(0,T.primaryKey)({name:`${e}_DailyReportAttachment_pk`,columns:[u.id]}),(0,T.foreignKey)({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),(0,T.foreignKey)({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[u.uploadedBy],foreignColumns:[n.id]}),(0,T.uniqueIndex)(`${e}_DailyReportAttachment_source_unique`).on(u.hubId,u.sourceKey),(0,T.index)(`${e}_DailyReportAttachment_hub_id_index`).on(u.hubId,u.createdAt)]);return{hub:o,internal:a,comment:i,attachment:d,label:l,hubLabel:s,userStatus:c}}var me=require("drizzle-orm/mssql-core");function sl(e){let t=(0,me.mssqlSchema)(e),r=t.table("DailyReportSearchDocument",{hubId:(0,me.bigint)("hub_id",{mode:"number"}).notNull(),searchText:(0,me.nvarchar)("search_text",{length:"max"}).notNull(),sourceDigest:(0,me.binary)("source_digest",{length:32}).notNull(),normalizerVersion:(0,me.varchar)("normalizer_version",{length:64}).notNull(),indexedAt:(0,me.datetime2)("indexed_at").notNull(),rowVersion:(0,me.binary)("row_version",{length:8}).notNull(),authorName:(0,me.nvarchar)("author_name",{length:lt.maxValueLength}),customerName:(0,me.nvarchar)("customer_name",{length:lt.maxValueLength})},o=>[(0,me.primaryKey)({name:`${e}_DailyReportSearchDocument_pk`,columns:[o.hubId]})]),n=t.table("DailyReportSearchComment",{hubId:(0,me.bigint)("hub_id",{mode:"number"}).notNull(),ordinal:(0,me.int)("ordinal").notNull(),authorUserId:(0,me.bigint)("author_user_id",{mode:"number"}),commentText:(0,me.nvarchar)("comment_text",{length:"max"}).notNull()},o=>[(0,me.primaryKey)({name:`${e}_DailyReportSearchComment_pk`,columns:[o.hubId,o.ordinal]})]);return{document:r,comment:n}}var zp=5e7,Ro=2e8,Gp=1,So=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})})}),ll=125,cl=4,ul=16,dl=50,pl=2,Rr=Object.freeze({renderMs:Be.renderMs,nanosecondsPerBlockVisit:ll,margin:cl,maxBlockVisits:Math.floor(Be.renderMs*1e6/(ll*cl)),walkBudgetMs:ul,nanosecondsPerWalkStep:dl,walkMargin:pl,maxWalkSteps:Math.floor(ul*1e6/(dl*pl))}),Kp=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),ml=75,yl=4,hl="#ffffff",Jp=1,Qp={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},Xp=[/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/],fl=Object.freeze({ok:!1,reason:"failed"}),Rl=Object.freeze({ok:!1,reason:"unsupported"}),Sl=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:za(e)}),gl=(e,t)=>{switch(t){case"jpeg":{let r=Wn(e);return r===null?null:Sl(r)}case"png":{let r=Ja(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=Qa(e,Rr.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},bl=(e,t)=>{let r=Kp.get(t.depth);if(r===void 0)return null;let n=t.channels*r,o=So,a=o.wholeImageBuffer[e.layout];return(a.kind==="none"?0:a.kind==="decoded-raster"?t.width*t.height*n:a.kind==="jpeg-coefficients"?e.coefficientBytes:t.width*t.height*a.bytesPerPixel)+o.pipelineRows*t.width*n+o.fixedBytes},Dl=(e,t,r)=>{let n=gl(e,t);return n===null?null:bl(n,r)},Zp=e=>e!==null&&e<=Ro,em=(e,t)=>{if(t!=="jpeg")return gl(e,t);let r=Ga(e,Rr);return r===null||r.blockVisits>Rr.maxBlockVisits?null:Sl(r.header)},tm=e=>{let t=e instanceof Error?e.message:"";return Xp.some(r=>r.test(t))?"failed":"unsupported"},Tl=e=>{e.cache(!1),e.concurrency(Gp),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(Qp)});let t=async(n,o,a,i,l)=>{let s=em(n,o);if(s===null)return Rl;try{let c=e(n,{limitInputPixels:zp,animated:!1});if(!Zp(bl(s,await c.metadata())))return Rl;if(l.aborted)return fl;let d=await c.rotate().resize({width:a,height:i,fit:"inside",withoutEnlargement:!0}).flatten({background:hl}).webp({quality:ml,effort:yl}).toBuffer();return{ok:!0,bytes:new Uint8Array(d),contentType:"image/webp"}}catch(c){return{ok:!1,reason:tm(c)}}},r=async(n,{format:o,maxWidth:a,maxHeight:i,signal:l})=>l.aborted?fl:t(n,o,a,i,l);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${ml}-e${yl}/flatten-${hl}/v${Jp}`,render:r}};function rm(e){e.redis||ge(e.logger,2,"Server").warn("redis provider is not injected: cross-worker cache invalidation is disabled (staleness is bounded only by TTL) and SSE publishing is skipped.");let t=gr(e.redis),r=new Ft({defaultTtlMs:e.cacheDefaultTtlMs,maxBuckets:e.cacheMaxBuckets,maxBytes:e.cacheMaxBytes},t),n=on({...e,cache:r,epochs:t}),o=new Wt({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),a=Jr({authenticate:e.authenticate,resolveVisibleSourceTypes:e.resolveVisibleSourceTypes,service:n,encodeUserId:e.encodeUserId,redis:e.redis,sseReader:o,streamKey:n.streamKey,loginRedirectPath:e.loginRedirectPath,enableDevCacheClear:e.enableDevCacheClear,logger:e.logger});return{service:n,cache:r,epochs:t,sseReader:o,streamKey:n.streamKey,knownSourceTypes:n.searchFilterSourceTypes,...a}}0&&(module.exports={DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,DAILY_REPORT_SSE_CATCH_UP_BATCH,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,DailyReportSseReader,DailyReportViewerScope,SqlResultCache,buildDailyReportSseStreamKey,createDailyReportHandlers,createDailyReportServer,createDailyReportService,createEpochStore,createSharpThumbnailRenderer,defineDailyReportSchema,defineDailyReportSearchSchema,encodeIdsStreamRows,isStreamIdLte,parseClientTempId,predictSharpThumbnailWorkingSetBytes,readDailyReportSseStreamEntry,transformJsonArray});
12
12
  /* v8 ignore next -- @preserve 到達不能: 時間切れと中断の購読はどちらも cleanup で同時に外れ、枠を渡すときも先に cleanup するので、列にいない待機者でここへは来ない。それでも splice(-1) が別の待機者を消さないよう残す */