@aiquants/daily-report 0.36.0 → 0.38.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +110 -3
- package/README.md +145 -56
- package/dist/client.d.mts +39 -8
- package/dist/client.d.ts +39 -8
- package/dist/client.js +5 -5
- package/dist/client.mjs +5 -5
- package/dist/{comment-adapter-pzx3O8_h.d.mts → comment-adapter-BsbOiHmX.d.mts} +1 -1
- package/dist/{comment-adapter-BvGGQkBE.d.ts → comment-adapter-CldlCy1v.d.ts} +1 -1
- package/dist/index.d.mts +7 -3
- package/dist/index.d.ts +7 -3
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/search-filters-wire-5MWi6GWu.d.mts +12 -0
- package/dist/search-filters-wire-5MWi6GWu.d.ts +12 -0
- package/dist/server.d.mts +83 -25
- package/dist/server.d.ts +83 -25
- package/dist/server.js +10 -10
- package/dist/server.mjs +10 -10
- package/dist/styles/daily-report.standalone.css +1 -1
- package/package.json +1 -1
- package/dist/{search-marks-wire-DCFuK5yr.d.mts → search-marks-wire-CZRU4q3h.d.mts} +0 -0
- package/dist/{search-marks-wire-DCFuK5yr.d.ts → search-marks-wire-CZRU4q3h.d.ts} +0 -0
- package/dist/{sse-schema-getLS62T.d.mts → sse-schema-byewDmZK.d.mts} +52 -52
- package/dist/{sse-schema-getLS62T.d.ts → sse-schema-byewDmZK.d.ts} +52 -52
package/dist/server.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";var xr=Object.defineProperty;var is=Object.getOwnPropertyDescriptor;var ss=Object.getOwnPropertyNames;var ls=Object.prototype.hasOwnProperty;var wn=e=>{throw TypeError(e)};var cs=(e,t)=>{for(var r in t)xr(e,r,{get:t[r],enumerable:!0})},us=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ss(t))!ls.call(e,o)&&o!==r&&xr(e,o,{get:()=>t[o],enumerable:!(n=is(t,o))||n.enumerable});return e};var ds=e=>us(xr({},"__esModule",{value:!0}),e);var xn=(e,t,r)=>t.has(e)||wn("Cannot "+r);var wt=(e,t,r)=>(xn(e,t,"read from private field"),r?r.call(e):t.get(e)),Cr=(e,t,r)=>t.has(e)?wn("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Pr=(e,t,r,n)=>(xn(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var Ou={};cs(Ou,{DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES:()=>or,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES:()=>nr,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES:()=>An,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL:()=>Bt,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL:()=>Tn,DAILY_REPORT_SSE_CATCH_UP_BATCH:()=>gr,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS:()=>hn,DailyReportSseReader:()=>Dt,DailyReportViewerScope:()=>Ce,SqlResultCache:()=>yt,createDailyReportHandlers:()=>Dr,createDailyReportServer:()=>Lu,createDailyReportService:()=>Tr,createEpochStore:()=>Yt,createSharpThumbnailRenderer:()=>Pi,defineDailyReportSchema:()=>yi,defineDailyReportSearchSchema:()=>hi,isStreamIdLte:()=>Xe,parseClientTempId:()=>Qt,predictSharpThumbnailWorkingSetBytes:()=>Ci,readDailyReportSseStreamEntry:()=>gt,transformJsonArray:()=>pi});module.exports=ds(Ou);var ms=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,le=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${ms(r)}`),pt=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),Mr=(e,t,r)=>le(e,`one of ${r.map(n=>JSON.stringify(n)).join(", ")}`,t),ne=(e,t,r,n)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r&&(n===void 0||t<=n))return t;throw le(e,n===void 0?`an integer >= ${r}`:`an integer from ${r} to ${n}`,t)},it=(e,t,r,n)=>t===void 0?n:ne(e,t,r);var ce=()=>Math.floor(performance.now());var ke=class extends Error{constructor(t){super(`cache miss refused (${t})`),this.name="SqlResultCacheMissRefusal",this.reason=t}},Yt=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{}}}),xt=(e,t)=>t?e.map(r=>structuredClone(r)):e,yt=class{constructor(t,r){this.epochStore=r;this.buckets=new Map;this.inFlight=new Map;this.forcedFetches=new Map;this.maybeRefreshAhead=t=>{let r=t.refreshAheadRatio;if(r===void 0)return;let{cacheKey:n}=t,o=this.buckets.get(n);if(!o)return;let a=t.ttlMsOverride??this.defaultTtlMs;if(a-(o.expireAt-ce())<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:ce()+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 ke(o.signal.aborted?"aborted":"busy");try{for(let h of r)h();let s=await t.fetcher();return this.inFlight.get(n)===a&&this.writeBucket(n,{records:s,expireAt:ce()+(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 ke("aborted");return this.buckets.delete(r),xt(await this.readOwnOrRetry(this.forcedFetch(t),t),o)}let i=this.buckets.get(r);if(i&&i.expireAt>ce())if(t.epochKey){let c=await this.epochStore.getEpoch(t.epochKey);if(c===null||i.epoch===c)return this.maybeRefreshAhead(t),xt(i.records,o);this.buckets.delete(r)}else return this.maybeRefreshAhead(t),xt(i.records,o);let l=this.inFlight.get(r);if(l!==void 0)return xt(await this.readOwnOrRetry(l,t),o);if(a?.signal.aborted)throw new ke("aborted");return xt(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 ke&&(o===void 0||n.reason==="aborted"&&!o.signal.aborted)))throw n;return this.getOrFetch({...r,snapshot:!1})}};this.clearAll=()=>{this.buckets.clear(),this.inFlight.clear()};this.invalidatePrefix=t=>{for(let r of this.buckets.keys())r.startsWith(t)&&this.buckets.delete(r);for(let r of this.inFlight.keys())r.startsWith(t)&&this.inFlight.delete(r)};this.defaultTtlMs=ne("defaultTtlMs",t.defaultTtlMs,1),this.maxBuckets=ne("maxBuckets",t.maxBuckets,1),this.lastSweepAt=ce()}writeBucket(t,r){this.buckets.delete(t),this.buckets.set(t,r);let n=ce();n-this.lastSweepAt>=this.defaultTtlMs&&this.sweepExpired(n);for(let o of this.buckets.keys()){if(this.buckets.size<=this.maxBuckets)break;this.buckets.delete(o)}}sweepExpired(t){this.lastSweepAt=t;for(let[r,n]of this.buckets)n.expireAt<=t&&this.buckets.delete(r)}};var Cn="ids-stream";var qt=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+(?=.)/,"")},Wt=(e,t)=>e.businessDate!==t.businessDate?e.businessDate===null?1:t.businessDate===null||e.businessDate>t.businessDate?-1:1:t.reportHubId-e.reportHubId,Pn=e=>{for(let t=1;t<e.length;t++)if(Wt(e[t-1],e[t])>0)return!1;return!0},Mn=(e,t)=>{let r=e.findIndex(n=>Wt({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var ue=Object.freeze({businessDate:"business-date",idsStream:Cn,report:"report",search:"search",reports:"reports",searchMarks:"search-marks",action:"action"}),Ae=Object.freeze({businessDate:"businessDate",reportHubId:"reportHubId",searchQuery:"q",searchCombine:"combine",reportIds:"ids",forceRefresh:"forceRefresh",cursorReportHubId:"cursor_report_hub_id",cursorBusinessDate:"cursor_business_date",cursorSnapshot:"cursor_snapshot"});var ps=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var Ln=e=>e<10?`0${e}`:`${e}`,ys=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=Ln(e.getMonth()+1),n=Ln(e.getDate());return`${t}-${r}-${n}`},ht=e=>{let t=ps.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}`},jt=e=>ht(e)===e;var Pe=e=>e==null?null:e instanceof Date?ys(e):ht(e);var On=(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)}}},qu=Object.freeze(["API","Action","Attachment","ExternalSource","Isolation","Reads","Refresh","Search","SSE","SseReader","Server","Service","Streams","Visibility","ActionProvider","DetailLoader","SseConnection"]),Nn=e=>`[DailyReport${e}]`,fe=(e,t,r)=>e===void 0?On(t,Nn(r)):On(0,Nn(r),e);var hs="legacy-",Lr=e=>`${hs}${e}`;var vn=require("zod"),ft=e=>Number.isSafeInteger(e)&&e>0,De=vn.z.number().int().positive().max(Number.MAX_SAFE_INTEGER);var fs=/^[1-9][0-9]*$/,Rs=/^(?:0|[1-9][0-9]*)$/,He=e=>{if(e===null||!fs.test(e))return null;let t=Number(e);return ft(t)?t:null},Or=e=>{if(e===null||!Rs.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null},Nr=e=>e==="true"?!0:e==="false"?!1:null,Ct=e=>e===null?!1:Nr(e);var kn=Object.freeze(["subject","content","author","employeeName","updatedBy","category","creationCategory","customerName"]),ze=Object.freeze({field:e=>e,interviewer:(e,t)=>`interviewer:${e}:${t}`,attachment:e=>`attachment:${e}`,comment:(e,t)=>`comment:${e}:${t}`});var Ss=2166136261,gs=16777619,vr=e=>{let t=Ss;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,gs);return t>>>0},bs=String.fromCodePoint(3),Ds=String.fromCodePoint(2),As=String.fromCodePoint(1),zt=e=>vr(e.map(t=>t.map(r=>r.map(n=>`${n.tier}${n.text}`).join(bs)).join(Ds)).join(As));var Hn=e=>e==="intersection"||e==="union",Ee=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),kr=2,Un=2,Hr=(e,t)=>({ids:e.map(r=>r.reportHubId),businessDates:e.map(r=>r.businessDate),sourceTypes:e.map(r=>r.sourceType),words:t});var Qu=2*(1+kr);var Cs=require("zod");var Gt=/^(?:[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 $n=15e3,Bn="lastEventId",Ts=/^\d{1,15}-\d{1,15}$/,Fn=e=>Ts.test(e),Es=P.z.object({name:P.z.string().nullish(),affiliation:P.z.string().nullish()}),Is=P.z.object({name:P.z.string().nullish(),text:P.z.string().nullish(),color:P.z.string().nullish()}),_s=P.z.object({id:De,name:P.z.string().nullish(),color:P.z.string().nullish()}),Vn=P.z.object({id:De,userId:P.z.string().nullish(),userName:P.z.string().nullish(),content:P.z.string().nullish(),createdAt:P.z.string().nullish(),isMine:P.z.boolean()}),ws=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)}),Ur=P.z.object({reportHubId:De,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(Es),subject:P.z.string().nullish(),content:P.z.string().nullish(),externalComments:P.z.array(Is),isRead:P.z.boolean(),isStarred:P.z.boolean(),labels:P.z.array(_s),postedComments:P.z.array(Vn),attachments:P.z.array(ws).default([])}),st=P.z.string().regex(Gt),xs=P.z.object({type:P.z.literal("connected")}),Kt=P.z.object({type:P.z.literal("status-update"),reportHubId:De,statusType:P.z.enum(["star","read"]),value:P.z.boolean(),clientTempId:st,recipientRawUserId:De.optional()}),$r=P.z.string().optional(),Br=P.z.object({type:P.z.literal("comment-add"),reportHubId:De,comment:Vn,clientTempId:st,recipientRawUserId:De.optional(),sourceType:$r}),Fr=P.z.object({type:P.z.literal("comment-delete"),reportHubId:De,commentId:De,clientTempId:st,recipientRawUserId:De.optional(),sourceType:$r}),Vr=P.z.object({type:P.z.literal("report-create"),reportHubId:De,report:Ur,clientTempId:st,recipientRawUserId:De.optional()}),Yr=P.z.object({type:P.z.literal("report-update"),reportHubId:De,report:Ur,clientTempId:st,recipientRawUserId:De.optional()}),qr=P.z.object({type:P.z.literal("report-publish"),reportHubId:De,report:Ur,clientTempId:st,recipientRawUserId:De.optional()}),Wr=P.z.object({type:P.z.literal("report-delete"),reportHubId:De,clientTempId:st,sourceType:$r}),Yn=P.z.discriminatedUnion("type",[xs,Kt,Br,Fr,Vr,Yr,qr,Wr]);var Me=Object.freeze({intent:"intent",clientTempId:"clientTempId",businessDate:"businessDate",operationTimestamp:"operationTimestamp",reportHubId:"reportHubId",title:"title",content:"content",isStarred:"isStarred",isRead:"isRead",commentId:"commentId"});var Jt=Math.max(1,Math.floor(10.556701030927835));var Ue=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var Le=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),Ue(()=>{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 Qt=e=>e!==null&&Gt.test(e)?e:null,jr=e=>Hn(e)?e:null,zr=e=>{if(e===null)return null;let t=e.split(",");if(t.length>Ee.maxDetailIds)return null;let r=[];for(let n of t){let o=He(n);if(o===null||r.includes(o))return null;r.push(o)}return r},qn=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var jn=Object.freeze({status:400,error:"Invalid form"}),zn=e=>({status:413,error:"Form too large",measuredBy:e}),Ps=(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)}}))},Ms=async e=>{let t=Or(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:zn("declared")};let r=!1,n=e.body===null?null:Ps(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?zn("counted"):jn}}let l=qn(i);return l===null?{refusal:jn}:{fields:l}},Gn=(e,t)=>(r,n)=>{let o=r.get(t);if(o===null)return{error:`${t} required`};let a=Nr(o);return a===null?{error:`Invalid ${t}`}:{command:{...n,intent:e,value:a}}},Jn=Object.freeze({update:(e,t,r)=>{let n=e.get(Me.title),o=e.get(Me.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:Gn("toggleStar",Me.isStarred),toggleRead:Gn("toggleRead",Me.isRead),addComment:(e,t)=>{let r=e.get(Me.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=He(e.get(Me.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),Ls=e=>Object.hasOwn(Jn,e),Os=(e,t)=>{let r=e.get(Me.intent),n=e.get(Me.businessDate),o=n===null?null:ht(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get(Me.operationTimestamp),i=Or(a);if(a!==null&&i===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get(Me.clientTempId);if(!l)return{error:"clientTempId required"};let c=Qt(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=He(e.get(Me.reportHubId));return s===null?{error:"Invalid reportHubId"}:r===null||!Ls(r)?{error:"Invalid intent"}:Jn[r](e,{clientTempId:c,businessDate:o,operationTimestamp:i,reportHubId:s},t)},Qn=async(e,t)=>{let r=await Ms(e);if("refusal"in r)return r;let n=Os(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},Ns=6e4,vs="form_too_large",Kn=["declared","counted"],Xn=e=>{let t=Le({windowMs:Ns,tallies:Kn,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${Kn.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(vs,r,n)}};var tt=Object.freeze({[ue.businessDate]:{body:"json",admission:["refresh-bucket","cache","miss-gate"]},[ue.idsStream]:{body:"stream",admission:["refresh-bucket","stream-slots","cache","miss-gate"]},[ue.report]:{body:"json",admission:["refresh-bucket","cache","miss-gate"]},[ue.search]:{body:"json",admission:["search-limiter"]},[ue.reports]:{body:"json",admission:["search-limiter"]},[ue.searchMarks]:{body:"json",admission:["search-limiter"]}}),Zn=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),Gr=e=>e!==void 0&&Object.hasOwn(tt,e);var Kr=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),eo=e=>Object.hasOwn(Kr,e);var ks="download",Hs="thumbnail",Us="1";var Jr=e=>{let t=e.getAll(Hs),r=e.getAll(ks);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&eo(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===Us?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};var to=require("crypto"),Qr=e=>`"${(0,to.createHash)("sha256").update(e).digest("hex")}"`,ro=e=>Qr(JSON.stringify(e));var Ge=Object.freeze({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'"}),Xr=(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},ee=(e,t,r,n=200)=>{let o=JSON.stringify(r),a=Qr(o),i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate",ETag:a,...Ge});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&Xr(e.headers.get("If-None-Match"),a)?new Response(null,{status:304,headers:i}):new Response(o,{status:n,headers:i})},$s=5e3/1e3,Bs=new Map([[503,$s]]),$e=e=>{let t=Bs.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var en="Cross-site request rejected",Fs="Not Found",Vs=new Set(["same-origin","none"]),Ys=new Set(["GET","HEAD","OPTIONS"]),no=["api","action","sse","attachment"],oo=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...Ge}}),qs=()=>oo(403,en),Xt=()=>oo(404,Fs),Pt=Object.freeze({navigable:()=>!1,frameworkDataRefusal:()=>null,crossSiteRejection:qs}),ao=e=>new URL(e.url).pathname.endsWith(".data"),Ws=e=>{let t=e.headers.get("Origin");return t===null?!0:URL.canParse(t)&&new URL(t).host===new URL(e.url).host},io=(e,t)=>{let r=e.headers.get("Sec-Fetch-Site");return r===null?!(Ys.has(e.method)||Ws(e)):Vs.has(r)?!1:!(e.method==="GET"&&e.headers.get("Sec-Fetch-Mode")==="navigate"&&e.headers.get("Sec-Fetch-Dest")==="document"&&t.navigable(e))},js=6e4,zs="refusals",Gs=32,Ks=/^[a-z-]+$/,Zr=e=>{if(e===null)return"-";let t=e.slice(0,Gs);return Ks.test(t)&&t===e?e:JSON.stringify(t)},so=e=>{let t=Le({windowMs:js,tallies:no,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${no.map(i=>`${i}:${a[i]}`).join(",")}`)}});return(r,n)=>{let o=()=>{let{headers:a}=n;e.warn(`cross_site_rejected route=${r} site=${Zr(a.get("Sec-Fetch-Site"))} mode=${Zr(a.get("Sec-Fetch-Mode"))} dest=${Zr(a.get("Sec-Fetch-Dest"))} method=${n.method}`)};t.record(zs,r,o)}};var lo=(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 Js="same-origin",Qs="SAMEORIGIN",Rt=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":Js,"X-Frame-Options":Qs}),Zt=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...Rt});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},co=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),Xs=/^[\x20-\x7E]+$/,Zs=/^[\w.+-]+\/[\w.+-]+/,tn=e=>e&&Xs.test(e)&&Zs.test(e)?e:null,el=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,uo=e=>encodeURIComponent(e.replace(el,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),mo=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),er={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},po={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},tr=e=>typeof e=="string"&&Object.hasOwn(po,e),rr=e=>po[e],Ke="Attachment request failed";var Fe=e=>{let t=ne("limit",e.limit,1),r=ne("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:ne("queue.max",e.queue.max,0),maxPerOwner:ne("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:ne("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],i=new Map,l=new Map,c=(S,T)=>S.get(T)??0,s=(S,T,N)=>{let H=c(S,T)+N;H<=0?S.delete(T):S.set(T,H)},h=S=>c(l,S)<r,m=S=>o<t&&h(S),b=S=>(o+=1,s(l,S,1),g(S)),f=()=>{for(;o<t;){let S=a.findIndex(N=>h(N.owner));if(S<0)return;let[T]=a.splice(S,1);s(i,T.owner,-1),T.grant(b(T.owner))}},g=S=>{let T=!1;return()=>{T||(T=!0,o-=1,s(l,S,-1),f())}};return{canAcquire:m,acquire:(S,T)=>{if(T.aborted)return Promise.resolve(null);if(m(S))return Promise.resolve(b(S));if(n===null||a.length>=n.max||c(i,S)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:N}=n,H=W=>{let x=()=>{let $=a.indexOf(U);$<0||(a.splice($,1),s(i,S,-1),B(),W(null))},_=Ue(x,N),B=()=>{clearTimeout(_),T.removeEventListener("abort",x)},U={owner:S,grant:$=>{B(),W($)}};a.push(U),s(i,S,1),T.addEventListener("abort",x,{once:!0})};return new Promise(H)}}};var tl=1024,rn="Too many requests",rl=(e,t)=>{ne("limitPerWindow",e,1),ne("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<=tl)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))}}},Je=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(ne("windowMs",r,1e3)%1e3!==0)throw le("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=rl(e.limitPerWindow,r),i=Object.freeze({status:429,message:rn,headers:Object.freeze({"Retry-After":String(r/1e3)})}),l=Le({windowMs:r,tallies:[t],writeSuppressed:(c,{count:s,since:h})=>{n.warn(`${t}_suppressed count=${s} since=${h} ${o(c)}`)}});return{spend:(c,s)=>a.consume(c,ce())?null:(l.record(c,t,()=>n.warn(`429 ${s} reason=${t}`)),i),refund:(c,s)=>{a.refund(c,ce(),s)}}};var ol=256*1024,yo=6e4,al=e=>Math.ceil(e/2),il=new Uint8Array(new ArrayBuffer(0)),sl=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=il,t()},i=l=>{clearTimeout(o),o=Ue(()=>{l.error(new Error(`attachment body idle for ${yo} ms`)),a()},yo)};return new ReadableStream({start(l){i(l)},pull(l){let c=Math.min(n+ol,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})},ho=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=Je({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:c=>`viewer=${c}`}),l=Fe({limit:e.concurrency,maxHeldPerOwner:al(e.concurrency),queue:null});return async c=>{let{request:s,delivery:h,attachmentId:m,internalUserId:b,readAttachment:f,cookie:g,fail:S}=c,T=e.maxBytes,N=i.spend(b,`attachment=${m} viewer=${b}`);if(N)return S(N.status,N.message,N.headers);let H=await n(s),W=await t.getAttachmentForUser(H,m,b);if(!W)return o.warn(`404 attachment=${m} viewer=${b} reason=not_visible`),S(404,"Attachment not found");if(W.fileSize!=null&&W.fileSize>T)return o.warn(`413 attachment=${m} viewer=${b} reason=db_size`),S(413,"Attachment too large");let x=tn(W.fileType),_=`filename="${mo(W.fileName)}"; filename*=UTF-8''${uo(W.fileName)}`,B=await l.acquire(b,s.signal);if(!B)return s.signal.aborted?(o.info(`503 attachment=${m} viewer=${b} reason=aborted`),S(503,"Attachment request aborted")):(o.warn(`503 attachment=${m} viewer=${b} reason=concurrency`),S(503,"Too many concurrent downloads",$e(503)));let U=!1;try{let $=await f(W.filePath,{maxBytes:T,head:s.method==="HEAD",principal:r(b),signal:s.signal});if(s.signal.aborted)return o.info(`503 attachment=${m} viewer=${b} reason=aborted`),S(503,"Attachment request aborted");if(!$.ok){if(!tr($.reason))return o.error(`500 attachment=${m} viewer=${b} reason=port_contract code=failure_reason`),S(500,Ke);let ae=rr($.reason);return $.reason==="not_found"&&a(m,!1),o.warn(`${ae} attachment=${m} viewer=${b} reason=${$.reason} code=${$.code??"-"}`),S(ae,er[ae],$e(ae))}if($.bytes.byteLength>T)return o.error(`500 attachment=${m} viewer=${b} reason=port_contract code=over_max_bytes`),S(500,Ke);let de=s.method==="HEAD";if(de&&$.size!==void 0&&$.size>T)return o.error(`500 attachment=${m} viewer=${b} reason=port_contract code=over_max_bytes`),S(500,Ke);if(!de&&$.size!==void 0&&$.size!==$.bytes.byteLength)return o.error(`500 attachment=${m} viewer=${b} reason=port_contract code=size_mismatch`),S(500,Ke);let be=x??tn($.contentType),me=be!==null&&co.has(be),K=me?be:"application/octet-stream",Z=me&&h.kind!=="download"?"inline":"attachment",oe=de?$.size:$.bytes.byteLength,Re=new Headers({"Content-Type":K,"Content-Disposition":`${Z}; ${_}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...Rt});return oe!==void 0&&Re.set("Content-Length",String(oe)),g&&Re.append("Set-Cookie",g),a(m,!0),o.info(`200 attachment=${m} viewer=${b} type=${K} disposition=${Z} bytes=${oe??"-"}`),de?new Response(null,{status:200,headers:Re}):(U=!0,new Response(sl($.bytes,B),{status:200,headers:Re}))}finally{U||B()}}};var xe=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),Wd=xe.queueWaitMs+xe.readMs+xe.renderMs+xe.transferMarginMs;var So=require("buffer"),go=new Set([194,198,202,206]),ll=new Set([192,193,194,195]),bo=216,cl=217,Do=218,ul=4,dl=64,ml=2,fo=8,Ro=28,rt=12,nn=8,pl=20,Ao=rt+nn+10,yl=2,Qe=(e,t)=>e[t]<<8|e[t+1],St=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];return n},Ve=(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},To=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,Eo=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),Io=e=>(e.stepsLeft-=1,e.stepsLeft>=0),_o=e=>e[0]===255&&e[1]===bo,wo=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!Io(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===cl)return"eoi";if(o===0||o===bo)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=Qe(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")}},hl=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!Io(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}},xo=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=Qe(e,r+1),a=Qe(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],h=s>>4,m=s&15;if(h<1||h>4||m<1||m>4)return null;l.push({id:e[r+6+3*c],horizontal:h,vertical:m})}return{marker:t,width:a,height:o,components:l}},Co=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>ul||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},Po=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:go.has(e.marker)||t<e.components.length}),on=e=>{if(!_o(e))return null;let t=Eo(e.byteLength),r=null;for(let n=2;;){if(wo(e,n,t)!=="segment")return null;if(To(t.marker)){if(r!==null||(r=xo(e,t),r===null))return null}else if(t.marker===Do){if(r===null)return null;let o=Co(e,t);return o===null?null:Po(r,o.length)}n=t.end}},Mo=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*fo)),i=Math.ceil(e.height*o/(r*fo));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},Lo=e=>e.multiScan?Mo(e).reduce((r,n)=>r+n,0)*dl*ml:0,fl=896,Oo=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!_o(e))return null;let n=So.Buffer.from(e.buffer,e.byteOffset,e.byteLength),o=Eo(r),a=null,i=null,l=new Map,c=0,s=0,h=0;for(let m=2;;){let b=wo(e,m,o);if(b===null)return null;if(b==="eoi")return i===null?null:{header:i,blockVisits:s};if(m=o.end,To(o.marker)){if(a!==null||!ll.has(o.marker)||(a=xo(e,o),a===null))return null;let f=Mo(a);l=new Map;for(let[g,S]of a.components.entries()){let T=l.get(S.id);l.set(S.id,T===void 0?f[g]:Math.max(T,f[g]))}c=a.components.length*(go.has(a.marker)?fl:1)}else if(o.marker===Do){if(a===null||h===c)return null;let f=Co(e,o);if(f===null)return null;for(let S of f){let T=l.get(S);if(T===void 0)return null;s+=T}if(h+=1,i===null&&(i=Po(a,f.length)),s>t||!i.multiScan)return{header:i,blockVisits:s};let g=hl(n,o.end,o);if(g===null)return null;m=g}}},No=e=>{if(e.byteLength<24||Qe(e,8)!==0||Qe(e,10)!==13||!Ve(e,12,"IHDR"))return null;let t=Qe(e,16)*65536+Qe(e,18),r=Qe(e,20)*65536+Qe(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},Rl=e=>{if(Ve(e,rt,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=St(e,26,2)&16383,r=St(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(Ve(e,rt,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=St(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return Ve(e,rt,"VP8X")?e.byteLength<Ao?null:{width:St(e,24,3)+1,height:St(e,27,3)+1}:null},vo=e=>{if(No(e)===null||e.byteLength<=Ro)return null;switch(e[Ro]){case 0:return!1;case 1:return!0;default:return null}},ko=(e,t)=>{if(Ve(e,rt,"VP8 "))return"lossy";if(Ve(e,rt,"VP8L"))return"lossless";if(!Ve(e,rt,"VP8X")||e.byteLength<Ao)return null;if((e[pl]&yl)!==0)return"animated";let r=!1,n=t;for(let o=rt;o+nn<=e.byteLength;){if(n-=1,n<0)return null;if(Ve(e,o,"VP8L"))return"lossless";if(Ve(e,o,"VP8 "))return r?"lossy-alpha":"lossy";Ve(e,o,"ALPH")&&(r=!0);let a=St(e,o+4,4);o+=nn+a+a%2}return null},Ho={png:No,jpeg:on,webp:Rl};var nr=Object.freeze(["image/webp","image/jpeg","image/png"]),or=1024*1024;var Sl=new Set(["image/png","image/jpeg","image/gif","image/webp"]),gl={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},bl=new Set(nr),Dl=e=>typeof e=="string"&&bl.has(e),Al=256,ar=(e,t)=>e.fileType===null||!Sl.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,Tl=[137,80,78,71,13,10,26,10],El=[255,216,255],Il=[[71,73,70,56,55,97],[71,73,70,56,57,97]],_l=[82,73,70,70],wl=[87,69,66,80],Mt=(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},an=e=>{if(Mt(e,Tl,0))return"png";if(Mt(e,El,0))return"jpeg";for(let t of Il)if(Mt(e,t,0))return"gif";return Mt(e,_l,0)&&Mt(e,wl,8)?"webp":null},Uo=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:ro([t])}},$o=(e,t)=>{if(!Dl(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>or)return"too_large";let r=gl[e.contentType];if(an(e.bytes)!==r)return"signature";let n=Ho[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},Bo=e=>{ne("maxBytes",e.maxBytes,0),ne("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)+Al;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 sn=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,i=ce(),l=new AbortController,c=!1,s,h,m=()=>{a(ce()-i)},b=x=>{s=Ue(()=>{c=!0,x({timedOut:!0}),h=Ue(m,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},f=new Promise(b),g=AbortSignal.any([r,l.signal]),S=x=>{x(n(g))},T=new Promise(S),N=x=>(clearTimeout(s),clearTimeout(h),c&&o(ce()-i,x.kind==="error"?{error:x.error}:null),x),H=T.then(x=>N({kind:"value",value:x}),x=>N({kind:"error",error:x}));return{outcome:Promise.race([T.then(x=>({timedOut:!1,value:x})),f]),settled:H}};var nt={404:"Attachment not found",500:Ke,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},Fo=(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=$o(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},xl=e=>{let t=new AbortController,r=()=>{t.abort()},n=Ue(r,xe.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},Vo=()=>{},Cl=(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)}),Yo=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:i}=e,l=new Map,c=(f,g)=>{let S=g.then(Vo,Vo);l.set(f,S);let T=()=>{l.get(f)===S&&l.delete(f)};S.then(T)},s=async(f,g)=>{let S=l.get(f.key);if(S===void 0)return t.acquire(f.owner,g);let T=xl(g);try{if(await Cl(S,T.signal),T.signal.aborted)return null;let N=r.get(f.key);return N!==void 0?{...N,identity:"verified"}:await t.acquire(f.owner,T.signal)}finally{T.end()}},h=(f,g)=>{if(f.fileSize===null)return g.kind==="exact"?"verified":"unrecorded";if(g.kind==="exact"?g.bytes===f.fileSize:f.fileSize>g.maxBytes)return"verified";let T=g.kind==="exact"?String(g.bytes):`>${g.maxBytes}`;return i.warn(`size_mismatch expected=${f.fileSize} got=${T} attachment=${f.attachmentId} viewer=${f.owner} variant=thumbnail`),"unverified"},m=(f,g)=>(S,T)=>{let N=T===null?"":` message=${T.error instanceof Error?T.error.message:"unknown"}`;i.warn(`${f}_overrun ms=${S} attachment=${g.attachmentId} viewer=${g.owner} variant=thumbnail${N}`)},b=(f,g)=>S=>{i.warn(`${f}_stuck ms=${S} attachment=${g.attachmentId} viewer=${g.owner} variant=thumbnail`)};return async(f,g)=>{let S=await s(f,g);if(S===null)return{kind:"failure",status:503,reason:g.aborted?"aborted":"queue"};if(typeof S!="function")return S;let T=S,N=null;try{if(g.aborted)return{kind:"failure",status:503,reason:"aborted"};let H=r.get(f.key);if(H!==void 0)return{...H,identity:"verified"};let W=sn({budgetMs:xe.readMs,flightSignal:g,call:ae=>f.readAttachment(f.filePath,{maxBytes:n,head:!1,principal:o(f.owner),signal:ae}),onOverrun:m("read",f),onStuck:b("read",f)}),x=await W.outcome;if(x.timedOut)return N=W.settled,g.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(g.aborted)return{kind:"failure",status:503,reason:"aborted"};let _=x.value;if(!_.ok&&_.reason!=="too_large")return tr(_.reason)?(_.reason==="not_found"&&a(f.attachmentId,!1),{kind:"failure",status:rr(_.reason),reason:_.reason,code:_.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(_.ok&&_.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let B=h(f,_.ok?{kind:"exact",bytes:_.bytes.byteLength}:{kind:"over",maxBytes:n}),U=ae=>{B==="verified"&&r.set(f.key,ae)},$=ae=>(U(ae),{...ae,identity:B});if(!_.ok)return $({kind:"unrenderable",reason:"too_large"});let de=an(_.bytes);if(de===null)return $({kind:"unrenderable",reason:"signature"});let be=sn({budgetMs:xe.renderMs,flightSignal:g,call:ae=>f.renderer.render(_.bytes,{format:de,maxWidth:f.box.maxWidth,maxHeight:f.box.maxHeight,signal:ae}),onOverrun:m("render",f),onStuck:b("render",f)}),me=ae=>{if(ae.kind==="error")return;let Se=Fo(ae.value,f.box);"entry"in Se&&U(Se.entry)},K=null,Z=()=>(K===null&&(K=be.settled.then(me),c(f.key,K)),K);g.addEventListener("abort",Z,{once:!0});let oe=await be.outcome.finally(()=>g.removeEventListener("abort",Z));if(oe.timedOut||g.aborted)return N=Z(),g.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let Re=Fo(oe.value,f.box);return"entry"in Re?$(Re.entry):Re.failure}finally{N===null?T():N.then(T,T)}}};var qo=()=>{let e=new Map;return{join:(t,r,n)=>{let o=()=>{let c=new AbortController,s=()=>{e.get(t)?.controller===c&&e.delete(t)},m={promise:n(c.signal).finally(s),controller:c,waiters:0};return e.set(t,m),m},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 zo=10,Pl=1/zo,Wo=1-Pl,Ml=1024,Ll=64,Ol=8,jo="private, no-cache",Nl="no-store",vl=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),kl=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},Go=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:c}=l,s=(x,_)=>Je({reason:x,limitPerWindow:_,windowMs:6e4,logger:o,windowFields:B=>`viewer=${B} variant=thumbnail`}),h=s("rate_limit",l.rateLimitPerMinute),m=s("revalidation_rate_limit",l.rateLimitPerMinute*zo),b=Fe({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:Ll,maxPerOwner:Ol,maxWaitMs:xe.queueWaitMs}}),f=Bo({maxBytes:l.cacheBytes,maxEntries:Ml}),g=qo(),S=Yo({gate:b,cache:f,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),T=(x,_,B,U)=>{let $=`attachment=${x.attachmentId} viewer=${x.internalUserId} variant=thumbnail cache=${U}`;if(_.kind==="failure")return o[kl(_)](`${_.status} ${$} reason=${_.reason} code=${_.code??"-"}`),x.fail(_.status,nt[_.status],$e(_.status));let de=vl[_.identity];if(_.kind==="unrenderable")return o.info(`404 ${$} reason=${_.reason}${de}`),x.fail(404,nt[404]);let be=_.identity==="verified"?{"Cache-Control":jo,ETag:B}:{"Cache-Control":Nl},me=new Headers({"Content-Type":_.contentType,"Content-Length":String(_.bytes.byteLength),...be,"Content-Security-Policy":"default-src 'none'; sandbox",...Rt});return x.cookie&&me.append("Set-Cookie",x.cookie),o.info(`200 ${$} type=${_.contentType} bytes=${_.bytes.byteLength}${de}`),new Response(_.bytes,{status:200,headers:me})},N=(x,_)=>{let B=x.spend(_.internalUserId,`attachment=${_.attachmentId} viewer=${_.internalUserId} variant=thumbnail`);return B===null?null:_.fail(B.status,B.message,B.headers)},H=x=>N(h,x),W=(x,_)=>_?N(m,x):H(x);return async(x,_)=>{let{request:B,attachmentId:U,internalUserId:$,readAttachment:de,cookie:be,fail:me}=x,K=Kr[_],Z=B.headers.get("If-None-Match"),oe=Z!==null,Re=W(x,oe);if(Re)return Re;let ae=await n(B),Se=await t.getAttachmentForUser(ae,U,$),_e=Se!==null&&ar(Se,i)?Uo({rendererId:c.id,box:K,attachmentId:U,filePath:Se.filePath,fileType:Se.fileType,fileSize:Se.fileSize}):null;if(_e&&Xr(Z,_e.etag)){let I=new Headers({"Cache-Control":jo,ETag:_e.etag,...Rt});return be&&I.append("Set-Cookie",be),o.info(`304 attachment=${U} viewer=${$} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:I})}if(oe){let I=H(x);if(I)return I}if(!Se)return o.warn(`404 attachment=${U} viewer=${$} variant=thumbnail reason=not_visible`),me(404,nt[404]);if(!_e)return h.refund($,Wo),o.info(`404 attachment=${U} viewer=${$} variant=thumbnail reason=not_eligible`),me(404,nt[404]);let{key:we,etag:et}=_e,ve=f.get(we);if(ve)return h.refund($,Wo),T(x,{...ve,identity:"verified"},et,"hit");let M=I=>S({key:we,attachmentId:U,filePath:Se.filePath,fileSize:Se.fileSize,box:K,owner:$,readAttachment:de,renderer:c},I),O;try{O=await g.join(we,B.signal,M)}catch(I){return o.error(`500 attachment=${U} viewer=${$} variant=thumbnail cache=miss reason=port_exception message=${I instanceof Error?I.message:"unknown"}`),me(500,nt[500])}return T(x,O,et,"miss")}};var Hl='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',Ul=()=>Zt(403,en,{cookie:null}),Ko=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=Jr(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>Zt(404,er[404],{cookie:null}),crossSiteRejection:Ul}),Jo=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:lo(r,a)},c=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:ho({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:Go({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:s,params:h})=>{let m=null,b=(f,g,S={})=>Zt(f,g,{cookie:m,extraHeaders:S});try{let{user:f,cookie:g}=await t(s,{failureRedirect:null});if(m=g??null,!f)return b(401,"Unauthorized");let S=Jr(new URL(s.url).searchParams);if(S.kind==="invalid")return b(400,"Invalid attachment request");if(S.kind==="thumbnail"&&s.method!=="GET")return b(405,"Method not allowed",{Allow:"GET"});if(s.method!=="GET"&&s.method!=="HEAD")return b(405,"Method not allowed",{Allow:"GET, HEAD"});if(c===null)return b(404,"Attachment not found");if(h.token===void 0)throw new Error(Hl);let T=c.idCodec.decode(h.token);if(T===null||!ft(T))return b(400,"Invalid attachment token");let N=await r.getUserIdByExternalId(f.id);if(!N)return b(403,"Forbidden");let H={request:s,delivery:S,attachmentId:T,internalUserId:N,readAttachment:c.read,cookie:m,fail:b};return S.kind!=="thumbnail"?await c.serveOriginal(H):c.serveThumbnail===null?b(404,nt[404]):await c.serveThumbnail(H,S.variant)}catch(f){if(f instanceof Response)throw f;return a.error(`500 attachment=? viewer=? reason=unexpected message=${f instanceof Error?f.message:"unknown"}`),b(500,Ke)}}};var $l=32*1024*1024,Bl=60,Fl=4,Vl=120,Yl=2,ql=8*1024*1024,ir=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Wl=e=>{if(e===void 0)throw pt("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!ir(e))throw le("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw pt("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw le("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw le("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},jl=e=>{if(e===void 0)return null;if(!ir(e))throw le("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:Wl(e.renderer),rateLimitPerMinute:it("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,Vl),concurrency:it("attachments.thumbnails.concurrency",e.concurrency,1,Yl),cacheBytes:it("attachments.thumbnails.cacheBytes",e.cacheBytes,0,ql)})},Qo=e=>{let t=e;if(t===void 0)return null;if(!ir(t))throw le("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw pt("attachments.idCodec","injected when attachments is given");if(!ir(r)||typeof r.encode!="function"||typeof r.decode!="function")throw le("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw pt("attachments.read","injected when attachments is given");if(typeof n!="function")throw le("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:it("attachments.maxBytes",t.maxBytes,1,$l),rateLimitPerMinute:it("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,Bl),concurrency:it("attachments.concurrency",t.concurrency,1,Fl),thumbnails:jl(t.thumbnails)})},zl=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"]]),sr=e=>{for(let[t,r]of zl)if(Object.hasOwn(e,t))throw pt(r,`given in place of the flat key ${t}`)};var Zo=8,Gl=8*Zo,Kl=128,Jl=2,ea=Jl*Kl,Ql=4*ea,Xl=6e4,Zl=6e4,ec="Too many reads",Xo=Object.freeze(Object.keys(tt).filter(e=>tt[e].admission.includes("miss-gate"))),ta=e=>{let t=Fe({limit:Gl,maxHeldPerOwner:Zo,queue:{max:Ql,maxPerOwner:ea,maxWaitMs:Xl}}),r=Le({windowMs:Zl,tallies:Xo,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`cache_miss_admission_suppressed count=${o} since=${a} viewer=${n} endpoints=${Xo.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}})}},lr=(e,t)=>{let r=ee(e,t,{error:{message:ec}},503);for(let[n,o]of Object.entries($e(503)))r.headers.set(n,o);return r};var tc=/^[0-9a-f]{1,16}$/;var ra=e=>{let t=e.get(Ae.cursorReportHubId),r=e.get(Ae.cursorBusinessDate),n=e.get(Ae.cursorSnapshot),o=n!==null&&tc.test(n)?n:null,a=null;if(t!==null){let l=He(t);if(l===null)return{refused:"cursor"};if(r!==null&&!jt(r))return{refused:"cursor"};a={businessDate:r,reportHubId:l}}else if(r!==null)return{refused:"cursor"};let i=Ct(e.get(Ae.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var cr=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,rc=2,nc=16,oc=rc*nc,ac=6e4,na=()=>{},ic=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},oa=e=>{let t=Fe({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:oc,queue:null}),r=Le({windowMs:ac,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 na;if(a.aborted){if(t.canAcquire(n))return na}else{let i=await t.acquire(n,a);if(i!==null)return ic(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var ur=30,ca=4e3,sc="stream interrupted by server error",lc="Too many streams",cc=15e3,ua=Symbol("ids-stream-heartbeat"),aa=()=>{},ia=e=>e.return(void 0).then(aa,aa),uc=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(ua),cc)}),stop:()=>clearTimeout(e)}};async function*sa(e,t,r,n){let o=t?Mn(e,t):0,a=!0;for(;;){let i=e.slice(o,o+(a?r:ca));o+=i.length;let l=o>=e.length,c=i[i.length-1];if(yield{kind:"chunk",items:i,nextCursor:l||!c?null:{businessDate:c.businessDate,reportHubId:c.reportHubId},isLast:l,...a?{total:e.length}:{},...a?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...a&&n.restarted?{restarted:!0}:{}},a=!1,l)return}}var da=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform",...Ge});return e&&t.append("Set-Cookie",e),t},la=(e,t,r,n,o)=>{let a=async(h,m)=>{o(),m&&await ia(t);try{h.close()}catch{}},i=new TextEncoder,l=!1,c=null,s=new ReadableStream({async pull(h){if(l||r.aborted){await a(h,!0);return}let m=uc();try{c===null&&(c=t.next());let b=await Promise.race([c,m.fired]);if(m.stop(),b===ua){if(l||r.aborted){await a(h,!0);return}h.enqueue(i.encode(`
|
|
2
|
-
`));return}c=null;let{value:f,done:
|
|
3
|
-
`))}catch(
|
|
4
|
-
`)),
|
|
5
|
-
`,
|
|
6
|
-
`)},
|
|
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`],Lc=()=>{let e=(0,ya.createHash)("sha256");e.update(JSON.stringify(ye.DEFAULT_NORMALIZE_OPTIONS));for(let t of["","\u30A2","\u4F50"," "])e.update("\0"),e.update(cn(Pc(t)));return e.update("\0"),e.update(JSON.stringify(Mc.map(t=>hr(t,8)))),`dr-search-v${mc};fz=${e.digest("hex").slice(0,16)};u=${process.versions.unicode};icu=${process.versions.icu}`},ln=null,Da=()=>(ln===null&&(ln=Lc()),ln);var Oc=/^-+/u,Nc=/\s+/u,Aa=e=>{let t=Oc.exec(e);return t===null?[e]:[e,"\u30FC".repeat(t[0].length)+e.slice(t[0].length)]},vc=(e,t)=>{let r=[...Aa(e).map(n=>({text:n,tier:0})),...t.flatMap(n=>Aa(n).map(o=>({text:o,tier:1})))];return r.filter((n,o)=>r.findIndex(a=>a.text===n.text)===o)},pn=(e,t)=>{if(e.length>Ee.maxQueryLength)return{ok:!1,reason:"too-long"};let r=[],n=new Set,o=0;for(let{query:a}of(0,Ta.parseQuerySets)(Lt(e),t).sets){let i=[],l=new Set;for(let s of a.split(Nc)){let h=mr(s);if(h.length===0)return{ok:!1,reason:"blank-word"};if(h.length>Ee.maxWordLength)return{ok:!1,reason:"word-too-long"};l.has(h)||(l.add(h),i.push({alternatives:vc(h,Ra(s))}))}if(i.length>Ee.maxWordsPerSet)return{ok:!1,reason:"too-many-words-in-set"};let c=[...l].sort().join("\0");n.has(c)||(n.add(c),o+=i.length,r.push({words:i}))}return r.length===0?{ok:!1,reason:"empty"}:r.length>Ee.maxSets?{ok:!1,reason:"too-many-sets"}:o>Ee.maxWords?{ok:!1,reason:"too-many-words"}:{ok:!0,plan:{combine:t,sets:r}}},Ot=e=>e.sets.map(t=>t.words.map(r=>r.alternatives));var Ha=require("@aiquants/sse"),ot=require("@aiquants/sse/server");var gt=(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=Yn.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}},kc=["externalComments","postedComments"],Ea=new WeakMap,Hc=e=>{let t=Ea.get(e);if(t!==void 0)return t;let r={recipientRemoved:null,commentsRedacted:null};return Ea.set(e,r),r},Ia=e=>{let{recipientRawUserId:t,...r}=e;return r},_a=(e,t)=>{let{published:r}=e;if(!(t||Object.hasOwn(r,"recipientRawUserId")))return e.text;let n=Hc(e);if(t){if(n.commentsRedacted===null){let o=Ia(r),a=o.report;n.commentsRedacted=JSON.stringify({...o,report:{...a,...Object.fromEntries(kc.map(i=>[i,[]]))}})}return n.commentsRedacted}return n.recipientRemoved===null&&(n.recipientRemoved=JSON.stringify(Ia(r))),n.recipientRemoved};var Ma=require("@aiquants/sse"),La=require("@aiquants/sse/shared-source");var lt="daily-report:ids:",ct="daily-report:business-date:",fr=(e,t)=>`${e}st:${t}`,yn=e=>`${lt}user:${e}:`,wa=(e,t)=>fr(yn(e),t),Uc=e=>`${ct}${e}:`,xa=(e,t)=>fr(Uc(e),t),Nt=e=>`daily-report:date:${e}:user:`,bt=(e,t)=>`${Nt(e)}${t}:`,Ca=(e,t,r)=>fr(bt(e,t),r),Ye=e=>`daily-report:detail:${e}:user:`,Rr=(e,t)=>`${Ye(e)}${t}:`,Pa=(e,t,r)=>fr(Rr(e,t),r);var Xe=(e,t)=>{let[r,n]=e.split("-").map(Number),[o,a]=t.split("-").map(Number);return r!==o?r<o:n<=a},$c=5e3,Bc=Jt,Dt=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=fe(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,La.createSharedSource)({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:Ma.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:$c,COUNT:Bc});if(i)for(let l of i)for(let c of l.messages){a=c.id;let{entry:s,json:h}=gt(c,this._logger);this._invalidateCaches(h),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(lt),(r==="comment-add"||r==="comment-delete"||r==="status-update")&&typeof n=="number"&&this.config.cache.invalidatePrefix(Ye(n))}};var kt=require("drizzle-orm");var Fc="",Vc=64,Yc=e=>e.toLowerCase(),qc=e=>e.trim().toLowerCase();function Oa(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=qc(r);n.length>0&&t.add(n)}return t}function Oe(e,t){return e===null?!0:t==null?!1:e.has(Yc(t))}function Ne(e){return e!==null&&e.size===0}function Ht(e,t){if(t!==null)return t.size===0?kt.sql`1 = 0`:(0,kt.inArray)(kt.sql`LOWER(${e})`,[...t])}var At,Tt,vt=class vt{constructor(t,r){Cr(this,At);Cr(this,Tt);Pr(this,At,t),Pr(this,Tt,r)}get visible(){return wt(this,At)===null?null:new Set(wt(this,At))}get commentable(){return wt(this,Tt)===null?null:new Set(wt(this,Tt))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=Oa(r?t.read:t),o=r?t.comment:void 0;if(o===void 0)return new vt(n,n);let a=Oa(o),i=new Set;for(let l of a??[])n.has(l)&&i.add(l);return new vt(n,i)}static unrestricted(t){return new vt(null,null)}};At=new WeakMap,Tt=new WeakMap;var Ce=vt;function Ut(e){let t=Na(e.visible),r=Na(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function Na(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(Fc);if(t.length<=Vc)return`s:${t}`;let r=2166136261;for(let n=0;n<t.length;n++)r^=t.charCodeAt(n),r=Math.imul(r,16777619);return`sh:${(r>>>0).toString(16)}`}var Ua=Object.freeze({...Pt,route:"sse",frameworkDataRefusal:Xt}),va=864e5,Wc={baseMs:2e3,jitterMs:8e3},hn=6e4,gr=Jt,$a=JSON.stringify({type:"connected"}),ka="0-0",jc=(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 Oe(r,e.report.sourceType);case"comment-add":case"comment-delete":return Oe(n,o??"Internal");case"report-delete":return Oe(r,o)}},zc=(e,t)=>t===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"?!1:!Oe(t,e.report.sourceType),Gc=(e,t)=>{e.writeEvent({event:null,id:t,data:$a})},Kc=(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||!jc(o,a,r.visibleSet,r.commentableSet)){Gc(e,t.id);return}e.writeEvent({event:null,id:t.id,data:_a(n,zc(o,r.commentableSet))})},Ba=e=>{let{authenticate:t,service:r,resolveViewerScope:n,redis:o,sseReader:a,streamKey:i,streamSlots:l,logger:c}=e,s=async(h,m)=>{let{request:b,internalUserId:f,cursor:g}=m,S=m.initialScope.visible,T=m.initialScope.commentable,N=0,H=setInterval(()=>{let K=++N;n(b,"refresh").then(Z=>{K===N&&(S=Z.visible,T=Z.commentable)})},hn);h.onClose(()=>clearInterval(H));let W=g===null?ka:g,x=g!==null&&o!==void 0,_=[],B=null,U=K=>{Xe(K.id,W)||(W=K.id,Kc(h,K,{internalUserId:f,visibleSet:S,commentableSet:T}))},$=async(K,Z)=>{let[oe]=await K.xRange(i,"-","+",{COUNT:1});return oe!==void 0&&!Xe(oe.id,Z)},de=async(K,Z)=>{if(await $(K,Z))return!1;let oe=Z;for(;;){let Re=await K.xRange(i,oe,"+",{COUNT:gr}),ae=Re[0];if(ae!==void 0&&ae.id!==oe&&await $(K,oe))return!1;for(let ie of Re){if(B!==null&&Xe(B,ie.id))return!0;Xe(ie.id,W)||U(gt(ie,c).entry)}let Se=Re.at(-1);if(Re.length<gr||Se===void 0||h.isClosed())return!0;oe=Se.id}},be=a.subscribe(K=>{if(!x){U(K);return}Xe(K.id,W)||(B===null&&(B=K.id),_.push(K))},K=>{c.error(`[SSE:${f}] Fan-Out reader error:`,K),h.close()});if(h.onClose(be),g===null){await a.ready();try{let K=await o?.getClient();if(K){let Z=await K.xRevRange(i,"+","-",{COUNT:1});Z.length>0&&!Xe(Z[0].id,W)&&(W=Z[0].id)}}catch{}}if(h.writeEvent({event:null,id:W===ka?null:W,data:$a}),(0,ot.startSseHeartbeat)(h,{intervalMs:$n,retry:Wc,runtime:Ha.systemSseRuntime}),g===null||o===void 0)return;await a.ready();let me=await o.getClient();if(me===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await de(me,g)){h.writeRetry(va),h.writeEvent({event:"resync-required",id:null,data:""}),h.close();return}x=!1;for(let K of _.splice(0))U(K)};return async({request:h,params:m})=>{let b,f=()=>{let S=new Headers;b!==void 0&&S.append("Set-Cookie",b);for(let[T,N]of Object.entries(Ge))S.set(T,N);return S},g=S=>(0,ot.terminalStreamResponse)(S,{data:"",retryMs:va,headers:f()});try{let S=await t(h,{failureRedirect:null});b=S.cookie;let{user:T}=S;if(!T)return g("auth-required");let N=await r.getUserIdByExternalId(T.id);if(!N)return g("forbidden");if(m.endpoint!=="updates")return new Response("Not Found",{status:404,headers:f()});let H=(0,ot.readLastEventId)(h,Bn);if(H!==null&&!Fn(H))return c.warn(`[SSE:${N}] malformed resume cursor; asking the client to resync`),g("resync-required");let W=cr(h),x=await l.admit(N,"sse",W);if(x===null){let B=f();for(let[U,$]of Object.entries($e(503)))B.set(U,$);return new Response("Too many streams",{status:503,headers:B})}let _=!1;try{let B=await n(h,"initial");return(0,ot.createSseResponse)({requestSignal:W,headers:f(),onError:(U,$)=>c.error(`[SSE:${N}] ${$} failed:`,U),produce:U=>(_=!0,U.onClose(x),s(U,{request:h,internalUserId:N,cursor:H,initialScope:B}))})}finally{_||x()}}catch(S){if(S instanceof Response)throw S;let T=S instanceof Error?S:new Error(String(S));return c.error(`500 sse name=${T.name} message=${T.message}`),new Response("Internal Server Error",{status:500,headers:f()})}}};var Fa=(e,t)=>{let r=new Headers({...t?.headers,"Content-Type":"application/json",...Ge});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},Jc=Object.freeze({...Pt,route:"api",frameworkDataRefusal:({params:e})=>Gr(e.endpoint)&&tt[e.endpoint].body==="stream"?Xt():null}),Qc=Object.freeze({...Pt,route:"action"}),Xc=(e,t,r)=>({...r,status:"OK",intent:e.intent,reportHubId:t,clientTempId:e.clientTempId}),Ya=6e4,qa=5,Zc=qa*Math.ceil(Ya/500),eu=2,tu=6,ru=6e4,nu=qa*eu*tu,ou=2,au=10,iu=2,su=10,Va=(e,t)=>Math.max(e,Un)*t,br=(e,t,r)=>{let n=ee(e,t,{error:{message:r.message}},r.status);for(let[o,a]of Object.entries(r.headers))n.headers.set(o,a);return n};function Dr(e){sr(e);let{authenticate:t,service:r,encodeUserId:n,redis:o,sseReader:a,streamKey:i}=e,l={titleMaxLength:ne("service.titleMaxLength",r.titleMaxLength,1)},c=e.loginRedirectPath??"/auth/login",s=fe(e.logger,3,"API"),h=fe(e.logger,3,"Visibility"),m=fe(e.logger,1,"SSE"),b=fe(e.logger,1,"Attachment"),f=fe(e.logger,2,"Isolation"),g=fe(e.logger,2,"Action"),S=fe(e.logger,2,"Search"),T=fe(e.logger,2,"Refresh"),N=fe(e.logger,2,"Streams"),H=fe(e.logger,2,"Reads"),W=Je({reason:"refresh_rate_limit",limitPerWindow:nu,windowMs:ru,logger:T,windowFields:()=>"route=api"}),x=oa(N),_=ta(H),B=async(M,O,I,F,z)=>{let X=await r.getUserIdByExternalId(O.id);try{return await z(X===null?void 0:_.admissionFor(X,M,I.signal))}catch(Q){if(Q instanceof ke)return lr(I,F);throw Q}},U=(M,O,I,F)=>{let z=W.spend(O.id,`endpoint=${M}`);return z===null?null:br(I,F,z)},$=async(M,O="initial")=>{let I=e.resolveVisibleSourceTypes;if(!I)return Ce.unrestricted("no visibility port injected: this deployment does not restrict by source type");try{let F=await I(M,{reason:O});return F==null?Ce.unrestricted("visibility port returned null/undefined: this deployment opts out of source-type filtering"):Ce.restrictTo(F)}catch(F){return h.error("resolveVisibleSourceTypes threw; failing closed (deny all)",F),Ce.restrictTo([])}},de=async({request:M})=>{let{user:O,cookie:I}=await t(M,{failureRedirect:c}),F=new Headers;I&&F.append("Set-Cookie",I);let z=await r.getUserIdByExternalId(O.id),X=z?n(z):null;return{data:{user:O,userId:X},headers:F}},be=r.searchLimits===null?null:dr({...r.searchLimits,route:ue.search,logger:S}),me=r.searchLimits===null?null:dr({concurrency:Va(r.searchLimits.concurrency,ou),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*au,route:ue.reports,logger:S}),K=r.searchLimits===null?null:dr({concurrency:Va(r.searchLimits.concurrency,iu),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*su,route:ue.searchMarks,logger:S}),Z={[ue.businessDate]:async(M,O,I,F,z)=>{let X=M.searchParams.get(Ae.businessDate),Q=X===null?null:ht(X);if(Q===null)return ee(I,O,{error:{message:"Invalid business date"}},400);let j=Ct(M.searchParams.get(Ae.forceRefresh));if(j===null)return ee(I,O,{error:{message:"Invalid forceRefresh"}},400);let J=j?U(ue.businessDate,F,I,O):null;return J!==null?J:B(ue.businessDate,F,I,O,async L=>{let se=await r.getDailyReportsByBusinessDateByExternalId(z,Q,F.id,{forceRefresh:j,admission:L});return ee(I,O,{businessDate:Q,reports:se},200)})},[ue.idsStream]:ma({service:r,logger:s,streamSlots:x,missGate:_,refuseForcedRead:(M,O,I)=>U(ue.idsStream,M,O,I)}),[ue.report]:async(M,O,I,F,z)=>{let X=He(M.searchParams.get(Ae.reportHubId));if(X===null)return ee(I,O,{error:{message:"Invalid reportHubId"}},400);let Q=Ct(M.searchParams.get(Ae.forceRefresh));if(Q===null)return ee(I,O,{error:{message:"Invalid forceRefresh"}},400);let j=Q?U(ue.report,F,I,O):null;return j!==null?j:B(ue.report,F,I,O,async J=>{let L=await r.getDailyReportDetailByIdByExternalId(z,X,F.id,{snapshot:!0,forceRefresh:Q,admission:J});return L?ee(I,O,{report:L},200):ee(I,O,{error:{message:"Report not found"}},404)})},[ue.search]:async(M,O,I,F,z)=>{if(be===null)return ee(I,O,{error:{message:"Unknown endpoint"}},404);let X=M.searchParams.get(Ae.searchQuery),Q=jr(M.searchParams.get(Ae.searchCombine));if(X===null||Q===null)return ee(I,O,{error:{message:"Invalid search request"}},400);let j=pn(X,Q);if(!j.ok)return ee(I,O,{error:{message:"Invalid search query",reason:j.reason}},400);let J=Ot(j.plan),L=await r.getUserIdByExternalId(F.id);if(!L)return ee(I,O,Hr([],J),200);let se=await be.admit(L,I.signal);if("refusal"in se)return br(I,O,se.refusal);try{let ge=await r.searchDailyReports(z,L,j.plan);return ee(I,O,Hr(ge,J),200)}finally{se.release()}},[ue.reports]:async(M,O,I,F,z)=>{if(me===null)return ee(I,O,{error:{message:"Unknown endpoint"}},404);let X=zr(M.searchParams.get(Ae.reportIds));if(X===null)return ee(I,O,{error:{message:"Invalid ids"}},400);let Q=await r.getUserIdByExternalId(F.id);if(!Q)return ee(I,O,{reports:[]},200);let j=await me.admit(Q,I.signal);if("refusal"in j)return br(I,O,j.refusal);try{let J=await r.getDailyReportDetailsByIdsByExternalId(z,X,F.id);return ee(I,O,{reports:J},200)}finally{j.release()}},[ue.searchMarks]:async(M,O,I,F,z)=>{if(K===null)return ee(I,O,{error:{message:"Unknown endpoint"}},404);let X=M.searchParams.get(Ae.searchQuery),Q=jr(M.searchParams.get(Ae.searchCombine));if(X===null||Q===null)return ee(I,O,{error:{message:"Invalid search request"}},400);let j=pn(X,Q);if(!j.ok)return ee(I,O,{error:{message:"Invalid search query",reason:j.reason}},400);let J=zr(M.searchParams.get(Ae.reportIds));if(J===null)return ee(I,O,{error:{message:"Invalid ids"}},400);let L=await r.getUserIdByExternalId(F.id);if(!L)return ee(I,O,{wordsDigest:zt(Ot(j.plan)),reports:[]},200);let se=await K.admit(L,I.signal);if("refusal"in se)return br(I,O,se.refusal);try{let ge=await r.markDailyReportSearchHits(z,L,j.plan,J);return ee(I,O,ge,200)}finally{se.release()}}},oe=async({request:M,params:O})=>{let{user:I,cookie:F}=await t(M,{failureRedirect:null}),z=F??null;if(!I)return ee(M,z,{error:{message:"Unauthorized"}},401);let X=O.endpoint;if(!Gr(X))return ee(M,z,{error:{message:"Unknown endpoint"}},404);let Q=Zn[tt[X].body];if(!Q.includes(M.method)){let J=ee(M,z,{error:{message:"Method not allowed"}},405);return J.headers.set("Allow",Q.join(", ")),J}let j=ce();try{let J=new URL(M.url),L=await $(M),se=await Z[X](J,z,M,I,L);return tt[X].body==="json"&&s.debug(`${se.status} endpoint=${X} etag_match=${se.status===304}`),se}catch(J){let L=ce()-j,se=J instanceof Error?J:new Error(String(J));return s.error(`500 endpoint=${X} elapsed=${L}ms name=${se.name} code=${"code"in se?se.code:"N/A"} message=${se.message}`,se),ee(M,z,{error:{message:"Internal Server Error"}},500)}},Re=Xn(g),ae=Je({reason:"rate_limit",limitPerWindow:Zc,windowMs:Ya,logger:g,windowFields:()=>"route=action"}),Se=async(M,O,I,F,z)=>{let{clientTempId:X}=M;if(M.intent==="create"){let L=await r.createDailyReport(O,M.businessDate,X);return z(M,L.reportHubId,{report:L})}let{reportHubId:Q,businessDate:j}=M,J=async(L,se)=>{try{let ge=await se(L.value);return z(L,Q,{updatedStatus:{isStarred:ge.isStarred,isRead:ge.isRead},operationTimestamp:L.operationTimestamp})}catch(ge){if(ge instanceof Error&&ge.message==="Not Found")return F({error:"Report not found"},{status:404});throw ge}};switch(M.intent){case"update":try{return await r.updateDailyReport(Q,O,M.changes,X),z(M,Q,{})}catch(L){if(L instanceof Error){if(L.message==="Unauthorized")return F({error:"Unauthorized"},{status:403});if(L.message==="Not Found")return F({error:"Report not found"},{status:404})}throw L}case"publish":try{let L=await r.publishDailyReport(Q,O,X);return z(M,Q,{report:L})}catch(L){if(L instanceof Error){if(L.message==="Unauthorized")return F({error:"Unauthorized"},{status:403});if(L.message==="Not Found")return F({error:"Report not found"},{status:404})}throw L}case"delete":try{return await r.deleteDailyReport(Q,O,X),z(M,Q,{})}catch(L){if(L instanceof Error){if(L.message==="Unauthorized")return F({error:"Unauthorized"},{status:403});if(L.message==="Not Found")return F({error:"Report not found"},{status:404})}throw L}case"toggleStar":return await J(M,L=>r.setStarStatus(I,O,Q,j,L,X));case"toggleRead":return await J(M,L=>r.setReadStatus(I,O,Q,j,L,X));case"addComment":try{let L=await r.addComment(I,O,Q,M.content,j,X);return z(M,Q,{newComment:L})}catch(L){if(L instanceof Error){if(L.message==="Not Found")return F({error:"Report not found"},{status:404});if(L.message.startsWith("Comments are restricted"))return F({error:"Comments are restricted for this report"},{status:403})}throw L}case"deleteComment":try{return await r.deleteComment(I,O,Q,M.commentId,j,X),z(M,Q,{deletedCommentId:M.commentId})}catch(L){if(L instanceof Error){if(L.message==="Unauthorized")return F({error:"Unauthorized"},{status:403});if(L.message==="Not Found")return F({error:"Comment not found"},{status:404})}throw L}}},ie=async({request:M,params:O})=>{let{user:I,cookie:F}=await t(M,{failureRedirect:null}),z=(j,J)=>Fa(j,{...J,setCookie:F}),X=(j,J,L)=>Fa(Xc(j,J,L),{setCookie:F});if(!I)return z({error:"Unauthorized"},{status:401});let Q=ce();try{if(O.endpoint!==ue.action)return z({error:"Unknown endpoint"},{status:404});let j=ae.spend(I.id,"action");if(j!==null)return z({error:j.message},{status:j.status,headers:j.headers});let J=await Qn(M,l);if("refusal"in J){let{refusal:We}=J;return We.status===413&&Re(We.measuredBy),z({error:We.error},{status:We.status})}let{command:L}=J;if(L.intent==="clearCache"&&!e.enableDevCacheClear)return z({error:"Invalid intent"},{status:400});let se=await r.getUserIdByExternalId(I.id);if(!se)return z({error:"User not found"},{status:404});let ge=await $(M);return L.intent==="clearCache"?(await r.clearCache(),z({status:"OK",intent:"clearCache"})):await Se(L,se,ge,z,X)}catch(j){if(j instanceof Response)throw j;let J=ce()-Q,L=j instanceof Error?j:new Error(String(j));return s.error(`500 action elapsed=${J}ms name=${L.name} message=${L.message}`,L),z({error:"Internal Server Error"},{status:500})}},_e=Ba({authenticate:t,service:r,resolveViewerScope:$,redis:o,sseReader:a,streamKey:i,streamSlots:x,logger:m}),we=Jo({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:$,logger:b}),et=so(f),ve=(M,O)=>async I=>{let F=ao(I.request)?M.frameworkDataRefusal(I):null;if(F!==null)throw F;return io(I.request,M)?(et(M.route,I.request),M.crossSiteRejection()):O(I)};return{index:{loader:de},api:{loader:ve(Jc,oe),action:ve(Qc,ie)},sse:{loader:ve(Ua,_e)},attachment:{loader:ve(Ko,we)}}}var It=require("@aiquants/mssql"),p=require("drizzle-orm");var Wa=(e,t,r,n)=>Oe(n.commentable,t)||e.authorUserId!==null&&e.authorUserId===r;var lu=["tables","externalSourceTexts","concurrency","rateLimitPerMinute"],cu=["document","comment"],uu=["hubId","searchText","sourceDigest","normalizerVersion","indexedAt","rowVersion"],du=["hubId","ordinal","authorUserId","commentText"],fn=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},ja=(e,t,r)=>{for(let n of Object.keys(t))if(!r.includes(n))throw Mr(e,n,r)},za=(e,t,r)=>{if(typeof t!="object"||t===null)throw le(e,"a table object",t);let n=t;for(let o of r)if(typeof n[o]!="object"||n[o]===null)throw le(`${e}.${o}`,"a column",n[o])},Ga=(e,t)=>{if(!fn(e))throw le("search","a plain object",e);ja("search key",e,lu);let{tables:r}=e;if(!fn(r))throw le("search.tables","a plain object with document and comment",r);ja("search.tables key",r,cu),za("search.tables.document",r.document,uu),za("search.tables.comment",r.comment,du);let n=new Map;if(e.externalSourceTexts!==void 0){if(!fn(e.externalSourceTexts))throw le("search.externalSourceTexts","a plain object",e.externalSourceTexts);for(let[o,a]of Object.entries(e.externalSourceTexts)){if(!t.includes(o))throw Mr("search.externalSourceTexts key",o,t);if(typeof a!="function")throw le(`search.externalSourceTexts.${o}`,"a function",a);n.set(o,a)}}return{tables:r,externalSourceTexts:n,concurrency:ne("search.concurrency",e.concurrency,1),rateLimitPerMinute:ne("search.rateLimitPerMinute",e.rateLimitPerMinute,1)}};var ut=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},dt=(e,t)=>{let r=typeof e=="string"?He(e):typeof e=="number"&&ft(e)?e:null;if(r===null)throw new Error(`[daily-report] search: column ${t} holds no positive id`);return r},Et=(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 mu=/[[%_]/gu,pu=e=>e.replace(mu,t=>`[${t}]`),Ka=e=>`%${pu(e)}%`;var Be=Object.freeze({reportHubId:"report_hub_id",businessDate:"business_date",sourceType:"source_type"}),mt=Object.freeze({reportHubId:"report_hub_id",matchedSets:"matched_sets"}),Te=Object.freeze({hubId:"hub_id",sourceDigest:"source_digest",normalizerVersion:"normalizer_version"}),G=e=>q.sql`${q.sql.identifier(e.name)}`,Rn=e=>q.sql.join(e.map(t=>q.sql`${t}`),q.sql`, `),Ja=(e,t)=>q.sql`SELECT ${G(e.id)} AS ${q.sql.identifier(Te.hubId)} FROM ${e} WITH (UPDLOCK, ROWLOCK) WHERE ${e.id} IN (${Rn(t)}) ORDER BY ${e.id}`,yu=(e,t,r)=>{let{hub:n}=e,{document:o,comment:a}=e.search,i=t.alternatives.map(m=>Ka(m.text)),l=q.sql.join(i.map(m=>q.sql`${o.searchText} LIKE ${m}`),q.sql` OR `),c=q.sql.join(i.map(m=>q.sql`${a.commentText} LIKE ${m}`),q.sql` OR `),s=Ht(n.sourceType,r.scope.commentable),h=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})${h}))`},Qa=(e,t,r)=>q.sql`(${q.sql.join(t.words.map(n=>yu(e,n,r)),q.sql` AND `)})`,Xa=(e,t,r,n)=>{let{hub:o,hubLabel:a,label:i}=e,l=[q.sql`${o.deletedAt} IS NULL`];r.length>0&&l.push(q.sql`(${o.userId} = ${t.userId} OR NOT EXISTS (SELECT 1 FROM ${a} INNER JOIN ${i} ON ${i.id} = ${a.labelId} WHERE ${a.hubId} = ${o.id} AND ${i.name} IN (${Rn(r)})))`);let c=Ht(o.sourceType,t.scope.visible);return c!==void 0&&l.push(c),n!==void 0&&l.push(q.sql`${o.id} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${JSON.stringify(n)}))`),l},Za=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,l=Xa(e,r,n,o),c=t.combine==="intersection"?q.sql` AND `:q.sql` OR `;return l.push(q.sql`(${q.sql.join(t.sets.map(s=>Qa(e,s,r)),c)})`),q.sql`SELECT ${G(a.id)} AS ${q.sql.identifier(Be.reportHubId)}, CONVERT(char(10), ${G(a.businessDate)}, 23) AS ${q.sql.identifier(Be.businessDate)}, ${G(a.sourceType)} AS ${q.sql.identifier(Be.sourceType)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${q.sql.join(l,q.sql` AND `)} ORDER BY ${a.businessDate} DESC, ${a.id} DESC`},ei=(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 ${Qa(e,c,r)} THEN ${2**s} ELSE 0 END)`),q.sql` + `);return q.sql`SELECT ${G(a.id)} AS ${q.sql.identifier(mt.reportHubId)}, ${l} AS ${q.sql.identifier(mt.matchedSets)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${q.sql.join(Xa(e,r,n,o),q.sql` AND `)}`},ti=(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}))),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 (${G(n.hubId)} bigint, ${G(n.searchText)} nvarchar(max), ${G(n.sourceDigest)} char(64), ${G(n.normalizerVersion)} varchar(64))) AS s ON t.${G(n.hubId)} = s.${G(n.hubId)}
|
|
8
|
-
WHEN MATCHED THEN UPDATE SET t.${
|
|
9
|
-
WHEN NOT MATCHED THEN INSERT (${
|
|
1
|
+
"use strict";var Br=Object.defineProperty;var xs=Object.getOwnPropertyDescriptor;var Cs=Object.getOwnPropertyNames;var Ps=Object.prototype.hasOwnProperty;var Yn=e=>{throw TypeError(e)};var Ms=(e,t)=>{for(var r in t)Br(e,r,{get:t[r],enumerable:!0})},Ls=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Cs(t))!Ps.call(e,o)&&o!==r&&Br(e,o,{get:()=>t[o],enumerable:!(n=xs(t,o))||n.enumerable});return e};var Ns=e=>Ls(Br({},"__esModule",{value:!0}),e);var qn=(e,t,r)=>t.has(e)||Yn("Cannot "+r);var Lt=(e,t,r)=>(qn(e,t,"read from private field"),r?r.call(e):t.get(e)),Vr=(e,t,r)=>t.has(e)?Yn("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Yr=(e,t,r,n)=>(qn(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var Sd={};Ms(Sd,{DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES:()=>hr,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES:()=>yr,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES:()=>Fn,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL:()=>Jt,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL:()=>Hn,DAILY_REPORT_SSE_CATCH_UP_BATCH:()=>Pr,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS:()=>xn,DailyReportSseReader:()=>Ct,DailyReportViewerScope:()=>Pe,SqlResultCache:()=>bt,createDailyReportHandlers:()=>Lr,createDailyReportServer:()=>Rd,createDailyReportService:()=>kr,createEpochStore:()=>Zt,createSharpThumbnailRenderer:()=>Zi,defineDailyReportSchema:()=>Fi,defineDailyReportSearchSchema:()=>Hi,isStreamIdLte:()=>rt,parseClientTempId:()=>lr,predictSharpThumbnailWorkingSetBytes:()=>Xi,readDailyReportSseStreamEntry:()=>wt,transformJsonArray:()=>ki});module.exports=Ns(Sd);var Os=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,le=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${Os(r)}`),gt=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),qr=(e,t,r)=>le(e,`one of ${r.map(n=>JSON.stringify(n)).join(", ")}`,t),te=(e,t,r,n)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r&&(n===void 0||t<=n))return t;throw le(e,n===void 0?`an integer >= ${r}`:`an integer from ${r} to ${n}`,t)},ct=(e,t,r,n)=>t===void 0?n:te(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}},Zt=e=>({async getEpoch(t){try{let r=await e?.getClient();if(!r)return null;let n=await r.get(t);return n?Number(n):0}catch{return null}},async incrementEpoch(t){try{let r=await e?.getClient();if(!r)return;await r.incr(t)}catch{}}}),Nt=(e,t)=>t?e.map(r=>structuredClone(r)):e,bt=class{constructor(t,r){this.epochStore=r;this.buckets=new Map;this.inFlight=new Map;this.forcedFetches=new Map;this.maybeRefreshAhead=t=>{let r=t.refreshAheadRatio;if(r===void 0)return;let{cacheKey:n}=t,o=this.buckets.get(n);if(!o)return;let a=t.ttlMsOverride??this.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 y of r)y();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.buckets.delete(r),Nt(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),Nt(i.records,o);this.buckets.delete(r)}else return this.maybeRefreshAhead(t),Nt(i.records,o);let l=this.inFlight.get(r);if(l!==void 0)return Nt(await this.readOwnOrRetry(l,t),o);if(a?.signal.aborted)throw new He("aborted");return Nt(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.inFlight.clear()};this.invalidatePrefix=t=>{for(let r of this.buckets.keys())r.startsWith(t)&&this.buckets.delete(r);for(let r of this.inFlight.keys())r.startsWith(t)&&this.inFlight.delete(r)};this.defaultTtlMs=te("defaultTtlMs",t.defaultTtlMs,1),this.maxBuckets=te("maxBuckets",t.maxBuckets,1),this.lastSweepAt=ue()}writeBucket(t,r){this.buckets.delete(t),this.buckets.set(t,r);let n=ue();n-this.lastSweepAt>=this.defaultTtlMs&&this.sweepExpired(n);for(let o of this.buckets.keys()){if(this.buckets.size<=this.maxBuckets)break;this.buckets.delete(o)}}sweepExpired(t){this.lastSweepAt=t;for(let[r,n]of this.buckets)n.expireAt<=t&&this.buckets.delete(r)}};var jn="ids-stream";var er=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+(?=.)/,"")},tr=(e,t)=>e.businessDate!==t.businessDate?e.businessDate===null?1:t.businessDate===null||e.businessDate>t.businessDate?-1:1:t.reportHubId-e.reportHubId,Wn=e=>{for(let t=1;t<e.length;t++)if(tr(e[t-1],e[t])>0)return!1;return!0},zn=(e,t)=>{let r=e.findIndex(n=>tr({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var oe=Object.freeze({businessDate:"business-date",idsStream:jn,report:"report",search:"search",reports:"reports",searchMarks:"search-marks",searchFacets:"search-facets",action:"action"}),Re=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 vs=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var Gn=e=>e<10?`0${e}`:`${e}`,ks=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=Gn(e.getMonth()+1),n=Gn(e.getDate());return`${t}-${r}-${n}`},Dt=e=>{let t=vs.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}`},rr=e=>Dt(e)===e;var Oe=e=>e==null?null:e instanceof Date?ks(e):Dt(e);var Kn=(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)}}},Cd=Object.freeze(["API","Action","Attachment","ExternalSource","Isolation","Reads","Refresh","Search","SSE","SseReader","Server","Service","Streams","Visibility","ActionProvider","DetailLoader","IdsStream","SseConnection"]),Jn=e=>`[DailyReport${e}]`,Se=(e,t,r)=>e===void 0?Kn(t,Jn(r)):Kn(0,Jn(r),e);var Fs="legacy-",jr=e=>`${Fs}${e}`;var Qn=require("zod"),At=e=>Number.isSafeInteger(e)&&e>0,Ae=Qn.z.number().int().positive().max(Number.MAX_SAFE_INTEGER);var Hs=/^[1-9][0-9]*$/,Us=/^(?:0|[1-9][0-9]*)$/,Ue=e=>{if(e===null||!Hs.test(e))return null;let t=Number(e);return At(t)?t:null},Wr=e=>{if(e===null||!Us.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 Xn=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 $s=2166136261,Bs=16777619,Gr=e=>{let t=$s;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,Bs);return t>>>0},Vs=String.fromCodePoint(3),Ys=String.fromCodePoint(2),qs=String.fromCodePoint(1),nr=e=>Gr(e.map(t=>t.map(r=>r.map(n=>`${n.tier}${n.text}`).join(Vs)).join(Ys)).join(qs));var Zn=e=>e==="intersection"||e==="union",Ie=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),Kr=2,or=2,ut=Object.freeze({word:0,reading:1});var Jr=(e,t)=>({ids:e.map(r=>r.reportHubId),businessDates:e.map(r=>r.businessDate),sourceTypes:e.map(r=>r.sourceType),words:t});var kd=2*(1+Kr);var Qs=require("zod");var ar=/^(?:[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 v=require("zod");var eo=15e3,to="lastEventId",js=/^\d{1,15}-\d{1,15}$/,ro=e=>js.test(e),Ws=v.z.object({name:v.z.string().nullish(),affiliation:v.z.string().nullish()}),zs=v.z.object({name:v.z.string().nullish(),text:v.z.string().nullish(),color:v.z.string().nullish()}),Gs=v.z.object({id:Ae,name:v.z.string().nullish(),color:v.z.string().nullish()}),no=v.z.object({id:Ae,userId:v.z.string().nullish(),userName:v.z.string().nullish(),content:v.z.string().nullish(),createdAt:v.z.string().nullish(),isMine:v.z.boolean()}),Ks=v.z.object({id:v.z.string(),fileName:v.z.string(),fileType:v.z.string().nullable(),fileSize:v.z.number().nullable(),createdAt:v.z.string().nullable(),state:v.z.enum(["present","absent","unknown"]),hasThumbnail:v.z.boolean().default(!1)}),Qr=v.z.object({reportHubId:Ae,date:v.z.string().nullish(),createdAt:v.z.string().nullish(),author:v.z.string().nullish(),userId:v.z.string().nullish(),sourceType:v.z.string().nullish(),employeeName:v.z.string().nullish(),updatedBy:v.z.string().nullish(),updatedAt:v.z.string().nullish(),category:v.z.string().nullish(),creationCategory:v.z.string().nullish(),visitTimeFrom:v.z.string().nullish(),visitTimeTo:v.z.string().nullish(),customerName:v.z.string().nullish(),interviewers:v.z.array(Ws),subject:v.z.string().nullish(),content:v.z.string().nullish(),externalComments:v.z.array(zs),isRead:v.z.boolean(),isStarred:v.z.boolean(),labels:v.z.array(Gs),postedComments:v.z.array(no),attachments:v.z.array(Ks).default([])}),dt=v.z.string().regex(ar),Js=v.z.object({type:v.z.literal("connected")}),ir=v.z.object({type:v.z.literal("status-update"),reportHubId:Ae,statusType:v.z.enum(["star","read"]),value:v.z.boolean(),clientTempId:dt,recipientRawUserId:Ae.optional()}),Xr=v.z.string().optional(),Zr=v.z.object({type:v.z.literal("comment-add"),reportHubId:Ae,comment:no,clientTempId:dt,recipientRawUserId:Ae.optional(),sourceType:Xr}),en=v.z.object({type:v.z.literal("comment-delete"),reportHubId:Ae,commentId:Ae,clientTempId:dt,recipientRawUserId:Ae.optional(),sourceType:Xr}),tn=v.z.object({type:v.z.literal("report-create"),reportHubId:Ae,report:Qr,clientTempId:dt,recipientRawUserId:Ae.optional()}),rn=v.z.object({type:v.z.literal("report-update"),reportHubId:Ae,report:Qr,clientTempId:dt,recipientRawUserId:Ae.optional()}),nn=v.z.object({type:v.z.literal("report-publish"),reportHubId:Ae,report:Qr,clientTempId:dt,recipientRawUserId:Ae.optional()}),on=v.z.object({type:v.z.literal("report-delete"),reportHubId:Ae,clientTempId:dt,sourceType:Xr}),oo=v.z.discriminatedUnion("type",[Js,ir,Zr,en,tn,rn,nn,on]);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 sr=Math.max(1,Math.floor(10.556701030927835));var $e=(e,t)=>{let r=setTimeout(e,t);return r.unref?.(),r};var ke=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 zd=Object.freeze({authors:Object.freeze([]),sourceTypes:Object.freeze([]),customers:Object.freeze([])}),Xs=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,an=e=>{let t=e.trim();return t.length===0?null:t.replace(Xs,"\uFFFD")},Zs=e=>{let t=an(e);return t===null?"filter-blank-value":t!==e?"filter-value-not-canonical":e.length>Qe.maxValueLength?"filter-value-too-long":null},el=e=>{if(e.length>Qe.maxValuesPerFacet)return"filter-too-many-values";let t=new Set;for(let r of e){let n=Zs(r);if(n!==null)return n;if(t.has(r))return"filter-duplicate-value";t.add(r)}return null},tl=e=>{let t=0;for(let r of e.authors)t+=r.length;for(let r of e.customers)t+=r.length;return t},ao=e=>{for(let t of[e.authors,e.sourceTypes,e.customers]){let r=el(t);if(r!==null)return r}return tl(e)>Qe.maxTotalValueLength?"filters-too-long":null};var io=e=>e.trim().length===0;var lr=e=>e!==null&&ar.test(e)?e:null,sn=e=>Zn(e)?e:null,ln=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},so=e=>{let[t,...r]=e;return t===void 0?null:[t,...r]},lo=(e,t)=>{let r={authors:e.getAll(Re.searchAuthor),sourceTypes:e.getAll(Re.searchSourceType),customers:e.getAll(Re.searchCustomer)},n=ao(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:so(r.authors),customers:so(r.customers)}}},co=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var mo=Object.freeze({status:400,error:"Invalid form"}),po=e=>({status:413,error:"Form too large",measuredBy:e}),rl=(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)}}))},nl=async e=>{let t=Wr(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:po("declared")};let r=!1,n=e.body===null?null:rl(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?po("counted"):mo}}let l=co(i);return l===null?{refusal:mo}:{fields:l}},yo=(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}}},fo=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:yo("toggleStar",ve.isStarred),toggleRead:yo("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}}}}),ol=e=>Object.hasOwn(fo,e),al=(e,t)=>{let r=e.get(ve.intent),n=e.get(ve.businessDate),o=n===null?null:Dt(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get(ve.operationTimestamp),i=Wr(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=lr(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||!ol(r)?{error:"Invalid intent"}:fo[r](e,{clientTempId:c,businessDate:o,operationTimestamp:i,reportHubId:s},t)},Ro=async(e,t)=>{let r=await nl(e);if("refusal"in r)return r;let n=al(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},il=6e4,sl="form_too_large",ho=["declared","counted"],So=e=>{let t=ke({windowMs:il,tallies:ho,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`form_too_large_suppressed count=${n} since=${o} measured=${ho.map(i=>`${i}:${a[i]}`).join(",")}`)}});return r=>{let n=()=>{e.warn(`413 action reason=form_too_large measured=${r} limit=${1048576}`)};t.record(sl,r,n)}};var ot=Object.freeze({[oe.businessDate]:{body:"json",admission:["refresh-bucket","cache","miss-gate"]},[oe.idsStream]:{body:"stream",admission:["refresh-bucket","stream-slots","cache","miss-gate"]},[oe.report]:{body:"json",admission:["refresh-bucket","cache","miss-gate"]},[oe.search]:{body:"json",admission:["search-limiter"]},[oe.reports]:{body:"json",admission:["search-limiter"]},[oe.searchMarks]:{body:"json",admission:["search-limiter"]},[oe.searchFacets]:{body:"json",admission:["search-limiter"]}}),go=Object.freeze({json:Object.freeze(["GET"]),stream:Object.freeze(["GET","HEAD"])}),cn=e=>e!==void 0&&Object.hasOwn(ot,e);var un=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),bo=e=>Object.hasOwn(un,e);var ll="download",cl="thumbnail",ul="1";var dn=e=>{let t=e.getAll(cl),r=e.getAll(ll);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&bo(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===ul?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};var Do=require("crypto"),mn=e=>`"${(0,Do.createHash)("sha256").update(e).digest("hex")}"`,Ao=e=>mn(JSON.stringify(e));var Ye=Object.freeze({"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'"}),pn=(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},Z=(e,t,r,n=200)=>{let o=JSON.stringify(r),a=mn(o),i=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate",ETag:a,...Ye});return t&&i.append("Set-Cookie",t),e.method==="GET"&&n===200&&pn(e.headers.get("If-None-Match"),a)?new Response(null,{status:304,headers:i}):new Response(o,{status:n,headers:i})},Xe=(e,t,r)=>{let n=new Headers({...t===null?{}:{"Content-Type":"application/json"},"Cache-Control":"no-store",...Ye});return e&&n.append("Set-Cookie",e),new Response(t===null?null:JSON.stringify(t),{status:r,headers:n})},dl=5e3/1e3,ml=new Map([[503,dl]]),xe=e=>{let t=ml.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var hn="Cross-site request rejected",pl="Not Found",yl=new Set(["same-origin","none"]),hl=new Set(["GET","HEAD","OPTIONS"]),To=["api","action","sse","attachment"],Eo=(e,t)=>new Response(JSON.stringify({error:{message:t}}),{status:e,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...Ye}}),fl=()=>Eo(403,hn),cr=()=>Eo(404,pl),vt=Object.freeze({navigable:()=>!1,frameworkDataRefusal:()=>null,crossSiteRejection:fl}),Io=e=>new URL(e.url).pathname.endsWith(".data"),Rl=e=>{let t=e.headers.get("Origin");return t===null?!0:URL.canParse(t)&&new URL(t).host===new URL(e.url).host},_o=(e,t)=>{let r=e.headers.get("Sec-Fetch-Site");return r===null?!(hl.has(e.method)||Rl(e)):yl.has(r)?!1:!(e.method==="GET"&&e.headers.get("Sec-Fetch-Mode")==="navigate"&&e.headers.get("Sec-Fetch-Dest")==="document"&&t.navigable(e))},Sl=6e4,gl="refusals",bl=32,Dl=/^[a-z-]+$/,yn=e=>{if(e===null)return"-";let t=e.slice(0,bl);return Dl.test(t)&&t===e?e:JSON.stringify(t)},wo=e=>{let t=ke({windowMs:Sl,tallies:To,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${To.map(i=>`${i}:${a[i]}`).join(",")}`)}});return(r,n)=>{let o=()=>{let{headers:a}=n;e.warn(`cross_site_rejected route=${r} site=${yn(a.get("Sec-Fetch-Site"))} mode=${yn(a.get("Sec-Fetch-Mode"))} dest=${yn(a.get("Sec-Fetch-Dest"))} method=${n.method}`)};t.record(gl,r,o)}};var xo=(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 Al="same-origin",Tl="SAMEORIGIN",Tt=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":Al,"X-Frame-Options":Tl}),ur=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...Tt});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},Co=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),El=/^[\x20-\x7E]+$/,Il=/^[\w.+-]+\/[\w.+-]+/,fn=e=>e&&El.test(e)&&Il.test(e)?e:null,_l=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Po=e=>encodeURIComponent(e.replace(_l,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),Mo=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),dr={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable",503:"Attachment storage busy",504:"Attachment storage timed out"},Lo={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},mr=e=>typeof e=="string"&&Object.hasOwn(Lo,e),pr=e=>Lo[e],Ze="Attachment request failed";var qe=e=>{let t=te("limit",e.limit,1),r=te("maxHeldPerOwner",e.maxHeldPerOwner,1),n=e.queue===null?null:{max:te("queue.max",e.queue.max,0),maxPerOwner:te("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:te("queue.maxWaitMs",e.queue.maxWaitMs,1)},o=0,a=[],i=new Map,l=new Map,c=(b,w)=>b.get(w)??0,s=(b,w,F)=>{let V=c(b,w)+F;V<=0?b.delete(w):b.set(w,V)},y=b=>c(l,b)<r,m=b=>o<t&&y(b),S=b=>(o+=1,s(l,b,1),A(b)),f=()=>{let b=-1,w=r;for(let[F,V]of a.entries()){let P=c(l,V.owner);if(P<w&&(b=F,w=P,P===0))break}return b},R=()=>{for(;o<t;){let b=f();if(b<0)return;let[w]=a.splice(b,1);s(i,w.owner,-1),w.grant(S(w.owner))}},A=b=>{let w=!1;return()=>{w||(w=!0,o-=1,s(l,b,-1),R())}};return{canAcquire:m,acquire:(b,w)=>{if(w.aborted)return Promise.resolve(null);if(m(b))return Promise.resolve(S(b));if(n===null||a.length>=n.max||c(i,b)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:F}=n,V=P=>{let I=()=>{let ce=a.indexOf(H);ce<0||(a.splice(ce,1),s(i,b,-1),$(),P(null))},q=$e(I,F),$=()=>{clearTimeout(q),w.removeEventListener("abort",I)},H={owner:b,grant:ce=>{$(),P(ce)}};a.push(H),s(i,b,1),w.addEventListener("abort",I,{once:!0})};return new Promise(V)}}};var wl=1024,Rn="Too many requests",xl=(e,t)=>{te("limitPerWindow",e,1),te("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<=wl)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))}}},et=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(te("windowMs",r,1e3)%1e3!==0)throw le("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=xl(e.limitPerWindow,r),i=Object.freeze({status:429,message:Rn,headers:Object.freeze({"Retry-After":String(r/1e3)})}),l=ke({windowMs:r,tallies:[t],writeSuppressed:(c,{count:s,since:y})=>{n.warn(`${t}_suppressed count=${s} since=${y} ${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 Pl=256*1024,No=6e4,Ml=e=>Math.ceil(e/2),Ll=new Uint8Array(new ArrayBuffer(0)),Nl=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=Ll,t()},i=l=>{clearTimeout(o),o=$e(()=>{l.error(new Error(`attachment body idle for ${No} ms`)),a()},No)};return new ReadableStream({start(l){i(l)},pull(l){let c=Math.min(n+Pl,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})},Oo=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=et({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:c=>`viewer=${c}`}),l=qe({limit:e.concurrency,maxHeldPerOwner:Ml(e.concurrency),queue:null});return async c=>{let{request:s,delivery:y,attachmentId:m,internalUserId:S,readAttachment:f,cookie:R,fail:A}=c,b=e.maxBytes,w=i.spend(S,`attachment=${m} viewer=${S}`);if(w)return A(w.status,w.message,w.headers);let F=await n(s),V=await t.getAttachmentForUser(F,m,S);if(!V)return o.warn(`404 attachment=${m} viewer=${S} reason=not_visible`),A(404,"Attachment not found");if(V.fileSize!=null&&V.fileSize>b)return o.warn(`413 attachment=${m} viewer=${S} reason=db_size`),A(413,"Attachment too large");let P=fn(V.fileType),I=`filename="${Mo(V.fileName)}"; filename*=UTF-8''${Po(V.fileName)}`,q=await l.acquire(S,s.signal);if(!q)return s.signal.aborted?(o.info(`503 attachment=${m} viewer=${S} reason=aborted`),A(503,"Attachment request aborted")):(o.warn(`503 attachment=${m} viewer=${S} reason=concurrency`),A(503,"Too many concurrent downloads",xe(503)));let $=!1;try{let H=await f(V.filePath,{maxBytes:b,head:s.method==="HEAD",principal:r(S),signal:s.signal});if(s.signal.aborted)return o.info(`503 attachment=${m} viewer=${S} reason=aborted`),A(503,"Attachment request aborted");if(!H.ok){if(!mr(H.reason))return o.error(`500 attachment=${m} viewer=${S} reason=port_contract code=failure_reason`),A(500,Ze);let me=pr(H.reason);return H.reason==="not_found"&&a(m,!1),o.warn(`${me} attachment=${m} viewer=${S} reason=${H.reason} code=${H.code??"-"}`),A(me,dr[me],xe(me))}if(H.bytes.byteLength>b)return o.error(`500 attachment=${m} viewer=${S} reason=port_contract code=over_max_bytes`),A(500,Ze);let ce=s.method==="HEAD";if(ce&&H.size!==void 0&&H.size>b)return o.error(`500 attachment=${m} viewer=${S} reason=port_contract code=over_max_bytes`),A(500,Ze);if(!ce&&H.size!==void 0&&H.size!==H.bytes.byteLength)return o.error(`500 attachment=${m} viewer=${S} reason=port_contract code=size_mismatch`),A(500,Ze);let de=P??fn(H.contentType),ge=de!==null&&Co.has(de),G=ge?de:"application/octet-stream",re=ge&&y.kind!=="download"?"inline":"attachment",ee=ce?H.size:H.bytes.byteLength,se=new Headers({"Content-Type":G,"Content-Disposition":`${re}; ${I}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...Tt});return ee!==void 0&&se.set("Content-Length",String(ee)),R&&se.append("Set-Cookie",R),a(m,!0),o.info(`200 attachment=${m} viewer=${S} type=${G} disposition=${re} bytes=${ee??"-"}`),ce?new Response(null,{status:200,headers:se}):($=!0,new Response(Nl(H.bytes,q),{status:200,headers:se}))}finally{$||q()}}};var Ce=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),Om=Ce.queueWaitMs+Ce.readMs+Ce.renderMs+Ce.transferMarginMs;var Fo=require("buffer"),Ho=new Set([194,198,202,206]),Ol=new Set([192,193,194,195]),Uo=216,vl=217,$o=218,kl=4,Fl=64,Hl=2,vo=8,ko=28,at=12,Sn=8,Ul=20,Bo=at+Sn+10,$l=2,tt=(e,t)=>e[t]<<8|e[t+1],Et=(e,t,r)=>{let n=0;for(let o=r-1;o>=0;o-=1)n=n*256+e[t+o];return n},je=(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},Vo=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,Yo=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),qo=e=>(e.stepsLeft-=1,e.stepsLeft>=0),jo=e=>e[0]===255&&e[1]===Uo,Wo=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!qo(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===vl)return"eoi";if(o===0||o===Uo)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=tt(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")}},Bl=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!qo(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}},zo=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=tt(e,r+1),a=tt(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],y=s>>4,m=s&15;if(y<1||y>4||m<1||m>4)return null;l.push({id:e[r+6+3*c],horizontal:y,vertical:m})}return{marker:t,width:a,height:o,components:l}},Go=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>kl||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},Ko=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:Ho.has(e.marker)||t<e.components.length}),gn=e=>{if(!jo(e))return null;let t=Yo(e.byteLength),r=null;for(let n=2;;){if(Wo(e,n,t)!=="segment")return null;if(Vo(t.marker)){if(r!==null||(r=zo(e,t),r===null))return null}else if(t.marker===$o){if(r===null)return null;let o=Go(e,t);return o===null?null:Ko(r,o.length)}n=t.end}},Jo=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*vo)),i=Math.ceil(e.height*o/(r*vo));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},Qo=e=>e.multiScan?Jo(e).reduce((r,n)=>r+n,0)*Fl*Hl:0,Vl=896,Xo=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!jo(e))return null;let n=Fo.Buffer.from(e.buffer,e.byteOffset,e.byteLength),o=Yo(r),a=null,i=null,l=new Map,c=0,s=0,y=0;for(let m=2;;){let S=Wo(e,m,o);if(S===null)return null;if(S==="eoi")return i===null?null:{header:i,blockVisits:s};if(m=o.end,Vo(o.marker)){if(a!==null||!Ol.has(o.marker)||(a=zo(e,o),a===null))return null;let f=Jo(a);l=new Map;for(let[R,A]of a.components.entries()){let b=l.get(A.id);l.set(A.id,b===void 0?f[R]:Math.max(b,f[R]))}c=a.components.length*(Ho.has(a.marker)?Vl:1)}else if(o.marker===$o){if(a===null||y===c)return null;let f=Go(e,o);if(f===null)return null;for(let A of f){let b=l.get(A);if(b===void 0)return null;s+=b}if(y+=1,i===null&&(i=Ko(a,f.length)),s>t||!i.multiScan)return{header:i,blockVisits:s};let R=Bl(n,o.end,o);if(R===null)return null;m=R}}},Zo=e=>{if(e.byteLength<24||tt(e,8)!==0||tt(e,10)!==13||!je(e,12,"IHDR"))return null;let t=tt(e,16)*65536+tt(e,18),r=tt(e,20)*65536+tt(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},Yl=e=>{if(je(e,at,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=Et(e,26,2)&16383,r=Et(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(je(e,at,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=Et(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return je(e,at,"VP8X")?e.byteLength<Bo?null:{width:Et(e,24,3)+1,height:Et(e,27,3)+1}:null},ea=e=>{if(Zo(e)===null||e.byteLength<=ko)return null;switch(e[ko]){case 0:return!1;case 1:return!0;default:return null}},ta=(e,t)=>{if(je(e,at,"VP8 "))return"lossy";if(je(e,at,"VP8L"))return"lossless";if(!je(e,at,"VP8X")||e.byteLength<Bo)return null;if((e[Ul]&$l)!==0)return"animated";let r=!1,n=t;for(let o=at;o+Sn<=e.byteLength;){if(n-=1,n<0)return null;if(je(e,o,"VP8L"))return"lossless";if(je(e,o,"VP8 "))return r?"lossy-alpha":"lossy";je(e,o,"ALPH")&&(r=!0);let a=Et(e,o+4,4);o+=Sn+a+a%2}return null},ra={png:Zo,jpeg:gn,webp:Yl};var yr=Object.freeze(["image/webp","image/jpeg","image/png"]),hr=1024*1024;var ql=new Set(["image/png","image/jpeg","image/gif","image/webp"]),jl={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},Wl=new Set(yr),zl=e=>typeof e=="string"&&Wl.has(e),Gl=256,fr=(e,t)=>e.fileType===null||!ql.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,Kl=[137,80,78,71,13,10,26,10],Jl=[255,216,255],Ql=[[71,73,70,56,55,97],[71,73,70,56,57,97]],Xl=[82,73,70,70],Zl=[87,69,66,80],kt=(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},bn=e=>{if(kt(e,Kl,0))return"png";if(kt(e,Jl,0))return"jpeg";for(let t of Ql)if(kt(e,t,0))return"gif";return kt(e,Xl,0)&&kt(e,Zl,8)?"webp":null},na=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:Ao([t])}},oa=(e,t)=>{if(!zl(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>hr)return"too_large";let r=jl[e.contentType];if(bn(e.bytes)!==r)return"signature";let n=ra[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},aa=e=>{te("maxBytes",e.maxBytes,0),te("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)+Gl;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 Dn=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:o,onStuck:a}=e,i=ue(),l=new AbortController,c=!1,s,y,m=()=>{a(ue()-i)},S=P=>{s=$e(()=>{c=!0,P({timedOut:!0}),y=$e(m,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},f=new Promise(S),R=AbortSignal.any([r,l.signal]),A=P=>{P(n(R))},b=new Promise(A),w=P=>(clearTimeout(s),clearTimeout(y),c&&o(ue()-i,P.kind==="error"?{error:P.error}:null),P),F=b.then(P=>w({kind:"value",value:P}),P=>w({kind:"error",error:P}));return{outcome:Promise.race([b.then(P=>({timedOut:!1,value:P})),f]),settled:F}};var it={404:"Attachment not found",500:Ze,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},ia=(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=oa(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},ec=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)}}},sa=()=>{},tc=(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)}),la=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:i}=e,l=new Map,c=(f,R)=>{let A=R.then(sa,sa);l.set(f,A);let b=()=>{l.get(f)===A&&l.delete(f)};A.then(b)},s=async(f,R)=>{let A=l.get(f.key);if(A===void 0)return t.acquire(f.owner,R);let b=ec(R);try{if(await tc(A,b.signal),b.signal.aborted)return null;let w=r.get(f.key);return w!==void 0?{...w,identity:"verified"}:await t.acquire(f.owner,b.signal)}finally{b.end()}},y=(f,R)=>{if(f.fileSize===null)return R.kind==="exact"?"verified":"unrecorded";if(R.kind==="exact"?R.bytes===f.fileSize:f.fileSize>R.maxBytes)return"verified";let b=R.kind==="exact"?String(R.bytes):`>${R.maxBytes}`;return i.warn(`size_mismatch expected=${f.fileSize} got=${b} attachment=${f.attachmentId} viewer=${f.owner} variant=thumbnail`),"unverified"},m=(f,R)=>(A,b)=>{let w=b===null?"":` message=${b.error instanceof Error?b.error.message:"unknown"}`;i.warn(`${f}_overrun ms=${A} attachment=${R.attachmentId} viewer=${R.owner} variant=thumbnail${w}`)},S=(f,R)=>A=>{i.warn(`${f}_stuck ms=${A} attachment=${R.attachmentId} viewer=${R.owner} variant=thumbnail`)};return async(f,R)=>{let A=await s(f,R);if(A===null)return{kind:"failure",status:503,reason:R.aborted?"aborted":"queue"};if(typeof A!="function")return A;let b=A,w=null;try{if(R.aborted)return{kind:"failure",status:503,reason:"aborted"};let F=r.get(f.key);if(F!==void 0)return{...F,identity:"verified"};let V=Dn({budgetMs:Ce.readMs,flightSignal:R,call:me=>f.readAttachment(f.filePath,{maxBytes:n,head:!1,principal:o(f.owner),signal:me}),onOverrun:m("read",f),onStuck:S("read",f)}),P=await V.outcome;if(P.timedOut)return w=V.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 I=P.value;if(!I.ok&&I.reason!=="too_large")return mr(I.reason)?(I.reason==="not_found"&&a(f.attachmentId,!1),{kind:"failure",status:pr(I.reason),reason:I.reason,code:I.code}):{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};if(I.ok&&I.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let q=y(f,I.ok?{kind:"exact",bytes:I.bytes.byteLength}:{kind:"over",maxBytes:n}),$=me=>{q==="verified"&&r.set(f.key,me)},H=me=>($(me),{...me,identity:q});if(!I.ok)return H({kind:"unrenderable",reason:"too_large"});let ce=bn(I.bytes);if(ce===null)return H({kind:"unrenderable",reason:"signature"});let de=Dn({budgetMs:Ce.renderMs,flightSignal:R,call:me=>f.renderer.render(I.bytes,{format:ce,maxWidth:f.box.maxWidth,maxHeight:f.box.maxHeight,signal:me}),onOverrun:m("render",f),onStuck:S("render",f)}),ge=me=>{if(me.kind==="error")return;let fe=ia(me.value,f.box);"entry"in fe&&$(fe.entry)},G=null,re=()=>(G===null&&(G=de.settled.then(ge),c(f.key,G)),G);R.addEventListener("abort",re,{once:!0});let ee=await de.outcome.finally(()=>R.removeEventListener("abort",re));if(ee.timedOut||R.aborted)return w=re(),R.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let se=ia(ee.value,f.box);return"entry"in se?H(se.entry):se.failure}finally{w===null?b():w.then(b,b)}}};var ca=()=>{let e=new Map;return{join:(t,r,n)=>{let o=()=>{let c=new AbortController,s=()=>{e.get(t)?.controller===c&&e.delete(t)},m={promise:n(c.signal).finally(s),controller:c,waiters:0};return e.set(t,m),m},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 ma=10,rc=1/ma,ua=1-rc,nc=1024,oc=64,ac=8,da="private, no-cache",ic="no-store",sc=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),lc=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},pa=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:c}=l,s=(P,I)=>et({reason:P,limitPerWindow:I,windowMs:6e4,logger:o,windowFields:q=>`viewer=${q} variant=thumbnail`}),y=s("rate_limit",l.rateLimitPerMinute),m=s("revalidation_rate_limit",l.rateLimitPerMinute*ma),S=qe({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:oc,maxPerOwner:ac,maxWaitMs:Ce.queueWaitMs}}),f=aa({maxBytes:l.cacheBytes,maxEntries:nc}),R=ca(),A=la({gate:S,cache:f,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),b=(P,I,q,$)=>{let H=`attachment=${P.attachmentId} viewer=${P.internalUserId} variant=thumbnail cache=${$}`;if(I.kind==="failure")return o[lc(I)](`${I.status} ${H} reason=${I.reason} code=${I.code??"-"}`),P.fail(I.status,it[I.status],xe(I.status));let ce=sc[I.identity];if(I.kind==="unrenderable")return o.info(`404 ${H} reason=${I.reason}${ce}`),P.fail(404,it[404]);let de=I.identity==="verified"?{"Cache-Control":da,ETag:q}:{"Cache-Control":ic},ge=new Headers({"Content-Type":I.contentType,"Content-Length":String(I.bytes.byteLength),...de,"Content-Security-Policy":"default-src 'none'; sandbox",...Tt});return P.cookie&&ge.append("Set-Cookie",P.cookie),o.info(`200 ${H} type=${I.contentType} bytes=${I.bytes.byteLength}${ce}`),new Response(I.bytes,{status:200,headers:ge})},w=(P,I)=>{let q=P.spend(I.internalUserId,`attachment=${I.attachmentId} viewer=${I.internalUserId} variant=thumbnail`);return q===null?null:I.fail(q.status,q.message,q.headers)},F=P=>w(y,P),V=(P,I)=>I?w(m,P):F(P);return async(P,I)=>{let{request:q,attachmentId:$,internalUserId:H,readAttachment:ce,cookie:de,fail:ge}=P,G=un[I],re=q.headers.get("If-None-Match"),ee=re!==null,se=V(P,ee);if(se)return se;let me=await n(q),fe=await t.getAttachmentForUser(me,$,H),ne=fe!==null&&fr(fe,i)?na({rendererId:c.id,box:G,attachmentId:$,filePath:fe.filePath,fileType:fe.fileType,fileSize:fe.fileSize}):null;if(ne&&pn(re,ne.etag)){let E=new Headers({"Cache-Control":da,ETag:ne.etag,...Tt});return de&&E.append("Set-Cookie",de),o.info(`304 attachment=${$} viewer=${H} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:E})}if(ee){let E=F(P);if(E)return E}if(!fe)return o.warn(`404 attachment=${$} viewer=${H} variant=thumbnail reason=not_visible`),ge(404,it[404]);if(!ne)return y.refund(H,ua),o.info(`404 attachment=${$} viewer=${H} variant=thumbnail reason=not_eligible`),ge(404,it[404]);let{key:Ne,etag:Fe}=ne,we=f.get(Ne);if(we)return y.refund(H,ua),b(P,{...we,identity:"verified"},Fe,"hit");let Ve=E=>A({key:Ne,attachmentId:$,filePath:fe.filePath,fileSize:fe.fileSize,box:G,owner:H,readAttachment:ce,renderer:c},E),O;try{O=await R.join(Ne,q.signal,Ve)}catch(E){return o.error(`500 attachment=${$} viewer=${H} variant=thumbnail cache=miss reason=port_exception message=${E instanceof Error?E.message:"unknown"}`),ge(500,it[500])}return b(P,O,Fe,"miss")}};var cc='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',uc=()=>ur(403,hn,{cookie:null}),ya=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=dn(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>ur(404,dr[404],{cookie:null}),crossSiteRejection:uc}),ha=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:xo(r,a)},c=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:Oo({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:pa({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:s,params:y})=>{let m=null,S=(f,R,A={})=>ur(f,R,{cookie:m,extraHeaders:A});try{let{user:f,cookie:R}=await t(s,{failureRedirect:null});if(m=R??null,!f)return S(401,"Unauthorized");let A=dn(new URL(s.url).searchParams);if(A.kind==="invalid")return S(400,"Invalid attachment request");if(A.kind==="thumbnail"&&s.method!=="GET")return S(405,"Method not allowed",{Allow:"GET"});if(s.method!=="GET"&&s.method!=="HEAD")return S(405,"Method not allowed",{Allow:"GET, HEAD"});if(c===null)return S(404,"Attachment not found");if(y.token===void 0)throw new Error(cc);let b=c.idCodec.decode(y.token);if(b===null||!At(b))return S(400,"Invalid attachment token");let w=await r.getUserIdByExternalId(f.id);if(!w)return S(403,"Forbidden");let F={request:s,delivery:A,attachmentId:b,internalUserId:w,readAttachment:c.read,cookie:m,fail:S};return A.kind!=="thumbnail"?await c.serveOriginal(F):c.serveThumbnail===null?S(404,it[404]):await c.serveThumbnail(F,A.variant)}catch(f){if(f instanceof Response)throw f;return a.error(`500 attachment=? viewer=? reason=unexpected message=${f instanceof Error?f.message:"unknown"}`),S(500,Ze)}}};var dc=32*1024*1024,mc=60,pc=4,yc=120,hc=2,fc=8*1024*1024,Rr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Rc=e=>{if(e===void 0)throw gt("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!Rr(e))throw le("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw gt("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw le("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw le("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},Sc=e=>{if(e===void 0)return null;if(!Rr(e))throw le("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:Rc(e.renderer),rateLimitPerMinute:ct("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,yc),concurrency:ct("attachments.thumbnails.concurrency",e.concurrency,1,hc),cacheBytes:ct("attachments.thumbnails.cacheBytes",e.cacheBytes,0,fc)})},fa=e=>{let t=e;if(t===void 0)return null;if(!Rr(t))throw le("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw gt("attachments.idCodec","injected when attachments is given");if(!Rr(r)||typeof r.encode!="function"||typeof r.decode!="function")throw le("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw gt("attachments.read","injected when attachments is given");if(typeof n!="function")throw le("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:ct("attachments.maxBytes",t.maxBytes,1,dc),rateLimitPerMinute:ct("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,mc),concurrency:ct("attachments.concurrency",t.concurrency,1,pc),thumbnails:Sc(t.thumbnails)})},gc=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"]]),Sr=e=>{for(let[t,r]of gc)if(Object.hasOwn(e,t))throw gt(r,`given in place of the flat key ${t}`)};var Sa=8,bc=8*Sa,Dc=128,Ac=2,ga=Ac*Dc,Tc=4*ga,Ec=6e4,Ic=6e4,_c="Too many reads",Ra=Object.freeze(Object.keys(ot).filter(e=>ot[e].admission.includes("miss-gate"))),ba=e=>{let t=qe({limit:bc,maxHeldPerOwner:Sa,queue:{max:Tc,maxPerOwner:ga,maxWaitMs:Ec}}),r=ke({windowMs:Ic,tallies:Ra,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{e.warn(`cache_miss_admission_suppressed count=${o} since=${a} viewer=${n} endpoints=${Ra.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}})}},gr=(e,t)=>{let r=Z(e,t,{error:{message:_c}},503);for(let[n,o]of Object.entries(xe(503)))r.headers.set(n,o);return r};var wc=/^[0-9a-f]{1,16}$/;var Da=e=>{let t=e.get(Re.cursorReportHubId),r=e.get(Re.cursorBusinessDate),n=e.get(Re.cursorSnapshot),o=n!==null&&wc.test(n)?n:null,a=null;if(t!==null){let l=Ue(t);if(l===null)return{refused:"cursor"};if(r!==null&&!rr(r))return{refused:"cursor"};a={businessDate:r,reportHubId:l}}else if(r!==null)return{refused:"cursor"};let i=Ot(e.get(Re.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var br=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,xc=2,Cc=16,Pc=xc*Cc,Mc=6e4,Aa=()=>{},Lc=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},Ta=e=>{let t=qe({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:Pc,queue:null}),r=ke({windowMs:Mc,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 Aa;if(a.aborted){if(t.canAcquire(n))return Aa}else{let i=await t.acquire(n,a);if(i!==null)return Lc(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var Dr=30,xa=4e3,Nc="stream interrupted by server error",Oc="Too many streams",vc=15e3,Ca=Symbol("ids-stream-heartbeat"),Ea=()=>{},Ia=e=>e.return(void 0).then(Ea,Ea),kc=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(Ca),vc)}),stop:()=>clearTimeout(e)}};async function*_a(e,t,r,n){let o=t?zn(e,t):0,a=!0;for(;;){let i=e.slice(o,o+(a?r:xa));o+=i.length;let l=o>=e.length,c=i[i.length-1];if(yield{kind:"chunk",items:i,nextCursor:l||!c?null:{businessDate:c.businessDate,reportHubId:c.reportHubId},isLast:l,...a?{total:e.length}:{},...a?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...a&&n.restarted?{restarted:!0}:{}},a=!1,l)return}}var Pa=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform",...Ye});return e&&t.append("Set-Cookie",e),t},wa=(e,t,r,n,o)=>{let a=async(y,m)=>{o(),m&&await Ia(t);try{y.close()}catch{}},i=new TextEncoder,l=!1,c=null,s=new ReadableStream({async pull(y){if(l||r.aborted){await a(y,!0);return}let m=kc();try{c===null&&(c=t.next());let S=await Promise.race([c,m.fired]);if(m.stop(),S===Ca){if(l||r.aborted){await a(y,!0);return}y.enqueue(i.encode(`
|
|
2
|
+
`));return}c=null;let{value:f,done:R}=S;if(R){await a(y,!1);return}if(l||r.aborted){await a(y,!0);return}y.enqueue(i.encode(`${JSON.stringify(f)}
|
|
3
|
+
`))}catch(S){if(m.stop(),c=null,o(),l||r.aborted)return;S instanceof He||n.error(`ids-stream emission failed: ${S instanceof Error?S.message:String(S)}`);try{let f={kind:"error",error:Nc};y.enqueue(i.encode(`${JSON.stringify(f)}
|
|
4
|
+
`)),y.close()}catch{}}},cancel(){l=!0,o(),Ia(t)}});return new Response(s,{status:200,headers:Pa(e)})},Ma=e=>{let{service:t,logger:r,streamSlots:n,missGate:o,refuseForcedRead:a}=e,i=async(l,c,s,y,m,S,f)=>{let R=!1,A=null,b=null,w=new Promise((P,I)=>{A=P,b=I});w.catch(()=>{});let F=t.getDailyReportIdsByExternalId(s,c.id,{forceRefresh:l.forceRefresh,admission:f,onFetchStart:l.cursor?void 0:()=>{R=!0,t.readSseStreamAnchor().then(P=>t.getDailyReportIdsFirstPageByExternalId(s,c.id,Dr).then(I=>({items:I,streamAnchor:P}))).then(P=>A?.(P),P=>b?.(P))}});if(F.catch(()=>{}),l.cursor){let{items:P,streamAnchor:I,snapshot:q}=await F,$=l.snapshot!==null&&l.snapshot===q;return wa(y,_a(P,$?l.cursor:null,Dr,{snapshot:q,restarted:!$,streamAnchor:I}),m,r,S)}let V=(async function*(){let P=await Promise.race([F.then($=>({kind:"full",source:$}),$=>({kind:"full-error",error:$})),w.then($=>({kind:"page",page:$}),()=>({kind:"page-error"}))]),I=null,q=!1;if(P.kind==="full")I=P.source;else if(P.kind==="page"){let{items:$,streamAnchor:H}=P.page;if($.length<Dr){yield{kind:"chunk",items:$,nextCursor:null,isLast:!0,total:$.length,streamAnchor:H};return}yield{kind:"chunk",items:$,nextCursor:null,isLast:!1,provisional:!0},q=!0}else if(P.kind==="full-error"&&R){let $=await w.catch(()=>null);$&&$.items.length>0&&(yield{kind:"chunk",items:$.items,nextCursor:null,isLast:!1,provisional:!0})}I===null&&(I=await F),yield*_a(I.items,null,q?xa:Dr,{snapshot:I.snapshot,streamAnchor:I.streamAnchor})})();return wa(y,V,m,r,S)};return async(l,c,s,y,m)=>{let S=Da(l.searchParams);if("refused"in S)return Z(s,c,{error:{message:S.refused==="cursor"?"Invalid cursor":"Invalid forceRefresh"}},400);let{query:f}=S;if(f.forceRefresh){let w=a(y,s,c);if(w!==null)return w}let R=br(s),A=await t.getUserIdByExternalId(y.id),b=await n.admit(A,"ids-stream",R);if(b===null){let w=Z(s,c,{error:{message:Oc}},503);for(let[F,V]of Object.entries(xe(503)))w.headers.set(F,V);return w}if(R.aborted)return new Response(null,{status:200,headers:Pa(c)});try{return await i(f,y,m,c,R,b,A===null?void 0:o.admissionFor(A,oe.idsStream,R))}catch(w){if(b(),w instanceof He)return gr(s,c);throw w}}};var Ht=require("drizzle-orm");var Fc="",Hc=64,Uc=e=>e.toLowerCase(),$c=e=>e.trim().toLowerCase();function La(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=$c(r);n.length>0&&t.add(n)}return t}function Me(e,t){return e===null?!0:t==null?!1:e.has(Uc(t))}function Le(e){return e!==null&&e.size===0}function Ut(e,t){if(t!==null)return t.size===0?Ht.sql`1 = 0`:(0,Ht.inArray)(Ht.sql`LOWER(${e})`,[...t])}var It,_t,Ft=class Ft{constructor(t,r){Vr(this,It);Vr(this,_t);Yr(this,It,t),Yr(this,_t,r)}get visible(){return Lt(this,It)===null?null:new Set(Lt(this,It))}get commentable(){return Lt(this,_t)===null?null:new Set(Lt(this,_t))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=La(r?t.read:t),o=r?t.comment:void 0;if(o===void 0)return new Ft(n,n);let a=La(o),i=new Set;for(let l of a??[])n.has(l)&&i.add(l);return new Ft(n,i)}static unrestricted(t){return new Ft(null,null)}};It=new WeakMap,_t=new WeakMap;var Pe=Ft;function $t(e){let t=Na(e.visible),r=Na(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function Na(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(Fc);if(t.length<=Hc)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 Oa=(e,t,r,n)=>Me(n.commentable,t)||e.authorUserId!==null&&e.authorUserId===r;var ja=require("@aiquants/fuzzy-search");var ka=require("crypto"),he=require("@aiquants/fuzzy-search/normalize");var Tr=`
|
|
5
|
+
`,Er=4e3,Bc=1,Fa=new Set([8203,8288,65279,173]),Vc=new RegExp(`[${String.fromCodePoint(...Fa)}]`,"gu"),Yc=new RegExp(`\\r\\n|[\\n\\r${String.fromCodePoint(133,8232,8233)}]`,"gu"),qc=/(\s+)/u,jc=/^\s+$/u,Wc=/^(?:(?=\p{Lo})[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]|[A-Za-z0-9])$/u,zc=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]),Bt=e=>e.replace(Vc,""),Ha=e=>{let t=Bt(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++)Fa.has(e.charCodeAt(o))||(r[n++]=o);return{text:t,rawIndex:r}},Tn=e=>(0,he.normalizeText)(e,he.DEFAULT_NORMALIZE_OPTIONS),Ar=e=>Tn(Bt(e)),Gc=(0,he.resolveNormalizeOptions)({...he.DEFAULT_NORMALIZE_OPTIONS,convertRomaji:!0},"[daily-report] search reading options"),Kc=3,Jc=/^[-ー]+/u,Qc=/[^\p{L}\p{M}]/gu,Xc=/ー{2,}/gu,Zc=/\p{Script=Latin}/u,va=/(?=\p{L})\p{Script=Latin}/u,eu=e=>(0,he.clusterCountOf)(e.replace(Jc,"").replace(Qc,"").replace(Xc,"\u30FC")),tu=(e,t)=>{for(let r of t)if(!(0,he.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})`)},Ua=e=>{if(!va.test(e))return[];let t=Ar(e);if(!va.test(t))return[];let r=(0,he.queryNeedles)(t,Gc,!1);tu(t,r);let n=[];for(let o of r){if(o.tier===ut.word)continue;let a=Ar(o.text);if(!(a.length===0||a.length>Ie.maxWordLength)&&!(a===t||Zc.test(a))&&!(eu(a)<Kc||n.includes(a))&&(n.push(a),n.length===Kr))break}return n},$a=(e,t)=>{let r=e.charCodeAt(t-1),n=e.charCodeAt(t);return r>=55296&&r<=56319&&n>=56320&&n<=57343},ru=(e,t)=>{let r=e.codePointAt(t),n=t>=2&&$a(e,t-1)?t-2:t-1;return Wc.test(String.fromCodePoint(r))&&!zc.has(e.codePointAt(n))},nu=(e,t,r)=>{let n=[],o=0,a=0;for(;e.length-a>r;){let i=a+r;for(;i>a&&!ru(e,i);)i--;i===a&&(i=a+r,$a(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}},En=(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(qc)){let s=o;if(o+=c.length,i+c.length<=t){i===0&&(a=s),i+=c.length;continue}if(l(),jc.test(c))continue;if(c.length<=t){a=s,i=c.length;continue}let y=nu(c,s,t);n+=y.forcedCuts,r.push(y.pieces)}return l(),{chunks:r,forcedCuts:n}},In=(e,t)=>{let r=En(e,t),n=[];for(let o of r.chunks){let a=o.map(i=>Tn(e.slice(i.start,i.end))).join("");a.length>0&&n.push(a)}return{text:n.join(" "),forcedCuts:r.forcedCuts}},_n=(e,t)=>{let r=0;for(let n of e.matchAll(Yc))t(e.slice(r,n.index),r),r=n.index+n[0].length;t(e.slice(r),r)},ou=(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},Ba=(e,t)=>{let r="",n=[],o=[];for(let a of t.chunks){let i="",l=[],c=[];for(let s of a){let y=e.slice(s.start,s.end),m=ou((0,he.toMappedFormsInto)(y,he.DEFAULT_NORMALIZE_OPTIONS,new he.InteriorPairs(0)),y),[S,f]=(0,he.trimmedRange)(m.text);i+=m.text.slice(S,f);for(let R=S;R<f;R++)l.push(s.start+m.start[R]),c.push(s.start+m.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}},Ir=(e,t=Er)=>{let r=[],n=0;return _n(Bt(e),o=>{let a=In(o,t);n+=a.forcedCuts,a.text.length>0&&r.push(a.text)}),{text:r.join(Tr),forcedCuts:n}},Va=e=>e.filter(t=>t.length>0).join(Tr),au=e=>{let t=[];for(let r=0;r<=65535;r++)r>=55296&&r<=57343||t.push(e+String.fromCharCode(r));return t.join(`
|
|
6
|
+
`)},iu=[`\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`],su=()=>{let e=(0,ka.createHash)("sha256");e.update(JSON.stringify(he.DEFAULT_NORMALIZE_OPTIONS));for(let t of["","\u30A2","\u4F50"," "])e.update("\0"),e.update(Tn(au(t)));return e.update("\0"),e.update(JSON.stringify(iu.map(t=>Ir(t,8)))),`dr-search-v${Bc};fz=${e.digest("hex").slice(0,16)};u=${process.versions.unicode};icu=${process.versions.icu}`},An=null,Ya=()=>(An===null&&(An=su()),An);var lu=/^-+/u,cu=/\s+/u,qa=e=>{let t=lu.exec(e);return t===null?[e]:[e,"\u30FC".repeat(t[0].length)+e.slice(t[0].length)]},uu=(e,t)=>{let r=[...qa(e).map(n=>({text:n,tier:ut.word})),...t.flatMap(n=>qa(n).map(o=>({text:o,tier:ut.reading})))];return r.filter((n,o)=>r.findIndex(a=>a.text===n.text)===o)},du=e=>JSON.stringify(e.map(({text:t,tier:r})=>JSON.stringify([r,t])).sort()),_r=(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,ja.parseQuerySets)(Bt(e),t).sets){let i=[],l=new Set;for(let s of a.split(cu)){let y=Ar(s);if(y.length===0)return{ok:!1,reason:"blank-word"};if(y.length>Ie.maxWordLength)return{ok:!1,reason:"word-too-long"};let m=uu(y,Ua(s)),S=du(m);l.has(S)||(l.add(S),i.push({alternatives:m}))}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}}},Vt=e=>e.sets.map(t=>t.words.map(r=>r.alternatives));var Qp=Object.freeze({sourceTypes:null,authors:null,customers:null}),mu=e=>e.sourceTypes!==null||e.authors!==null||e.customers!==null,Wa=(e,t,r)=>{if(io(e)&&mu(r))return{ok:!0,criteria:{plan:null,filters:r}};let n=_r(e,t);return n.ok?{ok:!0,criteria:{plan:n.plan,filters:r}}:{ok:!1,reason:n.reason}};var za=6e4,pu=1,yu=2e3,hu=Object.freeze({search:null,reports:null,"search-marks":yu,"search-facets":null}),fu=(e,t)=>{let r=hu[e];return r===null?null:{max:t,maxPerOwner:or,maxWaitMs:r}},Yt=e=>{let{concurrency:t,route:r,logger:n}=e,o=et({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:za,logger:n,windowFields:()=>`route=${r}`}),a=qe({limit:t,maxHeldPerOwner:Math.max(1,Math.floor(t/2)),queue:fu(r,t)}),i=Object.freeze({status:429,message:Rn,headers:Object.freeze({"Retry-After":String(pu)})}),l=ke({windowMs:za,tallies:["busy"],writeSuppressed:(c,{count:s,since:y})=>{n.warn(`busy_suppressed count=${s} since=${y} route=${r} concurrency=${t}`)}});return{admit:async(c,s)=>{let y=o.spend(c,r);if(y!==null)return{refusal:y};let m=await a.acquire(c,s);return m!==null?{release:m}:(o.refund(c,1),s.aborted||l.record(r,"busy",()=>n.warn(`429 ${r} reason=busy concurrency=${t}`)),{refusal:i})}}};var ai=require("@aiquants/sse"),st=require("@aiquants/sse/server");var wt=(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=oo.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}},Ru=["externalComments","postedComments"],Ga=new WeakMap,Su=e=>{let t=Ga.get(e);if(t!==void 0)return t;let r={recipientRemoved:null,commentsRedacted:null};return Ga.set(e,r),r},Ka=e=>{let{recipientRawUserId:t,...r}=e;return r},Ja=(e,t)=>{let{published:r}=e;if(!(t||Object.hasOwn(r,"recipientRawUserId")))return e.text;let n=Su(e);if(t){if(n.commentsRedacted===null){let o=Ka(r),a=o.report;n.commentsRedacted=JSON.stringify({...o,report:{...a,...Object.fromEntries(Ru.map(i=>[i,[]]))}})}return n.commentsRedacted}return n.recipientRemoved===null&&(n.recipientRemoved=JSON.stringify(Ka(r))),n.recipientRemoved};var ti=require("@aiquants/sse"),ri=require("@aiquants/sse/shared-source");var mt="daily-report:ids:",pt="daily-report:business-date:",wr=(e,t)=>`${e}st:${t}`,wn=e=>`${mt}user:${e}:`,Qa=(e,t)=>wr(wn(e),t),gu=e=>`${pt}${e}:`,Xa=(e,t)=>wr(gu(e),t),qt=e=>`daily-report:date:${e}:user:`,xt=(e,t)=>`${qt(e)}${t}:`,Za=(e,t,r)=>wr(xt(e,t),r),We=e=>`daily-report:detail:${e}:user:`,xr=(e,t)=>`${We(e)}${t}:`,ei=(e,t,r)=>wr(xr(e,t),r);var rt=(e,t)=>{let[r,n]=e.split("-").map(Number),[o,a]=t.split("-").map(Number);return r!==o?r<o:n<=a},bu=5e3,Du=sr,Ct=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=Se(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,ri.createSharedSource)({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:ti.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:bu,COUNT:Du});if(i)for(let l of i)for(let c of l.messages){a=c.id;let{entry:s,json:y}=wt(c,this._logger);this._invalidateCaches(y),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(mt),(r==="comment-add"||r==="comment-delete"||r==="status-update")&&typeof n=="number"&&this.config.cache.invalidatePrefix(We(n))}};var ii=Object.freeze({...vt,route:"sse",frameworkDataRefusal:cr}),ni=864e5,Au={baseMs:2e3,jitterMs:8e3},xn=6e4,Pr=sr,si=JSON.stringify({type:"connected"}),oi="0-0",Tu=(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 Me(r,e.report.sourceType);case"comment-add":case"comment-delete":return Me(n,o??"Internal");case"report-delete":return Me(r,o)}},Eu=(e,t)=>t===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"?!1:!Me(t,e.report.sourceType),Iu=(e,t)=>{e.writeEvent({event:null,id:t,data:si})},_u=(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||!Tu(o,a,r.visibleSet,r.commentableSet)){Iu(e,t.id);return}e.writeEvent({event:null,id:t.id,data:Ja(n,Eu(o,r.commentableSet))})},li=e=>{let{authenticate:t,service:r,resolveViewerScope:n,redis:o,sseReader:a,streamKey:i,streamSlots:l,logger:c}=e,s=async(y,m)=>{let{request:S,internalUserId:f,cursor:R}=m,A=m.initialScope.visible,b=m.initialScope.commentable,w=0,F=setInterval(()=>{let G=++w;n(S,"refresh").then(re=>{G===w&&(A=re.visible,b=re.commentable)})},xn);y.onClose(()=>clearInterval(F));let V=R===null?oi:R,P=R!==null&&o!==void 0,I=[],q=null,$=G=>{rt(G.id,V)||(V=G.id,_u(y,G,{internalUserId:f,visibleSet:A,commentableSet:b}))},H=async(G,re)=>{let[ee]=await G.xRange(i,"-","+",{COUNT:1});return ee!==void 0&&!rt(ee.id,re)},ce=async(G,re)=>{if(await H(G,re))return!1;let ee=re;for(;;){let se=await G.xRange(i,ee,"+",{COUNT:Pr}),me=se[0];if(me!==void 0&&me.id!==ee&&await H(G,ee))return!1;for(let Ge of se){if(q!==null&&rt(q,Ge.id))return!0;rt(Ge.id,V)||$(wt(Ge,c).entry)}let fe=se.at(-1);if(se.length<Pr||fe===void 0||y.isClosed())return!0;ee=fe.id}},de=a.subscribe(G=>{if(!P){$(G);return}rt(G.id,V)||(q===null&&(q=G.id),I.push(G))},G=>{c.error(`[SSE:${f}] Fan-Out reader error:`,G),y.close()});if(y.onClose(de),R===null){await a.ready();try{let G=await o?.getClient();if(G){let re=await G.xRevRange(i,"+","-",{COUNT:1});re.length>0&&!rt(re[0].id,V)&&(V=re[0].id)}}catch{}}if(y.writeEvent({event:null,id:V===oi?null:V,data:si}),(0,st.startSseHeartbeat)(y,{intervalMs:eo,retry:Au,runtime:ai.systemSseRuntime}),R===null||o===void 0)return;await a.ready();let ge=await o.getClient();if(ge===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await ce(ge,R)){y.writeRetry(ni),y.writeEvent({event:"resync-required",id:null,data:""}),y.close();return}P=!1;for(let G of I.splice(0))$(G)};return async({request:y,params:m})=>{let S,f=()=>{let A=new Headers;S!==void 0&&A.append("Set-Cookie",S);for(let[b,w]of Object.entries(Ye))A.set(b,w);return A},R=A=>(0,st.terminalStreamResponse)(A,{data:"",retryMs:ni,headers:f()});try{let A=await t(y,{failureRedirect:null});S=A.cookie;let{user:b}=A;if(!b)return R("auth-required");let w=await r.getUserIdByExternalId(b.id);if(!w)return R("forbidden");if(m.endpoint!=="updates")return new Response("Not Found",{status:404,headers:f()});let F=(0,st.readLastEventId)(y,to);if(F!==null&&!ro(F))return c.warn(`[SSE:${w}] malformed resume cursor; asking the client to resync`),R("resync-required");let V=br(y),P=await l.admit(w,"sse",V);if(P===null){let q=f();for(let[$,H]of Object.entries(xe(503)))q.set($,H);return new Response("Too many streams",{status:503,headers:q})}let I=!1;try{let q=await n(y,"initial");return(0,st.createSseResponse)({requestSignal:V,headers:f(),onError:($,H)=>c.error(`[SSE:${w}] ${H} failed:`,$),produce:$=>(I=!0,$.onClose(P),s($,{request:y,internalUserId:w,cursor:F,initialScope:q}))})}finally{I||P()}}catch(A){if(A instanceof Response)throw A;let b=A instanceof Error?A:new Error(String(A));return c.error(`500 sse name=${b.name} message=${b.message}`),new Response("Internal Server Error",{status:500,headers:f()})}}};var ci=(e,t)=>{let r=new Headers({...t?.headers,"Content-Type":"application/json",...Ye});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},wu=Object.freeze({...vt,route:"api",frameworkDataRefusal:({params:e})=>cn(e.endpoint)&&ot[e.endpoint].body==="stream"?cr():null}),xu=Object.freeze({...vt,route:"action"}),Cu=(e,t,r)=>({...r,status:"OK",intent:e.intent,reportHubId:t,clientTempId:e.clientTempId}),mi=6e4,pi=5,Pu=pi*Math.ceil(mi/500),Mu=2,Lu=6,Nu=6e4,Ou=pi*Mu*Lu,vu=2,ku=10,Fu=2,Hu=10,ui=(e,t)=>Math.max(e,or)*t,Cn=(e,t)=>{for(let[r,n]of Object.entries(t))e.headers.set(r,n);return e},Mr=(e,t,r)=>Cn(Z(e,t,{error:{message:r.message}},r.status),r.headers),di=e=>Cn(Xe(e,null,503),xe(503));function Lr(e){Sr(e);let{authenticate:t,service:r,encodeUserId:n,redis:o,sseReader:a,streamKey:i}=e,l={titleMaxLength:te("service.titleMaxLength",r.titleMaxLength,1)},c=e.loginRedirectPath??"/auth/login",s=Se(e.logger,3,"API"),y=Se(e.logger,3,"Visibility"),m=Se(e.logger,1,"SSE"),S=Se(e.logger,1,"Attachment"),f=Se(e.logger,2,"Isolation"),R=Se(e.logger,2,"Action"),A=Se(e.logger,2,"Search"),b=Se(e.logger,2,"Refresh"),w=Se(e.logger,2,"Streams"),F=Se(e.logger,2,"Reads"),V=et({reason:"refresh_rate_limit",limitPerWindow:Ou,windowMs:Nu,logger:b,windowFields:()=>"route=api"}),P=Ta(w),I=ba(F),q=async(O,E,C,Y,j)=>{let J=await r.getUserIdByExternalId(E.id);try{return await j(J===null?void 0:I.admissionFor(J,O,C.signal))}catch(K){if(K instanceof He)return gr(C,Y);throw K}},$=(O,E,C,Y)=>{let j=V.spend(E.id,`endpoint=${O}`);return j===null?null:Mr(C,Y,j)},H=async(O,E="initial")=>{let C=e.resolveVisibleSourceTypes;if(!C)return Pe.unrestricted("no visibility port injected: this deployment does not restrict by source type");try{let Y=await C(O,{reason:E});return Y==null?Pe.unrestricted("visibility port returned null/undefined: this deployment opts out of source-type filtering"):Pe.restrictTo(Y)}catch(Y){return y.error("resolveVisibleSourceTypes threw; failing closed (deny all)",Y),Pe.restrictTo([])}},ce=async({request:O})=>{let{user:E,cookie:C}=await t(O,{failureRedirect:c}),Y=new Headers;C&&Y.append("Set-Cookie",C);let j=await r.getUserIdByExternalId(E.id),J=j?n(j):null;return{data:{user:E,userId:J},headers:Y}},de=r.searchLimits===null?null:Yt({...r.searchLimits,route:oe.search,logger:A}),ge=r.searchLimits===null?null:Yt({concurrency:ui(r.searchLimits.concurrency,vu),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*ku,route:oe.reports,logger:A}),G=r.searchLimits===null?null:Yt({concurrency:ui(r.searchLimits.concurrency,Fu),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*Hu,route:oe.searchMarks,logger:A}),re=r.searchLimits===null?null:Yt({...r.searchLimits,route:oe.searchFacets,logger:A}),ee={[oe.businessDate]:async(O,E,C,Y,j)=>{let J=O.searchParams.get(Re.businessDate),K=J===null?null:Dt(J);if(K===null)return Z(C,E,{error:{message:"Invalid business date"}},400);let z=Ot(O.searchParams.get(Re.forceRefresh));if(z===null)return Z(C,E,{error:{message:"Invalid forceRefresh"}},400);let Q=z?$(oe.businessDate,Y,C,E):null;return Q!==null?Q:q(oe.businessDate,Y,C,E,async M=>{let ae=await r.getDailyReportsByBusinessDateByExternalId(j,K,Y.id,{forceRefresh:z,admission:M});return Z(C,E,{businessDate:K,reports:ae},200)})},[oe.idsStream]:Ma({service:r,logger:s,streamSlots:P,missGate:I,refuseForcedRead:(O,E,C)=>$(oe.idsStream,O,E,C)}),[oe.report]:async(O,E,C,Y,j)=>{let J=Ue(O.searchParams.get(Re.reportHubId));if(J===null)return Z(C,E,{error:{message:"Invalid reportHubId"}},400);let K=Ot(O.searchParams.get(Re.forceRefresh));if(K===null)return Z(C,E,{error:{message:"Invalid forceRefresh"}},400);let z=K?$(oe.report,Y,C,E):null;return z!==null?z:q(oe.report,Y,C,E,async Q=>{let M=await r.getDailyReportDetailByIdByExternalId(j,J,Y.id,{snapshot:!0,forceRefresh:K,admission:Q});return M?Z(C,E,{report:M},200):Z(C,E,{error:{message:"Report not found"}},404)})},[oe.search]:async(O,E,C,Y,j)=>{if(de===null)return Z(C,E,{error:{message:"Unknown endpoint"}},404);let J=O.searchParams.get(Re.searchQuery),K=sn(O.searchParams.get(Re.searchCombine));if(J===null||K===null)return Z(C,E,{error:{message:"Invalid search request"}},400);let z=lo(O.searchParams,r.searchFilterSourceTypes);if(!z.ok)return Z(C,E,{error:{message:"Invalid search filters",reason:z.reason}},400);let Q=Wa(J,K,z.filters);if(!Q.ok)return Z(C,E,{error:{message:"Invalid search query",reason:Q.reason}},400);let{criteria:M}=Q,ae=M.plan===null?[]:Vt(M.plan),be=await r.getUserIdByExternalId(Y.id);if(!be)return Z(C,E,Jr([],ae),200);let Ee=await de.admit(be,C.signal);if("refusal"in Ee)return Mr(C,E,Ee.refusal);try{let St=await r.searchDailyReports(j,be,M);return Z(C,E,Jr(St,ae),200)}finally{Ee.release()}},[oe.reports]:async(O,E,C,Y,j)=>{if(ge===null)return Z(C,E,{error:{message:"Unknown endpoint"}},404);let J=ln(O.searchParams.get(Re.reportIds));if(J===null)return Z(C,E,{error:{message:"Invalid ids"}},400);let K=await r.getUserIdByExternalId(Y.id);if(!K)return Z(C,E,{reports:[]},200);let z=await ge.admit(K,C.signal);if("refusal"in z)return Mr(C,E,z.refusal);try{let Q=await r.getDailyReportDetailsByIdsByExternalId(j,J,Y.id);return Z(C,E,{reports:Q},200)}finally{z.release()}},[oe.searchMarks]:async(O,E,C,Y,j)=>{if(G===null)return Xe(E,{error:{message:"Unknown endpoint"}},404);let J=O.searchParams.get(Re.searchQuery),K=sn(O.searchParams.get(Re.searchCombine));if(J===null||K===null)return Xe(E,{error:{message:"Invalid search request"}},400);let z=_r(J,K);if(!z.ok)return Xe(E,{error:{message:"Invalid search query",reason:z.reason}},400);let Q=ln(O.searchParams.get(Re.reportIds));if(Q===null)return Xe(E,{error:{message:"Invalid ids"}},400);let M=await r.getUserIdByExternalId(Y.id);if(!M)return Xe(E,{wordsDigest:nr(Vt(z.plan)),reports:[]},200);let ae=await G.admit(M,C.signal);if("refusal"in ae)return C.signal.aborted?di(E):Cn(Xe(E,{error:{message:ae.refusal.message}},ae.refusal.status),ae.refusal.headers);try{let be=await r.markDailyReportSearchHits(j,M,z.plan,Q,{signal:C.signal});return C.signal.throwIfAborted(),Xe(E,be,200)}catch(be){if(C.signal.aborted&&be===C.signal.reason)return di(E);throw be}finally{ae.release()}},[oe.searchFacets]:async(O,E,C,Y,j)=>{if(re===null)return Z(C,E,{error:{message:"Unknown endpoint"}},404);let J=await r.getUserIdByExternalId(Y.id);if(!J)return Z(C,E,{sourceTypes:[],authors:[],customers:[]},200);let K=await re.admit(J,C.signal);if("refusal"in K)return Mr(C,E,K.refusal);try{let z=await r.listDailyReportSearchFacets(j,J);return Z(C,E,z,200)}finally{K.release()}}},se=async({request:O,params:E})=>{let{user:C,cookie:Y}=await t(O,{failureRedirect:null}),j=Y??null;if(!C)return Z(O,j,{error:{message:"Unauthorized"}},401);let J=E.endpoint;if(!cn(J))return Z(O,j,{error:{message:"Unknown endpoint"}},404);let K=go[ot[J].body];if(!K.includes(O.method)){let Q=Z(O,j,{error:{message:"Method not allowed"}},405);return Q.headers.set("Allow",K.join(", ")),Q}let z=ue();try{let Q=new URL(O.url),M=await H(O),ae=await ee[J](Q,j,O,C,M);return ot[J].body==="json"&&s.debug(`${ae.status} endpoint=${J} etag_match=${ae.status===304}`),ae}catch(Q){let M=ue()-z,ae=Q instanceof Error?Q:new Error(String(Q));return s.error(`500 endpoint=${J} elapsed=${M}ms name=${ae.name} code=${"code"in ae?ae.code:"N/A"} message=${ae.message}`,ae),Z(O,j,{error:{message:"Internal Server Error"}},500)}},me=So(R),fe=et({reason:"rate_limit",limitPerWindow:Pu,windowMs:mi,logger:R,windowFields:()=>"route=action"}),Ge=async(O,E,C,Y,j)=>{let{clientTempId:J}=O;if(O.intent==="create"){let M=await r.createDailyReport(E,O.businessDate,J);return j(O,M.reportHubId,{report:M})}let{reportHubId:K,businessDate:z}=O,Q=async(M,ae)=>{try{let be=await ae(M.value);return j(M,K,{updatedStatus:{isStarred:be.isStarred,isRead:be.isRead},operationTimestamp:M.operationTimestamp})}catch(be){if(be instanceof Error&&be.message==="Not Found")return Y({error:"Report not found"},{status:404});throw be}};switch(O.intent){case"update":try{return await r.updateDailyReport(K,E,O.changes,J),j(O,K,{})}catch(M){if(M instanceof Error){if(M.message==="Unauthorized")return Y({error:"Unauthorized"},{status:403});if(M.message==="Not Found")return Y({error:"Report not found"},{status:404})}throw M}case"publish":try{let M=await r.publishDailyReport(K,E,J);return j(O,K,{report:M})}catch(M){if(M instanceof Error){if(M.message==="Unauthorized")return Y({error:"Unauthorized"},{status:403});if(M.message==="Not Found")return Y({error:"Report not found"},{status:404})}throw M}case"delete":try{return await r.deleteDailyReport(K,E,J),j(O,K,{})}catch(M){if(M instanceof Error){if(M.message==="Unauthorized")return Y({error:"Unauthorized"},{status:403});if(M.message==="Not Found")return Y({error:"Report not found"},{status:404})}throw M}case"toggleStar":return await Q(O,M=>r.setStarStatus(C,E,K,z,M,J));case"toggleRead":return await Q(O,M=>r.setReadStatus(C,E,K,z,M,J));case"addComment":try{let M=await r.addComment(C,E,K,O.content,z,J);return j(O,K,{newComment:M})}catch(M){if(M instanceof Error){if(M.message==="Not Found")return Y({error:"Report not found"},{status:404});if(M.message.startsWith("Comments are restricted"))return Y({error:"Comments are restricted for this report"},{status:403})}throw M}case"deleteComment":try{return await r.deleteComment(C,E,K,O.commentId,z,J),j(O,K,{deletedCommentId:O.commentId})}catch(M){if(M instanceof Error){if(M.message==="Unauthorized")return Y({error:"Unauthorized"},{status:403});if(M.message==="Not Found")return Y({error:"Comment not found"},{status:404})}throw M}}},ne=async({request:O,params:E})=>{let{user:C,cookie:Y}=await t(O,{failureRedirect:null}),j=(z,Q)=>ci(z,{...Q,setCookie:Y}),J=(z,Q,M)=>ci(Cu(z,Q,M),{setCookie:Y});if(!C)return j({error:"Unauthorized"},{status:401});let K=ue();try{if(E.endpoint!==oe.action)return j({error:"Unknown endpoint"},{status:404});let z=fe.spend(C.id,"action");if(z!==null)return j({error:z.message},{status:z.status,headers:z.headers});let Q=await Ro(O,l);if("refusal"in Q){let{refusal:Ee}=Q;return Ee.status===413&&me(Ee.measuredBy),j({error:Ee.error},{status:Ee.status})}let{command:M}=Q;if(M.intent==="clearCache"&&!e.enableDevCacheClear)return j({error:"Invalid intent"},{status:400});let ae=await r.getUserIdByExternalId(C.id);if(!ae)return j({error:"User not found"},{status:404});let be=await H(O);return M.intent==="clearCache"?(await r.clearCache(),j({status:"OK",intent:"clearCache"})):await Ge(M,ae,be,j,J)}catch(z){if(z instanceof Response)throw z;let Q=ue()-K,M=z instanceof Error?z:new Error(String(z));return s.error(`500 action elapsed=${Q}ms name=${M.name} message=${M.message}`,M),j({error:"Internal Server Error"},{status:500})}},Ne=li({authenticate:t,service:r,resolveViewerScope:H,redis:o,sseReader:a,streamKey:i,streamSlots:P,logger:m}),Fe=ha({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:H,logger:S}),we=wo(f),Ve=(O,E)=>async C=>{let Y=Io(C.request)?O.frameworkDataRefusal(C):null;if(Y!==null)throw Y;return _o(C.request,O)?(we(O.route,C.request),O.crossSiteRejection()):E(C)};return{index:{loader:ce},api:{loader:Ve(wu,se),action:Ve(xu,ne)},sse:{loader:Ve(ii,Ne)},attachment:{loader:Ve(ya,Fe)}}}var Pt=require("@aiquants/mssql"),g=require("drizzle-orm");var yt=require("drizzle-orm"),Nr=(e,t,r,n)=>{if(r.length===0)return;let{hub:o,hubLabel:a,label:i}=e,l=n==="author-or-authorless"?yt.sql`${o.userId} = ${t} OR ${o.userId} IS NULL`:yt.sql`${o.userId} = ${t}`,c=yt.sql.join(r.map(s=>yt.sql`${s}`),yt.sql`, `);return yt.sql`(${l} OR NOT EXISTS (SELECT 1 FROM ${a} INNER JOIN ${i} ON ${i.id} = ${a.labelId} WHERE ${a.hubId} = ${o.id} AND ${i.name} IN (${c})))`};var Uu=["tables","externalSourceTexts","concurrency","rateLimitPerMinute"],$u=["document","comment"],Bu=["hubId","searchText","sourceDigest","normalizerVersion","indexedAt","rowVersion","authorName","customerName"],Vu=["hubId","ordinal","authorUserId","commentText"],Pn=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},yi=(e,t,r)=>{for(let n of Object.keys(t))if(!r.includes(n))throw qr(e,n,r)},hi=(e,t,r)=>{if(typeof t!="object"||t===null)throw le(e,"a table object",t);let n=t;for(let o of r)if(typeof n[o]!="object"||n[o]===null)throw le(`${e}.${o}`,"a column",n[o])},fi=(e,t)=>{if(!Pn(e))throw le("search","a plain object",e);yi("search key",e,Uu);let{tables:r}=e;if(!Pn(r))throw le("search.tables","a plain object with document and comment",r);yi("search.tables key",r,$u),hi("search.tables.document",r.document,Bu),hi("search.tables.comment",r.comment,Vu);let n=new Map;if(e.externalSourceTexts!==void 0){if(!Pn(e.externalSourceTexts))throw le("search.externalSourceTexts","a plain object",e.externalSourceTexts);for(let[o,a]of Object.entries(e.externalSourceTexts)){if(!t.includes(o))throw qr("search.externalSourceTexts key",o,t);if(typeof a!="function")throw le(`search.externalSourceTexts.${o}`,"a function",a);n.set(o,a)}}return{tables:r,externalSourceTexts:n,concurrency:te("search.concurrency",e.concurrency,1),rateLimitPerMinute:te("search.rateLimitPerMinute",e.rateLimitPerMinute,1)}};var lt=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},ht=(e,t)=>{let r=typeof e=="string"?Ue(e):typeof e=="number"&&At(e)?e:null;if(r===null)throw new Error(`[daily-report] search: column ${t} holds no positive id`);return r},ft=(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 Yu=/[[%_]/gu,qu=e=>e.replace(Yu,t=>`[${t}]`),Ri=e=>`%${qu(e)}%`;var Be=Object.freeze({reportHubId:"report_hub_id",businessDate:"business_date",sourceType:"source_type"}),Rt=Object.freeze({reportHubId:"report_hub_id",matchedSets:"matched_sets"}),Wt=Object.freeze({value:"value"}),Te=Object.freeze({hubId:"hub_id",sourceDigest:"source_digest",normalizerVersion:"normalizer_version"}),B=e=>U.sql`${U.sql.identifier(e.name)}`,jt=e=>U.sql.join(e.map(t=>U.sql`${t}`),U.sql`, `),Si=(e,t)=>U.sql`SELECT ${B(e.id)} AS ${U.sql.identifier(Te.hubId)} FROM ${e} WITH (UPDLOCK, ROWLOCK) WHERE ${e.id} IN (${jt(t)}) ORDER BY ${e.id}`,ju=(e,t,r)=>{let{hub:n}=e,{document:o,comment:a}=e.search,i=t.alternatives.map(m=>Ri(m.text)),l=U.sql.join(i.map(m=>U.sql`${o.searchText} LIKE ${m}`),U.sql` OR `),c=U.sql.join(i.map(m=>U.sql`${a.commentText} LIKE ${m}`),U.sql` OR `),s=Ut(n.sourceType,r.scope.commentable),y=s===void 0?U.sql``:U.sql` AND (${s} OR ${a.authorUserId} = ${r.userId})`;return U.sql`((${l}) OR EXISTS (SELECT 1 FROM ${a} WHERE ${a.hubId} = ${n.id} AND (${c})${y}))`},gi=(e,t,r)=>U.sql`(${U.sql.join(t.words.map(n=>ju(e,n,r)),U.sql` AND `)})`,Mn=(e,t,r,n)=>{let{hub:o}=e,a=[U.sql`${o.deletedAt} IS NULL`],i=Nr(e,t.userId,r,"author");i!==void 0&&a.push(i);let l=Ut(o.sourceType,t.scope.visible);return l!==void 0&&a.push(l),n!==void 0&&a.push(U.sql`${o.id} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${JSON.stringify(n)}))`),a},Wu=(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 (${jt([...t.sourceTypes])})`)}return t.authors!==null&&o.push(U.sql`${n.authorName} IN (${jt(t.authors)})`),t.customers!==null&&o.push(U.sql`${n.customerName} IN (${jt(t.customers)})`),o},bi=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,{plan:l}=t,c=[...Mn(e,r,n,o),...Wu(e,t.filters)];if(l!==null){let s=l.combine==="intersection"?U.sql` AND `:U.sql` OR `;c.push(U.sql`(${U.sql.join(l.sets.map(y=>gi(e,y,r)),s)})`)}return U.sql`SELECT ${B(a.id)} AS ${U.sql.identifier(Be.reportHubId)}, CONVERT(char(10), ${B(a.businessDate)}, 23) AS ${U.sql.identifier(Be.businessDate)}, ${B(a.sourceType)} AS ${U.sql.identifier(Be.sourceType)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${U.sql.join(c,U.sql` AND `)} ORDER BY ${a.businessDate} DESC, ${a.id} DESC`},Di=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,l=U.sql.join(t.sets.map((c,s)=>U.sql`(CASE WHEN ${gi(e,c,r)} THEN ${2**s} ELSE 0 END)`),U.sql` + `);return U.sql`SELECT ${B(a.id)} AS ${U.sql.identifier(Rt.reportHubId)}, ${l} AS ${U.sql.identifier(Rt.matchedSets)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${U.sql.join(Mn(e,r,n,o),U.sql` AND `)}`},Ai=(e,t,r,n)=>{let{hub:o}=e,{document:a}=e.search,i=a[t],l=[...Mn(e,r,n),U.sql`${i} IS NOT NULL`];return U.sql`SELECT ${i} AS ${U.sql.identifier(Wt.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}`},Ti=(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 U.sql`MERGE ${n} WITH (HOLDLOCK) AS t USING (SELECT * FROM OPENJSON(${a}) WITH (${B(n.hubId)} bigint, ${B(n.searchText)} nvarchar(max), ${B(n.sourceDigest)} char(64), ${B(n.normalizerVersion)} varchar(64), ${B(n.authorName)} nvarchar(max), ${B(n.customerName)} nvarchar(max))) AS s ON t.${B(n.hubId)} = s.${B(n.hubId)}
|
|
8
|
+
WHEN MATCHED THEN UPDATE SET t.${B(n.searchText)} = s.${B(n.searchText)}, t.${B(n.sourceDigest)} = CONVERT(binary(32), s.${B(n.sourceDigest)}, 2), t.${B(n.normalizerVersion)} = s.${B(n.normalizerVersion)}, t.${B(n.authorName)} = s.${B(n.authorName)}, t.${B(n.customerName)} = s.${B(n.customerName)}, t.${B(n.indexedAt)} = SYSUTCDATETIME()
|
|
9
|
+
WHEN NOT MATCHED THEN INSERT (${B(n.hubId)}, ${B(n.searchText)}, ${B(n.sourceDigest)}, ${B(n.normalizerVersion)}, ${B(n.authorName)}, ${B(n.customerName)}) VALUES (s.${B(n.hubId)}, s.${B(n.searchText)}, CONVERT(binary(32), s.${B(n.sourceDigest)}, 2), s.${B(n.normalizerVersion)}, s.${B(n.authorName)}, s.${B(n.customerName)});
|
|
10
10
|
DELETE FROM ${o} WHERE ${o.hubId} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${l}));
|
|
11
|
-
INSERT INTO ${o} (${G(o.hubId)}, ${G(o.ordinal)}, ${G(o.authorUserId)}, ${G(o.commentText)}) SELECT ${G(o.hubId)}, ${G(o.ordinal)}, ${G(o.authorUserId)}, ${G(o.commentText)} FROM OPENJSON(${i}) WITH (${G(o.hubId)} bigint, ${G(o.ordinal)} int, ${G(o.authorUserId)} bigint, ${G(o.commentText)} nvarchar(max));`},ri=(e,t)=>q.sql`SELECT ${G(e.hubId)} AS ${q.sql.identifier(Te.hubId)}, LOWER(CONVERT(char(64), ${G(e.sourceDigest)}, 2)) AS ${q.sql.identifier(Te.sourceDigest)}, ${G(e.normalizerVersion)} AS ${q.sql.identifier(Te.normalizerVersion)} FROM ${e} WHERE ${e.hubId} IN (${Rn(t)})`,ni=(e,t,r)=>q.sql`SELECT TOP (${r}) ${G(e.id)} AS ${q.sql.identifier(Te.hubId)} FROM ${e} WHERE ${e.id} > ${t} ORDER BY ${e.id}`;var oi=e=>({search:async(t,r)=>Ne(r.scope.visible)?[]:ut(await t.execute(Za(e.tables,r.plan,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=Et(o[Be.sourceType],Be.sourceType);if(a===null)throw new Error(`[daily-report] search: column ${Be.sourceType} is null`);return{reportHubId:dt(o[Be.reportHubId],Be.reportHubId),businessDate:Et(o[Be.businessDate],Be.businessDate),sourceType:a}}),matchedSets:async(t,r)=>{if(Ne(r.scope.visible))return new Map;let n=ut(await t.execute(ei(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[mt.matchedSets];if(!(typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&l<=o))throw new Error(`[daily-report] search: column ${mt.matchedSets} holds no mask of ${r.plan.sets.length} keywords`);a.set(dt(i[mt.reportHubId],mt.reportHubId),l)}return a}});var qe=require("@aiquants/mssql"),bn=require("drizzle-orm");var ai=require("crypto");var Sn=e=>e===null?"n;":`s${e.length}:${e}`,hu=e=>{let t=(0,ai.createHash)("sha256");t.update(`F${e.fields.length};`);for(let[r,n]of e.fields)t.update(Sn(r)+Sn(n));return t.update(`C${e.comments.length};`),e.comments.forEach((r,n)=>{t.update(`${n};${r.authorUserId===null?"n":`i${r.authorUserId}`};${Sn(r.text)}`)}),t.digest("hex")},gn=e=>{let t=0,r=[];for(let[,o]of e.fields){if(o===null)continue;let a=hr(o);t+=a.forcedCuts,r.push(a.text)}let n=[];for(let o of e.comments){let a=hr(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:ba(r),comments:n,sourceDigest:hu(e),forcedCuts:t}};var ii=e=>{let t=async(c,s)=>{let h=[];for(let m of(0,qe.chunk)(s,qe.MAX_IN_LIST))for(let b of ut(await c.execute(Ja(e.hub,m))))h.push(dt(b[Te.hubId],Te.hubId));return h},r=async(c,s)=>{for(let h of(0,qe.chunk)(s,qe.MAX_IN_LIST))await c.execute(ti(e.tables,h,e.normalizerVersion))},n=async(c,s)=>{let h=new Map;for(let m of(0,qe.chunk)(s,qe.MAX_IN_LIST))for(let b of ut(await c.execute(ri(e.tables.document,m))))h.set(dt(b[Te.hubId],Te.hubId),{sourceDigest:Et(b[Te.sourceDigest],Te.sourceDigest),normalizerVersion:Et(b[Te.normalizerVersion],Te.normalizerVersion)});return h},o=async(c,s,h)=>ut(await c.execute(ni(e.hub,s,h))).map(m=>dt(m[Te.hubId],Te.hubId)),a=async(c,s)=>{let h=await t(c,[...new Set(s)].sort((b,f)=>b-f));if(h.length===0)return;let m=(await e.loadSources(c,h)).map(gn);m.length>0&&await r(c,m)},i=c=>e.inTransaction(async s=>{await s.execute(bn.sql`SET DEADLOCK_PRIORITY LOW`);let h=await t(s,c),m=await n(s,h),b=(await e.loadSources(s,h)).map(gn),f=b.filter(g=>{let S=m.get(g.hubId);return S===void 0||S.sourceDigest!==g.sourceDigest||S.normalizerVersion!==e.normalizerVersion});return f.length>0&&await r(s,f),await s.execute(bn.sql`SET DEADLOCK_PRIORITY NORMAL`),{scanned:b.length,written:f.length,forcedCuts:b.reduce((g,S)=>g+S.forcedCuts,0)}});return{writeHubs:a,reconcile:async(c,s)=>{let{batchSize:h,hubIds:m,signal:b,onProgress:f}=s;ne("reconcileSearchIndex: batchSize",h,1,qe.MAX_IN_LIST);let g=ce(),S=m===void 0?null:(0,qe.chunk)([...new Set(m)].sort((N,H)=>N-H),h),T={scanned:0,written:0,skipped:0,forcedCuts:0,lastHubId:null};for(let N=0;;N++){b?.throwIfAborted();let H=S===null?await o(c,T.lastHubId===null?0:T.lastHubId,h):S[N];if(H===void 0||H.length===0)break;let W=await i(H);T={scanned:T.scanned+W.scanned,written:T.written+W.written,skipped:T.skipped+W.scanned-W.written,forcedCuts:T.forcedCuts+W.forcedCuts,lastHubId:H[H.length-1]},f?.(T)}return{...T,elapsedMs:ce()-g}}}};var si=255,fu=(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},Ru=(e,t,r=yr)=>{let n=new Map;for(let l of t){if(l.text.length===0)throw new Error("[daily-report] search marks: an alternative has an empty text");let c=n.get(l.text);(c===void 0||l.tier<c)&&n.set(l.text,l.tier)}let o=[];if(n.size===0)return o;let a=fa(e),i=l=>a.rawIndex===null?l:a.rawIndex[l];return mn(a.text,(l,c)=>{let s=dn(l,r).text,h=null;for(let[m,b]of n){let f=s.indexOf(m);if(!(f<0))for(h===null&&(h=fu(ga(l,un(l,r)),s));f>=0;)o.push({start:i(c+h.start[f]),end:i(c+h.end[f+m.length-1]-1)+1,tier:b}),f=s.indexOf(m,f+1)}}),o},Su=(e,t,r=yr)=>{let n=Ru(e,t,r),o=[];if(n.length===0)return o;let a=new Uint8Array(e.length).fill(si);for(let l of n)for(let c=l.start;c<l.end;c++)l.tier<a[c]&&(a[c]=l.tier);let i=0;for(let l=1;l<=e.length;l++)l<e.length&&a[l]===a[i]||(a[i]!==si&&o.push(i,l,a[i]),i=l);return o},li=(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)},ci=(e,t)=>{let r=t.flatMap(a=>a.alternatives),n={},o=(a,i)=>{typeof i!="string"||i.length===0||(n[a]={fingerprint:vr(i),ranges:Su(i,r)})};for(let a of kn)o(ze.field(a),e[a]);e.interviewers.forEach((a,i)=>{o(ze.interviewer(i,"name"),a.name),o(ze.interviewer(i,"affiliation"),a.affiliation)}),e.attachments.forEach((a,i)=>{o(ze.attachment(i),a.fileName)}),e.externalComments.forEach((a,i)=>{o(ze.comment(Lr(i),"author"),a.name),o(ze.comment(Lr(i),"content"),a.text)});for(let a of e.postedComments)o(ze.comment(a.id,"author"),a.userName),o(ze.comment(a.id,"content"),a.content);return n};var Ze=e=>(0,p.getColumns)(e),ui=qt([]),Ie=(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}`},bu=e=>{let{length:t}=e;if(t===void 0)throw le("tables.hub.title","a character column with a declared length",t);return ne("tables.hub.title.length",t,1)},di=e=>e===""?null:e,Du=Object.freeze([]),Dn=(e,t,r)=>{let n=e.get(t);n?n.push(r):e.set(t,[r])},Ar=(e,t)=>e.get(t)??Du,mi=(e,t)=>[e,t].filter(r=>typeof r=="string"&&r.length>0).join(pr);function Tr(e){let{db:t,tables:r,userTable:n,resolveUserId:o,encodeUserId:a,redis:i,cache:l,epochs:c}=e,{hub:s,internal:h,comment:m,label:b,hubLabel:f,userStatus:g}=r,S=e.externalSources??[],T=e.draftLabelNames&&e.draftLabelNames.length>0?e.draftLabelNames:[e.draftLabelName??"\u4E0B\u66F8\u304D"],N=T[0]??"\u4E0B\u66F8\u304D",H=fe(e.logger,1,"Service");sr(e);let W=Qo(e.attachments),x=bu(s.title),_=u=>(0,It.runWithTransactionRetry)(d=>t.transaction(y=>d(()=>u(y))),e.transactionRetry),B=e.search===void 0?null:Ga(e.search,S.map(u=>u.sourceType)),U=B===null?null:oi({tables:{hub:s,hubLabel:f,label:b,search:B.tables},draftLabelNames:T}),$=null,de=()=>{if(B===null)return null;if($===null){let u=B.externalSourceTexts;$=ii({hub:s,tables:B.tables,loadSources:(d,y)=>zi(d,y,u),inTransaction:_,normalizerVersion:Da()})}return $},be=e.idsTtlMs??18e4,me="daily-report:ids:epoch",K=e.businessDateTtlMs??3e5,Z="daily-report:date-epoch:",oe="daily-report:detail-epoch:",ae=`${e.streamKey??"daily-report:sse-stream"}:v2`,Se=e.streamMaxLen??1e4,ie=u=>c.incrementEpoch(u),_e=u=>Ht(s.sourceType,u),we=async(u,d)=>{let y=await i?.getClient();if(!y){H.warn(`[SSE] Redis client unavailable (${d})`);return}let R=JSON.stringify(u),A=Buffer.byteLength(R);if(A>6356992){H.warn(`[SSE] Event too large (${d}): ${A} bytes > ${6356992}; not published`);return}let E=ce();try{await y.xAdd(ae,"*",{data:R},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:Se}});let w=ce()-E;w>1e3&&H.warn(`[SSE] Slow publish (${d}): ${w}ms`)}catch(w){H.error(`[SSE] Redis publish failed (${d}):`,w)}},et=async()=>{try{let u=await i?.getClient();if(u===void 0)return null;let[d]=await u.xRevRange(ae,"+","-",{COUNT:1});return d===void 0?null:d.id}catch(u){return H.error("SSE stream anchor read failed",u),null}},ve=u=>u==null||u===""?null:/^\d+$/.test(u)?a(Number(u)):u,M=()=>{let u={};for(let d of S)u[`ext_${d.sourceType}`]=Ze(d.table);return u},O=u=>{let d=u;for(let y of S)d=d.leftJoin(y.table,(0,p.and)((0,p.eq)(s.sourceType,y.sourceType),(0,p.eq)(s.sourceIdNum,y.idColumn)));return d},I=u=>{let{hub:d,internal:y}=u,R=d.summary,A=[],E=null,w=null,v=null,C=null,V=null,k=null,te=[],Y=S.find(pe=>pe.sourceType===d.sourceType),re=Y?u[`ext_${Y.sourceType}`]:void 0;if(Y&&re){let pe=Y.mapRow(re);pe.content!==void 0&&(R=pe.content),pe.employeeName!==void 0&&(k=pe.employeeName),pe.category!==void 0&&(E=pe.category),pe.creationCategory!==void 0&&(w=pe.creationCategory),pe.visitTimeFrom!==void 0&&(v=pe.visitTimeFrom),pe.visitTimeTo!==void 0&&(C=pe.visitTimeTo),pe.customerName!==void 0&&(V=pe.customerName),pe.interviewers!==void 0&&(A=pe.interviewers),pe.externalComments!==void 0&&(te=pe.externalComments)}else d.sourceType==="Internal"&&y&&(R=y.body);return{content:R,author:u.creatorName??ve(d.createdBy)??"",employeeName:k??u.creatorName??ve(d.createdBy),updatedBy:ve(d.updatedBy),category:E,creationCategory:w,visitTimeFrom:v,visitTimeTo:C,customerName:V,interviewers:A,externalComments:te}},F=(u,d,y)=>{let{hub:R}=d,A=I(d),E=(d.labels??[]).map(k=>({id:k.id,name:k.name,color:k.color})),w=d.postedCommentRows??[],v=Oe(u.commentable,R.sourceType),C=A.creationCategory?T.includes(A.creationCategory):!1,V=ge?.[0]??null;return C&&V&&!E.some(k=>k.id===V)&&E.push({id:V,name:N,color:null}),{reportHubId:R.id,date:Ie(R.businessDate,"YYYY-MM-DD"),author:A.author,userId:R.userId?a(R.userId):"",sourceType:R.sourceType??"Internal",createdAt:Ie(R.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:Ie(R.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:A.updatedBy,employeeName:A.employeeName,category:A.category,creationCategory:A.creationCategory,visitTimeFrom:A.visitTimeFrom,visitTimeTo:A.visitTimeTo,customerName:A.customerName,interviewers:A.interviewers,subject:R.title,content:A.content,externalComments:v?A.externalComments:[],isRead:d.isRead??!1,isStarred:d.isStarred??!1,labels:E,postedComments:w.filter(k=>Wa({authorUserId:k.userId},R.sourceType,y??null,u)).map(k=>({...k,userId:a(k.userId),isMine:y?k.userId===y:!1})),attachments:d.attachments}},z=async(u,d)=>{let y=(0,p.aliasedTable)(f,"draft_label"),R=await at();return(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).from(s).leftJoin(y,(0,p.and)((0,p.eq)(y.hubId,s.id),(0,p.inArray)(y.labelId,R))).where((0,p.and)((0,p.isNull)(s.deletedAt),(0,p.or)((0,p.eq)(s.userId,d),(0,p.isNull)(s.userId),(0,p.isNull)(y.hubId)),_e(u.visible))).orderBy((0,p.desc)(s.businessDate),(0,p.desc)(s.id))).map(E=>({...E,businessDate:Ie(E.businessDate,"YYYY-MM-DD")}))},X=async(u,d,y)=>{let R=await J(d);if(!R)return[];if(Ne(u.visible))return[];let A=(0,p.aliasedTable)(f,"draft_label"),E=await at();return(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).top(y).from(s).leftJoin(A,(0,p.and)((0,p.eq)(A.hubId,s.id),(0,p.inArray)(A.labelId,E))).where((0,p.and)((0,p.isNull)(s.deletedAt),(0,p.or)((0,p.eq)(s.userId,R),(0,p.isNull)(s.userId),(0,p.isNull)(A.hubId)),_e(u.visible))).orderBy((0,p.desc)(s.businessDate),(0,p.desc)(s.id))).map(v=>({...v,businessDate:Ie(v.businessDate,"YYYY-MM-DD")}))},Q=async(u,d)=>{let y=await O(t.select({hub:Ze(s),internal:Ze(h),creatorName:n.displayName,...M()}).from(s)).leftJoin(h,(0,p.eq)(s.id,h.hubId)).leftJoin(n,(0,p.eq)(s.userId,n.id)).where((0,p.and)((0,p.eq)(s.businessDate,p.sql`${d}`),(0,p.isNull)(s.deletedAt),_e(u.visible))).orderBy((0,p.desc)(s.id)),R=await Ft(y.map(A=>A.hub.id));return y.map(A=>F(u,{...A,attachments:R.get(A.hub.id)??[]}))},j=new Map,J=async u=>{if(!e.disableUserIdCache&&j.has(u))return j.get(u)??null;let d=await o(u);return d!==null&&!e.disableUserIdCache&&j.set(u,d),d},L=async(u,d,{forceRefresh:y=!1,snapshot:R=!1,ttlMsOverride:A,onFetchStart:E,admission:w}={})=>{let v=await J(d);if(!v)return{items:[],streamAnchor:null,snapshot:ui};if(Ne(u.visible))return{items:[],streamAnchor:await et(),snapshot:ui};let C=wa(v,Ut(u)),[V]=await l.getOrFetch({cacheKey:C,fetcher:async()=>{let k=await et(),te=await z(u,v);if(!Pn(te)){H.warn("ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)");let Y=[...te].sort(Wt);return[{items:Y,streamAnchor:k,snapshot:qt(Y)}]}return[{items:te,streamAnchor:k,snapshot:qt(te)}]},onFetchStart:E,forceRefresh:y,snapshot:R,admission:w,ttlMsOverride:A??be,epochKey:me,refreshAheadRatio:.5});if(V===void 0)throw new Error("[DailyReportService] ids cache returned no record");return V},se=(u,d,{forceRefresh:y=!1,snapshot:R=!1,ttlMsOverride:A}={})=>{let E=Pe(d);return E?Ne(u.visible)?Promise.resolve([]):l.getOrFetch({cacheKey:xa(E,Ut(u)),fetcher:()=>Q(u,E),forceRefresh:y,snapshot:R,ttlMsOverride:A??K}):Promise.resolve([])},ge=null,We=async()=>(ge!==null||(ge=(await t.select({id:b.id}).from(b).where((0,p.inArray)(b.name,T)).orderBy(b.id)).map(d=>d.id)),ge),at=async()=>{let u=await We();return u.length>0?u:[-1]},Er=async()=>{let u=await We();if(u.length===0)return null;let[d]=await t.select({id:b.id}).top(1).from(b).where((0,p.eq)(b.name,N));return d?.id??u[0]},Mi=(u,d)=>d!=null?"absent":u!=null?"present":"unknown",Ft=async u=>{let d=new Map,y=r.attachment;if(u.length===0||!y||W===null)return d;let R=W.idCodec,A=W.thumbnails!==null,E=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,p.inArray)(y.hubId,u)).orderBy((0,p.asc)(y.createdAt),(0,p.asc)(y.id));for(let w of E){let v=w.fileType?String(w.fileType):null,C=w.fileSize!=null?Number(w.fileSize):null,V=Mi(w.objectCheckedAt,w.objectMissingAt),k={id:R.encode(Number(w.id)),fileName:String(w.fileName),fileType:v,fileSize:C,createdAt:Ie(w.createdAt,"YYYY-MM-DD HH:mm:ss"),state:V,hasThumbnail:A&&V!=="absent"&&ar({fileType:v,fileSize:C},W.maxBytes)},te=d.get(Number(w.hubId));te?te.push(k):d.set(Number(w.hubId),[k])}return d},Li=async(u,d,y)=>{let R=r.attachment;if(!R||Ne(u.visible))return null;let A=await at(),E=(0,p.aliasedTable)(f,"draft_label");return(await t.select({fileName:R.fileName,filePath:R.filePath,fileType:R.fileType,fileSize:R.fileSize}).top(1).from(R).innerJoin(s,(0,p.eq)(s.id,R.hubId)).leftJoin(E,(0,p.and)((0,p.eq)(E.hubId,s.id),(0,p.inArray)(E.labelId,A))).where((0,p.and)((0,p.eq)(R.id,d),(0,p.isNull)(s.deletedAt),(0,p.or)((0,p.eq)(s.userId,y),(0,p.isNull)(E.hubId)),_e(u.visible))))[0]??null},Oi=async u=>{let d=r.attachment;if(!d)return;let y=new Date;try{await t.update(d).set({objectCheckedAt:y,objectMissingAt:y,updatedAt:y}).where((0,p.eq)(d.id,u))}catch(R){H.error("markAttachmentMissing failed",R)}},Ni=async u=>{let d=r.attachment;if(!d)return;let y=new Date;try{await t.update(d).set({objectCheckedAt:y,objectMissingAt:null,updatedAt:y}).where((0,p.eq)(d.id,u))}catch(R){H.error("markAttachmentPresent failed",R)}},Ir=async(u,d,y)=>{let R=await at(),A=(0,p.aliasedTable)(f,"draft_label"),E=await O(t.select({hub:Ze(s),internal:Ze(h),isRead:g.isRead,isStarred:g.isStarred,creatorName:n.displayName,...M()}).from(s)).leftJoin(h,(0,p.eq)(s.id,h.hubId)).leftJoin(g,(0,p.and)((0,p.eq)(s.id,g.hubId),(0,p.eq)(g.userId,d))).leftJoin(A,(0,p.and)((0,p.eq)(A.hubId,s.id),(0,p.inArray)(A.labelId,R))).leftJoin(n,(0,p.eq)(s.userId,n.id)).where((0,p.and)(y,(0,p.isNull)(s.deletedAt),(0,p.or)((0,p.eq)(s.userId,d),(0,p.isNull)(A.hubId)),_e(u.visible))).orderBy((0,p.desc)(s.id));if(E.length===0)return[];let w=E.map(Y=>Y.hub.id),v=await t.select({hubId:f.hubId,id:b.id,name:b.name,color:b.color}).from(f).innerJoin(b,(0,p.eq)(f.labelId,b.id)).where((0,p.inArray)(f.hubId,w)),C=await t.select({hubId:m.hubId,id:m.id,body:m.body,createdAt:m.createdAt,userId:m.userId,userName:n.displayName}).from(m).leftJoin(n,(0,p.eq)(m.userId,n.id)).where((0,p.inArray)(m.hubId,w)).orderBy((0,p.asc)(m.createdAt)),V=await Ft(w),k=new Map,te=new Map;for(let Y of v){let re=k.get(Y.hubId);re||(re=[],k.set(Y.hubId,re)),re.push({id:Y.id,name:Y.name,color:Y.color})}for(let Y of C){let re=te.get(Y.hubId);re||(re=[],te.set(Y.hubId,re)),re.push({id:Y.id,content:Y.body,createdAt:Ie(Y.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:Y.userId,userName:Y.userName||""})}return E.map(Y=>{let re=Y.hub.id;return F(u,{...Y,attachments:V.get(re)??[],labels:k.get(re)||[],postedCommentRows:te.get(re)||[]},d)})},vi=async(u,d,y,{forceRefresh:R=!1,snapshot:A=!1,ttlMsOverride:E,admission:w}={})=>{let v=await J(y);if(!v)return[];let C=Pe(d);if(!C)return[];if(Ne(u.visible))return[];let V=Ca(C,v,Ut(u));return l.getOrFetch({cacheKey:V,fetcher:()=>Ir(u,v,(0,p.eq)(s.businessDate,p.sql`${C}`)),forceRefresh:R,snapshot:A,admission:w,ttlMsOverride:E??K,epochKey:`${Z}${C}`})},_t=async(u,d,y,{forceRefresh:R=!1,snapshot:A=!1,ttlMsOverride:E,admission:w}={})=>{if(Ne(u.visible))return null;let v=Pa(d,y,Ut(u));return(await l.getOrFetch({cacheKey:v,fetcher:async()=>{let V=await at(),k=(0,p.aliasedTable)(f,"draft_label"),te=await O(t.select({hub:Ze(s),internal:Ze(h),isRead:g.isRead,isStarred:g.isStarred,creatorName:n.displayName,...M()}).from(s)).leftJoin(h,(0,p.eq)(s.id,h.hubId)).leftJoin(g,(0,p.and)((0,p.eq)(s.id,g.hubId),(0,p.eq)(g.userId,y))).leftJoin(k,(0,p.and)((0,p.eq)(k.hubId,s.id),(0,p.inArray)(k.labelId,V))).leftJoin(n,(0,p.eq)(s.userId,n.id)).where((0,p.and)((0,p.eq)(s.id,d),(0,p.isNull)(s.deletedAt),(0,p.or)((0,p.eq)(s.userId,y),(0,p.isNull)(k.hubId)),_e(u.visible)));if(te.length===0)return[];let Y=te[0].hub.id,re=await t.select({id:b.id,name:b.name,color:b.color}).from(f).innerJoin(b,(0,p.eq)(f.labelId,b.id)).where((0,p.eq)(f.hubId,Y)),pe=await t.select({id:m.id,body:m.body,createdAt:m.createdAt,userId:m.userId,userName:n.displayName}).from(m).leftJoin(n,(0,p.eq)(m.userId,n.id)).where((0,p.eq)(m.hubId,Y)).orderBy((0,p.asc)(m.createdAt)),ns=await Ft([Y]),os=re.map(je=>({id:je.id,name:je.name,color:je.color})),as=pe.map(je=>({id:je.id,content:je.body,createdAt:Ie(je.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:je.userId,userName:je.userName||""}));return[F(u,{...te[0],attachments:ns.get(Y)??[],labels:os,postedCommentRows:as},y)]},forceRefresh:R,snapshot:A,admission:w,ttlMsOverride:E??K,epochKey:`${oe}${d}`}))[0]??null},ki=async(u,d,y,R={})=>{let A=await J(y);return A?_t(u,d,A,R):null},Hi=async(u,d,y)=>{if(d.length>Ee.maxDetailIds)throw le("getDailyReportDetailsByIdsByExternalId: reportHubIds",`at most ${Ee.maxDetailIds} ids`,d.length);let R=await J(y);return!R||d.length===0?[]:Ne(u.visible)?[]:Ir(u,R,(0,p.inArray)(s.id,[...d]))},Ui=async(u,d)=>{let y=await at(),R=(0,p.aliasedTable)(f,"draft_label"),[A]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt}).top(1).from(s).leftJoin(R,(0,p.and)((0,p.eq)(R.hubId,s.id),(0,p.inArray)(R.labelId,y))).where((0,p.and)((0,p.eq)(s.id,u),(0,p.or)((0,p.eq)(s.userId,d),(0,p.isNull)(R.hubId))));return A??null},_r=async(u,d,y)=>{let R=await Ui(d,y);if(!R||R.deletedAt||!Oe(u.visible,R.sourceType))throw new Error("Not Found")},$i=async(u,d,y,R,A,E)=>{await _r(u,y,d);let w=await t.select().top(1).from(g).where((0,p.and)((0,p.eq)(g.hubId,y),(0,p.eq)(g.userId,d))),v;if(w.length>0?w[0].isStarred!==A?v=(await t.update(g).set({isStarred:A,updatedAt:new Date,updatedBy:String(d)}).output().where((0,p.and)((0,p.eq)(g.hubId,y),(0,p.eq)(g.userId,d))))[0]:v=w[0]:v=(await t.insert(g).output().values({hubId:y,userId:d,isStarred:A,isRead:!1,createdAt:new Date,createdBy:String(d),updatedAt:new Date,updatedBy:String(d)}))[0],R){let C=Pe(R);C&&(l.invalidatePrefix(bt(C,d)),await ie(`${Z}${C}`))}return l.invalidatePrefix(Rr(y,d)),await ie(`${oe}${y}`),await we(Kt.parse({type:"status-update",reportHubId:y,recipientRawUserId:d,statusType:"star",value:A,clientTempId:E}),"setStarStatus"),v},Bi=async(u,d,y,R,A,E)=>{await _r(u,y,d);let w=await t.select().top(1).from(g).where((0,p.and)((0,p.eq)(g.hubId,y),(0,p.eq)(g.userId,d))),v;if(w.length>0?w[0].isRead!==A?v=(await t.update(g).set({isRead:A,updatedAt:new Date,updatedBy:String(d)}).output().where((0,p.and)((0,p.eq)(g.hubId,y),(0,p.eq)(g.userId,d))))[0]:v=w[0]:v=(await t.insert(g).output().values({hubId:y,userId:d,isRead:A,isStarred:!1,createdAt:new Date,createdBy:String(d),updatedAt:new Date,updatedBy:String(d)}))[0],R){let C=Pe(R);C&&(l.invalidatePrefix(bt(C,d)),await ie(`${Z}${C}`))}return l.invalidatePrefix(Rr(y,d)),await ie(`${oe}${y}`),await we(Kt.parse({type:"status-update",reportHubId:y,recipientRawUserId:d,statusType:"read",value:A,clientTempId:E}),"setReadStatus"),v},En=async(u,d)=>{if(d===null)return;let y=await at(),[R]=await t.select({hubId:f.hubId}).top(1).from(f).where((0,p.and)((0,p.eq)(f.hubId,u),(0,p.inArray)(f.labelId,y)));return R?d:void 0},Fi=async(u,d,y,R,A,E)=>{let[w]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt,userId:s.userId}).top(1).from(s).where((0,p.eq)(s.id,y));if(!w||w.deletedAt)throw new Error("Not Found");if(await _r(u,y,d),!Oe(u.commentable,w.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(w.sourceType.toLowerCase()!=="internal")throw new Error("Comments are restricted for external daily report sources");let v=await En(y,w.userId),C=de(),V=await _(async re=>{let[pe]=await re.insert(m).output().values({hubId:y,userId:d,body:R,createdAt:new Date,createdBy:String(d),updatedAt:new Date,updatedBy:String(d)});return C!==null&&await C.writeHubs(re,[y]),pe}),[k]=await t.select({displayName:n.displayName}).top(1).from(n).where((0,p.eq)(n.id,d)),te=k?.displayName??"";if(A){let re=Pe(A);re&&(l.invalidatePrefix(Nt(re)),await ie(`${Z}${re}`))}l.invalidatePrefix(Ye(y)),await ie(`${oe}${y}`);let Y={id:V.id,userId:a(V.userId),userName:te,content:V.body,createdAt:Ie(V.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await we(Br.parse({type:"comment-add",reportHubId:y,comment:Y,clientTempId:E,recipientRawUserId:v,sourceType:w.sourceType}),"addComment"),Y},Vi=async(u,d)=>await u.select().top(1).from(m).where((0,p.eq)(m.id,d)),Yi=async(u,d,y,R,A,E)=>{let w=await Vi(t,R);if(w.length===0)throw new Error("Not Found");if(w[0].hubId!==y)throw new Error("Not Found");let[v]=await t.select({userId:s.userId,sourceType:s.sourceType}).top(1).from(s).where((0,p.eq)(s.id,w[0].hubId));if(!(v&&Oe(u.visible,v.sourceType)))throw new Error("Not Found");if(w[0].userId!==d)throw new Error("Unauthorized");let C=await En(y,v.userId),V=de();if(await _(async k=>{await k.delete(m).where((0,p.eq)(m.id,R)),V!==null&&await V.writeHubs(k,[y])}),A){let k=Pe(A);k&&(l.invalidatePrefix(Nt(k)),await ie(`${Z}${k}`))}l.invalidatePrefix(Ye(y)),await ie(`${oe}${y}`),await we(Fr.parse({type:"comment-delete",reportHubId:y,commentId:R,clientTempId:E,recipientRawUserId:C,sourceType:v?.sourceType}),"deleteComment")},qi=async(u,d)=>{let y=new Map,R=r.attachment;if(!R||W===null)return y;let A=await u.select({hubId:R.hubId,fileName:R.fileName}).from(R).where((0,p.inArray)(R.hubId,[...d])).orderBy((0,p.asc)(R.hubId),(0,p.asc)(R.createdAt),(0,p.asc)(R.id));for(let E of A)Dn(y,Number(E.hubId),String(E.fileName));return y},Wi=async(u,d,y)=>{let R=new Map;for(let[A,E]of y){let w=new Map;for(let{hub:C}of d)C.sourceType===A&&C.sourceIdNum!==null&&w.set(C.sourceIdNum,C.id);if(w.size===0)continue;let v=await E(u,[...w.keys()]);for(let[C,V]of v){let k=w.get(C);if(k===void 0)throw le(`search.externalSourceTexts.${A} answer key`,"a source id that was asked for",C);if(!(Array.isArray(V)&&V.every(te=>typeof te=="string")))throw le(`search.externalSourceTexts.${A} answer for ${C}`,"an array of strings",V);R.set(k,V)}}return R},ji=(u,d)=>{let y=I(u),R=[["subject",u.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 E of y.interviewers)R.push(["interviewerName",E.name??null],["interviewerAffiliation",E.affiliation??null]);for(let E of d.labelNames)R.push(["label",E]);for(let E of d.attachmentNames)R.push(["attachment",E]);for(let E of d.extraTexts)R.push(["extra",E]);let A=[];for(let E of y.externalComments)A.push({authorUserId:null,text:mi(E.name,E.text)});for(let E of d.postedComments)A.push({authorUserId:E.userId,text:mi(E.userName,E.body)});return{hubId:u.hub.id,fields:R,comments:A}},zi=async(u,d,y)=>{let R=[];for(let A of(0,It.chunk)(d,It.MAX_IN_LIST)){let E=await O(u.select({hub:Ze(s),internal:Ze(h),creatorName:n.displayName,...M()}).from(s)).leftJoin(h,(0,p.eq)(s.id,h.hubId)).leftJoin(n,(0,p.eq)(s.userId,n.id)).where((0,p.inArray)(s.id,[...A])).orderBy((0,p.asc)(s.id)),w=new Map,v=await u.select({hubId:f.hubId,name:b.name}).from(f).innerJoin(b,(0,p.eq)(f.labelId,b.id)).where((0,p.inArray)(f.hubId,[...A])).orderBy((0,p.asc)(f.hubId),(0,p.asc)(b.id));for(let Y of v)Dn(w,Y.hubId,Y.name);let C=new Map,V=await u.select({hubId:m.hubId,userId:m.userId,body:m.body,userName:n.displayName}).from(m).leftJoin(n,(0,p.eq)(m.userId,n.id)).where((0,p.inArray)(m.hubId,[...A])).orderBy((0,p.asc)(m.hubId),(0,p.asc)(m.createdAt),(0,p.asc)(m.id));for(let Y of V)Dn(C,Y.hubId,Y);let k=await qi(u,A),te=await Wi(u,E,y);for(let Y of E){let re=Y.hub.id;R.push(ji(Y,{labelNames:Ar(w,re),postedComments:Ar(C,re),attachmentNames:Ar(k,re),extraTexts:Ar(te,re)}))}}return R},Gi=(u,d,y)=>U===null?Promise.reject(new Error("[daily-report] searchDailyReports: the search setting is not configured")):U.search(t,{plan:y,viewerUserId:d,scope:u}),Ki=async(u,d,y,R)=>{if(U===null)throw new Error("[daily-report] markDailyReportSearchHits: the search setting is not configured");if(R.length>Ee.maxDetailIds)throw le("markDailyReportSearchHits: reportHubIds",`at most ${Ee.maxDetailIds} ids`,R.length);let A=zt(Ot(y));if(R.length===0||Ne(u.visible))return{wordsDigest:A,reports:[]};let E=new Map;for(let V of await Ir(u,d,(0,p.inArray)(s.id,[...R])))E.has(V.reportHubId)||E.set(V.reportHubId,V);let w=[...E.values()],v=y.combine==="union"&&y.sets.length>=2&&w.length>0?await U.matchedSets(t,{plan:y,viewerUserId:d,scope:u,ids:w.map(V=>V.reportHubId)}):null,C=[];for(let V of w){C.length>0&&await new Promise(Y=>setImmediate(Y));let k=v===null?null:v.get(V.reportHubId),te=k===void 0?0:k;C.push({reportHubId:V.reportHubId,matchedSets:te,fields:ci(V,li(y,te))})}return{wordsDigest:A,reports:C}},Ji=u=>{let d=de();return d===null?Promise.reject(new Error("[daily-report] reconcileSearchIndex: the search setting is not configured")):d.reconcile(t,u)},Qi=async(u,d,y)=>{if(!jt(d))throw le("createDailyReport: businessDate","a business-date key in the canonical form YYYY-MM-DD naming a day from 0001-01-01 to 9999-12-31",d);H.info("createDailyReport called",{userId:u,businessDate:d});let[R]=await t.select({displayName:n.displayName}).from(n).where((0,p.eq)(n.id,u)),A=R?.displayName??a(u),E=de();try{let w=await _(async C=>{H.info("Starting transaction");let V=`internal-temp-${Date.now()}-${Math.random()}`,[k]=await C.insert(s).output().values({sourceType:"Internal",sourceId:V,businessDate:new Date(`${d}T00:00:00Z`),userId:u,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)});await C.update(s).set({sourceId:String(k.id)}).where((0,p.eq)(s.id,k.id)),H.info("Hub created",k),await C.insert(h).values({hubId:k.id,body:"",createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)}),H.info("Internal created"),H.info("Calling getDraftLabelId");let te=await Er();H.info("draftLabelId",te);let Y=[];return te&&(await C.insert(f).values({hubId:k.id,labelId:te,createdAt:new Date,createdBy:String(u)}),Y.push({id:te,name:N,color:null})),H.info("Label assigned"),E!==null&&await E.writeHubs(C,[k.id]),{reportHubId:k.id,date:d,createdAt:Ie(k.createdAt,"YYYY-MM-DD HH:mm:ss"),author:A,userId:a(u),sourceType:"Internal",employeeName:A,updatedBy:a(u),updatedAt:Ie(k.updatedAt,"YYYY-MM-DD HH:mm:ss"),category:null,creationCategory:null,visitTimeFrom:null,visitTimeTo:null,customerName:null,interviewers:[],subject:k.title,content:"",externalComments:[],isRead:!0,isStarred:!1,labels:Y,postedComments:[],attachments:[]}});l.invalidatePrefix(bt(d,u)),l.invalidatePrefix(ct),l.invalidatePrefix(yn(u)),await ie(me),await ie(`${Z}${d}`);let v=await _t(Ce.unrestricted("post-write self read: the writer always sees the row they just wrote"),w.reportHubId,u,{forceRefresh:!0});if(v){let C=await We(),V=v.labels.some(k=>C.includes(k.id));await we(Vr.parse({type:"report-create",reportHubId:v.reportHubId,report:v,clientTempId:y,recipientRawUserId:V?u:void 0}),"createDailyReport")}return v??w}catch(w){throw H.error("Error in createDailyReport",w),w}},Vt=async(u,d)=>await u.select().top(1).from(s).where((0,p.eq)(s.id,d)),wr=async(u,d,y)=>{await u.update(s).set(y).where((0,p.eq)(s.id,d))},In=async(u,d,y)=>{await u.update(h).set(y).where((0,p.eq)(h.hubId,d))},_n=async(u,d,y)=>{await u.delete(f).where((0,p.and)((0,p.eq)(f.hubId,d),(0,p.eq)(f.labelId,y)))},Xi=async(u,d,y)=>{let R=await Vt(t,u);if(!R.length||R[0].deletedAt)throw new Error("Not Found");if(R[0].userId!==d)throw new Error("Unauthorized");let A=de();if(await _(async E=>{await wr(E,u,{deletedAt:new Date,deletedBy:String(d),updatedAt:new Date,updatedBy:String(d)}),A!==null&&await A.writeHubs(E,[u])}),l.invalidatePrefix(Ye(u)),l.invalidatePrefix(ct),l.invalidatePrefix(lt),await ie(me),R[0].businessDate){let E=Pe(Ie(R[0].businessDate,"YYYY-MM-DD"));E&&await ie(`${Z}${E}`)}await we(Wr.parse({type:"report-delete",reportHubId:u,clientTempId:y,sourceType:R[0].sourceType}),"deleteDailyReport")},Zi=async(u,d,y,R)=>{let A=await Vt(t,u);if(!A.length||A[0].deletedAt)throw new Error("Not Found");if(A[0].userId!==d)throw new Error("Unauthorized");let E=de();await _(async C=>{y.title!==void 0&&await wr(C,u,{title:di(y.title),updatedAt:new Date,updatedBy:String(d)}),y.content!==void 0&&await In(C,u,{body:di(y.content),updatedAt:new Date,updatedBy:String(d)}),E!==null&&await E.writeHubs(C,[u])}),l.invalidatePrefix(Ye(u)),l.invalidatePrefix(ct),await ie(`${oe}${u}`);let w=Pe(Ie(A[0].businessDate,"YYYY-MM-DD"));w&&(l.invalidatePrefix(Nt(w)),await ie(`${Z}${w}`));let v=await _t(Ce.unrestricted("post-write self read: the writer always sees the row they just wrote"),u,d,{forceRefresh:!0});if(v){let C=await We(),V=v.labels.some(k=>C.includes(k.id));await we(Yr.parse({type:"report-update",reportHubId:v.reportHubId,report:v,clientTempId:R,recipientRawUserId:V?d:void 0}),"updateDailyReport")}},es=async(u,d,y)=>{let R=await Vt(t,u);if(!R.length)throw new Error("Not Found");if(R[0].userId!==d)throw new Error("Unauthorized");let A=await Er();if(!A)return null;let E=de();if(await _(async C=>{await _n(C,u,A),E!==null&&await E.writeHubs(C,[u])}),l.invalidatePrefix(Ye(u)),l.invalidatePrefix(ct),l.invalidatePrefix(lt),await ie(me),R[0].businessDate){let C=Pe(Ie(R[0].businessDate,"YYYY-MM-DD"));C&&await ie(`${Z}${C}`)}let w=Pe(Ie(R[0].businessDate,"YYYY-MM-DD"));w&&l.invalidatePrefix(bt(w,d));let v=await _t(Ce.unrestricted("post-write self read: the writer always sees the row they just wrote"),u,d,{forceRefresh:!0});return v&&await we(qr.parse({type:"report-publish",reportHubId:v.reportHubId,report:v,clientTempId:y}),"publishDailyReport"),v??null},ts=async(u,d)=>{l.invalidatePrefix(ct),l.invalidatePrefix(lt),await ie(me);for(let y of new Set(u))l.invalidatePrefix(Ye(y)),await ie(`${oe}${y}`);for(let y of new Set(d)){let R=Pe(y);R&&await ie(`${Z}${R}`)}},rs=async()=>{l.clearAll(),j.clear(),ge=null,c&&await ie(me),H.info("Server-side DB/SQL caches cleared successfully.")};return{streamKey:ae,streamMaxLen:Se,attachmentDelivery:W,titleMaxLength:x,searchLimits:B===null?null:{concurrency:B.concurrency,rateLimitPerMinute:B.rateLimitPerMinute},clearCache:rs,invalidateHubReadCaches:ts,getUserIdByExternalId:J,getDailyReportIdsByExternalId:L,getDailyReportIdsFirstPageByExternalId:X,readSseStreamAnchor:et,getDailyReportsByBusinessDate:se,getDailyReportsByBusinessDateByExternalId:vi,getDailyReportDetailById:_t,getDailyReportDetailByIdByExternalId:ki,getDailyReportDetailsByIdsByExternalId:Hi,getDraftLabelId:Er,searchDailyReports:Gi,markDailyReportSearchHits:Ki,reconcileSearchIndex:Ji,getAttachmentsByHubIds:Ft,getAttachmentForUser:Li,markAttachmentMissing:Oi,markAttachmentPresent:Ni,setStarStatus:$i,setReadStatus:Bi,addComment:Fi,deleteComment:Yi,createDailyReport:Qi,updateDailyReport:Zi,publishDailyReport:es,deleteDailyReport:Xi,findDailyReportHubById:Vt,updateDailyReportHub:wr,updateDailyReportInternal:In,deleteDailyReportLabel:_n}}var pi=(e,t,r,n)=>{if(!e)return[];try{let o=JSON.parse(e);return Array.isArray(o)?o.map(r).filter(a=>a!==null):(fe(n,1,"ExternalSource").warn(`Unexpected ${t} format: not an array`),[])}catch(o){return fe(n,1,"ExternalSource").warn(`Failed to parse ${t}:`,o),[]}};var $t=require("drizzle-orm"),D=require("drizzle-orm/mssql-core");function yi(e,t){let r=(0,D.mssqlSchema)(e),n=t.userTable,o=r.table("DailyReportHub",{id:(0,D.bigint)("id",{mode:"number"}).identity().notNull(),sourceType:(0,D.nvarchar)("source_type",{length:20}).notNull(),sourceId:(0,D.nvarchar)("source_id",{length:100}).notNull(),sourceIdNum:(0,D.bigint)("source_id_num",{mode:"number"}).generatedAlwaysAs($t.sql`TRY_CAST(source_id AS BIGINT)`),businessDate:(0,D.date)("business_date"),userId:(0,D.bigint)("user_id",{mode:"number"}),title:(0,D.nvarchar)("title",{length:200}),summary:(0,D.nvarchar)("summary",{length:"max"}),createdAt:(0,D.datetime2)("created_at").notNull(),createdBy:(0,D.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,D.datetime2)("updated_at").notNull(),updatedBy:(0,D.nvarchar)("updated_by",{length:50}).notNull(),deletedAt:(0,D.datetime2)("deleted_at"),deletedBy:(0,D.nvarchar)("deleted_by",{length:50})},m=>[(0,D.primaryKey)({name:`${e}_DailyReportHub_pk`,columns:[m.id]}),(0,D.foreignKey)({name:`${e}_DailyReportHub_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]}),(0,D.index)(`${e}_DailyReportHub_business_date_index`).on(m.businessDate),(0,D.index)(`${e}_DailyReportHub_updated_at_index`).on(m.updatedAt),(0,D.index)(`${e}_DailyReportHub_source_index`).on(m.sourceType,m.sourceId),(0,D.index)(`${e}_DailyReportHub_user_id_index`).on(m.userId),(0,D.index)(`${e}_DailyReportHub_business_date_id_index`).on((0,$t.desc)(m.businessDate),(0,$t.desc)(m.id)),(0,D.index)(`${e}_DailyReportHub_deleted_at_index`).on(m.deletedAt)]),a=r.table("DailyReportInternal",{hubId:(0,D.bigint)("hub_id",{mode:"number"}).notNull(),body:(0,D.nvarchar)("body",{length:"max"}),metadata:(0,D.nvarchar)("metadata",{length:"max"}),createdAt:(0,D.datetime2)("created_at").notNull(),createdBy:(0,D.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,D.datetime2)("updated_at").notNull(),updatedBy:(0,D.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,D.primaryKey)({name:`${e}_DailyReportInternal_pk`,columns:[m.hubId]}),(0,D.foreignKey)({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]})]),i=r.table("DailyReportComment",{id:(0,D.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,D.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,D.bigint)("user_id",{mode:"number"}).notNull(),body:(0,D.nvarchar)("body",{length:"max"}).notNull(),createdAt:(0,D.datetime2)("created_at").notNull(),createdBy:(0,D.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,D.datetime2)("updated_at").notNull(),updatedBy:(0,D.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,D.primaryKey)({name:`${e}_DailyReportComment_pk`,columns:[m.id]}),(0,D.foreignKey)({name:`${e}_DailyReportComment_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),(0,D.foreignKey)({name:`${e}_DailyReportComment_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]}),(0,D.index)(`${e}_DailyReportComment_hub_id_index`).on(m.hubId)]),l=r.table("DailyReportLabel",{id:(0,D.bigint)("id",{mode:"number"}).identity().notNull(),userId:(0,D.bigint)("user_id",{mode:"number"}),name:(0,D.nvarchar)("name",{length:50}).notNull(),color:(0,D.nvarchar)("color",{length:20}),sortOrder:(0,D.int)("sort_order"),createdAt:(0,D.datetime2)("created_at").notNull(),createdBy:(0,D.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,D.datetime2)("updated_at").notNull(),updatedBy:(0,D.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,D.primaryKey)({name:`${e}_DailyReportLabel_pk`,columns:[m.id]}),(0,D.foreignKey)({name:`${e}_DailyReportLabel_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]})]),c=r.table("DailyReportHub_Label",{hubId:(0,D.bigint)("hub_id",{mode:"number"}).notNull(),labelId:(0,D.bigint)("label_id",{mode:"number"}).notNull(),createdAt:(0,D.datetime2)("created_at").notNull(),createdBy:(0,D.nvarchar)("created_by",{length:50}).notNull()},m=>[(0,D.primaryKey)({name:`${e}_DailyReportHub_Label_pk`,columns:[m.hubId,m.labelId]}),(0,D.foreignKey)({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),(0,D.foreignKey)({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[m.labelId],foreignColumns:[l.id]})]),s=r.table("DailyReportUserStatus",{hubId:(0,D.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,D.bigint)("user_id",{mode:"number"}).notNull(),isRead:(0,D.bit)("is_read").default(!1).notNull(),isStarred:(0,D.bit)("is_starred").default(!1).notNull(),createdAt:(0,D.datetime2)("created_at").notNull(),createdBy:(0,D.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,D.datetime2)("updated_at").notNull(),updatedBy:(0,D.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,D.primaryKey)({name:`${e}_DailyReportUserStatus_pk`,columns:[m.hubId,m.userId]}),(0,D.foreignKey)({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),(0,D.foreignKey)({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]})]),h=r.table("DailyReportAttachment",{id:(0,D.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,D.bigint)("hub_id",{mode:"number"}).notNull(),uploadedBy:(0,D.bigint)("uploaded_by",{mode:"number"}),sourceKey:(0,D.nvarchar)("source_key",{length:200}).notNull(),fileName:(0,D.nvarchar)("file_name",{length:255}).notNull(),filePath:(0,D.nvarchar)("file_path",{length:"max"}).notNull(),fileType:(0,D.nvarchar)("file_type",{length:100}),fileSize:(0,D.bigint)("file_size",{mode:"number"}),objectCheckedAt:(0,D.datetime2)("object_checked_at"),objectMissingAt:(0,D.datetime2)("object_missing_at"),createdAt:(0,D.datetime2)("created_at").notNull(),createdBy:(0,D.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,D.datetime2)("updated_at").notNull(),updatedBy:(0,D.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,D.primaryKey)({name:`${e}_DailyReportAttachment_pk`,columns:[m.id]}),(0,D.foreignKey)({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),(0,D.foreignKey)({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[m.uploadedBy],foreignColumns:[n.id]}),(0,D.uniqueIndex)(`${e}_DailyReportAttachment_source_unique`).on(m.hubId,m.sourceKey),(0,D.index)(`${e}_DailyReportAttachment_hub_id_index`).on(m.hubId,m.createdAt)]);return{hub:o,internal:a,comment:i,attachment:h,label:l,hubLabel:c,userStatus:s}}var he=require("drizzle-orm/mssql-core");function hi(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()},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 Au=5e7,An=2e8,Tu=1,Tn=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})})}),fi=125,Ri=4,Si=16,gi=50,bi=2,Bt=Object.freeze({renderMs:xe.renderMs,nanosecondsPerBlockVisit:fi,margin:Ri,maxBlockVisits:Math.floor(xe.renderMs*1e6/(fi*Ri)),walkBudgetMs:Si,nanosecondsPerWalkStep:gi,walkMargin:bi,maxWalkSteps:Math.floor(Si*1e6/(gi*bi))}),Eu=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),Di=75,Ai=4,Ti="#ffffff",Iu=1,_u={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},wu=[/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/],Ei=Object.freeze({ok:!1,reason:"failed"}),Ii=Object.freeze({ok:!1,reason:"unsupported"}),_i=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:Lo(e)}),wi=(e,t)=>{switch(t){case"jpeg":{let r=on(e);return r===null?null:_i(r)}case"png":{let r=vo(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=ko(e,Bt.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},xi=(e,t)=>{let r=Eu.get(t.depth);if(r===void 0)return null;let n=t.channels*r,o=Tn,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},Ci=(e,t,r)=>{let n=wi(e,t);return n===null?null:xi(n,r)},xu=e=>e!==null&&e<=An,Cu=(e,t)=>{if(t!=="jpeg")return wi(e,t);let r=Oo(e,Bt);return r===null||r.blockVisits>Bt.maxBlockVisits?null:_i(r.header)},Pu=e=>{let t=e instanceof Error?e.message:"";return wu.some(r=>r.test(t))?"failed":"unsupported"},Pi=e=>{e.cache(!1),e.concurrency(Tu),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(_u)});let t=async(n,o,a,i,l)=>{let c=Cu(n,o);if(c===null)return Ii;try{let s=e(n,{limitInputPixels:Au,animated:!1});if(!xu(xi(c,await s.metadata())))return Ii;if(l.aborted)return Ei;let h=await s.rotate().resize({width:a,height:i,fit:"inside",withoutEnlargement:!0}).flatten({background:Ti}).webp({quality:Di,effort:Ai}).toBuffer();return{ok:!0,bytes:new Uint8Array(h),contentType:"image/webp"}}catch(s){return{ok:!1,reason:Pu(s)}}},r=async(n,{format:o,maxWidth:a,maxHeight:i,signal:l})=>l.aborted?Ei:t(n,o,a,i,l);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${Di}-e${Ai}/flatten-${Ti}/v${Iu}`,render:r}};var Mu=4096;function Lu(e){e.redis||fe(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=Yt(e.redis),r=new yt({defaultTtlMs:ne("cacheDefaultTtlMs",e.cacheDefaultTtlMs??6e4,1),maxBuckets:ne("cacheMaxBuckets",e.cacheMaxBuckets??Mu,1)},t),n=Tr({...e,cache:r,epochs:t}),o=new Dt({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),a=Dr({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,isStreamIdLte,parseClientTempId,predictSharpThumbnailWorkingSetBytes,readDailyReportSseStreamEntry,transformJsonArray});
|
|
11
|
+
INSERT INTO ${o} (${B(o.hubId)}, ${B(o.ordinal)}, ${B(o.authorUserId)}, ${B(o.commentText)}) SELECT ${B(o.hubId)}, ${B(o.ordinal)}, ${B(o.authorUserId)}, ${B(o.commentText)} FROM OPENJSON(${i}) WITH (${B(o.hubId)} bigint, ${B(o.ordinal)} int, ${B(o.authorUserId)} bigint, ${B(o.commentText)} nvarchar(max));`},Ei=(e,t)=>U.sql`SELECT ${B(e.hubId)} AS ${U.sql.identifier(Te.hubId)}, LOWER(CONVERT(char(64), ${B(e.sourceDigest)}, 2)) AS ${U.sql.identifier(Te.sourceDigest)}, ${B(e.normalizerVersion)} AS ${U.sql.identifier(Te.normalizerVersion)} FROM ${e} WHERE ${e.hubId} IN (${jt(t)})`,Ii=(e,t,r)=>U.sql`SELECT TOP (${r}) ${B(e.id)} AS ${U.sql.identifier(Te.hubId)} FROM ${e} WHERE ${e.id} > ${t} ORDER BY ${e.id}`;var _i=e=>({search:async(t,r)=>Le(r.scope.visible)?[]:lt(await t.execute(bi(e.tables,r.criteria,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=ft(o[Be.sourceType],Be.sourceType);if(a===null)throw new Error(`[daily-report] search: column ${Be.sourceType} is null`);return{reportHubId:ht(o[Be.reportHubId],Be.reportHubId),businessDate:ft(o[Be.businessDate],Be.businessDate),sourceType:a}}),matchedSets:async(t,r)=>{if(Le(r.scope.visible))return new Map;let n=lt(await t.execute(Di(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[Rt.matchedSets];if(!(typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&l<=o))throw new Error(`[daily-report] search: column ${Rt.matchedSets} holds no mask of ${r.plan.sets.length} keywords`);a.set(ht(i[Rt.reportHubId],Rt.reportHubId),l)}return a},facetValues:async(t,r)=>Le(r.scope.visible)?[]:lt(await t.execute(Ai(e.tables,r.column,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=ft(o[Wt.value],Wt.value);if(a===null)throw new Error(`[daily-report] search: column ${Wt.value} is null`);return a})});var ze=require("@aiquants/mssql"),On=require("drizzle-orm");var xi=require("crypto");var zu=Object.freeze({authorName:"author",customerName:"customer"}),Ln=e=>e===null?null:an(e),wi=(e,t,r)=>{let n=Ln(r);if(n!==null&&n.length>Qe.maxValueLength){let o=Qe.maxValueLength;throw new Error(`[daily-report] search index: report ${e}: the ${zu[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},zt=e=>e===null?"n;":`s${e.length}:${e}`,Gt="utf16le",Gu=e=>{let t=(0,xi.createHash)("sha256");t.update(`F${e.fields.length};`,Gt);for(let[r,n]of e.fields)t.update(zt(r)+zt(n),Gt);return t.update(`C${e.comments.length};`,Gt),e.comments.forEach((r,n)=>{t.update(`${n};${r.authorUserId===null?"n":`i${r.authorUserId}`};${zt(r.text)}`,Gt)}),t.update(`P;${zt(Ln(e.filterValues.authorName))}${zt(Ln(e.filterValues.customerName))}`,Gt),t.digest("hex")},Nn=e=>{let t=0,r=[];for(let[,o]of e.fields){if(o===null)continue;let a=Ir(o);t+=a.forcedCuts,r.push(a.text)}let n=[];for(let o of e.comments){let a=Ir(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:Va(r),comments:n,sourceDigest:Gu(e),forcedCuts:t,authorName:wi(e.hubId,"authorName",e.filterValues.authorName),customerName:wi(e.hubId,"customerName",e.filterValues.customerName)}};var Ci=e=>{let t=async(c,s)=>{let y=[];for(let m of(0,ze.chunk)(s,ze.MAX_IN_LIST))for(let S of lt(await c.execute(Si(e.hub,m))))y.push(ht(S[Te.hubId],Te.hubId));return y},r=async(c,s)=>{for(let y of(0,ze.chunk)(s,ze.MAX_IN_LIST))await c.execute(Ti(e.tables,y,e.normalizerVersion))},n=async(c,s)=>{let y=new Map;for(let m of(0,ze.chunk)(s,ze.MAX_IN_LIST))for(let S of lt(await c.execute(Ei(e.tables.document,m))))y.set(ht(S[Te.hubId],Te.hubId),{sourceDigest:ft(S[Te.sourceDigest],Te.sourceDigest),normalizerVersion:ft(S[Te.normalizerVersion],Te.normalizerVersion)});return y},o=async(c,s,y)=>lt(await c.execute(Ii(e.hub,s,y))).map(m=>ht(m[Te.hubId],Te.hubId)),a=async(c,s)=>{let y=await t(c,[...new Set(s)].sort((S,f)=>S-f));if(y.length===0)return;let m=(await e.loadSources(c,y)).map(Nn);m.length>0&&await r(c,m)},i=c=>e.inTransaction(async s=>{await s.execute(On.sql`SET DEADLOCK_PRIORITY LOW`);let y=await t(s,c),m=await n(s,y),S=(await e.loadSources(s,y)).map(Nn),f=S.filter(R=>{let A=m.get(R.hubId);return A===void 0||A.sourceDigest!==R.sourceDigest||A.normalizerVersion!==e.normalizerVersion});return f.length>0&&await r(s,f),await s.execute(On.sql`SET DEADLOCK_PRIORITY NORMAL`),{scanned:S.length,written:f.length,forcedCuts:S.reduce((R,A)=>R+A.forcedCuts,0)}});return{writeHubs:a,reconcile:async(c,s)=>{let{batchSize:y,hubIds:m,signal:S,onProgress:f}=s;te("reconcileSearchIndex: batchSize",y,1,ze.MAX_IN_LIST);let R=ue(),A=m===void 0?null:(0,ze.chunk)([...new Set(m)].sort((w,F)=>w-F),y),b={scanned:0,written:0,skipped:0,forcedCuts:0,lastHubId:null};for(let w=0;;w++){S?.throwIfAborted();let F=A===null?await o(c,b.lastHubId===null?0:b.lastHubId,y):A[w];if(F===void 0||F.length===0)break;let V=await i(F);b={scanned:b.scanned+V.scanned,written:b.written+V.written,skipped:b.skipped+V.scanned-V.written,forcedCuts:b.forcedCuts+V.forcedCuts,lastHubId:F[F.length-1]},f?.(b)}return{...b,elapsedMs:ue()-R}}}};var Pi=require("@aiquants/fuzzy-search/normalize");var vn=255,Or=Object.values(ut).sort((e,t)=>e-t),Ku=new Intl.Segmenter("und",{granularity:"grapheme"}),Ju=(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},Qu=(e,t)=>e.chunks.length===1&&e.chunks[0].length===1&&e.chunks[0][0].start===0&&e.chunks[0][0].end===t.length,Xu=(e,t,r)=>{let n=e.slice(t,r);if(!(0,Pi.holdsMultiUnitCluster)(n))return null;let o=new Int32Array(r-t),a=new Int32Array(r-t);for(let{index:i,segment:l}of Ku.segment(n))o.fill(t+i,i,i+l.length),a.fill(t+i+l.length,i,i+l.length);return{start:t,clusterStarts:o,clusterEnds:a}},Zu=(e,t,r)=>({start:e.clusterStarts[t-e.start],end:e.clusterEnds[r-1-e.start]}),ed=(e,t,r=Er)=>{let n=new Map;for(let l of t){if(l.text.length===0)throw new Error("[daily-report] search marks: an alternative has an empty text");let c=n.get(l.text);(c===void 0||l.tier<c)&&n.set(l.text,l.tier)}let o=[];if(n.size===0)return o;let a=Ha(e),i=l=>a.rawIndex===null?l:a.rawIndex[l];return _n(a.text,(l,c)=>{let s=In(l,r).text,y=null,m=null;for(let[S,f]of n){let R=s.indexOf(S);if(!(R<0)){if(y===null){let A=En(l,r);y=Ju(Ba(l,A),s),m=Qu(A,l)?null:Xu(e,i(c),i(c+l.length-1)+1)}for(;R>=0;){let A=i(c+y.start[R]),b=i(c+y.end[R+S.length-1]-1)+1;m===null?o.push({start:A,end:b,tier:f}):o.push({...Zu(m,A,b),tier:f}),R=s.indexOf(S,R+1)}}}}),o},td=(e,t,r=Er)=>{let n=ed(e,t,r),o=[];if(n.length===0)return o;let a=Or.map(()=>new Int32Array(e.length+1));for(let{start:s,end:y,tier:m}of n)a[m][s]++,a[m][y]--;let i=new Int32Array(Or.length),l=0,c=vn;for(let s=0;s<=e.length;s++){let y=vn;for(let m=Or.length-1;m>=0;m--){let S=Or[m];i[S]+=a[S][s],i[S]>0&&(y=S)}y!==c&&(c!==vn&&o.push(l,s,c),l=s,c=y)}return o},Mi=(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)},Li=(e,t)=>{let r=t.flatMap(a=>a.alternatives),n={},o=(a,i)=>{typeof i!="string"||i.length===0||(n[a]={fingerprint:Gr(i),ranges:td(i,r)})};for(let a of Xn)o(Je.field(a),e[a]);e.interviewers.forEach((a,i)=>{o(Je.interviewer(i,"name"),a.name),o(Je.interviewer(i,"affiliation"),a.affiliation)}),e.attachments.forEach((a,i)=>{o(Je.attachment(i),a.fileName)}),e.externalComments.forEach((a,i)=>{o(Je.comment(jr(i),"author"),a.name),o(Je.comment(jr(i),"content"),a.text)});for(let a of e.postedComments)o(Je.comment(a.id,"author"),a.userName),o(Je.comment(a.id,"content"),a.content);return n};var nt=e=>(0,g.getColumns)(e),Ni=er([]),_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}`},nd=e=>{let{length:t}=e;if(t===void 0)throw le("tables.hub.title","a character column with a declared length",t);return te("tables.hub.title.length",t,1)},Oi=e=>e===""?null:e,od=Object.freeze([]),kn=(e,t,r)=>{let n=e.get(t);n?n.push(r):e.set(t,[r])},vr=(e,t)=>e.get(t)??od,vi=(e,t)=>[e,t].filter(r=>typeof r=="string"&&r.length>0).join(Tr),ad=e=>{let t=new Set;return e.filter(r=>{let n=r.toLowerCase();return t.has(n)?!1:(t.add(n),!0)})};function kr(e){let{db:t,tables:r,userTable:n,resolveUserId:o,encodeUserId:a,redis:i,cache:l,epochs:c}=e,{hub:s,internal:y,comment:m,label:S,hubLabel:f,userStatus:R}=r,A=e.externalSources??[],b=e.draftLabelNames&&e.draftLabelNames.length>0?e.draftLabelNames:[e.draftLabelName??"\u4E0B\u66F8\u304D"],w=b[0]??"\u4E0B\u66F8\u304D",F=Se(e.logger,1,"Service");Sr(e);let V=fa(e.attachments),P=nd(s.title),I=u=>(0,Pt.runWithTransactionRetry)(d=>t.transaction(p=>d(()=>u(p))),e.transactionRetry),q=e.search===void 0?null:fi(e.search,A.map(u=>u.sourceType)),$={hub:s,hubLabel:f,label:S},H=q===null?null:_i({tables:{...$,search:q.tables},draftLabelNames:b}),ce=null,de=()=>{if(q===null)return null;if(ce===null){let u=q.externalSourceTexts;ce=Ci({hub:s,tables:q.tables,loadSources:(d,p)=>fs(d,p,u),inTransaction:I,normalizerVersion:Ya()})}return ce},ge=e.idsTtlMs??18e4,G="daily-report:ids:epoch",re=e.businessDateTtlMs??3e5,ee="daily-report:date-epoch:",se="daily-report:detail-epoch:",fe=`${e.streamKey??"daily-report:sse-stream"}:v2`,Ge=e.streamMaxLen??1e4,ne=u=>c.incrementEpoch(u),Ne=u=>Ut(s.sourceType,u),Fe=(u,d)=>Nr($,u,b,d),we=async(u,d)=>{let p=await i?.getClient();if(!p){F.warn(`[SSE] Redis client unavailable (${d})`);return}let h=JSON.stringify(u),T=Buffer.byteLength(h);if(T>6356992){F.warn(`[SSE] Event too large (${d}): ${T} bytes > ${6356992}; not published`);return}let x=ue();try{await p.xAdd(fe,"*",{data:h},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:Ge}});let L=ue()-x;L>1e3&&F.warn(`[SSE] Slow publish (${d}): ${L}ms`)}catch(L){F.error(`[SSE] Redis publish failed (${d}):`,L)}},Ve=async()=>{try{let u=await i?.getClient();if(u===void 0)return null;let[d]=await u.xRevRange(fe,"+","-",{COUNT:1});return d===void 0?null:d.id}catch(u){return F.error("SSE stream anchor read failed",u),null}},O=u=>u==null||u===""?null:/^\d+$/.test(u)?a(Number(u)):u,E=()=>{let u={};for(let d of A)u[`ext_${d.sourceType}`]=nt(d.table);return u},C=u=>{let d=u;for(let p of A)d=d.leftJoin(p.table,(0,g.and)((0,g.eq)(s.sourceType,p.sourceType),(0,g.eq)(s.sourceIdNum,p.idColumn)));return d},Y=u=>{let{hub:d,internal:p}=u,h=d.summary,T=[],x=null,L=null,k=null,N=null,W=null,_=null,X=[],ie=A.find(pe=>pe.sourceType===d.sourceType),De=ie?u[`ext_${ie.sourceType}`]:void 0;if(ie&&De){let pe=ie.mapRow(De);pe.content!==void 0&&(h=pe.content),pe.employeeName!==void 0&&(_=pe.employeeName),pe.category!==void 0&&(x=pe.category),pe.creationCategory!==void 0&&(L=pe.creationCategory),pe.visitTimeFrom!==void 0&&(k=pe.visitTimeFrom),pe.visitTimeTo!==void 0&&(N=pe.visitTimeTo),pe.customerName!==void 0&&(W=pe.customerName),pe.interviewers!==void 0&&(T=pe.interviewers),pe.externalComments!==void 0&&(X=pe.externalComments)}else d.sourceType==="Internal"&&p&&(h=p.body);return{content:h,author:u.creatorName??O(d.createdBy)??"",employeeName:_??u.creatorName??O(d.createdBy),updatedBy:O(d.updatedBy),category:x,creationCategory:L,visitTimeFrom:k,visitTimeTo:N,customerName:W,interviewers:T,externalComments:X}},j=(u,d,p)=>{let{hub:h}=d,T=Y(d),x=(d.labels??[]).map(_=>({id:_.id,name:_.name,color:_.color})),L=d.postedCommentRows??[],k=Me(u.commentable,h.sourceType),N=T.creationCategory?b.includes(T.creationCategory):!1,W=Ee?.[0]??null;return N&&W&&!x.some(_=>_.id===W)&&x.push({id:W,name:w,color:null}),{reportHubId:h.id,date:_e(h.businessDate,"YYYY-MM-DD"),author:T.author,userId:h.userId?a(h.userId):"",sourceType:h.sourceType??"Internal",createdAt:_e(h.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:_e(h.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:T.updatedBy,employeeName:T.employeeName,category:T.category,creationCategory:T.creationCategory,visitTimeFrom:T.visitTimeFrom,visitTimeTo:T.visitTimeTo,customerName:T.customerName,interviewers:T.interviewers,subject:h.title,content:T.content,externalComments:k?T.externalComments:[],isRead:d.isRead??!1,isStarred:d.isStarred??!1,labels:x,postedComments:L.filter(_=>Oa({authorUserId:_.userId},h.sourceType,p??null,u)).map(_=>({..._,userId:a(_.userId),isMine:p?_.userId===p:!1})),attachments:d.attachments}},J=async(u,d)=>(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).from(s).where((0,g.and)((0,g.isNull)(s.deletedAt),Fe(d,"author-or-authorless"),Ne(u.visible))).orderBy((0,g.desc)(s.businessDate),(0,g.desc)(s.id))).map(h=>({...h,businessDate:_e(h.businessDate,"YYYY-MM-DD")})),K=async(u,d,p)=>{let h=await M(d);return h?Le(u.visible)?[]:(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).top(p).from(s).where((0,g.and)((0,g.isNull)(s.deletedAt),Fe(h,"author-or-authorless"),Ne(u.visible))).orderBy((0,g.desc)(s.businessDate),(0,g.desc)(s.id))).map(x=>({...x,businessDate:_e(x.businessDate,"YYYY-MM-DD")})):[]},z=async(u,d)=>{let p=await C(t.select({hub:nt(s),internal:nt(y),creatorName:n.displayName,...E()}).from(s)).leftJoin(y,(0,g.eq)(s.id,y.hubId)).leftJoin(n,(0,g.eq)(s.userId,n.id)).where((0,g.and)((0,g.eq)(s.businessDate,g.sql`${d}`),(0,g.isNull)(s.deletedAt),Ne(u.visible))).orderBy((0,g.desc)(s.id)),h=await Qt(p.map(T=>T.hub.id));return p.map(T=>j(u,{...T,attachments:h.get(T.hub.id)??[]}))},Q=new Map,M=async u=>{if(!e.disableUserIdCache&&Q.has(u))return Q.get(u)??null;let d=await o(u);return d!==null&&!e.disableUserIdCache&&Q.set(u,d),d},ae=async(u,d,{forceRefresh:p=!1,snapshot:h=!1,ttlMsOverride:T,onFetchStart:x,admission:L}={})=>{let k=await M(d);if(!k)return{items:[],streamAnchor:null,snapshot:Ni};if(Le(u.visible))return{items:[],streamAnchor:await Ve(),snapshot:Ni};let N=Qa(k,$t(u)),[W]=await l.getOrFetch({cacheKey:N,fetcher:async()=>{let _=await Ve(),X=await J(u,k);if(!Wn(X)){F.warn("ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)");let ie=[...X].sort(tr);return[{items:ie,streamAnchor:_,snapshot:er(ie)}]}return[{items:X,streamAnchor:_,snapshot:er(X)}]},onFetchStart:x,forceRefresh:p,snapshot:h,admission:L,ttlMsOverride:T??ge,epochKey:G,refreshAheadRatio:.5});if(W===void 0)throw new Error("[daily-report] getDailyReportIdsByExternalId: the ids cache returned no record");return W},be=(u,d,{forceRefresh:p=!1,snapshot:h=!1,ttlMsOverride:T}={})=>{let x=Oe(d);return x?Le(u.visible)?Promise.resolve([]):l.getOrFetch({cacheKey:Xa(x,$t(u)),fetcher:()=>z(u,x),forceRefresh:p,snapshot:h,ttlMsOverride:T??re}):Promise.resolve([])},Ee=null,St=async()=>(Ee!==null||(Ee=(await t.select({id:S.id}).from(S).where((0,g.inArray)(S.name,b)).orderBy(S.id)).map(d=>d.id)),Ee),Fr=async()=>{let u=await St();if(u.length===0)return null;let[d]=await t.select({id:S.id}).top(1).from(S).where((0,g.eq)(S.name,w));return d?.id??u[0]},es=(u,d)=>d!=null?"absent":u!=null?"present":"unknown",Qt=async u=>{let d=new Map,p=r.attachment;if(u.length===0||!p||V===null)return d;let h=V.idCodec,T=V.thumbnails!==null,x=await t.select({id:p.id,hubId:p.hubId,fileName:p.fileName,fileType:p.fileType,fileSize:p.fileSize,createdAt:p.createdAt,objectCheckedAt:p.objectCheckedAt,objectMissingAt:p.objectMissingAt}).from(p).where((0,g.inArray)(p.hubId,u)).orderBy((0,g.asc)(p.createdAt),(0,g.asc)(p.id));for(let L of x){let k=L.fileType?String(L.fileType):null,N=L.fileSize!=null?Number(L.fileSize):null,W=es(L.objectCheckedAt,L.objectMissingAt),_={id:h.encode(Number(L.id)),fileName:String(L.fileName),fileType:k,fileSize:N,createdAt:_e(L.createdAt,"YYYY-MM-DD HH:mm:ss"),state:W,hasThumbnail:T&&W!=="absent"&&fr({fileType:k,fileSize:N},V.maxBytes)},X=d.get(Number(L.hubId));X?X.push(_):d.set(Number(L.hubId),[_])}return d},ts=async(u,d,p)=>{let h=r.attachment;return!h||Le(u.visible)?null:(await t.select({fileName:h.fileName,filePath:h.filePath,fileType:h.fileType,fileSize:h.fileSize}).top(1).from(h).innerJoin(s,(0,g.eq)(s.id,h.hubId)).where((0,g.and)((0,g.eq)(h.id,d),(0,g.isNull)(s.deletedAt),Fe(p,"author"),Ne(u.visible))))[0]??null},rs=async u=>{let d=r.attachment;if(!d)return;let p=new Date;try{await t.update(d).set({objectCheckedAt:p,objectMissingAt:p,updatedAt:p}).where((0,g.eq)(d.id,u))}catch(h){F.error("markAttachmentMissing failed",h)}},ns=async u=>{let d=r.attachment;if(!d)return;let p=new Date;try{await t.update(d).set({objectCheckedAt:p,objectMissingAt:null,updatedAt:p}).where((0,g.eq)(d.id,u))}catch(h){F.error("markAttachmentPresent failed",h)}},Hr=async(u,d,p)=>{let h=await C(t.select({hub:nt(s),internal:nt(y),isRead:R.isRead,isStarred:R.isStarred,creatorName:n.displayName,...E()}).from(s)).leftJoin(y,(0,g.eq)(s.id,y.hubId)).leftJoin(R,(0,g.and)((0,g.eq)(s.id,R.hubId),(0,g.eq)(R.userId,d))).leftJoin(n,(0,g.eq)(s.userId,n.id)).where((0,g.and)(p,(0,g.isNull)(s.deletedAt),Fe(d,"author"),Ne(u.visible))).orderBy((0,g.desc)(s.id));if(h.length===0)return[];let T=h.map(_=>_.hub.id),x=await t.select({hubId:f.hubId,id:S.id,name:S.name,color:S.color}).from(f).innerJoin(S,(0,g.eq)(f.labelId,S.id)).where((0,g.inArray)(f.hubId,T)),L=await t.select({hubId:m.hubId,id:m.id,body:m.body,createdAt:m.createdAt,userId:m.userId,userName:n.displayName}).from(m).leftJoin(n,(0,g.eq)(m.userId,n.id)).where((0,g.inArray)(m.hubId,T)).orderBy((0,g.asc)(m.createdAt)),k=await Qt(T),N=new Map,W=new Map;for(let _ of x){let X=N.get(_.hubId);X||(X=[],N.set(_.hubId,X)),X.push({id:_.id,name:_.name,color:_.color})}for(let _ of L){let X=W.get(_.hubId);X||(X=[],W.set(_.hubId,X)),X.push({id:_.id,content:_.body,createdAt:_e(_.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:_.userId,userName:_.userName||""})}return h.map(_=>{let X=_.hub.id;return j(u,{..._,attachments:k.get(X)??[],labels:N.get(X)||[],postedCommentRows:W.get(X)||[]},d)})},os=async(u,d,p,{forceRefresh:h=!1,snapshot:T=!1,ttlMsOverride:x,admission:L}={})=>{let k=await M(p);if(!k)return[];let N=Oe(d);if(!N)return[];if(Le(u.visible))return[];let W=Za(N,k,$t(u));return l.getOrFetch({cacheKey:W,fetcher:()=>Hr(u,k,(0,g.eq)(s.businessDate,g.sql`${N}`)),forceRefresh:h,snapshot:T,admission:L,ttlMsOverride:x??re,epochKey:`${ee}${N}`})},Mt=async(u,d,p,{forceRefresh:h=!1,snapshot:T=!1,ttlMsOverride:x,admission:L}={})=>{if(Le(u.visible))return null;let k=ei(d,p,$t(u));return(await l.getOrFetch({cacheKey:k,fetcher:async()=>{let W=await C(t.select({hub:nt(s),internal:nt(y),isRead:R.isRead,isStarred:R.isStarred,creatorName:n.displayName,...E()}).from(s)).leftJoin(y,(0,g.eq)(s.id,y.hubId)).leftJoin(R,(0,g.and)((0,g.eq)(s.id,R.hubId),(0,g.eq)(R.userId,p))).leftJoin(n,(0,g.eq)(s.userId,n.id)).where((0,g.and)((0,g.eq)(s.id,d),(0,g.isNull)(s.deletedAt),Fe(p,"author"),Ne(u.visible)));if(W.length===0)return[];let _=W[0].hub.id,X=await t.select({id:S.id,name:S.name,color:S.color}).from(f).innerJoin(S,(0,g.eq)(f.labelId,S.id)).where((0,g.eq)(f.hubId,_)),ie=await t.select({id:m.id,body:m.body,createdAt:m.createdAt,userId:m.userId,userName:n.displayName}).from(m).leftJoin(n,(0,g.eq)(m.userId,n.id)).where((0,g.eq)(m.hubId,_)).orderBy((0,g.asc)(m.createdAt)),De=await Qt([_]),pe=X.map(Ke=>({id:Ke.id,name:Ke.name,color:Ke.color})),ws=ie.map(Ke=>({id:Ke.id,content:Ke.body,createdAt:_e(Ke.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:Ke.userId,userName:Ke.userName||""}));return[j(u,{...W[0],attachments:De.get(_)??[],labels:pe,postedCommentRows:ws},p)]},forceRefresh:h,snapshot:T,admission:L,ttlMsOverride:x??re,epochKey:`${se}${d}`}))[0]??null},as=async(u,d,p,h={})=>{let T=await M(p);return T?Mt(u,d,T,h):null},is=async(u,d,p)=>{if(d.length>Ie.maxDetailIds)throw le("getDailyReportDetailsByIdsByExternalId: reportHubIds",`at most ${Ie.maxDetailIds} ids`,d.length);let h=await M(p);return!h||d.length===0?[]:Le(u.visible)?[]:Hr(u,h,(0,g.inArray)(s.id,[...d]))},ss=async(u,d)=>{let[p]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt}).top(1).from(s).where((0,g.and)((0,g.eq)(s.id,u),Fe(d,"author")));return p??null},Ur=async(u,d,p)=>{let h=await ss(d,p);if(!h||h.deletedAt||!Me(u.visible,h.sourceType))throw new Error("Not Found")},ls=async(u,d,p,h,T,x)=>{await Ur(u,p,d);let L=await t.select().top(1).from(R).where((0,g.and)((0,g.eq)(R.hubId,p),(0,g.eq)(R.userId,d))),k;if(L.length>0?L[0].isStarred!==T?k=(await t.update(R).set({isStarred:T,updatedAt:new Date,updatedBy:String(d)}).output().where((0,g.and)((0,g.eq)(R.hubId,p),(0,g.eq)(R.userId,d))))[0]:k=L[0]:k=(await t.insert(R).output().values({hubId:p,userId:d,isStarred:T,isRead:!1,createdAt:new Date,createdBy:String(d),updatedAt:new Date,updatedBy:String(d)}))[0],h){let N=Oe(h);N&&(l.invalidatePrefix(xt(N,d)),await ne(`${ee}${N}`))}return l.invalidatePrefix(xr(p,d)),await ne(`${se}${p}`),await we(ir.parse({type:"status-update",reportHubId:p,recipientRawUserId:d,statusType:"star",value:T,clientTempId:x}),"setStarStatus"),k},cs=async(u,d,p,h,T,x)=>{await Ur(u,p,d);let L=await t.select().top(1).from(R).where((0,g.and)((0,g.eq)(R.hubId,p),(0,g.eq)(R.userId,d))),k;if(L.length>0?L[0].isRead!==T?k=(await t.update(R).set({isRead:T,updatedAt:new Date,updatedBy:String(d)}).output().where((0,g.and)((0,g.eq)(R.hubId,p),(0,g.eq)(R.userId,d))))[0]:k=L[0]:k=(await t.insert(R).output().values({hubId:p,userId:d,isRead:T,isStarred:!1,createdAt:new Date,createdBy:String(d),updatedAt:new Date,updatedBy:String(d)}))[0],h){let N=Oe(h);N&&(l.invalidatePrefix(xt(N,d)),await ne(`${ee}${N}`))}return l.invalidatePrefix(xr(p,d)),await ne(`${se}${p}`),await we(ir.parse({type:"status-update",reportHubId:p,recipientRawUserId:d,statusType:"read",value:T,clientTempId:x}),"setReadStatus"),k},Un=async(u,d)=>{if(d===null)return;let p=await St();if(p.length===0)return;let[h]=await t.select({hubId:f.hubId}).top(1).from(f).where((0,g.and)((0,g.eq)(f.hubId,u),(0,g.inArray)(f.labelId,p)));return h?d:void 0},us=async(u,d,p,h,T,x)=>{let[L]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt,userId:s.userId}).top(1).from(s).where((0,g.eq)(s.id,p));if(!L||L.deletedAt)throw new Error("Not Found");if(await Ur(u,p,d),!Me(u.commentable,L.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(L.sourceType.toLowerCase()!=="internal")throw new Error("Comments are restricted for external daily report sources");let k=await Un(p,L.userId),N=de(),W=await I(async De=>{let[pe]=await De.insert(m).output().values({hubId:p,userId:d,body:h,createdAt:new Date,createdBy:String(d),updatedAt:new Date,updatedBy:String(d)});return N!==null&&await N.writeHubs(De,[p]),pe}),[_]=await t.select({displayName:n.displayName}).top(1).from(n).where((0,g.eq)(n.id,d)),X=_?.displayName??"";if(T){let De=Oe(T);De&&(l.invalidatePrefix(qt(De)),await ne(`${ee}${De}`))}l.invalidatePrefix(We(p)),await ne(`${se}${p}`);let ie={id:W.id,userId:a(W.userId),userName:X,content:W.body,createdAt:_e(W.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await we(Zr.parse({type:"comment-add",reportHubId:p,comment:ie,clientTempId:x,recipientRawUserId:k,sourceType:L.sourceType}),"addComment"),ie},ds=async(u,d)=>await u.select().top(1).from(m).where((0,g.eq)(m.id,d)),ms=async(u,d,p,h,T,x)=>{let L=await ds(t,h);if(L.length===0)throw new Error("Not Found");if(L[0].hubId!==p)throw new Error("Not Found");let[k]=await t.select({userId:s.userId,sourceType:s.sourceType}).top(1).from(s).where((0,g.eq)(s.id,L[0].hubId));if(!(k&&Me(u.visible,k.sourceType)))throw new Error("Not Found");if(L[0].userId!==d)throw new Error("Unauthorized");let N=await Un(p,k.userId),W=de();if(await I(async _=>{await _.delete(m).where((0,g.eq)(m.id,h)),W!==null&&await W.writeHubs(_,[p])}),T){let _=Oe(T);_&&(l.invalidatePrefix(qt(_)),await ne(`${ee}${_}`))}l.invalidatePrefix(We(p)),await ne(`${se}${p}`),await we(en.parse({type:"comment-delete",reportHubId:p,commentId:h,clientTempId:x,recipientRawUserId:N,sourceType:k?.sourceType}),"deleteComment")},ps=async(u,d)=>{let p=new Map,h=r.attachment;if(!h||V===null)return p;let T=await u.select({hubId:h.hubId,fileName:h.fileName}).from(h).where((0,g.inArray)(h.hubId,[...d])).orderBy((0,g.asc)(h.hubId),(0,g.asc)(h.createdAt),(0,g.asc)(h.id));for(let x of T)kn(p,Number(x.hubId),String(x.fileName));return p},ys=async(u,d,p)=>{let h=new Map;for(let[T,x]of p){let L=new Map;for(let{hub:N}of d)N.sourceType===T&&N.sourceIdNum!==null&&L.set(N.sourceIdNum,N.id);if(L.size===0)continue;let k=await x(u,[...L.keys()]);for(let[N,W]of k){let _=L.get(N);if(_===void 0)throw le(`search.externalSourceTexts.${T} answer key`,"a source id that was asked for",N);if(!(Array.isArray(W)&&W.every(X=>typeof X=="string")))throw le(`search.externalSourceTexts.${T} answer for ${N}`,"an array of strings",W);h.set(_,W)}}return h},hs=(u,d)=>{let p=Y(u),h=[["subject",u.hub.title],["content",p.content],["author",p.author],["employeeName",p.employeeName],["updatedBy",p.updatedBy],["category",p.category],["creationCategory",p.creationCategory],["customerName",p.customerName]];for(let x of p.interviewers)h.push(["interviewerName",x.name??null],["interviewerAffiliation",x.affiliation??null]);for(let x of d.labelNames)h.push(["label",x]);for(let x of d.attachmentNames)h.push(["attachment",x]);for(let x of d.extraTexts)h.push(["extra",x]);let T=[];for(let x of p.externalComments)T.push({authorUserId:null,text:vi(x.name,x.text)});for(let x of d.postedComments)T.push({authorUserId:x.userId,text:vi(x.userName,x.body)});return{hubId:u.hub.id,fields:h,comments:T,filterValues:{authorName:p.employeeName,customerName:p.customerName}}},fs=async(u,d,p)=>{let h=[];for(let T of(0,Pt.chunk)(d,Pt.MAX_IN_LIST)){let x=await C(u.select({hub:nt(s),internal:nt(y),creatorName:n.displayName,...E()}).from(s)).leftJoin(y,(0,g.eq)(s.id,y.hubId)).leftJoin(n,(0,g.eq)(s.userId,n.id)).where((0,g.inArray)(s.id,[...T])).orderBy((0,g.asc)(s.id)),L=new Map,k=await u.select({hubId:f.hubId,name:S.name}).from(f).innerJoin(S,(0,g.eq)(f.labelId,S.id)).where((0,g.inArray)(f.hubId,[...T])).orderBy((0,g.asc)(f.hubId),(0,g.asc)(S.id));for(let ie of k)kn(L,ie.hubId,ie.name);let N=new Map,W=await u.select({hubId:m.hubId,userId:m.userId,body:m.body,userName:n.displayName}).from(m).leftJoin(n,(0,g.eq)(m.userId,n.id)).where((0,g.inArray)(m.hubId,[...T])).orderBy((0,g.asc)(m.hubId),(0,g.asc)(m.createdAt),(0,g.asc)(m.id));for(let ie of W)kn(N,ie.hubId,ie);let _=await ps(u,T),X=await ys(u,x,p);for(let ie of x){let De=ie.hub.id;h.push(hs(ie,{labelNames:vr(L,De),postedComments:vr(N,De),attachmentNames:vr(_,De),extraTexts:vr(X,De)}))}}return h},Rs=(u,d,p)=>H===null?Promise.reject(new Error("[daily-report] searchDailyReports: the search setting is not configured")):H.search(t,{criteria:p,viewerUserId:d,scope:u}),$n=Object.freeze(ad(["Internal",...A.map(u=>u.sourceType)])),Ss=async(u,d)=>{if(H===null)throw new Error("[daily-report] listDailyReportSearchFacets: the search setting is not configured");let p=$n.filter(x=>Me(u.visible,x)),h=await H.facetValues(t,{column:"authorName",viewerUserId:d,scope:u}),T=await H.facetValues(t,{column:"customerName",viewerUserId:d,scope:u});return{sourceTypes:p,authors:h,customers:T}},gs=async(u,d,p,h,T)=>{if(H===null)throw new Error("[daily-report] markDailyReportSearchHits: the search setting is not configured");if(h.length>Ie.maxDetailIds)throw le("markDailyReportSearchHits: reportHubIds",`at most ${Ie.maxDetailIds} ids`,h.length);let{signal:x}=T,L=nr(Vt(p));if(h.length===0||Le(u.visible))return{wordsDigest:L,reports:[]};x.throwIfAborted();let k=await Hr(u,d,(0,g.inArray)(s.id,[...h]));x.throwIfAborted();let N=p.combine==="union"&&p.sets.length>=2&&k.length>0?await H.matchedSets(t,{plan:p,viewerUserId:d,scope:u,ids:k.map(_=>_.reportHubId)}):null,W=[];for(let _ of k){W.length>0&&await new Promise(De=>setImmediate(De)),x.throwIfAborted();let X=N===null?null:N.get(_.reportHubId),ie=X===void 0?0:X;W.push({reportHubId:_.reportHubId,matchedSets:ie,fields:Li(_,Mi(p,ie))})}return{wordsDigest:L,reports:W}},bs=u=>{let d=de();return d===null?Promise.reject(new Error("[daily-report] reconcileSearchIndex: the search setting is not configured")):d.reconcile(t,u)},Ds=async(u,d,p)=>{if(!rr(d))throw le("createDailyReport: businessDate","a business-date key in the canonical form YYYY-MM-DD naming a day from 0001-01-01 to 9999-12-31",d);F.info("createDailyReport called",{userId:u,businessDate:d});let[h]=await t.select({displayName:n.displayName}).from(n).where((0,g.eq)(n.id,u)),T=h?.displayName??a(u),x=de();try{let L=await I(async N=>{F.info("Starting transaction");let W=`internal-temp-${Date.now()}-${Math.random()}`,[_]=await N.insert(s).output().values({sourceType:"Internal",sourceId:W,businessDate:new Date(`${d}T00:00:00Z`),userId:u,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)});await N.update(s).set({sourceId:String(_.id)}).where((0,g.eq)(s.id,_.id)),F.info("Hub created",_),await N.insert(y).values({hubId:_.id,body:"",createdAt:new Date,createdBy:String(u),updatedAt:new Date,updatedBy:String(u)}),F.info("Internal created"),F.info("Calling getDraftLabelId");let X=await Fr();F.info("draftLabelId",X);let ie=[];return X&&(await N.insert(f).values({hubId:_.id,labelId:X,createdAt:new Date,createdBy:String(u)}),ie.push({id:X,name:w,color:null})),F.info("Label assigned"),x!==null&&await x.writeHubs(N,[_.id]),{reportHubId:_.id,date:d,createdAt:_e(_.createdAt,"YYYY-MM-DD HH:mm:ss"),author:T,userId:a(u),sourceType:"Internal",employeeName:T,updatedBy:a(u),updatedAt:_e(_.updatedAt,"YYYY-MM-DD HH:mm:ss"),category:null,creationCategory:null,visitTimeFrom:null,visitTimeTo:null,customerName:null,interviewers:[],subject:_.title,content:"",externalComments:[],isRead:!0,isStarred:!1,labels:ie,postedComments:[],attachments:[]}});l.invalidatePrefix(xt(d,u)),l.invalidatePrefix(pt),l.invalidatePrefix(wn(u)),await ne(G),await ne(`${ee}${d}`);let k=await Mt(Pe.unrestricted("post-write self read: the writer always sees the row they just wrote"),L.reportHubId,u,{forceRefresh:!0});if(k){let N=await St(),W=k.labels.some(_=>N.includes(_.id));await we(tn.parse({type:"report-create",reportHubId:k.reportHubId,report:k,clientTempId:p,recipientRawUserId:W?u:void 0}),"createDailyReport")}return k??L}catch(L){throw F.error("Error in createDailyReport",L),L}},Xt=async(u,d)=>await u.select().top(1).from(s).where((0,g.eq)(s.id,d)),$r=async(u,d,p)=>{await u.update(s).set(p).where((0,g.eq)(s.id,d))},Bn=async(u,d,p)=>{await u.update(y).set(p).where((0,g.eq)(y.hubId,d))},Vn=async(u,d,p)=>{await u.delete(f).where((0,g.and)((0,g.eq)(f.hubId,d),(0,g.eq)(f.labelId,p)))},As=async(u,d,p)=>{let h=await Xt(t,u);if(!h.length||h[0].deletedAt)throw new Error("Not Found");if(h[0].userId!==d)throw new Error("Unauthorized");let T=de();if(await I(async x=>{await $r(x,u,{deletedAt:new Date,deletedBy:String(d),updatedAt:new Date,updatedBy:String(d)}),T!==null&&await T.writeHubs(x,[u])}),l.invalidatePrefix(We(u)),l.invalidatePrefix(pt),l.invalidatePrefix(mt),await ne(G),h[0].businessDate){let x=Oe(_e(h[0].businessDate,"YYYY-MM-DD"));x&&await ne(`${ee}${x}`)}await we(on.parse({type:"report-delete",reportHubId:u,clientTempId:p,sourceType:h[0].sourceType}),"deleteDailyReport")},Ts=async(u,d,p,h)=>{let T=await Xt(t,u);if(!T.length||T[0].deletedAt)throw new Error("Not Found");if(T[0].userId!==d)throw new Error("Unauthorized");let x=de();await I(async N=>{p.title!==void 0&&await $r(N,u,{title:Oi(p.title),updatedAt:new Date,updatedBy:String(d)}),p.content!==void 0&&await Bn(N,u,{body:Oi(p.content),updatedAt:new Date,updatedBy:String(d)}),x!==null&&await x.writeHubs(N,[u])}),l.invalidatePrefix(We(u)),l.invalidatePrefix(pt),await ne(`${se}${u}`);let L=Oe(_e(T[0].businessDate,"YYYY-MM-DD"));L&&(l.invalidatePrefix(qt(L)),await ne(`${ee}${L}`));let k=await Mt(Pe.unrestricted("post-write self read: the writer always sees the row they just wrote"),u,d,{forceRefresh:!0});if(k){let N=await St(),W=k.labels.some(_=>N.includes(_.id));await we(rn.parse({type:"report-update",reportHubId:k.reportHubId,report:k,clientTempId:h,recipientRawUserId:W?d:void 0}),"updateDailyReport")}},Es=async(u,d,p)=>{let h=await Xt(t,u);if(!h.length)throw new Error("Not Found");if(h[0].userId!==d)throw new Error("Unauthorized");let T=await Fr();if(!T)return null;let x=de();if(await I(async N=>{await Vn(N,u,T),x!==null&&await x.writeHubs(N,[u])}),l.invalidatePrefix(We(u)),l.invalidatePrefix(pt),l.invalidatePrefix(mt),await ne(G),h[0].businessDate){let N=Oe(_e(h[0].businessDate,"YYYY-MM-DD"));N&&await ne(`${ee}${N}`)}let L=Oe(_e(h[0].businessDate,"YYYY-MM-DD"));L&&l.invalidatePrefix(xt(L,d));let k=await Mt(Pe.unrestricted("post-write self read: the writer always sees the row they just wrote"),u,d,{forceRefresh:!0});return k&&await we(nn.parse({type:"report-publish",reportHubId:k.reportHubId,report:k,clientTempId:p}),"publishDailyReport"),k??null},Is=async(u,d)=>{l.invalidatePrefix(pt),l.invalidatePrefix(mt),await ne(G);for(let p of new Set(u))l.invalidatePrefix(We(p)),await ne(`${se}${p}`);for(let p of new Set(d)){let h=Oe(p);h&&await ne(`${ee}${h}`)}},_s=async()=>{l.clearAll(),Q.clear(),Ee=null,c&&await ne(G),F.info("Server-side DB/SQL caches cleared successfully.")};return{streamKey:fe,streamMaxLen:Ge,attachmentDelivery:V,titleMaxLength:P,searchLimits:q===null?null:{concurrency:q.concurrency,rateLimitPerMinute:q.rateLimitPerMinute},searchFilterSourceTypes:$n,clearCache:_s,invalidateHubReadCaches:Is,getUserIdByExternalId:M,getDailyReportIdsByExternalId:ae,getDailyReportIdsFirstPageByExternalId:K,readSseStreamAnchor:Ve,getDailyReportsByBusinessDate:be,getDailyReportsByBusinessDateByExternalId:os,getDailyReportDetailById:Mt,getDailyReportDetailByIdByExternalId:as,getDailyReportDetailsByIdsByExternalId:is,getDraftLabelId:Fr,searchDailyReports:Rs,markDailyReportSearchHits:gs,listDailyReportSearchFacets:Ss,reconcileSearchIndex:bs,getAttachmentsByHubIds:Qt,getAttachmentForUser:ts,markAttachmentMissing:rs,markAttachmentPresent:ns,setStarStatus:ls,setReadStatus:cs,addComment:us,deleteComment:ms,createDailyReport:Ds,updateDailyReport:Ts,publishDailyReport:Es,deleteDailyReport:As,findDailyReportHubById:Xt,updateDailyReportHub:$r,updateDailyReportInternal:Bn,deleteDailyReportLabel:Vn}}var ki=(e,t,r,n)=>{if(!e)return[];try{let o=JSON.parse(e);return Array.isArray(o)?o.map(r).filter(a=>a!==null):(Se(n,1,"ExternalSource").warn(`Unexpected ${t} format: not an array`),[])}catch(o){return Se(n,1,"ExternalSource").warn(`Failed to parse ${t}:`,o),[]}};var Kt=require("drizzle-orm"),D=require("drizzle-orm/mssql-core");function Fi(e,t){let r=(0,D.mssqlSchema)(e),n=t.userTable,o=r.table("DailyReportHub",{id:(0,D.bigint)("id",{mode:"number"}).identity().notNull(),sourceType:(0,D.nvarchar)("source_type",{length:20}).notNull(),sourceId:(0,D.nvarchar)("source_id",{length:100}).notNull(),sourceIdNum:(0,D.bigint)("source_id_num",{mode:"number"}).generatedAlwaysAs(Kt.sql`TRY_CAST(source_id AS BIGINT)`),businessDate:(0,D.date)("business_date"),userId:(0,D.bigint)("user_id",{mode:"number"}),title:(0,D.nvarchar)("title",{length:200}),summary:(0,D.nvarchar)("summary",{length:"max"}),createdAt:(0,D.datetime2)("created_at").notNull(),createdBy:(0,D.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,D.datetime2)("updated_at").notNull(),updatedBy:(0,D.nvarchar)("updated_by",{length:50}).notNull(),deletedAt:(0,D.datetime2)("deleted_at"),deletedBy:(0,D.nvarchar)("deleted_by",{length:50})},m=>[(0,D.primaryKey)({name:`${e}_DailyReportHub_pk`,columns:[m.id]}),(0,D.foreignKey)({name:`${e}_DailyReportHub_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]}),(0,D.index)(`${e}_DailyReportHub_business_date_index`).on(m.businessDate),(0,D.index)(`${e}_DailyReportHub_updated_at_index`).on(m.updatedAt),(0,D.index)(`${e}_DailyReportHub_source_index`).on(m.sourceType,m.sourceId),(0,D.index)(`${e}_DailyReportHub_user_id_index`).on(m.userId),(0,D.index)(`${e}_DailyReportHub_business_date_id_index`).on((0,Kt.desc)(m.businessDate),(0,Kt.desc)(m.id)),(0,D.index)(`${e}_DailyReportHub_deleted_at_index`).on(m.deletedAt)]),a=r.table("DailyReportInternal",{hubId:(0,D.bigint)("hub_id",{mode:"number"}).notNull(),body:(0,D.nvarchar)("body",{length:"max"}),metadata:(0,D.nvarchar)("metadata",{length:"max"}),createdAt:(0,D.datetime2)("created_at").notNull(),createdBy:(0,D.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,D.datetime2)("updated_at").notNull(),updatedBy:(0,D.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,D.primaryKey)({name:`${e}_DailyReportInternal_pk`,columns:[m.hubId]}),(0,D.foreignKey)({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]})]),i=r.table("DailyReportComment",{id:(0,D.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,D.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,D.bigint)("user_id",{mode:"number"}).notNull(),body:(0,D.nvarchar)("body",{length:"max"}).notNull(),createdAt:(0,D.datetime2)("created_at").notNull(),createdBy:(0,D.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,D.datetime2)("updated_at").notNull(),updatedBy:(0,D.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,D.primaryKey)({name:`${e}_DailyReportComment_pk`,columns:[m.id]}),(0,D.foreignKey)({name:`${e}_DailyReportComment_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),(0,D.foreignKey)({name:`${e}_DailyReportComment_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]}),(0,D.index)(`${e}_DailyReportComment_hub_id_index`).on(m.hubId)]),l=r.table("DailyReportLabel",{id:(0,D.bigint)("id",{mode:"number"}).identity().notNull(),userId:(0,D.bigint)("user_id",{mode:"number"}),name:(0,D.nvarchar)("name",{length:50}).notNull(),color:(0,D.nvarchar)("color",{length:20}),sortOrder:(0,D.int)("sort_order"),createdAt:(0,D.datetime2)("created_at").notNull(),createdBy:(0,D.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,D.datetime2)("updated_at").notNull(),updatedBy:(0,D.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,D.primaryKey)({name:`${e}_DailyReportLabel_pk`,columns:[m.id]}),(0,D.foreignKey)({name:`${e}_DailyReportLabel_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]})]),c=r.table("DailyReportHub_Label",{hubId:(0,D.bigint)("hub_id",{mode:"number"}).notNull(),labelId:(0,D.bigint)("label_id",{mode:"number"}).notNull(),createdAt:(0,D.datetime2)("created_at").notNull(),createdBy:(0,D.nvarchar)("created_by",{length:50}).notNull()},m=>[(0,D.primaryKey)({name:`${e}_DailyReportHub_Label_pk`,columns:[m.hubId,m.labelId]}),(0,D.foreignKey)({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),(0,D.foreignKey)({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[m.labelId],foreignColumns:[l.id]})]),s=r.table("DailyReportUserStatus",{hubId:(0,D.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,D.bigint)("user_id",{mode:"number"}).notNull(),isRead:(0,D.bit)("is_read").default(!1).notNull(),isStarred:(0,D.bit)("is_starred").default(!1).notNull(),createdAt:(0,D.datetime2)("created_at").notNull(),createdBy:(0,D.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,D.datetime2)("updated_at").notNull(),updatedBy:(0,D.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,D.primaryKey)({name:`${e}_DailyReportUserStatus_pk`,columns:[m.hubId,m.userId]}),(0,D.foreignKey)({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),(0,D.foreignKey)({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]})]),y=r.table("DailyReportAttachment",{id:(0,D.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,D.bigint)("hub_id",{mode:"number"}).notNull(),uploadedBy:(0,D.bigint)("uploaded_by",{mode:"number"}),sourceKey:(0,D.nvarchar)("source_key",{length:200}).notNull(),fileName:(0,D.nvarchar)("file_name",{length:255}).notNull(),filePath:(0,D.nvarchar)("file_path",{length:"max"}).notNull(),fileType:(0,D.nvarchar)("file_type",{length:100}),fileSize:(0,D.bigint)("file_size",{mode:"number"}),objectCheckedAt:(0,D.datetime2)("object_checked_at"),objectMissingAt:(0,D.datetime2)("object_missing_at"),createdAt:(0,D.datetime2)("created_at").notNull(),createdBy:(0,D.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,D.datetime2)("updated_at").notNull(),updatedBy:(0,D.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,D.primaryKey)({name:`${e}_DailyReportAttachment_pk`,columns:[m.id]}),(0,D.foreignKey)({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[m.hubId],foreignColumns:[o.id]}),(0,D.foreignKey)({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[m.uploadedBy],foreignColumns:[n.id]}),(0,D.uniqueIndex)(`${e}_DailyReportAttachment_source_unique`).on(m.hubId,m.sourceKey),(0,D.index)(`${e}_DailyReportAttachment_hub_id_index`).on(m.hubId,m.createdAt)]);return{hub:o,internal:a,comment:i,attachment:y,label:l,hubLabel:c,userStatus:s}}var ye=require("drizzle-orm/mssql-core");function Hi(e){let t=(0,ye.mssqlSchema)(e),r=t.table("DailyReportSearchDocument",{hubId:(0,ye.bigint)("hub_id",{mode:"number"}).notNull(),searchText:(0,ye.nvarchar)("search_text",{length:"max"}).notNull(),sourceDigest:(0,ye.binary)("source_digest",{length:32}).notNull(),normalizerVersion:(0,ye.varchar)("normalizer_version",{length:64}).notNull(),indexedAt:(0,ye.datetime2)("indexed_at").notNull(),rowVersion:(0,ye.binary)("row_version",{length:8}).notNull(),authorName:(0,ye.nvarchar)("author_name",{length:Qe.maxValueLength}),customerName:(0,ye.nvarchar)("customer_name",{length:Qe.maxValueLength})},o=>[(0,ye.primaryKey)({name:`${e}_DailyReportSearchDocument_pk`,columns:[o.hubId]})]),n=t.table("DailyReportSearchComment",{hubId:(0,ye.bigint)("hub_id",{mode:"number"}).notNull(),ordinal:(0,ye.int)("ordinal").notNull(),authorUserId:(0,ye.bigint)("author_user_id",{mode:"number"}),commentText:(0,ye.nvarchar)("comment_text",{length:"max"}).notNull()},o=>[(0,ye.primaryKey)({name:`${e}_DailyReportSearchComment_pk`,columns:[o.hubId,o.ordinal]})]);return{document:r,comment:n}}var id=5e7,Fn=2e8,sd=1,Hn=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})})}),Ui=125,$i=4,Bi=16,Vi=50,Yi=2,Jt=Object.freeze({renderMs:Ce.renderMs,nanosecondsPerBlockVisit:Ui,margin:$i,maxBlockVisits:Math.floor(Ce.renderMs*1e6/(Ui*$i)),walkBudgetMs:Bi,nanosecondsPerWalkStep:Vi,walkMargin:Yi,maxWalkSteps:Math.floor(Bi*1e6/(Vi*Yi))}),ld=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),qi=75,ji=4,Wi="#ffffff",cd=1,ud={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},dd=[/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/],zi=Object.freeze({ok:!1,reason:"failed"}),Gi=Object.freeze({ok:!1,reason:"unsupported"}),Ki=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:Qo(e)}),Ji=(e,t)=>{switch(t){case"jpeg":{let r=gn(e);return r===null?null:Ki(r)}case"png":{let r=ea(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=ta(e,Jt.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},Qi=(e,t)=>{let r=ld.get(t.depth);if(r===void 0)return null;let n=t.channels*r,o=Hn,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},Xi=(e,t,r)=>{let n=Ji(e,t);return n===null?null:Qi(n,r)},md=e=>e!==null&&e<=Fn,pd=(e,t)=>{if(t!=="jpeg")return Ji(e,t);let r=Xo(e,Jt);return r===null||r.blockVisits>Jt.maxBlockVisits?null:Ki(r.header)},yd=e=>{let t=e instanceof Error?e.message:"";return dd.some(r=>r.test(t))?"failed":"unsupported"},Zi=e=>{e.cache(!1),e.concurrency(sd),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(ud)});let t=async(n,o,a,i,l)=>{let c=pd(n,o);if(c===null)return Gi;try{let s=e(n,{limitInputPixels:id,animated:!1});if(!md(Qi(c,await s.metadata())))return Gi;if(l.aborted)return zi;let y=await s.rotate().resize({width:a,height:i,fit:"inside",withoutEnlargement:!0}).flatten({background:Wi}).webp({quality:qi,effort:ji}).toBuffer();return{ok:!0,bytes:new Uint8Array(y),contentType:"image/webp"}}catch(s){return{ok:!1,reason:yd(s)}}},r=async(n,{format:o,maxWidth:a,maxHeight:i,signal:l})=>l.aborted?zi:t(n,o,a,i,l);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${qi}-e${ji}/flatten-${Wi}/v${cd}`,render:r}};var hd=4096,fd=6e4;function Rd(e){e.redis||Se(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=Zt(e.redis),r=new bt({defaultTtlMs:te("cacheDefaultTtlMs",e.cacheDefaultTtlMs??fd,1),maxBuckets:te("cacheMaxBuckets",e.cacheMaxBuckets??hd,1)},t),n=kr({...e,cache:r,epochs:t}),o=new Ct({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),a=Lr({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,isStreamIdLte,parseClientTempId,predictSharpThumbnailWorkingSetBytes,readDailyReportSseStreamEntry,transformJsonArray});
|
|
12
12
|
/* v8 ignore next -- @preserve 到達不能: 時間切れと中断の購読はどちらも cleanup で同時に外れ、枠を渡すときも先に cleanup するので、列にいない待機者でここへは来ない。それでも splice(-1) が別の待機者を消さないよう残す */
|